Contents

PlayCanvas Engine API: All Pages

The API reference of the PlayCanvas Engine, playcanvas 2.23.1 on npm: its classes, interfaces, type aliases and functions by category, and its constants.

The same pages as Markdown, for AI agents: llms-full.txt.

Contents

AnimBlendTree

Class · extends AnimNode · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree.js#L23

AnimBlendTrees are used to store and blend multiple AnimNodes together. BlendTrees can be the child of other AnimBlendTrees, in order to create a hierarchy of AnimNodes. It takes a blend type as an argument which defines which function should be used to determine the weights of each of its children, based on the current parameter value.

The blend type is one of ANIM_BLEND_1D, ANIM_BLEND_2D_DIRECTIONAL, ANIM_BLEND_2D_CARTESIAN and ANIM_BLEND_DIRECT, each implemented by a subclass. Every child sits at a point on the parameter axis or plane, and the tree weights the children by where the current parameter values fall among those points. With syncAnimations set, the children's playback speeds are synchronized so that a walk and a run cycle stay in step while blending. Blend trees are described in the AnimStateGraph and built when it loads.

Constructors

constructor

new AnimBlendTree(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)

Create a new AnimBlendTree instance.

Parameters

AnimBlendTree1D

Class · extends AnimBlendTree · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-1d.js#L19

An AnimBlendTree that calculates its weights using the 1D algorithm from chapter 6 of Rune Skovbo Johansen's thesis.

The children sit at points along a single parameter, and the two whose points bracket the current value share the weight between them. This is the tree for one-dimensional blends such as idle, walk and run driven by a speed parameter.

Constructors

constructor

new AnimBlendTree1D(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: any[], syncAnimations: boolean, createTree: Function, findParameter: Function)

Create a new BlendTree1D instance.

Parameters

AnimBlendTreeCartesian2D

Class · extends AnimBlendTree · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-2d-cartesian.js#L17

An AnimBlendTree that calculates its weights using the 2D Cartesian algorithm from chapter 6, section 3 of Rune Skovbo Johansen's thesis.

The children sit at points on a plane defined by two parameters, and weights are computed from where the current parameter point lies among them, treating the two axes as independent. Use it when the parameters are unrelated quantities, such as forward speed against turn rate.

Inherited from AnimBlendTree

AnimBlendTreeDirect

Class · extends AnimBlendTree · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-direct.js#L10

An AnimBlendTree that calculates normalized weight values based on the total weight. Each child's weight is read from its own parameter and the weights are then normalized to sum to one, so the mix is driven explicitly rather than by a position in parameter space.

Inherited from AnimBlendTree

AnimBlendTreeDirectional2D

Class · extends AnimBlendTree · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-blend-tree-2d-directional.js#L16

An AnimBlendTree that calculates its weights using the 2D directional algorithm from chapter 6 of Rune Skovbo Johansen's thesis.

The children's points are treated as directions from the origin, so the weights follow the angle and magnitude of the current parameter point. Use it when the two parameters form a direction, such as a movement vector driving an eight-way locomotion set.

Inherited from AnimBlendTree

AnimComponent

Class · extends Component · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/component.js#L54

The AnimComponent enables an Entity to play back animations on models and entity properties. Animations are driven by animation state graphs, which can be authored in the PlayCanvas Editor or constructed programmatically, and support blending between multiple layers and clips.

You should never need to use the AnimComponent constructor directly. To add an AnimComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('anim', {
    activate: true,
    speed: 1
});

Once the AnimComponent is added to the entity, you can access it via the Entity#anim property:

entity.anim.speed = 2; // Play animations at double speed

console.log(entity.anim.speed); // Get the playback speed and print it

Relevant Engine API examples:

Accessors

activate

get activate(): boolean
set activate(value: boolean)

Gets whether the first animation will begin playing when the scene is loaded.

baseLayer

get baseLayer(): AnimComponentLayer | null

Returns the base layer of the state graph.

layers

get layers(): readonly AnimComponentLayer[]

Returns the animation layers available in this anim component. Use addLayer or loadStateGraph to change layers.

normalizeWeights

get normalizeWeights(): boolean
set normalizeWeights(value: boolean)

Gets whether the animation component will normalize the weights of its layers by their sum total.

playable

get playable(): boolean

Returns whether all component layers are currently playable.

playing

get playing(): boolean
set playing(value: boolean)

Gets whether to play or pause all animations in the component.

rootBone

get rootBone(): Entity
set rootBone(value: Entity)

Gets the entity that this anim component should use as the root of the animation hierarchy.

speed

get speed(): number
set speed(value: number)

Gets the speed multiplier for animation play back speed.

Methods

addLayer

addLayer(name: string, weight?: number, mask?: any[], blendType?: string): AnimComponentLayer

Adds a new anim component layer to the anim component.

Parameters

Returns AnimComponentLayer: The created anim component layer.

assignAnimation

assignAnimation(nodePath: string, animTrack: AnimTrack, layerName?: string, speed?: number, loop?: boolean): void

Associates an animation with a state or blend tree node in the loaded state graph. If all states are linked and the activate value was set to true then the component will begin playing. If no state graph is loaded, a default state graph will be created with a single state based on the provided nodePath parameter.

Parameters

findAnimationLayer

findAnimationLayer(name: string): AnimComponentLayer

Finds an AnimComponentLayer in this component.

Parameters

Returns AnimComponentLayer: Layer.

getBoolean

getBoolean(name: string): boolean

Returns a boolean parameter value by name.

Parameters

Returns boolean: A boolean.

getFloat

getFloat(name: string): number

Returns a float parameter value by name.

Parameters

Returns number: A float.

getInteger

getInteger(name: string): number

Returns an integer parameter value by name.

Parameters

Returns number: An integer.

getTrigger

getTrigger(name: string): boolean

Returns a trigger parameter value by name.

Parameters

Returns boolean: A boolean.

loadStateGraph

loadStateGraph(stateGraph: any): void

Initializes component animation controllers using the provided state graph.

Parameters

Example

entity.anim.loadStateGraph({
    "layers": [
        {
            "name": layerName,
            "states": [
                {
                    "name": "START",
                    "speed": 1
                },
                {
                    "name": "Initial State",
                    "speed": speed,
                    "loop": loop,
                    "defaultState": true
                }
            ],
            "transitions": [
                {
                    "from": "START",
                    "to": "Initial State"
                }
            ]
        }
    ],
    "parameters": {}
});

rebind

rebind(): void

Rebind all of the components layers.

removeNodeAnimations

removeNodeAnimations(nodeName: string, layerName?: string): void

Removes animations from a node in the loaded state graph.

Parameters

removeStateGraph

removeStateGraph(): void

Removes all layers from the anim component.

reset

reset(): void

Reset all of the components layers and parameters to their initial states. If a layer was playing before it will continue playing.

resetTrigger

resetTrigger(name: string): void

Resets the value of a trigger parameter that was defined in the animation components state graph to false.

Parameters

setBoolean

setBoolean(name: string, value: boolean): void

Sets the value of a boolean parameter that was defined in the animation components state graph.

Parameters

setFloat

setFloat(name: string, value: number): void

Sets the value of a float parameter that was defined in the animation components state graph.

Parameters

setInteger

setInteger(name: string, value: number): void

Sets the value of an integer parameter that was defined in the animation components state graph.

Parameters

setTrigger

setTrigger(name: string, singleFrame?: boolean): void

Sets the value of a trigger parameter that was defined in the animation components state graph to true.

Parameters

Inherited from Component

AnimComponentLayer

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/component-layer.js#L34

An AnimComponentLayer is one layer of an AnimComponent. It runs the state machine that the AnimStateGraph defines for that layer and contributes the result to the entity's final pose with a weight, either overwriting the layers beneath it or adding to them according to blendType. A mask limits which nodes of the hierarchy the layer animates, which is how an upper-body action plays on top of a full-body locomotion layer. The first layer is AnimComponent#baseLayer; add more with AnimComponent#addLayer.

Playback is per layer: play starts a named state, transition blends to another state over a given time, pause and reset act on the current state, and activeState, activeStateProgress and transitioning report where the layer is. assignAnimation binds an AnimTrack to a state, or to a node inside a blend tree using a dotted path, and blendToWeight fades the whole layer in or out.

Example

// Fade in an upper-body layer and play its 'Wave' state over the base layer
const layer = entity.anim.findAnimationLayer('UpperBody');
layer.blendToWeight(1, 0.3);
layer.play('Wave');

Accessors

activeState

get activeState(): string

Gets the currently active state name.

activeStateCurrentTime

get activeStateCurrentTime(): number
set activeStateCurrentTime(time: number)

Gets the active state's time in seconds.

activeStateDuration

get activeStateDuration(): number

Gets the currently active states duration.

activeStateProgress

get activeStateProgress(): number

Gets the currently active state's progress as a value normalized by the state's animation duration. Looped animations will return values greater than 1.

mask

get mask(): any
set mask(value: any)

Gets the mask of bones which should be animated or ignored by this layer.

name

get name(): string

Returns the name of the layer.

playable

get playable(): boolean

Returns true if a state graph has been loaded and all states in the graph have been assigned animation tracks.

playing

get playing(): boolean
set playing(value: boolean)

Gets whether this layer is currently playing.

previousState

get previousState(): string | null

Gets the previously active state name.

states

get states(): string[]

Gets all available states in this layers state graph.

transitioning

get transitioning(): boolean

Gets whether the anim component layer is currently transitioning between states.

transitionProgress

get transitionProgress(): number | null

Gets the progress, if the anim component layer is currently transitioning between states. Otherwise returns null.

weight

get weight(): number
set weight(value: number)

Sets the blending weight of this layer.

Methods

assignAnimation

assignAnimation(nodePath: string, animTrack: AnimTrack, speed?: number, loop?: boolean): void

Assigns an animation track to a state or blend tree node in the current graph. If a state for the given nodePath doesn't exist, it will be created. If all states nodes are linked and the AnimComponent#activate value was set to true then the component will begin playing.

Parameters

blendToWeight

blendToWeight(weight: number, time: number): void

Blend from the current weight value to the provided weight value over a given amount of time.

Parameters

getAnimationAsset

getAnimationAsset(stateName: string): { asset: number }

Returns an object holding the animation asset id that is associated with the given state.

Parameters

Returns { asset: number }: An object containing the animation asset id associated with the given state.

pause

pause(): void

Pause the animation in the current state.

play

play(name?: string): void

Start playing the animation in the current state.

Parameters

rebind

rebind(): void

Rebind any animations in the layer to the currently present components and model of the anim components entity.

removeNodeAnimations

removeNodeAnimations(nodeName: string): void

Removes animations from a node in the loaded state graph.

Parameters

reset

reset(): void

Reset the animation component to its initial state, including all parameters. The system will be paused.

transition

transition(to: string, time?: number, transitionOffset?: number): void

Transition to any state in the current layers graph. Transitions can be instant or take an optional blend time.

Parameters

AnimComponentSystem

Class · extends ComponentSystem · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/anim/system.js#L33

Manages the AnimComponents of an application and advances their state graphs each frame. Reach it through app.systems.anim; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

AnimCurve

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-curve.js#L24

Animation curve links an input data set to an output data set and defines the interpolation method to use. The paths name the targets the curve drives, input and output index into the owning AnimTrack's keyframe time and value data, and interpolation is one of INTERPOLATION_STEP, INTERPOLATION_LINEAR or INTERPOLATION_CUBIC.

Constructors

constructor

new AnimCurve(paths: AnimCurvePath[], input: number, output: number, interpolation: number)

Create a new animation curve.

Parameters

Accessors

input

get input(): number

The index of the AnimTrack input which contains the key data for this curve.

interpolation

get interpolation(): number

The interpolation method used by this curve.

output

get output(): number

The index of the AnimTrack input which contains the key data for this curve.

paths

get paths(): AnimCurvePath[]

The list of paths which identify targets of this curve.

AnimData

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-data.js#L8

Wraps a set of data used in animation: a flat data array read components values at a time, so a three-component set holds positions and a four-component set holds quaternions. An AnimTrack keeps its keyframe times and values as AnimData that its curves index into.

Constructors

constructor

new AnimData(components: number, data: number[] | Float32Array<ArrayBufferLike>)

Create a new animation AnimData instance.

Parameters

Accessors

components

get components(): number

Gets the number of components that make up an element.

data

get data(): number[] | Float32Array<ArrayBufferLike>

Gets the data.

AnimEvents

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-events.js#L10

AnimEvents stores a sorted array of animation events which should fire sequentially during the playback of an AnimTrack. Each event is an object with a name and a time in seconds plus any extra properties you attach. When playback passes an event's time it is fired on the AnimComponent under the event's name, so a script listens with entity.anim.on('footstep', callback) and receives the event object.

Constructors

constructor

new AnimEvents(events: any[])

Create a new AnimEvents instance.

Parameters

Example

const events = new AnimEvents([
    {
        name: 'my_event',
        time: 1.3, // given in seconds
        // any additional properties added are optional and will be available in the EventHandler callback's event object
        myProperty: 'test',
        myOtherProperty: true
    }
]);
animTrack.events = events;

AnimNode

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-node.js#L19

AnimNodes are used to represent a single animation track in the current state. Each state can contain multiple AnimNodes, in which case they are stored in a BlendTree hierarchy, which will control the weight (contribution to the states final animation) of its child AnimNodes.

animTrack is the clip the node plays, speed multiplies its playback rate, and weight is set by the parent blend tree, or is one for a node that is the state's only animation.

Constructors

constructor

new AnimNode(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | number[], speed?: number)

Create a new AnimNode instance.

Parameters

AnimState

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-state.js#L29

Defines a single state that the controller can be in. Each state contains either a single AnimNode or an AnimBlendTree of multiple AnimNodes, which will be used to animate the Entity while the state is active. An AnimState will stay active and play as long as there is no AnimTransition with its conditions met that has that AnimState as its source state.

speed and loop control the playback of the state's tracks. States are defined in the AnimStateGraph and entered either by a transition or directly with AnimComponentLayer#play.

Constructors

constructor

new AnimState(controller: AnimController, name: string, speed?: number, loop?: boolean, blendTree?: any)

Create a new AnimState instance.

Parameters

AnimStateGraph

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/state-graph/anim-state-graph.js#L21

An asset resource which represents an anim state graph. It can be loaded into an anim component using the AnimComponent#loadStateGraph method.

The graph is data, not behavior. It lists its layers, each with its states, the transitions between them and their conditions, and the parameters those conditions read. Loading it into a component builds the runtime AnimState, AnimTransition and AnimBlendTree objects, and AnimComponent#assignAnimation then attaches an AnimTrack to each state. One graph can drive any number of components.

Usage

Scripts can retrieve an AnimStateGraph instance from assets of type 'animstategraph'. An AnimStateGraph can then be loaded into an anim component as follows:

const animStateGraph = app.assets.get(ASSET_ID).resource;
const entity = new Entity();
entity.addComponent('anim');
entity.anim.loadStateGraph(animStateGraph);

AnimTrack

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-track.js#L21

An AnimTrack stores the curve data necessary to animate a set of target nodes. It can be linked to the nodes it should animate using the AnimComponent#assignAnimation method.

A track is the engine's animation clip: a name, a duration in seconds and a list of curves, each of which reads keyframe times from one of the inputs and values from one of the outputs, and writes the result to a target path such as a node's local position or a component property. Optional events fire at set times during playback. Tracks come from animation assets, GLB animations among them, and are what an AnimState plays; one track can be assigned in any number of components.

Properties

EMPTY

static EMPTY: AnimTrack

This AnimTrack can be used as a placeholder track when creating a state graph before having all associated animation data available.

Accessors

curves

get curves(): AnimCurve[]

Gets the list of curves contained in the AnimTrack.

duration

get duration(): number

Gets the duration of the AnimTrack.

events

get events(): AnimEvents
set events(animEvents: AnimEvents)

Gets the animation events that will fire during the playback of this anim track.

inputs

get inputs(): AnimData[]

Gets the list of curve key data contained in the AnimTrack.

name

get name(): string

Gets the name of the AnimTrack.

outputs

get outputs(): AnimData[]

Gets the list of curve values contained in the AnimTrack.

AnimTransition

Class · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/anim-transition.js#L20

AnimTransitions represent connections in the controllers state graph between AnimStates. During each frame, the controller tests to see if any of the AnimTransitions have the current AnimState as their source (from) state. If so and the AnimTransitions parameter based conditions are met, the controller will transition to the destination state.

Each condition compares a parameter with a value using one of the predicates such as ANIM_GREATER_THAN or ANIM_EQUAL_TO. time is the blend duration, exitTime restricts the transition to a point in the source state's playback, priority orders transitions whose conditions pass together, and interruptionSource says which other transitions may cut this one short. A transition may also start from the ANIM_STATE_ANY state so that it applies from every state.

Constructors

constructor

new AnimTransition(options: object)

Create a new AnimTransition.

Parameters

Animation

Class · category: Animation (Legacy)

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/animation.js#L36

An Animation contains the data that defines how a Skeleton animates over time. The Animation contains an array of AnimationNodes, where each AnimationNode targets a specific GraphNode referenced by a Skeleton.

An Animation can be played back by an AnimationComponent.

Constructors

constructor

new Animation()

Create a new Animation instance.

Properties

duration

duration: number = 0

Duration of the animation in seconds.

name

name: string = ''

Human-readable name of the animation.

Accessors

nodes

get nodes(): AnimationNode[]

A read-only property to get array of animation nodes.

Methods

addNode

addNode(node: AnimationNode): void

Adds a node to the internal nodes array.

Parameters

getNode

getNode(name: string): AnimationNode

Gets a AnimationNode by name.

Parameters

Returns AnimationNode: The AnimationNode with the specified name.

AnimationComponent

Class · extends Component · category: Animation (Legacy)

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/animation/component.js#L43

The AnimationComponent enables an Entity to play back skeletal animations on a model. It is a legacy component that has largely been superseded by AnimComponent, which supports more advanced features such as animation state graphs and blending.

You should never need to use the AnimationComponent constructor directly. To add an AnimationComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('animation', {
    assets: [animationAsset.id],
    speed: 1
});

Once the AnimationComponent is added to the entity, you can access it via the Entity#animation property:

entity.animation.speed = 2; // Play the animation at double speed

console.log(entity.animation.speed); // Get the playback speed and print it

Properties

activate

activate: boolean = true

If true, the first animation asset will begin playing when the scene is loaded.

skeleton

skeleton: Skeleton | null = null

Get the skeleton for the current model. If the model is loaded from glTF/glb, then the skeleton is null.

speed

speed: number = 1

Speed multiplier for animation play back. 1 is playback at normal speed and 0 pauses the animation.

Accessors

animations

get animations(): {}
set animations(value: {})

Gets the dictionary of animations by name.

assets

get assets(): (number | Asset<string>)[]
set assets(value: (number | Asset<string>)[])

Gets the array of animation assets or asset ids.

currentTime

get currentTime(): number
set currentTime(currentTime: number)

Gets the current time position (in seconds) of the animation.

duration

get duration(): number

Gets the duration in seconds of the current animation. Returns 0 if no animation is playing.

loop

get loop(): boolean
set loop(value: boolean)

Gets whether the animation will restart from the beginning when it reaches the end.

Methods

getAnimation

getAnimation(name: string): Animation

Return an animation.

Parameters

Returns Animation: An Animation.

play

play(name: string, blendTime?: number): void

Start playing an animation.

Parameters

Inherited from Component

AnimationComponentSystem

Class · extends ComponentSystem · category: Animation (Legacy)

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/animation/system.js#L21

Manages the AnimationComponents of an application, the legacy animation system. Reach it through app.systems.animation; components are created with Entity#addComponent, never by calling the system directly. New work should use AnimComponent.

Inherited from ComponentSystem

AnimationNode

Class · category: Animation (Legacy)

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/animation.js#L17

AnimationNode represents an array of keyframes that animate the transform of a GraphNode over time. Typically, an Animation maintains a collection of AnimationNodes, one for each GraphNode in a Skeleton.

Constructors

constructor

new AnimationNode()

Create a new AnimationNode instance.

Skeleton

Class · category: Animation (Legacy)

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/animation/skeleton.js#L39

Represents a skeleton used to play animations.

Constructors

constructor

new Skeleton(graph: GraphNode)

Create a new Skeleton instance.

Parameters

Properties

looping

looping: boolean = true

Determines whether skeleton is looping its animation.

Accessors

animation

get animation(): Animation
set animation(value: Animation)

Gets the animation on the skeleton.

currentTime

get currentTime(): number
set currentTime(value: number)

Gets the current time of the currently active animation in seconds.

numNodes

get numNodes(): number

Gets the number of nodes in the skeleton.

Methods

addTime

addTime(delta: number): void

Progresses the animation assigned to the specified skeleton by the supplied time delta. If the delta takes the animation passed its end point, if the skeleton is set to loop, the animation will continue from the beginning. Otherwise, the animation's current time will remain at its duration (i.e. the end).

Parameters

blend

blend(skel1: Skeleton, skel2: Skeleton, alpha: number): void

Blends two skeletons together.

Parameters

setGraph

setGraph(graph: GraphNode): void

Links a skeleton to a node hierarchy. The nodes animated skeleton are then subsequently used to drive the local transformation matrices of the node hierarchy.

Parameters

updateGraph

updateGraph(): void

Synchronizes the currently linked node hierarchy with the current state of the skeleton. Internally, this function converts the interpolated keyframe at each node in the skeleton into the local transformation matrix at each corresponding node in the linked node hierarchy.

AnimationHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/animation.js#L15

Resource handler for the animation asset type. Loads an AnimTrack from a GLB file, or a legacy Animation from a PlayCanvas JSON animation file.

Inherited from ResourceHandler

Asset

Class · extends EventHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L167

An Asset is the engine's record of a single resource: a texture, a material, a glTF container, a sound, a script and so on. Assets live in the application's AssetRegistry at AppBase#assets, which loads them on demand.

An asset has five parts:

Loading is driven by the registry: call AssetRegistry#load, or set preload so the asset loads when added. Wait for the result with ready or listen for the load and error events. unload releases the resource.

The type string also types the resource: new Asset('brick', 'texture', file) creates an Asset<'texture'> whose resource is a Texture once loaded, and app.assets.find('brick', 'texture') returns one. See AssetMap for the built-in types and for adding application-defined ones. An asset whose type is only known as a string has a resource of type unknown.

Example

const asset = new Asset('brick', 'texture', { url: 'textures/brick.png' });
app.assets.add(asset);
app.assets.load(asset);
asset.ready((asset) => {
    material.diffuseMap = asset.resource;
});

template

Constructors

constructor

new Asset<K extends string & {} | AssetType>(name: string, type: K, file?: object, data?: any, options?: object)

Create a new Asset record. Add it to the AssetRegistry with AssetRegistry#add so the application can find and load it.

Parameters

Example

// an Asset<'texture'>: once loaded, asset.resource is a Texture
const asset = new Asset("a texture", "texture", {
    url: "http://example.com/my/assets/here/texture.png"
});

Properties

id

id: number

The asset id.

loaded

loaded: boolean = false

True if the asset has finished attempting to load the resource. It is not guaranteed that the resources are available as there could have been a network error.

loading

loading: boolean = false

True if the resource is currently being loaded.

options

options: any = {}

Optional JSON data that contains the asset handler options.

registry

registry: AssetRegistry | null = null

The asset registry that this Asset belongs to.

tags

tags: Tags

Asset tags. Enables finding of assets by tags using the AssetRegistry#findByTag method.

type

type: K

The type of the asset: one of the AssetType names, or the name of an application-defined resource handler. See AssetMap.

Accessors

data

get data(): any
set data(value: any)

Gets optional asset JSON data.

file

get file(): any
set file(value: any)

Gets the file details or null if no file.

name

get name(): string
set name(value: string)

Gets the asset name.

preload

get preload(): boolean
set preload(value: boolean)

Gets whether to preload an asset.

resource

get resource(): AssetResource<K> | undefined
set resource(value: AssetResource<K>)

Gets the asset resource. Its type follows the asset's type: a Texture for an Asset<'texture'>, a Material for an Asset<'material'> and so on (see AssetMap), or unknown when the type is only known as a string. It is undefined until the asset has loaded and after Asset#unload, so narrow it before use unless the asset is known to be loaded, for example inside Asset#ready.

resources

get resources(): AssetResource<K>[]
set resources(value: AssetResource<K>[])

Gets the asset resources. For a cube map asset, the first entry is the cube map and the remaining entries are its prefiltered levels, some of which may be null.

Methods

getFileUrl

getFileUrl(): string | null

Return the URL required to fetch the file for this asset.

Returns string | null: The URL. Returns null if the asset has no associated file.

Example

const asset = app.assets.find("My Image", "texture");
const img = "&lt;img src='" + asset.getFileUrl() + "'&gt;";

ready

ready(callback: AssetReadyCallback<K>, scope?: any): void

Take a callback which is called as soon as the asset is loaded. If the asset is already loaded the callback is called straight away.

The callback fires on success only, and a failed load still marks the asset as loaded while firing error rather than load. So a callback registered before the failure never runs, and one registered after it runs immediately with Asset#resource still null. Listen for the error event as well whenever a failure has to be handled, check asset.resource inside the callback, and never await this callback alone.

Parameters

Example

const asset = app.assets.find("My Asset");
asset.ready((asset) => {
    // asset loaded
});
app.assets.load(asset);

unload

unload(): void

Destroys the associated resource and marks asset as unloaded. The unload event also fires while the asset is loading, allowing resource handlers to cancel pending work.

Example

const asset = app.assets.find("My Asset");
asset.unload();
// asset.resource is null

Events

EVENT_ADDLOCALIZED

static EVENT_ADDLOCALIZED: string = 'add:localized'

Fired when we add a new localized asset id to the asset.

Example

asset.on('add:localized', (locale, assetId) => {
   console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`);
});

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when one of the asset properties file, data, resource or resources is changed.

Example

asset.on('change', (asset, property, newValue, oldValue) => {
   console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`);
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired if the asset encounters an error while loading.

Example

asset.on('error', (err, asset) => {
   console.error(`Error loading asset ${asset.name}: ${err}`);
});

EVENT_LOAD

static EVENT_LOAD: string = 'load'

Fired when the asset has completed loading.

Example

asset.on('load', (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});

EVENT_PROGRESS

static EVENT_PROGRESS: string = 'progress'

Fired as the asset's file downloads, with the number of bytes received so far and the total expected. Only asset types whose file is fetched as binary data report progress: animation (GLB only), audio, binary, container, gsplat, model and texture. Textures loaded through an image element have no download progress, so they fire once at 0 and once at a fixed placeholder total, whether or not the file was downloaded.

Please note:

Example

asset.on('progress', (receivedBytes, totalBytes) => {
   console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`);
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when the asset is removed from the asset registry.

Example

asset.on('remove', (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});

EVENT_REMOVELOCALIZED

static EVENT_REMOVELOCALIZED: string = 'remove:localized'

Fired when we remove a localized asset id from the asset.

Example

asset.on('remove:localized', (locale, assetId) => {
  console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`);
});

EVENT_UNLOAD

static EVENT_UNLOAD: string = 'unload'

Fired just before the asset unloads the resource. This allows for the opportunity to prepare for an asset that will be unloaded. E.g. Changing the texture of a model to a default before the one it was using is unloaded.

Example

asset.on('unload', (asset) => {
   console.log(`Asset about to unload: ${asset.name}`);
});

Inherited from EventHandler

AssetListLoader

Class · extends EventHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-list-loader.js#L30

An AssetListLoader loads a group of assets together and reports once when every one of them has loaded or failed. Pass it Asset instances or asset ids. Assets not yet in the AssetRegistry are added, and ids that the registry does not know yet are waited for until a matching asset is registered. Call load to start loading and ready to be told when the list is complete without starting anything.

Example

const assets = [
    new Asset('model', 'container', { url: 'http://example.com/asset.glb' }),
    new Asset('styling', 'css', { url: 'http://example.com/asset.css' })
];
const assetListLoader = new AssetListLoader(assets, app.assets);
assetListLoader.load((err, failed) => {
    if (err) {
        console.error(`${failed.length} assets failed to load`);
    } else {
        console.log(`${assets.length} assets loaded`);
    }
});

Constructors

constructor

new AssetListLoader(assetList: number[] | Asset<string>[], assetRegistry: AssetRegistry)

Create a new AssetListLoader using a list of assets to load and the asset registry used to load and manage them.

Parameters

Example

const assetListLoader = new AssetListLoader([
    new Asset("texture1", "texture", { url: 'http://example.com/my/assets/here/texture1.png' }),
    new Asset("texture2", "texture", { url: 'http://example.com/my/assets/here/texture2.png' })
], app.assets);

Methods

destroy

destroy(): void

Removes all references to this asset list loader.

load

load(done: Function, scope?: any): void

Start loading asset list and call done() when all assets have loaded or failed to load.

Parameters

ready

ready(done: Function, scope?: any): void

Sets a callback which will be called when all assets in the list have been loaded.

Parameters

Inherited from EventHandler

AssetReference

Class · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-reference.js#L22

An AssetReference follows a single asset slot on behalf of its owner, such as the texture property of a component, and calls back when that asset is added to the registry, loads or is removed. Point it at an asset by setting id or url. The asset does not need to exist yet: the add callback fires when an asset with that id or URL is later registered. The unload callback is delivered only for a reference by id.

Example

const reference = new AssetReference('textureAsset', this, this.app.assets, {
    load: this.onTextureAssetLoad,
    remove: this.onTextureAssetRemove
}, this);
reference.id = this.textureAsset.id;

Constructors

constructor

new AssetReference(propertyName: string, parent: any, registry: AssetRegistry, callbacks: object, scope?: any)

Create a new AssetReference instance.

Parameters

Example

const reference = new AssetReference('textureAsset', this, this.app.assets, {
    load: this.onTextureAssetLoad,
    add: this.onTextureAssetAdd,
    remove: this.onTextureAssetRemove
}, this);
reference.id = this.textureAsset.id;

Accessors

id

get id(): number | null
set id(value: number | null)

Gets the asset id which this references.

url

get url(): string | null
set url(value: string | null)

Gets the asset url which this references.

AssetRegistry

Class · extends EventHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L69

The AssetRegistry holds every Asset an application knows about and drives their loading through the ResourceLoader. Each application has one at AppBase#assets.

Look assets up by id with get, by name and type with find and findAll, by URL with getByUrl, or by tag with findByTag. Register an asset with add, or create and load one in a single call with loadFromUrl, which reuses any asset already registered for that URL.

Adding an asset does not fetch it unless Asset#preload is true. Call load to fetch it, then wait with Asset#ready or listen for the registry's load, error, add and remove events. Each also fires per asset as load:[id] and, except for error, per URL as load:url:[url].

Example

const asset = app.assets.find('brick', 'texture');
app.assets.load(asset);
asset.ready((asset) => {
    material.diffuseMap = asset.resource;
});

Example

app.assets.loadFromUrl('models/robot.glb', 'container', (err, asset) => {
    app.root.addChild(asset.resource.instantiateRenderEntity());
});

Constructors

constructor

new AssetRegistry(loader: ResourceLoader)

Create an instance of an AssetRegistry.

Parameters

Properties

bundles

bundles: BundleRegistry | null = null

The bundle registry that tracks which assets are packed into bundle assets and serves their files from loaded bundles. Assigned when the application creates its bundle registry; null until then.

prefix

prefix: string | null = null

A URL prefix that will be added to all asset loading requests.

Methods

add

add(asset: Asset<string>): void

Add an asset to the registry. If Asset#preload is true, it will also get loaded.

Parameters

Example

const asset = new Asset("My Asset", "texture", {
    url: "../path/to/image.jpg"
});
app.assets.add(asset);

filter

filter(callback: FilterAssetCallback): Asset<string>[]

Return all Assets that satisfy a filter callback.

Parameters

Returns Asset<string>[]: A list of all Assets found.

Example

const assets = app.assets.filter(asset => asset.name.includes('monster'));
console.log(`Found ${assets.length} assets with a name containing 'monster'`);

find

find<K extends string & {} | AssetType>(name: string, type: K): Asset<K> | null

Return the first Asset with the specified name and type found in the registry.

The type also types the result: find('brick', 'texture') returns Asset<'texture'> | null, whose resource is a Texture. See AssetMap.

Parameters

Returns Asset<K> | null: A single Asset or null if no Asset is found.

Example

const asset = app.assets.find("myTextureAsset", "texture");
if (asset) {
    const texture = asset.resource; // a Texture
}
find(name: string, type?: string): Asset<string> | null

Return the first Asset with the specified name found in the registry, of any type or of a type only known as a string. The result is a plain Asset, whose resource is unknown.

Parameters

Returns Asset<string> | null: A single Asset or null if no Asset is found.

Example

const asset = app.assets.find("myAsset");

findAll

findAll<K extends string & {} | AssetType>(name: string, type: K): Asset<K>[]

Return all Assets with the specified name and type found in the registry.

The type also types the result, as for AssetRegistry#find: findAll('brick', 'texture') returns Asset<'texture'>[].

Parameters

Returns Asset<K>[]: A list of all Assets found.

Example

const assets = app.assets.findAll('brick', 'texture');
console.log(`Found ${assets.length} texture assets named 'brick'`);
const textures = assets.map(asset => asset.resource); // Texture[]
findAll(name: string, type?: string): Asset<string>[]

Return all Assets with the specified name found in the registry, of any type or of a type only known as a string.

Parameters

Returns Asset<string>[]: A list of all Assets found.

Example

const assets = app.assets.findAll('brick');

findByTag

findByTag(...query: any[]): Asset<string>[]

Return all Assets that satisfy the search query. Query can be simply a string, or comma separated strings, to have inclusive results of assets that match at least one query. A query that consists of an array of tags can be used to match assets that have each tag of array.

Parameters

Returns Asset<string>[]: A list of all Assets matched query.

Example

const assets = app.assets.findByTag("level-1");
// returns all assets that tagged by `level-1`

Example

const assets = app.assets.findByTag("level-1", "level-2");
// returns all assets that tagged by `level-1` OR `level-2`

Example

const assets = app.assets.findByTag(["level-1", "monster"]);
// returns all assets that tagged by `level-1` AND `monster`

Example

const assets = app.assets.findByTag(["level-1", "monster"], ["level-2", "monster"]);
// returns all assets that tagged by (`level-1` AND `monster`) OR (`level-2` AND `monster`)

get

get(id: number): Asset<string> | undefined

Retrieve an asset from the registry by its id field.

Parameters

Returns Asset<string> | undefined: The asset.

Example

const asset = app.assets.get(100);

getByUrl

getByUrl(url: string): Asset<string> | undefined

Retrieve an asset from the registry by its file's URL field.

Parameters

Returns Asset<string> | undefined: The asset.

Example

const asset = app.assets.getByUrl("../path/to/image.jpg");

list

list(filters?: object): Asset<string>[]

Create a filtered list of assets from the registry.

Parameters

Returns Asset<string>[]: The filtered list of assets.

load

load(asset: Asset<string>, options?: object): void

Load the asset's file from a remote source. Listen for load events on the asset to find out when it is loaded.

Container-backed render assets wait for the container referenced by data.containerAsset to be registered and loaded before firing load. The container can be registered later, but if it is never registered, the render asset remains loading indefinitely. If that render asset is marked for preload, it also prevents AppBase#preload from completing.

Parameters

Example

// load some assets
const assetsToLoad = [
    app.assets.find("My Asset"),
    app.assets.find("Another Asset")
];
let count = 0;
assetsToLoad.forEach((assetToLoad) => {
    assetToLoad.ready((asset) => {
        count++;
        if (count === assetsToLoad.length) {
            // done
        }
    });
    app.assets.load(assetToLoad);
});

loadFromUrl

loadFromUrl<K extends string & {} | AssetType>(url: string, type: K, callback: LoadAssetCallback<K>): void

Use this to load and create an asset if you don't have assets created. Usually you would only use this if you are not integrated with the PlayCanvas Editor.

The type also types the loaded asset: loadFromUrl(url, 'texture', callback) passes an Asset<'texture'> to callback, whose resource is a Texture. See AssetMap. An asset already registered for the URL is reused, whatever its type, so load a URL as one type only; otherwise the callback can receive an asset of another type than requested.

Parameters

Example

app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) {
    const texture = asset.resource; // a Texture
});

loadFromUrlAndFilename

loadFromUrlAndFilename<K extends string & {} | AssetType>(url: string, filename: string, type: K, callback: LoadAssetCallback<K>): void

Use this to load and create an asset when both the URL and filename are required. For example, use this function when loading BLOB assets, where the URL does not adequately identify the file.

Parameters

Example

const file = magicallyObtainAFile();
app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) {
    const texture = asset.resource; // a Texture
});

remove

remove(asset: Asset<string>): boolean

Remove an asset from the registry.

Parameters

Returns boolean: True if the asset was successfully removed and false otherwise.

Example

const asset = app.assets.get(100);
app.assets.remove(asset);

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when an asset is added to the registry. This event is available in three forms. They are as follows:

  1. add - Fired when any asset is added to the registry.
  2. add:[id] - Fired when an asset is added to the registry, where [id] is the unique id of the asset.
  3. add:url:[url] - Fired when an asset is added to the registry and matches the URL [url], where [url] is the URL of the asset.

Example

app.assets.on('add', (asset) => {
   console.log(`Asset added: ${asset.name}`);
});

Example

const id = 123456;
app.assets.on('add:' + id, (asset) => {
   console.log(`Asset added: ${asset.name}`);
});

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('add:url:' + asset.file.url, (asset) => {
   console.log(`Asset added: ${asset.name}`);
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when an error occurs during asset loading. This event is available in two forms. They are as follows:

  1. error - Fired when any asset reports an error in loading.
  2. error:[id] - Fired when an asset reports an error in loading, where [id] is the unique id of the asset.

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error', (err, asset) => {
    console.error(err);
});
app.assets.load(asset);

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('error:' + id, (err, asset) => {
    console.error(err);
});
app.assets.load(asset);

EVENT_LOAD

static EVENT_LOAD: string = 'load'

Fired when an asset completes loading. This event is available in three forms. They are as follows:

  1. load - Fired when any asset finishes loading.
  2. load:[id] - Fired when a specific asset has finished loading, where [id] is the unique id of the asset.
  3. load:url:[url] - Fired when an asset finishes loading whose URL matches [url], where [url] is the URL of the asset.

Example

app.assets.on('load', (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:' + id, (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('load:url:' + asset.file.url, (asset) => {
    console.log(`Asset loaded: ${asset.name}`);
});
app.assets.load(asset);

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when an asset is removed from the registry. This event is available in three forms. They are as follows:

  1. remove - Fired when any asset is removed from the registry.
  2. remove:[id] - Fired when an asset is removed from the registry, where [id] is the unique id of the asset.
  3. remove:url:[url] - Fired when an asset is removed from the registry and matches the URL [url], where [url] is the URL of the asset.

Example

app.assets.on('remove', (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});

Example

const id = 123456;
app.assets.on('remove:' + id, (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});

Example

const id = 123456;
const asset = app.assets.get(id);
app.assets.on('remove:url:' + asset.file.url, (asset) => {
   console.log(`Asset removed: ${asset.name}`);
});

Inherited from EventHandler

AudioHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/audio.js#L15

Resource handler for the audio asset type. Decodes any audio format the browser supports, such as MP3, OGG and WAV, into a Sound through the application's SoundManager.

Inherited from ResourceHandler

ContainerHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/container.js#L206

Resource handler for the container asset type. Loads glTF and GLB files, whose meshes, materials, textures, animations and Gaussian splats become one ContainerResource.

For glTF files, the asset options object can be used to pass load time callbacks for handling the various resources at different stages of loading. The table below lists the resource types and the corresponding supported process functions.

resource preprocess process processAsync postprocess
global √ √
node √ √ √
light √ √ √
camera √ √ √
animation √ √
material √ √ √
image √ √ √
texture √ √ √
buffer √ √ √
bufferView √ √ √

Additional options that can be passed for glTF files: [options.morphPreserveData] - When true, the morph target keeps its data passed using the options, allowing the clone operation. [options.morphPreferHighPrecision] - When true, high precision storage for morph targets should be preferred. This is faster to create and allows higher precision, but takes more memory and might be slower to render. Defaults to false. [options.skipMeshes] - When true, the meshes and gaussian splats from the container are not created. This can be useful if you only need access to textures or animations and similar.

For example, to receive a texture preprocess callback:

const containerAsset = new Asset(filename, 'container', { url: url, filename: filename }, null, {
    texture: {
        preprocess: (gltfTexture) => {
            console.log("texture preprocess");
        }
    }
});

Inherited from ResourceHandler

CubemapHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/cubemap.js#L33

Resource handler for the cubemap asset type. Assembles a cube map Texture from six face texture assets, from a prefiltered environment file, or both, and stores the results in Asset#resources.

Methods

load

load(url: any, callback: any, asset: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any, asset: any): any

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns any: The parsed resource data.

patch

patch(asset: any, registry: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

FontHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/font.js#L45

Resource handler for the font asset type. Loads a Font from a JSON glyph description and the texture pages that accompany it. Bitmap fonts and multi-channel signed distance field fonts are both supported.

Methods

load

load(url: any, callback: any, asset: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any, asset: any): Font

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns Font: The parsed resource data.

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

MaterialHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/material.js#L29

Resource handler for the material asset type. Loads material JSON into a StandardMaterial and binds the texture assets it references. A custom parser may produce another kind of Material.

Methods

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

ModelHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/model.js#L18

Resource handler for the model asset type. Loads legacy PlayCanvas JSON models and GLB files into a Model. OBJ files are supported once the ObjModelParser shipped in playcanvas/scripts/esm/parsers/obj-model.mjs is registered with ResourceHandler#addParser.

Methods

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

RenderHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/render.js#L19

Resource handler for the render asset type. A render asset has no file of its own: it takes the meshes of one glTF mesh from the container asset named in its data and exposes them as a Render.

Methods

load

load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): void

Waits for a render asset's container to supply its meshes. Without an asset, completes with no render data.

Parameters

open

open(url: any, data: any): Render

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns Render: The parsed resource data.

patch

patch(asset: any, registry: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

ResourceHandler

Class · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L83

A ResourceHandler loads and opens resources of one asset type on behalf of the ResourceLoader. The engine ships a handler for every built-in AssetType, and an application registers the ones listed in AppOptions#resourceHandlers, so a hand-configured AppBase may support only some types. Register your own with ResourceLoader#addHandler to add a new type.

A handler works in two steps. load fetches the raw data for a URL and open turns that data into the resource stored on Asset#resource. A handler may also implement patch to resolve references to other assets once the resource exists. Rather than overriding those methods, a handler can register one ResourceParser per file format with addParser and let the base class pick the parser that claims the file.

Example

class CsvHandler extends ResourceHandler {
    constructor(app) {
        super(app, 'csv');
    }

    load(url, callback) {
        this.fetch(url, 'text', callback);
    }

    open(url, data) {
        return data.split('\n').map(line => line.split(','));
    }
}
app.loader.addHandler('csv', new CsvHandler(app));

Constructors

constructor

new ResourceHandler(app: AppBase, handlerType: string)

Parameters

Properties

_app

protected _app: AppBase

The running app instance.

handlerType

handlerType: string = ''

Type of the resource the handler handles.

Accessors

app

get app(): AppBase

Gets the running AppBase instance.

maxRetries

get maxRetries(): number
set maxRetries(value: number)

Gets the number of times to retry a failed request for the resource.

parsers

get parsers(): ResourceParser[]

Gets a read-only copy of the registered parsers.

Methods

addParser

addParser(parser: ResourceParser, decider?: any): void

Registers a ResourceParser for this handler. Parsers are consulted newest-first: the most recently added parser whose ResourceParser#canParse returns true is selected. This lets a later registration override a built-in parser for the same format.

Register parsers before starting loads for this handler's type - selection runs for both the load and open phases, so changing the registry while loads are in flight can route them inconsistently. Note that handlers that implement their own loading without consulting registered parsers (for example cubemap or font) ignore registered parsers.

Parameters

Example

app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice));

fetch

fetch(url: string | { load: string; original: string }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset<string>): void

Fetches a resource's raw data using this handler's retry settings, reusing pre-fetched asset.file.contents when available. A convenience for a ResourceParser's load method, so parsers don't reimplement the fetch boilerplate.

Parameters

load

load(url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: string, data: any, asset?: Asset<string>): any

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns any: The parsed resource data.

patch

patch(asset: Asset<string>, assets: AssetRegistry): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

removeParser

removeParser(parser: ResourceParser): void

Removes a previously registered ResourceParser.

Parameters

ResourceLoader

Class · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/loader.js#L43

The ResourceLoader turns a URL and an asset type into a loaded resource. It owns one ResourceHandler per type, dispatches each request to the matching handler, and caches the result by URL and type so the same request is fetched once. Each application has one at AppBase#loader.

Most code never calls the loader directly: the AssetRegistry does so on its behalf when an Asset loads. Use the loader to add support for a new asset type with addHandler, to reach an existing handler with getHandler, or to tune requests with maxConcurrentRequests, withCredentials and enableRetry.

Parsers for formats the engine does not load by default ship in the package and are registered on an existing handler rather than added as one: playcanvas/scripts/esm/parsers/obj-model.mjs adds .obj model loading and playcanvas/scripts/esm/parsers/spz-parser.mjs adds .spz Gaussian-splat loading.

Example

app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice));

Example

app.loader.getHandler('gsplat').addParser(new SpzParser(app));

Constructors

constructor

new ResourceLoader(app: AppBase)

Create a new ResourceLoader instance.

Parameters

Accessors

maxConcurrentRequests

get maxConcurrentRequests(): number
set maxConcurrentRequests(value: number)

Gets the maximum number of asset requests that can be in flight at the same time.

withCredentials

get withCredentials(): boolean
set withCredentials(value: boolean)

Gets whether asset requests are sent with credentials.

Methods

addHandler

addHandler(type: string & {} | AssetType, handler: ResourceHandler): void

Add a ResourceHandler for a resource type. Handler should support at least load() and open(). Handlers can optionally support patch(asset, assets) to handle dependencies on other assets.

Parameters

Example

// register a handler for a new 'csv' asset type (see ResourceHandler for the class)
app.loader.addHandler('csv', new CsvHandler(app));

clearCache

clearCache(url: string, type: string): void

Remove resource from cache.

Parameters

destroy

destroy(): void

Destroys the resource loader.

disableRetry

disableRetry(): void

Disables retrying of failed requests when loading assets.

enableRetry

enableRetry(maxRetries?: number): void

Enables retrying of failed requests when loading assets. Retries use exponential backoff and are also enabled by default for new applications.

Parameters

getFromCache

getFromCache(url: string, type: string): any

Check cache for resource from a URL. If present, return the cached value.

Parameters

Returns any: The resource loaded from the cache.

getHandler

getHandler(type: string & {} | AssetType): ResourceHandler | undefined

Get a ResourceHandler for a resource type.

Parameters

Returns ResourceHandler | undefined: The registered handler, or undefined if the requested handler is not registered.

load

load(url: string, type: string, callback: ResourceLoaderCallback, asset?: Asset<string>, options?: object): void

Make a request for a resource from a remote URL. Parse the returned data using the handler for the specified type. When loaded and parsed, use the callback to return an instance of the resource.

Parameters

Example

app.loader.load("../path/to/texture.png", "texture", function (err, texture) {
    // use texture here
});

open

open(type: string, data: any): any

Convert raw resource data into a resource instance. E.g. Take 3D model format JSON and return a Model.

Parameters

Returns any: The parsed resource data.

patch

patch(asset: Asset<string>, assets: AssetRegistry): void

Perform any operations on a resource, that requires a dependency on its asset data or any other asset data.

Parameters

removeHandler

removeHandler(type: string & {} | AssetType): void

Remove a ResourceHandler for a resource type.

Parameters

SceneHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/scene.js#L15

Resource handler for the scene asset type. Loads a PlayCanvas scene JSON file, instantiates its entity hierarchy as the root of AppBase#scene and applies the scene's settings.

Methods

load

load(url: any, callback: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any): Scene

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns Scene: The parsed resource data.

Inherited from ResourceHandler

ScriptHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/script.js#L21

Resource handler for loading JavaScript files dynamically. Two types of JavaScript files can be loaded, PlayCanvas scripts which contain calls to createScript, or regular JavaScript files, such as third-party libraries.

Methods

load

load(url: any, callback: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any): any

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns any: The parsed resource data.

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

SpriteHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/sprite.js#L30

Resource handler for the sprite asset type. Builds a Sprite from sprite JSON, loaded from a file or supplied as asset data, and binds the TextureAtlas asset it references.

Methods

load

load(url: any, callback: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any): Sprite

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns Sprite: The parsed resource data.

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

TextureAtlasHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/texture-atlas.js#L41

Resource handler for the textureatlas asset type. Loads a texture and its frame definitions into a TextureAtlas. The frames come from the asset data, or from a JSON file with a texture of the same name beside it.

Methods

load

load(url: any, callback: any): void

Load a resource from a remote URL. When parsers are registered, the matching parser's load is used; otherwise the base implementation does nothing (subclasses may override).

Parameters

open

open(url: any, data: any, asset: any): TextureAtlas | null

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns TextureAtlas | null: The parsed resource data.

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

TextureHandler

Class · extends ResourceHandler · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/texture.js#L172

Resource handler for the texture asset type. Loads 2D and 3D Texture resources from any image format the browser decodes, such as PNG, JPEG, WebP and AVIF, and from DDS, KTX, KTX2, Basis and HDR files.

Methods

open

open(url: any, data: any, asset: any): any

The open function is passed the raw resource data. The handler can then process the data into a format that can be used at runtime. When parsers are registered, the matching parser's open is used (if it implements one); otherwise the base implementation simply returns the data.

Parameters

Returns any: The parsed resource data.

patch

patch(asset: any, assets: any): void

The patch function performs any operations on a resource that requires a dependency on its asset data or any other asset data. The base implementation does nothing.

Parameters

Inherited from ResourceHandler

MiniStats

Class · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L120

MiniStats is a small graphical overlay that displays realtime performance metrics. By default, it shows CPU and GPU durations, frame intervals, draw call count and estimated GPU resource memory. It can also display additional counters from AppBase#stats.

The default CPU timings, including render time, draw call count and memory estimates are available in all builds. GPU timing requires device support and is enabled when MiniStats creates its GPU timer. Some additional counters, such as AppStats#primitiveCount, require a debug or profiler build. See AppStats for measurement scope and availability. In the detailed views, click a category heading to collapse or expand its sub-counters. Click elsewhere in the overlay to change size. Collapsing a category preserves its sampling and graph history. Resources is enabled and collapsed by default, and displays current counts of existing tracked resources, including internal resources, in detailed views. Resource counts refresh at textRefreshRate while visible, including their sum in the collapsed heading; they have no average or peak. In graph views, resource histories use the latest sampled counts and scale to accommodate the highest count seen.

Constructors

constructor

new MiniStats(app: AppBase, options?: MiniStatsOptions)

Create a new MiniStats instance.

Parameters

Example

const miniStats = new MiniStats(app);

Accessors

cpuCollapsed

get cpuCollapsed(): boolean
set cpuCollapsed(value: boolean)

enabled

get enabled(): boolean
set enabled(value: boolean)

engineCollapsed

get engineCollapsed(): boolean
set engineCollapsed(value: boolean)

gpuCollapsed

get gpuCollapsed(): boolean
set gpuCollapsed(value: boolean)

resourcesCollapsed

get resourcesCollapsed(): boolean
set resourcesCollapsed(value: boolean)

resourcesEnabled

get resourcesEnabled(): boolean
set resourcesEnabled(value: boolean)

userCollapsed

get userCollapsed(): boolean
set userCollapsed(value: boolean)

vramCollapsed

get vramCollapsed(): boolean
set vramCollapsed(value: boolean)

Methods

destroy

destroy(): void

Destroy the MiniStats instance and release its event listeners, textures and mesh.

Example

miniStats.destroy();

getDefaultOptions

static getDefaultOptions(extraStats?: string[]): MiniStatsOptions

Returns options for three sizes: compact core counters, grouped averages, and grouped averages and peaks with graph history. Engine counters appear first, starting with draw calls and frame time, followed by User, CPU, GPU and VRAM. In the detailed views, Engine and User have collapsible headings, omitted when empty.

Parameters

Returns MiniStatsOptions: The default options for MiniStats.

Example

const options = MiniStats.getDefaultOptions(['gsplats']);
options.sizes[2].width = 280;
const miniStats = new MiniStats(app, options);

Tracing

Class · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/tracing.js#L12

Log tracing functionality, allowing for tracing of the internal functionality of the engine. Note that the trace logging only takes place in the debug build of the engine and is stripped out in other builds.

The debug build ships in the npm package: import from 'playcanvas/debug' instead of 'playcanvas' to enable trace channels, assertions and validation warnings. A 'playcanvas/profiler' build is also available for per-frame timings.

Properties

stack

static stack: boolean = false

Enable call stack logging for trace calls. Defaults to false.

Methods

get

static get(channel: string): boolean

Test if the trace channel is enabled.

Parameters

Returns boolean: - True if the trace channel is enabled.

set

static set(channel: string, enabled?: boolean): void

Enable or disable a trace channel.

Parameters

GltfExporter

Class · category: Exporter

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/exporters/gltf-exporter.js#L145

Implementation of the GLTF 2.0 format exporter.

Methods

build

build(entity: Entity, options?: object): Promise<ArrayBuffer>

Converts a hierarchy of entities to GLB format.

Parameters

Returns Promise<ArrayBuffer>: - The GLB file content.

Inherited from CoreExporter

UsdzExporter

Class · category: Exporter

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/exporters/usdz-exporter.js#L154

Implementation of the USDZ format exporter. Note that ASCII version of the format (USDA) is used.

Methods

build

build(entity: Entity, options?: object): Promise<ArrayBuffer>

Converts a hierarchy of entities to USDZ format. Skinned meshes are exported in their current pose.

Parameters

Returns Promise<ArrayBuffer>: - The USDZ file content.

Inherited from CoreExporter

AppBase

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L130

AppBase represents the base functionality for all PlayCanvas applications. It is responsible for initializing and managing the application lifecycle. It coordinates core engine systems such as:

Using AppBase directly requires you to register ComponentSystems and ResourceHandlers yourself. This facilitates tree-shaking when bundling your application.

It is the preferred entry point for new code - Application is a convenience subclass that registers everything for you, and is expected to be deprecated in a future release.

new AppBase(canvas) only constructs the instance and its root entity. You must then call AppBase#init with an AppOptions supplying at minimum graphicsDevice, componentSystems and resourceHandlers before adding components or calling AppBase#start. Create the graphicsDevice with createGraphicsDevice.

Constructors

constructor

new AppBase(canvas: OffscreenCanvas | HTMLCanvasElement)

Create a new AppBase instance.

Parameters

Example

const app = new AppBase(canvas);

const options = new AppOptions();
app.init(options);

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

Properties

assets

assets: AssetRegistry

The asset registry managed by the application.

Example

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

autoRender

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.

Example

// 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

elementInput: ElementInput | null = null

Used to handle input for ElementComponents.

gamepads

gamepads: GamePads | null = null

Used to access GamePad input.

graphicsDevice

graphicsDevice: GraphicsDevice

The graphics device used by the application.

i18n

i18n: I18n

Handles localization.

keyboard

keyboard: Keyboard | null = null

The keyboard device.

lightmapper

lightmapper: Lightmapper | null = null

The run-time lightmapper.

loader

loader: ResourceLoader

The resource loader.

maxDeltaTime

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

Example

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

mouse

mouse: Mouse | null = null

The mouse device.

renderNextFrame

renderNextFrame: boolean

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.

Example

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

root

root: Entity

The root entity of the application.

Example

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

scene

scene: Scene

The scene managed by the application.

Example

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

scenes

scenes: SceneRegistry

The scene registry managed by the application.

Example

// 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

scripts: ScriptRegistry

The application's script registry.

scriptsOrder

scriptsOrder: string[] = []

Scripts in order of loading first.

systems

systems: ComponentSystemRegistry

The application's component system registry.

Example

// Set global gravity to zero
this.app.systems.rigidbody.gravity.set(0, 0, 0);

Example

// Set the global sound volume to 50%
this.app.systems.sound.volume = 0.5;

timeScale

timeScale: number = 1

Scales the global time delta. Defaults to 1. Scripts, animation and physics all receive the scaled delta, so 0 stops them together. To pause or slow down physics alone while the rest of the application keeps running, use RigidBodyComponentSystem#timeScale.

Example

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

touch

touch: TouchDevice | null = null

Used to get touch events input.

xr

xr: XrManager | null = null

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

Example

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

Accessors

batcher

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.

fillMode

get fillMode(): string

The current fill mode of the canvas. Can be:

resolutionMode

get resolutionMode(): string

The current resolution mode of the canvas, Can be:

stats

get stats(): AppStats

The application's performance statistics. Returns the same AppStats instance on every access. Engine measurements are read-only; AppStats#user holds writable application-defined counters. See AppStats for units, sampling and GPU profiling setup.

Methods

applySceneSettings

applySceneSettings(settings: object): void

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

Parameters

Example

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);

configure

configure(url: string, callback: ConfigureAppCallback): void

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

Parameters

destroy

destroy(): 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.

Example

app.destroy();

drawLine

drawLine(start: Vec3, end: Vec3, color?: Color, depthTest?: boolean, layer?: Layer): void

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

Example

// Render a 1-unit long white line
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLine(start, end);

Example

// Render a 1-unit long red line which is not depth tested and renders on top of other geometry
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLine(start, end, Color.RED, false);

Example

// Render a 1-unit long white line into the world layer
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
const worldLayer = app.scene.layers.getLayerById(LAYERID_WORLD);
app.drawLine(start, end, Color.WHITE, true, worldLayer);

drawLineArrays

drawLineArrays(positions: number[], colors: number[] | Color, depthTest?: boolean, layer?: Layer): void

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

Example

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

drawLines

drawLines(positions: Vec3[], colors: Color | Color[], depthTest?: boolean, layer?: Layer): void

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

Example

// Render a single line, with unique colors for each point
const start = new Vec3(0, 0, 0);
const end = new Vec3(1, 0, 0);
app.drawLines([start, end], [Color.RED, Color.WHITE]);

Example

// Render 2 discrete line segments
const points = [
    // Line 1
    new Vec3(0, 0, 0),
    new Vec3(1, 0, 0),
    // Line 2
    new Vec3(1, 1, 0),
    new Vec3(1, 1, 1)
];
const colors = [
    // Line 1
    Color.RED,
    Color.YELLOW,
    // Line 2
    Color.CYAN,
    Color.BLUE
];
app.drawLines(points, colors);

init

init(appOptions: AppOptions): void

Initialize the app.

Parameters

isHidden

isHidden(): boolean

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.

preload

preload(callback: PreloadAppCallback): void

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

Container-backed render assets wait for their referenced containers to be registered and loaded. If a preloaded render asset's data.containerAsset refers to a container that is never registered, this method never calls its callback or fires preload:end. Debug builds warn when a render asset starts waiting for an unregistered container.

Parameters

resizeCanvas

resizeCanvas(width?: number, height?: number): { height: number; width: number } | undefined

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

Parameters

Returns { height: number; width: number } | undefined: An object containing the values calculated to use as width and height, or undefined if resizing is not allowed or an XR session is active.

setAreaLightLuts

setAreaLightLuts(ltcMat1: number[], ltcMat2: number[]): void

Sets the area light LUT tables for this app.

Parameters

setCanvasFillMode

setCanvasFillMode(mode: string, width?: number, height?: number): void

Controls how the canvas fills the window. The canvas is sized when this is called and on every AppBase#resizeCanvas; the engine installs no window resize listener of its own, so call resizeCanvas from your own handler to keep the window-relative modes tracking the window.

Parameters

setCanvasResolution

setCanvasResolution(mode: string, width?: number, height?: number): void

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

Parameters

setSkybox

setSkybox(asset: Asset<string>): void

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

Parameters

start

start(): 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.

The main loop is driven by requestAnimationFrame. Where that is unavailable, such as in Node.js, no loop runs, so call update yourself at the rate you need.

Example

app.start();

update

update(dt: number): void

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, except where there is no main loop, such as in Node.js.

Parameters

Example

// run a Node.js server at 20 updates per second
setInterval(() => app.update(1 / 20), 50);

updateCanvasSize

updateCanvasSize(): 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.

getApplication

static getApplication(id?: string): AppBase | undefined

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

Returns AppBase | undefined: The running application, if any.

Example

const app = AppBase.getApplication();

Inherited from EventHandler

Application

Class · extends AppBase · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/application.js#L109

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.

New code should prefer AppBase, as this class is expected to be deprecated in a future release. Two limitations motivate that:

The equivalent AppBase setup registers only what the app actually uses:

const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] });

const options = new AppOptions();
options.graphicsDevice = device;
options.componentSystems = [RenderComponentSystem, CameraComponentSystem, LightComponentSystem];
options.resourceHandlers = [TextureHandler, ContainerHandler];

const app = new AppBase(canvas);
app.init(options);

The component systems this class registers are listed on the constructor below. That list doubles as a migration checklist, as it maps each component name to the system you would need to register yourself.

AppBase#keyboard, AppBase#mouse, AppBase#touch, AppBase#gamepads and AppBase#elementInput stay null unless the matching device is passed to this constructor, so a game that reads input must construct with, for example, { keyboard: new Keyboard(window), mouse: new Mouse(canvas), touch: new TouchDevice(canvas) }.

Constructors

constructor

new Application(canvas: OffscreenCanvas | HTMLCanvasElement, options?: object)

Create a new Application instance.

Automatically registers these component systems with the application's component system registry:

Parameters

Example

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

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

Inherited from AppBase

AppOptions

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-options.js#L23

AppOptions holds configuration settings utilized in the creation of an AppBase instance. It allows functionality to be included or excluded from the AppBase instance.

Properties

assetPrefix

assetPrefix: string

Prefix to apply to asset urls before loading.

batchManager

batchManager: typeof BatchManager

The BatchManager.

componentSystems

componentSystems: typeof ComponentSystem[] = []

The component systems the app requires.

devtools

devtools: boolean = true

Whether the app announces itself to developer tools, such as the PlayCanvas Inspector browser extension, so they can find and inspect it. Set to false to keep a production build from announcing itself. This is an opt-out, not a protection: code running on the page can still reach the app by other means. Defaults to true.

elementInput

elementInput: ElementInput

Input handler for ElementComponents.

gamepads

gamepads: GamePads

Gamepad handler for input.

graphicsDevice

graphicsDevice: GraphicsDevice

The graphics device.

keyboard

keyboard: Keyboard

Keyboard handler for input.

lightmapper

lightmapper: typeof Lightmapper

The lightmapper.

mouse

mouse: Mouse

Mouse handler for input.

physicsWorld

physicsWorld: PhysicsWorld

The physics backend used to simulate rigid bodies, collisions and joints, such as AmmoPhysicsWorld or NullPhysicsWorld. When set, the application installs it into the RigidBodyComponentSystem during AppBase#init, so AppOptions#componentSystems must include RigidBodyComponentSystem. A useful simulation also requires CollisionComponentSystem - rigid bodies and triggers obtain their shapes from collision components - and JointComponentSystem if joints are used. The rigid body system registers its contact listener with the world. When omitted, an AmmoPhysicsWorld is created automatically once application libraries have loaded, if the Ammo.js WasmModule is present. The application takes ownership of the world and destroys it with the application.

resourceHandlers

resourceHandlers: typeof ResourceHandler[] = []

The resource handlers the app requires.

scriptPrefix

scriptPrefix: string

Prefix to apply to script urls before loading.

scriptsOrder

scriptsOrder: string[]

Scripts in order of loading first.

soundManager

soundManager: SoundManager

The sound manager

touch

touch: TouchDevice

TouchDevice handler for input.

xr

xr: typeof XrManager

The XrManager.

AppStats

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-stats.js#L47

Performance statistics for an application, accessed through AppBase#stats. Engine measurements are read-only; user holds writable application-defined counters. Includes frame cadence, CPU phase timings, overall GPU frame timing, and estimated GPU resource memory usage. CPU timings, GPU timings and memory statistics are available in all builds, subject to graphics capabilities. Primitive counting requires a debug or profiler build; see each getter for its availability.

Durations are in milliseconds and memory sizes are in bytes. Values are the latest available measurements, not averages, except for fps, which refreshes approximately once per second. Frame counters are published at the start of the next application tick; CPU timings are updated when their respective phases finish. CPU phases overlap and must not all be added together. CPU timings and counters are initially zero. GPU results arrive asynchronously and can describe an older frame than the CPU measurements.

GPU profiling is disabled by default. Enable it with app.graphicsDevice.gpuProfiler.enabled = true when a profiler exists (see the example below). WebGL requires the disjoint timer query extension; WebGPU requires the timestamp-query feature. Enabling profiling on an unsupported device produces no timings. gpuFrameTime returns undefined when profiling is disabled, unsupported, or no valid result has arrived. Reading stats does not enable profiling. MiniStats also enables GPU profiling when it creates its GPU timer.

Memory statistics estimate resources tracked by the application's graphics device, which may be shared by applications. They do not represent total physical GPU memory usage or capacity, and exclude untracked driver overhead and JavaScript memory.

Example

const profiler = app.graphicsDevice.gpuProfiler;
if (profiler) {
    profiler.enabled = true;
}

app.on('frameend', () => {
    const stats = app.stats;
    console.log(stats.cpuUpdateTime, stats.cpuRenderTime, stats.gpuFrameTime);
});

See AppBase#stats

Accessors

cpuAnimationTime

get cpuAnimationTime(): number

CPU duration of the latest dedicated animation-update phase in milliseconds, used by AnimComponentSystem. Excludes the legacy AnimationComponentSystem, which runs in the system update phase. Part of cpuUpdateTime. Available in all builds.

cpuPhysicsTime

get cpuPhysicsTime(): number

CPU duration of the most recent physics step in milliseconds, including synchronization and contact handling. Normally part of cpuSystemUpdateTime. Multiple manual steps are not accumulated. Zero before any step or when physics is paused through its timeScale property. Available in all builds.

cpuRenderTime

get cpuRenderTime(): number

CPU duration of the latest scene render in milliseconds, including prerender and postrender event listeners, hierarchy synchronization, batching and render command submission. Excludes graphics device frameStart/frameEnd work and does not measure GPU execution. Retains the latest measurement when rendering is skipped. Available in all builds.

cpuSystemPostUpdateTime

get cpuSystemPostUpdateTime(): number

CPU duration of the latest component systems post-update phase in milliseconds, including script postUpdate callbacks. Part of cpuUpdateTime. Available in all builds.

cpuSystemUpdateTime

get cpuSystemUpdateTime(): number

CPU duration of the latest component systems update phase in milliseconds. Includes script updates, physics and other systems subscribed to the update event. Part of cpuUpdateTime. Available in all builds.

cpuUpdateTime

get cpuUpdateTime(): number

CPU duration of the latest application update in milliseconds, including component systems, application update event listeners and input updates. Excludes graphics device updates. Includes the other CPU update phase timings. Available in all builds.

drawCallCount

get drawCallCount(): number

Total draw calls submitted during the previous frame, published at the start of the next application tick. Available in all builds.

fps

get fps(): number

Frame count over the latest approximately one-second reporting interval. Initially zero until an interval completes. Available in all builds.

frameTime

get frameTime(): number

Interval between application ticks in milliseconds, including time outside the engine. Unaffected by time scaling or delta-time clamping. Available in all builds.

gpuFrameTime

get gpuFrameTime(): number | undefined

Overall duration of the most recently resolved GPU frame in milliseconds. Available in all builds when GPU profiling is supported and enabled. Returns undefined until a valid timing arrives, when profiling is disabled, or after timing invalidation such as context loss. Results arrive asynchronously and may be several frames old.

WebGL measures a whole-frame timer query. WebGPU measures the span from the first profiled pass beginning to the last pass ending, including gaps between passes. This is elapsed GPU time, not GPU utilization, and is not the sum of potentially overlapping pass durations.

primitiveCount

get primitiveCount(): number | undefined

Total primitives submitted during the previous frame, published at the start of the next application tick. Counts triangles, lines and points across all passes, including instances and CPU-authored multi-draw commands. Counts are calculated before GPU clipping and culling.

Available only in debug and profiler builds. Returns undefined in release and minified builds. This is an estimate from draw parameters: GPU-generated indirect draws are excluded, and primitive-restart indices in indexed strips are not inspected. No GPU readback is performed.

user

get user(): Map<string, number>

Application-defined numeric counters. Returns the same map on every access. Entries can be added, updated, deleted or cleared by the application; the engine never resets them. Available in all builds. Values and their units are defined by the application.

To display a counter in MiniStats, configure a graph with a path such as user.ai. Counter names used in MiniStats must not contain dots, which separate path segments. Initialize counters before accumulating values and reset per-frame totals on frameupdate.

Example

app.stats.user.set('ai', 0);
app.on('frameupdate', () => app.stats.user.set('ai', 0));

// Accumulate time spent in application code during this frame.
const start = performance.now();
// ... run AI logic ...
app.stats.user.set('ai', app.stats.user.get('ai') + performance.now() - start);

vramIndexBufferBytes

get vramIndexBufferBytes(): number

Estimated GPU index buffer memory in bytes. Available in all builds.

vramStorageBufferBytes

get vramStorageBufferBytes(): number

Estimated GPU storage buffer memory in bytes. Available in all builds. Zero on backends without storage buffers or when none have been allocated.

vramTextureBytes

get vramTextureBytes(): number

Estimated GPU texture memory in bytes. Available in all builds.

vramTotalBytes

get vramTotalBytes(): number

Total estimated GPU resource memory in bytes: textures, vertex buffers, index buffers, uniform buffers and storage buffers. Available in all builds.

vramUniformBufferBytes

get vramUniformBufferBytes(): number

Estimated GPU uniform buffer memory in bytes. Available in all builds. Zero when no tracked uniform buffers have been allocated.

vramVertexBufferBytes

get vramVertexBufferBytes(): number

Estimated GPU vertex buffer memory in bytes. Available in all builds.

Component

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/component.js#L77

Components are used to attach functionality on a Entity. Components can receive update events each frame, and expose properties to the PlayCanvas Editor.

Properties

entity

entity: Entity

The Entity that this Component is attached to.

system

system: ComponentSystem

The ComponentSystem used to create this Component.

Accessors

enabled

get enabled(): boolean
set enabled(value: boolean)

Gets the enabled state of the component.

Inherited from EventHandler

ComponentSystem

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/system.js#L21

Component Systems contain the logic and functionality to update all Components of a particular type.

Constructors

constructor

new ComponentSystem(app: AppBase)

Create a new ComponentSystem instance.

Parameters

Properties

id

readonly id: string

The id type of the ComponentSystem.

Inherited from EventHandler

ComponentSystemRegistry

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/registry.js#L92

The ComponentSystemRegistry manages the instances of an application's ComponentSystems. AppBase maintains a single instance of this class which can be accessed via AppBase#systems.

// Set the gravity to zero
app.systems.rigidbody.gravity = new Vec3(0, 0, 0);

// Set the volume to 50%
app.systems.sound.volume = 0.5;

Constructors

constructor

new ComponentSystemRegistry()

Create a new ComponentSystemRegistry instance.

Properties

anim

readonly anim: AnimComponentSystem | undefined

Gets the AnimComponentSystem from the registry.

animation

readonly animation: AnimationComponentSystem | undefined

Gets the AnimationComponentSystem from the registry.

audiolistener

readonly audiolistener: AudioListenerComponentSystem | undefined

Gets the AudioListenerComponentSystem from the registry.

button

readonly button: ButtonComponentSystem | undefined

Gets the ButtonComponentSystem from the registry.

camera

readonly camera: CameraComponentSystem | undefined

Gets the CameraComponentSystem from the registry.

collision

readonly collision: CollisionComponentSystem | undefined

Gets the CollisionComponentSystem from the registry.

element

readonly element: ElementComponentSystem | undefined

Gets the ElementComponentSystem from the registry.

gsplat

readonly gsplat: GSplatComponentSystem | undefined

Gets the GSplatComponentSystem from the registry.

joint

readonly joint: JointComponentSystem | undefined

Gets the JointComponentSystem from the registry.

layoutchild

readonly layoutchild: LayoutChildComponentSystem | undefined

Gets the LayoutChildComponentSystem from the registry.

layoutgroup

readonly layoutgroup: LayoutGroupComponentSystem | undefined

Gets the LayoutGroupComponentSystem from the registry.

light

readonly light: LightComponentSystem | undefined

Gets the LightComponentSystem from the registry.

model

readonly model: ModelComponentSystem | undefined

Gets the ModelComponentSystem from the registry.

particlesystem

readonly particlesystem: ParticleSystemComponentSystem | undefined

Gets the ParticleSystemComponentSystem from the registry.

render

readonly render: RenderComponentSystem | undefined

Gets the RenderComponentSystem from the registry.

rigidbody

readonly rigidbody: RigidBodyComponentSystem | undefined

Gets the RigidBodyComponentSystem from the registry.

screen

readonly screen: ScreenComponentSystem | undefined

Gets the ScreenComponentSystem from the registry.

script

readonly script: ScriptComponentSystem | undefined

Gets the ScriptComponentSystem from the registry.

scrollbar

readonly scrollbar: ScrollbarComponentSystem | undefined

Gets the ScrollbarComponentSystem from the registry.

scrollview

readonly scrollview: ScrollViewComponentSystem | undefined

Gets the ScrollViewComponentSystem from the registry.

sound

readonly sound: SoundComponentSystem | undefined

Gets the SoundComponentSystem from the registry.

sprite

readonly sprite: SpriteComponentSystem | undefined

Gets the SpriteComponentSystem from the registry.

Inherited from EventHandler

Entity

Class · extends GraphNode · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L153

An Entity is the core primitive of a PlayCanvas application. Every object in a scene (a camera, a light, a 3D model, a sound source, a piece of UI, or your own gameplay object) is represented by an Entity. On its own, an Entity is simply a named node in the scene graph; it gains behavior from the Components attached to it.

An Entity therefore brings together two things:

Add a capability with Entity#addComponent, access it later through the matching property (such as Entity#camera or Entity#render), and remove it with Entity#removeComponent. An entity, together with all of its descendants and their components, can be enabled or disabled as a group via GraphNode#enabled, and removed from the scene with Entity#destroy.

Example

// Create an entity, give it a camera component, position it, and add it to the scene
const camera = new Entity('camera');
camera.addComponent('camera', {
    clearColor: new Color(0.1, 0.1, 0.1)
});
camera.setPosition(0, 0, 10);
app.root.addChild(camera);

Example

// Entities form a hierarchy: a child inherits its parent's transform
const parent = new Entity('parent');
const child = new Entity('child');
parent.addChild(child);
parent.setLocalPosition(5, 0, 0); // moves both parent and child

Constructors

constructor

new Entity(name?: string, app?: AppBase)

Create a new Entity.

Parameters

Example

const entity = new Entity();

// Add a Component to the Entity
entity.addComponent('camera', {
    fov: 45,
    nearClip: 1,
    farClip: 10000
});

// Add the Entity into the scene graph
app.root.addChild(entity);

// Move the entity
entity.translate(10, 0, 0);

// Or translate it by setting its position directly
const p = entity.getPosition();
entity.setPosition(p.x + 10, p.y, p.z);

// Change the entity's rotation in local space
const e = entity.getLocalEulerAngles();
entity.setLocalEulerAngles(e.x, e.y + 90, e.z);

// Or use rotateLocal
entity.rotateLocal(0, 90, 0);

Properties

anim

readonly anim: AnimComponent | undefined

Gets the AnimComponent attached to this entity.

animation

readonly animation: AnimationComponent | undefined

Gets the AnimationComponent attached to this entity.

audiolistener

readonly audiolistener: AudioListenerComponent | undefined

Gets the AudioListenerComponent attached to this entity.

button

readonly button: ButtonComponent | undefined

Gets the ButtonComponent attached to this entity.

camera

readonly camera: CameraComponent | undefined

Gets the CameraComponent attached to this entity.

collision

readonly collision: CollisionComponent | undefined

Gets the CollisionComponent attached to this entity.

element

readonly element: ElementComponent | undefined

Gets the ElementComponent attached to this entity.

gsplat

readonly gsplat: GSplatComponent | undefined

Gets the GSplatComponent attached to this entity.

joint

readonly joint: JointComponent | undefined

Gets the JointComponent attached to this entity.

layoutchild

readonly layoutchild: LayoutChildComponent | undefined

Gets the LayoutChildComponent attached to this entity.

layoutgroup

readonly layoutgroup: LayoutGroupComponent | undefined

Gets the LayoutGroupComponent attached to this entity.

light

readonly light: LightComponent | undefined

Gets the LightComponent attached to this entity.

model

readonly model: ModelComponent | undefined

Gets the ModelComponent attached to this entity.

particlesystem

readonly particlesystem: ParticleSystemComponent | undefined

Gets the ParticleSystemComponent attached to this entity.

render

readonly render: RenderComponent | undefined

Gets the RenderComponent attached to this entity.

rigidbody

readonly rigidbody: RigidBodyComponent | undefined

Gets the RigidBodyComponent attached to this entity.

screen

readonly screen: ScreenComponent | undefined

Gets the ScreenComponent attached to this entity.

script

readonly script: ScriptComponent | undefined

Gets the ScriptComponent attached to this entity.

scrollbar

readonly scrollbar: ScrollbarComponent | undefined

Gets the ScrollbarComponent attached to this entity.

scrollview

readonly scrollview: ScrollViewComponent | undefined

Gets the ScrollViewComponent attached to this entity.

sound

readonly sound: SoundComponent | undefined

Gets the SoundComponent attached to this entity.

sprite

readonly sprite: SpriteComponent | undefined

Gets the SpriteComponent attached to this entity.

Accessors

guid

get guid(): string

Gets the GUID for this Entity.

Methods

_notifyHierarchyStateChanged

protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void

Parameters

_onHierarchyStateChanged

protected _onHierarchyStateChanged(enabled: boolean): void

Parameters

addComponent

addComponent<K extends string & {} | ComponentName>(type: K, data?: K extends ComponentName ? ComponentOptions<K> : any): (K extends ComponentName ? ComponentMap[K] : Component) | null

Create a new component and add it to the entity. Use this to add functionality to the entity like rendering a model, playing sounds and so on.

For the built-in components the type also types the options and the result: entity.addComponent('camera', { fov: 45 }) accepts any settable property of CameraComponent and returns CameraComponent | null. See ComponentOptions for the rule and ComponentMap for extending this to application-defined components.

Parameters

Returns (K extends ComponentName ? ComponentMap[K] : Component) | null: The new Component that was attached to the entity or null if there was an error.

Example

const entity = new Entity();

// Add a light component with default properties
entity.addComponent("light");

// Add a camera component with some specified properties
entity.addComponent("camera", {
    fov: 45,
    clearColor: new Color(1, 0, 0)
});

clone

clone(): Entity

Create a deep copy of the Entity. Duplicate the full Entity hierarchy, with all Components and all descendants. Note, this Entity is not in the hierarchy and must be added manually.

Returns Entity: A new Entity which is a deep copy of the original.

Example

const e = this.entity.clone();

// Add clone as a sibling to the original
this.entity.parent.addChild(e);

destroy

destroy(): void

Destroy the entity and all of its descendants. First, all of the entity's components are disabled and then removed. Then, the entity is removed from the hierarchy. This is then repeated recursively for all descendants of the entity.

The last thing the entity does is fire the destroy event.

Example

const firstChild = this.entity.children[0];
firstChild.destroy(); // destroy child and all of its descendants

findByGuid

findByGuid(guid: string): Entity | null

Find a descendant of this entity with the GUID.

Parameters

Returns Entity | null: The entity with the matching GUID or null if no entity is found.

findComponent

findComponent<K extends string & {} | ComponentName>(type: K): (K extends ComponentName ? ComponentMap[K] : Component) | null

Search the entity and all of its descendants for the first component of specified type.

Parameters

Returns (K extends ComponentName ? ComponentMap[K] : Component) | null: A component of specified type, if the entity or any of its descendants has one. Returns null otherwise.

Example

// Get the first found light component in the hierarchy tree that starts with this entity
const light = entity.findComponent("light");

findComponents

findComponents<K extends string & {} | ComponentName>(type: K): (K extends ComponentName ? ComponentMap[K] : Component)[]

Search the entity and all of its descendants for all components of specified type.

Parameters

Returns (K extends ComponentName ? ComponentMap[K] : Component)[]: All components of specified type in the entity or any of its descendants. Returns empty array if none found.

Example

// Get all light components in the hierarchy tree that starts with this entity
const lights = entity.findComponents("light");

findScript

findScript<T extends Script>(type: Object): T | undefined

Search the entity and all of its descendants for the first script instance of the specified class. The result is typed as an instance of that class, so no cast is needed.

Parameters

Returns T | undefined: A script instance of the specified class, if the entity or any of its descendants has one. Returns undefined otherwise.

Example

// Get the first PlayerController instance in the hierarchy tree that starts with this entity
const controller = entity.findScript(PlayerController); // PlayerController | undefined
findScript(name: string): Script | undefined

Search the entity and all of its descendants for the first script instance with the specified name.

Parameters

Returns Script | undefined: A script instance with the specified name, if the entity or any of its descendants has one. Returns undefined otherwise.

Example

// Get the first found "playerController" instance in the hierarchy tree that starts with this entity
const controller = entity.findScript("playerController");

findScripts

findScripts<T extends Script>(type: Object): T[]

Search the entity and all of its descendants for all script instances of the specified class. The result is typed as an array of that class, so no cast is needed.

Parameters

Returns T[]: All script instances of the specified class in the entity or any of its descendants. Returns an empty array if none are found.

Example

// Get all PlayerController instances in the hierarchy tree that starts with this entity
const controllers = entity.findScripts(PlayerController); // PlayerController[]
findScripts(name: string): Script[]

Search the entity and all of its descendants for all script instances with the specified name.

Parameters

Returns Script[]: All script instances with the specified name in the entity or any of its descendants. Returns an empty array if none are found.

Example

// Get all "playerController" instances in the hierarchy tree that starts with this entity
const controllers = entity.findScripts("playerController");

removeComponent

removeComponent(type: string & {} | ComponentName): void

Remove a component from the Entity.

Parameters

Example

const entity = new Entity();
entity.addComponent("light"); // add new light component

entity.removeComponent("light"); // remove light component

Events

EVENT_DESTROY

static EVENT_DESTROY: string = 'destroy'

Fired after the entity is destroyed.

Example

entity.on('destroy', (e) => {
    console.log(`Entity ${e.name} has been destroyed`);
});

Inherited from GraphNode

EventHandle

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handle.js#L34

Event Handle that is created by EventHandler and can be used for easier event removal and management.

Example

const evt = obj.on('test', (a, b) => {
    console.log(a + b);
});
obj.fire('test');

evt.off(); // easy way to remove this event
obj.fire('test'); // this will not trigger an event

Example

// store an array of event handles
let events = [];

events.push(objA.on('testA', () => {}));
events.push(objB.on('testB', () => {}));

// when needed, remove all events
events.forEach((evt) => {
    evt.off();
});
events = [];

Constructors

constructor

new EventHandle(handler: EventHandler, name: string, callback: HandleEventCallback, scope: any, once?: boolean)

Parameters

Methods

off

off(): void

Remove this event from its handler.

EventHandler

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handler.js#L34

Abstract base class that implements functionality for event handling.

const obj = new EventHandlerSubclass();

// subscribe to an event
obj.on('hello', (str) => {
    console.log('event hello is fired', str);
});

// fire event
obj.fire('hello', 'world');

Methods

fire

fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler

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

Parameters

Returns EventHandler: Self for chaining.

Example

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

hasEvent

hasEvent(name: string): boolean

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

Parameters

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

Example

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

off

off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler

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.

Use this form to remove all listeners matching a name (and optionally callback/scope). To remove a single known subscription, prefer retaining the EventHandle returned by EventHandler#on / EventHandler#once and calling its EventHandle#off: it removes exactly that subscription and is faster (no scan of the callback list).

Parameters

Returns EventHandler: Self for chaining.

Example

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

on

on(name: string, callback: HandleEventCallback, scope?: any): EventHandle

Attach an event handler to an event.

Parameters

Returns EventHandle: An event handle. For later removal, prefer retaining this handle and calling its EventHandle#off over EventHandler#off with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list).

Example

obj.on('test', (a, b) => {
    console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console

Example

// preferred removal: retain the handle and call off() on it
const evt = obj.on('test', (a, b) => {
    console.log(a + b);
});
// some time later
evt.off();

once

once(name: string, callback: HandleEventCallback, scope?: any): EventHandle

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

Parameters

Returns EventHandle: An event handle. For removal before it fires, prefer retaining this handle and calling its EventHandle#off over EventHandler#off with a name/callback: it removes exactly this subscription and is faster (no scan of the callback list).

Example

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

GraphNode

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L122

A GraphNode is a node in the scene graph: a named object with a position, rotation and scale, and a list of children whose transforms are expressed relative to it. Nodes form a tree, and the world transform of any node is its local transform combined with the world transform of its parent; the root has no parent, so its world transform is its local one. The engine brings every world transform up to date each frame before rendering, so a change to a parent reaches all of its descendants.

GraphNode is the base class of Entity, which adds components, so in practice these methods are called on entities. The conventions are the same on both:

Build the hierarchy with addChild, insertChild, removeChild and reparent, and search it with findByName, findByPath, findByTag and find. Setting enabled to false disables the node and its whole subtree.

Example

// Move a node one unit in its own facing direction, then turn it to face a target
node.translateLocal(0, 0, -1);
node.lookAt(target.getPosition());

Example

// Getters return read-only internal storage: clone before modifying
const start = node.getPosition().clone();
start.y += 1;
node.setPosition(start);

Constructors

constructor

new GraphNode(name?: string)

Create a new GraphNode instance.

Parameters

Properties

_children

protected _children: GraphNode[] = []

name

name: string

The non-unique name of a graph node. Defaults to 'Untitled'.

tags

tags: Tags

Interface for tagging graph nodes. Tag based searches can be performed using the findByTag function.

Accessors

children

get children(): readonly GraphNode[]

Gets the children of this graph node. Use addChild, insertChild, removeChild or reparent to change the hierarchy.

enabled

get enabled(): boolean
set enabled(enabled: boolean)

Gets the enabled state of the GraphNode.

forward

get forward(): Readonly<Vec3>

Gets the normalized local space negative Z-axis vector of the graph node in world space.

graphDepth

get graphDepth(): number

Gets the depth of this child within the graph. Note that for performance reasons this is only recalculated when a node is added to a new parent. In other words, it is not recalculated when a node is simply removed from the graph.

parent

get parent(): GraphNode | null

Gets the parent of this graph node.

path

get path(): string

Gets the path of this graph node relative to the root of the hierarchy.

right

get right(): Readonly<Vec3>

Gets the normalized local space X-axis vector of the graph node in world space.

root

get root(): GraphNode

Gets the oldest ancestor graph node from this graph node.

up

get up(): Readonly<Vec3>

Gets the normalized local space Y-axis vector of the graph node in world space.

Methods

_notifyHierarchyStateChanged

protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void

Parameters

_onHierarchyStateChanged

protected _onHierarchyStateChanged(enabled: boolean): void

Called when the enabled flag of the entity or one of its parents changes.

Parameters

addChild

addChild(node: GraphNode): void

Add a new child to the child list and update the parent value of the child node. If the node already had a parent, it is removed from its child list.

The child keeps its existing local transform, which is now interpreted relative to the new parent, so a node placed in world space before being added will appear to move. Set the transform after adding, or re-apply the world placement with GraphNode#setPosition.

Parameters

Example

const e = new Entity(app);
this.entity.addChild(e);

clone

clone(): GraphNode

Clone a graph node.

Returns GraphNode: A clone of the specified graph node.

destroy

destroy(): void

Destroy the graph node and all of its descendants. First, the graph node is removed from the hierarchy. This is then repeated recursively for all descendants of the graph node.

The last thing the graph node does is fire the destroy event.

Example

const firstChild = graphNode.children[0];
firstChild.destroy(); // destroy child and all of its descendants

find

find(attr: string | FindNodeCallback, value?: any): GraphNode[]

Search the graph node and all of its descendants for the nodes that satisfy some search criteria.

Parameters

Returns GraphNode[]: The array of graph nodes that match the search criteria.

Example

// Finds all nodes that have a model component and have 'door' in their lower-cased name
const doors = house.find((node) => {
    return node.model && node.name.toLowerCase().indexOf('door') !== -1;
});

Example

// Finds all nodes that have the name property set to 'Test'
const entities = parent.find('name', 'Test');

findByName

findByName(name: string): GraphNode | null

Get the first node found in the graph with the name. The search is depth first.

Parameters

Returns GraphNode | null: The first node to be found matching the supplied name. Returns null if no node is found.

findByPath

findByPath(path: string | string[]): GraphNode | null

Get the first node found in the graph by its full path in the graph. The full path has this form 'parent/child/sub-child'. The search is depth first.

Parameters

Returns GraphNode | null: The first node to be found matching the supplied path. Returns null if no node is found.

Example

// String form
const grandchild = this.entity.findByPath('child/grandchild');

Example

// Array form
const grandchild = this.entity.findByPath(['child', 'grandchild']);

findByTag

findByTag(...query: any[]): GraphNode[]

Return all graph nodes that satisfy the search query. Query can be simply a string, or comma separated strings, to have inclusive results of graph nodes that match at least one query. A query that consists of an array of tags can be used to match graph nodes that have each tag of the array.

Parameters

Returns GraphNode[]: A list of all graph nodes that match the query.

Example

// Return all graph nodes tagged with `animal`
const animals = node.findByTag("animal");

Example

// Return all graph nodes tagged with `bird` OR `mammal`
const birdsAndMammals = node.findByTag("bird", "mammal");

Example

// Return all graph nodes tagged with `carnivore` AND `mammal`
const meatEatingMammals = node.findByTag(["carnivore", "mammal"]);

Example

// Return all graph nodes tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`)
const meatEatingMammalsAndReptiles = node.findByTag(["carnivore", "mammal"], ["carnivore", "reptile"]);

findOne

findOne(attr: string | FindNodeCallback, value?: any): GraphNode | null

Search the graph node and all of its descendants for the first node that satisfies some search criteria.

Parameters

Returns GraphNode | null: A graph node that matches the search criteria. Returns null if no node is found.

Example

// Find the first node that is called 'head' and has a model component
const head = player.findOne((node) => {
    return node.model && node.name === 'head';
});

Example

// Finds the first node that has the name property set to 'Test'
const node = parent.findOne('name', 'Test');

forEach

forEach(callback: ForEachNodeCallback, thisArg?: any): void

Executes a provided function once on this graph node and all of its descendants.

Parameters

Example

// Log the path and name of each node in descendant tree starting with "parent"
parent.forEach((node) => {
    console.log(node.path + "/" + node.name);
});

getEulerAngles

getEulerAngles(): Readonly<Vec3>

Get the world space rotation for the specified GraphNode in Euler angles. The angles are in degrees and in XYZ order.

Important: The value returned by this function should be considered read-only. In order to set the world space rotation of the graph node, use setEulerAngles.

Returns Readonly<Vec3>: The world space rotation of the graph node in Euler angle form.

Example

const angles = this.entity.getEulerAngles();
angles.y = 180; // rotate the entity around Y by 180 degrees
this.entity.setEulerAngles(angles);

getLocalEulerAngles

getLocalEulerAngles(): Readonly<Vec3>

Get the local space rotation for the specified GraphNode in Euler angles. The angles are in degrees and in XYZ order.

Important: The value returned by this function should be considered read-only. In order to set the local space rotation of the graph node, use setLocalEulerAngles.

Returns Readonly<Vec3>: The local space rotation of the graph node as Euler angles in XYZ order.

Example

const angles = this.entity.getLocalEulerAngles();
angles.y = 180;
this.entity.setLocalEulerAngles(angles);

getLocalPosition

getLocalPosition(): Readonly<Vec3>

Get the position in local space for the specified GraphNode. The position is returned as a Vec3. The returned vector should be considered read-only. To update the local position, use setLocalPosition.

Returns Readonly<Vec3>: The local space position of the graph node.

Example

const position = this.entity.getLocalPosition().clone();
position.x += 1; // move the entity 1 unit along x.
this.entity.setLocalPosition(position);

getLocalRotation

getLocalRotation(): Readonly<Quat>

Get the rotation in local space for the specified GraphNode. The rotation is returned as a Quat. The returned quaternion should be considered read-only. To update the local rotation, use setLocalRotation.

Returns Readonly<Quat>: The local space rotation of the graph node as a quaternion.

Example

const rotation = this.entity.getLocalRotation();

getLocalScale

getLocalScale(): Readonly<Vec3>

Get the scale in local space for the specified GraphNode. The scale is returned as a Vec3. The returned vector should be considered read-only. To update the local scale, use setLocalScale.

Returns Readonly<Vec3>: The local space scale of the graph node.

Example

const scale = this.entity.getLocalScale().clone();
scale.x = 100;
this.entity.setLocalScale(scale);

getLocalTransform

getLocalTransform(): Readonly<Mat4>

Get the local transform matrix for this graph node. This matrix is the transform relative to the node's parent's world transformation matrix.

Returns Readonly<Mat4>: The node's local transformation matrix.

Example

const transform = this.entity.getLocalTransform();

getPosition

getPosition(): Readonly<Vec3>

Get the world space position for the specified GraphNode. The position is returned as a Vec3. The value returned by this function should be considered read-only. In order to set the world space position of the graph node, use setPosition.

Returns Readonly<Vec3>: The world space position of the graph node.

Example

const position = this.entity.getPosition().clone();
position.x = 10;
this.entity.setPosition(position);

getRotation

getRotation(): Readonly<Quat>

Get the world space rotation for the specified GraphNode. The rotation is returned as a Quat. The value returned by this function should be considered read-only. In order to set the world space rotation of the graph node, use setRotation.

Returns Readonly<Quat>: The world space rotation of the graph node as a quaternion.

Example

const rotation = this.entity.getRotation();

getWorldTransform

getWorldTransform(): Readonly<Mat4>

Get the world transformation matrix for this graph node.

Returns Readonly<Mat4>: The node's world transformation matrix.

Example

const transform = this.entity.getWorldTransform();

insertChild

insertChild(node: GraphNode, index: number): void

Insert a new child to the child list at the specified index and update the parent value of the child node. If the node already had a parent, it is removed from its child list.

Parameters

Example

const e = new Entity(app);
this.entity.insertChild(e, 1);

isAncestorOf

isAncestorOf(node: GraphNode): boolean

Check if node is ancestor for another node.

Parameters

Returns boolean: If node is ancestor for another node.

Example

if (body.isAncestorOf(foot)) {
    // foot is within body's hierarchy
}

isDescendantOf

isDescendantOf(node: GraphNode): boolean

Check if node is descendant of another node.

Parameters

Returns boolean: If node is descendant of another node.

Example

if (roof.isDescendantOf(house)) {
    // roof is descendant of house entity
}

lookAt

lookAt(x: number, y: number, z: number, ux?: number, uy?: number, uz?: number): void

Reorients the graph node so that the negative z-axis points towards the target.

The up vector must not be parallel to the direction from the node to the target. When it is — looking straight up or down with the default up vector, or at the node's own position — the basis is degenerate and the node's rotation is reset to identity, discarding whatever rotation it already had, with nothing reported. Pass a different up vector in those cases.

Parameters

Returns void

Example

// Look at the world space origin, using the (default) positive y-axis for up
this.entity.lookAt(0, 0, 0);

Example

// Look at world space coordinate [10, 10, 10], using the negative world y-axis for up
this.entity.lookAt(10, 10, 10, 0, -1, 0);
lookAt(target: Vec3, up?: Vec3): void

Reorients the graph node so that the negative z-axis points towards the target.

Parameters

Returns void

Example

// Look at another entity, using the (default) positive y-axis for up
const target = otherEntity.getPosition();
this.entity.lookAt(target);

Example

// Look at another entity, using the negative world y-axis for up
const target = otherEntity.getPosition();
this.entity.lookAt(target, Vec3.DOWN);

remove

remove(): void

Remove graph node from current parent.

removeChild

removeChild(child: GraphNode): void

Remove the node from the child list and update the parent value of the child.

This detaches the node without disabling it: the removed subtree still reports enabled === true, and its lights, cameras, scripts and sounds keep running. Set enabled = false to deactivate a node, or destroy the entity to remove it outright.

Parameters

Example

const child = this.entity.children[0];
this.entity.removeChild(child);

reparent

reparent(parent: GraphNode, index?: number): void

Remove graph node from current parent and add as child to new parent.

Parameters

rotate

rotate(x: number, y: number, z: number): void

Rotates the graph node in world space by the specified Euler angles. Eulers are specified in degrees in XYZ order.

Parameters

Returns void

Example

this.entity.rotate(0, 90, 0);
rotate(rotation: Vec3): void

Rotates the graph node in world space by the specified Euler angles. Eulers are specified in degrees in XYZ order.

Parameters

Returns void

Example

const rotation = new Vec3(0, 90, 0);
this.entity.rotate(rotation);

rotateLocal

rotateLocal(x: number, y: number, z: number): void

Rotates the graph node in local space by the specified Euler angles. Eulers are specified in degrees in XYZ order.

Parameters

Returns void

Example

this.entity.rotateLocal(0, 90, 0);
rotateLocal(rotation: Vec3): void

Rotates the graph node in local space by the specified Euler angles. Eulers are specified in degrees in XYZ order.

Parameters

Returns void

Example

const rotation = new Vec3(0, 90, 0);
this.entity.rotateLocal(rotation);

setEulerAngles

setEulerAngles(x: number, y: number, z: number): void

Sets the world space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.

Parameters

Returns void

Example

this.entity.setEulerAngles(0, 90, 0);
setEulerAngles(angles: Vec3): void

Sets the world space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.

Parameters

Returns void

Example

const angles = new Vec3(0, 90, 0);
this.entity.setEulerAngles(angles);

setLocalEulerAngles

setLocalEulerAngles(x: number, y: number, z: number): void

Sets the local space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.

Parameters

Returns void

Example

// Set rotation of 90 degrees around y-axis via 3 numbers
this.entity.setLocalEulerAngles(0, 90, 0);
setLocalEulerAngles(angles: Vec3): void

Sets the local space rotation of the specified graph node using Euler angles. Eulers are interpreted in XYZ order.

Parameters

Returns void

Example

// Set rotation of 90 degrees around y-axis via a vector
const angles = new Vec3(0, 90, 0);
this.entity.setLocalEulerAngles(angles);

setLocalPosition

setLocalPosition(x: number, y: number, z: number): void

Sets the local space position of the specified graph node.

Parameters

Returns void

Example

this.entity.setLocalPosition(0, 10, 0);
setLocalPosition(position: Vec3): void

Sets the local space position of the specified graph node.

Parameters

Returns void

Example

const pos = new Vec3(0, 10, 0);
this.entity.setLocalPosition(pos);

setLocalRotation

setLocalRotation(x: number, y: number, z: number, w: number): void

Sets the local space rotation of the specified graph node.

Parameters

Returns void

Example

this.entity.setLocalRotation(0, 0, 0, 1);
setLocalRotation(rotation: Quat): void

Sets the local space rotation of the specified graph node.

Parameters

Returns void

Example

const q = new Quat();
this.entity.setLocalRotation(q);

setLocalScale

setLocalScale(x: number, y: number, z: number): void

Sets the local space scale factor of the specified graph node.

Parameters

Returns void

Example

this.entity.setLocalScale(10, 10, 10);
setLocalScale(scale: Vec3): void

Sets the local space scale factor of the specified graph node.

Parameters

Returns void

Example

const scale = new Vec3(10, 10, 10);
this.entity.setLocalScale(scale);

setPosition

setPosition(x: number, y: number, z: number): void

Sets the world space position of the specified graph node.

Parameters

Returns void

Example

this.entity.setPosition(0, 10, 0);
setPosition(position: Vec3): void

Sets the world space position of the specified graph node.

Parameters

Returns void

Example

const position = new Vec3(0, 10, 0);
this.entity.setPosition(position);

setPositionAndRotation

setPositionAndRotation(position: Vec3, rotation: Quat): void

Sets the world space position and rotation of the specified graph node. This is faster than setting the position and rotation independently.

Parameters

Example

const position = new Vec3(0, 10, 0);
const rotation = new Quat().setFromEulerAngles(0, 90, 0);
this.entity.setPositionAndRotation(position, rotation);

setRotation

setRotation(x: number, y: number, z: number, w: number): void

Sets the world space rotation of the specified graph node.

Parameters

Returns void

Example

this.entity.setRotation(0, 0, 0, 1);
setRotation(rotation: Quat): void

Sets the world space rotation of the specified graph node.

Parameters

Returns void

Example

const rotation = new Quat();
this.entity.setRotation(rotation);

translate

translate(x: number, y: number, z: number): void

Translates the graph node in world space by the specified translation vector.

Parameters

Returns void

Example

this.entity.translate(10, 0, 0);
translate(translation: Vec3): void

Translates the graph node in world space by the specified translation vector.

Parameters

Returns void

Example

const translation = new Vec3(10, 0, 0);
this.entity.translate(translation);

translateLocal

translateLocal(x: number, y: number, z: number): void

Translates the graph node in local space by the specified translation vector.

Parameters

Returns void

Example

this.entity.translateLocal(10, 0, 0);
translateLocal(translation: Vec3): void

Translates the graph node in local space by the specified translation vector.

Parameters

Returns void

Example

const t = new Vec3(10, 0, 0);
this.entity.translateLocal(t);

Inherited from EventHandler

Http

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/net/http.js#L28

Used to send and receive HTTP requests.

Methods

del

del(url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest

Perform an HTTP DELETE request to the given url with additional options such as headers, retries, credentials, etc.

Parameters

Returns XMLHttpRequest: The request object.

Example

http.del("http://example.com/", {
    "retry": true,
    "maxRetries": 5
}, (err, response) => {
    console.log(response);
});

get

get(url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest

Perform an HTTP GET request to the given url with additional options such as headers, retries, credentials, etc.

Parameters

Returns XMLHttpRequest: The request object.

Example

http.get("http://example.com/", {
    "retry": true,
    "maxRetries": 5
}, (err, response) => {
    console.log(response);
});

post

post(url: string, data: any, options: object, callback: HttpResponseCallback): XMLHttpRequest

Perform an HTTP POST request to the given url with additional options such as headers, retries, credentials, etc.

Parameters

Returns XMLHttpRequest: The request object.

Example

http.post("http://example.com/", {
    "name": "Alex"
}, {
    "retry": true,
    "maxRetries": 5
}, (err, response) => {
    console.log(response);
});

put

put(url: string, data: any, options: object, callback: HttpResponseCallback): XMLHttpRequest

Perform an HTTP PUT request to the given url with additional options such as headers, retries, credentials, etc.

Parameters

Returns XMLHttpRequest: The request object.

Example

http.put("http://example.com/", {
    "name": "Alex"
}, {
    "retry": true,
    "maxRetries": 5
}, (err, response) => {
    console.log(response);
});

request

request(method: string, url: string, options: object, callback: HttpResponseCallback): XMLHttpRequest

Make a general purpose HTTP request with additional options such as headers, retries, credentials, etc.

Parameters

Returns XMLHttpRequest: The request object.

Example

http.request("get", "http://example.com/", {
    "retry": true,
    "maxRetries": 5
}, (err, response) => {
    console.log(response);
});

I18n

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/i18n/i18n.js#L18

Handles localization. Responsible for loading localization assets and returning translations for a certain key. Can also handle plural forms. To override its default behavior define a different implementation for getText and getPluralText.

Constructors

constructor

new I18n(app: AppBase)

Create a new I18n instance.

Parameters

Accessors

assets

get assets(): number[] | Asset<string>[]
set assets(value: number[] | Asset<string>[])

Gets the array of asset ids that contain localization data in the expected format.

locale

get locale(): string
set locale(value: string)

Gets the current locale.

Methods

addData

addData(data: any): void

Adds localization data. If the locale and key for a translation already exists it will be overwritten.

Parameters

Example

this.app.i18n.addData({
    header: {
        version: 1
    },
    data: [{
        info: {
            locale: 'en-US'
        },
        messages: {
            "key": "translation",
            // The number of plural forms depends on the locale. See the manual for more information.
            "plural_key": ["one item", "more than one items"]
        }
    }, {
        info: {
            locale: 'fr-FR'
        },
        messages: {
            // ...
        }
    }]
});

destroy

destroy(): void

Frees up memory.

findAvailableLocale

findAvailableLocale(desiredLocale: string): string

Returns the first available locale based on the desired locale specified. First tries to find the desired locale in the loaded translations and then tries to find an alternative locale based on the language.

Parameters

Returns string: The locale found or if no locale is available returns the default en-US locale.

Example

const locale = this.app.i18n.getText('en-US');

getPluralText

getPluralText(key: string, n: number, locale?: string): string

Returns the pluralized translation for the specified key, number n and locale. If the locale is not specified it will use the current locale.

Parameters

Returns string: The translated text. If no translations are found at all for the locale then it will return the en-US translation. If no translation exists for that key then it will return the localization key.

Example

// manually replace {number} in the resulting translation with our number
const localized = this.app.i18n.getPluralText('{number} apples', number).replace("{number}", number);

getText

getText(key: string, locale?: string): string

Returns the translation for the specified key and locale. If the locale is not specified it will use the current locale.

Parameters

Returns string: The translated text. If no translations are found at all for the locale then it will return the en-US translation. If no translation exists for that key then it will return the localization key.

Example

const localized = this.app.i18n.getText('localization-key');
const localizedFrench = this.app.i18n.getText('localization-key', 'fr-FR');

removeData

removeData(data: any): void

Removes localization data.

Parameters

Events

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when the locale is changed.

Example

app.i18n.on('change', (newLocale, oldLocale) => {
   console.log(`Locale changed from ${oldLocale} to ${newLocale}`);
});

Inherited from EventHandler

RefCountedObject

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/ref-counted-object.js#L6

Base class that implements reference counting for objects.

Accessors

refCount

get refCount(): number

Gets the current reference count.

Methods

decRefCount

decRefCount(): void

Decrements the reference counter.

incRefCount

incRefCount(): void

Increments the reference counter.

Tags

Class · extends EventHandler · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/tags.js#L14

Tags is a powerful tag management system for categorizing and filtering objects in PlayCanvas applications. It provides an efficient way to attach string identifiers to objects and query them using logical operations.

Tags are automatically available on Assets and Entitys (see Asset#tags and GraphNode#tags). You can search for specific assets via AssetRegistry#findByTag and specific entities via GraphNode#findByTag.

Constructors

constructor

new Tags(parent?: any)

Create a new Tags instance.

Parameters

Accessors

size

get size(): number

Number of tags in set.

Methods

add

add(...args: any[]): boolean

Add a tag, duplicates are ignored. Can be array or comma separated arguments for multiple tags.

Parameters

Returns boolean: True if any tag were added.

Example

tags.add('level-1');

Example

tags.add('ui', 'settings');

Example

tags.add(['level-2', 'mob']);

clear

clear(): void

Remove all tags.

Example

tags.clear();

has

has(...query: any[]): boolean

Check if tags satisfy filters. Filters can be provided by simple name of tag, as well as by array of tags. When an array is provided it will check if tags contain each tag within the array. If any of comma separated argument is satisfied, then it will return true. Any number of combinations are valid, and order is irrelevant.

Parameters

Returns boolean: True if filters are satisfied.

Example

tags.has('player'); // player

Example

tags.has('mob', 'player'); // player OR mob

Example

tags.has(['level-1', 'mob']); // monster AND level-1

Example

tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels)

list

list(): string[]

Returns immutable array of tags.

Returns string[]: Copy of tags array.

remove

remove(...args: any[]): boolean

Remove tag.

Parameters

Returns boolean: True if any tag were removed.

Example

tags.remove('level-1');

Example

tags.remove('ui', 'settings');

Example

tags.remove(['level-2', 'mob']);

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired for each individual tag that is added.

Example

tags.on('add', (tag, parent) => {
   console.log(`${tag} added to ${parent.name}`);
});

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when tags have been added or removed. It will fire once on bulk changes, while add and remove will fire on each tag operation.

Example

tags.on('change', (parent) => {
   console.log(`Tags changed on ${parent.name}`);
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired for each individual tag that is removed.

Example

tags.on('remove', (tag, parent) => {
  console.log(`${tag} removed from ${parent.name}`);
});

Inherited from EventHandler

Template

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/template.js#L13

Create a Template resource from raw database data.

Constructors

constructor

new Template(app: AppBase, data: any)

Create a new Template instance.

Parameters

Methods

instantiate

instantiate(): Entity

Create an instance of this template.

Returns Entity: The root entity of the created instance.

WasmModule

Class · category: Framework

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L149

A pure static utility class which supports immediate and lazy loading of WebAssembly modules. Note that you can load WebAssembly modules even before instantiating your AppBase instance.

This class is generally only needed if you are developing against the Engine directly. Editor projects automatically load WebAssembly modules included in the project's assets.

Do not use this class to load the Basis WebAssembly module. Instead, please refer to basisInitialize.

Example

// Load the Ammo.js physics engine
WasmModule.setConfig('Ammo', {
    glueUrl: `ammo.wasm.js`,
    wasmUrl: `ammo.wasm.wasm`,
    fallbackUrl: `ammo.js`
});
await new Promise((resolve) => {
    WasmModule.getInstance('Ammo', () => resolve());
});

Methods

getConfig

static getConfig(moduleName: string): any

Get a wasm module's configuration.

Parameters

Returns any: The previously set configuration.

getInstance

static getInstance(moduleName: string, callback: ModuleInstanceCallback): void

Get a wasm module instance. The instance will be created if necessary and returned in the second parameter to callback.

Parameters

setConfig

static setConfig(moduleName: string, config?: object): void

Set a wasm module's configuration.

Parameters

Gizmo

Class · extends EventHandler · category: Gizmo

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/gizmo.js#L56

The base class for all gizmos.

A gizmo is an interactive widget drawn over the scene in its own Layer; createLayer makes such a layer and adds it to the scene and the camera. Construct a gizmo for a CameraComponent, then attach the GraphNodes it should act on, which are then listed in nodes; detach releases them. A gizmo updates and renders itself from the application's update and prerender hooks, so it needs no per-frame call and is torn down with destroy. size scales the widget, which otherwise keeps a constant apparent size as the camera moves; coordSpace selects 'world' or 'local' axes; enabled hides it without detaching; and mouseButtons chooses which buttons interact. Pointer interaction is reported through the pointer:down, pointer:move and pointer:up events, node changes through nodes:attach and nodes:detach, and the resulting transforms through position:update, rotation:update and scale:update. TransformGizmo builds the translate, rotate and scale gizmos on this base.

Constructors

constructor

new Gizmo(camera: CameraComponent, layer: Layer, name?: string)

Creates a new Gizmo object.

Parameters

Example

const gizmo = new Gizmo(camera, layer);

Properties

_app

protected _app: AppBase

Internal reference to the app containing the gizmo.

_camera

protected _camera: CameraComponent

Internal reference to camera component to view the gizmo.

_coordSpace

protected _coordSpace: GizmoSpace = 'world'

Internal version of coordinate space. Defaults to 'world'.

_device

protected _device: GraphicsDevice

Internal reference to the graphics device of the app.

_handles

protected _handles: EventHandle[] = []

Internal list of app event handles for the gizmo.

_layer

protected _layer: Layer

Internal reference to layer to render the gizmo..

_mouseButtons

protected _mouseButtons: [boolean, boolean, boolean]

Internal array of mouse buttons that can interact with the gizmo.

_renderUpdate

protected _renderUpdate: boolean = false

Internal flag to track if a render update is required.

_scale

protected _scale: number = 1

Internal version of the gizmo scale. Defaults to 1.

intersectShapes

intersectShapes: Shape[] = []

The intersection shapes for the gizmo.

nodes

nodes: GraphNode[] = []

The graph nodes attached to the gizmo.

preventDefault

preventDefault: boolean = true

Flag to indicate whether to call preventDefault on pointer events.

root

root: Entity

The root gizmo entity.

Accessors

camera

get camera(): CameraComponent
set camera(camera: CameraComponent)

Gets the camera component to view the gizmo.

cameraDir

protected get cameraDir(): Vec3

coordSpace

get coordSpace(): GizmoSpace
set coordSpace(value: GizmoSpace)

Gets the gizmo coordinate space.

enabled

get enabled(): boolean
set enabled(state: boolean)

Gets the gizmo enabled state.

facingDir

protected get facingDir(): Vec3

layer

get layer(): Layer
set layer(layer: Layer)

Gets the gizmo render layer.

mouseButtons

get mouseButtons(): [boolean, boolean, boolean]

Array of mouse buttons that can interact with the gizmo. The button indices are defined as:

The full list of button indices can be found here: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

size

get size(): number
set size(value: number)

Gets the gizmo size.

Methods

_updatePosition

protected _updatePosition(): void

_updateRotation

protected _updateRotation(): void

_updateScale

protected _updateScale(): void

attach

attach(nodes?: GraphNode | GraphNode[]): void

Attach an array of graph nodes to the gizmo.

Parameters

Example

const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);

destroy

destroy(): void

Detaches all graph nodes and destroys the gizmo instance.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.destroy();

detach

detach(): void

Detaches all graph nodes from the gizmo.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.detach();

prerender

prerender(): void

Pre-render method. This is called before the gizmo is rendered.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.prerender();

update

update(): void

Updates the gizmo position, rotation, and scale.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.attach([boxA, boxB]);
gizmo.update();

createLayer

static createLayer(app: AppBase, layerName?: string, layerIndex?: number): Layer

Creates a new gizmo layer and adds it to the scene.

Parameters

Returns Layer: The new layer.

Events

EVENT_NODESATTACH

static EVENT_NODESATTACH: string = 'nodes:attach'

Fired when graph nodes are attached.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('nodes:attach', () => {
    console.log('Graph nodes attached');
});

EVENT_NODESDETACH

static EVENT_NODESDETACH: string = 'nodes:detach'

Fired when graph nodes are detached.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('nodes:detach', () => {
    console.log('Graph nodes detached');
});

EVENT_POINTERDOWN

static EVENT_POINTERDOWN: string = 'pointer:down'

Fired when the pointer is down on the gizmo.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:down', (x, y, meshInstance) => {
    console.log(`Pointer was down on ${meshInstance.node.name} at ${x}, ${y}`);
});

EVENT_POINTERMOVE

static EVENT_POINTERMOVE: string = 'pointer:move'

Fired when the pointer is moving over the gizmo.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:move', (x, y, meshInstance) => {
    console.log(`Pointer was moving on ${meshInstance.node.name} at ${x}, ${y}`);
});

EVENT_POINTERUP

static EVENT_POINTERUP: string = 'pointer:up'

Fired when the pointer is up off the gizmo.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('pointer:up', (x, y, meshInstance) => {
    console.log(`Pointer was up on ${meshInstance.node.name} at ${x}, ${y}`);
})

EVENT_POSITIONUPDATE

static EVENT_POSITIONUPDATE: string = 'position:update'

Fired when the gizmo's position is updated.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('position:update', (position) => {
    console.log(`The gizmo's position was updated to ${position}`);
})

EVENT_RENDERUPDATE

static EVENT_RENDERUPDATE: string = 'render:update'

Fired when the gizmo render has updated.

Example

const gizmo = new TransformGizmo(camera, layer);
gizmo.on('render:update', () => {
    console.log('Gizmo render has been updated');
});

EVENT_ROTATIONUPDATE

static EVENT_ROTATIONUPDATE: string = 'rotation:update'

Fired when the gizmo's rotation is updated.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('rotation:update', (rotation) => {
    console.log(`The gizmo's rotation was updated to ${rotation}`);
});

EVENT_SCALEUPDATE

static EVENT_SCALEUPDATE: string = 'scale:update'

Fired when the gizmo's scale is updated.

Example

const gizmo = new Gizmo(camera, layer);
gizmo.on('scale:update', (scale) => {
    console.log(`The gizmo's scale was updated to ${scale}`);
});

Inherited from EventHandler

RotateGizmo

Class · extends TransformGizmo · category: Gizmo

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/rotate-gizmo.js#L68

The RotateGizmo provides interactive 3D manipulation handles for rotating/reorienting Entitys in a Scene. It creates a visual widget with a draggable ring for each axis of rotation, plus a fourth ring for rotation in the camera's view plane, allowing precise control over object orientation through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.

Note that the gizmo can be driven by both mouse+keyboard and touch input.

// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);

// Create a rotate gizmo
const gizmo = new RotateGizmo(cameraComponent, gizmoLayer);

// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
    type: 'box'
});
app.root.addChild(entity);

// Attach the gizmo to the entity
gizmo.attach([entity]);

Relevant Engine API examples:

Constructors

constructor

new RotateGizmo(camera: CameraComponent, layer: Layer)

Creates a new RotateGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.

Parameters

Example

const gizmo = new RotateGizmo(camera, layer);

Properties

_shapes

protected _shapes: { f: ArcShape; x: ArcShape; xyz: SphereShape; y: ArcShape; z: ArcShape }

Internal object containing the gizmo shapes to render.

Properties

rotationMode

rotationMode: "absolute" | "orbit" = 'absolute'

The rotation mode of the gizmo. This can be either:

snapIncrement

snapIncrement: number = 5

Accessors

angleGuideThickness

get angleGuideThickness(): number
set angleGuideThickness(value: number)

Gets the angle guide line thickness.

centerRadius

get centerRadius(): number
set centerRadius(value: number)

Gets the center radius.

faceRingRadius

get faceRingRadius(): number
set faceRingRadius(value: number)

Gets the face ring radius.

faceTubeRadius

get faceTubeRadius(): number
set faceTubeRadius(value: number)

Gets the face tube radius.

ringTolerance

get ringTolerance(): number
set ringTolerance(value: number)

Gets the ring tolerance.

xyzRingRadius

get xyzRingRadius(): number
set xyzRingRadius(value: number)

Gets the XYZ ring radius.

xyzTubeRadius

get xyzTubeRadius(): number
set xyzTubeRadius(value: number)

Gets the XYZ tube radius.

Methods

_calculateArcAngle

protected _calculateArcAngle(point: Vec3, x: number, y: number): number

Parameters

Returns number: The angle.

_drawGuideLines

_drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void

Parameters

_screenToPoint

protected _screenToPoint(x: number, y: number): Vec3

Parameters

Returns Vec3: The point (space is TransformGizmo#coordSpace).

destroy

destroy(): void

prerender

prerender(): void

Inherited from TransformGizmo

ScaleGizmo

Class · extends TransformGizmo · category: Gizmo

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/scale-gizmo.js#L60

The ScaleGizmo provides interactive 3D manipulation handles for scaling/resizing Entitys in a Scene. It creates a visual widget with box-tipped lines along the X, Y and Z axes, planes at their intersections, and a center box, allowing precise control over object scaling through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.

Note that the gizmo can be driven by both mouse+keyboard and touch input.

// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);

// Create a scale gizmo
const gizmo = new ScaleGizmo(cameraComponent, gizmoLayer);

// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
    type: 'box'
});
app.root.addChild(entity);

// Attach the gizmo to the entity
gizmo.attach([entity]);

Relevant Engine API examples:

Constructors

constructor

new ScaleGizmo(camera: CameraComponent, layer: Layer)

Creates a new ScaleGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.

Parameters

Example

const gizmo = new ScaleGizmo(camera, layer);

Properties

_coordSpace

protected _coordSpace: GizmoSpace = 'local'

_shapes

protected _shapes: { x: BoxLineShape; xy: PlaneShape; xyz: BoxShape; xz: PlaneShape; y: BoxLineShape; yz: PlaneShape; z: BoxLineShape }

Internal object containing the gizmo shapes to render.

Properties

_uniform

protected _uniform: boolean = false

Internal state if transform should use uniform scaling.

flipPlanes

flipPlanes: boolean = true

Flips the planes to face the camera.

lowerBoundScale

lowerBoundScale: Vec3

The lower bound for scaling.

snapIncrement

snapIncrement: number = 1

Accessors

axisBoxSize

get axisBoxSize(): number
set axisBoxSize(value: number)

Gets the axis box size.

axisCenterSize

get axisCenterSize(): number
set axisCenterSize(value: number)

Gets the axis center size.

axisGap

get axisGap(): number
set axisGap(value: number)

Gets the axis gap.

axisLineLength

get axisLineLength(): number
set axisLineLength(value: number)

Gets the axis line length.

axisLineThickness

get axisLineThickness(): number
set axisLineThickness(value: number)

Gets the axis line thickness.

axisLineTolerance

get axisLineTolerance(): number
set axisLineTolerance(value: number)

Gets the axis line tolerance.

axisPlaneGap

get axisPlaneGap(): number
set axisPlaneGap(value: number)

Gets the plane gap.

axisPlaneSize

get axisPlaneSize(): number
set axisPlaneSize(value: number)

Gets the plane size.

coordSpace

get coordSpace(): GizmoSpace
set coordSpace(value: GizmoSpace)

Sets the gizmo coordinate space. Defaults to 'world'

uniform

get uniform(): boolean
set uniform(value: boolean)

Gets the uniform scaling state for planes.

Methods

_screenToPoint

protected _screenToPoint(x: number, y: number): Vec3

Parameters

Returns Vec3: The point (space is TransformGizmo#coordSpace).

prerender

prerender(): void

Inherited from TransformGizmo

TransformGizmo

Class · extends Gizmo · category: Gizmo

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/transform-gizmo.js#L61

The base class for all transform gizmos.

It adds to Gizmo everything the TranslateGizmo, RotateGizmo and ScaleGizmo share: colored X, Y and Z handles with plane and center shapes, any of which enableShape can turn off; a drag interaction that fires transform:start, transform:move with the position or angle delta so far, and transform:end; snap with snapIncrement to quantize the change; dragMode to show, hide or keep only the selected shape while dragging; and a color theme adjusted through setTheme, xAxisColor, yAxisColor, zAxisColor and colorAlpha. The subclasses decide what a drag does to the attached nodes.

Constructors

constructor

new TransformGizmo(camera: CameraComponent, layer: Layer, name?: string)

Creates a new TransformGizmo object.

Parameters

Example

const gizmo = new TransformGizmo(camera, layer);

Properties

_rootStartPos

protected _rootStartPos: Vec3

Internal gizmo starting rotation in world space.

_rootStartRot

protected _rootStartRot: Quat

Internal gizmo starting rotation in world space.

_selectedAxis

protected _selectedAxis: "" | GizmoAxis = ''

Internal currently selected axis.

_selectedIsPlane

protected _selectedIsPlane: boolean = false

Internal state of if currently selected shape is a plane.

_selectionStartPoint

protected _selectionStartPoint: Vec3

Internal selection starting coordinates in world space.

_shapes

protected _shapes: { f?: Shape; x?: Shape; xy?: Shape; xyz?: Shape; xz?: Shape; y?: Shape; yz?: Shape; z?: Shape } = {}

Internal object containing the gizmo shapes to render.

Properties

_theme

protected _theme: GizmoTheme

Internal theme.

dragMode

dragMode: GizmoDragMode = 'selected'

Whether to hide the shapes when dragging. Defaults to 'selected'.

snap

snap: boolean = false

Whether snapping is enabled. Defaults to false.

snapIncrement

snapIncrement: number = 1

Snapping increment. Defaults to 1.

Accessors

_dragging

protected get _dragging(): boolean

theme

get theme(): GizmoTheme

Gets the current theme for the gizmo.

Methods

_createPlane

protected _createPlane(axis: string, isFacing: boolean, isLine: boolean): Plane

Parameters

Returns Plane: - The plane.

_createRay

protected _createRay(mouseWPos: Vec3): Ray

Parameters

Returns Ray: - The ray.

_createTransform

protected _createTransform(): void

_dirFromAxis

protected _dirFromAxis(axis: string, dir: Vec3): Vec3

Parameters

Returns Vec3: - The direction

_drawGuideLines

protected _drawGuideLines(pos: Vec3, rot: Quat, activeAxis: "" | GizmoAxis, activeIsPlane: boolean): void

Parameters

_drawSpanLine

protected _drawSpanLine(pos: Vec3, rot: Quat, axis: "x" | "y" | "z"): void

Parameters

_projectToAxis

protected _projectToAxis(point: Vec3, axis: string): void

Parameters

_screenToPoint

protected _screenToPoint(x: number, y: number, isFacing?: boolean, isLine?: boolean): Vec3

Parameters

Returns Vec3: The point (space is Gizmo#coordSpace).

destroy

destroy(): void

enableShape

enableShape(shapeAxis: "face" | GizmoAxis, enabled: boolean): void

Set the shape to be enabled or disabled.

Parameters

isShapeEnabled

isShapeEnabled(shapeAxis: "face" | GizmoAxis): boolean

Get the enabled state of the shape.

Parameters

Returns boolean: - Then enabled state of the shape

prerender

prerender(): void

setTheme

setTheme(partial: object): void

Sets the theme or partial theme for the gizmo.

Parameters

Events

EVENT_TRANSFORMEND

static EVENT_TRANSFORMEND: string = 'transform:end'

Fired when the transformation has ended.

Example

const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:end', () => {
    console.log('Transformation ended');
});

EVENT_TRANSFORMMOVE

static EVENT_TRANSFORMMOVE: string = 'transform:move'

Fired during the transformation.

Example

const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:move', (pointDelta, angleDelta) => {
    console.log(`Transformation moved by ${pointDelta} (angle: ${angleDelta})`);
});

EVENT_TRANSFORMSTART

static EVENT_TRANSFORMSTART: string = 'transform:start'

Fired when the transformation has started.

Example

const gizmo = new TransformGizmo(camera, layer);
gizmo.on('transform:start', () => {
    console.log('Transformation started');
});

Inherited from Gizmo

TranslateGizmo

Class · extends TransformGizmo · category: Gizmo

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/translate-gizmo.js#L61

The TranslateGizmo provides interactive 3D manipulation handles for translating/moving Entitys in a Scene. It creates a visual widget with arrows along the X, Y and Z axes, planes at their intersections, and a center sphere, allowing precise control over object positioning through direct manipulation. The gizmo's visual appearance can be customized away from the defaults as required.

Note that the gizmo can be driven by both mouse+keyboard and touch input.

// Create a layer for rendering all gizmos
const gizmoLayer = Gizmo.createLayer(app);

// Create a translate gizmo
const gizmo = new TranslateGizmo(cameraComponent, gizmoLayer);

// Create an entity to attach the gizmo to
const entity = new Entity();
entity.addComponent('render', {
    type: 'box'
});
app.root.addChild(entity);

// Attach the gizmo to the entity
gizmo.attach([entity]);

Relevant Engine API examples:

Constructors

constructor

new TranslateGizmo(camera: CameraComponent, layer: Layer)

Creates a new TranslateGizmo object. Use Gizmo.createLayer to create the layer required to display the gizmo.

Parameters

Example

const gizmo = new TranslateGizmo(camera, layer);

Properties

_shapes

protected _shapes: { x: ArrowShape; xy: PlaneShape; xyz: SphereShape; xz: PlaneShape; y: ArrowShape; yz: PlaneShape; z: ArrowShape }

Internal object containing the gizmo shapes to render.

Properties

flipPlanes

flipPlanes: boolean = true

Flips the planes to face the camera.

snapIncrement

snapIncrement: number = 1

Accessors

axisArrowLength

get axisArrowLength(): number
set axisArrowLength(value: number)

Gets the arrow length.

axisArrowThickness

get axisArrowThickness(): number
set axisArrowThickness(value: number)

Gets the arrow thickness.

axisCenterSize

get axisCenterSize(): number
set axisCenterSize(value: number)

Gets the axis center size.

axisGap

get axisGap(): number
set axisGap(value: number)

Gets the axis gap.

axisLineLength

get axisLineLength(): number
set axisLineLength(value: number)

Gets the axis line length.

axisLineThickness

get axisLineThickness(): number
set axisLineThickness(value: number)

Gets the axis line thickness.

axisLineTolerance

get axisLineTolerance(): number
set axisLineTolerance(value: number)

Gets the axis line tolerance.

axisPlaneGap

get axisPlaneGap(): number
set axisPlaneGap(value: number)

Gets the plane gap.

axisPlaneSize

get axisPlaneSize(): number
set axisPlaneSize(value: number)

Gets the plane size.

Methods

_drawGuideLines

_drawGuideLines(pos: Vec3, rot: Quat, activeAxis: GizmoAxis, activeIsPlane: boolean): void

Parameters

_screenToPoint

protected _screenToPoint(x: number, y: number): Vec3

Parameters

Returns Vec3: The point (space is TransformGizmo#coordSpace).

prerender

prerender(): void

Inherited from TransformGizmo

Batch

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch.js#L14

Holds information about batched mesh instances. Created in BatchManager#create.

Constructors

constructor

new Batch(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId: number)

Create a new Batch instance.

Parameters

Properties

batchGroupId

batchGroupId: number

Link this batch to a specific batch group. This is done automatically with default batches.

dynamic

dynamic: boolean

Whether this batch is dynamic (supports transforming mesh instances at runtime).

meshInstance

meshInstance: MeshInstance = null

A single combined mesh instance, the result of batching.

origMeshInstances

origMeshInstances: MeshInstance[]

An array of original mesh instances, from which this batch was generated.

Methods

destroy

destroy(scene: Scene, layers: number[]): void

Removes the batch from the layers and destroys it.

Parameters

BatchGroup

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch-group.js#L8

Holds mesh batching settings and a unique id. Created via BatchManager#addGroup.

Constructors

constructor

new BatchGroup(id: number, name: string, dynamic: boolean, maxAabbSize: number, layers?: number[])

Create a new BatchGroup instance.

Parameters

Properties

dynamic

dynamic: boolean

Whether objects within this batch group should support transforming at runtime.

id

id: number

Unique id. Can be assigned to model, render and element components.

layers

layers: number[]

Layer ID array. Default is [LAYERID_WORLD]. The whole batch group will belong to these layers. Layers of source models will be ignored.

maxAabbSize

maxAabbSize: number

Maximum size of any dimension of a bounding box around batched objects. BatchManager#prepare will split objects into local groups based on this size.

name

name: string

Name of the group.

BatchManager

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/batching/batch-manager.js#L66

Glues many mesh instances into a single one for better performance.

Constructors

constructor

new BatchManager(device: GraphicsDevice, root: Entity, scene: Scene)

Create a new BatchManager instance.

Parameters

Methods

addGroup

addGroup(name: string, dynamic: boolean, maxAabbSize: number, id?: number, layers?: number[]): BatchGroup

Adds new global batch group.

Parameters

Returns BatchGroup: Group object.

create

create(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId?: number): Batch

Takes a mesh instance list that has been prepared by prepare, and returns a Batch object. This method assumes that all mesh instances provided can be rendered in a single draw call.

Parameters

Returns Batch: The resulting batch object.

generate

generate(groupIds?: number[]): void

Destroys all batches and creates new based on scene models. Hides original models. Called by engine automatically on app start, and if batchGroupIds on models are changed.

Parameters

getGroupById

getGroupById(id: number): BatchGroup | null

Retrieves a BatchGroup object with a corresponding id, if it exists, or null otherwise.

Parameters

Returns BatchGroup | null: The batch group matching the id or null if not found.

getGroupByName

getGroupByName(name: string): BatchGroup | null

Retrieves a BatchGroup object with a corresponding name, if it exists, or null otherwise.

Parameters

Returns BatchGroup | null: The batch group matching the name or null if not found.

markGroupDirty

markGroupDirty(id: number): void

Mark a specific batch group as dirty. Dirty groups are re-batched before the next frame is rendered. Note, re-batching a group is a potentially expensive operation.

Parameters

prepare

prepare(meshInstances: MeshInstance[], dynamic: boolean, maxAabbSize?: number, translucent: boolean): MeshInstance[][]

Takes a list of mesh instances to be batched and sorts them into lists one for each draw call. The input list will be split, if:

Parameters

Returns MeshInstance[][]: An array of arrays of mesh instances, each valid to pass to create.

removeGroup

removeGroup(id: number): void

Remove global batch group by id. Note, this traverses the entire scene graph and clears the batch group id from all components.

Parameters

BindBaseFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L21

A base class to describe the format of the resource for BindGroupFormat.

Constructors

constructor

new BindBaseFormat(name: string, visibility: number)

Create a new instance.

Parameters

Properties

name

name: string

BindGroupFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L299

BindGroupFormat is a data structure that defines the layout of resources (buffers, textures, samplers) used by rendering or compute shaders. It describes the binding points for each resource type, and the visibility of these resources in the shader stages. Currently this class is only used on WebGPU platform to specify the input and output resources for vertex, fragment and compute shaders written in SHADERLANGUAGE_WGSL language.

Call BindGroupFormat#destroy when no longer needed. On WebGPU, the graphics device retains bind group formats for device recovery until they are explicitly destroyed.

Constructors

constructor

new BindGroupFormat(graphicsDevice: GraphicsDevice, formats: (BindTextureFormat | BindStorageTextureFormat | BindUniformBufferFormat | BindStorageBufferFormat)[])

Create a new instance.

Parameters

Properties

bufferFormatsMap

bufferFormatsMap: Map<string, number>

device

device: GraphicsDevice

storageBufferFormatsMap

storageBufferFormatsMap: Map<string, number>

storageTextureFormatsMap

storageTextureFormatsMap: Map<string, number>

textureFormatsMap

textureFormatsMap: Map<string, number>

Methods

destroy

destroy(): void

Frees resources associated with this bind group.

BindStorageBufferFormat

Class · extends BindBaseFormat · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L81

A class to describe the format of the storage buffer for BindGroupFormat.

Constructors

constructor

new BindStorageBufferFormat(name: string, visibility: number, readOnly?: boolean)

Create a new instance.

Parameters

Inherited from BindBaseFormat

BindStorageTextureFormat

Class · extends BindBaseFormat · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L243

A class to describe the format of the storage texture for BindGroupFormat. Storage texture is a texture created with the storage flag set to true, which allows it to be used as an output of a compute shader.

Note: At the current time, storage textures are only supported in compute shaders in a write-only mode.

Constructors

constructor

new BindStorageTextureFormat(name: string, format?: number, textureDimension?: string, write?: boolean, read?: boolean)

Create a new instance.

Parameters

Inherited from BindBaseFormat

BindTextureFormat

Class · extends BindBaseFormat · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L122

A class to describe the format of the texture for BindGroupFormat.

Constructors

constructor

new BindTextureFormat(name: string, visibility: number, textureDimension?: string, sampleType?: number, hasSampler?: boolean, samplerName?: string | null, multisampled?: boolean)

Create a new instance.

Parameters

Properties

hasSampler

hasSampler: boolean

Whether a sampler binding follows this texture. Always false when multisampled is true.

multisampled

multisampled: boolean

Whether this is a multisampled (texture_multisampled_*) binding.

samplerName

samplerName: string | null = null

Sampler uniform name. null when multisampled is true; otherwise the provided name or ${name}_sampler.

Inherited from BindBaseFormat

BindUniformBufferFormat

Class · extends BindBaseFormat · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/bind-group-format.js#L69

A class to describe the format of the uniform buffer for BindGroupFormat.

Inherited from BindBaseFormat

Inherited from BindTextureFormat

BlendState

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/blend-state.js#L69

BlendState is a descriptor that defines how output of fragment shader is written and blended into render target. A blend state can be set on a material using Material#blendState, or in some cases on the graphics device using GraphicsDevice#setBlendState.

For the best performance, do not modify blend state after it has been created, but create multiple blend states and assign them to the material or graphics device as needed.

By default the blend state applies to all color attachments of the render target. When multiple color attachments are used, individual attachments can be given an independent blend state using BlendState#setAttachment. This requires GraphicsDevice#supportsIndependentBlending - on devices without support, the state of the attachment 0 is used for all attachments.

Constructors

constructor

new BlendState(blend?: boolean, colorOp?: number, colorSrcFactor?: number, colorDstFactor?: number, alphaOp?: number, alphaSrcFactor?: number, alphaDstFactor?: number, redWrite?: boolean, greenWrite?: boolean, blueWrite?: boolean, alphaWrite?: boolean)

Create a new BlendState instance.

All factor parameters can take the following values:

All op parameters can take the following values:

Parameters

Properties

ADDBLEND

static readonly ADDBLEND: BlendState

A blend state that does simple additive blending.

ALPHABLEND

static readonly ALPHABLEND: BlendState

A blend state that does simple translucency using alpha channel.

NOBLEND

static readonly NOBLEND: BlendState

A blend state that has blending disabled and writes to all color channels.

NOWRITE

static readonly NOWRITE: BlendState

A blend state that does not write to color channels.

Accessors

blend

get blend(): boolean
set blend(value: boolean)

Gets whether blending is enabled.

hasAttachmentOverrides

get hasAttachmentOverrides(): boolean

Gets whether any color attachment has been given an independent blend state using BlendState#setAttachment.

Methods

clearAttachment

clearAttachment(index: number): void

Removes the independent blend state of the specified color attachment, making it follow attachment 0 again.

Parameters

clone

clone(): BlendState

Returns an identical copy of the specified blend state.

Returns BlendState: The result of the cloning.

copy

copy(rhs: BlendState): BlendState

Copies the contents of a source blend state to this blend state.

Parameters

Returns BlendState: Self for chaining.

equals

equals(rhs: BlendState): boolean

Reports whether two BlendStates are equal.

Parameters

Returns boolean: True if the blend states are equal and false otherwise.

getAttachment

getAttachment(index: number, dst: BlendState): BlendState

Stores the blend state of the specified color attachment in the supplied blend state. When the attachment does not have an independent blend state, the state of attachment 0 is stored.

Parameters

Returns BlendState: The supplied dst, for chaining.

setAttachment

setAttachment(index: number, src: BlendState | null): void

Assigns an independent blend state to the specified color attachment. The blend state of the supplied source is copied, and so subsequent changes to either the source or to attachment 0 do not affect it. An attachment which has not been assigned an independent state instead follows attachment 0.

Note that this requires GraphicsDevice#supportsIndependentBlending - on devices without support, the state of attachment 0 is used for all attachments.

Parameters

Example

// attachment 1 keeps the blending of attachment 0, but does not write any channels
const state = material.blendState.clone();
const noWrite = state.clone();
noWrite.setColorWrite(false, false, false, false);
state.setAttachment(1, noWrite);

BoxGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/box-geometry.js#L37

A procedural box-shaped geometry.

Typically, you would:

  1. Create a BoxGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new BoxGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new BoxGeometry(opts?: object)

Create a new BoxGeometry instance.

By default, the constructor creates a box centered on the object space origin with a width, length and height of 1 unit and 1 segment in either axis (2 triangles per face). The box is created with UVs in the range of 0 to 1 on each face.

Parameters

Example

const geometry = new BoxGeometry({
    halfExtents: new Vec3(1, 1, 1),
    widthSegments: 2,
    lengthSegments: 2,
    heightSegments: 2
});

Inherited from Geometry

CameraComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/component.js#L78

The CameraComponent enables an Entity to render the scene. A scene requires at least one enabled camera component to be rendered. The camera's view direction is along the negative z-axis of the owner entity.

Note that multiple camera components can be enabled simultaneously (for split-screen or offscreen rendering, for example).

You should never need to use the CameraComponent constructor directly. To add a CameraComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('camera', {
    nearClip: 1,
    farClip: 100,
    fov: 55
});

Once the CameraComponent is added to the entity, you can access it via the Entity#camera property:

entity.camera.nearClip = 2; // Set the near clip of the camera

console.log(entity.camera.nearClip); // Get the near clip of the camera

For ready-made camera behaviour, attach the CameraControls script from playcanvas/scripts/esm/camera-controls.mjs, which provides orbit, fly and pan driven by mouse, touch and gamepad input.

Relevant Engine API examples:

Accessors

aperture

get aperture(): number
set aperture(value: number)

Gets the camera aperture in f-stops.

aspectRatio

get aspectRatio(): number
set aspectRatio(value: number)

Gets the aspect ratio (width divided by height) of the camera.

aspectRatioMode

get aspectRatioMode(): number
set aspectRatioMode(value: number)

Gets the aspect ratio mode of the camera.

calculateProjection

get calculateProjection(): CalculateMatrixCallback
set calculateProjection(value: CalculateMatrixCallback)

Gets the custom function to calculate the camera projection matrix manually.

calculateTransform

get calculateTransform(): CalculateMatrixCallback
set calculateTransform(value: CalculateMatrixCallback)

Gets the custom function to calculate the camera transformation matrix manually.

clearColor

get clearColor(): Color
set clearColor(value: Color)

Gets the camera component's clear color.

clearColorBuffer

get clearColorBuffer(): boolean
set clearColorBuffer(value: boolean)

Gets whether the camera will automatically clear the color buffer before rendering.

clearDepth

get clearDepth(): number
set clearDepth(value: number)

Gets the depth value to clear the depth buffer to.

clearDepthBuffer

get clearDepthBuffer(): boolean
set clearDepthBuffer(value: boolean)

Gets whether the camera will automatically clear the depth buffer before rendering.

clearStencilBuffer

get clearStencilBuffer(): boolean
set clearStencilBuffer(value: boolean)

Gets whether the camera will automatically clear the stencil buffer before rendering.

cullFaces

get cullFaces(): boolean
set cullFaces(value: boolean)

Gets whether the camera will cull triangle faces.

disablePostEffectsLayer

get disablePostEffectsLayer(): number
set disablePostEffectsLayer(layer: number)

Gets the layer id of the layer on which the post-processing of the camera stops being applied to.

farClip

get farClip(): number
set farClip(value: number)

Gets the distance from the camera after which no rendering will take place.

flipFaces

get flipFaces(): boolean
set flipFaces(value: boolean)

Gets whether the camera will flip the face direction of triangles.

fog

get fog(): FogParams | null
set fog(value: FogParams | null)

Gets a FogParams that defines fog parameters, or null if those are not set.

fov

get fov(): number
set fov(value: number)

Gets the field of view of the camera in degrees.

frustum

get frustum(): Frustum

Gets the camera's frustum shape.

frustumCulling

get frustumCulling(): boolean
set frustumCulling(value: boolean)

Gets whether frustum culling is enabled.

gammaCorrection

get gammaCorrection(): number
set gammaCorrection(value: number)

Gets the gamma correction used when rendering the scene.

horizontalFov

get horizontalFov(): boolean
set horizontalFov(value: boolean)

Gets whether the camera's field of view (fov) is horizontal or vertical.

jitter

get jitter(): number
set jitter(value: number)

Gets the jitter intensity applied in the projection matrix.

layers

get layers(): readonly number[]
set layers(newValue: readonly number[])

Gets the array of layer IDs (Layer#id) to which this camera belongs.

nearClip

get nearClip(): number
set nearClip(value: number)

Gets the distance from the camera before which no rendering will take place.

orthoHeight

get orthoHeight(): number
set orthoHeight(value: number)

Gets the half-height of the orthographic view window (in the Y-axis).

postEffects

get postEffects(): PostEffectQueue

Gets the post effects queue for this camera. Use this to add or remove post effects from the camera.

priority

get priority(): number
set priority(newValue: number)

Gets the priority to control the render order of this camera.

projection

get projection(): number
set projection(value: number)

Gets the type of projection used to render the camera.

projectionMatrix

get projectionMatrix(): Mat4

Gets the camera's projection matrix.

projectionOffset

get projectionOffset(): Vec2
set projectionOffset(value: Vec2)

Gets the offset of the projection window.

rect

get rect(): Readonly<Vec4>
set rect(value: Readonly<Vec4>)

Gets the rendering rectangle for the camera.

renderTarget

get renderTarget(): RenderTarget
set renderTarget(value: RenderTarget)

Gets the render target to which rendering of the camera is performed.

scissorRect

get scissorRect(): Vec4
set scissorRect(value: Vec4)

Gets the scissor rectangle for the camera.

sensitivity

get sensitivity(): number
set sensitivity(value: number)

Gets the camera sensitivity in ISO.

shutter

get shutter(): number
set shutter(value: number)

Gets the camera shutter speed in seconds.

toneMapping

get toneMapping(): number
set toneMapping(value: number)

Gets the tonemapping transform applied to the rendered color buffer.

viewMatrix

get viewMatrix(): Mat4

Gets the camera's view matrix.

Methods

calculateAspectRatio

calculateAspectRatio(rt?: RenderTarget | null): number

Computes the aspect ratio this camera would produce when rendering to the given render target, without changing the camera's state. When rt is omitted, the camera's own CameraComponent#renderTarget is used, and if that is also null, the backbuffer is used. The camera's CameraComponent#rect viewport is taken into account.

Parameters

Returns number: The computed aspect ratio.

endXr

endXr(callback?: XrErrorCallback): void

Attempt to end XR session of this camera.

Parameters

Example

// On an entity with a camera component
this.entity.camera.endXr((err) => {
    // not anymore in XR
});

getClearColor

getClearColor(index: number): Color

Gets the clear color of a color attachment of the camera's render target.

Parameters

Returns Color: The clear color of the attachment.

getShaderPass

getShaderPass(): string | undefined

Shader pass name.

Returns string | undefined: The name of the shader pass, or undefined if no shader pass is set.

requestSceneColorMap

requestSceneColorMap(enabled: boolean): void

Request the scene to generate a texture containing the scene color map. Note that this call is accumulative, and for each enable request, a disable request need to be called. Note that this setting is ignored when framePasses is used.

Parameters

requestSceneDepthMap

requestSceneDepthMap(enabled: boolean): void

Request the scene to generate a texture containing the scene depth map. Note that this call is accumulative, and for each enable request, a disable request need to be called. Note that this setting is ignored when framePasses is used.

Parameters

screenToWorld

screenToWorld(screenx: number, screeny: number, cameraz: number, worldCoord?: Vec3): Vec3

Convert a point from 2D screen space to 3D world space.

Parameters

Returns Vec3: The world space coordinate.

Example

// Get the start and end points of a 3D ray fired from a screen click position
const start = entity.camera.screenToWorld(clickX, clickY, entity.camera.nearClip);
const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip);

// Use the ray coordinates to perform a raycast
const result = app.systems.rigidbody.raycastFirst(start, end);
if (result) {
    console.log(`Entity ${result.entity.name} was selected`);
}

setClearColor

setClearColor(index: number, color: Color | null): void

Sets the clear color of a color attachment of the camera's render target, which allows the color buffers of a RenderTarget with multiple color buffers to clear to different colors. The attachment 0 clears to CameraComponent#clearColor, and the other attachments clear to the same color unless given their own here. Pass null to remove the color of an attachment, so that it clears to the attachment 0 color again. The components of the clear color of an integer format attachment are the integer values to clear to.

Parameters

Example

// clear the second color buffer of the render target to a different color
entity.camera.setClearColor(1, new pc.Color(0.5, 0.5, 1, 1));

setShaderPass

setShaderPass(name: string): number

Sets the name of the shader pass the camera will use when rendering.

In addition to existing names (see the parameter description), a new name can be specified, which creates a new shader pass with the given name. The name provided can only use alphanumeric characters and underscores. When a shader is compiled for the new pass, a define is added to the shader. For example, if the name is 'custom_rendering', the define 'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally execute code only when that shader pass is active.

Another instance where this approach may prove useful is when a camera needs to render a more cost-effective version of shaders, such as when creating a reflection texture. To accomplish this, a callback on the material that triggers during shader compilation can be used. This callback can modify the shader generation options specifically for this shader pass.

const shaderPassId = camera.setShaderPass('custom_rendering');

material.onUpdateShader = function (options) {
    if (options.pass === shaderPassId) {
        options.litOptions.normalMapEnabled = false;
        options.litOptions.useSpecular = false;
    }
    return options;
};

Parameters

Returns number: The id of the shader pass.

startXr

startXr(type: string, spaceType: string, options?: object): void

Attempt to start XR session with this camera.

Parameters

Example

// On an entity with a camera component
this.entity.camera.startXr(XRTYPE_VR, XRSPACE_LOCAL, {
    callback: (err) => {
        if (err) {
            // failed to start XR session
        } else {
            // in XR
        }
    }
});

worldToScreen

worldToScreen(worldCoord: Vec3, screenCoord?: Vec3): Vec3

Convert a point from 3D world space to 2D screen space.

The returned z is the unnormalized clip space depth, not a behind-the-camera flag: it also goes negative for points in front of a perspective camera that are nearer than twice the near clip, and for an orthographic camera it is negative across the whole near half of the depth range. To reject points behind the camera, test the view space depth instead - pass the world position through CameraComponent#viewMatrix and discard it when the resulting z is zero or greater.

Parameters

Returns Vec3: The screen space coordinate.

Inherited from Component

CameraComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/system.js#L77

Used to add and remove CameraComponents from Entities. It also holds an array of all active cameras.

Properties

cameras

cameras: CameraComponent[] = []

Holds all the active camera components.

Inherited from ComponentSystem

CameraFrame

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L300

Implementation of a simple to use camera rendering pass, which supports SSAO, Bloom and other rendering effects.

Overriding compose shader chunks: The final compose pass registers its shader chunks in a way that does not override any chunks that were already provided. To customize the compose pass output, set your shader chunks on the ShaderChunks map before creating the CameraFrame. Those chunks will be picked up by the compose pass and preserved.

Example (GLSL):

Example

// Provide custom compose chunk(s) before constructing CameraFrame
ShaderChunks.get(graphicsDevice, SHADERLANGUAGE_GLSL).set('composeVignettePS', `
    #ifdef VIGNETTE
        vec3 applyVignette(vec3 color, vec2 uv) {
            return color * uv.u;
        }
    #endif
`);

// For WebGPU, use SHADERLANGUAGE_WGSL instead.

Constructors

constructor

new CameraFrame(app: AppBase, cameraComponent: CameraComponent)

Creates a new CameraFrame instance.

Parameters

Properties

bloom

bloom: Bloom

Bloom settings.

colorEnhance

colorEnhance: ColorEnhance

Color enhancement settings.

colorLUT

colorLUT: ColorLUT

Color LUT settings.

debug

debug: "depth" | "scene" | "ssao" | "bloom" | "vignette" | "dofcoc" | "dofblur" | null = null

Debug rendering, which displays an intermediate value of the frame in place of the composed result. This never changes what the frame renders - a mode whose value this frame does not generate simply displays nothing: 'depth' renders black when no effect has produced the scene depth, and the modes of a disabled effect are ignored. Set to null to disable.

dof

dof: Dof

DoF settings.

fringing

fringing: Fringing

Fringing settings.

grading

grading: Grading

Grading settings.

rendering

rendering: Rendering

Rendering settings.

ssao

ssao: Ssao

SSAO settings.

taa

taa: Taa

Taa settings.

vignette

vignette: Vignette

Vignette settings.

volumetricFog

volumetricFog: VolumetricFog

Volumetric fog settings.

Accessors

enabled

get enabled(): boolean
set enabled(value: boolean)

Gets the enabled state of the camera frame.

Methods

createRenderPass

createRenderPass(): FramePassCameraFrame

Creates a frame pass for the camera frame. Override this method to utilize a custom frame pass, typically one that extends FramePassCameraFrame.

Returns FramePassCameraFrame: - The frame pass.

destroy

destroy(): void

Destroys the camera frame, removing all render passes.

update

update(): void

Applies any changes made to the properties of this instance.

isSplatSceneDepthSupported

static isSplatSceneDepthSupported(device: GraphicsDevice): boolean

Returns whether a device is able to let the gaussian splats contribute to the scene depth, which the volumetric fog and the depth of field need in order to be bounded by the splats instead of drawing through them. Their contribution additionally has to be turned on using GSplatParams#sceneDepthWrite; this reports whether doing so can take effect, so that an application rendering gaussian splats can disable those effects on the devices which cannot respect them.

This tests the device alone, and so can be called before any camera frame is created. Whether a particular one then renders the depth this way also depends on its own settings - multi-sampling and a camera not clearing the whole of its render target both rule it out - and a debug build warns, naming the reason, when the splats end up not contributing.

Parameters

Returns boolean: True if the splats can contribute to the scene depth.

CapsuleGeometry

Class · extends ConeBaseGeometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/capsule-geometry.js#L33

A procedural capsule-shaped geometry.

Typically, you would:

  1. Create a CapsuleGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new CapsuleGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new CapsuleGeometry(opts?: object)

Create a new CapsuleGeometry instance.

By default, the constructor creates a capsule standing vertically centered on the XZ-plane with a radius of 0.3, a height of 1.0, 1 height segment and 20 cap segments. The capsule is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new CapsuleGeometry({
    radius: 1,
    height: 2,
    heightSegments: 2,
    sides: 20
});

Inherited from ConeBaseGeometry

CircleGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/circle-geometry.js#L33

A procedural circle-shaped geometry - a flat disc in the XZ plane.

Typically, you would:

  1. Create a CircleGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new CircleGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new CircleGeometry(opts?: object)

Create a new CircleGeometry instance.

By default, the constructor creates a circle centered on the object space origin with a radius of 0.5, 64 sectors and 8 rings. The normal vector of the circle is aligned along the positive Y axis. The circle is created with UVs in the range of 0 to 1, mapped planarly across its bounding square.

Parameters

Example

const geometry = new CircleGeometry({
    radius: 100,
    sectors: 128,
    rings: 64,
    ringExponent: 2
});

Inherited from Geometry

Compute

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/compute.js#L34

A representation of a compute shader with the associated resources, that can be executed on the GPU. Only supported on WebGPU platform.

Call Compute#destroy when no longer needed. The graphics device retains compute instances for device recovery until they are explicitly destroyed.

Constructors

constructor

new Compute(graphicsDevice: GraphicsDevice, shader: Shader, name?: string)

Create a compute instance. Note that this is supported on WebGPU only and is a no-op on other platforms.

Parameters

Properties

name

name: string

The non-unique name of an instance of the class. Defaults to 'Unnamed'.

Methods

deleteParameter

deleteParameter(name: string): void

Deletes a shader parameter from the compute instance.

Parameters

destroy

destroy(): void

Frees resources associated with this compute instance.

getParameter

getParameter(name: string): number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined

Returns the value of a shader parameter from the compute instance.

Parameters

Returns number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined: The value of the specified parameter.

setParameter

setParameter(name: string, value: number | number[] | Float32Array<ArrayBufferLike> | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView): void

Sets a shader parameter on a compute instance.

Parameters

setupDispatch

setupDispatch(x: number, y?: number, z?: number): void

Prepare the compute work dispatch.

Parameters

setupIndirectDispatch

setupIndirectDispatch(slotIndex: number, buffer?: StorageBuffer | null): void

Prepare the compute work dispatch to use indirect parameters from a buffer. The dispatch parameters (x, y, z workgroup counts) are read from the buffer at the specified slot index.

When using the device's built-in buffer (buffer parameter is null), this method must be called each frame as slots are only valid for the current frame.

Parameters

Example

// Reserve a slot in the indirect dispatch buffer
const slot = device.getIndirectDispatchSlot();

// First compute shader writes dispatch parameters to the buffer
prepareCompute.setParameter('indirectBuffer', device.indirectDispatchBuffer);
prepareCompute.setParameter('slot', slot);
prepareCompute.setupDispatch(1, 1, 1);
device.computeDispatch([prepareCompute]);

// Second compute shader uses indirect dispatch
processCompute.setupIndirectDispatch(slot);
device.computeDispatch([processCompute]);

ConeBaseGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cone-base-geometry.js#L13

Shared superclass of CapsuleGeometry, ConeGeometry and CylinderGeometry. Use those classes instead of this one.

Inherited from Geometry

ConeGeometry

Class · extends ConeBaseGeometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cone-geometry.js#L33

A procedural cone-shaped geometry.

Typically, you would:

  1. Create a ConeGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new ConeGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new ConeGeometry(opts?: object)

Create a new ConeGeometry instance.

By default, the constructor creates a cone standing vertically centered on the XZ-plane with a base radius of 0.5, a height of 1.0, 5 height segments and 18 cap segments. The cone is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new ConeGeometry({
    baseRadius: 1,
    height: 2,
    heightSegments: 2,
    capSegments: 20
});

Inherited from ConeBaseGeometry

ContainerResource

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/container.js#L18

Container for a list of animations, textures, materials, renders, gsplats and a model.

Properties

animations

animations: Asset<"animation">[] = []

An array of the animation assets. Each resource is an AnimTrack.

gsplats

gsplats: Asset<"gsplat">[] = []

An array of the gsplat assets, created for meshes using the KHR_gaussian_splatting glTF extension.

materials

materials: Asset<"material">[] = []

An array of the Material and/or StandardMaterial assets.

renders

renders: Asset<"render">[] = []

An array of the render assets. Each holds the meshes of one glTF mesh.

textures

textures: Asset<"texture">[] = []

An array of the Texture assets.

Methods

applyMaterialVariant

applyMaterialVariant(entity: Entity, name?: string): void

Applies a material variant to an entity hierarchy.

Parameters

Example

// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
    const entity = asset.resource.instantiateRenderEntity({
        castShadows: true
    });
    app.root.addChild(entity);
    const materialVariants = asset.resource.getMaterialVariants();
    asset.resource.applyMaterialVariant(entity, materialVariants[0]);
});

applyMaterialVariantInstances

applyMaterialVariantInstances(instances: MeshInstance[], name?: string): void

Applies a material variant to a set of mesh instances. Compared to the applyMaterialVariant, this method allows for setting the variant on a specific set of mesh instances instead of the whole entity.

Parameters

Example

// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
    const entity = asset.resource.instantiateRenderEntity({
        castShadows: true
    });
    app.root.addChild(entity);
    const materialVariants = asset.resource.getMaterialVariants();
    const renders = entity.findComponents("render");
    for (let i = 0; i < renders.length; i++) {
        const renderComponent = renders[i];
        asset.resource.applyMaterialVariantInstances(renderComponent.meshInstances, materialVariants[0]);
    }
});

getMaterialVariants

getMaterialVariants(): string[]

Queries the list of available material variants.

Returns string[]: An array of variant names.

instantiateModelEntity

instantiateModelEntity(options?: any): Entity

Instantiates an entity with a model component.

Parameters

Returns Entity: A single entity with a model component. Model component internally contains a hierarchy based on GraphNode.

Example

// load a glb file and instantiate an entity with a model component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
    const entity = asset.resource.instantiateModelEntity({
        castShadows: true
    });
    app.root.addChild(entity);
});

instantiateRenderEntity

instantiateRenderEntity(options?: any): Entity

Instantiates an entity with a render component.

Parameters

Returns Entity: A hierarchy of entities with render components on entities containing renderable geometry.

Example

// load a glb file and instantiate an entity with a render component based on it
app.assets.loadFromUrl("statue.glb", "container", (err, asset) => {
    const entity = asset.resource.instantiateRenderEntity({
        castShadows: true
    });
    app.root.addChild(entity);

    // find all render components containing mesh instances, and change blend mode on their materials
    const renders = entity.findComponents("render");
    renders.forEach((render) => {
        render.meshInstances.forEach((meshInstance) => {
            meshInstance.material.blendType = BLEND_MULTIPLICATIVE;
            meshInstance.material.update();
        });
    });
});

CylinderGeometry

Class · extends ConeBaseGeometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/cylinder-geometry.js#L33

A procedural cylinder-shaped geometry.

Typically, you would:

  1. Create a CylinderGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new CylinderGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new CylinderGeometry(opts?: object)

Create a new CylinderGeometry instance.

By default, the constructor creates a cylinder standing vertically centered on the XZ-plane with a radius of 0.5, a height of 1.0, 1 height segment and 20 cap segments. The cylinder is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new CylinderGeometry({
    radius: 1,
    height: 2,
    heightSegments: 2,
    capSegments: 10
});

Inherited from ConeBaseGeometry

DepthState

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/depth-state.js#L26

DepthState is a descriptor that defines how the depth value of the fragment is used by the rendering pipeline. A depth state can be set on a material using Material#depthState, or in some cases on the graphics device using GraphicsDevice#setDepthState.

For the best performance, do not modify depth state after it has been created, but create multiple depth states and assign them to the material or graphics device as needed.

Constructors

constructor

new DepthState(func?: number, write?: boolean)

Create a new Depth State instance.

Parameters

Properties

key

key: number = 0

A unique number representing the depth state. You can use this number to quickly compare two depth states for equality. The key is always maintained valid without a dirty flag, to avoid condition check at runtime, considering these change rarely.

DEFAULT

static readonly DEFAULT: DepthState

A default depth state that has the depth testing function set to FUNC_LESSEQUAL and depth writes enabled.

NODEPTH

static readonly NODEPTH: DepthState

A depth state that always passes the fragment but does not write depth to the depth buffer.

WRITEDEPTH

static readonly WRITEDEPTH: DepthState

A depth state that always passes the fragment and writes depth to the depth buffer.

Accessors

depthBias

get depthBias(): number
set depthBias(value: number)

Gets the constant depth bias added to each fragment's depth.

depthBiasSlope

get depthBiasSlope(): number
set depthBiasSlope(value: number)

Gets the depth bias that scales with the fragment's slope.

func

get func(): number
set func(value: number)

Gets the depth testing function.

test

get test(): boolean
set test(value: boolean)

Gets whether depth testing is performed.

write

get write(): boolean
set write(value: boolean)

Gets whether depth writing is performed.

Methods

clone

clone(): DepthState

Returns an identical copy of the specified depth state.

Returns DepthState: The result of the cloning.

copy

copy(rhs: DepthState): DepthState

Copies the contents of a source depth state to this depth state.

Parameters

Returns DepthState: Self for chaining.

equals

equals(rhs: DepthState): boolean

Reports whether two DepthStates are equal.

Parameters

Returns boolean: True if the depth states are equal and false otherwise.

DomeGeometry

Class · extends SphereGeometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/dome-geometry.js#L33

A procedural dome-shaped geometry.

Typically, you would:

  1. Create a DomeGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new DomeGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new DomeGeometry(opts?: object)

Create a new DomeGeometry instance.

By default, the constructor creates a dome with a radius of 0.5, 16 latitude bands and 16 longitude bands. The dome is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new DomeGeometry({
    latitudeBands: 32,
    longitudeBands: 32
});

Inherited from SphereGeometry

DrawCommands

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/draw-commands.js#L11

Container holding parameters for multi-draw commands.

Obtain an instance via MeshInstance#setMultiDraw and populate it using add followed by update.

Accessors

count

get count(): number

Number of draw calls to perform.

maxCount

get maxCount(): number

Maximum number of multi-draw calls the space is allocated for.

Methods

add

add(i: number, indexOrVertexCount: number, instanceCount: number, firstIndexOrVertex: number, baseVertex?: number, firstInstance?: number): void

Writes one draw command into the allocated storage.

Parameters

update

update(count: number): void

Finalize and set draw count after all commands have been added.

Parameters

FogParams

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/fog-params.js#L9

Fog parameters.

Properties

color

color: Color

The color of the fog (if enabled), specified in sRGB color space. Defaults to black (0, 0, 0).

density

density: number = 0

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

end

end: number = 1000

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. Defaults to 1000.

start

start: number = 1

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

type

type: string = FOG_NONE

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

Defaults to FOG_NONE.

Geometry

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry.js#L10

The Geometry class serves as a container for storing geometric information. It encapsulates data such as positions, normals, colors, and indices.

Properties

blendIndices

blendIndices: ArrayLike<number> | undefined

Blend indices.

blendWeights

blendWeights: ArrayLike<number> | undefined

Blend weights.

colors

colors: ArrayLike<number> | undefined

Colors.

indices

indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined

Indices.

normals

normals: ArrayLike<number> | undefined

Normals.

positions

positions: ArrayLike<number> | undefined

Positions.

tangents

tangents: ArrayLike<number> | undefined

Tangents.

uvs

uvs: ArrayLike<number> | undefined

UVs.

uvs1

uvs1: ArrayLike<number> | undefined

Additional Uvs.

Methods

calculateNormals

calculateNormals(): void

Generates normal information from the positions and triangle indices.

calculateTangents

calculateTangents(): void

Generates tangent information from the positions, normals, texture coordinates and triangle indices.

GraphicsDevice

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/graphics-device.js#L58

The graphics device manages the underlying graphics context. It is responsible for submitting render state changes and graphics primitives to the hardware. A graphics device is tied to a specific canvas HTML element. It is valid to have more than one canvas element per page and create a new graphics device against each.

Properties

backBufferAntialias

backBufferAntialias: boolean = false

True if the back buffer should use anti-aliasing.

canvas

readonly canvas: HTMLCanvasElement

The canvas DOM element that provides the underlying WebGL context used by the graphics device.

gpuProfiler

gpuProfiler: GpuProfiler

The GPU profiler.

insideRenderPass

insideRenderPass: boolean = false

isHdr

isHdr: boolean = false

True if the back-buffer is using HDR format, which means that the browser will display the rendered images in high dynamic range mode. This is true if the options.displayFormat is set to DISPLAYFORMAT_HDR when creating the graphics device using createGraphicsDevice, and HDR is supported by the device.

isNull

readonly isNull: boolean = false

True if the deviceType is Null

isWebGL2

readonly isWebGL2: boolean = false

True if the deviceType is WebGL2

isWebGPU

readonly isWebGPU: boolean = false

True if the deviceType is WebGPU

maxAnisotropy

readonly maxAnisotropy: number

The maximum supported texture anisotropy setting.

maxColorAttachments

readonly maxColorAttachments: number = 1

The maximum supported number of color buffers attached to a render target.

maxCubeMapSize

readonly maxCubeMapSize: number

The maximum supported dimension of a cube map.

maxIndirectDispatchCount

maxIndirectDispatchCount: number = 256

The maximum number of indirect compute dispatches that can be used within a single frame. Used on WebGPU only. Defaults to 256.

maxIndirectDrawCount

maxIndirectDrawCount: number = 1024

The maximum number of indirect draw calls that can be used within a single frame. Used on WebGPU only. This needs to be adjusted based on the maximum number of draw calls that can be used within a single frame. Defaults to 1024.

maxSamples

readonly maxSamples: number = 1

The maximum supported number of hardware anti-aliasing samples.

maxSubgroupSize

readonly maxSubgroupSize: number = 0

Maximum subgroup (warp/wavefront) size reported for the device. Zero means either the device does not expose subgroup sizes, or the WebGPU implementation did not report the value.

maxTextureSize

readonly maxTextureSize: number

The maximum supported dimension of a texture.

maxVolumeSize

readonly maxVolumeSize: number

The maximum supported dimension of a 3D texture (any axis).

minSubgroupSize

readonly minSubgroupSize: number = 0

Minimum subgroup (warp/wavefront) size reported for the device. Zero means either the device does not expose subgroup sizes, or the WebGPU implementation did not report the value.

precision

readonly precision: string

The highest shader precision supported by this graphics device. Can be 'highp', 'mediump' or 'lowp'.

samples

readonly samples: number

The number of hardware anti-aliasing samples used by the frame buffer.

scope

readonly scope: ScopeSpace

The scope namespace for shader attributes and variables.

supportsClipDistances

supportsClipDistances: boolean = false

True if the device supports clip distances (WebGPU only). Clip distances allow you to restrict primitives' clip volume with user-defined half-spaces in the output of vertex stage.

supportsCompute

readonly supportsCompute: boolean = false

True if the device supports compute shaders.

supportsDualSourceBlending

readonly supportsDualSourceBlending: boolean = false

True if the device supports dual-source blending, which allows a fragment shader to output a secondary color used by the source 1 blend factors.

supportsHtmlTextures

readonly supportsHtmlTextures: boolean = false

True if HTML elements (e.g. <div>) can be used as texture sources via the HTML-in-Canvas API. When supported, an HTML element appended to a canvas with the layoutsubtree attribute can be passed to Texture#setSource and rendered as a live texture in the 3D scene.

supportsIndependentBlending

readonly supportsIndependentBlending: boolean = false

True if the device supports independent blending, which allows each color attachment of a render target to use its own blend state and color write mask, specified using BlendState#setAttachment. When false, the state of the attachment 0 is used for all attachments.

supportsIndirectDraw

readonly supportsIndirectDraw: boolean = false

True if the device supports indirect draw calls, where the draw parameters are sourced from a GPU buffer instead of being supplied by the CPU (WebGPU only). Also see MeshInstance#setIndirect.

supportsLinearIndexing

readonly supportsLinearIndexing: boolean = false

True if the device supports the WGSL linear_indexing extension, which provides the global_invocation_index and workgroup_index built-in values in compute shaders. The requires linear_indexing; directive is then automatically injected for compute shader modules, and the shader define CAPS_LINEAR_INDEXING is set for conditional compilation.

supportsMultiDraw

supportsMultiDraw: boolean = true

True if the device supports multi-draw. This is always supported on WebGPU, and support on WebGL2 is optional, but pretty common.

supportsPacked4x8IntegerDotProduct

readonly supportsPacked4x8IntegerDotProduct: boolean = false

True if the device supports the WGSL packed_4x8_integer_dot_product language feature, which exposes the DP4a-family built-in functions for 8-bit packed integer dot products: dot4U8Packed, dot4I8Packed, and the pack4x{I,U}8, pack4x{I,U}8Clamp, unpack4x{I,U}8 helpers. Useful for accelerating quantized inference and similar integer-heavy compute workloads. The requires packed_4x8_integer_dot_product; directive is automatically injected into WGSL shaders when this feature is available, and the shader define CAPS_PACKED_4X8_INTEGER_DOT_PRODUCT is set for conditional compilation.

supportsPointerCompositeAccess

readonly supportsPointerCompositeAccess: boolean = false

True if the device supports the WGSL pointer_composite_access language feature, which provides syntactic sugar for dereferencing pointers to composite types: p.field and p[i] may be written instead of (*p).field and (*p)[i]. The requires pointer_composite_access; directive is automatically injected into WGSL shaders when this feature is available, and the shader define CAPS_POINTER_COMPOSITE_ACCESS is set for conditional compilation.

supportsPrimitiveIndex

readonly supportsPrimitiveIndex: boolean = false

True if the device supports primitive index in fragment shaders (WebGPU only). When supported, fragment shaders can access the pcPrimitiveIndex built-in variable which uniquely identifies the current primitive being processed.

supportsShaderF16

readonly supportsShaderF16: boolean = false

True if the device supports 16-bit floating-point types in shaders (WebGPU only). When supported, shaders can use native WGSL types: f16, vec2h, vec3h, vec4h, mat2x2h, mat3x3h, mat4x4h. For convenience, PlayCanvas also provides type aliases (half, half2, half3, half4, half2x2, half3x3, half4x4) that resolve to f16 types when supported, or fall back to f32 types when not supported.

supportsStorageTextureRead

readonly supportsStorageTextureRead: boolean = false

True if the device can read from StorageTexture in the compute shader. By default, the storage texture can be only used with the write operation. When a shader uses this feature, add a requires directive to signal non-portability at the top of the WGSL shader code. The shader define CAPS_STORAGE_TEXTURE_READ is set when this capability is available.

requires readonly_and_readwrite_storage_textures;

supportsSubgroupId

readonly supportsSubgroupId: boolean = false

True if the device supports the WGSL subgroup_id extension, which provides access to subgroup_id and num_subgroups built-in values in workgroups. The requires subgroup_id; directive is automatically injected into WGSL shaders when this feature is available.

supportsSubgroups

readonly supportsSubgroups: boolean = false

True if the device supports subgroup operations in shaders (WebGPU only). When supported, compute and fragment shaders can use WGSL subgroup builtins such as subgroupBroadcast, subgroupAll, subgroupAny, subgroupAdd, subgroupShuffle, etc. The enable subgroups; directive is automatically injected into WGSL shaders when this feature is available.

supportsSubgroupSizeControl

readonly supportsSubgroupSizeControl: boolean = false

True if the device supports subgroup size control (WebGPU only). This depends on supportsSubgroups and, when available, allows a compute shader to pin its execution to a specific subgroup size (a power of two within the minSubgroupSize to maxSubgroupSize range) via the WGSL @subgroup_size attribute. The subgroup-size-control device feature is automatically requested when this is supported, and the shader define CAPS_SUBGROUP_SIZE_CONTROL is set for conditional compilation.

supportsSubgroupUniformity

readonly supportsSubgroupUniformity: boolean = false

True if the device supports the WGSL subgroup_uniformity extension, which allows subgroup functionality to be considered uniform in more cases during shader compilation. This is automatically enabled via the enable subgroups; directive when supportsSubgroups is true.

supportsTextureAndSamplerLet

readonly supportsTextureAndSamplerLet: boolean = false

True if the device supports the WGSL texture_and_sampler_let language feature, which allows assigning texture and sampler variables to let bindings within a WGSL shader (preparation for bindless-style indirection patterns). The requires texture_and_sampler_let; directive is automatically injected into WGSL shaders when this feature is available, and the shader define CAPS_TEXTURE_AND_SAMPLER_LET is set for conditional compilation.

supportsTextureFormatsTier1

readonly supportsTextureFormatsTier1: boolean = false

True if the device supports the WebGPU 'texture-formats-tier1' feature (WebGPU only). When available, 16-bit unorm and snorm texture formats become usable, the 8-bit snorm formats become renderable, blendable and multisample-capable, and a wider set of 8-bit and 16-bit formats can be bound as storage textures. Implied by supportsTextureFormatsTier2.

supportsTextureFormatsTier2

readonly supportsTextureFormatsTier2: boolean = false

True if the device supports the WebGPU 'texture-formats-tier2' feature (WebGPU only). This extends tier 1 and enables read-write storage access for additional texture formats.

supportsTransientAttachments

readonly supportsTransientAttachments: boolean = false

True if the device supports transient ("memoryless") render target attachments (WebGPU only). When supported, attachments that are only used within a single render pass (cleared on load and discarded on store) can be allocated as memoryless, allowing tile-based GPUs to keep their contents in on-chip memory and avoid VRAM allocation. See the transientColor / transientDepth options of RenderTarget and createGraphicsDevice.

supportsUnrestrictedPointerParameters

readonly supportsUnrestrictedPointerParameters: boolean = false

True if the device supports the WGSL unrestricted_pointer_parameters language feature, which allows passing pointers in the storage, uniform, and workgroup address spaces as function arguments. The requires unrestricted_pointer_parameters; directive is automatically injected into WGSL shaders when this feature is available, and the shader define CAPS_UNRESTRICTED_POINTER_PARAMETERS is set for conditional compilation.

textureFloatBlendable

readonly textureFloatBlendable: boolean = false

True if blending can be used when rendering to 32-bit floating-point render targets. Note that 16-bit floating-point render targets are always blendable when they are renderable.

textureFloatFilterable

readonly textureFloatFilterable: boolean = false

True if filtering can be applied when sampling float textures.

textureFloatRenderable

readonly textureFloatRenderable: boolean

True if 32-bit floating-point textures can be used as a frame buffer.

textureHalfFloatRenderable

readonly textureHalfFloatRenderable: boolean

True if 16-bit floating-point textures can be used as a frame buffer.

textureRG11B10Renderable

readonly textureRG11B10Renderable: boolean = false

True if small-float textures with format PIXELFORMAT_111110F can be used as a frame buffer. This is always true on WebGL2, but optional on WebGPU device.

Accessors

deviceType

get deviceType(): "webgl2" | "webgpu"

Gets the type of the device. Can be:

fullscreen

get fullscreen(): boolean
set fullscreen(fullscreen: boolean)

Gets whether the device is currently in fullscreen mode.

height

get height(): number

Height of the back buffer in pixels.

indirectDispatchBuffer

get indirectDispatchBuffer(): StorageBuffer | null

Returns the buffer used to store arguments for indirect compute dispatch calls. The size of the buffer is controlled by the maxIndirectDispatchCount property. This buffer can be passed to a Compute shader along with a slot obtained by calling getIndirectDispatchSlot, in order to prepare indirect dispatch parameters.

Only available on WebGPU, returns null on other platforms.

indirectDrawBuffer

get indirectDrawBuffer(): StorageBuffer | null

Returns the buffer used to store arguments for indirect draw calls. The size of the buffer is controlled by the maxIndirectDrawCount property. This buffer can be passed to a Compute shader along with a slot obtained by calling getIndirectDrawSlot, in order to prepare indirect draw parameters. Also see MeshInstance#setIndirect.

Only available on WebGPU, returns null on other platforms.

maxPixelRatio

get maxPixelRatio(): number
set maxPixelRatio(ratio: number)

Gets the maximum pixel ratio.

width

get width(): number

Width of the back buffer in pixels.

Methods

computeDispatch

computeDispatch(computes: Compute[], name?: string): void

Dispatch multiple compute shaders inside a single compute shader pass.

Parameters

destroy

destroy(): void

Destroy the graphics device.

getIndirectDispatchSlot

getIndirectDispatchSlot(count?: number): number

Retrieves the first available slot in the indirectDispatchBuffer used for indirect compute dispatch, which can be utilized by a Compute shader to generate indirect dispatch parameters for another compute shader.

When reserving multiple consecutive slots, specify the optional count parameter.

Parameters

Returns number: - The first reserved slot index used for indirect dispatch.

getIndirectDrawSlot

getIndirectDrawSlot(count?: number): number

Retrieves the first available slot in the indirectDrawBuffer used for indirect rendering, which can be utilized by a Compute shader to generate indirect draw parameters and by MeshInstance#setIndirect to configure indirect draw calls.

When reserving multiple consecutive slots, specify the optional count parameter.

Only available on WebGPU, see GraphicsDevice#supportsIndirectDraw. Returns 0 on other platforms.

Parameters

Returns number: - The first reserved slot index used for indirect rendering.

getRenderableHdrFormat

getRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefined

Get a renderable HDR pixel format supported by the graphics device.

Note:

Parameters

Returns number | undefined: The first supported renderable HDR format or undefined if none is supported.

getRenderTarget

getRenderTarget(): RenderTarget

Queries the currently set render target on the device.

Returns RenderTarget: The current render target.

Example

// Get the current render target
const renderTarget = device.getRenderTarget();

postInit

postInit(): void

Function that executes after the device has been created.

setBlendColor

setBlendColor(r: number, g: number, b: number, a: number): void

Sets the constant blend color and alpha values used with BLENDMODE_CONSTANT and BLENDMODE_ONE_MINUS_CONSTANT factors specified in BlendState. Defaults to [0, 0, 0, 0].

Parameters

setBlendState

setBlendState(blendState: BlendState): void

Sets the specified blend state.

Parameters

setCullMode

setCullMode(cullMode: number): void

Controls how triangles are culled based on their face direction. The default cull mode is CULLFACE_BACK.

Parameters

setDepthState

setDepthState(depthState: DepthState): void

Sets the specified depth state.

Parameters

setDrawStates

setDrawStates(blendState?: BlendState, depthState?: DepthState, cullMode?: number, frontFace?: number, stencilFront?: StencilParameters, stencilBack?: StencilParameters): void

Sets all draw-related render states in a single call. All parameters have sensible defaults for utility rendering (full-screen quads, particles, etc.), so calling setDrawStates() with no arguments resets to a safe baseline.

Parameters

setFrontFace

setFrontFace(frontFace: number): void

Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is FRONTFACE_CCW.

Parameters

setRenderTarget

setRenderTarget(renderTarget: RenderTarget | null): void

Sets the specified render target on the device. If null is passed as a parameter, the back buffer becomes the current target for all rendering operations.

Parameters

Example

// Set a render target to receive all rendering output
device.setRenderTarget(renderTarget);

// Set the back buffer to receive all rendering output
device.setRenderTarget(null);

setStencilState

setStencilState(stencilFront?: StencilParameters, stencilBack?: StencilParameters): void

Sets the specified stencil state. If both stencilFront and stencilBack are null, stencil operation is disabled.

Parameters

validateAttributes

protected validateAttributes(shader: Shader, vertexBuffers: (VertexBuffer | null | undefined)[]): void

Validate that all attributes required by the shader are present in the currently assigned vertex buffers.

Parameters

Inherited from EventHandler

GSplatComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/gsplat/component.js#L71

The GSplatComponent enables an Entity to render 3D Gaussian Splats. Splats are always loaded from Assets rather than being created programmatically. The asset type is gsplat which supports multiple file formats including .ply, .sog, .meta.json (SOG format), and .lod-meta.json (streaming LOD format).

You should never need to use the GSplatComponent constructor directly. To add a GSplatComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('gsplat', {
    asset: asset
});

Once the GSplatComponent is added to the entity, you can access it via the Entity#gsplat property:

entity.gsplat.customAabb = new BoundingBox(new Vec3(), new Vec3(10, 10, 10));

console.log(entity.gsplat.customAabb);

Relevant Engine API examples:

Accessors

asset

get asset(): number | Asset<string>
set asset(value: number | Asset<string>)

Gets the gsplat asset id for this gsplat component.

castShadows

get castShadows(): boolean
set castShadows(value: boolean)

Gets whether gsplat will cast shadows for lights that have shadow casting enabled.

customAabb

get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)

Gets the custom object space bounding box for visibility culling of the attached gsplat. Returns the custom AABB if set, otherwise falls back to the resource's AABB.

id

get id(): number

Gets the unique identifier for this component. This ID is used by the picking system and is also written to the work buffer when app.scene.gsplat.enableIds is enabled, making it available to custom shaders for effects like highlighting or animation.

layers

get layers(): number[]
set layers(value: number[])

Gets the array of layer IDs (Layer#id) to which this gsplat belongs.

lodBaseDistance

get lodBaseDistance(): number
set lodBaseDistance(value: number)

Gets the base distance for the first LOD transition.

lodMultiplier

get lodMultiplier(): number
set lodMultiplier(value: number)

Gets the geometric multiplier between successive LOD distance thresholds.

lodRangeMax

get lodRangeMax(): number
set lodRangeMax(value: number)

Gets the maximum allowed LOD index.

lodRangeMin

get lodRangeMin(): number
set lodRangeMin(value: number)

Gets the minimum allowed LOD index.

resource

get resource(): GSplatResourceBase | null
set resource(value: GSplatResourceBase | null)

Gets the GSplat resource. Returns the directly set resource if available, otherwise returns the resource from the assigned asset.

workBufferUpdate

get workBufferUpdate(): number
set workBufferUpdate(value: number)

Gets the work buffer update mode.

Methods

deleteParameter

deleteParameter(name: string): void

Deletes a shader parameter previously set with setParameter.

Parameters

getInstanceTexture

getInstanceTexture(name: string): Texture | null

Gets an instance texture by name. Instance textures are per-component textures defined in the resource's format with storage: GSPLAT_STREAM_INSTANCE.

Parameters

Returns Texture | null: The texture, or null if not found.

Example

// Add an instance stream to the resource format
resource.format.addExtraStreams([
    { name: 'instanceTint', format: PIXELFORMAT_RGBA8, storage: GSPLAT_STREAM_INSTANCE }
]);

// Get the instance texture and fill it with data
const texture = entity.gsplat.getInstanceTexture('instanceTint');
if (texture) {
    const data = texture.lock();
    // Fill texture data...
    texture.unlock();
}

getParameter

getParameter(name: string): number | number[] | ArrayBufferView<ArrayBufferLike> | undefined

Gets a shader parameter value previously set with setParameter.

Parameters

Returns number | number[] | ArrayBufferView<ArrayBufferLike> | undefined: The parameter value, or undefined if not set.

hide

hide(): void

Stop rendering this component without removing its mesh instance from the scene hierarchy.

setParameter

setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void

Sets a shader parameter for this gsplat instance. Parameters set here are applied during rendering.

Parameters

setWorkBufferModifier

setWorkBufferModifier(value: { glsl?: string; wgsl?: string } | null): void

Sets custom shader code for modifying splats when written to the work buffer.

Must provide all three functions:

Calling this method automatically triggers a work buffer re-render.

Parameters

Example

entity.gsplat.setWorkBufferModifier({
    glsl: `
        void modifySplatCenter(inout vec3 center) {}
        void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) {}
        void modifySplatColor(vec3 center, inout vec4 color) { color.rgb *= vec3(1.0, 0.0, 0.0); }
    `,
    wgsl: `
        fn modifySplatCenter(center: ptr<function, vec3f>) {}
        fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) {}
        fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) { (*color).r = 1.0; (*color).g = 0.0; (*color).b = 0.0; }
    `
});

show

show(): void

Enable rendering of the component if hidden using hide.

Inherited from Component

GSplatComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/gsplat/system.js#L65

Manages the GSplatComponents of an application. Reach it through app.systems.gsplat; components are created with Entity#addComponent, never by calling the system directly.

Methods

getMaterial

getMaterial(camera: Camera, layer: Layer): ShaderMaterial | null

Gets the GSplat material for the given camera and layer.

Returns null if the material hasn't been created yet. Materials are created during the first frame update when the GSplat is rendered. To be notified immediately when materials are created, listen to the 'material:created' event on GSplatComponentSystem:

Parameters

Returns ShaderMaterial | null: The material, or null if not created yet.

Example

app.systems.gsplat.on('material:created', (material, camera, layer) => {
    // Material is now available
    material.setParameter('myParam', value);
});

Events

EVENT_FRAMEREADY

static EVENT_FRAMEREADY: string = 'frame:ready'

Fired every frame for each camera and layer combination rendering GSplats. The handler is passed the CameraComponent, the Layer, a boolean indicating if the current frame has up-to-date sorting, and a number indicating how many resources are loading.

The ready parameter indicates whether the current frame reflects all recent changes (camera movement, splat transforms, lod updates, etc.) with the latest sorting applied. The loadingCount parameter reports the total number of octree LOD resources currently loading or queued to load.

This event is useful for video capture or other workflows that need to wait for frames to be fully ready. Only capture frames and move camera to next position when both ready === true and loadingCount === 0. Note that loadingCount can be used as a boolean in conditionals (0 is falsy, non-zero is truthy) for backward compatibility.

Example

// Wait for frame to be ready before capturing
app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => {
    if (ready && !loadingCount) {
        console.log(`Frame ready to capture for camera ${camera.entity.name}`);
        // Capture frame here
    }
});

Example

// Track loading progress (0..1)
let maxLoadingCount = 0;
app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => {
    maxLoadingCount = Math.max(maxLoadingCount, loadingCount);
    const progress = maxLoadingCount > 0 ? (maxLoadingCount - loadingCount) / maxLoadingCount : 1;
    console.log(`Loading progress: ${(progress * 100).toFixed(1)}%`);
});

EVENT_FRAMEREQUEST

static EVENT_FRAMEREQUEST: string = 'frame:request'

Fired once per frame, after the component/script updates and before rendering, when GSplat streaming has produced new data that a render would show (newly streamed octree LOD) or a CPU sort result is ready to be applied. This drives on-demand rendering for apps that run with AppBase#autoRender set to false: a typical handler sets AppBase#renderNextFrame so the new data is shown.

Streaming (LOD evaluation, file loading) runs every frame regardless of autoRender, so the scene keeps loading in the background; this event tells you when it's worth rendering.

Note: this event covers streaming changes only. Changes you make yourself — moving the camera, modifying the scene, or adding, removing, or changing properties of gsplat components — should trigger a render yourself.

Example

app.autoRender = false;
app.systems.gsplat.on('frame:request', () => {
    app.renderNextFrame = true;
});

EVENT_MATERIALCREATED

static EVENT_MATERIALCREATED: string = 'material:created'

Fired when a GSplat material is created for a camera and layer combination. Materials are created during the first frame update when the GSplat is rendered. The handler is passed the ShaderMaterial, the CameraComponent, and the Layer.

This event is useful for setting up custom material chunks and parameters before the first render.

Example

app.systems.gsplat.on('material:created', (material, camera, layer) => {
    console.log(`Material created for camera ${camera.entity.name} on layer ${layer.name}`);
    // Set custom material parameters before first render
    material.setParameter('myParam', value);
});

Inherited from ComponentSystem

GSplatContainer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-container.js#L66

A container for procedural Gaussian Splat data. This class allows you to create splat data programmatically using either a built-in format or a custom format with your own texture streams and read code.

A default format is provided via GSplatFormat.createDefaultFormat which uses float textures for easy CPU population.

Example

// Example 1: Using the default format (easy CPU population)
const format = GSplatFormat.createDefaultFormat(device);
const container = new GSplatContainer(device, 100, format);

// Float format textures are straightforward to fill
const centerTex = container.getTexture('dataCenter');
const pixels = centerTex.lock();
// pixels is Float32Array, fill with [x, y, z, 0, x, y, z, 0, ...]
centerTex.unlock();

// Set bounding box
container.aabb = new BoundingBox();

// fill centers only if you need CPU sorting
container.centers.set([x0, y0, z0, x1, y1, z1, ...]);  // xyz per splat

// Add to scene
entity.addComponent('gsplat', { resource: container });

Example

// Example 2: Using a custom format
const format = new GSplatFormat(device, [
    { name: 'data', format: PIXELFORMAT_RGBA32F }
], {
    // Shader code to read splat attributes from the texture
    readGLSL: `
        vec4 d = loadData();
        splatCenter = d.xyz;
        splatColor = vec4(1.0);
        splatScale = vec3(d.w);
        splatRotation = vec4(0, 0, 0, 1);
    `,
    readWGSL: `
        let d = loadData();
        splatCenter = d.xyz;
        splatColor = vec4f(1.0);
        splatScale = vec3f(d.w);
        splatRotation = vec4f(0, 0, 0, 1);
    `
});

const container = new GSplatContainer(device, 100, format);

Constructors

constructor

new GSplatContainer(device: GraphicsDevice, maxSplats: number, format: GSplatFormat)

Creates a new GSplatContainer instance.

Parameters

Accessors

centers

get centers(): Float32Array<ArrayBufferLike>
set centers(value: Float32Array<ArrayBufferLike>)

CPU-side splat center positions (xyz per splat), or null when not built for this resource.

maxSplats

get maxSplats(): number

Maximum number of splats this container can hold.

numSplats

get numSplats(): number

Gets the number of splats to render.

Methods

update

update(numSplats?: number, centersUpdated?: boolean): void

Updates the container after modifying texture data and centers. Call this after filling data to signal that the container contents have changed.

Parameters

Inherited from GSplatResourceBase

GSplatFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-format.js#L89

Gsplat resources store per-splat data (positions, colors, rotations, scales, spherical harmonics) in GPU textures. This class describes those texture streams and generates the shader code needed to access them.

Each stream defines a texture with a name and pixel format. The class automatically generates shader declarations (uniforms/samplers) and load functions (e.g. loadColor()) for each stream. A read shader can be provided to define how splat attributes are extracted from these textures.

Users can add extra streams via addExtraStreams for custom per-splat data. These can be per-resource (shared across instances) or per-instance (unique to each gsplat component).

For loaded gsplat resources, base streams are automatically configured based on the loaded data format. For GSplatContainer, users define both base and extra streams to specify the complete data layout.

Constructors

constructor

new GSplatFormat(device: GraphicsDevice, streams: GSplatStreamDescriptor[], options: object)

Creates a new GSplatFormat instance.

Parameters

Properties

streams

readonly streams: GSplatStreamDescriptor[]

Array of stream descriptors.

Accessors

extraStreams

get extraStreams(): GSplatStreamDescriptor[]

Gets the extra streams array. Streams can only be added via addExtraStreams, not removed. Do not modify the returned array directly.

Methods

addExtraStreams

addExtraStreams(streams: GSplatStreamDescriptor[]): void

Adds additional texture streams for custom gsplat data. Each stream defines a texture that can store extra information, accessible in shaders via generated load functions. Streams with storage: GSPLAT_STREAM_INSTANCE are created per gsplat component instance, while others are shared across all instances of the same resource.

Note: Streams cannot be removed once added currently.

Parameters

createDefaultFormat

static createDefaultFormat(device: GraphicsDevice): GSplatFormat

Creates a default format using 32F/16F textures, simple to use for CPU data population. This format can be rendered to by GSplatProcessor when supported. Check GraphicsDevice#textureFloatRenderable (for RGBA32F) and GraphicsDevice#textureHalfFloatRenderable (for RGBA16F).

The format stores:

Parameters

Returns GSplatFormat: The default format.

createSimpleFormat

static createSimpleFormat(device: GraphicsDevice): GSplatFormat

Creates a simple format with uniform-scale splats and no rotation. Streams:

Parameters

Returns GSplatFormat: The simple format.

GSplatParams

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-params.js#L40

Parameters for the GSplat system.

Constructors

constructor

new GSplatParams(device: GraphicsDevice)

Creates a new GSplatParams instance.

Parameters

Properties

colorRampIntensity

colorRampIntensity: number = 1

Intensity multiplier for overdraw visualization mode. Value of 1 uses alpha of 1/32, allowing approximately 32 overdraws to reach full brightness with additive blending. Higher values increase brightness per splat. Defaults to 1.

colorUpdateAngle

colorUpdateAngle: number = 10

Viewing angle threshold in degrees for triggering spherical harmonics color updates. When the camera translates enough to change the viewing angle to an octree node or splat by this amount, its SH colors are re-evaluated. Distant nodes naturally update less frequently since they require more camera movement to reach the angle threshold. An orthographic camera views all splats along its forward direction, so their colors are re-evaluated together once the camera rotates by this amount, and moving it has no effect. Set to 0 to update every frame where camera moves. Defaults to 10.

cooldownTicks

cooldownTicks: number = 100

Number of update ticks before unloading unused streamed resources. When a streamed resource's reference count reaches zero, it enters a cooldown period before being unloaded. This allows recently used data to remain in memory for quick reuse if needed again soon. Set to 0 to unload immediately when unused. Defaults to 100.

dither

dither: string = DITHER_BLUENOISE

The noise pattern the coverage of a GSplatParams#stochastic splat is dithered against, ignored when stochastic is false. Can be:

Defaults to DITHER_BLUENOISE, which looks best under temporal anti-aliasing. DITHER_NONE is not a coverage pattern, so it is not accepted here - turn stochastic off instead.

lodUpdateAngle

lodUpdateAngle: number = 90

Angle threshold in degrees to trigger LOD updates based on camera rotation. Set to 0 to disable rotation-based updates. Rotation only affects LOD through lodBehindPenalty, so rotation-based updates also stop when the penalty is 1. Defaults to 90.

lodUpdateDistance

lodUpdateDistance: number = 1

Distance threshold in world units to trigger LOD updates for camera and gsplat instances. Defaults to 1.

radialSorting

radialSorting: boolean = false

Enables radial sorting based on distance from camera (for cubemap rendering). When false, uses directional sorting along camera forward vector. Defaults to false.

Note: Radial sorting helps reduce sorting artifacts when the camera rotates (looks around), while linear sorting is better at minimizing artifacts when the camera translates (moves).

sceneDepthWrite

sceneDepthWrite: boolean = false

Whether the gaussian splats contribute to the scene depth, which the volumetric fog and the depth of field need in order to be bounded by the splats instead of drawing through them.

This costs an extra full screen render target, and so defaults to false. Enable it for a scene where the splats need to take part in those effects. Requires the camera to render using CameraFrame - see CameraFrame.isSplatSceneDepthSupported.

On some devices enabling this stores the scene depth at a lower precision, which the other effects using it share. The depth stays accurate over camera clip distances of roughly 0.000015 to 16384 there; past the far end of that a distant depth loses accuracy, and the pixels nothing covers stop reading as far away as they are. Keep the far clip inside that range on those devices, or leave the effects which read the depth off.

stochastic

stochastic: boolean = false

Enables stochastic alpha rendering on the WebGPU GPU-sort renderer. Splats are drawn without sorting, using dithered coverage, opaque blending and depth writes. Ignored by the CPU-sort renderer. Picking continues to use sorted rendering. Defaults to false. Applications can customize the sampling through the material's opacityDitherPS chunk.

useFog

useFog: boolean = true

Whether to apply scene fog to Gaussian splats. When false, splats ignore fog settings even if the scene or camera has fog configured. Defaults to true.

useTonemap

useTonemap: boolean = true

Whether to apply the camera's tonemapping and the scene exposure to Gaussian splats. When false, splats render with their stored colors, unaffected by Scene#exposure and the camera's CameraComponent#toneMapping. Fog, when enabled, still applies. Defaults to true.

Accessors

alphaClip

get alphaClip(): number
set alphaClip(value: number)

Gets the alpha threshold for shadow, pick, and prepass rendering.

alphaClipForward

get alphaClipForward(): number
set alphaClipForward(value: number)

Gets the forward-pass alpha threshold.

antiAlias

get antiAlias(): boolean
set antiAlias(value: boolean)

Gets whether anti-aliasing compensation is enabled.

colorizeColorUpdate

get colorizeColorUpdate(): boolean
set colorizeColorUpdate(value: boolean)

Deprecated: Use debug with GSPLAT_DEBUG_SH_UPDATE instead.

colorRamp

get colorRamp(): Texture | null
set colorRamp(value: Texture | null)

Gets the color ramp texture for overdraw visualization.

currentRenderer

get currentRenderer(): number

The current rendering pipeline in effect after platform-based fallback resolution. When renderer is set to a mode requiring WebGPU on a WebGL device, this returns the fallback mode actually being used.

dataFormat

get dataFormat(): string
set dataFormat(value: string)

Gets the work buffer data format.

debug

get debug(): number
set debug(value: number)

Gets the debug rendering mode for Gaussian splats.

enableIds

get enableIds(): boolean
set enableIds(value: boolean)

Gets the ID storage enabled state.

fisheye

get fisheye(): number
set fisheye(value: number)

Gets the fisheye projection strength.

format

get format(): GSplatFormat

Format descriptor for work buffer streams. Describes the textures used by the work buffer for intermediate storage during rendering. Users can add extra streams via GSplatFormat#addExtraStreams for custom per-splat data.

Example

// Add a custom stream to store per-splat component IDs
app.scene.gsplat.format.addExtraStreams([{
    name: 'splatId',
    format: PIXELFORMAT_R32U
}]);

foveationCenter

get foveationCenter(): number
set foveationCenter(value: number)

Gets the protected centre radius for foveated contribution culling.

foveationStrength

get foveationStrength(): number
set foveationStrength(value: number)

Gets the foveated contribution culling strength.

lodBehindPenalty

get lodBehindPenalty(): number
set lodBehindPenalty(value: number)

Gets behind-camera LOD penalty multiplier.

lodUnderfillLimit

get lodUnderfillLimit(): number
set lodUnderfillLimit(value: number)

Gets the maximum allowed underfill LOD range.

material

get material(): ShaderMaterial

A material template that can be customized by the user. Any defines, parameters, or shader chunks set on this material will be automatically applied to all GSplat components. After making changes, call Material#update to for the changes to be applied on the next frame.

Example

// Set a custom parameter on all GSplat materials
app.scene.gsplat.material.setParameter('myCustomParam', 1.0);
app.scene.gsplat.material.update();

minContribution

get minContribution(): number
set minContribution(value: number)

Gets the minimum contribution threshold.

minPixelSize

get minPixelSize(): number
set minPixelSize(value: number)

Gets the minimum pixel size threshold.

renderer

get renderer(): number
set renderer(value: number)

Gets the requested rendering pipeline for gaussian splatting. This may differ from currentRenderer when a WebGPU mode falls back on a WebGL device.

splatBudget

get splatBudget(): number
set splatBudget(value: number)

Gets the number of splats across all GSplats in the scene.

splatBudgetMode

get splatBudgetMode(): string
set splatBudgetMode(value: string)

Gets how the splat budget is used.

twoDimensional

get twoDimensional(): boolean
set twoDimensional(value: boolean)

Gets whether 2D Gaussian Splatting mode is enabled.

varyings

get varyings(): GSplatVaryings

Custom varying streams for the gsplat render customization: per-splat values written by the gsplatModifyVS shader chunk and read per fragment by the gsplatModifyPS shader chunk. See GSplatVaryings.

Example

// Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value),
// and read per fragment in gsplatModifyPS using getFlag()
app.scene.gsplat.varyings.add([{
    name: 'flag',
    type: TYPE_UINT32,
    components: 1
}]);

GSplatProcessor

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/gsplat/gsplat-processor.js#L104

GSplatProcessor enables GPU-based processing of Gaussian Splat data using custom shader code. Gaussian Splats store per-splat attributes (position, rotation, scale, color, spherical harmonics) in texture streams. This processor reads from source streams and writes results to destination streams, enabling operations like painting, selection marking, or custom data transforms.

Custom streams can be added to loaded gsplat resources via GSplatFormat#addExtraStreams, or you can create fully procedural splat data using GSplatContainer.

The source and destination can reference the same resource or component, as long as the read and write streams don't overlap (you cannot read and write the same stream in one pass).

By default (when source streams are not specified), the processor provides access to the format's built-in getCenter(), getRotation(), getScale(), and getColor() functions for reading splat data. Note: getCenter() must be called first as it loads shared data used by the other functions.

Custom uniforms can be passed to the shader via setParameter, including scalar values, vectors, and additional textures for effects like brush patterns or lookup tables.

The following built-in uniforms are available in processing shaders:

Example

// Create a processor that reads splat positions and writes to a customColor texture
const processor = new GSplatProcessor(
    app.graphicsDevice,
    { component: entity.gsplat },  // source: all streams auto-bound
    { component: entity.gsplat, streams: ['customColor'] }, // destination: customColor stream only
    {
        processGLSL: `
            uniform vec4 uPaintSphere;
            uniform vec4 uPaintColor;

            void process() {
                vec3 center = getCenter();
                float dist = distance(center, uPaintSphere.xyz);
                if (dist < uPaintSphere.w) {
                    writeCustomColor(uPaintColor);
                } else {
                    writeCustomColor(vec4(0.0));
                }
            }
        `,
        processWGSL: `
            uniform uPaintSphere: vec4f;
            uniform uPaintColor: vec4f;

            fn process() {
                let center = getCenter();
                let dist = distance(center, uniform.uPaintSphere.xyz);
                if (dist < uniform.uPaintSphere.w) {
                    writeCustomColor(uniform.uPaintColor);
                } else {
                    writeCustomColor(vec4f(0.0));
                }
            }
        `
    }
);

// Set uniforms and execute
processor.setParameter('uPaintSphere', [0, 1, 0, 0.5]);
processor.setParameter('uPaintColor', [1, 0, 0, 1]);
processor.process();

Constructors

constructor

new GSplatProcessor(device: GraphicsDevice, source: GSplatProcessorBinding, destination: GSplatProcessorBinding, options: object)

Creates a new GSplatProcessor instance.

Parameters

Properties

blendState

blendState: BlendState = BlendState.NOBLEND

The blend state to use when processing. Allows accumulation of results (e.g., additive blending for painting). Defaults to no blending.

Methods

deleteParameter

deleteParameter(name: string): void

Removes a shader parameter.

Parameters

destroy

destroy(): void

Destroys this processor and releases all resources.

getParameter

getParameter(name: string): number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer | undefined

Gets a shader parameter value previously set with setParameter.

Parameters

Returns number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer | undefined: The parameter value, or undefined if not set.

process

process(): void

Executes the processing, reading from source streams and writing to destination streams.

setParameter

setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void

Sets a shader parameter for this processor. Parameters are applied during processing.

Parameters

GSplatVaryings

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-varyings.js#L89

Manages custom varying streams for the gsplat render customization. Streams added here generate set functions available to the gsplatModifyVS shader chunk, where they run once per splat, and matching get functions available to the gsplatModifyPS shader chunk, where the per-splat value can be read for each rendered fragment.

Access the instance via GSplatParams#varyings.

Accessors

streams

get streams(): GSplatVaryingDescriptor[]

Gets the varying stream descriptors. Do not modify the returned array.

Methods

add

add(streams: GSplatVaryingDescriptor[]): void

Adds varying streams. For each stream, a set function (set<Name>) is generated and made available to the gsplatModifyVS shader chunk, where it runs once per splat, and a matching get function (get<Name>) is made available to the gsplatModifyPS shader chunk, where the per-splat value can be read for each rendered fragment.

Supported types are TYPE_FLOAT32, TYPE_INT32 and TYPE_UINT32, with 1 to 4 components. Adding or removing streams rebuilds the gsplat shaders.

Note: on some platforms each component is stored in per-splat video memory, so its size scales with the number of rendered splats. Keep the data as compact as possible - prefer fewer components, and consider bit-packing multiple small values into a single uint component instead of using separate streams.

Parameters

Example

// Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value),
// and read per fragment in gsplatModifyPS using getFlag()
app.scene.gsplat.varyings.add([{
    name: 'flag',
    type: TYPE_UINT32,
    components: 1
}]);

remove

remove(names: string[]): void

Removes varying streams previously added by GSplatVaryings#add.

Parameters

ImgParser

Class · extends TextureParser · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/texture/img.js#L20

Parser for browser-supported image formats.

Methods

load

load(url: any, callback: any, asset: any): void

Load the texture from the remote URL. When loaded (or failed), use the callback to return an the raw resource data (or error).

Parameters

open

open(url: any, data: any, device: any, textureOptions?: {}): Texture

Convert raw resource data into a Texture.

Parameters

Returns Texture: The parsed resource data.

IndexBuffer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/index-buffer.js#L23

An index buffer stores index values into a VertexBuffer. Indexed graphical primitives can normally utilize less memory that unindexed primitives (if vertices are shared).

Typically, index buffers are set on Mesh objects.

Constructors

constructor

new IndexBuffer(graphicsDevice: GraphicsDevice, format: number, numIndices: number, usage?: number, initialData?: ArrayBuffer | ArrayBufferView<ArrayBufferLike>, options?: object)

Create a new IndexBuffer instance.

Parameters

Example

// Create an index buffer holding 3 16-bit indices. The buffer is marked as
// static, hinting that the buffer will never be modified.
const indices = new Uint16Array([0, 1, 2]);
const indexBuffer = new IndexBuffer(graphicsDevice,
                                       INDEXFORMAT_UINT16,
                                       3,
                                       BUFFER_STATIC,
                                       indices);

Methods

destroy

destroy(): void

Frees resources associated with this index buffer.

getFormat

getFormat(): number

Returns the data format of the specified index buffer.

Returns number: The data format of the specified index buffer. Can be:

getNumIndices

getNumIndices(): number

Returns the number of indices stored in the specified index buffer.

Returns number: The number of indices stored in the specified index buffer.

lock

lock(): ArrayBuffer | ArrayBufferView<ArrayBufferLike>

Gives access to the block of memory that stores the buffer's indices.

Returns ArrayBuffer | ArrayBufferView<ArrayBufferLike>: The memory that stores the buffer's indices. This matches whatever was supplied as the initial data: an ArrayBuffer when none was provided, otherwise the ArrayBuffer or typed array that was passed in. Use ArrayBufferConstructor.isView to distinguish the two before accessing it.

unlock

unlock(byteOffset?: number, byteLength?: number): void

Uploads the client side copy of the index buffer to the GPU. When called without arguments, uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. The first upload always initializes the entire GPU buffer, regardless of the requested range. A zero byte length does nothing, including before the first upload.

Partial uploads do not resize the buffer or change its CPU storage. The caller must upload every modified range before expecting those changes on the GPU. Context restoration uploads the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion in debug builds.

Parameters

Example

// After modifying bytes 16 through 31 of the CPU storage:
indexBuffer.unlock(16, 16);

Layer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/layer.js#L93

A Layer represents a renderable subset of the scene. It can contain a list of mesh instances, lights and cameras, their render settings and also defines custom callbacks before, after or during rendering. Layers are organized inside LayerComposition in a desired order.

A mesh instance is drawn through the layers it belongs to, and a camera draws only the layers listed in CameraComponent#layers. Components place their mesh instances by layer id, for example through RenderComponent#layers, and lights through LightComponent#layers; mesh instances you create yourself go in with addMeshInstances and out with removeMeshInstances.

The application creates five layers, reachable by id from Scene#layers: LAYERID_WORLD for the scene itself, LAYERID_DEPTH, LAYERID_SKYBOX, LAYERID_IMMEDIATE for debug drawing and LAYERID_UI. Within a layer, opaque and transparent mesh instances are drawn as two separate parts, ordered by opaqueSortMode and transparentSortMode, and the composition decides where each part falls in the frame. Set enabled to false to skip a layer entirely, and use onEnable and onDisable to react to that.

Example

// Draw a set of mesh instances in a layer of their own, right after the world's opaque objects
const layers = app.scene.layers;
const layer = new Layer({ name: 'Overlay' });
const world = layers.getLayerById(LAYERID_WORLD);
layers.insert(layer, layers.getOpaqueIndex(world) + 1);
layer.addMeshInstances(meshInstances);

Constructors

constructor

new Layer(options?: any)

Create a new Layer instance.

Parameters

Properties

id

id: number

A unique ID of the layer. Layer IDs are stored inside ModelComponent#layers, RenderComponent#layers, CameraComponent#layers, LightComponent#layers and ElementComponent#layers instead of names. Can be used in LayerComposition#getLayerById.

name

name: string

Name of the layer. Can be used in LayerComposition#getLayerByName.

onDisable

onDisable: Function

Custom function that is called after the layer has been disabled. This happens when:

onEnable

onEnable: Function

Custom function that is called after the layer has been enabled. This happens when:

opaqueSortMode

opaqueSortMode: number = SORTMODE_MATERIALMESH

Defines the method used for sorting opaque (that is, not semi-transparent) mesh instances before rendering. Can be:

Defaults to SORTMODE_MATERIALMESH.

transparentSortMode

transparentSortMode: number = SORTMODE_BACK2FRONT

Defines the method used for sorting semi-transparent mesh instances before rendering. Can be:

Defaults to SORTMODE_BACK2FRONT.

Accessors

clearColorBuffer

get clearColorBuffer(): boolean
set clearColorBuffer(val: boolean)

Gets whether the camera will clear the color buffer when it renders this layer.

clearDepthBuffer

get clearDepthBuffer(): boolean
set clearDepthBuffer(val: boolean)

Gets whether the camera will clear the depth buffer when it renders this layer.

clearStencilBuffer

get clearStencilBuffer(): boolean
set clearStencilBuffer(val: boolean)

Gets whether the camera will clear the stencil buffer when it renders this layer.

enabled

get enabled(): boolean
set enabled(val: boolean)

Gets the enabled state of the layer.

Methods

addCamera

addCamera(camera: CameraComponent): void

Adds a camera to this layer.

Parameters

addLight

addLight(light: LightComponent): void

Adds a light to this layer.

Parameters

addMeshInstances

addMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void

Adds an array of mesh instances to this layer.

Parameters

addShadowCasters

addShadowCasters(meshInstances: MeshInstance[]): void

Adds an array of mesh instances to this layer, but only as shadow casters (they will not be rendered anywhere, but only cast shadows on other objects).

Parameters

clearCameras

clearCameras(): void

Removes all cameras from this layer.

clearLights

clearLights(): void

Removes all lights from this layer.

clearMeshInstances

clearMeshInstances(skipShadowCasters?: boolean): void

Removes all mesh instances from this layer.

Parameters

removeCamera

removeCamera(camera: CameraComponent): void

Removes a camera from this layer.

Parameters

removeLight

removeLight(light: LightComponent): void

Removes a light from this layer.

Parameters

removeMeshInstances

removeMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void

Removes multiple mesh instances from this layer.

Parameters

removeShadowCasters

removeShadowCasters(meshInstances: MeshInstance[]): void

Removes multiple mesh instances from the shadow casters list of this layer, meaning they will stop casting shadows.

Parameters

LayerComposition

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/composition/layer-composition.js#L41

Layer Composition is a collection of Layer that is fed to Scene#layers to define rendering order.

Each layer is rendered as two parts, its opaque mesh instances and its transparent ones, and layerList holds the sequence of parts in the order they are drawn. push and insert add both parts of a layer together, while pushOpaque, pushTransparent, insertOpaque and insertTransparent place one part at a time, which is how the default composition places the depth and skybox layers between the world's opaque and transparent parts. Look layers up with getLayerById and getLayerByName, find where a part sits with getOpaqueIndex and getTransparentIndex, and take a layer out with remove. The composition fires add and remove as layers come and go.

The composition the application creates ends with the UI layer, so a pushed layer renders after the UI and outside the range a camera's post-processing applies to. To render inside that range, insert at an index taken from getOpaqueIndex or getTransparentIndex.

Example

// Draw decals right after the world's opaque objects and before its transparent ones
const layers = app.scene.layers;
const world = layers.getLayerById(LAYERID_WORLD);
const decals = new Layer({ name: 'Decals' });
layers.insertOpaque(decals, layers.getOpaqueIndex(world) + 1);

Constructors

constructor

new LayerComposition(name?: string)

Create a new layer composition.

Parameters

Properties

layerList

layerList: Layer[] = []

A read-only array of Layer sorted in the order they will be rendered.

subLayerEnabled

subLayerEnabled: boolean[] = []

A read-only array of boolean values, matching layerList. True means the layer is rendered, false means it's skipped.

Methods

getLayerById

getLayerById(id: number): Layer | null

Finds a layer inside this composition by its ID. Null is returned, if nothing is found.

Parameters

Returns Layer | null: The layer corresponding to the specified ID. Returns null if layer is not found.

getLayerByName

getLayerByName(name: string): Layer | null

Finds a layer inside this composition by its name. Null is returned, if nothing is found.

Parameters

Returns Layer | null: The layer corresponding to the specified name. Returns null if layer is not found.

getOpaqueIndex

getOpaqueIndex(layer: Layer): number

Gets index of the opaque part of the supplied layer in the layerList.

Parameters

Returns number: The index of the opaque part of the specified layer, or -1 if it is not part of the composition.

getTransparentIndex

getTransparentIndex(layer: Layer): number

Gets index of the semi-transparent part of the supplied layer in the layerList.

Parameters

Returns number: The index of the semi-transparent part of the specified layer, or -1 if it is not part of the composition.

insert

insert(layer: Layer, index: number): void

Inserts a layer (both opaque and semi-transparent parts) at the chosen index in the layerList.

Parameters

insertOpaque

insertOpaque(layer: Layer, index: number): void

Inserts an opaque part of the layer (non semi-transparent mesh instances) at the chosen index in the layerList.

Parameters

insertTransparent

insertTransparent(layer: Layer, index: number): void

Inserts a semi-transparent part of the layer at the chosen index in the layerList.

Parameters

push

push(layer: Layer): void

Adds a layer (both opaque and semi-transparent parts) to the end of the layerList.

The default composition ends with the UI layer, so a layer pushed here renders after the UI and after the last layer a camera's post-processing applies to. To place a layer inside the post-processed range instead, use LayerComposition#insert with an index from LayerComposition#getOpaqueIndex.

Parameters

pushOpaque

pushOpaque(layer: Layer): void

Adds part of the layer with opaque (non semi-transparent) objects to the end of the layerList.

Parameters

pushTransparent

pushTransparent(layer: Layer): void

Adds part of the layer with semi-transparent objects to the end of the layerList.

Parameters

remove

remove(layer: Layer): void

Removes a layer (both opaque and semi-transparent parts) from layerList.

Parameters

removeOpaque

removeOpaque(layer: Layer): void

Removes an opaque part of the layer (non semi-transparent mesh instances) from layerList.

Parameters

removeTransparent

removeTransparent(layer: Layer): void

Removes a transparent part of the layer from layerList.

Parameters

Inherited from EventHandler

LightComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/light/component.js#L136

The LightComponent enables an Entity to light the scene. There are three types of light:

Directional and spot lights are therefore aimed with the owner entity's rotation, and shine along its negative y-axis - so an unrotated light shines straight down. Note that GraphNode#lookAt orients an entity's negative z-axis, which aims a camera but not a light:

// an unrotated light shines straight down
light.setEulerAngles(0, 0, 0);

// tilted 45 degrees, it shines down and towards negative z
light.setEulerAngles(45, 0, 0);

// to aim it at a target, lookAt orients the negative z-axis and the extra rotation brings the
// negative y-axis onto it
light.lookAt(target.getPosition());
light.rotateLocal(90, 0, 0);

// to aim it along a world space direction, rotate the negative y-axis onto that direction.
// Unlike lookAt, this is well defined even when the direction is straight up or down
const dir = new Vec3(-0.5, -1, -0.3).normalize();
light.setRotation(new Quat().setFromDirections(Vec3.DOWN, dir));

// the direction a light currently shines in is the negative of its world space up vector
const currentDir = light.up.clone().mulScalar(-1);

You should never need to use the LightComponent constructor directly. To add a LightComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('light', {
    type: 'omni',
    color: new Color(1, 0, 0),
    intensity: 2
});

Once the LightComponent is added to the entity, you can access it via the Entity#light property:

entity.light.intensity = 3; // Set the intensity of the light

console.log(entity.light.intensity); // Get the intensity of the light

Relevant Engine API examples:

Accessors

affectDynamic

get affectDynamic(): boolean
set affectDynamic(value: boolean)

Gets whether the light will affect non-lightmapped objects.

affectLightmapped

get affectLightmapped(): boolean
set affectLightmapped(value: boolean)

Gets whether the light will affect lightmapped objects.

affectSpecularity

get affectSpecularity(): boolean
set affectSpecularity(value: boolean)

Gets whether material specularity will be affected by this light.

bake

get bake(): boolean
set bake(value: boolean)

Gets whether the light will be rendered into lightmaps.

bakeArea

get bakeArea(): number
set bakeArea(value: number)

Gets the angular size in degrees of the area used when baking soft shadow boundaries for the directional light into the lightmap.

bakeDir

get bakeDir(): boolean
set bakeDir(value: boolean)

Gets whether the light's direction will contribute to directional lightmaps.

bakeNumSamples

get bakeNumSamples(): number
set bakeNumSamples(value: number)

Gets the number of samples used to bake this light into the lightmap.

cascadeBlend

get cascadeBlend(): number
set cascadeBlend(value: number)

Gets the blend factor for cascaded shadow maps.

cascadeDistribution

get cascadeDistribution(): number
set cascadeDistribution(value: number)

Gets the distribution of subdivision of the camera frustum for individual shadow cascades.

castShadows

get castShadows(): boolean
set castShadows(value: boolean)

Gets whether the light will cast shadows.

color

get color(): Readonly<Color>
set color(value: Readonly<Color>)

Gets the color of the light. Use the setter to update the color.

get cookie(): Texture | null
set cookie(value: Texture | null)

Gets the texture to be used as the cookie for this light.

cookieAngle

get cookieAngle(): number
set cookieAngle(value: number)

Gets the angle for spotlight cookie rotation (in degrees).

cookieAsset

get cookieAsset(): number | null
set cookieAsset(value: number | null)

Gets the id of the texture asset used as the cookie for this light, or null if none is set.

cookieChannel

get cookieChannel(): string
set cookieChannel(value: string)

Gets the color channels of the cookie texture to use.

cookieFalloff

get cookieFalloff(): boolean
set cookieFalloff(value: boolean)

Gets whether normal spotlight falloff is active when a cookie texture is set.

cookieIntensity

get cookieIntensity(): number
set cookieIntensity(value: number)

Gets the cookie texture intensity.

cookieOffset

get cookieOffset(): Vec2 | null
set cookieOffset(value: Vec2 | null)

Gets the spotlight cookie position offset.

cookieScale

get cookieScale(): Vec2 | null
set cookieScale(value: Vec2 | null)

Gets the spotlight cookie scale.

falloffMode

get falloffMode(): number
set falloffMode(value: number)

Gets the fall off mode for the light.

innerConeAngle

get innerConeAngle(): number
set innerConeAngle(value: number)

Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) at which the spotlight cone starts to fade off.

intensity

get intensity(): number
set intensity(value: number)

Gets the brightness of the light.

isStatic

get isStatic(): boolean
set isStatic(value: boolean)

Gets whether the light ever moves.

layers

get layers(): readonly number[]
set layers(value: readonly number[])

Gets the array of layer IDs (Layer#id) to which this light should belong.

luminance

get luminance(): number
set luminance(value: number)

Gets the physically-based luminance.

mask

get mask(): number
set mask(value: number)

Gets the mask to determine which MeshInstances are lit by this light.

normalOffsetBias

get normalOffsetBias(): number
set normalOffsetBias(value: number)

Gets the normal offset depth bias.

numCascades

get numCascades(): number
set numCascades(value: number)

Gets the number of shadow cascades.

outerConeAngle

get outerConeAngle(): number
set outerConeAngle(value: number)

Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) at which the spotlight cone has faded to nothing.

penumbraFalloff

get penumbraFalloff(): number
set penumbraFalloff(value: number)

Gets the falloff rate for shadow penumbra for contact hardening shadows.

penumbraSize

get penumbraSize(): number
set penumbraSize(value: number)

Gets the size of penumbra for contact hardening shadows.

range

get range(): number
set range(value: number)

Gets the range of the light.

shadowBias

get shadowBias(): number
set shadowBias(value: number)

Get the depth bias for tuning the appearance of the shadow mapping generated by this light.

shadowBlockerSamples

get shadowBlockerSamples(): number
set shadowBlockerSamples(value: number)

Gets the number of blocker samples used for contact hardening shadows.

shadowDistance

get shadowDistance(): number
set shadowDistance(value: number)

Gets the distance from the viewpoint beyond which shadows are no longer rendered.

shadowIntensity

get shadowIntensity(): number
set shadowIntensity(value: number)

Gets the intensity of the shadow darkening.

shadowResolution

get shadowResolution(): number
set shadowResolution(value: number)

Gets the size of the texture used for the shadow map.

shadowSamples

get shadowSamples(): number
set shadowSamples(value: number)

Gets the number of shadow samples used for soft shadows.

shadowType

get shadowType(): number
set shadowType(value: number)

Gets the type of shadows being rendered by this light.

shadowUpdateMode

get shadowUpdateMode(): number
set shadowUpdateMode(value: number)

Gets the shadow update mode.

shadowUpdateOverrides

get shadowUpdateOverrides(): number[] | null
set shadowUpdateOverrides(values: number[] | null)

Gets an array of SHADOWUPDATE_ settings per shadow cascade.

shape

get shape(): number
set shape(value: number)

Gets the light source shape.

type

get type(): string
set type(value: string)

Gets the type of the light.

volumetricScattering

get volumetricScattering(): number
set volumetricScattering(value: number)

Gets the multiplier of the light's contribution to the volumetric fog.

vsmBias

get vsmBias(): number
set vsmBias(value: number)

Gets the VSM bias value.

vsmBlurMode

get vsmBlurMode(): number
set vsmBlurMode(value: number)

Gets the blurring mode for variance shadow maps.

vsmBlurSize

get vsmBlurSize(): number
set vsmBlurSize(value: number)

Gets the number of samples used for blurring a variance shadow map.

Inherited from Component

LightComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/light/system.js#L34

Manages the LightComponents of an application. Reach it through app.systems.light; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

LightingParams

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/lighting/lighting-params.js#L11

Lighting parameters, allow configuration of the global lighting parameters. For details see Clustered Lighting.

Properties

atlasSplit

atlasSplit: number[] | null = null

Atlas textures split description, which applies to both the shadow and cookie texture atlas. Defaults to null, which enables to automatic split mode. For details see Configuring Atlas Split.

debugLayer

debugLayer: number

Layer ID of a layer to contain the debug rendering of clustered lighting. Defaults to undefined, which disables the debug rendering. Debug rendering is only included in the debug version of the engine.

Accessors

areaLightsEnabled

get areaLightsEnabled(): boolean
set areaLightsEnabled(value: boolean)

Gets whether clustered lighting supports area lights.

cells

get cells(): Vec3
set cells(value: Vec3)

Gets the number of cells along each world space axis the space containing lights is subdivided into.

cookieAtlasResolution

get cookieAtlasResolution(): number
set cookieAtlasResolution(value: number)

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

cookiesEnabled

get cookiesEnabled(): boolean
set cookiesEnabled(value: boolean)

Gets whether clustered lighting supports cookie textures.

maxLights

get maxLights(): number
set maxLights(value: number)

Gets the maximum number of lights the clustered lighting can use in a single frame.

maxLightsPerCell

get maxLightsPerCell(): number
set maxLightsPerCell(value: number)

Gets the maximum number of lights a cell can store.

shadowAtlasResolution

get shadowAtlasResolution(): number
set shadowAtlasResolution(value: number)

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

shadowsEnabled

get shadowsEnabled(): boolean
set shadowsEnabled(value: boolean)

Gets whether clustered lighting supports shadow casting.

shadowType

get shadowType(): number
set shadowType(value: number)

Gets the type of shadow filtering used by all shadows.

Lightmapper

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/lightmapper/lightmapper.js#L66

The lightmapper is used to bake scene lights into textures.

Methods

bake

bake(nodes: Entity[] | null, mode?: number): void

Generates and applies the lightmaps.

Parameters

LitShaderOptions

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/programs/lit-shader-options.js#L20

The lit shader options determines how the lit-shader gets generated. It specifies a set of parameters which triggers different fragment and vertex shader generation in the backend.

You do not create one. The engine fills a LitShaderOptions from the material and scene state each time a StandardMaterial needs a shader variant, and every distinct set of values produces a distinct compiled shader. Developers rarely need to touch it: the material properties such as useFog, useLighting and useSkybox on StandardMaterial cover the usual cases, and the values here mirror them together with the scene state. It is exposed for the rare case of customizing shader generation through StandardMaterial#onUpdateShader.

Properties

alphaTest

alphaTest: boolean = false

Enable alpha testing. See Material#alphaTest.

alphaToCoverage

alphaToCoverage: boolean = false

Enable alpha to coverage. See Material#alphaToCoverage.

ambientSH

ambientSH: boolean = false

If ambient spherical harmonics are used. Ambient SH replace prefiltered cubemap ambient on certain platforms (mostly Android) for performance reasons.

ambientSource

ambientSource: string = 'constant'

One of "ambientSH", "envAtlas", "constant".

blendType

blendType: number = BLEND_NONE

The value of Material#blendType.

cubeMapProjection

cubeMapProjection: number = 0

The value of StandardMaterial#cubeMapProjection.

fog

fog: string = FOG_NONE

The type of fog being applied in the shader. See Scene#fog for the list of possible values.

fresnelModel

fresnelModel: number = 0

The value of StandardMaterial#fresnelModel.

gamma

gamma: number = GAMMA_NONE

The type of gamma correction being applied in the shader. See CameraComponent#gammaCorrection for the list of possible values.

linearDepth

linearDepth: boolean = false

Make vLinearDepth available in the shader.

occludeDirect

occludeDirect: boolean = false

The value of StandardMaterial#occludeDirect.

occludeSpecular

occludeSpecular: number = 0

The value of StandardMaterial#occludeSpecular.

occludeSpecularFloat

occludeSpecularFloat: boolean = false

Defines if StandardMaterial#occludeSpecularIntensity constant should affect specular occlusion.

opacityDither

opacityDither: string = DITHER_NONE

Enable opacity dithering. See StandardMaterial#opacityDither.

opacityFadesSpecular

opacityFadesSpecular: boolean = false

Enable specular fade. See StandardMaterial#opacityFadesSpecular.

opacityShadowDither

opacityShadowDither: string = DITHER_NONE

Enable opacity shadow dithering. See StandardMaterial#opacityShadowDither.

reflectionSource

reflectionSource: string = REFLECTIONSRC_NONE

One of REFLECTIONSRC_*** constants.

shaderChunks

shaderChunks: ShaderChunks | null = null

Custom shader chunks that will replace default ones.

shadowCatcher

shadowCatcher: boolean = false

Shader outputs the accumulated shadow value, used for shadow catcher materials.

skyboxIntensity

skyboxIntensity: number = 1.0

Skybox intensity factor.

ssao

ssao: boolean = false

Apply SSAO during the lighting.

toneMap

toneMap: number = -1

The type of tone mapping being applied in the shader. See CameraComponent#toneMapping for the list of possible values.

twoSidedLighting

twoSidedLighting: boolean = false

The value of StandardMaterial#twoSidedLighting.

useCubeMapRotation

useCubeMapRotation: boolean = false

If cube map rotation is enabled.

useInstancing

useInstancing: boolean = false

If hardware instancing compatible shader should be generated. Transform is read from per-instance VertexBuffer instead of shader's uniforms.

useMetalness

useMetalness: boolean = false

The value of StandardMaterial#useMetalness.

useMorphNormal

useMorphNormal: boolean = false

If morphing code should be generated to morph normals.

useMorphPosition

useMorphPosition: boolean = false

If morphing code should be generated to morph positions.

userAttributes

userAttributes: {} = {}

Object containing a map of user defined vertex attributes to attached shader semantics.

useRefraction

useRefraction: boolean = false

If refraction is used.

useSceneEnv

useSceneEnv: boolean = false

If the environment chunks sample the scene environment, published by the renderer as scene_envAtlas and scene_skybox, instead of the textures owned by the material (texture_envAtlas, texture_cubeMap).

useSpecular

useSpecular: boolean = false

If any specular or reflections are needed at all.

Material

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/material.js#L108

A material determines how a particular MeshInstance is rendered, and specifies render state including uniforms, textures, defines, and other properties.

This is a base class and cannot be instantiated and used directly. Only subclasses such as ShaderMaterial and StandardMaterial can be used to define materials for rendering.

Choose StandardMaterial for a physically based surface described by properties and textures, and ShaderMaterial to supply your own vertex and fragment shaders. Both share the state defined here: blending through blendType, depth behavior through depthTest, depthWrite and depthFunc, face culling through cull, alpha testing through alphaTest, shader uniforms through setParameter, and preprocessor defines through setDefine. getShaderChunks exposes the GLSL and WGSL chunks the material's shader is built from, so one chunk can be replaced without writing a whole shader.

After changing properties, call update so the change reaches the GPU. Most changes only refresh uniforms; a change that alters how the shader is generated also clears the material's compiled shader variants, which are rebuilt on demand. A material can be shared by any number of mesh instances, and clone makes an independent copy.

Example

// Make a material additive and double-sided, then apply the change
material.blendType = BLEND_ADDITIVE;
material.cull = CULLFACE_NONE;
material.update();

Constructors

constructor

protected new Material()

Properties

alphaToCoverage

alphaToCoverage: boolean = false

Enables or disables alpha to coverage. When enabled, and if hardware anti-aliasing is on, limited order-independent transparency can be achieved. Quality depends on the number of MSAA samples of the current render target. It can nicely soften edges of otherwise sharp alpha cutouts, but isn't recommended for large area semi-transparent surfaces. Note, that you don't need to enable blending to make alpha to coverage work. It will work without it, just like alphaTest.

This requires a multi-sampled render target, and is silently ignored when rendering to a single-sampled one. On WebGPU it additionally requires the first color attachment of the render target to use a blendable format with an alpha channel, and is silently ignored otherwise - note that PIXELFORMAT_111110F, the default HDR format used by CameraFrame, has no alpha channel.

cull

cull: number = CULLFACE_BACK

Controls how triangles are culled based on their face direction with respect to the viewpoint. Can be:

Defaults to CULLFACE_BACK.

frontFace

frontFace: number = FRONTFACE_CCW

Controls whether polygons are front- or back-facing by setting a winding orientation. Can be:

Defaults to FRONTFACE_CCW.

name

name: string = 'Untitled'

The name of the material.

stencilBack

stencilBack: StencilParameters | null = null

Stencil parameters for back faces (default is null).

stencilFront

stencilFront: StencilParameters | null = null

Stencil parameters for front faces (default is null).

userId

userId: string = ''

A unique id the user can assign to the material. The engine internally does not use this for anything, and the user can assign a value to this id for any purpose they like. Defaults to an empty string.

Accessors

alphaTest

get alphaTest(): number
set alphaTest(value: number)

Gets the alpha test reference value.

alphaWrite

get alphaWrite(): boolean
set alphaWrite(value: boolean)

Gets whether the alpha channel is written to the color buffer.

blendState

get blendState(): Readonly<BlendState>
set blendState(value: Readonly<BlendState>)

Gets the blend state for this material. Use the setter to update transparency and sort state.

blendType

get blendType(): number
set blendType(type: number)

Gets the blend mode for this material.

blueWrite

get blueWrite(): boolean
set blueWrite(value: boolean)

Gets whether the blue channel is written to the color buffer.

depthBias

get depthBias(): number
set depthBias(value: number)

Gets the offset for the output depth buffer value.

depthFunc

get depthFunc(): number
set depthFunc(value: number)

Gets the depth test function.

depthState

get depthState(): DepthState
set depthState(value: DepthState)

Gets the depth state.

depthTest

get depthTest(): boolean
set depthTest(value: boolean)

Gets whether depth testing is enabled.

depthWrite

get depthWrite(): boolean
set depthWrite(value: boolean)

Gets whether depth writing is enabled.

flatShading

get flatShading(): boolean
set flatShading(value: boolean)

Gets whether flat shading is enabled.

greenWrite

get greenWrite(): boolean
set greenWrite(value: boolean)

Gets whether the green channel is written to the color buffer.

redWrite

get redWrite(): boolean
set redWrite(value: boolean)

Gets whether the red channel is written to the color buffer.

shaderChunksVersion

get shaderChunksVersion(): string
set shaderChunksVersion(value: string)

Returns the version of the shader chunks.

slopeDepthBias

get slopeDepthBias(): number
set slopeDepthBias(value: number)

Gets the offset for the output depth buffer value based on the slope of the triangle relative to the camera.

Methods

_markLayoutDirty

protected _markLayoutDirty(): void

Marks the layout of the material as changed: the next preparation fetches it again, and replaces the uniform buffer and the bind group when it differs.

_markPropertyModified

protected _markPropertyModified(property: MaterialProperty): void

Records that the public value of a typed property changed. The value is written to the uniform buffer by the next Material#update.

Parameters

_markPropertyMutable

protected _markPropertyMutable(property: MaterialProperty, value: any): void

Records that the aggregate value of a typed property was handed out by its getter, so that an in-place mutation of the returned object can be detected by the next Material#update. Only the first exposure allocates a snapshot.

Parameters

clone

clone(): Material

Clone a material.

Returns Material: A newly cloned material.

copy

copy(source: Material): Material

Copy a material.

Parameters

Returns Material: The destination material.

deleteParameter

deleteParameter(name: string): void

Deletes a shader parameter on a material.

Parameters

destroy

destroy(): void

Removes this material from the scene and possibly frees up memory from its shaders (if there are no other materials using it).

getDefine

getDefine(name: string): boolean

Returns true if a define is enabled on the material, otherwise false.

Parameters

Returns boolean: The value of the define.

getParameter

getParameter(name: string): any

Retrieves the specified shader parameter from a material.

Parameters

Returns any: The named parameter.

getShaderChunks

getShaderChunks(shaderLanguage?: string): ShaderChunkMap

Returns an object containing shader chunks for a specific shader language for the material. These chunks define custom GLSL or WGSL code used to construct the final shader for the material. The chunks can be also be included in shaders using the #include "ChunkName" directive.

On the WebGL platform:

On the WebGPU platform:

To ensure faster shader compilation, it is recommended to provide shader chunks for all supported platforms.

A simple example on how to override a shader chunk providing emissive color for both GLSL and WGSL to simply return a red color:

material.getShaderChunks(SHADERLANGUAGE_GLSL).set('emissivePS', `
    void getEmission() {
        dEmission = vec3(1.0, 0.0, 1.0);
    }
`);

material.getShaderChunks(SHADERLANGUAGE_WGSL).set('emissivePS', `
    fn getEmission() {
        dEmission = vec3f(1.0, 0.0, 1.0);
    }
`);

// call update to apply the changes
material.update();

Parameters

Returns ShaderChunkMap: - The shader chunks for the specified shader language.

setDefine

setDefine(name: string, value: string | boolean | undefined): void

Adds or removes a define on the material. Defines can be used to enable or disable various parts of the shader code.

Parameters

setParameter

setParameter(name: string, data: number | number[] | ArrayBufferView<ArrayBufferLike> | Texture | StorageBuffer): void

Sets a shader parameter on a material.

Parameters

update

update(): void

Applies any changes made to the material's properties. This method should be called after modifying material properties to ensure the changes take effect.

The method will clear cached shader variants and trigger recompilation if:

Note: Shaders are not compiled immediately. Instead, existing shader variants are cleared and new variants will be compiled on-demand as they are needed for different render passes (e.g., forward, shadow, pick).

When global shader chunks are modified, update() must be called on each material that should reflect those changes.

Mesh

Class · extends RefCountedObject · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh.js#L203

A graphical primitive. The mesh is defined by a VertexBuffer and an optional IndexBuffer. It also contains a primitive definition which controls the type of the primitive and the portion of the vertex or index buffer to use.

A mesh holds geometry only. To draw it, pair it with a Material in a MeshInstance and give that instance to a RenderComponent or a Layer; one mesh can back any number of instances. Mesh.fromGeometry builds a mesh from a Geometry such as BoxGeometry in one call. Meshes are reference counted: every MeshInstance holds a reference to its mesh, so call destroy on a mesh you created only once no instance uses it.

Mesh APIs

There are two ways a mesh can be generated or updated.

Simple Mesh API

Mesh class provides interfaces such as setPositions and setUvs that provide a simple way to provide vertex and index data for the Mesh, and hiding the complexity of creating the VertexFormat. This is the recommended interface to use.

A simple example which creates a Mesh with 3 vertices, containing position coordinates only, to form a single triangle.

const mesh = new Mesh(device);
const positions = [
    0, 0, 0, // pos 0
    1, 0, 0, // pos 1
    1, 1, 0  // pos 2
];
mesh.setPositions(positions);
mesh.update();

An example which creates a Mesh with 4 vertices, containing position and uv coordinates in channel 0, and an index buffer to form two triangles. Float32Array is used for positions and uvs.

const mesh = new Mesh(device);
const positions = new Float32Array([
    0, 0, 0, // pos 0
    1, 0, 0, // pos 1
    1, 1, 0, // pos 2
    0, 1, 0  // pos 3
]);
const uvs = new Float32Array([
    0, 1  // uv 3
    1, 1, // uv 2
    1, 0, // uv 1
    0, 0, // uv 0
]);
const indices = [
    0, 1, 2, // triangle 0
    0, 2, 3  // triangle 1
];
mesh.setPositions(positions);
mesh.setNormals(calculateNormals(positions, indices));
mesh.setUvs(0, uvs);
mesh.setIndices(indices);
mesh.update();

This example demonstrates that vertex attributes such as position and normals, and also indices can be provided using Arrays ([]) and also Typed Arrays (Float32Array and similar). Note that typed arrays have higher performance, and are generally recommended for per-frame operations or larger meshes, but their construction using new operator is costly operation. If you only need to operate on a small number of vertices or indices, consider using Arrays to avoid the overhead associated with allocating Typed Arrays.

Follow these links for more complex examples showing the functionality.

Update Vertex and Index buffers

This allows greater flexibility, but is more complex to use. It allows more advanced setups, for example sharing a Vertex or Index Buffer between multiple meshes. See VertexBuffer, IndexBuffer and VertexFormat for details.

Constructors

constructor

new Mesh(graphicsDevice: GraphicsDevice, options?: object)

Create a new Mesh instance.

Parameters

Properties

indexBuffer

indexBuffer: IndexBuffer[]

An array of index buffers. For unindexed meshes, this array can be empty. The first index buffer in the array is used by MeshInstances with a renderStyle property set to RENDERSTYLE_SOLID. The second index buffer in the array is used if renderStyle is set to RENDERSTYLE_WIREFRAME.

primitive

primitive: { base: number; baseVertex: number; count: number; indexed?: boolean; type: number }[]

Array of primitive objects defining how vertex (and index) data in the mesh should be interpreted by the graphics device.

skin

skin: Skin | null = null

The skin data (if any) that drives skinned mesh animations for this mesh.

vertexBuffer

vertexBuffer: VertexBuffer = null

The vertex buffer holding the vertex data of the mesh.

Accessors

aabb

get aabb(): BoundingBox
set aabb(aabb: BoundingBox)

Gets the axis-aligned bounding box for the object space vertices of this mesh.

morph

get morph(): Morph | null
set morph(morph: Morph | null)

Gets the morph data that drives morph target animations for this mesh.

Methods

clear

clear(verticesDynamic?: boolean, indicesDynamic?: boolean, maxVertices?: number, maxIndices?: number): void

Clears the mesh of existing vertices and indices and resets the VertexFormat associated with the mesh. This call is typically followed by calls to methods such as setPositions, setVertexStream or setIndices and finally update to rebuild the mesh, allowing different VertexFormat.

Parameters

destroy

destroy(): void

Destroys the VertexBuffer and IndexBuffers associated with the mesh. This is normally called by Model#destroy and does not need to be called manually.

getColors

getColors(colors: NumericArray): number

Gets the vertex color data.

Parameters

Returns number: Returns the number of vertices populated.

getIndices

getIndices(indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>): number

Gets the index data.

Parameters

Returns number: Returns the number of indices populated.

getNormals

getNormals(normals: NumericArray): number

Gets the vertex normals data.

Parameters

Returns number: Returns the number of vertices populated.

getPositions

getPositions(positions: NumericArray): number

Gets the vertex positions data.

Parameters

Returns number: Returns the number of vertices populated.

getUvs

getUvs(channel: number, uvs: NumericArray): number

Gets the vertex uv data.

Parameters

Returns number: Returns the number of vertices populated.

getVertexStream

getVertexStream(semantic: string, data: NumericArray): number

Gets the vertex data corresponding to a semantic.

Parameters

Returns number: Returns the number of vertices populated.

setColors

setColors(colors: ArrayLike<number>, componentCount?: number, numVertices?: number): void

Sets the vertex color array. Colors are stored using TYPE_FLOAT32 format, which is useful for HDR colors.

Parameters

setColors32

setColors32(colors: ArrayLike<number>, numVertices?: number): void

Sets the vertex color array. Colors are stored using TYPE_UINT8 format, which is useful for LDR colors. Values in the array are expected in [0..255] range, and are mapped to [0..1] range in the shader.

Parameters

setIndices

setIndices(indices: number[] | Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, numIndices?: number): void

Sets the index array. Indices are stored using 16-bit format by default, unless more than 65535 vertices are specified, in which case 32-bit format is used.

Parameters

setNormals

setNormals(normals: ArrayLike<number>, componentCount?: number, numVertices?: number): void

Sets the vertex normals array. Normals are stored using TYPE_FLOAT32 format.

Parameters

setPositions

setPositions(positions: ArrayLike<number>, componentCount?: number, numVertices?: number): void

Sets the vertex positions array. Vertices are stored using TYPE_FLOAT32 format.

Parameters

setUvs

setUvs(channel: number, uvs: ArrayLike<number>, componentCount?: number, numVertices?: number): void

Sets the vertex uv array. Uvs are stored using TYPE_FLOAT32 format.

Parameters

setVertexStream

setVertexStream(semantic: string, data: ArrayLike<number>, componentCount: number, numVertices?: number, dataType?: number, dataTypeNormalize?: boolean, asInt?: boolean): void

Sets the vertex data for any supported semantic.

Parameters

update

update(primitiveType?: number, updateBoundingBox?: boolean): void

Applies any changes to vertex stream and indices to mesh. This allocates or reallocates vertexBuffer or indexBuffer to fit all provided vertices and indices, and fills them with data.

Parameters

fromGeometry

static fromGeometry(graphicsDevice: GraphicsDevice, geometry: Geometry, options?: object): Mesh

Create a new Mesh instance from Geometry object.

Parameters

Returns Mesh: A new mesh.

Inherited from RefCountedObject

MeshInstance

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh-instance.js#L285

An instance of a Mesh. A single mesh can be referenced by many mesh instances that can have different transforms and materials.

A mesh instance is created from a Mesh, a Material and the GraphNode whose world transform places it, and it is drawn only once it belongs to a Layer. Components such as RenderComponent create mesh instances from their assets and add them to the layers in their layers list. A mesh instance you construct yourself is placed either by assigning it to RenderComponent#meshInstances or by adding it to a layer directly with Layer#addMeshInstances.

Per-instance rendering state lives here rather than on the shared mesh or material: visible, castShadow and receiveShadow, cull for frustum culling, drawOrder for manual sorting, and setParameter for shader uniforms that override the material's. aabb is the world-space bounds derived from the mesh bounds and the node's transform, and can be assigned to override it.

Instancing

Hardware instancing lets the GPU draw many copies of the same geometry with a single draw call. Use setInstancing to attach a vertex buffer that holds per-instance data (for example a mat4 world-matrix for every instance). Set instancingCount to control how many instances are rendered. Passing null to setInstancing disables instancing once again.

// vb is a vertex buffer with one 4×4 matrix per instance
meshInstance.setInstancing(vb);
meshInstance.instancingCount = numInstances;

The default matrix format, VertexFormat.getDefaultInstancingFormat, occupies the attribute locations of TEXCOORD6 and TEXCOORD7. A material sampling those UV sets on an instanced mesh needs a custom instancing vertex format on other attributes, as shown by the instancing-custom example.

Examples

GPU-Driven Indirect Rendering (WebGPU Only)

Instead of issuing draw calls from the CPU, parameters are written into a GPU storage buffer and executed via indirect draw commands. Allocate one or more slots with GraphicsDevice.getIndirectDrawSlot(count), then bind the mesh instance to those slots:

const slot = app.graphicsDevice.getIndirectDrawSlot(count);
meshInstance.setIndirect(null, slot, count); // first arg can be a CameraComponent or null

Example

Multi-draw

Multi-draw lets the engine submit multiple sub-draws with a single API call. On WebGL2 this maps to the WEBGL_multi_draw extension; on WebGPU, to indirect multi-draw. Use setMultiDraw to allocate a DrawCommands container, fill it with sub-draws using DrawCommands#add and finalize with DrawCommands#update whenever the data changes.

Support: GraphicsDevice#supportsMultiDraw is true on WebGPU and commonly true on WebGL2 (high coverage). When not supported, the engine can still render by issuing a fast internal loop of single draws using the multi-draw data.

// two indexed sub-draws from a single mesh
const cmd = meshInstance.setMultiDraw(null, 2);
cmd.add(0, 36, 1, 0);
cmd.add(1, 60, 1, 36);
cmd.update(2);

Precedence

When draw commands (indirect or multi-draw, see setIndirect and setMultiDraw) are bound, they are the source of truth for rendering: the number of draws and the per-draw instance counts come from the draw commands, and instancingCount is ignored. In this case setting instancingCount to 0 does not skip rendering. instancingCount only takes effect for plain hardware instancing, when no draw commands are bound.

Constructors

constructor

new MeshInstance(mesh: Mesh, material: Material, node?: GraphNode)

Create a new MeshInstance instance.

Parameters

Example

// Create a mesh instance pointing to a 1x1x1 'cube' mesh
const mesh = Mesh.fromGeometry(app.graphicsDevice, new BoxGeometry());
const material = new StandardMaterial();

const meshInstance = new MeshInstance(mesh, material);

const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
this.app.scene.root.addChild(entity);

Properties

castShadow

castShadow: boolean = false

Enable shadow casting for this mesh instance. Use this property to enable/disable shadow casting without overhead of removing from scene. Note that this property does not add the mesh instance to appropriate list of shadow casters on a Layer, but allows mesh to be skipped from shadow casting while it is in the list already. Defaults to false.

cull

cull: boolean = true

Controls whether the mesh instance can be culled by frustum culling (see CameraComponent#frustumCulling). Defaults to true.

drawOrder

drawOrder: number = 0

Determines the rendering order of mesh instances. Only used when mesh instances are added to a Layer with Layer#opaqueSortMode or Layer#transparentSortMode (depending on the material) set to SORTMODE_MANUAL.

shaderPassMask

shaderPassMask: number = 0xFFFFFFFF

A bitmask controlling which shader passes this mesh instance is rendered in. Bit N corresponds to the shader pass with index N: the built-in forward pass is SHADER_FORWARD, and indices for custom shader passes are obtained from CameraComponent#setShaderPass. Defaults to 0xFFFFFFFF (all passes). For example, clearing the forward pass bit keeps the mesh in the other passes (such as the camera depth prepass that feeds Depth of Field) while making it invisible in the rendered color image.

Example

// clear the forward (color) pass bit, leaving all other pass bits set: the mesh is no longer
// drawn in the color image, but still takes part in the other passes (such as the prepass)
meshInstance.shaderPassMask &= ~(1 << SHADER_FORWARD);

Example

// set the forward (color) pass bit, leaving all other pass bits unchanged
meshInstance.shaderPassMask |= (1 << SHADER_FORWARD);

Example

// exclude the mesh from a custom shader pass set up on the camera (see
// CameraComponent#setShaderPass), leaving all other pass bits set
const customPass = cameraComponent.setShaderPass('custom_rendering');
meshInstance.shaderPassMask &= ~(1 << customPass);

Example

// test whether the forward (color) pass bit is set
const forwardBitSet = (meshInstance.shaderPassMask & (1 << SHADER_FORWARD)) !== 0;

Example

// set every pass bit (the default value)
meshInstance.shaderPassMask = 0xFFFFFFFF;

shadowCascadeMask

shadowCascadeMask: number = SHADOW_CASCADE_ALL

Specifies a bitmask that controls which shadow cascades a mesh instance contributes to when rendered with a LIGHTTYPE_DIRECTIONAL light source. This setting is only effective if the castShadow property is enabled. Defaults to SHADOW_CASCADE_ALL, which means the mesh casts shadows into all available cascades.

visible

visible: boolean = true

Enable rendering for this mesh instance. Use visible property to enable/disable rendering without overhead of removing from scene. But note that the mesh instance is still in the hierarchy and still in the draw call list.

visibleThisFrame

visibleThisFrame: boolean = false

Read this value in the Scene.EVENT_POSTCULL event to determine if the object is actually going to be rendered.

Accessors

aabb

get aabb(): BoundingBox
set aabb(aabb: BoundingBox)

Gets the world space axis-aligned bounding box for this mesh instance.

calculateSortDistance

get calculateSortDistance(): CalculateSortDistanceCallback | null
set calculateSortDistance(calculateSortDistance: CalculateSortDistanceCallback | null)

Gets the callback to calculate sort distance.

drawBucket

get drawBucket(): number
set drawBucket(bucket: number)

Gets the draw bucket for mesh instance.

instancingCount

get instancingCount(): number
set instancingCount(value: number)

Gets the number of instances when using hardware instancing to render the mesh.

mask

get mask(): number
set mask(val: number)

Gets the light mask of this mesh instance: which LightComponents light it.

material

get material(): Material | null
set material(material: Material | null)

Gets the material used by this mesh instance.

mesh

get mesh(): Mesh | null
set mesh(mesh: Mesh | null)

Gets the graphics mesh being instanced.

morphInstance

get morphInstance(): MorphInstance | null
set morphInstance(val: MorphInstance | null)

Gets the morph instance managing morphing of this mesh instance.

node

get node(): GraphNode
set node(node: GraphNode)

Gets the graph node defining the transform for this instance.

renderStyle

get renderStyle(): number
set renderStyle(renderStyle: number)

Gets the render style of the mesh instance.

skinInstance

get skinInstance(): SkinInstance | null
set skinInstance(val: SkinInstance | null)

Gets the skin instance managing skinning of this mesh instance.

Methods

deleteParameter

deleteParameter(name: string): void

Deletes a shader parameter on a mesh instance.

Parameters

getIndirectMetaData

getIndirectMetaData(): Int32Array<ArrayBufferLike>

Retrieves the mesh metadata needed for indirect rendering.

Returns Int32Array<ArrayBufferLike>: - A typed array with 4 elements representing the mesh metadata, which is typically needed when generating indirect draw call parameters using Compute shader. These can be provided to the Compute shader using vec4i uniform. The values are based on Mesh#primitive, stored in this order: [count, base, baseVertex, 0]. The last value is always zero and is reserved for future use.

getParameter

getParameter(name: string): any

Retrieves the specified shader parameter from a mesh instance.

Parameters

Returns any: The named parameter, or undefined if no parameter with that name is set on this mesh instance.

setIndirect

setIndirect(camera: CameraComponent | null, slot: number, count?: number): void

Sets the MeshInstance to be rendered using indirect rendering, where the GPU, typically using a Compute shader, stores draw call parameters in a buffer. Note that this is only supported on WebGPU (see GraphicsDevice#supportsIndirectDraw), and ignored on other platforms, where the mesh instance renders as a normal draw call.

Parameters

setInstancing

setInstancing(vertexBuffer: true | VertexBuffer | null, cull?: boolean): void

Sets up MeshInstance to be rendered using Hardware Instancing. Note that instancingCount is automatically set to the number of vertices of the vertex buffer when it is provided.

Parameters

setMultiDraw

setMultiDraw(camera: CameraComponent | null, maxCount?: number): DrawCommands | undefined

Sets the MeshInstance to be rendered using multi-draw, where multiple sub-draws are executed with a single draw call.

Note: Each call to this method invalidates any previously stored draw command data for the specified camera.

Parameters

Returns DrawCommands | undefined: The commands container to populate with sub-draw commands.

setParameter

setParameter(name: string, data: number | number[] | Float32Array<ArrayBufferLike> | Texture): void

Sets a shader parameter on a mesh instance. Note that this parameter will take precedence over parameter of the same name if set on Material this mesh instance uses for rendering. To change an array value, call this method again with it; the contents of an array are not guaranteed to be re-read on later draws.

Parameters

Model

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/model.js#L16

A model is a graphical object that can be added to or removed from a scene. It contains a hierarchy and any number of mesh instances.

Constructors

constructor

new Model()

Creates a new model.

Example

// Create a new model
const model = new Model();

Properties

graph

graph: GraphNode | null = null

The root node of the model's graph node hierarchy.

meshInstances

meshInstances: MeshInstance[] = []

An array of MeshInstances contained in this model.

morphInstances

morphInstances: MorphInstance[] = []

An array of MorphInstances contained in this model.

skinInstances

skinInstances: SkinInstance[] = []

An array of SkinInstances contained in this model.

Methods

clone

clone(): Model

Clones a model. The returned model has a newly created hierarchy and mesh instances, but meshes are shared between the clone and the specified model.

Returns Model: A clone of the specified model.

Example

const clonedModel = model.clone();

destroy

destroy(): void

Destroys skinning texture and possibly deletes vertex/index buffers of a model. Mesh is reference-counted, so buffers are only deleted if all models with referencing mesh instances were deleted. That means all in-scene models + the "base" one (asset.resource) which is created when the model is parsed. It is recommended to use asset.unload() instead, which will also remove the model from the scene.

generateWireframe

generateWireframe(): void

Generates the necessary internal data for a model to be renderable as wireframe. Once this function has been called, any mesh instance in the model can have its renderStyle property set to RENDERSTYLE_WIREFRAME.

Example

model.generateWireframe();
for (let i = 0; i < model.meshInstances.length; i++) {
    model.meshInstances[i].renderStyle = RENDERSTYLE_WIREFRAME;
}

ModelComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/model/component.js#L54

The ModelComponent enables an Entity to render 3D models. The type property can be set to one of several predefined shapes (such as box, sphere, cone and so on). Alternatively, the component can be configured to manage an arbitrary Model. This can either be created programmatically or loaded from an Asset.

The Model managed by this component is positioned, rotated, and scaled in world space by the world transformation matrix of the owner Entity. This world matrix is derived by combining the entity's local transformation (position, rotation, and scale) with the world transformation matrix of its parent entity in the scene hierarchy.

You should never need to use the ModelComponent constructor directly. To add a ModelComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('model', {
    type: 'box'
});

Once the ModelComponent is added to the entity, you can access it via the Entity#model property:

entity.model.type = 'capsule';  // Set the model component's type

console.log(entity.model.type); // Get the model component's type and print it

Properties

isStatic

isStatic: boolean = false

Mark meshes as non-movable (optimization).

Accessors

asset

get asset(): number | Asset<string> | null
set asset(value: number | Asset<string> | null)

Gets the model asset id for the component.

batchGroupId

get batchGroupId(): number
set batchGroupId(value: number)

Gets the batch group for the mesh instances in this component (see BatchGroup).

castShadows

get castShadows(): boolean
set castShadows(value: boolean)

Gets whether attached meshes will cast shadows for lights that have shadow casting enabled.

castShadowsLightmap

get castShadowsLightmap(): boolean
set castShadowsLightmap(value: boolean)

Gets whether meshes instances will cast shadows when rendering lightmaps.

customAabb

get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)

Gets the custom object space bounding box that is used for visibility culling of attached mesh instances.

layers

get layers(): readonly number[]
set layers(value: readonly number[])

Gets the array of layer IDs (Layer#id) to which the mesh instances belong.

lightmapped

get lightmapped(): boolean
set lightmapped(value: boolean)

Gets whether the component is affected by the runtime lightmapper.

lightmapSizeMultiplier

get lightmapSizeMultiplier(): number
set lightmapSizeMultiplier(value: number)

Gets the lightmap resolution multiplier.

mapping

get mapping(): Readonly<Record<string, number>>
set mapping(value: Readonly<Record<string, number>>)

Gets the dictionary that holds material overrides for each mesh instance.

material

get material(): Material
set material(value: Material)

Gets the Material that will be used to render the model.

materialAsset

get materialAsset(): number | Asset<string> | null
set materialAsset(value: number | Asset<string> | null)

Gets the material Asset that will be used to render the component.

meshInstances

get meshInstances(): readonly MeshInstance[] | null
set meshInstances(value: readonly MeshInstance[] | null)

Gets the array of mesh instances contained in the component's model. Use the setter to replace the array; do not mutate the returned array.

model

get model(): Model | null
set model(value: Model | null)

Gets the model owned by this component. In this case a model is not set or loaded, this will return null.

receiveShadows

get receiveShadows(): boolean
set receiveShadows(value: boolean)

Gets whether shadows will be cast on attached meshes.

type

get type(): "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus"
set type(value: "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus")

Gets the type of the component.

Methods

hide

hide(): void

Stop rendering model without removing it from the scene hierarchy. This method sets the MeshInstance#visible property of every MeshInstance in the model to false Note, this does not remove the model or mesh instances from the scene hierarchy or draw call list. So the model component still incurs some CPU overhead.

Example

this.timer = 0;
this.visible = true;
// ...
// blink model every 0.1 seconds
this.timer += dt;
if (this.timer > 0.1) {
    if (!this.visible) {
        this.entity.model.show();
        this.visible = true;
    } else {
        this.entity.model.hide();
        this.visible = false;
    }
    this.timer = 0;
}

show

show(): void

Enable rendering of the model if hidden using hide. This method sets all the MeshInstance#visible property on all mesh instances to true.

Inherited from Component

ModelComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/model/system.js#L53

Allows an Entity to render a model or a primitive shape like a box, capsule, sphere, cylinder, cone etc.

Inherited from ComponentSystem

Morph

Class · extends RefCountedObject · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph.js#L25

Contains a list of MorphTargets, a combined delta AABB and some associated data.

Constructors

constructor

new Morph(targets: MorphTarget[], graphicsDevice: GraphicsDevice, options?: object)

Create a new Morph instance.

Parameters

Properties

preferHighPrecision

preferHighPrecision: boolean

Accessors

targets

get targets(): MorphTarget[]

Gets the array of morph targets.

Methods

destroy

destroy(): void

Frees video memory allocated by this object.

Inherited from RefCountedObject

MorphInstance

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph-instance.js#L20

An instance of Morph. Contains weights to assign to every MorphTarget, manages selection of active morph targets.

Constructors

constructor

new MorphInstance(morph: Morph)

Create a new MorphInstance instance.

Parameters

Properties

morph

morph: Morph

The morph with its targets, which is being instanced.

Methods

clone

clone(): MorphInstance

Clones a MorphInstance. The returned clone uses the same Morph and weights are set to defaults.

Returns MorphInstance: A clone of the specified MorphInstance.

destroy

destroy(): void

Frees video memory allocated by this object.

getWeight

getWeight(key: string | number): number

Gets current weight of the specified morph target.

Parameters

Returns number: Weight.

setWeight

setWeight(key: string | number, weight: number): void

Sets weight of the specified morph target.

Parameters

update

update(): void

Selects active morph targets and prepares morph for rendering. Called automatically by renderer.

MorphTarget

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/morph-target.js#L11

A Morph Target (also known as Blend Shape) contains deformation data to apply to existing mesh. Multiple morph targets can be blended together on a mesh. This is useful for effects that are hard to achieve with conventional animation and skinning.

Constructors

constructor

new MorphTarget(options: object, ...args: any[])

Create a new MorphTarget instance.

Parameters

Properties

used

used: boolean = false

A used flag. A morph target can be used / owned by the Morph class only one time.

Accessors

defaultWeight

get defaultWeight(): number

Gets the default weight of the morph target.

name

get name(): string

Gets the name of the morph target.

Methods

clone

clone(): MorphTarget

Returns an identical copy of the specified morph target. This can only be used if the morph target was created with options.preserveData set to true.

Returns MorphTarget: A morph target instance containing the result of the cloning.

OutlineRenderer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/outline-renderer.js#L160

The OutlineRenderer draws solid color outlines around the silhouettes of entities, for example to highlight objects that are selected or hovered in an editor. Each entity can be outlined in its own color.

The outlines are generated in three steps:

The outlines are drawn over everything the scene camera has rendered up to that layer, so they remain visible when the outlined objects are occluded by other objects. Anything rendered in that layer or after it, such as gizmos, is drawn on top of the outlines.

OutlineRenderer#frameUpdate needs to be called every frame to keep the outlines in sync with the scene camera. Only render and model components are outlined, and the outline color is applied to mesh instances using a StandardMaterial.

Relevant Engine API examples:

Example

// Create a layer used to render the outlined objects. It is added to the layer composition, but
// not to the scene camera, so that the camera does not render the outlined objects a second time.
const outlineLayer = new Layer({ name: 'OutlineLayer' });
app.scene.layers.push(outlineLayer);

// Create the outline renderer
const outlineRenderer = new OutlineRenderer(app, outlineLayer);

// Outline an entity and its descendants in red, and another entity in white
outlineRenderer.addEntity(entity1, Color.RED);
outlineRenderer.addEntity(entity2, Color.WHITE);

// Each frame, composite the outlines into the scene before the scene camera renders the opaque
// part of the 'Immediate' layer
const immediateLayer = app.scene.layers.getLayerByName('Immediate');
app.on('update', () => {
    outlineRenderer.frameUpdate(cameraEntity, immediateLayer, false);
});

// Later, stop outlining the first entity
outlineRenderer.removeEntity(entity1);

Constructors

constructor

new OutlineRenderer(app: AppBase, renderingLayer?: Layer, priority?: number)

Create a new OutlineRenderer.

Parameters

Methods

addEntity

addEntity(entity: Entity, color: Color, recursive?: boolean): void

Add an entity to the outline renderer, to draw an outline around it. The mesh instances of the entity's render and model components are outlined, including those of its descendants unless recursive is false. Adding an entity that is already outlined changes its outline color.

Render and model components that are not currently rendered, because they or their entity are disabled, are skipped - this is evaluated when the entity is added.

An entity should be outlined by a single outline renderer at a time. The outline color is stored on its mesh instances, so they cannot be outlined by more than one renderer, and removing them from one renderer would remove their outline from the other as well.

Parameters

Example

// outline an entity and its descendants in orange
outlineRenderer.addEntity(entity, new Color(1, 0.5, 0));

destroy

destroy(): void

Destroy the outline renderer and its resources. All entities are removed from the outline renderer first.

frameUpdate

frameUpdate(sceneCameraEntity: Entity, blendLayer: Layer, blendLayerTransparent: boolean): void

Update the outline renderer. This needs to be called once per frame, after the scene camera has been positioned, for example from the application's update event, which fires after scripts have been updated. It matches the internal outline camera to the scene camera's transform, projection, clip planes and resolution, and schedules the outlines to be composited into the scene for this frame.

The outlines are composited just before the scene camera renders the opaque or transparent part of blendLayer, so that part of the layer, and everything rendered after it, is drawn on top of the outlines. The scene camera needs to render blendLayer, otherwise the outlines are not visible.

Parameters

Example

const immediateLayer = app.scene.layers.getLayerByName('Immediate');
app.on('update', () => {
    outlineRenderer.frameUpdate(cameraEntity, immediateLayer, false);
});

removeAllEntities

removeAllEntities(): void

Remove all entities from the outline renderer, for example to clear the selection.

Example

// outline only the newly selected entity
outlineRenderer.removeAllEntities();
outlineRenderer.addEntity(selectedEntity, Color.WHITE);

removeEntity

removeEntity(entity: Entity, recursive?: boolean): void

Remove an entity from the outline renderer, to stop drawing its outline. This also works for an entity that has been disabled since it was added.

Parameters

Example

outlineRenderer.removeEntity(entity);

ParticleSystemComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/particle-system/component.js#L137

The ParticleSystemComponent enables an Entity to simulate particles and produce a renderable particle mesh on either CPU or GPU. GPU simulation is generally much faster than its CPU counterpart, because it avoids slow CPU-GPU synchronization and takes advantage of many GPU cores. However, it requires client support for reasonable uniform counts, reading from multiple textures in a vertex shader and the OES_texture_float extension, including rendering into float textures. Most mobile devices fail to satisfy these requirements, so it's not recommended to simulate thousands of particles on them. The GPU version also can't sort particles, so enabling sorting forces CPU mode too.

Particle rotation is specified by a single angle parameter: default billboard particles rotate around the camera-facing axis, while mesh particles rotate around two different view-independent axes. Most of the simulation parameters are specified with Curve or CurveSet. Curves are interpolated based on each particle's lifetime, therefore parameters are able to change over time. Most curve parameters can also be specified by 2 minimum/maximum curves, so that each particle picks a random value in-between.

You should never need to use the ParticleSystemComponent constructor directly. To add a ParticleSystemComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('particlesystem', {
    numParticles: 100,
    lifetime: 2,
    rate: 0.1
});

Once the ParticleSystemComponent is added to the entity, you can access it via the Entity#particlesystem property:

entity.particlesystem.loop = false; // Play the system once then stop

console.log(entity.particlesystem.loop); // Get the loop flag and print it

Relevant Engine API examples:

Accessors

alignToMotion

get alignToMotion(): boolean
set alignToMotion(arg: boolean)

Gets whether particles are oriented in their direction of motion or not.

alphaGraph

get alphaGraph(): Curve
set alphaGraph(arg: Curve)

Gets the alpha graph.

alphaGraph2

get alphaGraph2(): Curve
set alphaGraph2(arg: Curve)

Gets the second alpha graph.

animIndex

get animIndex(): number
set animIndex(arg: number)

Gets the index of the animation to play.

animLoop

get animLoop(): boolean
set animLoop(arg: boolean)

Gets whether the sprite sheet animation plays once or loops continuously.

animNumAnimations

get animNumAnimations(): number
set animNumAnimations(arg: number)

Gets the number of sprite sheet animations contained within the current sprite sheet.

animNumFrames

get animNumFrames(): number
set animNumFrames(arg: number)

Gets the number of sprite sheet frames in the current sprite sheet animation.

animSpeed

get animSpeed(): number
set animSpeed(arg: number)

Gets the sprite sheet animation speed.

animStartFrame

get animStartFrame(): number
set animStartFrame(arg: number)

Gets the sprite sheet frame that the animation should begin playing from.

animTilesX

get animTilesX(): number
set animTilesX(arg: number)

Gets the number of horizontal tiles in the sprite sheet.

animTilesY

get animTilesY(): number
set animTilesY(arg: number)

Gets the number of vertical tiles in the sprite sheet.

autoPlay

get autoPlay(): boolean
set autoPlay(arg: boolean)

Gets whether the particle system plays automatically on creation.

blendType

get blendType(): number
set blendType(arg: number)

Gets how particles are blended when being written to the currently active render target.

colorGraph

get colorGraph(): CurveSet
set colorGraph(arg: CurveSet)

Gets the color graph.

colorGraph2

get colorGraph2(): CurveSet
set colorGraph2(arg: CurveSet)

Gets the second color graph.

colorMap

get colorMap(): Texture
set colorMap(arg: Texture)

Gets the color map texture to apply to all particles in the system.

colorMapAsset

get colorMapAsset(): Asset<string> | null
set colorMapAsset(arg: Asset<string> | null)

Gets the Asset used to set the colorMap.

depthSoftening

get depthSoftening(): number
set depthSoftening(arg: number)

Gets whether depth softening is enabled.

depthWrite

get depthWrite(): boolean
set depthWrite(arg: boolean)

Gets whether depth writes is enabled.

drawOrder

get drawOrder(): number
set drawOrder(drawOrder: number)

Gets the draw order of the component.

emitterExtents

get emitterExtents(): Vec3
set emitterExtents(arg: Vec3)

Gets the extents of a local space bounding box within which particles are spawned at random positions.

emitterExtentsInner

get emitterExtentsInner(): Vec3
set emitterExtentsInner(arg: Vec3)

Gets the exception of extents of a local space bounding box within which particles are not spawned.

emitterRadius

get emitterRadius(): number
set emitterRadius(arg: number)

Gets the radius within which particles are spawned at random positions.

emitterRadiusInner

get emitterRadiusInner(): number
set emitterRadiusInner(arg: number)

Gets the inner radius within which particles are not spawned.

emitterShape

get emitterShape(): number
set emitterShape(arg: number)

Gets the shape of the emitter.

halfLambert

get halfLambert(): boolean
set halfLambert(arg: boolean)

Gets whether Half Lambert lighting is enabled.

initialVelocity

get initialVelocity(): number
set initialVelocity(arg: number)

Gets the magnitude of the initial emitter velocity.

intensity

get intensity(): number
set intensity(arg: number)

Gets the color multiplier.

layers

get layers(): readonly number[]
set layers(arg: readonly number[])

Gets the array of layer IDs (Layer#id) to which this particle system belongs.

lifetime

get lifetime(): number
set lifetime(arg: number)

Gets the length of time in seconds between a particle's birth and its death.

lighting

get lighting(): boolean
set lighting(arg: boolean)

Gets whether particles will be lit by ambient and directional lights.

localSpace

get localSpace(): boolean
set localSpace(arg: boolean)

Gets whether particles move with respect to the emitter's transform rather then world space.

localVelocityGraph

get localVelocityGraph(): CurveSet
set localVelocityGraph(arg: CurveSet)

Gets the local space velocity graph.

localVelocityGraph2

get localVelocityGraph2(): CurveSet
set localVelocityGraph2(arg: CurveSet)

Gets the second velocity graph.

loop

get loop(): boolean
set loop(arg: boolean)

Gets whether the particle system loops.

mesh

get mesh(): Mesh
set mesh(arg: Mesh)

Gets the polygonal mesh to be used as a particle.

meshAsset

get meshAsset(): Asset<string> | null
set meshAsset(arg: Asset<string> | null)

Gets the Asset used to set the mesh.

normalMap

get normalMap(): Texture
set normalMap(arg: Texture)

Gets the normal map texture to apply to all particles in the system.

normalMapAsset

get normalMapAsset(): Asset<string> | null
set normalMapAsset(arg: Asset<string> | null)

Gets the Asset used to set the normalMap.

numParticles

get numParticles(): number
set numParticles(arg: number)

Gets the maximum number of simulated particles.

orientation

get orientation(): number
set orientation(arg: number)

Gets the particle orientation mode.

particleNormal

get particleNormal(): Vec3
set particleNormal(arg: Vec3)

Gets the particle normal.

preWarm

get preWarm(): boolean
set preWarm(arg: boolean)

Gets whether the particle system will be initialized as though it has already completed a full cycle.

radialSpeedGraph

get radialSpeedGraph(): Curve
set radialSpeedGraph(arg: Curve)

Gets the radial speed graph.

radialSpeedGraph2

get radialSpeedGraph2(): Curve
set radialSpeedGraph2(arg: Curve)

Gets the second radial speed graph.

randomizeAnimIndex

get randomizeAnimIndex(): boolean
set randomizeAnimIndex(arg: boolean)

Gets whether each particle emitted by the system will play a random animation from the sprite sheet, up to animNumAnimations.

rate

get rate(): number
set rate(arg: number)

Gets the minimal interval in seconds between particle births.

rate2

get rate2(): number
set rate2(arg: number)

Gets the maximal interval in seconds between particle births.

renderAsset

get renderAsset(): Asset<string> | null
set renderAsset(arg: Asset<string> | null)

Gets the Render Asset used to set the mesh.

rotationSpeedGraph

get rotationSpeedGraph(): Curve
set rotationSpeedGraph(arg: Curve)

Gets the rotation speed graph.

rotationSpeedGraph2

get rotationSpeedGraph2(): Curve
set rotationSpeedGraph2(arg: Curve)

Gets the second rotation speed graph.

scaleGraph

get scaleGraph(): Curve
set scaleGraph(arg: Curve)

Gets the scale graph.

scaleGraph2

get scaleGraph2(): Curve
set scaleGraph2(arg: Curve)

Gets the second scale graph.

screenSpace

get screenSpace(): boolean
set screenSpace(arg: boolean)

Gets whether particles are rendered in 2D screen space.

sort

get sort(): number
set sort(arg: number)

Gets the particle sorting mode.

startAngle

get startAngle(): number
set startAngle(arg: number)

Gets the minimal initial Euler angle of a particle.

startAngle2

get startAngle2(): number
set startAngle2(arg: number)

Gets the maximal initial Euler angle of a particle.

stretch

get stretch(): number
set stretch(arg: number)

Gets how much particles are stretched in their direction of motion.

useFog

get useFog(): boolean
set useFog(arg: boolean)

Gets whether the camera's fog is applied to the particles.

useTonemap

get useTonemap(): boolean
set useTonemap(arg: boolean)

Gets whether the camera's tonemapping and the scene exposure are applied to the particles.

velocityGraph

get velocityGraph(): CurveSet
set velocityGraph(arg: CurveSet)

Gets the world space velocity graph.

velocityGraph2

get velocityGraph2(): CurveSet
set velocityGraph2(arg: CurveSet)

Gets the second world space velocity graph.

wrap

get wrap(): boolean
set wrap(arg: boolean)

Gets whether particles wrap based on the set wrap bounds.

wrapBounds

get wrapBounds(): Vec3
set wrapBounds(arg: Vec3)

Gets the wrap bounds of the particle system.

Methods

isPlaying

isPlaying(): boolean

Checks if simulation is in progress.

Returns boolean: True if the particle system is currently playing and false otherwise.

pause

pause(): void

Freezes the simulation.

play

play(): void

Enables/unfreezes the simulation.

reset

reset(): void

Resets particle state, doesn't affect playing.

stop

stop(): void

Disables the emission of new particles, lets existing to finish their simulation.

unpause

unpause(): void

Unfreezes the simulation.

Inherited from Component

ParticleSystemComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/particle-system/system.js#L104

Manages the ParticleSystemComponents of an application. Reach it through app.systems.particlesystem; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

Picker

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/graphics/picker.js#L72

Picker object used to select mesh instances from screen coordinates. It can also optionally capture depth information to determine world positions of picked points.

The picker works by rendering mesh instances to an offscreen render target with unique IDs encoded as colors. When queried, it reads back the pixel data to identify which mesh instance was at the specified screen coordinates. If depth picking is enabled, it also captures depth values to compute world positions.

Main API methods:

Performance considerations: The picker resolution can be set lower than the screen resolution for better performance, though this reduces picking precision and may miss small objects.

Example

// Create a picker with depth picking enabled at quarter resolution
const picker = new Picker(app, canvas.width * 0.25, canvas.height * 0.25, true);

// In your update loop, prepare the picker
picker.resize(canvas.width * 0.25, canvas.height * 0.25);
picker.prepare(camera, scene);

// Pick mesh instances in an area
picker.getSelectionAsync(x, y, width, height).then((meshInstances) => {
    meshInstances.forEach((meshInstance) => {
        console.log('Picked:', meshInstance.node.name);
    });
});

// Pick world position (requires depth enabled)
picker.getWorldPointAsync(x, y).then((worldPoint) => {
    if (worldPoint) {
        console.log(worldPoint);
    }
});

See - Picker Example

Constructors

constructor

new Picker(app: AppBase, width: number, height: number, depth?: boolean)

Create a new Picker instance.

Parameters

Properties

height

height: number

width

width: number

Methods

destroy

destroy(): void

Frees resources associated with this picker.

getSelection

getSelection(x: number, y: number, width?: number, height?: number): (GSplatComponent | MeshInstance)[]

Return the list of mesh instances selected by the specified rectangle in the previously prepared pick buffer. The rectangle using top-left coordinate system.

Note: This function is not supported on WebGPU. Use getSelectionAsync instead. Note: This function is blocks the main thread while reading pixels from GPU memory. It's recommended to use getSelectionAsync instead.

Parameters

Returns (GSplatComponent | MeshInstance)[]: An array of mesh instances or gsplat components that are in the selection.

Example

// Get the selection at the point (10,20)
const selection = picker.getSelection(10, 20);

Example

// Get all models in rectangle with corners at (10,20) and (20,40)
const selection = picker.getSelection(10, 20, 10, 20);

getSelectionAsync

getSelectionAsync(x: number, y: number, width?: number, height?: number): Promise<(GSplatComponent | MeshInstance)[]>

Return the list of mesh instances selected by the specified rectangle in the previously prepared pick buffer. The rectangle uses top-left coordinate system.

This method is asynchronous and does not block the execution.

Parameters

Returns Promise<(GSplatComponent | MeshInstance)[]>: - Promise that resolves with an array of mesh instances or gsplat components that are in the selection.

Example

// Get the mesh instances at the rectangle with start at (10,20) and size of (5,5)
picker.getSelectionAsync(10, 20, 5, 5).then((meshInstances) => {
   console.log(meshInstances);
});

getWorldPointAsync

getWorldPointAsync(x: number, y: number): Promise<Vec3 | null>

Return the world position of the mesh instance picked at the specified screen coordinates. The position is reconstructed at the center of the pixel containing the coordinates, which is where its depth was rasterized.

Parameters

Returns Promise<Vec3 | null>: Promise that resolves with the world position of the picked point, or null if no depth is available or nothing was picked.

Example

// Get the world position at screen coordinates (100, 50)
picker.getWorldPointAsync(100, 50).then((worldPoint) => {
    if (worldPoint) {
        console.log('World position:', worldPoint);
        // Use the world position
    } else {
        console.log('No object at this position');
    }
});

prepare

prepare(camera: CameraComponent, scene: Scene, layers?: Layer[]): void

Primes the pick buffer with a rendering of the specified models from the point of view of the supplied camera. Once the pick buffer has been prepared, getSelection can be called multiple times on the same picker object. Therefore, if the models or camera do not change in any way, prepare does not need to be called again.

Parameters

resize

resize(width: number, height: number): void

Sets the resolution of the pick buffer. The pick buffer resolution does not need to match the resolution of the corresponding frame buffer use for general rendering of the 3D scene. However, the lower the resolution of the pick buffer, the less accurate the selection results returned by getSelection. On the other hand, smaller pick buffers will yield greater performance, so there is a trade off.

Parameters

PlaneGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/plane-geometry.js#L34

A procedural plane-shaped geometry.

Typically, you would:

  1. Create a PlaneGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new PlaneGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new PlaneGeometry(opts?: object)

Create a new PlaneGeometry instance.

By default, the constructor creates a plane centered on the object space origin with a width and length of 1 and 5 segments in either axis (50 triangles). The normal vector of the plane is aligned along the positive Y axis. The plane is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new PlaneGeometry({
    halfExtents: new Vec2(1, 1),
    widthSegments: 10,
    lengthSegments: 10
});

Inherited from Geometry

PostEffect

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/post-effect.js#L20

Base class for all post effects. Post effects take a render target as input, apply effects to it, and then render the result to an output render target or the screen if no output is specified.

Constructors

constructor

new PostEffect(graphicsDevice: GraphicsDevice)

Create a new PostEffect instance.

Parameters

Properties

device

device: GraphicsDevice

The graphics device of the application.

needsDepthBuffer

needsDepthBuffer: boolean

The property that should to be set to true (by the custom post effect) if a depth map is necessary (default is false).

quadVertexShader

static quadVertexShader: string

A simple vertex shader used to render a quad, which requires 'vec2 aPosition' in the vertex buffer, and generates uv coordinates vUv0 for use in the fragment shader.

Methods

drawQuad

drawQuad(target: RenderTarget | null, shader: Shader, rect?: Vec4): void

Draw a screen-space rectangle in a render target, using a specified shader.

Parameters

render

render(inputTarget: RenderTarget, outputTarget: RenderTarget, rect?: Vec4): void

Render the post effect using the specified inputTarget to the specified outputTarget.

Parameters

PostEffectQueue

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/post-effect-queue.js#L30

Used to manage multiple post effects for a camera. This is the legacy post-processing path. For new work use CameraFrame, which implements bloom, SSAO, depth of field, TAA, volumetric fog and tone mapping as one HDR pipeline; playcanvas/scripts/esm/camera-frame.mjs wraps it as an attachable script.

Constructors

constructor

new PostEffectQueue(app: AppBase, camera: CameraComponent)

Create a new PostEffectQueue instance.

Parameters

Methods

addEffect

addEffect(effect: PostEffect): void

Adds a post effect to the queue. If the queue is disabled adding a post effect will automatically enable the queue.

Parameters

destroy

destroy(): void

Removes all the effects from the queue and disables it.

disable

disable(): void

Disables the queue and all of its effects.

enable

enable(): void

Enables the queue and all of its effects. If there are no effects then the queue will not be enabled.

removeEffect

removeEffect(effect: PostEffect): void

Removes a post effect from the queue. If the queue becomes empty it will be disabled automatically.

Parameters

QuadRender

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/quad-render.js#L54

An object that renders a quad using a Shader.

Note: QuadRender does not modify render states. Before calling render, you should set up the required states using GraphicsDevice#setDrawStates, or the individual setters (GraphicsDevice#setBlendState, GraphicsDevice#setCullMode, GraphicsDevice#setFrontFace, GraphicsDevice#setDepthState, GraphicsDevice#setStencilState). Otherwise previously set states will be used.

Example:

const shader = ShaderUtils.createShader(app.graphicsDevice, {
    uniqueName: 'MyShader',
    attributes: { aPosition: SEMANTIC_POSITION },
    vertexGLSL: '// vertex shader code',
    fragmentGLSL: '// fragment shader code'
});
const quad = new QuadRender(shader);

// Set up render states before rendering (defaults are suitable for full-screen quads)
app.graphicsDevice.setDrawStates();

quad.render();
quad.destroy();

Constructors

constructor

new QuadRender(shader: Shader)

Create a new QuadRender instance.

Parameters

Methods

destroy

destroy(): void

Destroys the resources associated with this instance.

render

render(viewport?: Vec4, scissor?: Vec4, numInstances?: number): void

Renders the quad. If the viewport is provided, the original viewport and scissor is restored after the rendering.

Parameters

RenderComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/render/component.js#L61

The RenderComponent enables an Entity to render 3D meshes. The type property can be set to one of several predefined shapes (such as box, sphere, cone and so on). Alternatively, the component can be configured to manage an arbitrary array of MeshInstances. These can either be created programmatically or loaded from an Asset.

The MeshInstances managed by this component are positioned, rotated, and scaled in world space by the world transformation matrix of the owner Entity. This world matrix is derived by combining the entity's local transformation (position, rotation, and scale) with the world transformation matrix of its parent entity in the scene hierarchy.

You should never need to use the RenderComponent constructor directly. To add a RenderComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('render', {
    type: 'box'
});

Once the RenderComponent is added to the entity, you can access it via the Entity#render property:

entity.render.type = 'capsule';  // Set the render component's type

console.log(entity.render.type); // Get the render component's type and print it

Relevant Engine API examples:

Properties

isStatic

isStatic: boolean = false

Mark meshes as non-movable (optimization).

Accessors

asset

get asset(): number | null
set asset(value: number | null)

Gets the render asset id for the render component.

batchGroupId

get batchGroupId(): number
set batchGroupId(value: number)

Gets the batch group for the mesh instances in this component (see BatchGroup).

castShadows

get castShadows(): boolean
set castShadows(value: boolean)

Gets whether attached meshes will cast shadows for lights that have shadow casting enabled.

castShadowsLightmap

get castShadowsLightmap(): boolean
set castShadowsLightmap(value: boolean)

Gets whether meshes instances will cast shadows when rendering lightmaps.

customAabb

get customAabb(): BoundingBox | null
set customAabb(value: BoundingBox | null)

Gets the custom object space bounding box that is used for visibility culling of attached mesh instances.

layers

get layers(): readonly number[]
set layers(value: readonly number[])

Gets the array of layer IDs (Layer#id) to which the mesh instances belong.

lightmapped

get lightmapped(): boolean
set lightmapped(value: boolean)

Gets whether the component is affected by the runtime lightmapper.

lightmapSizeMultiplier

get lightmapSizeMultiplier(): number
set lightmapSizeMultiplier(value: number)

Gets the lightmap resolution multiplier.

material

get material(): Material
set material(value: Material)

Gets the material Material that will be used to render the component.

materialAssets

get materialAssets(): number[] | Asset<string>[]
set materialAssets(value?: number[] | Asset<string>[])

Gets the material assets that will be used to render the component.

meshInstances

get meshInstances(): readonly MeshInstance[]
set meshInstances(value: readonly MeshInstance[])

Gets the array of meshInstances contained in the component. Use the setter to replace the array; do not mutate the returned array.

receiveShadows

get receiveShadows(): boolean
set receiveShadows(value: boolean)

Gets whether shadows will be cast on attached meshes.

renderStyle

get renderStyle(): number
set renderStyle(renderStyle: number)

Gets the render style of this component's MeshInstances.

rootBone

get rootBone(): Entity | null
set rootBone(value: Entity | null)

Gets the root bone entity for the render component.

shadowCascadeMask

get shadowCascadeMask(): number
set shadowCascadeMask(value: number)

Gets the bitmask that controls which shadow cascades the attached meshes contribute to.

type

get type(): "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus"
set type(value: "plane" | "box" | "capsule" | "cone" | "cylinder" | "sphere" | "asset" | "torus")

Gets the type of the component.

Methods

hide

hide(): void

Stop rendering MeshInstances without removing them from the scene hierarchy. This method sets the MeshInstance#visible property of every MeshInstance to false. Note, this does not remove the mesh instances from the scene hierarchy or draw call list. So the render component still incurs some CPU overhead.

show

show(): void

Enable rendering of the component's MeshInstances if hidden using hide. This method sets the MeshInstance#visible property on all mesh instances to true.

Inherited from Component

RenderComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/render/system.js#L54

Allows an Entity to render a mesh or a primitive shape like a box, capsule, sphere, cylinder, cone etc.

Inherited from ComponentSystem

RenderTarget

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/render-target.js#L94

A render target is a rectangular rendering surface that can be rendered into, instead of the screen. It wraps one or more color buffer Textures and an optional depth (and stencil) buffer. Once a camera or a render pass has rendered into it, the color texture holds the result and can be used anywhere a normal texture can - applied to a material to display it in the scene, or fed into further processing. This underpins effects such as in-world screens, mirrors and portals, reflections, picking and custom multi-pass pipelines.

Usage

Create a texture to render into, wrap it in a render target and assign it to a camera. The texture must use a renderable, uncompressed format:

const texture = new Texture(device, {
    width: 512,
    height: 512,
    format: PIXELFORMAT_SRGBA8,
    mipmaps: false,
    minFilter: FILTER_LINEAR,
    magFilter: FILTER_LINEAR
});

const renderTarget = new RenderTarget({
    colorBuffer: texture,
    depth: true,
    origin: RENDERTARGET_ORIGIN_TOP
});

// the camera renders into the texture instead of the screen
cameraEntity.camera.renderTarget = renderTarget;

// and the texture can be used as any other, for example by a material
material.emissiveMap = texture;

When the result is sampled as a regular texture like this, specify the origin option as RENDERTARGET_ORIGIN_TOP, which stores the image in the same orientation on all graphics APIs. Multiple color buffers can be attached using the colorBuffers option, to render into all of them simultaneously from a single pass (MRT).

A live example: https://playcanvas.github.io/#/graphics/render-to-texture

Multisampling (MSAA)

Set the samples option to a value greater than 1 to render with hardware anti-aliasing. The render target internally allocates a multisampled buffer to render into, and automatically resolves it into the single-sampled colorBuffer at the end of a render pass - the color texture is used the same way as in the single-sampled case.

const renderTarget = new RenderTarget({ colorBuffer: texture, depth: true, samples: 4 });

Explicit multisampled color buffers and custom resolves (WebGPU)

A multisampled texture (a Texture created with samples greater than 1, WebGPU only) can be used as the color buffer directly. The render target then renders into its samples, and the sample count is inferred from the texture. Provide a resolveBuffer to get the standard hardware resolve, or omit it to keep the individual samples: these are then read in a shader using textureLoad on a texture_multisampled_2d, typically by a follow-up pass implementing a custom resolve - an operation the hardware resolve cannot express, such as a tonemapped or min/max resolve. This is also the only way to use multisampling with formats the hardware cannot resolve, such as integer formats.

// a multisampled texture, rendered into directly
const msColor = new Texture(device, {
    width: 512,
    height: 512,
    format: PIXELFORMAT_RGBA16F,
    samples: 4
});

// renders into the samples of msColor, which are stored (no resolve buffer),
// to be read by a custom resolve pass using textureLoad
const renderTarget = new RenderTarget({ colorBuffer: msColor, depth: true });

A live example: https://playcanvas.github.io/#/graphics-advanced/custom-msaa-resolve

Constructors

constructor

new RenderTarget(options?: object)

Creates a new RenderTarget instance. A color buffer or a depth buffer must be set.

Parameters

Example

// Create a 512x512x24-bit render target with a depth buffer
const colorBuffer = new Texture(graphicsDevice, {
    width: 512,
    height: 512,
    format: PIXELFORMAT_RGB8
});
const renderTarget = new RenderTarget({
    colorBuffer: colorBuffer,
    depth: true
});

// Set the render target on a camera component
camera.renderTarget = renderTarget;

// Destroy render target at a later stage. Note that the color buffer needs
// to be destroyed separately.
renderTarget.colorBuffer.destroy();
renderTarget.destroy();
camera.renderTarget = null;

Properties

autoResolve

autoResolve: boolean

name

name: string

The name of the render target.

Accessors

colorBuffer

get colorBuffer(): Texture

Color buffer set up on the render target.

colorBufferCount

get colorBufferCount(): number

The number of color buffers (attachments) set up on the render target.

depth

get depth(): boolean

True if the render target contains the depth attachment.

depthBuffer

get depthBuffer(): Texture

Depth buffer set up on the render target. Only available, if depthBuffer was set in constructor. Not available if depth property was used instead.

depthResolveBuffer

get depthResolveBuffer(): Texture | null

The single-sampled texture the multisampled depth buffer is resolved into at the end of a render pass. See the depthResolveBuffer constructor option. Null when not provided.

depthResolveMode

get depthResolveMode(): string
set depthResolveMode(value: string)

Gets how the samples of the multisampled depth buffer are resolved into a single depth value.

face

get face(): number

If the render target is bound to a cubemap, this property specifies which face of the cubemap is rendered to. Can be:

height

get height(): number

Height of the render target in pixels.

mipLevel

get mipLevel(): number

Mip level of the render target.

mipmaps

get mipmaps(): boolean

True if the mipmaps are automatically generated for the color buffer(s) if it contains a mip chain.

origin

get origin(): string

Gets the vertical orientation of the image stored in this render target, as resolved at construction from the origin option, or derived from the deprecated flipY option or property. Can be RENDERTARGET_ORIGIN_TOP, RENDERTARGET_ORIGIN_BOTTOM or RENDERTARGET_ORIGIN_NATIVE. See the origin option of the constructor for details.

resolveBuffer

get resolveBuffer(): Texture | null

The resolve texture of the first color attachment, when the render target uses explicit multisampled color buffers and a resolve buffer was provided. See the resolveBuffer constructor option. Null otherwise.

samples

get samples(): number

Number of antialiasing samples the render target uses.

stencil

get stencil(): boolean

True if the render target contains the stencil attachment.

transientColor

get transientColor(): boolean

True if the multi-sampled color attachment is allocated as a transient ("memoryless") attachment (WebGPU only). See the transientColor constructor option.

transientDepth

get transientDepth(): boolean

True if the depth attachment is allocated as a transient ("memoryless") attachment (WebGPU only). See the transientDepth constructor option.

width

get width(): number

Width of the render target in pixels.

Methods

copy

copy(source: RenderTarget, color?: boolean, depth?: boolean): boolean

Copies color and/or depth contents of source render target to this one. Formats, sizes and anti-aliasing samples must match.

A depth copy is supported in these cases:

Parameters

Returns boolean: True if the copy was successful, false otherwise.

destroy

destroy(): void

Frees resources associated with this render target.

getColorBuffer

getColorBuffer(index: number): Texture

Accessor for multiple render target color buffers.

Parameters

Returns Texture: - Color buffer at the specified index.

getResolveBuffer

getResolveBuffer(index?: number): Texture | null

Accessor for the per-attachment resolve textures. See the resolveBuffers constructor option.

Parameters

Returns Texture | null: - The resolve texture at the specified index, or null when the attachment has none.

resize

resize(width: number, height: number): void

Resizes the render target to the specified width and height. Internally this resizes all the assigned texture color and depth buffers.

Parameters

resolve

resolve(color?: boolean, depth?: boolean): void

If samples > 1, resolves the anti-aliased render target (WebGL2 only). When you're rendering to an anti-aliased render target, pixels aren't written directly to the readable texture. Instead, they're first written to an MSAA buffer, where each sample for each pixel is stored independently. In order to read the results, you first need to 'resolve' the buffer - to average all samples and create a simple texture with one color per pixel. This function performs this averaging and updates the colorBuffer and the depthBuffer. If autoResolve is set to true, the resolve will happen after every rendering to this render target, otherwise you can do it manually, during the app update or similar.

Parameters

RenderView

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/render-view.js#L13

Represents a single view of the scene - a region of the render target rendered from a single viewpoint. A standard camera produces one view, while in XR each eye (or screen) is a separate view. This is the base class for XrView.

Accessors

viewport

get viewport(): Vec4

A Vec4 (x, y, width, height) that represents the view's viewport. For a monoscopic screen it defines the fullscreen view; for stereoscopic views (left/right eye) it defines the part of the screen the view occupies.

Inherited from EventHandler

Scene

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/scene.js#L56

A scene is a graphical representation of an environment. It manages the scene hierarchy, all graphical objects, lights, and scene-wide properties.

Each application has one at AppBase#scene. The scene owns the rendering setup that is not tied to a single entity: the layers composition that decides render order; the lighting environment through ambientLight, skybox, envAtlas and the sky and lighting parameter objects; exposure, or physicalUnits in its place, for overall brightness; the lightmapping settings; and the fog described below.

The scene fires prerender and postrender for each camera that renders it, and precull and postcull around visibility culling. Per-frame work that needs to know the camera belongs in those handlers.

Fog is scene-wide: fog is a read-only FogParams whose type, color, start and end you set, and CameraComponent#fog can override it for a single camera.

Example

// Light the scene from a prefiltered environment and brighten it slightly
app.scene.envAtlas = envAtlasAsset.resource;
app.scene.skybox = skyboxAsset.resource;
app.scene.exposure = 1.2;

Example

// Run code for each camera just before it renders the scene
app.scene.on('prerender', (camera) => {
    // camera is the CameraComponent about to render
});

Properties

ambientBake

ambientBake: boolean = false

If enabled, the ambient lighting will be baked into lightmaps. This will be either the skybox if set up, otherwise ambientLight. Defaults to false.

ambientBakeOcclusionBrightness

ambientBakeOcclusionBrightness: number = 0

If ambientBake is true, this specifies the brightness of ambient occlusion. Typical range is -1 to 1. Defaults to 0, representing no change to brightness.

ambientBakeOcclusionContrast

ambientBakeOcclusionContrast: number = 0

If ambientBake is true, this specifies the contrast of ambient occlusion. Typical range is -1 to 1. Defaults to 0, representing no change to contrast.

ambientLight

ambientLight: Color

The color of the scene's ambient light, specified in sRGB color space. Defaults to black (0, 0, 0).

ambientLuminance

ambientLuminance: number = 0

The luminosity of the scene's ambient light in lux (lm/m^2). Used if physicalUnits is true. Defaults to 0.

exposure

exposure: number = 1

The exposure value tweaks the overall brightness of the scene. Ignored if physicalUnits is true. Defaults to 1.

lightmapFilterEnabled

lightmapFilterEnabled: boolean = false

Enables bilateral filter on runtime baked color lightmaps, which removes the noise and banding while preserving the edges. Defaults to false. Note that the filtering takes place in the image space of the lightmap, and it does not filter across lightmap UV space seams, often making the seams more visible. It's important to balance the strength of the filter with number of samples used for lightmap baking to limit the visible artifacts.

lightmapHDR

lightmapHDR: boolean = false

Enables HDR lightmaps. This can result in smoother lightmaps especially when many samples are used. Defaults to false.

lightmapMaxResolution

lightmapMaxResolution: number = 2048

The maximum lightmap resolution. Defaults to 2048.

lightmapMode

lightmapMode: number = BAKE_COLORDIR

The lightmap baking mode. Can be:

Defaults to BAKE_COLORDIR.

lightmapSizeMultiplier

lightmapSizeMultiplier: number = 1

The lightmap resolution multiplier. Defaults to 1.

physicalUnits

physicalUnits: boolean = false

Use physically based units for cameras and lights. When used, the exposure value is ignored.

root

root: Entity = null

The root entity of the scene, which is usually the only child to the Application root entity.

Accessors

ambientBakeNumSamples

get ambientBakeNumSamples(): number
set ambientBakeNumSamples(value: number)

Gets the number of samples used to bake the ambient light into the lightmap.

ambientBakeSpherePart

get ambientBakeSpherePart(): number
set ambientBakeSpherePart(value: number)

Gets the part of the sphere which represents the source of ambient light.

clusteredLightingEnabled

get clusteredLightingEnabled(): boolean
set clusteredLightingEnabled(value: boolean)

Gets whether clustered lighting is enabled.

envAtlas

get envAtlas(): Texture | null
set envAtlas(value: Texture | null)

Gets the environment lighting atlas.

fog

get fog(): FogParams

Gets the FogParams that define fog parameters.

gsplat

get gsplat(): GSplatParams

Gets the GSplat parameters.

layers

get layers(): LayerComposition
set layers(layers: LayerComposition)

Gets the LayerComposition that defines rendering order of this scene.

lighting

get lighting(): LightingParams

Gets the LightingParams that define lighting parameters.

lightmapFilterRange

get lightmapFilterRange(): number
set lightmapFilterRange(value: number)

Gets the range parameter of the bilateral filter.

lightmapFilterSmoothness

get lightmapFilterSmoothness(): number
set lightmapFilterSmoothness(value: number)

Gets the spatial parameter of the bilateral filter.

lightmapPixelFormat

get lightmapPixelFormat(): number

Gets the lightmap pixel format.

prefilteredCubemaps

get prefilteredCubemaps(): Texture[]
set prefilteredCubemaps(value: Texture[])

Gets the 6 prefiltered cubemaps acting as the source of image-based lighting.

sky

get sky(): Sky

Gets the Sky that defines sky properties.

skybox

get skybox(): Texture | null
set skybox(value: Texture | null)

Gets the base cubemap texture used as the scene's skybox when skyboxMip is 0.

skyboxHighlightMultiplier

get skyboxHighlightMultiplier(): number
set skyboxHighlightMultiplier(value: number)

Gets the highlight multiplied for the skybox.

skyboxIntensity

get skyboxIntensity(): number
set skyboxIntensity(value: number)

Gets the multiplier for skybox intensity.

skyboxLuminance

get skyboxLuminance(): number
set skyboxLuminance(value: number)

Gets the luminance (in lm/m^2) of the skybox.

skyboxMip

get skyboxMip(): number
set skyboxMip(value: number)

Gets the mip level of the skybox to be displayed.

skyboxRotation

get skyboxRotation(): Readonly<Quat>
set skyboxRotation(value: Readonly<Quat>)

Gets the rotation of the skybox to be displayed. Use the setter to update skybox state.

Methods

setSkybox

setSkybox(cubemaps?: Texture[]): void

Sets the cubemap for the scene skybox.

Parameters

Events

EVENT_POSTCULL

static EVENT_POSTCULL: string = 'postcull'

Fired after mesh instance visibility culling is performed for a camera; mesh instance visibility (such as MeshInstance#visibleThisFrame) is up to date when this fires. The handler is passed the CameraComponent that was culled, or null when the culling is internal (for example when culling shadow casters for a light's shadow map).

Example

app.scene.on('postcull', (camera) => {
   if (camera) {
       console.log(`Visibility culling was performed for camera ${camera.entity.name}`);
   }
});

EVENT_POSTRENDER

static EVENT_POSTRENDER: string = 'postrender'

Fired when the camera renders the scene. The handler is passed the CameraComponent that rendered the scene.

Example

app.scene.on('postrender', (camera) => {
   console.log(`Camera ${camera.entity.name} rendered the scene`);
});

EVENT_POSTRENDER_LAYER

static EVENT_POSTRENDER_LAYER: string = 'postrender:layer'

Fired when the camera renders a layer. The handler is passed the CameraComponent, the Layer that will be rendered, and a boolean parameter set to true if the layer is transparent. This is called during rendering to a render target or a default framebuffer, and additional rendering can be performed here, for example using QuadRender#render.

Example

app.scene.on('postrender:layer', (camera, layer, transparent) => {
   console.log(`Camera ${camera.entity.name} rendered the layer ${layer.name} (transparent: ${transparent})`);
});

EVENT_PRECULL

static EVENT_PRECULL: string = 'precull'

Fired before mesh instance visibility culling is performed for a camera, just before the camera's culling frustum is refreshed (so a handler may still adjust the camera). The handler is passed the CameraComponent being culled, or null when the culling is internal (for example when culling shadow casters for a light's shadow map). Note that light visibility culling happens earlier in the frame and is not bracketed by this event.

Example

app.scene.on('precull', (camera) => {
   if (camera) {
       console.log(`Visibility culling will be performed for camera ${camera.entity.name}`);
   }
});

EVENT_PRERENDER

static EVENT_PRERENDER: string = 'prerender'

Fired before the camera renders the scene. The handler is passed the CameraComponent that will render the scene.

Example

app.scene.on('prerender', (camera) => {
   console.log(`Camera ${camera.entity.name} will render the scene`);
});

EVENT_PRERENDER_LAYER

static EVENT_PRERENDER_LAYER: string = 'prerender:layer'

Fired before the camera renders a layer. The handler is passed the CameraComponent, the Layer that will be rendered, and a boolean parameter set to true if the layer is transparent. This is called during rendering to a render target or a default framebuffer, and additional rendering can be performed here, for example using QuadRender#render.

Example

app.scene.on('prerender:layer', (camera, layer, transparent) => {
   console.log(`Camera ${camera.entity.name} will render the layer ${layer.name} (transparent: ${transparent})`);
});

EVENT_SETLAYERS

static EVENT_SETLAYERS: string = 'set:layers'

Fired when the layer composition is set. Use this event to add callbacks or advanced properties to your layers. The handler is passed the old and the new LayerComposition.

Example

app.scene.on('set:layers', (oldComp, newComp) => {
    const list = newComp.layerList;
    for (let i = 0; i < list.length; i++) {
        const layer = list[i];
        switch (layer.name) {
            case 'MyLayer':
                layer.onEnable = myOnEnableFunction;
                layer.onDisable = myOnDisableFunction;
                break;
            case 'MyOtherLayer':
                layer.clearColorBuffer = true;
                break;
        }
    }
});

EVENT_SETSKYBOX

static EVENT_SETSKYBOX: string = 'set:skybox'

Fired when the skybox is set. The handler is passed the Texture that is the previously used skybox cubemap texture. The new skybox cubemap texture is in the skybox property.

Example

app.scene.on('set:skybox', (oldSkybox) => {
    console.log(`Skybox changed from ${oldSkybox.name} to ${app.scene.skybox.name}`);
});

Inherited from EventHandler

SceneDepthReader

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/graphics/scene-depth-reader.js#L59

Reads the scene depth of a camera back to the CPU.

A sample is the distance from the camera to the surface at that point, in world units, measured along the camera's view direction.

Reads are asynchronous and land a frame or two later. Any number of them may be in flight at once, so a read can be issued every frame without waiting for the previous one to finish.

Note that something has to be rendering the depth for there to be anything to read: an effect which consumes it, or CameraComponent#requestSceneDepthMap.

const reader = new SceneDepthReader(camera.camera);
const rect = new Vec4(0.45, 0.45, 0.1, 0.1);

app.on('update', () => {
    reader.read(rect, 8, 8)?.then((samples) => {
        const hit = samples.filter(Number.isFinite);
        console.log(hit.length ? Math.min(...hit) : 'nothing in view');
    });
});

Constructors

constructor

new SceneDepthReader(camera: CameraComponent)

Parameters

Methods

destroy

destroy(): void

Frees the resources the reader owns and stops reading for this camera. Reads which have not been rendered yet report their region as empty, and one already in flight does the same once it completes, rather than writing samples read through resources this has let go of.

read

read(rect: Vec4, width: number, height: number, target?: Float32Array<ArrayBufferLike>): Promise<Float32Array<ArrayBufferLike>> | null

Requests the depth of a region of the view, as width * height samples in row major order. The region is point sampled rather than averaged - one sample per cell, taken at its centre - so asking for more samples than the region resolves to repeats them.

Samples where nothing was rendered read as Infinity, as do the few which land within a hair of the far clip, that being the depth an empty pixel reports.

Note that on a device which stores the scene depth at a lower precision - see GSplatParams#sceneDepthWrite - a far clip beyond about 16384 leaves an empty pixel reporting a large distance rather than Infinity, as the two stop being far enough apart to tell one from the other.

Parameters

Returns Promise<Float32Array<ArrayBufferLike>> | null: The samples, in world units, or null when the camera is disabled or is not rendering a scene depth, leaving nothing to read.

SceneRegistry

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L56

Container for storing and loading of scenes. An instance of the registry is created on the AppBase object as AppBase#scenes.

Constructors

constructor

new SceneRegistry(app: AppBase)

Create a new SceneRegistry instance.

Parameters

Methods

add

add(name: string, url: string): boolean

Add a new item to the scene registry.

Parameters

Returns boolean: Returns true if the scene was successfully added to the registry, false otherwise.

changeScene

changeScene(sceneItem: string | SceneRegistryItem, callback?: ChangeSceneCallback): void

Change to a new scene. Calling this function will load the scene data, delete all entities and graph nodes under app.root and load the scene settings and hierarchy.

Parameters

Example

app.scenes.changeScene("Scene Name", (err, entity) => {
    if (!err) {
        // success
    } else {
        // error
    }
});

find

find(name: string): SceneRegistryItem | null

Find a Scene by name and return the SceneRegistryItem.

Parameters

Returns SceneRegistryItem | null: The stored data about a scene or null if no scene with that name exists.

findByUrl

findByUrl(url: string): SceneRegistryItem | null

Find a scene by the URL and return the SceneRegistryItem.

Parameters

Returns SceneRegistryItem | null: The stored data about a scene or null if no scene with that URL exists.

list

list(): SceneRegistryItem[]

Return the list of scene.

Returns SceneRegistryItem[]: All items in the registry.

loadScene

loadScene(url: string, callback: LoadSceneCallback): void

Load the scene hierarchy and scene settings. This is an internal method used by the AppBase.

Parameters

loadSceneData

loadSceneData(sceneItem: string | SceneRegistryItem, callback: LoadSceneDataCallback): void

Loads and stores the scene data to reduce the number of the network requests when the same scenes are loaded multiple times. Can also be used to load data before calling loadSceneHierarchy and loadSceneSettings to make scene loading quicker for the user.

Parameters

Example

const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneData(sceneItem, (err, sceneItem) => {
    if (err) {
        // error
    }
});

loadSceneHierarchy

loadSceneHierarchy(sceneItem: string | SceneRegistryItem, callback: LoadHierarchyCallback): void

Load a scene file, create and initialize the Entity hierarchy and add the hierarchy to the application root Entity.

Parameters

Example

const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneHierarchy(sceneItem, (err, entity) => {
    if (!err) {
        const e = app.root.find("My New Entity");
    } else {
        // error
    }
});

loadSceneSettings

loadSceneSettings(sceneItem: string | SceneRegistryItem, callback: LoadSettingsCallback): void

Load a scene file and apply the scene settings to the current scene.

Parameters

Example

const sceneItem = app.scenes.find("Scene Name");
app.scenes.loadSceneSettings(sceneItem, (err) => {
    if (!err) {
        // success
    } else {
        // error
    }
});

remove

remove(name: string): void

Remove an item from the scene registry.

Parameters

unloadSceneData

unloadSceneData(sceneItem: string | SceneRegistryItem): void

Unloads scene data that has been loaded previously using loadSceneData.

Parameters

Example

const sceneItem = app.scenes.find("Scene Name");
app.scenes.unloadSceneData(sceneItem);

SceneRegistryItem

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry-item.js#L6

Item to be stored in the SceneRegistry.

Constructors

constructor

new SceneRegistryItem(name: string, url: string)

Creates a new SceneRegistryItem instance.

Parameters

Properties

name

name: string

The name of the scene.

url

url: string

The url of the scene file.

Accessors

loaded

get loaded(): boolean

Returns true if the scene data has loaded.

loading

get loading(): boolean

Returns true if the scene data is still being loaded.

ScopeId

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/scope-id.js#L8

The scope for a variable.

Constructors

constructor

new ScopeId(name: string)

Create a new ScopeId instance.

Parameters

Properties

name

name: string

The variable name.

Methods

getValue

getValue(): any

Get variable value.

Returns any: The value.

setValue

setValue(value: any): void

Set variable value.

Parameters

ScopeSpace

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/scope-space.js#L8

The scope for variables.

Constructors

constructor

new ScopeSpace(name: string)

Create a new ScopeSpace instance.

Parameters

Properties

name

name: string

The scope name.

Methods

resolve

resolve(name: string): ScopeId

Get (or create, if it doesn't already exist) a variable in the scope.

Parameters

Returns ScopeId: The variable instance.

Shader

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/shader.js#L29

A shader is a program that is responsible for rendering graphical primitives on a device's graphics processor. The shader is generated from a shader definition. This shader definition specifies the code for processing vertices and fragments processed by the GPU. The language of the code is GLSL (or more specifically ESSL, the OpenGL ES Shading Language). The shader definition also describes how the PlayCanvas engine should map vertex buffer elements onto the attributes specified in the vertex shader code.

Constructors

constructor

new Shader(graphicsDevice: GraphicsDevice, definition: object)

Creates a new Shader instance.

Consider ShaderUtils.createShader as a simpler and more powerful way to create a shader.

Parameters

Example

// Create a shader that renders primitives with a solid red color

// Vertex shader
const vshader = `
attribute vec3 aPosition;

void main(void) {
    gl_Position = vec4(aPosition, 1.0);
}
`;

// Fragment shader
const fshader = `
precision ${graphicsDevice.precision} float;

void main(void) {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;

const shaderDefinition = {
    attributes: {
        aPosition: SEMANTIC_POSITION
    },
    vshader,
    fshader
};

const shader = new Shader(graphicsDevice, shaderDefinition);

Methods

destroy

destroy(): void

Frees resources associated with this shader.

ShaderChunkMap

Class · extends Map · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunk-map.js#L19

A collection of shader chunks, used by ShaderChunks. This is a map of shader chunk names to their code. As this class extends Map, it can be used as a Map as well in addition to custom functionality it provides.

Methods

add

add(object: any, override?: boolean): ShaderChunkMap

Adds multiple shader chunks to the Map. This method accepts an object where the keys are the names of the shader chunks and the values are the shader source code. If an element with the same name already exists, the element will be updated.

Parameters

Returns ShaderChunkMap: The ShaderChunkMap instance.

clear

clear(): void

Removes all shader chunks from the Map.

delete

delete(name: string): boolean

Removes a shader chunk by name from the Map. If the element does not exist, no action is taken.

Parameters

Returns boolean: True if an element in the Map existed and has been removed, or false if the element does not exist.

set

set(name: string, code: string): ShaderChunkMap

Adds a new shader chunk with a specified name and shader source code to the Map. If an element with the same name already exists, the element will be updated.

Parameters

Returns ShaderChunkMap: The ShaderChunkMap instance.

ShaderChunks

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunks.js#L18

A collection of GLSL and WGSL shader chunks, used to generate shaders.

Properties

version

version: string = ''

Specifies the API version of the shader chunks.

This should be a string containing the current engine major and minor version (e.g., '2.8' for engine v2.8.1) and ensures compatibility with the current engine version. When providing custom shader chunks, set this to the latest supported version. If a future engine release no longer supports the specified version, a warning will be issued. In that case, update your shader chunks to match the new format and set this to the latest version accordingly.

Methods

get

static get(device: GraphicsDevice, shaderLanguage?: string): ShaderChunkMap

Returns a shader chunks map for the given device and shader language.

Parameters

Returns ShaderChunkMap: The shader chunks for the specified language.

ShaderMaterial

Class · extends Material · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/shader-material.js#L66

A ShaderMaterial is a type of material that utilizes a specified shader for rendering purposes.

Use it when a surface cannot be expressed with StandardMaterial properties or shader chunk overrides. The shader is described by a ShaderDesc: a uniqueName, vertex and fragment source in GLSL for WebGL, in WGSL for WebGPU, or both, and an attributes map from shader inputs to SEMANTIC_* values so the engine can bind vertex data. Provide both languages when the application must run on both backends. The engine supplies the standard uniforms a shader declares by name, such as matrix_viewProjection; your own uniforms are set with Material#setParameter. Render state such as Material#blendType, Material#cull and Material#depthWrite comes from Material. Lighting, fog and shadows are not generated for you; the shader draws exactly what it is written to draw.

A simple example which creates a material with custom vertex and fragment shaders specified in GLSL format:

const material = new ShaderMaterial({
    uniqueName: 'MyShader',
    attributes: { aPosition: SEMANTIC_POSITION },
    vertexGLSL: `
        attribute vec3 aPosition;
        uniform mat4 matrix_viewProjection;
        void main(void)
        {
            gl_Position = matrix_viewProjection * pos;
        }`,
    fragmentGLSL: `
        void main(void) {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }`
});

Constructors

constructor

new ShaderMaterial(shaderDesc?: ShaderDesc)

Create a new ShaderMaterial instance.

Parameters

Accessors

shaderDesc

get shaderDesc(): ShaderDesc | undefined
set shaderDesc(value: ShaderDesc | undefined)

Gets the shader description.

Methods

copy

copy(source: ShaderMaterial): ShaderMaterial

Copy a ShaderMaterial.

Parameters

Returns ShaderMaterial: The destination material.

Inherited from Material

ShaderUtils

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-utils.js#L43

Utility class for creating shaders. Provides a higher-level API over the Shader constructor, handling cross-API concerns such as GLSL/WGSL selection and translation, shader caching, include and define resolution, and attaching commonly used extensions and precision qualifiers.

Methods

createShader

static createShader(device: GraphicsDevice, options: object): Shader

Creates a shader. When the active graphics device is WebGL, the provided GLSL vertex and fragment source code is used. For WebGPU, if WGSL vertex and fragment source code is supplied, it is used directly; otherwise, the system automatically translates the provided GLSL code into WGSL. In the case of GLSL shaders, additional blocks are appended to both the vertex and fragment source code to support extended features and maintain compatibility. These additions include the shader version declaration, precision qualifiers, and commonly used extensions, and therefore should be excluded from the user-supplied GLSL source. Note: The shader has access to all registered shader chunks via the #include directive. Any provided includes will be applied as overrides on top of those.

Parameters

Returns Shader: The newly created shader.

Skin

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skin.js#L13

A skin contains data about the bones in a hierarchy that drive a skinned mesh animation. Specifically, the skin stores the bone name and inverse bind matrix and for each bone. Inverse bind matrices are instrumental in the mathematics of vertex skinning.

Constructors

constructor

new Skin(graphicsDevice: GraphicsDevice, ibp: Mat4[], boneNames: string[])

Create a new Skin instance.

Parameters

SkinInstance

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skin-instance.js#L21

A skin instance is responsible for generating the matrix palette that is used to skin vertices from object space to world space.

Constructors

constructor

new SkinInstance(skin: Skin)

Create a new SkinInstance instance.

Parameters

Properties

bones

bones: GraphNode[]

An array of nodes representing each bone in this skin instance.

Methods

initSkin

initSkin(skin: Skin): void

Parameters

Sky

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/skybox/sky.js#L16

Implementation of the sky.

Properties

node

readonly node: GraphNode

A graph node with a transform used to render the sky mesh. Adjust the position, rotation and scale of this node to orient the sky mesh. Ignored for SKYTYPE_INFINITE.

Accessors

center

get center(): Vec3
set center(value: Vec3)

Gets the center of the sky.

depthWrite

get depthWrite(): boolean
set depthWrite(value: boolean)

Gets whether depth writing is enabled for the sky.

fisheye

get fisheye(): number
set fisheye(value: number)

Gets the fisheye projection strength for the sky.

type

get type(): string
set type(value: string)

Gets the type of the sky.

SphereGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/sphere-geometry.js#L33

A procedural sphere-shaped geometry.

Typically, you would:

  1. Create a SphereGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new SphereGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new SphereGeometry(opts?: object)

Create a new SphereGeometry instance.

By default, the constructor creates a sphere centered on the object space origin with a radius of 0.5 and 16 segments in both longitude and latitude. The sphere is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new SphereGeometry({
    radius: 1,
    latitudeBands: 32,
    longitudeBands: 32
});

Inherited from TorusGeometry

Inherited from Geometry

Sprite

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/sprite.js#L33

A Sprite contains references to one or more frames of a TextureAtlas. It can be used by the SpriteComponent or the ElementComponent to render a single frame or a sprite animation.

Constructors

constructor

new Sprite(device: GraphicsDevice, options?: object)

Create a new Sprite instance.

Parameters

Accessors

atlas

get atlas(): TextureAtlas
set atlas(value: TextureAtlas)

Gets the texture atlas.

frameKeys

get frameKeys(): string[]
set frameKeys(value: string[])

Gets the keys of the frames in the sprite atlas that this sprite is using.

meshes

get meshes(): Mesh[]

An array that contains a mesh for each frame.

pixelsPerUnit

get pixelsPerUnit(): number
set pixelsPerUnit(value: number)

Gets the number of pixels that map to one PlayCanvas unit.

renderMode

get renderMode(): number
set renderMode(value: number)

Sets the rendering mode of the sprite.

Methods

destroy

destroy(): void

Free up the meshes created by the sprite.

Inherited from EventHandler

SpriteAnimationClip

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/sprite-animation-clip.js#L17

Handles playing of sprite animations and loading of relevant sprite assets.

Constructors

constructor

new SpriteAnimationClip(component: SpriteComponent, data: object)

Create a new SpriteAnimationClip instance.

Parameters

Properties

fps

fps: number = 0

Frames per second for this animation clip. A negative value plays the animation backwards.

loop

loop: boolean = false

Whether to loop the animation clip when it reaches the end.

name

name: string | undefined

The name of this animation clip.

Accessors

duration

get duration(): number

Gets the total duration of the animation in seconds.

frame

get frame(): number
set frame(value: number)

Gets the index of the frame of the Sprite currently being rendered.

isPaused

get isPaused(): boolean

Sets whether the animation is currently paused.

isPlaying

get isPlaying(): boolean

Sets whether the animation is currently playing.

sprite

get sprite(): Sprite
set sprite(value: Sprite)

Gets the current sprite used to play the animation.

spriteAsset

get spriteAsset(): number
set spriteAsset(value: number)

Gets the id of the sprite asset used to play the animation.

time

get time(): number
set time(value: number)

Gets the current time of the animation in seconds.

Methods

pause

pause(): void

Pauses the animation.

play

play(): void

Plays the animation. If it's already playing then this does nothing.

resume

resume(): void

Resumes the paused animation.

stop

stop(): void

Stops the animation and resets the animation to the first frame.

Events

EVENT_END

static EVENT_END: string = 'end'

Fired when the clip stops playing because it reached its end.

Example

clip.on('end', () => {
    console.log('Clip ended');
});

EVENT_LOOP

static EVENT_LOOP: string = 'loop'

Fired when the clip reached the end of its current loop.

Example

clip.on('loop', () => {
    console.log('Clip looped');
});

EVENT_PAUSE

static EVENT_PAUSE: string = 'pause'

Fired when the clip is paused.

Example

clip.on('pause', () => {
    console.log('Clip paused');
});

EVENT_PLAY

static EVENT_PLAY: string = 'play'

Fired when the clip starts playing.

Example

clip.on('play', () => {
    console.log('Clip started playing');
});

EVENT_RESUME

static EVENT_RESUME: string = 'resume'

Fired when the clip is resumed.

Example

clip.on('resume', () => {
    console.log('Clip resumed');
});

EVENT_STOP

static EVENT_STOP: string = 'stop'

Fired when the clip is stopped.

Example

clip.on('stop', () => {
    console.log('Clip stopped');
});

Inherited from EventHandler

SpriteComponent

Class · extends Component · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/component.js#L65

The SpriteComponent enables an Entity to render a simple static sprite or sprite animations. The type property can be set to either SPRITETYPE_SIMPLE to render a single frame from a sprite asset, or SPRITETYPE_ANIMATED to play one or more SpriteAnimationClips.

You should never need to use the SpriteComponent constructor directly. To add a SpriteComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('sprite', {
    spriteAsset: spriteAsset
});

Once the SpriteComponent is added to the entity, you can access it via the Entity#sprite property:

entity.sprite.color = Color.RED; // Tint the sprite red

console.log(entity.sprite.color);   // Get the sprite tint and print it

Relevant Engine API examples:

Accessors

autoPlayClip

get autoPlayClip(): string
set autoPlayClip(value: string)

Gets the name of the clip to play automatically when the component is enabled.

batchGroupId

get batchGroupId(): number
set batchGroupId(value: number)

Gets the batch group for the sprite.

clips

get clips(): {}
set clips(value: {})

Gets the dictionary that contains SpriteAnimationClips.

color

get color(): Readonly<Color>
set color(value: Readonly<Color>)

Gets the color tint of the sprite in sRGB color space. Use the setter to update the tint.

currentClip

get currentClip(): SpriteAnimationClip

Gets the current clip being played.

drawOrder

get drawOrder(): number
set drawOrder(value: number)

Gets the draw order of the component.

flipX

get flipX(): boolean
set flipX(value: boolean)

Gets whether to flip the X axis when rendering a sprite.

flipY

get flipY(): boolean
set flipY(value: boolean)

Gets whether to flip the Y axis when rendering a sprite.

frame

get frame(): number
set frame(value: number)

Gets which frame from the current sprite asset to render.

height

get height(): number
set height(value: number)

Gets the height of the sprite when rendering using 9-Slicing.

layers

get layers(): readonly number[]
set layers(value: readonly number[])

Gets the array of layer IDs (Layer#id) to which this sprite belongs.

opacity

get opacity(): number
set opacity(value: number)

Gets the opacity of the sprite.

speed

get speed(): number
set speed(value: number)

Gets the global speed modifier used when playing sprite animation clips.

sprite

get sprite(): Sprite
set sprite(value: Sprite)

Gets the current sprite.

spriteAsset

get spriteAsset(): number | Asset<string>
set spriteAsset(value: number | Asset<string>)

Gets the asset id or the Asset of the sprite to render.

type

get type(): string
set type(value: string)

Gets the type of the SpriteComponent.

width

get width(): number
set width(value: number)

Gets the width of the sprite when rendering using 9-Slicing.

Methods

addClip

addClip(data: object): SpriteAnimationClip

Creates and adds a new SpriteAnimationClip to the component's clips.

Parameters

Returns SpriteAnimationClip: The new clip that was added.

clip

clip(name: string): SpriteAnimationClip

Get an animation clip by name.

Parameters

Returns SpriteAnimationClip: The clip.

pause

pause(): void

Pauses the current animation clip.

play

play(name: string): SpriteAnimationClip

Plays a sprite animation clip by name. If the animation clip is already playing then this will do nothing.

Parameters

Returns SpriteAnimationClip: The clip that started playing.

removeClip

removeClip(name: string): void

Removes a clip by name.

Parameters

resume

resume(): void

Resumes the current paused animation clip.

stop

stop(): void

Stops the current animation clip and resets it to the first frame.

Events

EVENT_END

static EVENT_END: string = 'end'

Fired when an animation clip stops playing because it reached its end. The handler is passed the SpriteAnimationClip that ended.

Example

entity.sprite.on('end', (clip) => {
    console.log(`Animation clip ${clip.name} ended.`);
});

EVENT_LOOP

static EVENT_LOOP: string = 'loop'

Fired when an animation clip reached the end of its current loop. The handler is passed the SpriteAnimationClip that looped.

Example

entity.sprite.on('loop', (clip) => {
    console.log(`Animation clip ${clip.name} looped.`);
});

EVENT_PAUSE

static EVENT_PAUSE: string = 'pause'

Fired when an animation clip is paused. The handler is passed the SpriteAnimationClip that was paused.

Example

entity.sprite.on('pause', (clip) => {
    console.log(`Animation clip ${clip.name} paused.`);
});

EVENT_PLAY

static EVENT_PLAY: string = 'play'

Fired when an animation clip starts playing. The handler is passed the SpriteAnimationClip that started playing.

Example

entity.sprite.on('play', (clip) => {
    console.log(`Animation clip ${clip.name} started playing.`);
});

EVENT_RESUME

static EVENT_RESUME: string = 'resume'

Fired when an animation clip is resumed. The handler is passed the SpriteAnimationClip that was resumed.

Example

entity.sprite.on('resume', (clip) => {
    console.log(`Animation clip ${clip.name} resumed.`);
});

EVENT_STOP

static EVENT_STOP: string = 'stop'

Fired when an animation clip is stopped. The handler is passed the SpriteAnimationClip that was stopped.

Example

entity.sprite.on('stop', (clip) => {
    console.log(`Animation clip ${clip.name} stopped.`);
});

Inherited from Component

SpriteComponentSystem

Class · extends ComponentSystem · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/system.js#L41

Manages the SpriteComponents of an application. Reach it through app.systems.sprite; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

StandardMaterial

Class · extends Material · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material.js#L627

A standard material is the main, general purpose material that is most often used for rendering. It can approximate a wide variety of surface types and can simulate dynamic reflected light. Most maps can use 3 types of input values in any combination: constant (Color or number), mesh vertex colors and a Texture. All enabled inputs are multiplied together. A texture samples one of the mesh's UV sets, selected by the map's UV channel property (0 to 7), and is ignored when the mesh does not provide that set. UV sets 6 and 7 share their vertex attribute locations with the default hardware instancing format, so an instanced mesh sampling them needs a custom instancing vertex format, see MeshInstance#setInstancing.

A property assignment only reaches the GPU once Material#update is called: a diffuse or emissive change made after the material's first frame is not applied until material.update() runs. The debug build reports unapplied changes to the properties stored in the material uniform buffer, such as diffuse.

Properties come in families that share a naming pattern. A family such as diffuse has a constant (diffuse), a texture (diffuseMap) with its diffuseMapUv, diffuseMapTiling, diffuseMapOffset, diffuseMapRotation and diffuseMapChannel, and a vertex color switch (diffuseVertexColor). The main families are diffuse; specular, or metalness when useMetalness is set; gloss; normalMap with bumpiness; emissive; opacity together with Material#blendType; ao; lightMap; and the advanced layers clearCoat, sheen, iridescence and refraction. Lighting can be turned off entirely with useLighting.

To go beyond the properties, replace individual shader chunks with Material#getShaderChunks. When the surface is not a lit material at all, use ShaderMaterial instead.

Example

const material = new StandardMaterial();
material.diffuse.set(0.8, 0.2, 0.2);
material.diffuseMap = brickAsset.resource;
material.useMetalness = true;
material.metalness = 0.1;
material.gloss = 0.6;
material.update();
entity.render.material = material;

Constructors

constructor

new StandardMaterial()

Create a new StandardMaterial instance.

Example

// Create a new Standard material
const material = new StandardMaterial();

// Update the material's diffuse and specular properties
material.diffuse.set(1, 0, 0);
material.specular.set(1, 1, 1);

// Notify the material that it has been modified
material.update();

Example

// Create a new Standard material
const material = new StandardMaterial();

// Assign a texture to the diffuse slot
material.diffuseMap = texture;

// Use the alpha channel of the texture for alpha testing with a reference value of 0.5
material.opacityMap = texture;
material.alphaTest = 0.5;

// Notify the material that it has been modified
material.update();

Properties

anisotropyMap

anisotropyMap: Texture | null

The anisotropy map of the material (default is null).

anisotropyMapOffset

anisotropyMapOffset: Vec2

Controls the 2D offset of the anisotropy map. Each component is between 0 and 1.

anisotropyMapRotation

anisotropyMapRotation: number

Controls the 2D rotation (in degrees) of the anisotropy map.

anisotropyMapTiling

anisotropyMapTiling: Vec2

Controls the 2D tiling of the anisotropy map.

anisotropyMapUv

anisotropyMapUv: number

Anisotropy map UV channel. Valid values are 0 to 7.

aoDetailMap

aoDetailMap: Texture | null

The detail (secondary) baked ambient occlusion (AO) map of the material (default is null). Will only be used if main (primary) ao map is non-null.

aoDetailMapChannel

aoDetailMapChannel: string

Color channels of the detail (secondary) AO map to use. Can be "r", "g", "b" or "a" (default is "g").

aoDetailMapOffset

aoDetailMapOffset: Vec2

Controls the 2D offset of the detail (secondary) AO map. Each component is between 0 and 1.

aoDetailMapRotation

aoDetailMapRotation: number

Controls the 2D rotation (in degrees) of the detail (secondary) AO map.

aoDetailMapTiling

aoDetailMapTiling: Vec2

Controls the 2D tiling of the detail (secondary) AO map.

aoDetailMapUv

aoDetailMapUv: number

Detail (secondary) AO map UV channel. Valid values are 0 to 7.

aoDetailMode

aoDetailMode: string

Determines how the main (primary) and detail (secondary) AO maps are blended together. Can be:

Defaults to DETAILMODE_MUL.

aoMap

aoMap: Texture | null

The main (primary) baked ambient occlusion (AO) map (default is null). Modulates ambient color.

aoMapChannel

aoMapChannel: string

Color channel of the main (primary) AO map to use. Can be "r", "g", "b" or "a".

aoMapOffset

aoMapOffset: Vec2

Controls the 2D offset of the main (primary) AO map. Each component is between 0 and 1.

aoMapRotation

aoMapRotation: number

Controls the 2D rotation (in degrees) of the main (primary) AO map.

aoMapTiling

aoMapTiling: Vec2

Controls the 2D tiling of the main (primary) AO map.

aoMapUv

aoMapUv: number

Main (primary) AO map UV channel. Valid values are 0 to 7.

aoVertexColor

aoVertexColor: boolean

Use mesh vertex colors for AO. If aoMap is set, it'll be multiplied by vertex colors.

aoVertexColorChannel

aoVertexColorChannel: string

Vertex color channels to use for AO. Can be "r", "g", "b" or "a".

clearCoatGlossInvert

clearCoatGlossInvert: boolean

Invert the clearcoat gloss component (default is false). Enabling this flag results in material treating the clear coat gloss members as roughness.

clearCoatGlossMap

clearCoatGlossMap: Texture | null

Monochrome clearcoat glossiness map (default is null). If specified, will be multiplied by normalized 'clearCoatGloss' value and/or vertex colors.

clearCoatGlossMapChannel

clearCoatGlossMapChannel: string

Color channel of the clearcoat gloss map to use. Can be "r", "g", "b" or "a".

clearCoatGlossMapOffset

clearCoatGlossMapOffset: Vec2

Controls the 2D offset of the clearcoat gloss map. Each component is between 0 and 1.

clearCoatGlossMapRotation

clearCoatGlossMapRotation: number

Controls the 2D rotation (in degrees) of the clear coat gloss map.

clearCoatGlossMapTiling

clearCoatGlossMapTiling: Vec2

Controls the 2D tiling of the clearcoat gloss map.

clearCoatGlossMapUv

clearCoatGlossMapUv: number

Clearcoat gloss map UV channel. Valid values are 0 to 7.

clearCoatGlossVertexColor

clearCoatGlossVertexColor: boolean

Use mesh vertex colors for clearcoat glossiness. If clearCoatGlossMap is set, it'll be multiplied by vertex colors.

clearCoatGlossVertexColorChannel

clearCoatGlossVertexColorChannel: string

Vertex color channel to use for clearcoat glossiness. Can be "r", "g", "b" or "a".

clearCoatMap

clearCoatMap: Texture | null

Monochrome clearcoat intensity map (default is null). If specified, will be multiplied by normalized 'clearCoat' value and/or vertex colors.

clearCoatMapChannel

clearCoatMapChannel: string

Color channel of the clearcoat intensity map to use. Can be "r", "g", "b" or "a".

clearCoatMapOffset

clearCoatMapOffset: Vec2

Controls the 2D offset of the clearcoat intensity map. Each component is between 0 and 1.

clearCoatMapRotation

clearCoatMapRotation: number

Controls the 2D rotation (in degrees) of the clearcoat intensity map.

clearCoatMapTiling

clearCoatMapTiling: Vec2

Controls the 2D tiling of the clearcoat intensity map.

clearCoatMapUv

clearCoatMapUv: number

Clearcoat intensity map UV channel. Valid values are 0 to 7.

clearCoatNormalMap

clearCoatNormalMap: Texture | null

The clearcoat normal map of the material (default is null). The texture must contains normalized, tangent space normals.

clearCoatNormalMapOffset

clearCoatNormalMapOffset: Vec2

Controls the 2D offset of the main clearcoat normal map. Each component is between 0 and 1.

clearCoatNormalMapRotation

clearCoatNormalMapRotation: number

Controls the 2D rotation (in degrees) of the main clearcoat map.

clearCoatNormalMapTiling

clearCoatNormalMapTiling: Vec2

Controls the 2D tiling of the main clearcoat normal map.

clearCoatNormalMapUv

clearCoatNormalMapUv: number

Clearcoat normal map UV channel. Valid values are 0 to 7.

clearCoatVertexColor

clearCoatVertexColor: boolean

Use mesh vertex colors for clearcoat intensity. If clearCoatMap is set, it'll be multiplied by vertex colors.

clearCoatVertexColorChannel

clearCoatVertexColorChannel: string

Vertex color channel to use for clearcoat intensity. Can be "r", "g", "b" or "a".

cubeMap

cubeMap: Texture | null

The cubic environment map of the material (default is null). This setting overrides sphereMap and will replace the scene lighting environment.

cubeMapProjection

cubeMapProjection: number

The type of projection applied to the cubeMap property:

diffuseDetailMap

diffuseDetailMap: Texture | null

The detail (secondary) diffuse map of the material (default is null). Will only be used if main (primary) diffuse map is non-null.

diffuseDetailMapChannel

diffuseDetailMapChannel: string

Color channels of the detail (secondary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

diffuseDetailMapOffset

diffuseDetailMapOffset: Vec2

Controls the 2D offset of the detail (secondary) diffuse map. Each component is between 0 and 1.

diffuseDetailMapRotation

diffuseDetailMapRotation: number

Controls the 2D rotation (in degrees) of the detail (secondary) diffuse map.

diffuseDetailMapTiling

diffuseDetailMapTiling: Vec2

Controls the 2D tiling of the detail (secondary) diffuse map.

diffuseDetailMapUv

diffuseDetailMapUv: number

Detail (secondary) diffuse map UV channel. Valid values are 0 to 7.

diffuseDetailMode

diffuseDetailMode: string

Determines how the main (primary) and detail (secondary) diffuse maps are blended together. Can be:

Defaults to DETAILMODE_MUL.

diffuseMap

diffuseMap: Texture | null

The main (primary) diffuse map of the material (default is null).

diffuseMapChannel

diffuseMapChannel: string

Color channels of the main (primary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

diffuseMapOffset

diffuseMapOffset: Vec2

Controls the 2D offset of the main (primary) diffuse map. Each component is between 0 and 1.

diffuseMapRotation

diffuseMapRotation: number

Controls the 2D rotation (in degrees) of the main (primary) diffuse map.

diffuseMapTiling

diffuseMapTiling: Vec2

Controls the 2D tiling of the main (primary) diffuse map.

diffuseMapUv

diffuseMapUv: number

Main (primary) diffuse map UV channel. Valid values are 0 to 7.

diffuseVertexColor

diffuseVertexColor: boolean

Multiply diffuse by the mesh vertex colors.

diffuseVertexColorChannel

diffuseVertexColorChannel: string

Vertex color channels to use for diffuse. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

emissiveMap

emissiveMap: Texture | null

The emissive map of the material (default is null). Can be HDR. When the emissive map is applied, the emissive color is multiplied by the texel color in the map. Since the emissive color is black by default, the emissive map won't be visible unless the emissive color is changed.

emissiveMapChannel

emissiveMapChannel: string

Color channels of the emissive map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

emissiveMapOffset

emissiveMapOffset: Vec2

Controls the 2D offset of the emissive map. Each component is between 0 and 1.

emissiveMapRotation

emissiveMapRotation: number

Controls the 2D rotation (in degrees) of the emissive map.

emissiveMapTiling

emissiveMapTiling: Vec2

Controls the 2D tiling of the emissive map.

emissiveMapUv

emissiveMapUv: number

Emissive map UV channel. Valid values are 0 to 7.

emissiveVertexColor

emissiveVertexColor: boolean

Use mesh vertex colors for emission. If emissiveMap or emissive are set, they'll be multiplied by vertex colors.

emissiveVertexColorChannel

emissiveVertexColorChannel: string

Vertex color channels to use for emission. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

enableGGXSpecular

enableGGXSpecular: boolean

Enables GGX specular. Also enables anisotropyIntensity parameter to set material anisotropy.

envAtlas

envAtlas: Texture | null

The prefiltered environment lighting atlas (default is null). This setting overrides cubeMap and sphereMap and will replace the scene lighting environment.

fresnelModel

fresnelModel: number

Defines the formula used for Fresnel effect. As a side-effect, enabling any Fresnel model changes the way diffuse and reflection components are combined. When Fresnel is off, legacy non energy-conserving combining is used. When it is on, combining behavior is energy-conserving.

glossInvert

glossInvert: boolean

Invert the gloss component (default is false). Enabling this flag results in material treating the gloss members as roughness.

glossMap

glossMap: Texture | null

Gloss map (default is null). If specified, will be multiplied by normalized gloss value and/or vertex colors.

glossMapChannel

glossMapChannel: string

Color channel of the gloss map to use. Can be "r", "g", "b" or "a".

glossMapOffset

glossMapOffset: Vec2

Controls the 2D offset of the gloss map. Each component is between 0 and 1.

glossMapRotation

glossMapRotation: number

Controls the 2D rotation (in degrees) of the gloss map.

glossMapTiling

glossMapTiling: Vec2

Controls the 2D tiling of the gloss map.

glossMapUv

glossMapUv: number

Gloss map UV channel. Valid values are 0 to 7.

glossVertexColor

glossVertexColor: boolean

Use mesh vertex colors for glossiness. If glossMap is set, it'll be multiplied by vertex colors.

glossVertexColorChannel

glossVertexColorChannel: string

Vertex color channel to use for glossiness. Can be "r", "g", "b" or "a".

heightMap

heightMap: Texture | null

The height map of the material (default is null). Used for a view-dependent parallax effect. The texture must represent the height of the surface where darker pixels are lower and lighter pixels are higher, with heightMapBase selecting the value that sits at the level of the original geometry. It is recommended to use it together with a normal map. Note that the parallax offset is applied to all other maps of the material, so the height map should use the same tiling and offset as those maps.

heightMapChannel

heightMapChannel: string

Color channel of the height map to use. Can be "r", "g", "b" or "a".

heightMapOffset

heightMapOffset: Vec2

Controls the 2D offset of the height map. Each component is between 0 and 1.

heightMapRotation

heightMapRotation: number

Controls the 2D rotation (in degrees) of the height map.

heightMapTiling

heightMapTiling: Vec2

Controls the 2D tiling of the height map.

heightMapUv

heightMapUv: number

Height map UV channel. Valid values are 0 to 7.

iridescenceMap

iridescenceMap: Texture | null

The per-pixel iridescence intensity. Only used when useIridescence is enabled.

iridescenceMapChannel

iridescenceMapChannel: string

Color channels of the iridescence map to use. Can be "r", "g", "b" or "a".

iridescenceMapOffset

iridescenceMapOffset: Vec2

Controls the 2D offset of the iridescence map. Each component is between 0 and 1.

iridescenceMapRotation

iridescenceMapRotation: number

Controls the 2D rotation (in degrees) of the iridescence map.

iridescenceMapTiling

iridescenceMapTiling: Vec2

Controls the 2D tiling of the iridescence map.

iridescenceMapUv

iridescenceMapUv: number

Iridescence map UV channel. Valid values are 0 to 7.

iridescenceThicknessMap

iridescenceThicknessMap: Texture | null

The per-pixel iridescence thickness. Defines a gradient weight between iridescenceThicknessMin and iridescenceThicknessMax. Only used when useIridescence is enabled.

iridescenceThicknessMapChannel

iridescenceThicknessMapChannel: string

Color channels of the iridescence thickness map to use. Can be "r", "g", "b" or "a".

iridescenceThicknessMapOffset

iridescenceThicknessMapOffset: Vec2

Controls the 2D offset of the iridescence thickness map. Each component is between 0 and 1.

iridescenceThicknessMapRotation

iridescenceThicknessMapRotation: number

Controls the 2D rotation (in degrees) of the iridescence thickness map.

iridescenceThicknessMapTiling

iridescenceThicknessMapTiling: Vec2

Controls the 2D tiling of the iridescence thickness map.

iridescenceThicknessMapUv

iridescenceThicknessMapUv: number

Iridescence thickness map UV channel. Valid values are 0 to 7.

lightMap

lightMap: Texture | null

A custom lightmap of the material (default is null). Lightmaps are textures that contain pre-rendered lighting. Can be HDR. When a mesh instance rendered with this material has a lightmap of its own, baked by the Lightmapper, that lightmap is used instead of this one.

lightMapChannel

lightMapChannel: string

Color channels of the lightmap to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

lightMapOffset

lightMapOffset: Vec2

Controls the 2D offset of the lightmap. Each component is between 0 and 1.

lightMapRotation

lightMapRotation: number

Controls the 2D rotation (in degrees) of the lightmap.

lightMapTiling

lightMapTiling: Vec2

Controls the 2D tiling of the lightmap.

lightMapUv

lightMapUv: number

Lightmap UV channel. Valid values are 0 to 7.

lightVertexColor

lightVertexColor: boolean

Use baked vertex lighting. If lightMap is set, it'll be multiplied by vertex colors.

lightVertexColorChannel

lightVertexColorChannel: string

Vertex color channels to use for baked lighting. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

metalnessMap

metalnessMap: Texture | null

Monochrome metalness map (default is null).

metalnessMapChannel

metalnessMapChannel: string

Color channel of the metalness map to use. Can be "r", "g", "b" or "a".

metalnessMapOffset

metalnessMapOffset: Vec2

Controls the 2D offset of the metalness map. Each component is between 0 and 1.

metalnessMapRotation

metalnessMapRotation: number

Controls the 2D rotation (in degrees) of the metalness map.

metalnessMapTiling

metalnessMapTiling: Vec2

Controls the 2D tiling of the metalness map.

metalnessMapUv

metalnessMapUv: number

Metalness map UV channel. Valid values are 0 to 7.

metalnessVertexColor

metalnessVertexColor: boolean

Use mesh vertex colors for metalness. If metalnessMap is set, it'll be multiplied by vertex colors.

metalnessVertexColorChannel

metalnessVertexColorChannel: string

Vertex color channel to use for metalness. Can be "r", "g", "b" or "a".

normalDetailMap

normalDetailMap: Texture | null

The detail (secondary) normal map of the material (default is null). Will only be used if main (primary) normal map is non-null.

normalDetailMapOffset

normalDetailMapOffset: Vec2

Controls the 2D offset of the detail (secondary) normal map. Each component is between 0 and 1.

normalDetailMapRotation

normalDetailMapRotation: number

Controls the 2D rotation (in degrees) of the detail (secondary) normal map.

normalDetailMapTiling

normalDetailMapTiling: Vec2

Controls the 2D tiling of the detail (secondary) normal map.

normalDetailMapUv

normalDetailMapUv: number

Detail (secondary) normal map UV channel. Valid values are 0 to 7.

normalMap

normalMap: Texture | null

The main (primary) normal map of the material (default is null). The texture must contains normalized, tangent space normals.

normalMapOffset

normalMapOffset: Vec2

Controls the 2D offset of the main (primary) normal map. Each component is between 0 and 1.

normalMapRotation

normalMapRotation: number

Controls the 2D rotation (in degrees) of the main (primary) normal map.

normalMapTiling

normalMapTiling: Vec2

Controls the 2D tiling of the main (primary) normal map.

normalMapUv

normalMapUv: number

Main (primary) normal map UV channel. Valid values are 0 to 7.

occludeDirect

occludeDirect: boolean

Tells if AO should darken directional lighting. Defaults to false.

occludeSpecular

occludeSpecular: number

Uses ambient occlusion to darken specular/reflection. It's a hack, because real specular occlusion is view-dependent. However, it can be better than nothing.

onUpdateShader

onUpdateShader: UpdateShaderCallback | undefined

A custom function that will be called after all shader generator properties are collected and before shader code is generated. This function will receive an object with shader generator settings (based on current material and scene properties), that you can change and then return. Returned value will be used instead. This is mostly useful when rendering the same set of objects, but with different shader variations based on the same material. For example, you may wish to render a depth or normal pass using textures assigned to the material, a reflection pass with simpler shaders and so on. These properties are split into two sections, generic standard material options and lit options. Properties of the standard material options are StandardMaterialOptions and the options for the lit options are LitShaderOptions.

opacityDither

opacityDither: string

Used to specify whether opacity is dithered, which allows transparency without alpha blending. Can be:

Defaults to DITHER_NONE.

opacityFadesSpecular

opacityFadesSpecular: boolean

Used to specify whether specular and reflections are faded out using opacity. Default is true. When set to false use alphaFade to fade out materials.

opacityMap

opacityMap: Texture | null

The opacity map of the material (default is null).

opacityMapChannel

opacityMapChannel: string

Color channel of the opacity map to use. Can be "r", "g", "b" or "a".

opacityMapOffset

opacityMapOffset: Vec2

Controls the 2D offset of the opacity map. Each component is between 0 and 1.

opacityMapRotation

opacityMapRotation: number

Controls the 2D rotation (in degrees) of the opacity map.

opacityMapTiling

opacityMapTiling: Vec2

Controls the 2D tiling of the opacity map.

opacityMapUv

opacityMapUv: number

Opacity map UV channel. Valid values are 0 to 7.

opacityShadowDither

opacityShadowDither: string

Used to specify whether shadow opacity is dithered, which allows shadow transparency without alpha blending. Can be:

Defaults to DITHER_NONE.

opacityVertexColor

opacityVertexColor: boolean

Use mesh vertex colors for opacity. If opacityMap is set, it'll be multiplied by vertex colors.

opacityVertexColorChannel

opacityVertexColorChannel: string

Vertex color channels to use for opacity. Can be "r", "g", "b" or "a".

parallaxMode

parallaxMode: string

Selects how the height map is used to offset the UV of the other maps of the material. Can be:

Defaults to PARALLAX_OFFSET.

pixelSnap

pixelSnap: boolean

Align vertices to pixel coordinates when rendering. Useful for pixel perfect 2D graphics.

refractionMap

refractionMap: Texture | null

The map of the refraction visibility.

refractionMapChannel

refractionMapChannel: string

Color channels of the refraction map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

refractionMapOffset

refractionMapOffset: Vec2

Controls the 2D offset of the refraction map. Each component is between 0 and 1.

refractionMapRotation

refractionMapRotation: number

Controls the 2D rotation (in degrees) of the refraction map.

refractionMapTiling

refractionMapTiling: Vec2

Controls the 2D tiling of the refraction map.

refractionMapUv

refractionMapUv: number

Refraction map UV channel. Valid values are 0 to 7.

refractionVertexColor

refractionVertexColor: boolean

Use mesh vertex colors for refraction. If refraction map is set, it will be multiplied by vertex colors.

refractionVertexColorChannel

refractionVertexColorChannel: string

Vertex color channel to use for refraction. Can be "r", "g", "b" or "a".

shadowCatcher

shadowCatcher: boolean

When enabled, the material will output accumulated directional shadow value in linear space as the color.

sheenGlossInvert

sheenGlossInvert: boolean

Invert the sheen gloss component (default is false). Enabling this flag results in material treating the sheen gloss members as roughness.

sheenGlossMap

sheenGlossMap: Texture | null

The sheen glossiness microstructure color map of the material (default is null).

sheenGlossMapChannel

sheenGlossMapChannel: string

Color channels of the sheen glossiness map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

sheenGlossMapOffset

sheenGlossMapOffset: Vec2

Controls the 2D offset of the sheen glossiness map. Each component is between 0 and 1.

sheenGlossMapRotation

sheenGlossMapRotation: number

Controls the 2D rotation (in degrees) of the sheen glossiness map.

sheenGlossMapTiling

sheenGlossMapTiling: Vec2

Controls the 2D tiling of the sheen glossiness map.

sheenGlossMapUv

sheenGlossMapUv: number

Sheen glossiness map UV channel. Valid values are 0 to 7.

sheenGlossVertexColor

sheenGlossVertexColor: boolean

Use mesh vertex colors for sheen glossiness. If sheen glossiness map or sheen glossiness tint are set, they'll be multiplied by vertex colors.

sheenGlossVertexColorChannel

sheenGlossVertexColorChannel: string

Vertex color channels to use for sheen glossiness. Can be "r", "g", "b" or "a".

sheenMap

sheenMap: Texture | null

The sheen microstructure color map of the material (default is null).

sheenMapChannel

sheenMapChannel: string

Color channels of the sheen map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

sheenMapOffset

sheenMapOffset: Vec2

Controls the 2D offset of the sheen map. Each component is between 0 and 1.

sheenMapRotation

sheenMapRotation: number

Controls the 2D rotation (in degrees) of the sheen map.

sheenMapTiling

sheenMapTiling: Vec2

Controls the 2D tiling of the sheen map.

sheenMapUv

sheenMapUv: number

Sheen map UV channel. Valid values are 0 to 7.

sheenVertexColor

sheenVertexColor: boolean

Use mesh vertex colors for sheen. If sheen map or sheen tint are set, they'll be multiplied by vertex colors.

sheenVertexColorChannel

sheenVertexColorChannel: string

Vertex color channels to use for sheen. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

specularityFactorMap

specularityFactorMap: Texture | null

The factor of specularity as a texture (default is null).

specularityFactorMapChannel

specularityFactorMapChannel: string

The channel used by the specularity factor texture to sample from (default is 'a').

specularityFactorMapOffset

specularityFactorMapOffset: Vec2

Controls the 2D offset of the specularity factor map. Each component is between 0 and 1.

specularityFactorMapRotation

specularityFactorMapRotation: number

Controls the 2D rotation (in degrees) of the specularity factor map.

specularityFactorMapTiling

specularityFactorMapTiling: Vec2

Controls the 2D tiling of the specularity factor map.

specularityFactorMapUv

specularityFactorMapUv: number

Specularity factor map UV channel. Valid values are 0 to 7.

specularityFactorTint

specularityFactorTint: boolean

Force inclusion of the constant specularityFactor when compositing with specularityFactorMap and/or specularity factor vertex colors. Defaults to false. Setting this to true is rarely needed - the constant is automatically applied whenever specularityFactor differs from 1. Provided as an explicit override.

specularityFactorVertexColor

specularityFactorVertexColor: boolean

Use mesh vertex colors for specularity factor. If specularityFactorMap or are specularityFactorTint are set, they'll be multiplied by vertex colors.

specularityFactorVertexColorChannel

specularityFactorVertexColorChannel: string

Vertex color channels to use for specularity factor. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

specularMap

specularMap: Texture | null

The specular map of the material (default is null).

specularMapChannel

specularMapChannel: string

Color channels of the specular map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

specularMapOffset

specularMapOffset: Vec2

Controls the 2D offset of the specular map. Each component is between 0 and 1.

specularMapRotation

specularMapRotation: number

Controls the 2D rotation (in degrees) of the specular map.

specularMapTiling

specularMapTiling: Vec2

Controls the 2D tiling of the specular map.

specularMapUv

specularMapUv: number

Specular map UV channel. Valid values are 0 to 7.

specularVertexColor

specularVertexColor: boolean

Multiply specular by the mesh vertex colors.

specularVertexColorChannel

specularVertexColorChannel: string

Vertex color channels to use for specular. Can be "r", "g", "b", "a", "rgb" or any swizzled combination.

sphereMap

sphereMap: Texture | null

The spherical environment map of the material (default is null). This will replace the scene lighting environment.

thicknessMap

thicknessMap: Texture | null

The per-pixel thickness of the medium, only used when useDynamicRefraction is enabled.

thicknessMapChannel

thicknessMapChannel: string

Color channels of the thickness map to use. Can be "r", "g", "b" or "a".

thicknessMapOffset

thicknessMapOffset: Vec2

Controls the 2D offset of the thickness map. Each component is between 0 and 1.

thicknessMapRotation

thicknessMapRotation: number

Controls the 2D rotation (in degrees) of the thickness map.

thicknessMapTiling

thicknessMapTiling: Vec2

Controls the 2D tiling of the thickness map.

thicknessMapUv

thicknessMapUv: number

Thickness map UV channel. Valid values are 0 to 7.

thicknessVertexColor

thicknessVertexColor: boolean

Use mesh vertex colors for thickness. If thickness map is set, it will be multiplied by vertex colors.

thicknessVertexColorChannel

thicknessVertexColorChannel: string

Vertex color channel to use for thickness. Can be "r", "g", "b" or "a".

twoSidedLighting

twoSidedLighting: boolean

Calculate proper normals (and therefore lighting) on backfaces.

useDynamicRefraction

useDynamicRefraction: boolean

Enables higher quality refractions using the grab pass instead of pre-computed cube maps for refractions.

useFog

useFog: boolean

Apply fogging (as configured in scene settings)

useIridescence

useIridescence: boolean

Enable thin-film iridescence.

useLighting

useLighting: boolean

Apply lighting

useMetalness

useMetalness: boolean

Use metalness properties instead of specular. When enabled, diffuse colors also affect specular instead of the dedicated specular map. This can be used as alternative to specular color to save space. With metalness == 0, the pixel is assumed to be dielectric, and diffuse color is used as normal. With metalness == 1, the pixel is fully metallic, and diffuse color is used as specular color instead.

useMetalnessSpecularColor

useMetalnessSpecularColor: boolean

When metalness is enabled, use the specular map to apply color tint to specular reflections.

useSheen

useSheen: boolean

Toggle sheen specular effect on/off.

useSkybox

useSkybox: boolean

Apply scene skybox as prefiltered environment map

useTonemap

useTonemap: boolean

Apply tonemapping (as configured via CameraComponent#toneMapping). Defaults to true.

vertexColorGamma

vertexColorGamma: boolean

When set to true, the vertex shader converts vertex colors from gamma to linear space to ensure correct interpolation in the fragment shader. This flag is provided for backwards compatibility, allowing users to mark their materials to handle vertex colors in gamma space. Defaults to false, which indicates that vertex colors are stored in linear space.

Accessors

alphaDither

get alphaDither(): number
set alphaDither(value: number)

Gets the dither alpha of the material.

alphaFade

get alphaFade(): number
set alphaFade(value: number)

Gets the alpha fade of the material.

alphaTest

get alphaTest(): number
set alphaTest(value: number)

Gets the alpha test reference value.

ambient

get ambient(): Color
set ambient(value: Color)

Gets the ambient color of the material.

anisotropyIntensity

get anisotropyIntensity(): number
set anisotropyIntensity(value: number)

Gets the anisotropy intensity of the material.

anisotropyRotation

get anisotropyRotation(): number
set anisotropyRotation(value: number)

Gets the anisotropy rotation of the material.

aoIntensity

get aoIntensity(): number
set aoIntensity(value: number)

Gets the ambient occlusion intensity of the material.

attenuation

get attenuation(): Color
set attenuation(value: Color)

Gets the attenuation color of the material.

attenuationDistance

get attenuationDistance(): number
set attenuationDistance(value: number)

Gets the attenuation distance of the material.

bumpiness

get bumpiness(): number
set bumpiness(value: number)

Gets the bumpiness of the material.

clearCoat

get clearCoat(): number
set clearCoat(value: number)

Gets the clearcoat intensity of the material.

clearCoatBumpiness

get clearCoatBumpiness(): number
set clearCoatBumpiness(value: number)

Gets the clearcoat bumpiness of the material.

clearCoatGloss

get clearCoatGloss(): number
set clearCoatGloss(value: number)

Gets the clearcoat glossiness of the material.

cubeMapProjectionBox

get cubeMapProjectionBox(): BoundingBox | null
set cubeMapProjectionBox(value: BoundingBox | null)

Gets the world space axis-aligned bounding box of the box-projection, or null. A change of its center or half extents is applied by StandardMaterial#update.

diffuse

get diffuse(): Color
set diffuse(value: Color)

Gets the diffuse color of the material.

dispersion

get dispersion(): number
set dispersion(value: number)

Gets the dispersion of the material.

emissive

get emissive(): Color
set emissive(value: Color)

Gets the emissive color of the material.

emissiveIntensity

get emissiveIntensity(): number
set emissiveIntensity(value: number)

Gets the emissive color multiplier.

gloss

get gloss(): number
set gloss(value: number)

Gets the glossiness of the material.

heightMapBase

get heightMapBase(): number
set heightMapBase(value: number)

Gets the height map base level of the material.

heightMapFactor

get heightMapFactor(): number
set heightMapFactor(value: number)

Gets the height map factor of the material.

iridescence

get iridescence(): number
set iridescence(value: number)

Gets the iridescence intensity of the material.

iridescenceRefractionIndex

get iridescenceRefractionIndex(): number
set iridescenceRefractionIndex(value: number)

Gets the index of refraction of the iridescent thin-film of the material.

iridescenceThicknessMax

get iridescenceThicknessMax(): number
set iridescenceThicknessMax(value: number)

Gets the maximum iridescence thickness of the material.

iridescenceThicknessMin

get iridescenceThicknessMin(): number
set iridescenceThicknessMin(value: number)

Gets the minimum iridescence thickness of the material.

metalness

get metalness(): number
set metalness(value: number)

Gets the metalness of the material.

normalDetailMapBumpiness

get normalDetailMapBumpiness(): number
set normalDetailMapBumpiness(value: number)

Gets the detail normal map bumpiness of the material.

occludeSpecularIntensity

get occludeSpecularIntensity(): number
set occludeSpecularIntensity(value: number)

Gets the specular occlusion intensity of the material.

opacity

get opacity(): number
set opacity(value: number)

Gets the opacity of the material.

parallaxSamples

get parallaxSamples(): number
set parallaxSamples(value: number)

Gets the maximum number of height map taps of parallax occlusion mapping of the material.

parallaxShadowSamples

get parallaxShadowSamples(): number
set parallaxShadowSamples(value: number)

Gets the maximum number of height map taps of the parallax self shadowing of the material.

reflectivity

get reflectivity(): number
set reflectivity(value: number)

Gets the environment map intensity of the material.

refraction

get refraction(): number
set refraction(value: number)

Gets the refraction of the material.

refractionIndex

get refractionIndex(): number
set refractionIndex(value: number)

Gets the index of refraction of the material.

sheen

get sheen(): Color
set sheen(value: Color)

Gets the sheen color of the material.

sheenGloss

get sheenGloss(): number
set sheenGloss(value: number)

Gets the sheen glossiness of the material.

specular

get specular(): Color
set specular(value: Color)

Gets the specular color of the material.

specularityFactor

get specularityFactor(): number
set specularityFactor(value: number)

Gets the specularity factor of the material.

thickness

get thickness(): number
set thickness(value: number)

Gets the thickness of the medium of the material.

Methods

copy

copy(source: StandardMaterial): StandardMaterial

Copy a StandardMaterial.

Parameters

Returns StandardMaterial: The destination material.

destroy

destroy(): void

Removes this material from the scene and possibly frees up memory from its shaders (if there are no other materials using it).

setAttribute

setAttribute(name: string, semantic: string): void

Sets a vertex shader attribute on a material.

Parameters

Example

mesh.setVertexStream(SEMANTIC_ATTR15, offset, 3);
material.setAttribute('offset', SEMANTIC_ATTR15);

update

update(): void

Inherited from Material

StandardMaterialOptions

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material-options.js#L10

The standard material options define a set of options used to control the shader frontend shader generation, such as textures, tints and multipliers.

Properties

clearCoatGlossInvert

clearCoatGlossInvert: boolean = false

Invert the clearcoat gloss channel.

clearCoatPackedNormal

clearCoatPackedNormal: boolean = false

If normal clear coat map contains X in RGB, Y in Alpha, and Z must be reconstructed.

defines

defines: Map<string, string>

The set of defines used to generate the shader.

forceUv1

forceUv1: boolean = false

If UV1 (second set of texture coordinates) is required in the shader. Will be declared as "vUv1" and passed to the fragment shader.

glossInvert

glossInvert: boolean = false

Invert the gloss channel.

glossTint

glossTint: boolean = false

Defines if StandardMaterial#gloss constant should affect glossiness value.

litOptions

litOptions: LitShaderOptions

Storage for the options for lit the shader and material.

metalnessTint

metalnessTint: boolean = false

Defines if StandardMaterial#metalness constant should affect metalness value.

normalDetailPackedNormal

normalDetailPackedNormal: boolean = false

If normal detail map contains X in RGB, Y in Alpha, and Z must be reconstructed.

packedNormal

packedNormal: boolean = false

If normal map contains X in RGB, Y in Alpha, and Z must be reconstructed.

sheenGlossInvert

sheenGlossInvert: boolean = false

Invert the sheen gloss channel.

useAO

useAO: boolean = false

True to include AO variables even if AO is not used, which allows SSAO to be used in the lit shader.

useInstanceLightMap

useInstanceLightMap: boolean = false

True if the lightmap comes from the mesh instance rather than from the material, and so is sampled from the mesh instance's own texture slot. See Lightmapper.

StencilParameters

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/stencil-parameters.js#L11

Holds stencil test settings.

Constructors

constructor

new StencilParameters(options?: any)

Create a new StencilParameters instance.

Parameters

Properties

DEFAULT

static readonly DEFAULT: StencilParameters

A default stencil state.

Accessors

fail

get fail(): number
set fail(value: number)

Gets the operation to perform if stencil test is failed.

func

get func(): number
set func(value: number)

Sets the comparison function that decides if the pixel should be written.

readMask

get readMask(): number
set readMask(value: number)

Gets the mask applied to stencil buffer value and reference value before comparison.

ref

get ref(): number
set ref(value: number)

Gets the stencil test reference value used in comparisons.

writeMask

get writeMask(): number
set writeMask(value: number)

Gets the bit mask applied to the stencil value when written.

zfail

get zfail(): number
set zfail(value: number)

Gets the operation to perform if depth test is failed.

zpass

get zpass(): number
set zpass(value: number)

Gets the operation to perform if both stencil and depth test are passed.

Methods

clone

clone(): StencilParameters

Clone the stencil parameters.

Returns StencilParameters: A cloned StencilParameters object.

copy

copy(rhs: StencilParameters): StencilParameters

Copies the contents of a source stencil parameters to this stencil parameters.

Parameters

Returns StencilParameters: Self for chaining.

StorageBuffer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/storage-buffer.js#L26

A storage buffer represents a memory which both the CPU and the GPU can access. Typically it is used to provide data for compute shader, and to store the result of the computation. Note that this class is only supported on the WebGPU platform.

After a graphics device is lost and restored, the GPU backing for a storage buffer is recreated at the same byte size but its contents are undefined until you write to it again or repopulate it via compute.

For debug identification in buffer memory listings (when the TRACEID_BUFFERS trace channel is enabled), call sites may assign the instance's name property to a descriptive string.

Constructors

constructor

new StorageBuffer(graphicsDevice: GraphicsDevice, byteSize: number, bufferUsage?: number, addStorageUsage?: boolean)

Create a new StorageBuffer instance.

Parameters

Methods

clear

clear(offset?: number, size?: number): void

Clear the content of a storage buffer to 0.

Parameters

copy

copy(srcBuffer: StorageBuffer, srcOffset?: number, dstOffset?: number, size?: number): void

Copy data from another storage buffer into this storage buffer.

Parameters

destroy

destroy(): void

Frees resources associated with this storage buffer.

read

read(offset?: number, size?: number, data?: ArrayBufferView<ArrayBufferLike> | null, immediate?: boolean): Promise<ArrayBufferView<ArrayBufferLike>>

Read the contents of a storage buffer.

Parameters

Returns Promise<ArrayBufferView<ArrayBufferLike>>: A promise that resolves with the data read from the storage buffer. Rejects with an AbortError if the read is cancelled, for example by device loss. Other read failures also reject the promise.

write

write(bufferOffset?: number, data: ArrayBuffer | ArrayBufferView<ArrayBufferLike>, dataOffset?: number, size?: number): void

Issues a write operation of the provided data into a storage buffer.

Parameters

Texture

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/texture.js#L70

Represents a texture, which is typically an image composed of pixels (texels). Textures are fundamental resources for rendering graphical objects. They are commonly used by Materials and sampled in Shaders (usually fragment shaders) to define the visual appearance of a 3D model's surface. Beyond storing color images, textures can hold various data types like normal maps, environment maps (cubemaps), or custom data for shader computations. Key properties control how the texture data is sampled, including filtering modes and coordinate wrapping.

Note on HDR texture format support:

  1. As textures:

    • float (i.e. PIXELFORMAT_RGBA32F), half-float (i.e. PIXELFORMAT_RGBA16F) and small-float (PIXELFORMAT_111110F) formats are always supported on both WebGL2 and WebGPU with point sampling.
    • half-float and small-float formats are always supported on WebGL2 and WebGPU with linear sampling.
    • float formats are supported on WebGL2 and WebGPU with linear sampling only if GraphicsDevice#textureFloatFilterable is true.
    • PIXELFORMAT_RGB9E5 is a compact HDR format with shared exponent, supported for sampling on both WebGL2 and WebGPU, but cannot be used as a render target.
  2. As renderable textures that can be used as color buffers in a RenderTarget:

Constructors

constructor

new Texture(graphicsDevice: GraphicsDevice, options?: object)

Create a new Texture instance.

Parameters

Example

// Create a 8x8x24-bit texture
const texture = new Texture(graphicsDevice, {
    width: 8,
    height: 8,
    format: PIXELFORMAT_RGB8
});

// Fill the texture with a gradient
const pixels = texture.lock();
const count = 0;
for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
        pixels[count++] = i * 32;
        pixels[count++] = j * 32;
        pixels[count++] = 255;
    }
}
texture.unlock();

Properties

_invalid

protected _invalid: boolean = false

_lockedLevel

protected _lockedLevel: number = -1

_lockedMode

protected _lockedMode: number = TEXTURELOCK_NONE

_numLevels

protected _numLevels: number = 0

_numLevelsRequested

protected _numLevelsRequested: number | undefined

_samples

protected _samples: number = 1

The number of MSAA samples of the texture, 1 if not multisampled.

_storage

protected _storage: boolean = false

id

protected id: number

name

name: string

The name of the texture.

Accessors

addressU

get addressU(): number
set addressU(v: number)

Gets the addressing mode to be applied to the texture horizontally.

addressV

get addressV(): number
set addressV(v: number)

Gets the addressing mode to be applied to the texture vertically.

addressW

get addressW(): number
set addressW(addressW: number)

Gets the addressing mode to be applied to the 3D texture depth.

anisotropy

get anisotropy(): number
set anisotropy(v: number)

Gets the integer value specifying the level of anisotropy to apply to the texture.

array

get array(): boolean

Returns true if this texture is a 2D texture array and false otherwise.

arrayLength

get arrayLength(): number

Returns the number of textures inside this texture if this is a 2D array texture or 0 otherwise.

compareFunc

get compareFunc(): number
set compareFunc(v: number)

Gets the comparison function when compareOnRead is enabled.

compareOnRead

get compareOnRead(): boolean
set compareOnRead(v: boolean)

Gets whether you can get filtered results of comparison using texture() in your shader.

cubemap

get cubemap(): boolean

Returns true if this texture is a cube map and false otherwise.

depth

get depth(): number

The number of depth slices in a 3D texture.

flipY

get flipY(): boolean
set flipY(flipY: boolean)

Gets whether the texture should be flipped in the Y-direction.

format

get format(): number

The pixel format of the texture. Can be:

height

get height(): number

The height of the texture in pixels.

magFilter

get magFilter(): number
set magFilter(v: number)

Gets the magnification filter to be applied to the texture.

minFilter

get minFilter(): number
set minFilter(v: number)

Gets the minification filter to be applied to the texture.

mipmaps

get mipmaps(): boolean
set mipmaps(v: boolean)

Gets whether the texture should generate/upload mipmaps.

numLevels

get numLevels(): number

Gets the number of mip levels.

pot

get pot(): boolean

Returns true if all dimensions of the texture are power of two, and false otherwise.

samples

get samples(): number

The number of MSAA samples of the texture, 1 if the texture is not multisampled. Specified via the samples constructor option (WebGPU only). A multisampled texture can only be rendered into, and its individual samples read in a shader using textureLoad.

srgb

get srgb(): boolean

Returns true if the texture is stored in an sRGB format, meaning it will be converted to linear space when sampled. Returns false if the texture is stored in a linear format.

storage

get storage(): boolean

Defines if texture can be used as a storage texture by a compute shader.

volume

get volume(): boolean

Returns true if this texture is a 3D volume and false otherwise.

width

get width(): number

The width of the texture in pixels.

Methods

copy

copy(source: Texture, options?: object): boolean

Copies a region of a source texture into this texture. Both textures must have the same pixel format. The copied region sizes must match (no scaling), and must lie within the chosen mip levels of both textures. Multisampled textures can be copied to other multisampled textures with the same sample count (WebGPU only), but only as a full-texture copy - no offsets or partial regions, and no copies between different sample counts (use a resolve instead).

Parameters

Returns boolean: True if the copy was successful, false otherwise.

destroy

destroy(): void

Frees resources associated with this texture.

getSource

getSource(mipLevel?: number): HTMLImageElement

Get the pixel data of the texture. If this is a cubemap then an array of 6 images will be returned otherwise a single image.

Parameters

Returns HTMLImageElement: The source image of this texture. Can be null if source not assigned for specific image level.

getView

getView(baseMipLevel?: number, mipLevelCount?: number, baseArrayLayer?: number, arrayLayerCount?: number): TextureView

Creates a TextureView for this texture, specifying a subset of mip levels and array layers. TextureViews can be used with compute shaders to access specific portions of a texture.

Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound.

Parameters

Returns TextureView: A new TextureView for this texture.

Example

// Create a view for mip level 1
const mip1View = texture.getView(1);

// Use with compute shader
compute.setParameter('outputTexture', mip1View);

lock

lock(options?: object): Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>

Locks a miplevel of the texture, returning a typed array to be filled with pixel data.

Parameters

Returns Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>: A typed array containing the pixel data of the locked mip level.

read

read(x: number, y: number, width: number, height: number, options?: object): Promise<Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>>

Download the textures data from the graphics memory to the local memory.

Parameters

Returns Promise<Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Float32Array<ArrayBufferLike>>: A promise that resolves with the pixel data of the texture.

setSource

setSource(source: HTMLElement | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | HTMLElement[], mipLevel?: number): void

Set the pixel data of the texture from a canvas, image, video, or HTML DOM element. If the texture is a cubemap, the supplied source must be an array of 6 canvases, images or videos.

Note: using an HTML element (e.g. <div>) as a source requires GraphicsDevice#supportsHtmlTextures to be true.

Parameters

unlock

unlock(): void

Unlocks the currently locked mip level and uploads it to VRAM.

upload

upload(): void

Forces a reupload of the texture's pixel data to graphics memory. Ordinarily, this function is called internally by setSource and unlock. However, it still needs to be called explicitly in the case where an HTMLVideoElement is set as the source of the texture. Normally, this is done once every frame before video textured geometry is rendered.

TextureAtlas

Class · extends EventHandler · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/texture-atlas.js#L15

A TextureAtlas contains a number of frames from a texture. Each frame defines a region in a texture. The TextureAtlas is referenced by Sprites.

Constructors

constructor

new TextureAtlas()

Create a new TextureAtlas instance.

Example

const atlas = new TextureAtlas();
atlas.frames = {
    '0': {
        // rect has u, v, width and height in pixels
        rect: new Vec4(0, 0, 256, 256),
        // pivot has x, y values between 0-1 which define the point
        // within the frame around which rotation and scale is calculated
        pivot: new Vec2(0.5, 0.5),
        // border has left, bottom, right and top in pixels defining regions for 9-slicing
        border: new Vec4(5, 5, 5, 5)
    },
    '1': {
        rect: new Vec4(256, 0, 256, 256),
        pivot: new Vec2(0.5, 0.5),
        border: new Vec4(5, 5, 5, 5)
    }
};

Accessors

frames

get frames(): any
set frames(value: any)

Gets the frames which define portions of the texture atlas.

texture

get texture(): Texture
set texture(value: Texture)

Gets the texture used by the atlas.

Methods

destroy

destroy(): void

Free up the underlying texture owned by the atlas.

removeFrame

removeFrame(key: string): void

Removes a frame from the texture atlas.

Parameters

Example

atlas.removeFrame('1');

setFrame

setFrame(key: string, data: object): void

Set a new frame in the texture atlas.

Parameters

Example

atlas.setFrame('1', {
    rect: new Vec4(0, 0, 128, 128),
    pivot: new Vec2(0.5, 0.5),
    border: new Vec4(5, 5, 5, 5)
});

Inherited from EventHandler

TextureParser

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/texture/texture.js#L14

Interface to a texture parser. Implementations of this interface handle the loading and opening of texture assets.

Methods

load

load(url: object, callback: ResourceHandlerCallback, asset?: Asset<string>): void

Load the texture from the remote URL. When loaded (or failed), use the callback to return an the raw resource data (or error).

Parameters

open

open(url: string, data: any, device: GraphicsDevice): Texture

Convert raw resource data into a Texture.

Parameters

Returns Texture: The parsed resource data.

TextureRenderer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/texture-renderer.js#L113

Displays textures for a single frame, for debugging. Call draw or sceneDepth during update or prerender on every frame the preview should be visible. Positions specify the top-left corner in normalized camera-viewport coordinates: (0, 0) is top-left and (1, 1) is bottom-right. Width and height are fractions of the viewport; a rectangle of (0, 0, 1, 1) fills it. Signed sizes can flip a preview, and rectangles can extend outside the viewport.

Supports 2D color textures in normalized, floating-point and device-supported compressed formats. Linear and sRGB color, and RGBM, RGBE and RGBP encoded HDR color, are detected automatically with the default channels selection, and single-channel formats such as PIXELFORMAT_R8 display their channel as grayscale. Other selections display stored channel values, including alpha, as opaque previews.

Depth textures using PIXELFORMAT_DEPTH, PIXELFORMAT_DEPTH16 or PIXELFORMAT_DEPTHSTENCIL are displayed as raw grayscale values. Use sceneDepth to display the rendering camera's scene depth, linearized and normalized by its far clip distance. The camera must have scene depth capture enabled.

Cube, volume, array, integer and multisampled textures are not supported. On WebGL2, raw depth textures must have comparison sampling disabled, and both raw depth and non-filterable float textures require nearest minification and magnification filters. WebGPU supports these textures regardless of their filtering and comparison sampler settings.

Resources are released automatically when the application is destroyed, or earlier by calling destroy. Supplied textures are never destroyed by this helper.

Previews produce fully opaque pixels but are drawn as alpha-blended instances, so they render in layers that only draw their transparent sub-layer, such as the default UI layer, which is also where they escape a camera frame's post-processing. They do not write or test depth and do not cast shadows. Ordering against other transparent geometry follows the destination layer's transparent sort mode.

Every camera rendering the destination layer draws the previews, including cameras rendering into a texture. Set camera to limit them to a single camera, typically the one rendering to the screen. A render pass whose target has the previewed texture among its attachments never draws that preview: sampling a texture while rendering into it is undefined on WebGL and an error on WebGPU. Both rules are applied as each layer is rendered, against the target the pass really renders into, so they hold for camera frames and custom render passes and do not depend on frustum culling.

Example

const textures = new TextureRenderer(app);
app.on('update', () => {
    textures.draw(texture, 0.7, 0.7, 0.25, 0.25);
});

Example

// camera is an entity with a camera component.
camera.camera.requestSceneDepthMap(true);
const textures = new TextureRenderer(app);
app.on('update', () => {
    textures.sceneDepth(0.7, 0.7, 0.25, 0.25);
});

Constructors

constructor

new TextureRenderer(app: AppBase)

Creates a debug texture renderer.

Parameters

Properties

camera

camera: CameraComponent | null = null

The only camera that draws the previews, or null to let every camera rendering the destination layer draw them. Defaults to null.

layer

layer: Layer | null = null

The layer used by subsequent draw calls, or null to use the application's default debug drawing layer (normally Immediate). Defaults to null.

Accessors

channels

set channels(value: string)

Channels displayed by subsequent draw calls. Must be exactly three characters from 'r', 'g', 'b' and 'a'. Defaults to 'rgb', which displays automatically decoded color, or the stored channel as grayscale for single-channel formats. Other selections display stored channel values without color decoding: for example, 'rrr' displays red as grayscale, 'aaa' displays alpha, and 'bgr' swaps red and blue. Values from 0 to 1 map directly from black to white. Output is always opaque. Ignored for depth textures and sceneDepth. Invalid values leave the previous selection unchanged.

Example

textures.channels = 'aaa';
textures.draw(texture, 0, 0, 0.25, 0.25);

Methods

destroy

destroy(): void

Removes all previews and releases the renderer's resources. Does not destroy supplied textures. Safe to call repeatedly; subsequent draw calls are ignored.

draw

draw(texture: Texture, x: number, y: number, width: number, height: number): void

Displays a 2D color or depth texture for this frame. Color encoding and supported filtering are detected automatically when channels is 'rgb'. Other selections display stored channel values. Raw depth is shown as grayscale without projection-dependent linearization; use sceneDepth for camera depth. Texture row 0 is displayed at the top. For rendered textures, use RENDERTARGET_ORIGIN_TOP on their render target for consistent orientation across backends.

Cube, volume, array, integer and multisampled textures are not supported. On WebGL2, depth textures must have comparison sampling disabled. Raw depth and non-filterable float textures must use nearest minification and magnification filters on WebGL2. WebGPU samples these textures independently of their filtering and comparison sampler settings.

Parameters

sceneDepth

sceneDepth(x: number, y: number, width: number, height: number): void

Displays the rendering camera's scene depth for this frame, linearized and normalized by its far clip distance. The camera must already supply a scene depth map, for example using CameraComponent#requestSceneDepthMap, and this layer must render after depth capture.

Parameters

TextureView

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/texture-view.js#L19

A TextureView specifies a texture and a subset of its mip levels and array layers. It is used when binding textures to compute shaders to specify which portion of the texture should be accessed. Create a TextureView using Texture#getView.

Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound and this class has no effect.

Properties

arrayLayerCount

readonly arrayLayerCount: number

The number of array layers accessible to the view.

baseArrayLayer

readonly baseArrayLayer: number

The first array layer accessible to the view.

baseMipLevel

readonly baseMipLevel: number

The first mip level accessible to the view.

mipLevelCount

readonly mipLevelCount: number

The number of mip levels accessible to the view.

texture

readonly texture: Texture

The texture this view references.

TorusGeometry

Class · extends Geometry · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/torus-geometry.js#L34

A procedural torus-shaped geometry.

Typically, you would:

  1. Create a TorusGeometry instance.
  2. Generate a Mesh from the geometry.
  3. Create a MeshInstance referencing the mesh.
  4. Create an Entity with a RenderComponent and assign the MeshInstance to it.
  5. Add the entity to the Scene.
// Create a mesh instance
const geometry = new TorusGeometry();
const mesh = Mesh.fromGeometry(app.graphicsDevice, geometry);
const material = new StandardMaterial();
const meshInstance = new MeshInstance(mesh, material);

// Create an entity
const entity = new Entity();
entity.addComponent('render', {
    meshInstances: [meshInstance]
});

// Add the entity to the scene hierarchy
app.scene.root.addChild(entity);

Constructors

constructor

new TorusGeometry(opts?: object)

Create a new TorusGeometry instance.

By default, the constructor creates a torus in the XZ-plane with a tube radius of 0.2, a ring radius of 0.3, 30 segments and 20 sides. The torus is created with UVs in the range of 0 to 1.

Parameters

Example

const geometry = new TorusGeometry({
    tubeRadius: 1,
    ringRadius: 2,
    sectorAngle: 360,
    segments: 30,
    sides: 20
});

Inherited from Geometry

TransformFeedback

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/transform-feedback.js#L89

This object allows you to configure and use the transform feedback feature (WebGL2 only). How to use:

  1. First, check that you're on WebGL2, by looking at the `app.graphicsDevice.isWebGL2`` value.
  2. Define the outputs in your vertex shader. The syntax is out vec3 out_vertex_position, note that there must be out_ in the name. You can then simply assign values to these outputs in VS. The order and size of shader outputs must match the output buffer layout.
  3. Create the shader using TransformFeedback.createShader(device, vsCode, yourShaderName).
  4. Create/acquire the input vertex buffer. Can be any VertexBuffer, either manually created, or from a Mesh.
  5. Create the TransformFeedback object: const tf = new TransformFeedback(inputBuffer). This object will internally create an output buffer.
  6. Run the shader: tf.process(shader). Shader will take the input buffer, process it and write to the output buffer, then the input/output buffers will be automatically swapped, so you'll immediately see the result.
// *** shader asset ***
attribute vec3 vertex_position;
attribute vec3 vertex_normal;
attribute vec2 vertex_texCoord0;
out vec3 out_vertex_position;
out vec3 out_vertex_normal;
out vec2 out_vertex_texCoord0;
void main(void) {
    // read position and normal, write new position (push away)
    out_vertex_position = vertex_position + vertex_normal * 0.01;
    // pass other attributes unchanged
    out_vertex_normal = vertex_normal;
    out_vertex_texCoord0 = vertex_texCoord0;
}
// *** script asset ***
var TransformExample = createScript('transformExample');

// attribute that references shader asset and material
TransformExample.attributes.add('shaderCode', { type: 'asset', assetType: 'shader' });
TransformExample.attributes.add('material', { type: 'asset', assetType: 'material' });

TransformExample.prototype.initialize = function() {
    const device = this.app.graphicsDevice;
    const mesh = Mesh.fromGeometry(app.graphicsDevice, new TorusGeometry({ tubeRadius: 0.01, ringRadius: 3 }));
    const meshInstance = new MeshInstance(mesh, this.material.resource);
    const entity = new Entity();
    entity.addComponent('render', {
        type: 'asset',
        meshInstances: [meshInstance]
    });
    app.root.addChild(entity);

    // if webgl2 is not supported, transform-feedback is not available
    if (!device.isWebGL2) return;
    const inputBuffer = mesh.vertexBuffer;
    this.tf = new TransformFeedback(inputBuffer);
    this.shader = TransformFeedback.createShader(device, this.shaderCode.resource, "tfMoveUp");
};

TransformExample.prototype.update = function(dt) {
    if (!this.app.graphicsDevice.isWebGL2) return;
    this.tf.process(this.shader);
};

Constructors

constructor

new TransformFeedback(inputBuffer: VertexBuffer | TransformFeedbackStream[], outputBuffer?: VertexBuffer, usage?: number)

Create a new TransformFeedback instance.

Parameters

Example

// a simulation writing its state back to itself, plus a stream consumed by instancing
const tf = new TransformFeedback([
    { input: positions, output: positionsOut },  // read and written, swapped each step
    { input: constants },                        // read only, never modified
    { output: instances }                        // written only, for the render pass
]);

Accessors

inputBuffer

get inputBuffer(): VertexBuffer

The current input buffer. When multiple input buffers are used, this is the first one - see TransformFeedback#inputBuffers.

inputBuffers

get inputBuffers(): VertexBuffer[]

The buffers read by the shader, in the order they were supplied.

outputBuffer

get outputBuffer(): VertexBuffer

The current output buffer. When multiple output buffers are used, this is the first one - see TransformFeedback#outputBuffers.

outputBuffers

get outputBuffers(): VertexBuffer[]

The buffers written by transform feedback, in the order of the captured varyings.

Methods

destroy

destroy(): void

Destroys the transform feedback helper object.

process

process(shader: Shader, swap?: boolean): void

Runs the specified shader on the input buffer, writes results into the new buffer, then optionally swaps input/output.

Parameters

createShader

static createShader(graphicsDevice: GraphicsDevice, vertexCode: string, name: string, feedbackVaryings?: string[], feedbackVaryingsMode?: number): Shader

Creates a transform feedback ready vertex shader from code.

Parameters

Returns Shader: A shader to use in the process() function.

UniformBufferFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/uniform-buffer-format.js#L256

A descriptor that defines the layout of data inside the uniform buffer.

Constructors

constructor

new UniformBufferFormat(graphicsDevice: GraphicsDevice, uniforms: UniformFormat[], options?: object)

Create a new UniformBufferFormat instance.

Parameters

Properties

uniforms

uniforms: UniformFormat[]

Methods

get

get(name: string): UniformFormat | undefined

Returns format of a uniform with specified name. Returns undefined if the uniform is not found.

Parameters

Returns UniformFormat | undefined: - The format of the uniform.

UniformFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/uniform-buffer-format.js#L48

A class storing description of an individual uniform, stored inside a uniform buffer.

Constructors

constructor

new UniformFormat(name: string, type: number, count?: number)

Create a new UniformFormat instance.

Parameters

Accessors

isArrayType

get isArrayType(): boolean

True if this is an array of elements (i.e. count > 0)

VertexBuffer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-buffer.js#L18

A vertex buffer is the mechanism via which the application specifies vertex data to the graphics hardware.

Constructors

constructor

new VertexBuffer(graphicsDevice: GraphicsDevice, format: VertexFormat, numVertices: number, options?: object, ...args: any[])

Create a new VertexBuffer instance.

Parameters

Methods

destroy

destroy(): void

Frees resources associated with this vertex buffer.

getFormat

getFormat(): VertexFormat

Returns the data format of the specified vertex buffer.

Returns VertexFormat: The data format of the specified vertex buffer.

getNumVertices

getNumVertices(): number

Returns the number of vertices stored in the specified vertex buffer.

Returns number: The number of vertices stored in the vertex buffer.

getUsage

getUsage(): number

Returns the usage type of the specified vertex buffer. This indicates whether the buffer can be modified once and used many times BUFFER_STATIC, modified repeatedly and used many times BUFFER_DYNAMIC or modified once and used at most a few times BUFFER_STREAM.

Returns number: The usage type of the vertex buffer (see BUFFER_*).

lock

lock(): ArrayBuffer | ArrayBufferView<ArrayBufferLike>

Returns a mapped memory block representing the content of the vertex buffer.

Returns ArrayBuffer | ArrayBufferView<ArrayBufferLike>: The memory that stores the buffer's vertices. This matches whatever was supplied as the initial data: an ArrayBuffer when none was provided, otherwise the ArrayBuffer or typed array that was passed in. Use ArrayBufferConstructor.isView to distinguish the two before accessing it.

setData

setData(data?: ArrayBuffer | ArrayBufferView<ArrayBufferLike>): boolean

Sets the data of the vertex buffer and uploads it to the GPU.

Parameters

Returns boolean: True if function finished successfully, false otherwise.

unlock

unlock(byteOffset?: number, byteLength?: number): void

Uploads the client side copy of the vertex buffer to the GPU. When called without arguments, uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. The first upload always initializes the entire GPU buffer, regardless of the requested range. A zero byte length does nothing, including before the first upload.

Partial uploads do not resize the buffer or change its CPU storage. The caller must upload every modified range before expecting those changes on the GPU. Context restoration uploads the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion in debug builds.

Parameters

Example

// After modifying bytes 16 through 31 of the CPU storage:
vertexBuffer.unlock(16, 16);

VertexFormat

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-format.js#L69

A vertex format is a descriptor that defines the layout of vertex data inside a VertexBuffer.

Constructors

constructor

new VertexFormat(graphicsDevice: GraphicsDevice, description: AttributeDescription[], vertexCount?: number)

Create a new VertexFormat instance.

Parameters

Example

// Specify 3-component positions (x, y, z)
const vertexFormat = new VertexFormat(graphicsDevice, [
    { semantic: SEMANTIC_POSITION, components: 3, type: TYPE_FLOAT32 }
]);

Example

// Specify 2-component positions (x, y), a texture coordinate (u, v) and a vertex color (r, g, b, a)
const vertexFormat = new VertexFormat(graphicsDevice, [
    { semantic: SEMANTIC_POSITION, components: 2, type: TYPE_FLOAT32 },
    { semantic: SEMANTIC_TEXCOORD0, components: 2, type: TYPE_FLOAT32 },
    { semantic: SEMANTIC_COLOR, components: 4, type: TYPE_UINT8, normalize: true }
]);

Methods

hasUv

hasUv(index: number): boolean

Returns true if the format contains the texture coordinate set with the specified index.

Parameters

Returns boolean: True if the format contains the texture coordinate set.

getDefaultInstancingFormat

static getDefaultInstancingFormat(graphicsDevice: GraphicsDevice): VertexFormat

The VertexFormat used to store matrices of type Mat4 for hardware instancing. The matrix rows use SEMANTIC_ATTR11, SEMANTIC_ATTR12, SEMANTIC_ATTR14 and SEMANTIC_ATTR15. The first two share their attribute locations with SEMANTIC_TEXCOORD6 and SEMANTIC_TEXCOORD7, so a shader reading those texture coordinate sets needs a custom instancing format on other attributes.

Parameters

Returns VertexFormat: The default instancing vertex format.

VertexIterator

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-iterator.js#L240

A vertex iterator simplifies the process of writing vertex data to a vertex buffer.

Constructors

constructor

new VertexIterator(vertexBuffer: VertexBuffer)

Create a new VertexIterator instance.

Parameters

Properties

element

element: {}

The vertex buffer elements.

Methods

end

end(): void

Notifies the vertex buffer being iterated that writes are complete. Internally the vertex buffer is unlocked and vertex data is uploaded to video memory.

Example

const iterator = new VertexIterator(vertexBuffer);
iterator.element[SEMANTIC_POSITION].set(-0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(255, 0, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 255, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.0, 0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 0, 255, 255);
iterator.end();

next

next(count?: number): void

Moves the vertex iterator on to the next vertex.

Parameters

Example

const iterator = new VertexIterator(vertexBuffer);
iterator.element[SEMANTIC_POSITION].set(-0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(255, 0, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.9, -0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 255, 0, 255);
iterator.next();
iterator.element[SEMANTIC_POSITION].set(0.0, 0.9, 0.0);
iterator.element[SEMANTIC_COLOR].set(0, 0, 255, 255);
iterator.end();

WebglGraphicsDevice

Class · extends GraphicsDevice · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/webgl/webgl-graphics-device.js#L144

WebglGraphicsDevice extends the base GraphicsDevice to provide rendering capabilities utilizing the WebGL 2.0 specification.

Constructors

constructor

new WebglGraphicsDevice(canvas: HTMLCanvasElement, options?: object)

Creates a new WebglGraphicsDevice instance.

Parameters

Properties

transformFeedbackBuffers

transformFeedbackBuffers: VertexBuffer[] | null | undefined

Accessors

fullscreen

get fullscreen(): boolean
set fullscreen(fullscreen: boolean)

Gets whether the device is currently in fullscreen mode.

Methods

clear

clear(options?: object): void

Clears the frame buffer of the currently set render target.

Parameters

Example

// Clear color buffer to black and depth buffer to 1
device.clear();

// Clear just the color buffer to red
device.clear({
    color: [1, 0, 0, 1],
    flags: CLEARFLAG_COLOR
});

// Clear color buffer to yellow and depth to 1.0
device.clear({
    color: [1, 1, 0, 1],
    depth: 1,
    flags: CLEARFLAG_COLOR | CLEARFLAG_DEPTH
});

copyRenderTarget

copyRenderTarget(source?: RenderTarget, dest?: RenderTarget, color?: boolean, depth?: boolean): boolean

Copies source render target into destination render target. Mostly used by post-effects.

Parameters

Returns boolean: True if the copy was successful, false otherwise.

destroy

destroy(): void

Destroy the graphics device.

postInit

postInit(): void

Function that executes after the device has been created.

setBindGroup

setBindGroup(index: number, bindGroup: BindGroup, offsets?: Uint32Array<ArrayBufferLike>): void

Parameters

setBlendState

setBlendState(blendState: any): void

Sets the specified blend state.

Parameters

setCullMode

setCullMode(cullMode: any): void

Controls how triangles are culled based on their face direction. The default cull mode is CULLFACE_BACK.

Parameters

setDepthState

setDepthState(depthState: any): void

Sets the specified depth state.

Parameters

setFrontFace

setFrontFace(frontFace: any): void

Controls whether polygons are front- or back-facing by setting a winding orientation. The default frontFace is FRONTFACE_CCW.

Parameters

setScissor

setScissor(x: number, y: number, w: number, h: number): void

Set the active scissor rectangle on the specified device.

Parameters

setShader

setShader(shader: Shader, asyncCompile?: boolean): void

Sets the active shader to be used during subsequent draw calls.

Parameters

setStencilState

setStencilState(stencilFront: any, stencilBack: any): void

Sets the specified stencil state. If both stencilFront and stencilBack are null, stencil operation is disabled.

Parameters

setViewport

setViewport(x: number, y: number, w: number, h: number): void

Set the active rectangle for rendering on the specified device.

Parameters

Inherited from GraphicsDevice

WideLine

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L46

A connected, variable-width line rendered by a WideLineRenderer. Point data is supplied using packed numeric arrays to avoid allocating an object for each point.

A WideLine can belong to at most one WideLineRenderer. Removing it from the renderer leaves the WideLine intact, allowing it to be added to another renderer later.

Accessors

cap

get cap(): number
set cap(value: number)

Gets the cap style.

closed

get closed(): boolean
set closed(value: boolean)

Gets whether the last point connects back to the first point.

dashLength

get dashLength(): number
set dashLength(value: number)

Gets the length of each visible dash in world units.

dashOffset

get dashOffset(): number
set dashOffset(value: number)

Gets the offset of the dash pattern in world units.

gapLength

get gapLength(): number
set gapLength(value: number)

Gets the length of each gap in world units.

join

get join(): number
set join(value: number)

Gets the join style.

pointCount

get pointCount(): number

The number of points in the line. This is zero until WideLine#set is called.

renderer

get renderer(): WideLineRenderer | null

The renderer that owns this line, or null when the line is not being rendered.

Methods

set

set(positions: ArrayLike<number>, colors?: ArrayLike<number> | Color, widths?: number | ArrayLike<number>): WideLine

Atomically replaces all point data. This is the only operation that can change the number of points. The colors and widths can each be supplied either per point or as a single uniform value.

Parameters

Returns WideLine: This line.

setColors

setColors(colors: ArrayLike<number> | Color): WideLine

Replaces colors without changing the number of points.

Parameters

Returns WideLine: This line.

setPositions

setPositions(positions: ArrayLike<number>): WideLine

Replaces positions without changing the number of points.

Parameters

Returns WideLine: This line.

setWidths

setWidths(widths: number | ArrayLike<number>): WideLine

Replaces widths without changing the number of points.

Parameters

Returns WideLine: This line.

WideLineRenderer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L550

Renders a collection of WideLine objects using a single instanced draw call per camera/layer pass. Lines can use different widths, colors, caps, joins and dash patterns while remaining in the same batch, as these properties are stored in per-segment instance data.

Each WideLine describes a connected polyline in world space. Its width can vary per point and is interpreted as screen pixels or world units according to WideLineRenderer#widthUnits. A line can belong to only one WideLineRenderer at a time. Use WideLineRenderer#add and WideLineRenderer#remove to transfer ownership without changing the line data.

Basic usage

The following example creates a three-point line with a color gradient, variable width and rounded ends and joins:

const renderer = new WideLineRenderer(app);
const line = new WideLine();

line.set(
    new Float32Array([
        -2, 0, 0,
         0, 1, 0,
         2, 0, 0
    ]),
    new Float32Array([
        1, 0, 0,
        1, 1, 0,
        0, 1, 1
    ]),
    new Float32Array([4, 12, 4])
);
line.cap = LINECAP_ROUND;
line.join = LINEJOIN_ROUND;
renderer.add(line);

// Release GPU resources and detach all lines when no longer needed.
app.on('destroy', () => renderer.destroy());

Point data can be updated using WideLine#setPositions, WideLine#setColors and WideLine#setWidths. These methods preserve the point count and reuse the line's existing storage. Use WideLine#set when the point count needs to change.

Performance

Each line segment is rendered as one GPU instance. All segments owned by this renderer are submitted together, so adding more WideLine objects does not add draw calls. A renderer with visible segments issues one draw call for each camera that renders its layer. Multiple renderers therefore provide useful update isolation, but each adds another draw call per camera/layer pass.

Changing any owned line marks the renderer dirty. Before the next render, instance data for all of its lines is rebuilt and uploaded. For mixed workloads, place lines that rarely change in one renderer and frequently updated lines in another. There is no static or dynamic mode; the separation is achieved using two renderer instances. This prevents dynamic updates from repeatedly rebuilding the static segment data:

const staticLines = new WideLineRenderer(app);
const dynamicLines = new WideLineRenderer(app);

staticLines.add(roadNetwork); // Built and uploaded once.
dynamicLines.add(projectilePath); // Updated frequently.

Buffer WideLineRenderer#capacity is measured in segments and grows automatically as needed. Setting it in advance can avoid GPU buffer reallocations when the expected maximum segment count is known. WideLineRenderer#clear removes the lines but retains this capacity for reuse.

Rendering behavior and limitations

See the following examples for interactive styling and update demonstrations:

Constructors

constructor

new WideLineRenderer(app: AppBase)

Creates a new wide line renderer.

Parameters

Accessors

capacity

get capacity(): number
set capacity(value: number)

Gets the allocated instance capacity, measured in generated line segments.

depthTest

get depthTest(): boolean
set depthTest(value: boolean)

Gets whether lines are tested against the depth buffer.

depthWrite

get depthWrite(): boolean
set depthWrite(value: boolean)

Gets whether lines write to the depth buffer.

enabled

get enabled(): boolean
set enabled(value: boolean)

Gets whether this renderer is visible.

layer

get layer(): Layer
set layer(value: Layer)

Gets the layer containing the renderer's mesh instance.

widthUnits

get widthUnits(): number
set widthUnits(value: number)

Gets the units used to interpret line widths.

Methods

add

add(line: WideLine): void

Adds a line to this renderer. A line can belong to only one renderer at a time.

Parameters

clear

clear(): void

Removes all lines. Allocated instance capacity is retained for reuse.

destroy

destroy(): void

Releases all renderer-owned resources. Lines previously owned by this renderer remain usable and can be added to another renderer.

remove

remove(line: WideLine): boolean

Removes a line from this renderer without modifying its point data or style.

Parameters

Returns boolean: True if the line was owned by this renderer and was removed.

WireRenderer

Class · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wire-renderer.js#L109

Renders wireframe shapes for a single frame, for debugging and visualization. Shapes are submitted as line segments to the layer given by WireRenderer#layer, which defaults to the LAYERID_IMMEDIATE layer, and are discarded once the frame has been rendered, so they must be issued again on every frame they should be visible.

The renderer holds the state used by the shapes it draws - WireRenderer#color, WireRenderer#layer, WireRenderer#depthTest, WireRenderer#segments and WireRenderer#transform. Fields can be assigned between calls, and drawing many shapes with the same state allocates nothing:

const wire = new WireRenderer(app);
wire.color = Color.RED;

app.on('update', () => {
    for (const item of items) {
        wire.sphere(item.position, item.radius);
    }
});

A second set of state is simply a second instance. Instances hold no GPU resources, and those sharing a layer and depth test mode submit into the same batch, so using several has no additional rendering cost:

const xray = new WireRenderer(app);
xray.depthTest = false;

These are thin lines, one pixel wide. For thick lines with caps, joins and dashes, intended as part of the rendered scene rather than as a debugging aid, see WideLineRenderer instead.

Constructors

constructor

new WireRenderer(app: AppBase)

Creates a new WireRenderer instance.

Parameters

Example

const wire = new WireRenderer(app);

Properties

color

color: Color

The color used by shapes, specified in sRGB color space. The alpha component is respected. Defaults to white.

depthTest

depthTest: boolean = true

Whether shapes are depth tested against the depth buffer. Defaults to true.

layer

layer: Layer | null = null

The layer shapes are rendered into, or null to use the LAYERID_IMMEDIATE layer. Defaults to null.

segments

segments: number = 20

The number of line segments used to approximate a full circle. Defaults to 20.

transform

transform: Mat4 | null = null

A matrix applied to every point of every shape, or null for no transform. Assign this to draw a group of shapes in the local space of a node. Defaults to null.

Methods

arrow

arrow(from: Vec3, to: Vec3): void

Renders an arrow, as a shaft with four barbs at its tip.

Parameters

Example

wire.arrow(position, position.clone().add(velocity));

axes

axes(matrix: Mat4, size: number): void

Renders the three axes of a matrix, colored red, green and blue for x, y and z respectively. This function ignores WireRenderer#color.

Parameters

Example

wire.axes(entity.getWorldTransform(), 1);

box

box(box: BoundingBox | OrientedBox): void

Renders the edges of a bounding box. An OrientedBox is rendered in its own orientation, composed with WireRenderer#transform.

Parameters

Example

wire.box(meshInstance.aabb);

boxMinMax

boxMinMax(min: Vec3, max: Vec3): void

Renders the edges of a box specified by its min and max corners.

Parameters

Example

wire.boxMinMax(new Vec3(-1, -1, -1), new Vec3(1, 1, 1));

capsule

capsule(start: Vec3, end: Vec3, radius: number): void

Renders a capsule as a ring and hemispherical cap at each end, joined by four side lines.

Parameters

Example

wire.capsule(feet, head, 0.4);

circle

circle(center: Vec3, normal: Vec3, radius: number): void

Renders a circle lying in the plane described by a normal.

Parameters

Example

wire.circle(Vec3.ZERO, Vec3.UP, 5);

cone

cone(apex: Vec3, direction: Vec3, angle: number, length: number): void

Renders a cone as a base ring joined to its apex by four side lines. The parameters match those describing a spot light, so a light's cone can be visualized directly.

Parameters

Example

wire.cone(position, direction, 30, 10);

cylinder

cylinder(start: Vec3, end: Vec3, radius: number): void

Renders a cylinder as a ring at each end joined by four side lines.

Parameters

Example

wire.cylinder(base, tip, 0.5);

frustum

frustum(source: CameraComponent | Mat4): void

Renders the edges of a view frustum. The camera does not need to be enabled or rendering, so the view volume of an inactive camera can be visualized.

Parameters

Example

wire.frustum(otherCamera.camera);

light

light(light: LightComponent, size?: number): void

Renders the shape and extent of a light, using the light's own color. An omni light is drawn as a sphere of its range, a spot light as its cone, and a directional light as an arrow showing the direction it shines in. A light shines along the negative y-axis of its entity, so the shape follows that axis rather than the entity's forward direction.

Parameters

Example

wire.light(entity.light);

line

line(start: Vec3, end: Vec3): void

Renders a single line segment.

Parameters

Example

wire.line(new Vec3(0, 0, 0), new Vec3(0, 1, 0));

lines

lines(positions: Vec3[], colors?: Color[]): void

Renders discrete line segments, formed by consecutive pairs of points.

Parameters

Example

wire.lines([start, end], [Color.RED, Color.WHITE]);

linesPacked

linesPacked(positions: number[] | Float32Array<ArrayBufferLike>, colors?: number[] | Float32Array<ArrayBufferLike>): void

Renders discrete line segments from packed arrays of numbers. This is the fastest of the line functions, as it avoids reading individual Vec3 and Color instances.

Parameters

Example

wire.linesPacked([0, 0, 0, 0, 1, 0]);

loop

loop(positions: Vec3[], colors?: Color[]): void

Renders a closed strip of connected line segments, joining the last point back to the first.

Parameters

Example

wire.loop(outline);

plane

plane(center: Vec3, normal: Vec3, size: number): void

Renders a square section of a plane, with a short stub along its normal.

The rotation of the square within its plane is derived from the normal, and no such derivation is continuous over all directions. An animated normal will therefore make the square appear to jump as it passes the direction where the derivation switches. To rotate a square smoothly, pass a fixed normal and drive WireRenderer#transform instead.

Parameters

Example

wire.plane(Vec3.ZERO, Vec3.UP, 10);

point

point(position: Vec3, size: number): void

Renders a small axis-aligned cross marking a position.

Parameters

Example

wire.point(hit.point, 0.2);

polyline

polyline(positions: Vec3[], colors?: Color[]): void

Renders an open strip of connected line segments.

Parameters

Example

wire.polyline(trajectory);

sphere

sphere(center: Vec3, radius: number): void

Renders a sphere as three great circles, one in each of the primary planes.

Parameters

Example

wire.sphere(new Vec3(0, 1, 0), 0.5);

calculateNormals

Function · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry-utils.js#L14

calculateNormals(positions: ArrayLike<number>, indices: ArrayLike<number>): number[]

Generates normal information from the specified positions and triangle indices.

Parameters

Returns number[]: An array of 3-dimensional vertex normals.

Example

const normals = calculateNormals(positions, indices);

calculateTangents

Function · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/geometry/geometry-utils.js#L87

calculateTangents(positions: ArrayLike<number>, normals: ArrayLike<number>, uvs: ArrayLike<number>, indices: ArrayLike<number>): number[]

Generates tangent information from the specified positions, normals, texture coordinates and triangle indices.

Parameters

Returns number[]: An array of 3-dimensional vertex tangents.

Example

const tangents = calculateTangents(positions, normals, uvs, indices);

createGraphicsDevice

Function · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/graphics-device-create.js#L92

createGraphicsDevice(canvas: HTMLCanvasElement, options?: object): Promise<GraphicsDevice>

Creates a graphics device.

Parameters

Returns Promise<GraphicsDevice>: - Promise object representing the created graphics device. It is rejected if none of the device types can be created, with an AggregateError whose errors contain the error of each device type that failed.

drawQuadWithShader

Function · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/quad-render-utils.js#L30

drawQuadWithShader(device: GraphicsDevice, target: RenderTarget | null, shader: Shader, rect?: Vec4, scissorRect?: Vec4, name?: string): void

Draws a screen-space quad using a specific shader.

Parameters

reprojectTexture

Function · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graphics/reproject-texture.js#L391

reprojectTexture(source: Texture, target: Texture, options?: object): boolean

This function reprojects textures between cubemap, equirectangular and octahedral formats. The function can read and write textures with pixel data in RGBE, RGBM, linear and sRGB formats. When specularPower is specified it will perform a phong-weighted convolution of the source (for generating a gloss maps).

Parameters

Returns boolean: True if the reprojection was applied and false otherwise (e.g. if rect is empty)

PIXELFORMAT_ASTC_4x4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L779

ATC compressed format with alpha channel in blocks of 4x4.

const PIXELFORMAT_ASTC_4x4: 28 = 28

PIXELFORMAT_ASTC_4x4_SRGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L998

Format equivalent to PIXELFORMAT_ASTC_4x4 but sampled in linear color space.

const PIXELFORMAT_ASTC_4x4_SRGB: 63 = 63

DualGestureSource

Class · extends InputSource · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/dual-gesture-source.js#L36

Dual gesture input source. Two virtual controls for a touch screen, one on the left of the element and one on the right, producing leftInput and rightInput deltas as [x, y] and a doubleTap delta. The layout chooses a joystick or a plain touch area for each side, for example joystick-touch, and the joysticks are exposed as leftJoystick and rightJoystick.

Constructors

constructor

new DualGestureSource(layout?: "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch")

Parameters

Accessors

layout

get layout(): "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch"
set layout(value: "joystick-joystick" | "joystick-touch" | "touch-joystick" | "touch-touch")

leftJoystick

get leftJoystick(): VirtualJoystick

rightJoystick

get rightJoystick(): VirtualJoystick

Methods

attach

attach(element: HTMLElement): void

Parameters

destroy

destroy(): void

detach

detach(): void

read

read(): { doubleTap: number[]; leftInput: number[]; rightInput: number[] }

Returns { doubleTap: number[]; leftInput: number[]; rightInput: number[] }

Inherited from InputSource

FlyController

Class · extends InputController · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/fly-controller.js#L27

The fly controller. Free flight: rotate deltas turn the pose about yaw and pitch, limited by yawRange and pitchRange, and move deltas translate it along its own right, up and forward axes, so movement follows where the camera looks. Motion is smoothed with rotateDamping and moveDamping.

Properties

moveDamping

moveDamping: number = 0.98

The movement damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.

rotateDamping

rotateDamping: number = 0.98

The rotation damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.

Accessors

pitchRange

get pitchRange(): Vec2
set pitchRange(value: Vec2)

yawRange

get yawRange(): Vec2
set yawRange(value: Vec2)

Methods

attach

attach(pose: Pose, smooth?: boolean): void

Parameters

destroy

destroy(): void

detach

detach(): void

update

update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose

Parameters

Returns Pose: - The controller pose.

Inherited from InputController

FocusController

Class · extends InputController · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/focus-controller.js#L25

The focus controller. It ignores the input frame and instead eases the pose from where it was towards the pose given to attach, smoothed by focusDamping. Use it to animate a camera onto a new target and then hand over to another controller; complete reports when the target has been reached.

Properties

focusDamping

focusDamping: number = 0.98

The focus damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.

Methods

attach

attach(pose: Pose, smooth?: boolean): void

Parameters

complete

complete(): boolean

Returns boolean

destroy

destroy(): void

detach

detach(): void

update

update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose

Parameters

Returns Pose: - The controller pose.

Inherited from InputController

GamepadSource

Class · extends InputSource · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/gamepad-source.js#L33

Game pad input source class. Each read polls the connected gamepads and yields buttons deltas for the buttons listed in buttonCode, and leftStick and rightStick deltas as [x, y].

Constructors

constructor

new GamepadSource()

Properties

buttonCode

static readonly buttonCode: { A: 0; B: 1; LB: 4; LEFT_STICK: 10; LT: 6; RB: 5; RIGHT_STICK: 11; RT: 7; SELECT: 8; START: 9; X: 2; Y: 3 } = BUTTON_CODES

The button codes (based on Xbox controller layout).

Properties

Methods

read

read(): { buttons: number[]; leftStick: number[]; rightStick: number[] }

Returns { buttons: number[]; leftStick: number[]; rightStick: number[] }

Inherited from InputSource

InputConsumer

Class · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L230

The base class for all input consumers, which are used to process input frames. A consumer implements update, receiving an InputFrame and the frame time, and does whatever that input means for it. InputController is the consumer that turns input into a Pose.

Constructors

constructor

new InputConsumer()

Methods

update

update(frame: InputFrame<any>, dt: number): void

Parameters

InputController

Class · extends InputConsumer · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L258

The base class for all input controllers. A controller consumes an InputFrame carrying move and rotate deltas and produces a Pose: attach sets the pose it starts from, update applies a frame and returns the current pose, and detach releases it. The application applies the returned pose to an entity. FlyController, OrbitController and FocusController implement three ways of doing this.

Example

controller.attach(pose.look(cameraPosition, target));

// each frame, after filling the frame's move and rotate deltas from your sources
const result = controller.update(frame, dt);
camera.setPosition(result.position);
camera.setEulerAngles(result.angles);

Properties

_pose

protected _pose: Pose

Methods

attach

attach(pose: Pose, smooth?: boolean): void

Parameters

destroy

destroy(): void

detach

detach(): void

update

update(frame: InputFrame<any>, dt: number): Pose

Parameters

Returns Pose: - The controller pose.

Inherited from InputConsumer

InputDelta

Class · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L15

Represents an input delta: a fixed-length array of numbers that accumulates input between reads. Sources append raw values to it as events arrive, and read returns the total and resets it to zero, so each read yields the change since the previous one. An InputFrame groups named deltas together.

Constructors

constructor

new InputDelta(arg: number | number[])

Parameters

Methods

add

add(other: InputDelta): InputDelta

Adds another InputDelta instance to this one.

Parameters

Returns InputDelta: Self for chaining.

append

append(offsets: number[]): InputDelta

Appends offsets to the current delta values.

Parameters

Returns InputDelta: Self for chaining.

copy

copy(other: InputDelta): InputDelta

Copies the values from another InputDelta instance to this one.

Parameters

Returns InputDelta: Self for chaining.

length

length(): number

The magnitude of the delta, calculated as the square root of the sum of squares of the values.

Returns number: - The magnitude of the delta.

read

read(): number[]

Returns the current value of the delta and resets it to zero.

Returns number[]: - The current value of the delta.

InputFrame

Class · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L110

Represents an input frame, which contains a map of input deltas. The keys and lengths are fixed by the object passed to the constructor, for example { move: [0, 0, 0], rotate: [0, 0, 0] }, and read flushes every delta at once. A frame is the unit of exchange in this input system: InputSources are frames that fill themselves from a device, and an application combines their values into a frame with the shape an InputController expects.

template The shape of the input frame.

Constructors

constructor

new InputFrame<T extends Record<string, number[]>>(data: T)

Parameters

Properties

deltas

deltas: { [K in string | number | symbol]: InputDelta }

Methods

read

read(): { [K in string | number | symbol]: number[] }

Returns the current frame state and resets the deltas to zero.

Returns { [K in string | number | symbol]: number[] }: - The flushed input frame with current deltas.

InputSource

Class · extends InputFrame · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/input.js#L153

The base class for all input devices. An input source is an InputFrame that fills its own deltas from DOM events or device polling once attach is given an element, and stops on detach. Call InputFrame#read once per frame to take the accumulated deltas. The built-in sources are KeyboardMouseSource, GamepadSource, MultiTouchSource, SingleGestureSource and DualGestureSource; subclass this to add another device.

template The shape of the input source.

Properties

_element

protected _element: HTMLElement | null = null

Methods

attach

attach(element: HTMLElement): void

Parameters

destroy

destroy(): void

detach

detach(): void

fire

fire(event: string, ...args: any[]): void

Fires an event with the given name and arguments.

Parameters

off

off(event: string, callback: HandleEventCallback): void

Removes an event listener for the specified event.

Parameters

on

on(event: string, callback: HandleEventCallback): void

Adds an event listener for the specified event.

Parameters

Inherited from InputFrame

KeyboardMouseSource

Class · extends InputSource · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/keyboard-mouse-source.js#L70

Keyboard and mouse input source class. Attached to an element, it accumulates key deltas for the keys listed in keyCode, button deltas for the mouse buttons, mouse deltas for pointer movement and wheel deltas for the scroll wheel. Pass pointerLock: true to use pointer lock for mouse movement.

Constructors

constructor

new KeyboardMouseSource(options?: object)

Parameters

Properties

_button

_button: number[]

keyCode

static readonly keyCode: { 0: 26; 1: 27; 2: 28; 3: 29; 4: 30; 5: 31; 6: 32; 7: 33; 8: 34; 9: 35; A: 0; B: 1; C: 2; CTRL: 42; D: 3; DOWN: 37; E: 4; F: 5; G: 6; H: 7; I: 8; J: 9; K: 10; L: 11; LEFT: 38; M: 12; N: 13; O: 14; P: 15; Q: 16; R: 17; RIGHT: 39; S: 18; SHIFT: 41; SPACE: 40; T: 19; U: 20; UP: 36; V: 21; W: 22; X: 23; Y: 24; Z: 25 } = KEY_CODES

The key codes for the keyboard keys.

Properties

Methods

attach

attach(element: HTMLElement): void

Parameters

detach

detach(): void

read

read(): { button: number[]; key: number[]; mouse: number[]; wheel: number[] }

Returns { button: number[]; key: number[]; mouse: number[]; wheel: number[] }

Inherited from InputSource

MultiTouchSource

Class · extends InputSource · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/multi-touch-source.js#L22

Multi-touch input source class. Attached to an element, it accumulates touch deltas for the movement of the touch points, count deltas for changes in the number of touches, and pinch deltas for the change in distance between two touches, which is what an orbiting camera needs on a touch screen.

Constructors

constructor

new MultiTouchSource()

Methods

attach

attach(element: HTMLElement): void

Parameters

detach

detach(): void

Inherited from InputSource

OrbitController

Class · extends InputController · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/controllers/orbit-controller.js#L24

The orbit controller. The pose orbits a focus point at a distance: rotate deltas turn the view around the focus within yawRange and pitchRange, the first two move components pan the focus point, and the third scales the distance within zoomRange. Motion is smoothed with rotateDamping, moveDamping and zoomDamping.

Properties

moveDamping

moveDamping: number = 0.98

The movement damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.

rotateDamping

rotateDamping: number = 0.98

The rotation damping. In the range 0 to 1, where a value of 0 means no damping and 1 means full damping. Default is 0.98.

zoomDamping

zoomDamping: number = 0.98

The zoom damping. A higher value means more damping. A value of 0 means no damping.

Accessors

pitchRange

get pitchRange(): Vec2
set pitchRange(range: Vec2)

yawRange

get yawRange(): Vec2
set yawRange(range: Vec2)

zoomRange

get zoomRange(): Vec2
set zoomRange(range: Vec2)

Methods

attach

attach(pose: Pose, smooth?: boolean): void

Parameters

destroy

destroy(): void

detach

detach(): void

update

update(frame: InputFrame<{ move: number[]; rotate: number[] }>, dt: number): Pose

Parameters

Returns Pose: - The controller pose.

Inherited from InputController

Pose

Class · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/pose.js#L18

Represents a pose in 3D space, including position and rotation. It is what an InputController produces: a position, Euler angles in degrees and, for controllers that orbit, the distance to the focus point. Optional ranges such as pitchRange and yRange clamp the result of rotate and move.

Constructors

constructor

new Pose(position?: Vec3, angles?: Vec3, distance?: number)

Creates a new Pose instance.

Parameters

Properties

angles

angles: Vec3

The angles of the pose in degrees calculated from the forward vector.

distance

distance: number = 0

The focus distance from the position to the pose.

pitchRange

pitchRange: Vec2

The allowed range of pitch angles in degrees, stored as (min, max). Applied when the pose is rotated via rotate.

position

position: Vec3

The position of the pose.

xRange

xRange: Vec2

The allowed range of positions along the x axis, stored as (min, max). Applied when the pose is translated via move.

yawRange

yawRange: Vec2

The allowed range of yaw angles in degrees, stored as (min, max). Applied when the pose is rotated via rotate.

yRange

yRange: Vec2

The allowed range of positions along the y axis, stored as (min, max). Applied when the pose is translated via move.

zRange

zRange: Vec2

The allowed range of positions along the z axis, stored as (min, max). Applied when the pose is translated via move.

Methods

clone

clone(): Pose

Creates a clone of this pose.

Returns Pose: A new Pose instance with the same position, angles, and distance.

copy

copy(other: Pose): Pose

Copies the position and rotation from another pose.

Parameters

Returns Pose: The updated Pose instance.

equalsApprox

equalsApprox(other: Pose, epsilon?: number): boolean

Checks if this pose is approximately equal to another pose within a given epsilon.

Parameters

Returns boolean: True if the poses are approximately equal, false otherwise.

getFocus

getFocus(out?: Vec3): Vec3

Gets the focus point of the pose, which is the position plus the forward vector scaled by the distance.

Parameters

Returns Vec3: The focus point of the pose.

lerp

lerp(lhs: Pose, rhs: Pose, alpha1: number, alpha2?: number, alpha3?: number): Pose

Lerps between two poses based on the given alpha values.

Parameters

Returns Pose: The updated Pose instance.

look

look(from: Vec3, to: Vec3): Pose

Sets the pose to look in the direction of the given vector.

Parameters

Returns Pose: The updated Pose instance.

move

move(offset: Vec3): Pose

Moves the pose by the given vector.

Parameters

Returns Pose: The updated Pose instance.

rotate

rotate(euler: Vec3): Pose

Rotates the pose by the given angles in degrees.

Parameters

Returns Pose: The updated Pose instance.

set

set(position: Vec3, angles: Vec3, distance: number): Pose

Sets the position and rotation of the pose.

Parameters

Returns Pose: The updated Pose instance.

SingleGestureSource

Class · extends InputSource · category: Input

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/input/sources/single-gesture-source.js#L19

Single gesture input source. One virtual control for a touch screen, either an on-screen joystick or a drag anywhere on the element depending on layout, producing an input delta as [x, y] and a doubleTap delta.

Constructors

constructor

new SingleGestureSource()

Accessors

joystick

get joystick(): VirtualJoystick

layout

get layout(): "joystick" | "touch"
set layout(value: "joystick" | "touch")

Methods

attach

attach(element: HTMLElement): void

Parameters

destroy

destroy(): void

detach

detach(): void

read

read(): { doubleTap: number[]; input: number[] }

Returns { doubleTap: number[]; input: number[] }

Inherited from InputSource

GamePad

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L358

A GamePad stores information about a gamepad from the Gamepad API.

Properties

hand

hand: string

The hand this gamepad is usually handled on. Only relevant for XR pads. Value is either "left", "right" or "none".

id

id: string

The identifier for the gamepad. Its structure depends on device.

index

index: number

The index for this controller. A gamepad that is disconnected and reconnected will retain the same index.

map

map: any

The buttons and axes map.

mapping

mapping: string

The gamepad mapping detected by the browser. Value is either "standard", "xr-standard", "" or "custom". When empty string, you may need to update the mapping yourself. "custom" means you updated the mapping.

Accessors

axes

get axes(): number[]

Gets the values from analog axes present on the GamePad. Values are between -1 and 1.

buttons

get buttons(): GamePadButton[]

Gets the buttons present on the GamePad.

connected

get connected(): boolean

Gets whether the gamepad is connected.

Methods

getAxis

getAxis(axis: number): number

Get the value of one of the analog axes of the pad.

Parameters

Returns number: The value of the axis between -1 and 1.

getButton

getButton(index: number): GamePadButton

Retrieve a button from its index.

Parameters

Returns GamePadButton: The button for the searched index. May be a placeholder if none found.

getValue

getValue(button: number): number

Returns the value of a button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed.

Parameters

Returns number: The value of the button between 0 and 1.

isPressed

isPressed(button: number): boolean

Returns true if the button is pressed.

Parameters

Returns boolean: True if the button is pressed.

isTouched

isTouched(button: number): boolean

Returns true if the button is touched.

Parameters

Returns boolean: True if the button is touched.

pulse

pulse(intensity: number, duration: number, options?: object): Promise<boolean>

Make the gamepad vibrate.

Parameters

Returns Promise<boolean>: Return a Promise resulting in true if the pulse was successfully completed.

resetMap

resetMap(): void

Reset gamepad mapping to default.

updateMap

updateMap(map: object): void

Update the map for this gamepad.

Parameters

Example

this.pad.updateMap({
    buttons: [[
        'PAD_FACE_1',
        'PAD_FACE_2',
        'PAD_FACE_3',
        'PAD_FACE_4',
        'PAD_L_SHOULDER_1',
        'PAD_R_SHOULDER_1',
        'PAD_L_SHOULDER_2',
        'PAD_R_SHOULDER_2',
        'PAD_SELECT',
        'PAD_START',
        'PAD_L_STICK_BUTTON',
        'PAD_R_STICK_BUTTON',
        'PAD_VENDOR'
    ],
    axes: [
        'PAD_L_STICK_X',
        'PAD_L_STICK_Y',
        'PAD_R_STICK_X',
        'PAD_R_STICK_Y'
    ],
    synthesizedButtons: {
        PAD_UP: { axis: 0, min: 0, max: 1 },
        PAD_DOWN: { axis: 0, min: -1, max: 0 },
        PAD_LEFT: { axis: 0, min: -1, max: 0 },
        PAD_RIGHT: { axis: 0, min: 0, max: 1 }
    }
});

wasPressed

wasPressed(button: number): boolean

Return true if the button was pressed since the last update.

Parameters

Returns boolean: Return true if the button was pressed, false if not.

wasReleased

wasReleased(button: number): boolean

Return true if the button was released since the last update.

Parameters

Returns boolean: Return true if the button was released, false if not.

wasTouched

wasTouched(button: number): boolean

Return true if the button was touched since the last update.

Parameters

Returns boolean: Return true if the button was touched, false if not.

GamePadButton

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L268

A GamePadButton stores information about a button from the Gamepad API.

Properties

pressed

pressed: boolean = false

Whether the button is currently down.

touched

touched: boolean = false

Whether the button is currently touched.

value

value: number = 0

The value for the button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed.

wasPressed

wasPressed: boolean = false

Whether the button was pressed.

wasReleased

wasReleased: boolean = false

Whether the button was released since the last update.

wasTouched

wasTouched: boolean = false

Whether the button was touched since the last update.

GamePads

Class · extends EventHandler · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/game-pads.js#L784

Input handler for accessing GamePad input.

For frame-accumulated input deltas rather than raw pad state, see GamepadSource, KeyboardMouseSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.

Constructors

constructor

new GamePads()

Create a new GamePads instance.

Properties

current

current: GamePad[] = []

The list of current gamepads.

gamepadsSupported

gamepadsSupported: boolean

Whether gamepads are supported by this device.

Methods

findById

findById(id: string): GamePad | null

Find a connected GamePad from its identifier.

Parameters

Returns GamePad | null: The GamePad with the matching identifier or null if no gamepad is found or the gamepad is not connected.

findByIndex

findByIndex(index: number): GamePad | null

Find a connected GamePad from its device index.

Parameters

Returns GamePad | null: The GamePad with the matching device index or null if no gamepad is found or the gamepad is not connected.

getAxis

getAxis(orderIndex: number, axis: number): number

Get the value of one of the analog axes of the pad.

Parameters

Returns number: The value of the axis between -1 and 1.

getMap

getMap(pad: Gamepad): any

Retrieve the order for buttons and axes for given HTML5 Gamepad.

Parameters

Returns any: Object defining the order of buttons and axes for given HTML5 Gamepad.

isPressed

isPressed(orderIndex: number, button: number): boolean

Returns true if the button on the pad requested is pressed.

Parameters

Returns boolean: True if the button is pressed.

poll

poll(pads?: GamePad[]): GamePad[]

Poll for the latest data from the gamepad API.

Parameters

Returns GamePad[]: An array of gamepads and mappings for the model of gamepad that is attached.

Example

const gamepads = new GamePads();
const pads = gamepads.poll();

pulse

pulse(orderIndex: number, intensity: number, duration: number, options?: object): Promise<boolean>

Make the gamepad vibrate.

Parameters

Returns Promise<boolean>: Return a Promise resulting in true if the pulse was successfully completed.

pulseAll

pulseAll(intensity: number, duration: number, options?: object): Promise<boolean[]>

Make all gamepads vibrate.

Parameters

Returns Promise<boolean[]>: Return a Promise resulting in an array of booleans defining if the pulse was successfully completed for every gamepads.

wasPressed

wasPressed(orderIndex: number, button: number): boolean

Returns true if the button was pressed since the last frame.

Parameters

Returns boolean: True if the button was pressed since the last frame.

wasReleased

wasReleased(orderIndex: number, button: number): boolean

Returns true if the button was released since the last frame.

Parameters

Returns boolean: True if the button was released since the last frame.

Events

EVENT_GAMEPADCONNECTED

static EVENT_GAMEPADCONNECTED: string = 'gamepadconnected'

Fired when a gamepad is connected. The handler is passed the GamePad object that was connected.

Example

const onPadConnected = (pad) => {
    if (!pad.mapping) {
        // Map the gamepad as the system could not find the proper map.
    } else {
        // Make the gamepad pulse.
    }
};

app.keyboard.on("gamepadconnected", onPadConnected, this);

EVENT_GAMEPADDISCONNECTED

static EVENT_GAMEPADDISCONNECTED: string = 'gamepaddisconnected'

Fired when a gamepad is disconnected. The handler is passed the GamePad object that was disconnected.

Example

const onPadDisconnected = (pad) => {
    // Pause the game.
};

app.keyboard.on("gamepaddisconnected", onPadDisconnected, this);

Inherited from EventHandler

Keyboard

Class · extends EventHandler · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/keyboard.js#L79

Manages keyboard input by tracking key states and dispatching events. Extends EventHandler in order to fire keydown and keyup events (see KeyboardEvent).

Allows the state of individual keys to be queried to check if they are currently pressed or were pressed/released since the last update. The class automatically handles browser visibility changes and window blur events by clearing key states. The Keyboard instance must be attached to a DOM element before it can detect key events.

Key state is derived from the legacy KeyboardEvent.keyCode property. Browsers populate it for real input, but a hand-constructed new KeyboardEvent(...) leaves it at 0, so synthesized events must set keyCode explicitly in order to be observed.

Keyboard#wasPressed and Keyboard#wasReleased compare against a snapshot taken once per frame, so a keydown and keyup delivered within the same task are seen by neither. Hold the key across at least one frame.

Your application's Keyboard instance is managed and accessible via AppBase#keyboard.

For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see KeyboardMouseSource, GamepadSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.

Constructors

constructor

new Keyboard(element?: Element | Window, options?: object)

Create a new Keyboard instance.

Parameters

Example

// attach keyboard listeners to the window
const keyboard = new Keyboard(window);

Properties

preventDefault

preventDefault: boolean

Call preventDefault() in key event handlers.

stopPropagation

stopPropagation: boolean

Call stopPropagation() in key event handlers.

Methods

attach

attach(element: Element | Window): void

Attach the keyboard event handlers to an Element. If already attached, this first detaches and clears current and previous key states, even when attaching to the same element. No keyup events are fired. Unlike Mouse#attach, held input states are not preserved.

Parameters

detach

detach(): void

Detach the keyboard event handlers from the element it is attached to and clear current and previous key states. This does not fire keyup events.

isPressed

isPressed(key: number): boolean

Return true if the key is currently down.

Parameters

Returns boolean: True if the key was pressed, false if not.

wasPressed

wasPressed(key: number): boolean

Returns true if the key was pressed since the last update.

Parameters

Returns boolean: True if the key was pressed.

wasReleased

wasReleased(key: number): boolean

Returns true if the key was released since the last update.

Parameters

Returns boolean: True if the key was pressed.

Events

EVENT_KEYDOWN

static EVENT_KEYDOWN: string = 'keydown'

Fired when a key is pressed. The handler is passed a KeyboardEvent.

Example

const onKeyDown = (e) => {
    if (e.key === KEY_SPACE) {
        // space key pressed
    }
    e.event.preventDefault(); // Use original browser event to prevent browser action.
};

app.keyboard.on('keydown', onKeyDown, this);

EVENT_KEYUP

static EVENT_KEYUP: string = 'keyup'

Fired when a key is released. The handler is passed a KeyboardEvent.

Example

const onKeyUp = (e) => {
    if (e.key === KEY_SPACE) {
        // space key released
    }
    e.event.preventDefault(); // Use original browser event to prevent browser action.
};

app.keyboard.on('keyup', onKeyUp, this);

Inherited from EventHandler

KeyboardEvent

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/keyboard-event.js#L14

The KeyboardEvent is passed into all event handlers registered on the Keyboard. The events are:

Constructors

constructor

new KeyboardEvent(keyboard?: Keyboard, event?: KeyboardEvent)

Create a new KeyboardEvent.

Parameters

Example

const onKeyDown = function (e) {
    if (e.key === KEY_SPACE) {
        // space key pressed
    }
    e.event.preventDefault(); // Use original browser event to prevent browser action.
};
app.keyboard.on("keydown", onKeyDown, this);

Properties

element

element: Element | null = null

The element that fired the keyboard event.

event

event: KeyboardEvent | null = null

The original browser event which was fired.

key

key: number | null = null

The keyCode of the key that has changed. See the KEY_* constants.

Mouse

Class · extends EventHandler · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse.js#L36

Manages mouse input by tracking button states and dispatching events. Extends EventHandler to fire mousedown, mouseup, mousemove and mousewheel events (see MouseEvent).

Allows the state of mouse buttons to be queried to check if they are currently pressed or were pressed/released since the last update. Provides methods to enable/disable pointer lock for raw mouse movement input and control over the context menu. The class automatically clears button states when the window loses focus or the document becomes hidden, without firing mouseup events. The Mouse instance must be attached to a DOM element before it can detect mouse events.

The first unlocked mouse movement after creation, detachment or focus loss establishes a new position and reports zero movement delta. Movement outside the target also invalidates the position, so re-entry reports zero delta. Pointer-locked movement uses the browser's relative movement deltas.

Your application's Mouse instance is managed and accessible via AppBase#mouse.

For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see KeyboardMouseSource, GamepadSource and MultiTouchSource, which feed InputControllers such as OrbitController, FlyController and FocusController.

Constructors

constructor

new Mouse(element?: Element)

Create a new Mouse instance.

Parameters

Methods

attach

attach(element: Element): void

Attach mouse events to an Element. If already attached, this changes the target element while preserving current and previous button states, unlike Keyboard#attach.

Parameters

detach

detach(): void

Remove mouse events from the element that it is attached to and clear current and previous button states. The previous mouse position is also invalidated so the next unlocked movement reports zero delta. This does not fire mouseup events.

disableContextMenu

disableContextMenu(): void

Disable the context menu usually activated with right-click.

disablePointerLock

disablePointerLock(success?: LockMouseCallback): void

Return control of the mouse cursor to the user.

Parameters

enableContextMenu

enableContextMenu(): void

Enable the context menu usually activated with right-click. This option is active by default.

enablePointerLock

enablePointerLock(success?: LockMouseCallback, error?: LockMouseCallback): void

Request that the browser hides the mouse cursor and locks the mouse to the element. Allowing raw access to mouse movement input without risking the mouse exiting the element. Notes:

Parameters

isPressed

isPressed(button: number): boolean

Returns true if the mouse button is currently pressed.

Parameters

Returns boolean: True if the mouse button is current pressed.

update

update(): void

Update method, should be called once per frame.

wasPressed

wasPressed(button: number): boolean

Returns true if the mouse button was pressed this frame (since the last call to update).

Parameters

Returns boolean: True if the mouse button was pressed since the last update.

wasReleased

wasReleased(button: number): boolean

Returns true if the mouse button was released this frame (since the last call to update).

Parameters

Returns boolean: True if the mouse button was released since the last update.

isPointerLocked

static isPointerLocked(): boolean

Check if the mouse pointer has been locked, using enablePointerLock.

Returns boolean: True if locked.

Events

EVENT_MOUSEDOWN

static EVENT_MOUSEDOWN: string = 'mousedown'

Fired when a mouse button is pressed. The handler is passed a MouseEvent.

Example

app.mouse.on('mousedown', (e) => {
    console.log(`The ${e.button} button was pressed at position: ${e.x}, ${e.y}`);
});

EVENT_MOUSEMOVE

static EVENT_MOUSEMOVE: string = 'mousemove'

Fired when the mouse is moved. The handler is passed a MouseEvent.

Example

app.mouse.on('mousemove', (e) => {
    console.log(`Current mouse position is: ${e.x}, ${e.y}`);
});

EVENT_MOUSEUP

static EVENT_MOUSEUP: string = 'mouseup'

Fired when a mouse button is released. The handler is passed a MouseEvent.

Example

app.mouse.on('mouseup', (e) => {
    console.log(`The ${e.button} button was released at position: ${e.x}, ${e.y}`);
});

EVENT_MOUSEWHEEL

static EVENT_MOUSEWHEEL: string = 'mousewheel'

Fired when a mouse wheel is moved. The handler is passed a MouseEvent.

Example

app.mouse.on('mousewheel', (e) => {
    console.log(`The mouse wheel was moved by ${e.wheelDelta}`);
});

Inherited from EventHandler

MouseEvent

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse-event.js#L27

The MouseEvent object is passed into all event handlers registered on the Mouse. The events are:

Constructors

constructor

new MouseEvent(mouse: Mouse, event: MouseEvent | WheelEvent)

Create a new MouseEvent instance.

Parameters

Properties

altKey

altKey: boolean = false

True if the alt key was pressed when this event was fired.

button

button: number = MOUSEBUTTON_NONE

The mouse button associated with this event. Can be:

buttons

buttons: boolean[]

The pressed state of all mouse buttons at the time this event was fired. A 3-element array of booleans for left, middle and right buttons respectively.

ctrlKey

ctrlKey: boolean = false

True if the ctrl key was pressed when this event was fired.

dx

dx: number = 0

The change in x coordinate since the last mouse movement event. When the pointer is not locked, this is zero until an unlocked movement establishes a position after creation, detachment, focus loss, movement outside the target or pointer-locked movement. Under pointer lock, this uses the browser's relative movement delta.

dy

dy: number = 0

The change in y coordinate since the last mouse movement event. When the pointer is not locked, this is zero until an unlocked movement establishes a position after creation, detachment, focus loss, movement outside the target or pointer-locked movement. Under pointer lock, this uses the browser's relative movement delta.

element

element: Element

The element that the mouse was fired from.

event

event: MouseEvent | WheelEvent

The original browser event.

metaKey

metaKey: boolean = false

True if the meta key was pressed when this event was fired.

shiftKey

shiftKey: boolean = false

True if the shift key was pressed when this event was fired.

wheelDelta

wheelDelta: number = 0

A value representing the amount the mouse wheel has moved, only valid for Mouse.EVENT_MOUSEWHEEL events.

x

x: number = 0

The x coordinate of the mouse pointer relative to the element Mouse is attached to.

y

y: number = 0

The y coordinate of the mouse pointer relative to the element Mouse is attached to.

Touch

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L40

A instance of a single point touch on a TouchDevice.

Constructors

constructor

new Touch(touch: Touch)

Create a new Touch object from the browser Touch.

Parameters

Properties

id

id: number

The identifier of the touch.

target

target: Element

The target DOM element of the touch event.

touch

touch: Touch

The original browser Touch object.

x

x: number

The x coordinate relative to the element that the TouchDevice is attached to.

y

y: number

The y coordinate relative to the element that the TouchDevice is attached to.

TouchDevice

Class · extends EventHandler · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-device.js#L17

Manages touch input by handling and dispatching touch events. Extends EventHandler to fire touchstart, touchend, touchmove, and touchcancel events (see TouchEvent).

Detects and processes touch interactions with the attached DOM element, allowing applications to respond to common touch gestures. The TouchDevice instance must be attached to a DOM element before it can detect touch events.

Your application's TouchDevice instance is managed and accessible via AppBase#touch.

Constructors

constructor

new TouchDevice(element: Element)

Create a new touch device and attach it to an element.

Parameters

Methods

attach

attach(element: Element): void

Attach a device to an element in the DOM. If the device is already attached to an element this method will detach it first.

Parameters

detach

detach(): void

Detach a device from the element it is attached to.

Events

EVENT_TOUCHCANCEL

static EVENT_TOUCHCANCEL: string = 'touchcancel'

Fired when a touch is interrupted in some way. The exact reasons for canceling a touch can vary from device to device. For example, a modal alert pops up during the interaction; the touch point leaves the document area, or there are more touch points than the device supports, in which case the earliest touch point is canceled. The handler is passed a TouchEvent.

Example

app.touch.on('touchcancel', (e) => {
    console.log(`Touch canceled at position: ${e.x}, ${e.y}`);
});

EVENT_TOUCHEND

static EVENT_TOUCHEND: string = 'touchend'

Fired when a touch ends. The handler is passed a TouchEvent.

Example

app.touch.on('touchend', (e) => {
    console.log(`Touch ended at position: ${e.x}, ${e.y}`);
});

EVENT_TOUCHMOVE

static EVENT_TOUCHMOVE: string = 'touchmove'

Fired when a touch moves. The handler is passed a TouchEvent.

Example

app.touch.on('touchmove', (e) => {
    console.log(`Touch moved to position: ${e.x}, ${e.y}`);
});

EVENT_TOUCHSTART

static EVENT_TOUCHSTART: string = 'touchstart'

Fired when a touch starts. The handler is passed a TouchEvent.

Example

app.touch.on('touchstart', (e) => {
    console.log(`Touch started at position: ${e.x}, ${e.y}`);
});

Inherited from EventHandler

TouchEvent

Class · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L103

The TouchEvent object is passed into all event handlers registered on the TouchDevice. The events are:

Constructors

constructor

new TouchEvent(device: TouchDevice, event: TouchEvent)

Create a new TouchEvent instance. It is created from an existing browser event.

Parameters

Properties

changedTouches

changedTouches: Touch[] = []

A list of touches that have changed since the last event.

element

element: Element

The target DOM element that the event was fired from.

event

event: TouchEvent

The original browser TouchEvent.

touches

touches: Touch[] = []

A list of all touches currently in contact with the device.

Methods

getTouchById

getTouchById(id: number, list: Touch[]): Touch | null

Get an event from one of the touch lists by the id. It is useful to access touches by their id so that you can be sure you are referencing the same touch.

Parameters

Returns Touch | null: The Touch object or null.

getTouchTargetCoords

Function · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/touch-event.js#L14

getTouchTargetCoords(touch: Touch): { x: number; y: number }

This function takes a browser Touch object and returns the coordinates of the touch relative to the target DOM element.

Parameters

Returns { x: number; y: number }: The coordinates of the touch relative to the touch.target DOM element.

BoundingBox

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/bounding-box.js#L48

Axis-Aligned Bounding Box. An AABB is commonly used for fast overlap tests in collision detection, spatial indexing and frustum culling.

A box is stored as a center and halfExtents. Set it from its extreme corners with setMinMax and read them back with getMin and getMax. Fit a box to vertex data with compute, grow it to enclose another box with add, and move a local box into world space with setFromTransformedAabb, which is how the engine derives a mesh instance's world bounds from its mesh's local bounds.

Tests such as intersects, containsPoint and intersectsRay return a boolean and allocate nothing. closestPoint writes into an optional result vector, while getMin and getMax return the box's own cached vectors, which should be treated as read-only. The constructor copies the vectors it is given.

Example

// Enclose every mesh instance of a render component in one box
const bounds = new BoundingBox();
entity.render.meshInstances.forEach((meshInstance, i) => {
    if (i === 0) {
        bounds.copy(meshInstance.aabb);
    } else {
        bounds.add(meshInstance.aabb);
    }
});

Example

// Pick against a box; the ray's direction must be normalized
const hit = new Vec3();
if (bounds.intersectsRay(ray, hit)) {
    console.log(`Hit at ${hit}`);
}

Constructors

constructor

new BoundingBox(center?: Vec3, halfExtents?: Vec3)

Create a new BoundingBox instance. The bounding box is axis-aligned.

Parameters

Properties

center

readonly center: Vec3

Center of box.

halfExtents

readonly halfExtents: Vec3

Half the distance across the box in each axis.

Methods

add

add(other: BoundingBox): void

Combines two bounding boxes into one, enclosing both.

Parameters

clone

clone(): BoundingBox

Returns a clone of the AABB.

Returns BoundingBox: A duplicate AABB.

closestPoint

closestPoint(point: Vec3, result?: Vec3): Vec3

Return the point on the AABB closest to a given point. If the point is inside the AABB, the point itself is returned.

Parameters

Returns Vec3: The closest point on the AABB.

Example

const box = new BoundingBox(new Vec3(0, 0, 0), new Vec3(1, 1, 1));
const point = new Vec3(2, 0, 0);
const closest = box.closestPoint(point); // Returns Vec3(1, 0, 0)

Example

// Reuse a result vector to avoid allocations in hot paths
const result = new Vec3();
box.closestPoint(point, result);

compute

compute(vertices: ArrayLike<number>, numVerts?: number): void

Compute the size of the AABB to encapsulate all specified vertices.

Parameters

containsPoint

containsPoint(point: Vec3): boolean

Test if a point is inside an AABB.

Parameters

Returns boolean: True if the point is inside the AABB and false otherwise.

copy

copy(src: BoundingBox): void

Copies the contents of a source AABB.

Parameters

equals

equals(other: BoundingBox): boolean

Reports whether two axis-aligned bounding boxes are equal.

Parameters

Returns boolean: True if the AABBs have the same center and half extents, false otherwise.

getMax

getMax(): Vec3

Return the maximum corner of the AABB.

Returns Vec3: Maximum corner.

getMin

getMin(): Vec3

Return the minimum corner of the AABB.

Returns Vec3: Minimum corner.

intersects

intersects(other: BoundingBox): boolean

Test whether two axis-aligned bounding boxes intersect.

Parameters

Returns boolean: True if there is an intersection.

intersectsBoundingSphere

intersectsBoundingSphere(sphere: BoundingSphere): boolean

Test if a Bounding Sphere is overlapping, enveloping, or inside this AABB.

Parameters

Returns boolean: True if the Bounding Sphere is overlapping, enveloping, or inside the AABB and false otherwise.

intersectsRay

intersectsRay(ray: Ray, point?: Vec3): boolean

Test if a ray intersects with the AABB.

Parameters

Returns boolean: True if there is an intersection.

setFromTransformedAabb

setFromTransformedAabb(aabb: BoundingBox, m: Mat4, ignoreScale?: boolean): void

Set an AABB to enclose the specified AABB if it were to be transformed by the specified 4x4 matrix.

Parameters

setMinMax

setMinMax(min: Vec3, max: Vec3): void

Sets the minimum and maximum corner of the AABB. Using this function is faster than assigning min and max separately.

Parameters

computeMinMax

static computeMinMax(vertices: ArrayLike<number>, min: Vec3, max: Vec3, numVerts?: number): void

Compute the min and max bounding values to encapsulate all specified vertices.

Parameters

BoundingSphere

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/bounding-sphere.js#L28

A bounding sphere is a volume for facilitating fast intersection testing.

A sphere is a center and a radius. It is the cheapest bounding volume to test, so it suits broad-phase checks made before a finer test. containsPoint, intersectsBoundingSphere and intersectsRay return a boolean and allocate nothing. Unlike BoundingBox, the constructor keeps a reference to the center vector it is given rather than copying it, so the sphere follows any later changes to that vector.

Example

// A trigger volume 2 units around an entity
const sphere = new BoundingSphere(entity.getPosition().clone(), 2);
if (sphere.containsPoint(player.getPosition())) {
    // the player is within 2 units of the entity
}

Constructors

constructor

new BoundingSphere(center?: Vec3, radius?: number)

Creates a new BoundingSphere instance.

Parameters

Example

// Create a new bounding sphere centered on the origin with a radius of 0.5
const sphere = new BoundingSphere();

Properties

center

readonly center: Vec3

Center of sphere.

radius

radius: number

The radius of the bounding sphere.

Methods

containsPoint

containsPoint(point: Vec3): boolean

Test if a point is inside the sphere.

Parameters

Returns boolean: True if the point is inside the sphere and false otherwise.

Example

const sphere = new BoundingSphere(new Vec3(0, 0, 0), 1);
const point = new Vec3(0.5, 0, 0);
const isInside = sphere.containsPoint(point); // true

intersectsBoundingSphere

intersectsBoundingSphere(sphere: BoundingSphere): boolean

Test if a Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere.

Parameters

Returns boolean: True if the Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere and false otherwise.

intersectsRay

intersectsRay(ray: Ray, point?: Vec3): boolean

Test if a ray intersects with the sphere.

Parameters

Returns boolean: True if there is an intersection.

Color

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/color.js#L30

An RGBA color.

Each color component is a floating point value in the range 0 to 1. The r (red), g (green) and b (blue) components define a color in RGB color space. The a (alpha) component defines transparency. An alpha of 1 is fully opaque. An alpha of 0 is fully transparent.

A Color stores the values it is given and does not track whether they are in linear or gamma (sRGB) space. Convert explicitly with linear and gamma when a value crosses that boundary. fromString and toString exchange colors with the #RRGGBB and #RRGGBBAA notation used by CSS, and lerp blends two colors.

Methods modify the color they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. The named constants such as WHITE and RED are frozen shared instances, so copy one before modifying it.

Example

// Set a material color from a CSS hex string
material.diffuse.fromString('#ff8800');
material.update();

Example

// Fade between two colors without allocating
const tint = new Color();
tint.lerp(Color.RED, Color.BLUE, t);

Constructors

constructor

new Color(r?: number, g?: number, b?: number, a?: number)

Creates a new Color instance.

Parameters

Example

const c1 = new Color(); // defaults to 0, 0, 0, 1
const c2 = new Color(0.1, 0.2, 0.3, 0.4);
new Color(arr: number[])

Creates a new Color instance.

Parameters

Example

const c = new Color([0.1, 0.2, 0.3, 0.4]);

Properties

a

a: number

The alpha component of the color.

b

b: number

The blue component of the color.

g

g: number

The green component of the color.

r

r: number

The red component of the color.

BLACK

static readonly BLACK: Color

A constant color set to black [0, 0, 0, 1].

BLUE

static readonly BLUE: Color

A constant color set to blue [0, 0, 1, 1].

CYAN

static readonly CYAN: Color

A constant color set to cyan [0, 1, 1, 1].

GRAY

static readonly GRAY: Color

A constant color set to gray [0.5, 0.5, 0.5, 1].

GREEN

static readonly GREEN: Color

A constant color set to green [0, 1, 0, 1].

MAGENTA

static readonly MAGENTA: Color

A constant color set to magenta [1, 0, 1, 1].

RED

static readonly RED: Color

A constant color set to red [1, 0, 0, 1].

WHITE

static readonly WHITE: Color

A constant color set to white [1, 1, 1, 1].

YELLOW

static readonly YELLOW: Color

A constant color set to yellow [1, 1, 0, 1].

Methods

clone

clone(): Color

Returns a clone of the specified color.

Returns Color: A duplicate color object.

Example

const c = new Color(1, 0, 0, 1);
const cClone = c.clone();
// cClone is [1, 0, 0, 1]

copy

copy(rhs: Color): Color

Copies the contents of a source color to a destination color.

Parameters

Returns Color: Self for chaining.

Example

const src = new Color(1, 0, 0, 1);
const dst = new Color();

dst.copy(src);

console.log("The two colors are " + (dst.equals(src) ? "equal" : "different"));

equals

equals(rhs: Color): boolean

Reports whether two colors are equal.

Parameters

Returns boolean: True if the colors are equal and false otherwise.

Example

const a = new Color(1, 0, 0, 1);
const b = new Color(1, 1, 0, 1);
console.log("The two colors are " + (a.equals(b) ? "equal" : "different"));

fromArray

fromArray(arr: number[], offset?: number): Color

Set the values of the color from an array.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color();
c.fromArray([1, 0, 1, 1]);
// c is set to [1, 0, 1, 1]

fromString

fromString(hex: string): Color

Set the values of the color from a string representation '#11223344' or '#112233'.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color();
c.fromString('#ff0000');
// c is now [1, 0, 0, 1]

gamma

gamma(src?: Color): Color

Converts the color from linear to gamma color space.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color(0.218, 0.218, 0.218, 1);
c.gamma();
// c is now approximately [0.5, 0.5, 0.5, 1]

lerp

lerp(lhs: Color, rhs: Color, alpha: number): Color

Returns the result of a linear interpolation between two specified colors.

Parameters

Returns Color: Self for chaining.

Example

const a = new Color(0, 0, 0);
const b = new Color(1, 1, 0.5);
const r = new Color();

r.lerp(a, b, 0);   // r is equal to a
r.lerp(a, b, 0.5); // r is 0.5, 0.5, 0.25
r.lerp(a, b, 1);   // r is equal to b

linear

linear(src?: Color): Color

Converts the color from gamma to linear color space.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color(0.5, 0.5, 0.5, 1);
c.linear();
// c is now approximately [0.218, 0.218, 0.218, 1]

mulScalar

mulScalar(scalar: number): Color

Multiplies RGB elements of a Color by a number. Note that the alpha value is left unchanged.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color(0.2, 0.4, 0.6, 1);
c.mulScalar(2);
// c is now [0.4, 0.8, 1.2, 1]

set

set(r: number, g: number, b: number, a?: number): Color

Assign values to the color components, including alpha.

Parameters

Returns Color: Self for chaining.

Example

const c = new Color();
c.set(1, 0, 0, 1);
// c is now red [1, 0, 0, 1]

toArray

toArray(arr?: number[], offset?: number): number[]

Parameters

Returns number[]: The color as an array.

toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView

Parameters

Returns ArrayBufferView: The color as an array.

toString

toString(alpha: boolean, asArray?: boolean): string

Converts the color to string form. The format is '#RRGGBBAA', where RR, GG, BB, AA are the red, green, blue and alpha values. When the alpha value is not included (the default), this is the same format as used in HTML/CSS.

Parameters

Returns string: The color in string form.

Example

const c = new Color(1, 1, 1);
// Outputs #ffffff
console.log(c.toString());

Curve

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/curve.js#L22

A curve is a collection of keys (time/value pairs). The shape of the curve is defined by its type that specifies an interpolation scheme for the keys.

Keys are kept sorted by time. Supply them to the constructor as a flat [time, value, ...] array or insert them one at a time with add, then evaluate the curve at any time with value. The type selects how values between keys are computed: CURVE_LINEAR, CURVE_SMOOTHSTEP, CURVE_SPLINE or CURVE_STEP. Curves drive values that change over time or over a normalized range, such as particle size over a particle's lifetime.

Example

// Ease a value in over one second and read it back a quarter of the way through
const curve = new Curve([0, 0, 1, 1]);
curve.type = CURVE_SMOOTHSTEP;
const v = curve.value(0.25);

Constructors

constructor

new Curve(data?: number[])

Creates a new Curve instance.

Parameters

Example

const curve = new Curve([
    0, 0,        // At 0 time, value of 0
    0.33, 2,     // At 0.33 time, value of 2
    0.66, 2.6,   // At 0.66 time, value of 2.6
    1, 3         // At 1 time, value of 3
]);

Properties

keys

keys: number[][] = []

The keys that define the curve. Each key is an array of two numbers with the time first and the value second.

tension

tension: number = 0.5

Controls how CURVE_SPLINE tangents are calculated. Valid range is between 0 and 1 where 0 results in a non-smooth curve (equivalent to linear interpolation) and 1 results in a very smooth curve. Use 0.5 for a Catmull-Rom spline.

type

type: number = CURVE_SMOOTHSTEP

The curve interpolation scheme. Can be:

Defaults to CURVE_SMOOTHSTEP.

Accessors

length

get length(): number

Gets the number of keys in the curve.

Methods

add

add(time: number, value: number): number[]

Adds a new key to the curve.

Parameters

Returns number[]: The newly created [time, value] pair.

Example

const curve = new Curve();
curve.add(0, 1);   // add key at time 0 with value 1
curve.add(1, 2);   // add key at time 1 with value 2

clear

clear(): Curve

Removes all keys from the curve.

Returns Curve: The curve instance.

Example

const curve = new Curve([0, 1, 1, 2]);
curve.clear(); // curve now has no keys

clone

clone(): Curve

Returns a clone of the specified curve object.

Returns Curve: A clone of the specified curve.

Example

const curve = new Curve([0, 0, 1, 10]);
const clonedCurve = curve.clone();

closest

closest(time: number): number[] | null

Returns the key closest to the specified time. When two keys are equally close, the later one is returned.

Parameters

Returns number[] | null: The [time, value] pair closest to the specified time, or null if no keys exist.

Example

const curve = new Curve([0, 1, 0.5, 2, 1, 3]);
const key = curve.closest(0.6); // returns [0.5, 2]

get

get(index: number): number[]

Gets the [time, value] pair at the specified index.

Parameters

Returns number[]: The [time, value] pair at the specified index.

Example

const curve = new Curve([0, 1, 1, 2]);
const key = curve.get(0); // returns [0, 1]

remove

remove(index: number): number[] | null

Removes the key at the specified index.

Parameters

Returns number[] | null: The removed [time, value] pair, or null if the index is out of range.

Example

const curve = new Curve([0, 1, 1, 2]);
curve.remove(0); // removes the key at time 0

sort

sort(): void

Sorts keys by time.

value

value(time: number): number

Returns the interpolated value of the curve at specified time.

Parameters

Returns number: The interpolated value.

Example

const curve = new Curve([0, 0, 1, 10]);
const value = curve.value(0.5); // returns interpolated value at time 0.5

CurveSet

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/curve-set.js#L24

A curve set is a collection of curves that share a time axis and are evaluated together, such as the three channels of a color or the components of a vector changing over time.

Build one from an array of [time, value, ...] key arrays, one per curve, or from a number of empty curves. Setting type applies that interpolation to every curve in the set, and value returns the value of each curve at a time as one array. Reach an individual Curve with get.

Example

// Animate an RGB color over time and sample it at the midpoint
const colorOverTime = new CurveSet([
    [0, 1, 1, 0],   // red:   1 at t = 0, 0 at t = 1
    [0, 0, 1, 1],   // green: 0 at t = 0, 1 at t = 1
    [0, 0, 1, 0]    // blue:  0 throughout
]);
const [r, g, b] = colorOverTime.value(0.5);

Constructors

constructor

new CurveSet(...args: any[])

Creates a new CurveSet instance.

Parameters

Example

// Create from an array of arrays of keys
const curveSet = new CurveSet([
    [
        0, 0,        // At 0 time, value of 0
        0.33, 2,     // At 0.33 time, value of 2
        0.66, 2.6,   // At 0.66 time, value of 2.6
        1, 3         // At 1 time, value of 3
    ],
    [
        0, 34,
        0.33, 35,
        0.66, 36,
        1, 37
    ]
]);

Properties

curves

curves: Curve[] = []

The array of curves in the set.

Accessors

length

get length(): number

Gets the number of curves in the curve set.

type

get type(): number
set type(value: number)

Gets the interpolation scheme applied to all curves in the curve set.

Methods

add

add(data?: number[]): Curve

Appends a new curve to the curve set. The new curve adopts the curve set's current CurveSet#type interpolation scheme, so that all curves in the set continue to share the same type.

Parameters

Returns Curve: The newly created curve.

Example

const curveSet = new CurveSet([[0, 0, 1, 1]]);
const curve = curveSet.add([0, 0, 1, 0.5]); // append a second curve

clear

clear(): CurveSet

Removes all curves from the curve set, leaving it empty.

Returns CurveSet: The curve set instance.

Example

const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.clear(); // the set now has no curves

clearKeys

clearKeys(): CurveSet

Removes all keys from every curve in the set, while keeping the curves themselves. The number of curves is unchanged, so CurveSet#value still returns an array of the same length.

Returns CurveSet: The curve set instance.

Example

const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.clearKeys(); // both curves are now empty, but the set still has 2 curves

clone

clone(): CurveSet

Returns a clone of the specified curve set object.

Returns CurveSet: A clone of the specified curve set.

Example

const curveSet = new CurveSet([[0, 0, 1, 1]]);
const clonedCurveSet = curveSet.clone();

get

get(index: number): Curve

Return a specific curve in the curve set.

Parameters

Returns Curve: The curve at the specified index.

Example

const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
const curve = curveSet.get(0); // returns the first curve

remove

remove(indexOrCurve: number | Curve): Curve | null

Removes a curve from the curve set.

Parameters

Returns Curve | null: The removed curve, or null if it was not found.

Example

const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
curveSet.remove(0);             // remove by index
curveSet.remove(curveSet.get(0)); // or remove by reference

value

value(time: number, result?: number[]): number[]

Returns the interpolated value of all curves in the curve set at the specified time.

Parameters

Returns number[]: The interpolated curve values at the specified time.

Example

const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]);
const values = curveSet.value(0.5); // returns interpolated values for all curves at time 0.5

FloatPacking

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/float-packing.js#L24

Utility static class providing functionality to pack float values to various storage representations.

float2Half converts a JavaScript number to the 16-bit half-float encoding used by half-precision textures and vertex formats, so float data can be uploaded to the GPU at half the size.

Example

// Fill a half-float buffer from an array of numbers
const halves = new Uint16Array(values.length);
for (let i = 0; i < values.length; i++) {
    halves[i] = FloatPacking.float2Half(values[i]);
}

Methods

float2Half

static float2Half(value: number): number

Packs a float to a 16-bit half-float representation used by the GPU.

Parameters

Returns number: The 16-bit half-float representation as an integer.

Example

const half = FloatPacking.float2Half(1.5);

Frustum

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/frustum.js#L65

A frustum is a shape that defines the viewing space of a camera. It can be used to determine visibility of points and bounding spheres. Typically, you would not create a Frustum shape directly, but instead query CameraComponent#frustum.

A frustum is six Planes, read and written with getPlane and setPlane, and normally derived from a camera's combined view-projection matrix with setFromMat4. containsPoint and containsAabb return a boolean. containsSphere returns 0 for a sphere outside, 1 for one that intersects and 2 for one fully inside, so callers can skip finer tests for objects that are entirely visible. None of the tests allocate.

Example

// Skip work for objects the camera cannot see
const frustum = entity.camera.frustum;
if (frustum.containsAabb(meshInstance.aabb)) {
    // visible: update it
}

Constructors

constructor

new Frustum()

Create a new Frustum instance.

Example

const frustum = new Frustum();

Methods

add

add(other: Frustum): Frustum

Expands this frustum to also contain another frustum. The other frustum's 8 corner points are computed, and each of this frustum's planes is pushed outwards just far enough to contain them all. The result is a conservative convex volume that contains both frustums. This is useful for multi-view rendering such as stereo XR, where culling should keep objects visible in any view.

Note: keeping each plane's orientation makes this correct for arbitrary frusta, including the asymmetric per-eye projections of XR headsets, where matching planes of the two eyes have different normals and a per-plane "outermost" selection would wrongly cut into the combined volume at a distance.

Parameters

Returns Frustum: Self for chaining.

clone

clone(): Frustum

Returns a clone of the specified frustum.

Returns Frustum: A duplicate frustum.

Example

const frustum = new Frustum();
const clone = frustum.clone();

containsAabb

containsAabb(aabb: BoundingBox): boolean

Tests whether an axis aligned bounding box intersects the frustum.

The test is conservative in the same way the plane based sphere test is: a box lying just outside a frustum corner can be reported as intersecting. It is however always at least as tight as testing the box's bounding sphere, since the extent of a box along a plane normal never exceeds the radius of its bounding sphere.

Unlike Frustum#containsSphere, a box completely inside the frustum is not distinguished from one merely intersecting it. Detecting that costs a comparison per plane and no caller needs it.

Parameters

Returns boolean: True if the bounding box intersects or is inside the frustum, false if it is completely outside.

containsPoint

containsPoint(point: Vec3): boolean

Tests whether a point is inside the frustum. Note that points lying in a frustum plane are considered to be outside the frustum.

Parameters

Returns boolean: True if the point is inside the frustum, false otherwise.

containsSphere

containsSphere(sphere: BoundingSphere): number

Tests whether a bounding sphere intersects the frustum. If the sphere is outside the frustum, zero is returned. If the sphere intersects the frustum, 1 is returned. If the sphere is completely inside the frustum, 2 is returned. Note that a sphere touching a frustum plane from the outside is considered to be outside the frustum.

Parameters

Returns number: 0 if the bounding sphere is outside the frustum, 1 if it intersects the frustum and 2 if it is contained by the frustum.

copy

copy(src: Frustum): Frustum

Copies the contents of a source frustum to a destination frustum.

Parameters

Returns Frustum: Self for chaining.

Example

const src = entity.camera.frustum;
const dst = new Frustum();
dst.copy(src);

getPlane

getPlane(index: number, result: Plane): Plane

Returns one of the frustum's six planes. The planes are ordered right, left, bottom, top, far, near, and their normals point inwards.

Parameters

Returns Plane: The supplied plane, containing the frustum plane.

Example

const plane = new Plane();
entity.camera.frustum.getPlane(0, plane);

setFromMat4

setFromMat4(matrix: Mat4): void

Updates the frustum shape based on the supplied 4x4 matrix.

Parameters

Example

// Create a perspective projection matrix
const projection = new Mat4();
projection.setPerspective(45, 16 / 9, 1, 1000);

// Create a frustum shape that is represented by the matrix
const frustum = new Frustum();
frustum.setFromMat4(projection);

setPlane

setPlane(index: number, plane: Plane): Frustum

Sets one of the frustum's six planes. The plane is normalized as it is stored, as the frustum's tests require unit length normals. The planes are ordered right, left, bottom, top, far, near, and their normals must point inwards.

Parameters

Returns Frustum: Self for chaining.

Kernel

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/kernel.js#L14

Sampling kernels: sets of 2D offsets, generated on demand, used to take several samples around a point, as blur, soft shadow and ambient occlusion effects do.

concentric produces a center point followed by points arranged in evenly spaced rings out to a radius of one, returned as a flat [x, y, x, y, ...] array ready to upload as a shader uniform.

Example

// A kernel with 3 rings and 8 points in the innermost ring
const offsets = Kernel.concentric(3, 8);   // [0, 0, x1, y1, x2, y2, ...]

Methods

concentric

static concentric(numRings: number, numPoints: number): number[]

Generate a set of points distributed in a series of concentric rings around the origin. The spacing between points is determined by the number of points in the first ring, and subsequent rings maintain this spacing by adjusting their number of points accordingly.

Parameters

Returns number[]: An array where each point is represented by two consecutive numbers (x, y).

Example

// Generate a kernel with 3 rings and 8 points in the first ring
const kernel = Kernel.concentric(3, 8);
// kernel is a flat array: [x0, y0, x1, y1, x2, y2, ...]

Mat3

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/mat3.js#L28

A 3x3 matrix. Mat3 is commonly used to represent rotation matrices, 2D transformations or the upper-left portion of a 4x4 matrix for transforming normals.

A new Mat3 is the identity. Elements live in data, a 9-element Float32Array in column-major order, so the first three entries are the first column. Build one from a rotation with setFromQuat, or take the upper-left 3x3 of a Mat4 with setFromMat4, and apply it to a Vec3 with transformVector. getX, getY and getZ read the columns, which for a rotation matrix are its axes.

Methods modify the matrix they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. IDENTITY and ZERO are frozen shared instances.

Example

// Take the rotation and scale of an entity's world transform and apply it to a direction
const rotationScale = new Mat3().setFromMat4(entity.getWorldTransform());
const worldDirection = rotationScale.transformVector(localDirection);

Constructors

constructor

new Mat3()

Create a new Mat3 instance. It is initialized to the identity matrix.

Properties

data

data: Float32Array<ArrayBufferLike>

Matrix elements in the form of a flat array.

IDENTITY

static readonly IDENTITY: Mat3

A constant matrix set to the identity.

ZERO

static readonly ZERO: Mat3

A constant matrix with all elements set to 0.

Methods

clone

clone(): Mat3

Creates a duplicate of the specified matrix.

Returns Mat3: A duplicate matrix.

Example

const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const dst = src.clone();
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));

copy

copy(rhs: Mat3): Mat3

Copies the contents of a source 3x3 matrix to a destination 3x3 matrix.

Parameters

Returns Mat3: Self for chaining.

Example

const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const dst = new Mat3();
dst.copy(src);
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));

equals

equals(rhs: Mat3): boolean

Reports whether two matrices are equal.

Parameters

Returns boolean: True if the matrices are equal and false otherwise.

Example

const a = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924));
const b = new Mat3();
console.log("The two matrices are " + (a.equals(b) ? "equal" : "different"));

getX

getX(x?: Vec3): Vec3

Extracts the x-axis from the specified matrix.

Parameters

Returns Vec3: The x-axis of the specified matrix.

Example

const m = new Mat3();
const xAxis = m.getX(); // Vec3(1, 0, 0) for identity matrix

getY

getY(y?: Vec3): Vec3

Extracts the y-axis from the specified matrix.

Parameters

Returns Vec3: The y-axis of the specified matrix.

Example

const m = new Mat3();
const yAxis = m.getY(); // Vec3(0, 1, 0) for identity matrix

getZ

getZ(z?: Vec3): Vec3

Extracts the z-axis from the specified matrix.

Parameters

Returns Vec3: The z-axis of the specified matrix.

Example

const m = new Mat3();
const zAxis = m.getZ(); // Vec3(0, 0, 1) for identity matrix

isIdentity

isIdentity(): boolean

Reports whether the specified matrix is the identity matrix.

Returns boolean: True if the matrix is identity and false otherwise.

Example

const m = new Mat3();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));

set

set(src: number[]): Mat3

Copies the contents of a source array[9] to a destination 3x3 matrix.

Parameters

Returns Mat3: Self for chaining.

Example

const dst = new Mat3();
dst.set([0, 1, 2, 3, 4, 5, 6, 7, 8]);

setFromMat4

setFromMat4(m: Mat4): Mat3

Converts the specified 4x4 matrix to a Mat3.

Parameters

Returns Mat3: Self for chaining.

Example

const m4 = new Mat4();
const m3 = new Mat3().setFromMat4(m4);

setFromQuat

setFromQuat(r: Quat): Mat3

Sets this matrix to the given quaternion rotation.

Parameters

Returns Mat3: Self for chaining.

Example

const r = new Quat(1, 2, 3, 4).normalize();

const m = new Mat3();
m.setFromQuat(r);

setIdentity

setIdentity(): Mat3

Sets the matrix to the identity matrix.

Returns Mat3: Self for chaining.

Example

m.setIdentity();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));

toString

toString(): string

Converts the matrix to string form.

Returns string: The matrix in string form.

Example

const m = new Mat3();
// Outputs [1, 0, 0, 0, 1, 0, 0, 0, 1]
console.log(m.toString());

transformVector

transformVector(vec: Vec3, res?: Vec3): Vec3

Transforms a 3-dimensional vector by a 3x3 matrix.

Parameters

Returns Vec3: The input vector v transformed by the current instance.

Example

const m = new Mat3();
const v = new Vec3(1, 2, 3);
const result = m.transformVector(v);

transpose

transpose(src?: Mat3): Mat3

Generates the transpose of the specified 3x3 matrix.

Parameters

Returns Mat3: Self for chaining.

Example

const m = new Mat3();

// Transpose in place
m.transpose();

Mat4

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/mat4.js#L48

A 4x4 matrix. Mat4 is commonly used to represent world, view and projection transformations in 3D graphics, combining rotation, translation and scale into a single matrix.

A new Mat4 is the identity. Elements live in data, a 16-element Float32Array in column-major order: the translation occupies elements 12, 13 and 14. Build a transform with setTRS, setFromEulerAngles or setFromAxisAngle, a camera matrix with setLookAt, setPerspective or setOrtho, and read parts back with getTranslation, getScale and getEulerAngles. Angles are in degrees.

Matrices combine by multiplication: r.mul2(a, b) computes a * b, so b is applied first when the result transforms a point. transformPoint applies the full transform including translation, while transformVector applies only rotation and scale, which is what directions need.

Methods modify the matrix they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. IDENTITY and ZERO are frozen shared instances, and the matrix returned by GraphNode#getWorldTransform is internal storage to be treated as read-only.

Example

// Compose a transform from position, rotation and scale
const world = new Mat4().setTRS(
    new Vec3(0, 1, 0),
    new Quat().setFromEulerAngles(0, 45, 0),
    Vec3.ONE
);

Example

// Transform a local point into world space
const worldPoint = entity.getWorldTransform().transformPoint(localPoint);

Constructors

constructor

new Mat4()

Create a new Mat4 instance. It is initialized to the identity matrix.

Properties

data

data: Float32Array<ArrayBufferLike>

Matrix elements in the form of a flat array.

IDENTITY

static readonly IDENTITY: Mat4

A constant matrix set to the identity.

ZERO

static readonly ZERO: Mat4

A constant matrix with all elements set to 0.

Methods

add

add(rhs: Mat4): Mat4

Adds the specified 4x4 matrix to the current instance.

Parameters

Returns Mat4: Self for chaining.

Example

const m = new Mat4();

m.add(Mat4.ONE);

console.log("The result of the addition is: " + m.toString());

add2

add2(lhs: Mat4, rhs: Mat4): Mat4

Adds the specified 4x4 matrices together and stores the result in the current instance.

Parameters

Returns Mat4: Self for chaining.

Example

const m = new Mat4();

m.add2(Mat4.IDENTITY, Mat4.ONE);

console.log("The result of the addition is: " + m.toString());

clone

clone(): Mat4

Creates a duplicate of the specified matrix.

Returns Mat4: A duplicate matrix.

Example

const src = new Mat4().setFromEulerAngles(10, 20, 30);
const dst = src.clone();
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));

copy

copy(rhs: Mat4): Mat4

Copies the contents of a source 4x4 matrix to a destination 4x4 matrix.

Parameters

Returns Mat4: Self for chaining.

Example

const src = new Mat4().setFromEulerAngles(10, 20, 30);
const dst = new Mat4();
dst.copy(src);
console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different"));

equals

equals(rhs: Mat4): boolean

Reports whether two matrices are equal.

Parameters

Returns boolean: True if the matrices are equal and false otherwise.

Example

const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4();
console.log("The two matrices are " + (a.equals(b) ? "equal" : "different"));

getEulerAngles

getEulerAngles(eulers?: Vec3): Vec3

Extracts the Euler angles equivalent to the rotational portion of the specified matrix. The returned Euler angles are in intrinsic XYZ order and in degrees.

Parameters

Returns Vec3: A 3-d vector containing the Euler angles.

Example

// Create a 4x4 rotation matrix of 45 degrees around the y-axis
const m = new Mat4().setFromAxisAngle(Vec3.UP, 45);

const eulers = m.getEulerAngles();

getScale

getScale(scale?: Vec3): Vec3

Extracts the scale component from the specified 4x4 matrix.

Parameters

Returns Vec3: The scale in X, Y and Z of the specified 4x4 matrix.

Example

// Query the scale component
const scale = m.getScale();

getTranslation

getTranslation(t?: Vec3): Vec3

Extracts the translational component from the specified 4x4 matrix.

Parameters

Returns Vec3: The translation of the specified 4x4 matrix.

Example

// Create a 4x4 matrix
const m = new Mat4();

// Query the translation component
const t = new Vec3();
m.getTranslation(t);

getX

getX(x?: Vec3): Vec3

Extracts the x-axis from the specified 4x4 matrix.

Parameters

Returns Vec3: The x-axis of the specified 4x4 matrix.

Example

// Create a 4x4 matrix
const m = new Mat4();

// Query the x-axis component
const x = new Vec3();
m.getX(x);

getY

getY(y?: Vec3): Vec3

Extracts the y-axis from the specified 4x4 matrix.

Parameters

Returns Vec3: The y-axis of the specified 4x4 matrix.

Example

// Create a 4x4 matrix
const m = new Mat4();

// Query the y-axis component
const y = new Vec3();
m.getY(y);

getZ

getZ(z?: Vec3): Vec3

Extracts the z-axis from the specified 4x4 matrix.

Parameters

Returns Vec3: The z-axis of the specified 4x4 matrix.

Example

// Create a 4x4 matrix
const m = new Mat4();

// Query the z-axis component
const z = new Vec3();
m.getZ(z);

invert

invert(src?: Mat4): Mat4

Sets the matrix to the inverse of a source matrix.

Parameters

Returns Mat4: Self for chaining.

Example

// Create a 4x4 rotation matrix of 180 degrees around the y-axis
const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180);

// Invert in place
rot.invert();

isIdentity

isIdentity(): boolean

Reports whether the specified matrix is the identity matrix.

Returns boolean: True if the matrix is identity and false otherwise.

Example

const m = new Mat4();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));

mul

mul(rhs: Mat4): Mat4

Multiplies the current instance by the specified 4x4 matrix.

Parameters

Returns Mat4: Self for chaining.

Example

const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);

// a = a * b
a.mul(b);

console.log("The result of the multiplication is: " + a.toString());

mul2

mul2(lhs: Mat4, rhs: Mat4): Mat4

Multiplies the specified 4x4 matrices together and stores the result in the current instance.

Parameters

Returns Mat4: Self for chaining.

Example

const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);
const r = new Mat4();

// r = a * b
r.mul2(a, b);

console.log("The result of the multiplication is: " + r.toString());

mulAffine2

mulAffine2(lhs: Mat4, rhs: Mat4): Mat4

Multiplies the specified 4x4 matrices together and stores the result in the current instance. This function assumes the matrices are affine transformation matrices, where the upper left 3x3 elements are a rotation matrix, and the bottom left 3 elements are translation. The rightmost column is assumed to be [0, 0, 0, 1]. The parameters are not verified to be in the expected format. This function is faster than general mul2.

Parameters

Returns Mat4: Self for chaining.

Example

const a = new Mat4().setFromEulerAngles(10, 20, 30);
const b = new Mat4().setFromAxisAngle(Vec3.UP, 180);
const r = new Mat4();

// r = a * b (optimized for affine transforms)
r.mulAffine2(a, b);

set

set(src: number[]): Mat4

Sets matrix data from an array.

Parameters

Returns Mat4: Self for chaining.

Example

const m = new Mat4();
m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]);

setFromAxisAngle

setFromAxisAngle(axis: Vec3, angle: number): Mat4

Sets the specified matrix to a rotation matrix equivalent to a rotation around an axis. The axis must be normalized (unit length) and the angle must be specified in degrees.

Parameters

Returns Mat4: Self for chaining.

Example

// Create a 4x4 rotation matrix
const rm = new Mat4().setFromAxisAngle(Vec3.UP, 90);

setFromEulerAngles

setFromEulerAngles(ex: number, ey: number, ez: number): Mat4

Sets the specified matrix to a rotation matrix defined by Euler angles. The rotation is applied using an intrinsic XYZ order: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis. Angles are specified in degrees.

Parameters

Returns Mat4: Self for chaining.

Example

const m = new Mat4();
m.setFromEulerAngles(45, 90, 180);

setIdentity

setIdentity(): Mat4

Sets the specified matrix to the identity matrix.

Returns Mat4: Self for chaining.

Example

m.setIdentity();
console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity"));

setLookAt

setLookAt(position: Vec3, target: Vec3, up: Vec3): Mat4

Sets the specified matrix to a viewing matrix derived from an eye point, a target point and an up vector. The matrix maps the target point to the negative z-axis and the eye point to the origin, so that when you use a typical projection matrix, the center of the scene maps to the center of the viewport. Similarly, the direction described by the up vector projected onto the viewing plane is mapped to the positive y-axis so that it points upward in the viewport. The up vector must not be parallel to the line of sight from the eye to the reference point.

Parameters

Returns Mat4: Self for chaining.

Example

const position = new Vec3(10, 10, 10);
const target = new Vec3(0, 0, 0);
const up = new Vec3(0, 1, 0);
const m = new Mat4().setLookAt(position, target, up);

setOrtho

setOrtho(left: number, right: number, bottom: number, top: number, near: number, far: number): Mat4

Sets the specified matrix to an orthographic projection matrix. The function's parameters define the shape of a cuboid-shaped frustum.

Parameters

Returns Mat4: Self for chaining.

Example

// Create a 4x4 orthographic projection matrix
const ortho = new Mat4().setOrtho(-2, 2, -2, 2, 1, 1000);

setPerspective

setPerspective(fov: number, aspect: number, znear: number, zfar: number, fovIsHorizontal?: boolean): Mat4

Sets the specified matrix to a perspective projection matrix. The function's parameters define the shape of a frustum.

Parameters

Returns Mat4: Self for chaining.

Example

// Create a 4x4 perspective projection matrix
const persp = new Mat4().setPerspective(45, 16 / 9, 1, 1000);

setReflection

setReflection(normal: Vec3, distance: number): Mat4

Sets the matrix to a reflection matrix, which can be used as a mirror transformation by the plane.

Parameters

Returns Mat4: Self for chaining.

Example

// Create a reflection matrix for a horizontal plane at y=0
const reflection = new Mat4().setReflection(Vec3.UP, 0);

setTRS

setTRS(t: Vec3, r: Quat, s: Vec3): Mat4

Sets the specified matrix to the concatenation of a translation, a quaternion rotation and a scale.

Parameters

Returns Mat4: Self for chaining.

Example

const t = new Vec3(10, 20, 30);
const r = new Quat();
const s = new Vec3(2, 2, 2);

const m = new Mat4();
m.setTRS(t, r, s);

toString

toString(): string

Converts the specified matrix to string form.

Returns string: The matrix in string form.

Example

const m = new Mat4();
// Outputs [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
console.log(m.toString());

transformPoint

transformPoint(vec: Vec3, res?: Vec3): Vec3

Transforms a 3-dimensional point by a 4x4 matrix.

Parameters

Returns Vec3: The input point v transformed by the current instance.

Example

// Create a 3-dimensional point
const v = new Vec3(1, 2, 3);

// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);

const tv = m.transformPoint(v);

transformVec4

transformVec4(vec: Vec4, res?: Vec4): Vec4

Transforms a 4-dimensional vector by a 4x4 matrix.

Parameters

Returns Vec4: The input vector v transformed by the current instance.

Example

// Create an input 4-dimensional vector
const v = new Vec4(1, 2, 3, 4);

// Create an output 4-dimensional vector
const result = new Vec4();

// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);

m.transformVec4(v, result);

transformVector

transformVector(vec: Vec3, res?: Vec3): Vec3

Transforms a 3-dimensional vector by a 4x4 matrix.

Parameters

Returns Vec3: The input vector v transformed by the current instance.

Example

// Create a 3-dimensional vector
const v = new Vec3(1, 2, 3);

// Create a 4x4 rotation matrix
const m = new Mat4().setFromEulerAngles(10, 20, 30);

const tv = m.transformVector(v);

transpose

transpose(src?: Mat4): Mat4

Sets the matrix to the transpose of a source matrix.

Parameters

Returns Mat4: Self for chaining.

Example

const m = new Mat4();

// Transpose in place
m.transpose();

OrientedBox

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/oriented-box.js#L36

An oriented bounding box is a box that can be rotated and translated in 3D space. It is defined by a world transform and half extents. Unlike an axis-aligned bounding box, an OBB can be oriented arbitrarily.

The constructor takes a Mat4 holding the box's position and rotation, then its half extents. Scale is assumed to be one, so size the box with the half extents rather than the matrix. worldTransform can be reassigned at any time and the setter copies the matrix, so assigning an entity's world transform each frame gives a box that follows it. The tests containsPoint, intersectsRay and intersectsBoundingSphere return a boolean and allocate nothing.

Example

// A 2 x 1 x 4 box that follows an entity
const box = new OrientedBox(entity.getWorldTransform(), new Vec3(1, 0.5, 2));

// later, after the entity has moved
box.worldTransform = entity.getWorldTransform();
if (box.containsPoint(player.getPosition())) {
    // the player is inside the box
}

Constructors

constructor

new OrientedBox(worldTransform?: Mat4, halfExtents?: Vec3)

Create a new OrientedBox instance.

Parameters

Accessors

worldTransform

get worldTransform(): Mat4
set worldTransform(value: Mat4)

Gets the world transform of the OBB.

Methods

containsPoint

containsPoint(point: Vec3): boolean

Test if a point is inside an OBB.

Parameters

Returns boolean: True if the point is inside the OBB and false otherwise.

intersectsBoundingSphere

intersectsBoundingSphere(sphere: BoundingSphere): boolean

Test if a Bounding Sphere is overlapping, enveloping, or inside this OBB.

Parameters

Returns boolean: True if the Bounding Sphere is overlapping, enveloping or inside this OBB and false otherwise.

intersectsRay

intersectsRay(ray: Ray, point?: Vec3): boolean

Test if a ray intersects with the OBB.

Parameters

Returns boolean: True if there is an intersection.

Plane

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/plane.js#L28

An infinite plane. Internally, it's represented in a parametric equation form: ax + by + cz + distance = 0.

A plane is a normal and a distance from the origin along that normal. Define one with the constructor or setFromPointNormal from a normal and a point the plane passes through, or with set from the four coefficients. None of these normalize the normal they are given, and distance is only a true distance when the normal is unit length, so call normalize afterwards if it is not. intersectsRay and intersectsLine return whether a hit occurred and write the hit point into an optional vector. The ray's direction must be normalized.

Example

// Find where a ray from the camera meets the ground plane at y = 0
const ground = new Plane(Vec3.UP, 0);
const hit = new Vec3();
if (ground.intersectsRay(ray, hit)) {
    marker.setPosition(hit);
}

Constructors

constructor

new Plane(normal?: Vec3, distance?: number)

Create a new Plane instance.

Parameters

Properties

distance

distance: number

The distance from the plane to the origin, along its normal.

normal

normal: Vec3

The normal of the plane.

Methods

clone

clone(): Plane

Returns a clone of the specified plane.

Returns Plane: A duplicate plane.

copy

copy(src: Plane): Plane

Copies the contents of a source plane to a destination plane.

Parameters

Returns Plane: Self for chaining.

intersectsLine

intersectsLine(start: Vec3, end: Vec3, point?: Vec3): boolean

Test if the plane intersects between two points.

Parameters

Returns boolean: True if there is an intersection.

intersectsRay

intersectsRay(ray: Ray, point?: Vec3): boolean

Test if a ray intersects with the infinite plane.

Parameters

Returns boolean: True if there is an intersection.

normalize

normalize(): Plane

Normalize the plane.

Returns Plane: Self for chaining.

set

set(nx: number, ny: number, nz: number, d: number): Plane

Sets the plane based on a normal and a distance from the origin.

Parameters

Returns Plane: Self for chaining.

setFromPointNormal

setFromPointNormal(point: Vec3, normal: Vec3): Plane

Sets the plane based on a specified normal and a point on the plane.

Parameters

Returns Plane: Self for chaining.

Quat

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/quat.js#L36

A quaternion representing rotation in 3D space. Quaternions are typically used to represent rotations in 3D applications, offering advantages over Euler angles including no gimbal lock and more efficient interpolation.

A new Quat is the identity rotation. Build a rotation with setFromEulerAngles, setFromAxisAngle, setFromDirections or setFromMat4, and read one back with getEulerAngles or getAxisAngle. Angles are in degrees throughout. Rotations combine by multiplication: a.mul(b) and r.mul2(a, b) both compute a * b, the same product Mat4 uses, and transformVector applies a rotation to a Vec3. Interpolate with slerp for constant angular speed, or with the cheaper lerp when the two rotations are close together.

Methods modify the quaternion they are called on and return it for chaining. Use clone for an independent copy and copy to overwrite. The static constants IDENTITY and ZERO are frozen shared instances, and the quaternion returned by GraphNode#getRotation is internal storage to be treated as read-only.

Example

// Rotate an entity 90 degrees about the world Y axis
const rotation = new Quat().setFromAxisAngle(Vec3.UP, 90);
entity.setRotation(rotation);

Example

// Turn smoothly towards a target orientation each frame
const smoothed = new Quat().slerp(entity.getRotation(), targetRotation, 0.1);
entity.setRotation(smoothed);

Constructors

constructor

new Quat(x?: number, y?: number, z?: number, w?: number)

Creates a new Quat instance.

Parameters

Example

const q1 = new Quat(); // defaults to 0, 0, 0, 1
const q2 = new Quat(1, 2, 3, 4);
new Quat(arr: number[])

Creates a new Quat instance.

Parameters

Example

const q = new Quat([1, 2, 3, 4]);

Properties

w

w: number

The w component of the quaternion.

x

x: number

The x component of the quaternion.

y

y: number

The y component of the quaternion.

z

z: number

The z component of the quaternion.

IDENTITY

static readonly IDENTITY: Quat

A constant quaternion set to [0, 0, 0, 1] (the identity). Represents no rotation.

ZERO

static readonly ZERO: Quat

A constant quaternion set to [0, 0, 0, 0].

Methods

clone

clone(): Quat

Returns an identical copy of the specified quaternion.

Returns Quat: A new quaternion identical to this one.

Example

const q = new Quat(-0.11, -0.15, -0.46, 0.87);
const qclone = q.clone();

console.log("The result of the cloning is: " + qclone.toString());

copy

copy(rhs: Quat): Quat

Copies the contents of a source quaternion to a destination quaternion.

Parameters

Returns Quat: Self for chaining.

Example

const src = new Quat();
const dst = new Quat();
dst.copy(src);
console.log("The two quaternions are " + (src.equals(dst) ? "equal" : "different"));

dot

dot(other: Quat): number

Calculates the dot product of two quaternions.

Parameters

Returns number: The dot product of the two quaternions.

Example

const a = new Quat(1, 0, 0, 0);
const b = new Quat(0, 1, 0, 0);
console.log("Dot product: " + a.dot(b)); // Outputs 0

equals

equals(rhs: Quat): boolean

Reports whether two quaternions are equal.

Parameters

Returns boolean: True if the quaternions are equal and false otherwise.

Example

const a = new Quat();
const b = new Quat();
console.log("The two quaternions are " + (a.equals(b) ? "equal" : "different"));

equalsApprox

equalsApprox(rhs: Quat, epsilon?: number): boolean

Reports whether two quaternions are equal using an absolute error tolerance.

Parameters

Returns boolean: True if the quaternions are equal and false otherwise.

Example

const a = new Quat();
const b = new Quat();
console.log("The two quaternions are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));

fromArray

fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Quat

Set the values of the quaternion from an array.

Parameters

Returns Quat: Self for chaining.

Example

const q = new Quat();
q.fromArray([20, 10, 5, 0]);
// q is set to [20, 10, 5, 0]

getAxisAngle

getAxisAngle(axis: Vec3): number

Gets the rotation axis and angle for a given quaternion. If a quaternion is created with setFromAxisAngle, this method will return the same values as provided in the original parameter list OR functionally equivalent values.

Parameters

Returns number: Angle, in degrees, of the rotation.

Example

const q = new Quat();
q.setFromAxisAngle(new Vec3(0, 1, 0), 90);
const v = new Vec3();
const angle = q.getAxisAngle(v);
// Outputs 90
console.log(angle);
// Outputs [0, 1, 0]
console.log(v.toString());

getEulerAngles

getEulerAngles(eulers?: Vec3): Vec3

Converts this quaternion to Euler angles, specified in degrees. The decomposition uses an intrinsic XYZ order, representing the angles required to achieve the quaternion's orientation by rotating sequentially: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis.

Parameters

Returns Vec3: The 3-dimensional vector holding the Euler angles in degrees. This will be the same object passed in as the eulers parameter (if one was provided).

Example

const q = new Quat();
q.setFromAxisAngle(Vec3.UP, 90);
const e = new Vec3();
q.getEulerAngles(e);
// Outputs [0, 90, 0]
console.log(e.toString());

invert

invert(src?: Quat): Quat

Generates the inverse of the specified quaternion.

Parameters

Returns Quat: Self for chaining.

Example

// Create a quaternion rotated 180 degrees around the y-axis
const rot = new Quat().setFromEulerAngles(0, 180, 0);

// Invert in place
rot.invert();

length

length(): number

Returns the magnitude of the specified quaternion.

Returns number: The magnitude of the specified quaternion.

Example

const q = new Quat(0, 0, 0, 5);
const len = q.length();
// Outputs 5
console.log("The length of the quaternion is: " + len);

lengthSq

lengthSq(): number

Returns the magnitude squared of the specified quaternion.

Returns number: The magnitude squared of the quaternion.

Example

const q = new Quat(3, 4, 0, 0);
const lenSq = q.lengthSq();
// Outputs 25
console.log("The length squared of the quaternion is: " + lenSq);

lerp

lerp(lhs: Quat, rhs: Quat, alpha: number): Quat

Performs a linear interpolation between two quaternions. The result of the interpolation is written to the quaternion calling the function.

Parameters

Returns Quat: Self for chaining.

Example

const q1 = new Quat(-0.11, -0.15, -0.46, 0.87);
const q2 = new Quat(-0.21, -0.21, -0.67, 0.68);

const result = new Quat();
result.lerp(q1, q2, 0);   // Return q1
result.lerp(q1, q2, 0.5); // Return the midpoint interpolant
result.lerp(q1, q2, 1);   // Return q2

mul

mul(rhs: Quat): Quat

Returns the result of multiplying the specified quaternions together.

Parameters

Returns Quat: Self for chaining.

Example

const a = new Quat().setFromEulerAngles(0, 30, 0);
const b = new Quat().setFromEulerAngles(0, 60, 0);

// a becomes a 90 degree rotation around the Y axis
// In other words, a = a * b
a.mul(b);

console.log("The result of the multiplication is: " + a.toString());

mul2

mul2(lhs: Quat, rhs: Quat): Quat

Returns the result of multiplying the specified quaternions together.

Parameters

Returns Quat: Self for chaining.

Example

const a = new Quat().setFromEulerAngles(0, 30, 0);
const b = new Quat().setFromEulerAngles(0, 60, 0);
const r = new Quat();

// r is set to a 90 degree rotation around the Y axis
// In other words, r = a * b
r.mul2(a, b);

mulScalar

mulScalar(scalar: number, src?: Quat): Quat

Multiplies each element of a quaternion by a number.

Parameters

Returns Quat: Self for chaining.

Example

const q = new Quat(1, 2, 3, 4);
q.mulScalar(2);
// q is now [2, 4, 6, 8]

normalize

normalize(src?: Quat): Quat

Normalizes the specified quaternion.

Parameters

Returns Quat: Self for chaining.

Example

const v = new Quat(0, 0, 0, 5);
v.normalize();
// Outputs [0, 0, 0, 1]
console.log(v.toString());

set

set(x: number, y: number, z: number, w: number): Quat

Sets the specified quaternion to the supplied numerical values.

Parameters

Returns Quat: Self for chaining.

Example

const q = new Quat();
q.set(1, 0, 0, 0);

// Outputs 1, 0, 0, 0
console.log("The result of the quaternion set is: " + q.toString());

setFromAxisAngle

setFromAxisAngle(axis: Vec3, angle: number): Quat

Sets a quaternion from an angular rotation around an axis.

Parameters

Returns Quat: Self for chaining.

Example

const q = new Quat();
q.setFromAxisAngle(Vec3.UP, 90);

setFromDirections

setFromDirections(from: Vec3, to: Vec3): Quat

Set the quaternion that represents the shortest rotation from one direction to another.

Parameters

Returns Quat: Self for chaining.

Example

const q = new Quat();
const from = new Vec3(0, 0, 1);
const to = new Vec3(0, 1, 0);
q.setFromDirections(from, to);

setFromEulerAngles

setFromEulerAngles(ex: number | Vec3, ey?: number, ez?: number): Quat

Sets this quaternion to represent a rotation specified by Euler angles in degrees. The rotation is applied using an intrinsic XYZ order: first around the X-axis, then around the newly transformed Y-axis, and finally around the resulting Z-axis.

Parameters

Returns Quat: The quaternion itself (this), now representing the orientation from the specified XYZ Euler angles. Allows for method chaining.

Example

// Create a quaternion from 3 individual Euler angles (interpreted as X, Y, Z order)
const q1 = new Quat();
q1.setFromEulerAngles(45, 90, 180); // 45 deg around X, then 90 deg around Y', then 180 deg around Z''
console.log("From numbers:", q1.toString());

Example

// Create the same quaternion from a Vec3 containing the angles (X, Y, Z)
const anglesVec = new Vec3(45, 90, 180);
const q2 = new Quat();
q2.setFromEulerAngles(anglesVec);
console.log("From Vec3:", q2.toString()); // Should match q1

setFromMat4

setFromMat4(m: Mat4): Quat

Converts the specified 4x4 matrix to a quaternion. Note that since a quaternion is purely a representation for orientation, only the rotational part of the matrix is used.

Parameters

Returns Quat: Self for chaining.

Example

// Create a 4x4 rotation matrix of 180 degrees around the y-axis
const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180);

// Convert to a quaternion
const q = new Quat().setFromMat4(rot);

slerp

slerp(lhs: Quat, rhs: Quat, alpha: number): Quat

Performs a spherical interpolation between two quaternions. The result of the interpolation is written to the quaternion calling the function.

Parameters

Returns Quat: Self for chaining.

Example

const q1 = new Quat(-0.11, -0.15, -0.46, 0.87);
const q2 = new Quat(-0.21, -0.21, -0.67, 0.68);

const result = new Quat();
result.slerp(q1, q2, 0);   // Return q1
result.slerp(q1, q2, 0.5); // Return the midpoint interpolant
result.slerp(q1, q2, 1);   // Return q2

toArray

toArray(arr?: number[], offset?: number): number[]

Parameters

Returns number[]: The quaternion as an array.

toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView

Parameters

Returns ArrayBufferView: The quaternion as an array.

toString

toString(): string

Converts the quaternion to string form.

Returns string: The quaternion in string form.

Example

const q = new Quat(0, 0, 0, 1);
// Outputs [0, 0, 0, 1]
console.log(q.toString());

transformVector

transformVector(vec: Vec3, res?: Vec3): Vec3

Transforms a 3-dimensional vector by the specified quaternion.

Parameters

Returns Vec3: The transformed vector (res if specified, otherwise a new Vec3).

Example

// Create a 3-dimensional vector
const v = new Vec3(1, 2, 3);

// Create a quaternion rotation
const q = new Quat().setFromEulerAngles(10, 20, 30);

const tv = q.transformVector(v);

Ray

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/ray.js#L20

An infinite ray. Rays are commonly used for picking, raycasting and intersection tests.

A ray is an origin and a direction. It performs no intersection itself: pass it to the intersectsRay method of a BoundingBox, BoundingSphere, OrientedBox, Plane or Tri. Keep the direction normalized, as those tests require it. The constructor copies the vectors it is given, and set updates both in place.

Example

// A ray from the camera through a screen position
const ray = new Ray();
entity.camera.screenToWorld(x, y, entity.camera.nearClip, ray.origin);
entity.camera.screenToWorld(x, y, entity.camera.farClip, ray.direction);
ray.direction.sub(ray.origin).normalize();

Constructors

constructor

new Ray(origin?: Vec3, direction?: Vec3)

Creates a new Ray instance. The ray is infinite, starting at a given origin and pointing in a given direction.

Parameters

Example

// Create a new ray starting at the position of this entity and pointing down
// the entity's negative Z axis
const ray = new Ray(this.entity.getPosition(), this.entity.forward);

Properties

direction

readonly direction: Vec3

The direction of the ray.

origin

readonly origin: Vec3

The starting point of the ray.

Methods

clone

clone(): Ray

Returns a clone of the Ray.

Returns Ray: A duplicate Ray.

copy

copy(src: Ray): Ray

Copies the contents of a source Ray.

Parameters

Returns Ray: Self for chaining.

set

set(origin: Vec3, direction: Vec3): Ray

Sets origin and direction to the supplied vector values.

Parameters

Returns Ray: Self for chaining.

Tri

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/shape/tri.js#L32

A triangle defined by three Vec3 vectors.

The vertices are v0, v1 and v2; the constructor and set copy the vectors they are given. intersectsRay tests a Ray whose direction is normalized against either face of the triangle and writes the hit point into an optional vector. It is the building block for precise picking against mesh geometry.

Example

const tri = new Tri(new Vec3(0, 0, 0), new Vec3(1, 0, 0), new Vec3(0, 1, 0));
const hit = new Vec3();
if (tri.intersectsRay(ray, hit)) {
    console.log(`Hit the triangle at ${hit}`);
}

Constructors

constructor

new Tri(v0?: Vec3, v1?: Vec3, v2?: Vec3)

Creates a new Tri object.

Parameters

Example

const v0 = new Vec3(1, 0, 0);
const v1 = new Vec3(0, 1, 0);
const v2 = new Vec3(2, 2, 1);
const t = new Tri(v0, v1, v2);

Properties

v0

readonly v0: Vec3

The first 3-dimensional vector of the triangle.

v1

readonly v1: Vec3

The second 3-dimensional vector of the triangle.

v2

readonly v2: Vec3

The third 3-dimensional vector of the triangle.

Methods

intersectsRay

intersectsRay(ray: Ray, point?: Vec3): boolean

Test if a ray intersects with the triangle.

Parameters

Returns boolean: True if there is an intersection.

set

set(v0: Vec3, v1: Vec3, v2: Vec3): Tri

Sets the specified triangle to the supplied 3-dimensional vectors.

Parameters

Returns Tri: Self for chaining.

Example

const t = new Tri(Vec3.UP, Vec3.RIGHT, Vec3.BACK);
const v0 = new Vec3(1, 0, 0);
const v1 = new Vec3(0, 1, 0);
const v2 = new Vec3(2, 2, 1);
t.set(v0, v1, v2);

// Outputs [[1, 0, 0], [0, 1, 0], [2, 2, 1]]
console.log("The result of the triangle set is: " + t.toString());

toString

toString(): string

Converts the specified triangle to string form.

Returns string: The triangle in string form.

Example

const t = new Tri(Vec3.UP, Vec3.RIGHT, Vec3.BACK);
// Outputs [[0, 1, 0], [1, 0, 0], [0, 0, 1]]
console.log(t.toString());

Vec2

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec2.js#L29

A 2-dimensional vector. Vec2 is commonly used to represent 2D positions, directions, texture coordinates (UVs) or any pair of related numeric values.

Operations follow one convention throughout the math classes: a method that modifies the vector it is called on returns it, so calls can be chained and nothing is allocated, while queries such as distance and dot return a number. Two-operand forms such as add2 and sub2 write the result of lhs op rhs into this, and it is safe for this to also be one of the operands. Use clone for an independent copy and copy to overwrite one vector with another.

The static constants such as ZERO and UP are frozen shared instances: read them freely, but writing to one throws. Copy a constant before modifying it.

Example

// Scroll a texture offset each frame without allocating
const offset = new Vec2(0, 0);
const speed = new Vec2(0.1, 0);
offset.addScaled(speed, dt);

Example

// Chain mutating operations; each returns the vector it was called on
const toTarget = new Vec2().sub2(target, position).normalize();
const distance = target.distance(position);

Constructors

constructor

new Vec2(x?: number, y?: number)

Creates a new Vec2 instance.

Parameters

Example

const v1 = new Vec2(); // defaults to 0, 0
const v2 = new Vec2(1, 2);
new Vec2(arr: number[])

Creates a new Vec2 instance.

Parameters

Example

const v = new Vec2([1, 2]);

Properties

x

x: number

The first component of the vector.

y

y: number

The second component of the vector.

DOWN

static readonly DOWN: Vec2

A constant vector set to [0, -1].

HALF

static readonly HALF: Vec2

A constant vector set to [0.5, 0.5].

LEFT

static readonly LEFT: Vec2

A constant vector set to [-1, 0].

ONE

static readonly ONE: Vec2

A constant vector set to [1, 1].

RIGHT

static readonly RIGHT: Vec2

A constant vector set to [1, 0].

UP

static readonly UP: Vec2

A constant vector set to [0, 1].

ZERO

static readonly ZERO: Vec2

A constant vector set to [0, 0].

Methods

add

add(rhs: Vec2): Vec2

Adds a 2-dimensional vector to another in place.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(10, 10);
const b = new Vec2(20, 20);

a.add(b);

// Outputs [30, 30]
console.log("The result of the addition is: " + a.toString());

add2

add2(lhs: Vec2, rhs: Vec2): Vec2

Adds two 2-dimensional vectors together and returns the result.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
const r = new Vec2();

r.add2(a, b);
// Outputs [30, 30]

console.log("The result of the addition is: " + r.toString());

addScalar

addScalar(scalar: number): Vec2

Adds a number to each element of a vector.

Parameters

Returns Vec2: Self for chaining.

Example

const vec = new Vec2(3, 4);

vec.addScalar(2);

// Outputs [5, 6]
console.log("The result of the addition is: " + vec.toString());

addScaled

addScaled(rhs: Vec2, scalar: number): Vec2

Adds a 2-dimensional vector scaled by scalar value. Does not modify the vector being added.

Parameters

Returns Vec2: Self for chaining.

Example

const vec = new Vec2(1, 2);

vec.addScaled(Vec2.UP, 2);

// Outputs [1, 4]
console.log("The result of the addition is: " + vec.toString());

angle

angle(): number

Returns the angle in degrees of the specified 2-dimensional vector.

Returns number: The angle in degrees of the specified 2-dimensional vector.

Example

const v = new Vec2(6, 0);
const angle = v.angle();
// Outputs 90..
console.log("The angle of the vector is: " + angle);

angleTo

angleTo(rhs: Vec2): number

Returns the shortest Euler angle between two 2-dimensional vectors.

Parameters

Returns number: The shortest angle in degrees between two 2-dimensional vectors.

Example

const a = new Vec2(0, 10); // up
const b = new Vec2(1, -1); // down-right
const angle = a.angleTo(b);
// Outputs 135..
console.log("The angle between vectors a and b: " + angle);

ceil

ceil(src?: Vec2): Vec2

Each element is rounded up to the next largest integer.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2(1.2, 3.1);
v.ceil();
// v is now [2, 4]

clone

clone(): Vec2

Returns an identical copy of the specified 2-dimensional vector.

Returns Vec2: A 2-dimensional vector containing the result of the cloning.

Example

const v = new Vec2(10, 20);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());

copy

copy(rhs: Vec2): Vec2

Copies the contents of a source 2-dimensional vector to a destination 2-dimensional vector.

Parameters

Returns Vec2: Self for chaining.

Example

const src = new Vec2(10, 20);
const dst = new Vec2();

dst.copy(src);

console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));

cross

cross(rhs: Vec2): number

Returns the result of a cross product operation performed on the two specified 2-dimensional vectors.

Parameters

Returns number: The cross product of the two vectors.

Example

const right = new Vec2(1, 0);
const up = new Vec2(0, 1);
const crossProduct = right.cross(up);

// Prints 1
console.log("The result of the cross product is: " + crossProduct);

distance

distance(rhs: Vec2): number

Returns the distance between the two specified 2-dimensional vectors.

Parameters

Returns number: The distance between the two vectors.

Example

const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const d = v1.distance(v2);
console.log("The distance between v1 and v2 is: " + d);

distanceSq

distanceSq(rhs: Vec2): number

Returns the squared distance between the two specified 2-dimensional vectors.

Parameters

Returns number: The squared distance between the two vectors.

Example

const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const d = v1.distanceSq(v2);
console.log("The squared distance between v1 and v2 is: " + d);

div

div(rhs: Vec2): Vec2

Divides a 2-dimensional vector by another in place.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(4, 9);
const b = new Vec2(2, 3);

a.div(b);

// Outputs [2, 3]
console.log("The result of the division is: " + a.toString());

div2

div2(lhs: Vec2, rhs: Vec2): Vec2

Divides one 2-dimensional vector by another and writes the result to the specified vector.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(4, 9);
const b = new Vec2(2, 3);
const r = new Vec2();

r.div2(a, b);

// Outputs [2, 3]
console.log("The result of the division is: " + r.toString());

divScalar

divScalar(scalar: number): Vec2

Divides each element of a vector by a number.

Parameters

Returns Vec2: Self for chaining.

Example

const vec = new Vec2(3, 6);

vec.divScalar(3);

// Outputs [1, 2]
console.log("The result of the division is: " + vec.toString());

dot

dot(rhs: Vec2): number

Returns the result of a dot product operation performed on the two specified 2-dimensional vectors.

Parameters

Returns number: The result of the dot product operation.

Example

const v1 = new Vec2(5, 10);
const v2 = new Vec2(10, 20);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);

equals

equals(rhs: Vec2): boolean

Reports whether two vectors are equal.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec2(1, 2);
const b = new Vec2(4, 5);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));

equalsApprox

equalsApprox(rhs: Vec2, epsilon?: number): boolean

Reports whether two vectors are equal using an absolute error tolerance.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec2();
const b = new Vec2();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));

floor

floor(src?: Vec2): Vec2

Each element is set to the largest integer less than or equal to its value.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2(1.2, 3.9);
v.floor();
// v is now [1, 3]

fromArray

fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec2

Set the values of the vector from an array.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2();
v.fromArray([20, 10]);
// v is set to [20, 10]

length

length(): number

Returns the magnitude of the specified 2-dimensional vector.

Returns number: The magnitude of the specified 2-dimensional vector.

Example

const vec = new Vec2(3, 4);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);

lengthSq

lengthSq(): number

Returns the magnitude squared of the specified 2-dimensional vector.

Returns number: The magnitude squared of the specified 2-dimensional vector.

Example

const vec = new Vec2(3, 4);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);

lerp

lerp(lhs: Vec2, rhs: Vec2, alpha: number): Vec2

Returns the result of a linear interpolation between two specified 2-dimensional vectors.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(0, 0);
const b = new Vec2(10, 10);
const r = new Vec2();

r.lerp(a, b, 0);   // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5
r.lerp(a, b, 1);   // r is equal to b

max

max(rhs: Vec2): Vec2

Each element is assigned a value from rhs parameter if it is larger.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(5, 1);
const b = new Vec2(2, 8);
a.max(b);
// a is now [5, 8]

min

min(rhs: Vec2): Vec2

Each element is assigned a value from rhs parameter if it is smaller.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(5, 1);
const b = new Vec2(2, 8);
a.min(b);
// a is now [2, 1]

mul

mul(rhs: Vec2): Vec2

Multiplies a 2-dimensional vector to another in place.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(2, 3);
const b = new Vec2(4, 5);

a.mul(b);

// Outputs 8, 15
console.log("The result of the multiplication is: " + a.toString());

mul2

mul2(lhs: Vec2, rhs: Vec2): Vec2

Returns the result of multiplying the specified 2-dimensional vectors together.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(2, 3);
const b = new Vec2(4, 5);
const r = new Vec2();

r.mul2(a, b);

// Outputs 8, 15
console.log("The result of the multiplication is: " + r.toString());

mulScalar

mulScalar(scalar: number): Vec2

Multiplies each element of a vector by a number.

Parameters

Returns Vec2: Self for chaining.

Example

const vec = new Vec2(3, 6);

vec.mulScalar(3);

// Outputs [9, 18]
console.log("The result of the multiplication is: " + vec.toString());

normalize

normalize(src?: Vec2): Vec2

Returns this 2-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2(25, 0);

v.normalize();

// Outputs 1, 0
console.log("The result of the vector normalization is: " + v.toString());

rotate

rotate(degrees: number): Vec2

Rotate a vector by an angle in degrees.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2(0, 10);

v.rotate(45); // rotates by 45 degrees

// Outputs [7.071068.., 7.071068..]
console.log("Vector after rotation is: " + v.toString());

round

round(src?: Vec2): Vec2

Each element is rounded up or down to the nearest integer.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2(1.4, 3.6);
v.round();
// v is now [1, 4]

set

set(x: number, y: number): Vec2

Sets the specified 2-dimensional vector to the supplied numerical values.

Parameters

Returns Vec2: Self for chaining.

Example

const v = new Vec2();
v.set(5, 10);

// Outputs 5, 10
console.log("The result of the vector set is: " + v.toString());

sub

sub(rhs: Vec2): Vec2

Subtracts a 2-dimensional vector from another in place.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(10, 10);
const b = new Vec2(20, 20);

a.sub(b);

// Outputs [-10, -10]
console.log("The result of the subtraction is: " + a.toString());

sub2

sub2(lhs: Vec2, rhs: Vec2): Vec2

Subtracts two 2-dimensional vectors from one another and returns the result.

Parameters

Returns Vec2: Self for chaining.

Example

const a = new Vec2(10, 10);
const b = new Vec2(20, 20);
const r = new Vec2();

r.sub2(a, b);

// Outputs [-10, -10]
console.log("The result of the subtraction is: " + r.toString());

subScalar

subScalar(scalar: number): Vec2

Subtracts a number from each element of a vector.

Parameters

Returns Vec2: Self for chaining.

Example

const vec = new Vec2(3, 4);

vec.subScalar(2);

// Outputs [1, 2]
console.log("The result of the subtraction is: " + vec.toString());

toArray

toArray(arr?: number[], offset?: number): number[]

Parameters

Returns number[]: The vector as an array.

toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView

Parameters

Returns ArrayBufferView: The vector as an array.

toString

toString(): string

Converts the vector to string form.

Returns string: The vector in string form.

Example

const v = new Vec2(20, 10);
// Outputs [20, 10]
console.log(v.toString());

Vec3

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec3.js#L34

A 3-dimensional vector. Vec3 is commonly used to represent 3D positions, directions, Euler angles or scales.

Operations follow one convention throughout the math classes: a method that modifies the vector it is called on returns it, so calls can be chained and nothing is allocated, while queries such as distance and dot return a number. Two-operand forms such as add2, sub2 and cross write the result of lhs op rhs into this, and it is safe for this to also be one of the operands. Use clone for an independent copy and copy to overwrite one vector with another.

The static constants such as ZERO, UP and FORWARD are frozen shared instances: read them freely, but writing to one throws. Vectors returned by engine getters such as GraphNode#getPosition are internal storage and should be treated as read-only; clone them if you need to keep or modify the value.

Example

// Move a point 5 units along a direction without allocating
const position = new Vec3(1, 2, 3);
const direction = new Vec3(0, 0, -1);
position.addScaled(direction, 5);   // position is now [1, 2, -2]

Example

// Chain mutating operations; each returns the vector it was called on
const toTarget = new Vec3().sub2(target, origin).normalize();
const distance = target.distance(origin);

Example

// Keep a copy of an entity's position, then modify it safely
const start = entity.getPosition().clone();
start.y += 1;

Constructors

constructor

new Vec3(x?: number, y?: number, z?: number)

Creates a new Vec3 instance.

Parameters

Example

const v1 = new Vec3(); // defaults to 0, 0, 0
const v2 = new Vec3(1, 2, 3);
new Vec3(arr: number[])

Creates a new Vec3 instance.

Parameters

Example

const v = new Vec3([1, 2, 3]);

Properties

x

x: number

The first component of the vector.

y

y: number

The second component of the vector.

z

z: number

The third component of the vector.

BACK

static readonly BACK: Vec3

A constant vector set to [0, 0, 1].

DOWN

static readonly DOWN: Vec3

A constant vector set to [0, -1, 0].

FORWARD

static readonly FORWARD: Vec3

A constant vector set to [0, 0, -1].

HALF

static readonly HALF: Vec3

A constant vector set to [0.5, 0.5, 0.5].

LEFT

static readonly LEFT: Vec3

A constant vector set to [-1, 0, 0].

ONE

static readonly ONE: Vec3

A constant vector set to [1, 1, 1].

RIGHT

static readonly RIGHT: Vec3

A constant vector set to [1, 0, 0].

UP

static readonly UP: Vec3

A constant vector set to [0, 1, 0].

ZERO

static readonly ZERO: Vec3

A constant vector set to [0, 0, 0].

Methods

add

add(rhs: Vec3): Vec3

Adds a 3-dimensional vector to another in place.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);

a.add(b);

// Outputs [30, 30, 30]
console.log("The result of the addition is: " + a.toString());

add2

add2(lhs: Vec3, rhs: Vec3): Vec3

Adds two 3-dimensional vectors together and returns the result.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
const r = new Vec3();

r.add2(a, b);
// Outputs [30, 30, 30]

console.log("The result of the addition is: " + r.toString());

addScalar

addScalar(scalar: number): Vec3

Adds a number to each element of a vector.

Parameters

Returns Vec3: Self for chaining.

Example

const vec = new Vec3(3, 4, 5);

vec.addScalar(2);

// Outputs [5, 6, 7]
console.log("The result of the addition is: " + vec.toString());

addScaled

addScaled(rhs: Vec3, scalar: number): Vec3

Adds a 3-dimensional vector scaled by scalar value. Does not modify the vector being added.

Parameters

Returns Vec3: Self for chaining.

Example

const vec = new Vec3(1, 2, 3);

vec.addScaled(Vec3.UP, 2);

// Outputs [1, 4, 3]
console.log("The result of the addition is: " + vec.toString());

ceil

ceil(src?: Vec3): Vec3

Each element is rounded up to the next largest integer.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3(1.2, 3.1, 5.9);
v.ceil();
// v is now [2, 4, 6]

clone

clone(): Vec3

Returns an identical copy of the specified 3-dimensional vector.

Returns Vec3: A 3-dimensional vector containing the result of the cloning.

Example

const v = new Vec3(10, 20, 30);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());

copy

copy(rhs: Vec3): Vec3

Copies the contents of a source 3-dimensional vector to a destination 3-dimensional vector.

Parameters

Returns Vec3: Self for chaining.

Example

const src = new Vec3(10, 20, 30);
const dst = new Vec3();

dst.copy(src);

console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));

cross

cross(lhs: Vec3, rhs: Vec3): Vec3

Returns the result of a cross product operation performed on the two specified 3-dimensional vectors.

Parameters

Returns Vec3: Self for chaining.

Example

const back = new Vec3().cross(Vec3.RIGHT, Vec3.UP);

// Prints the Z axis (i.e. [0, 0, 1])
console.log("The result of the cross product is: " + back.toString());

distance

distance(rhs: Vec3): number

Returns the distance between the two specified 3-dimensional vectors.

Parameters

Returns number: The distance between the two vectors.

Example

const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const d = v1.distance(v2);
console.log("The distance between v1 and v2 is: " + d);

distanceSq

distanceSq(rhs: Vec3): number

Returns the squared distance between the two specified 3-dimensional vectors.

Parameters

Returns number: The squared distance between the two vectors.

Example

const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const d = v1.distanceSq(v2);
console.log("The squared distance between v1 and v2 is: " + d);

div

div(rhs: Vec3): Vec3

Divides a 3-dimensional vector by another in place.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(4, 9, 16);
const b = new Vec3(2, 3, 4);

a.div(b);

// Outputs [2, 3, 4]
console.log("The result of the division is: " + a.toString());

div2

div2(lhs: Vec3, rhs: Vec3): Vec3

Divides one 3-dimensional vector by another and writes the result to the specified vector.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(4, 9, 16);
const b = new Vec3(2, 3, 4);
const r = new Vec3();

r.div2(a, b);

// Outputs [2, 3, 4]
console.log("The result of the division is: " + r.toString());

divScalar

divScalar(scalar: number): Vec3

Divides each element of a vector by a number.

Parameters

Returns Vec3: Self for chaining.

Example

const vec = new Vec3(3, 6, 9);

vec.divScalar(3);

// Outputs [1, 2, 3]
console.log("The result of the division is: " + vec.toString());

dot

dot(rhs: Vec3): number

Returns the result of a dot product operation performed on the two specified 3-dimensional vectors.

Parameters

Returns number: The result of the dot product operation.

Example

const v1 = new Vec3(5, 10, 20);
const v2 = new Vec3(10, 20, 40);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);

equals

equals(rhs: Vec3): boolean

Reports whether two vectors are equal.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec3(1, 2, 3);
const b = new Vec3(4, 5, 6);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));

equalsApprox

equalsApprox(rhs: Vec3, epsilon?: number): boolean

Reports whether two vectors are equal using an absolute error tolerance.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec3();
const b = new Vec3();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));

floor

floor(src?: Vec3): Vec3

Each element is set to the largest integer less than or equal to its value.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3(1.2, 3.9, 5.5);
v.floor();
// v is now [1, 3, 5]

fromArray

fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec3

Set the values of the vector from an array.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3();
v.fromArray([20, 10, 5]);
// v is set to [20, 10, 5]

length

length(): number

Returns the magnitude of the specified 3-dimensional vector.

Returns number: The magnitude of the specified 3-dimensional vector.

Example

const vec = new Vec3(3, 4, 0);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);

lengthSq

lengthSq(): number

Returns the magnitude squared of the specified 3-dimensional vector.

Returns number: The magnitude squared of the specified 3-dimensional vector.

Example

const vec = new Vec3(3, 4, 0);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);

lerp

lerp(lhs: Vec3, rhs: Vec3, alpha: number): Vec3

Returns the result of a linear interpolation between two specified 3-dimensional vectors.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(0, 0, 0);
const b = new Vec3(10, 10, 10);
const r = new Vec3();

r.lerp(a, b, 0);   // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5, 5
r.lerp(a, b, 1);   // r is equal to b

max

max(rhs: Vec3): Vec3

Each element is assigned a value from rhs parameter if it is larger.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(5, 1, 7);
const b = new Vec3(2, 8, 3);
a.max(b);
// a is now [5, 8, 7]

min

min(rhs: Vec3): Vec3

Each element is assigned a value from rhs parameter if it is smaller.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(5, 1, 7);
const b = new Vec3(2, 8, 3);
a.min(b);
// a is now [2, 1, 3]

mul

mul(rhs: Vec3): Vec3

Multiplies a 3-dimensional vector to another in place.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(2, 3, 4);
const b = new Vec3(4, 5, 6);

a.mul(b);

// Outputs [8, 15, 24]
console.log("The result of the multiplication is: " + a.toString());

mul2

mul2(lhs: Vec3, rhs: Vec3): Vec3

Returns the result of multiplying the specified 3-dimensional vectors together.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(2, 3, 4);
const b = new Vec3(4, 5, 6);
const r = new Vec3();

r.mul2(a, b);

// Outputs [8, 15, 24]
console.log("The result of the multiplication is: " + r.toString());

mulScalar

mulScalar(scalar: number): Vec3

Multiplies each element of a vector by a number.

Parameters

Returns Vec3: Self for chaining.

Example

const vec = new Vec3(3, 6, 9);

vec.mulScalar(3);

// Outputs [9, 18, 27]
console.log("The result of the multiplication is: " + vec.toString());

normalize

normalize(src?: Vec3): Vec3

Returns this 3-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3(25, 0, 0);

v.normalize();

// Outputs [1, 0, 0]
console.log("The result of the vector normalization is: " + v.toString());

project

project(rhs: Vec3): Vec3

Projects this 3-dimensional vector onto the specified vector.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3(5, 5, 5);
const normal = new Vec3(1, 0, 0);

v.project(normal);

// Outputs [5, 0, 0]
console.log("The result of the vector projection is: " + v.toString());

round

round(src?: Vec3): Vec3

Each element is rounded up or down to the nearest integer.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3(1.4, 3.6, 5.5);
v.round();
// v is now [1, 4, 6]

set

set(x: number, y: number, z: number): Vec3

Sets the specified 3-dimensional vector to the supplied numerical values.

Parameters

Returns Vec3: Self for chaining.

Example

const v = new Vec3();
v.set(5, 10, 20);

// Outputs [5, 10, 20]
console.log("The result of the vector set is: " + v.toString());

sub

sub(rhs: Vec3): Vec3

Subtracts a 3-dimensional vector from another in place.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);

a.sub(b);

// Outputs [-10, -10, -10]
console.log("The result of the subtraction is: " + a.toString());

sub2

sub2(lhs: Vec3, rhs: Vec3): Vec3

Subtracts two 3-dimensional vectors from one another and returns the result.

Parameters

Returns Vec3: Self for chaining.

Example

const a = new Vec3(10, 10, 10);
const b = new Vec3(20, 20, 20);
const r = new Vec3();

r.sub2(a, b);

// Outputs [-10, -10, -10]
console.log("The result of the subtraction is: " + r.toString());

subScalar

subScalar(scalar: number): Vec3

Subtracts a number from each element of a vector.

Parameters

Returns Vec3: Self for chaining.

Example

const vec = new Vec3(3, 4, 5);

vec.subScalar(2);

// Outputs [1, 2, 3]
console.log("The result of the subtraction is: " + vec.toString());

toArray

toArray(arr?: number[], offset?: number): number[]

Parameters

Returns number[]: The vector as an array.

toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView

Parameters

Returns ArrayBufferView: The vector as an array.

toString

toString(): string

Converts the vector to string form.

Returns string: The vector in string form.

Example

const v = new Vec3(20, 10, 5);
// Outputs [20, 10, 5]
console.log(v.toString());

Vec4

Class · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/vec4.js#L25

A 4-dimensional vector. Vec4 is commonly used to represent homogeneous coordinates or shader uniforms requiring four components.

Operations follow one convention throughout the math classes: a method that modifies the vector it is called on returns it, so calls can be chained and nothing is allocated, while queries such as length and dot return a number. Two-operand forms such as add2 and mul2 write the result of lhs op rhs into this, and it is safe for this to also be one of the operands. Use clone for an independent copy and copy to overwrite one vector with another.

The static constants ZERO, HALF and ONE are frozen shared instances: read them freely, but writing to one throws.

Example

// Interpolate between two 4-component values into a third, without allocating
const from = new Vec4(0, 0, 0, 0);
const to = new Vec4(1, 1, 1, 1);
const result = new Vec4();
result.lerp(from, to, 0.25);   // result is now [0.25, 0.25, 0.25, 0.25]

Constructors

constructor

new Vec4(x?: number, y?: number, z?: number, w?: number)

Creates a new Vec4 instance.

Parameters

Example

const v1 = new Vec4(); // defaults to 0, 0, 0, 0
const v2 = new Vec4(1, 2, 3, 4);
new Vec4(arr: number[])

Creates a new Vec4 instance.

Parameters

Example

const v = new Vec4([1, 2, 3, 4]);

Properties

w

w: number

The fourth component of the vector.

x

x: number

The first component of the vector.

y

y: number

The second component of the vector.

z

z: number

The third component of the vector.

HALF

static readonly HALF: Vec4

A constant vector set to [0.5, 0.5, 0.5, 0.5].

ONE

static readonly ONE: Vec4

A constant vector set to [1, 1, 1, 1].

ZERO

static readonly ZERO: Vec4

A constant vector set to [0, 0, 0, 0].

Methods

add

add(rhs: Vec4): Vec4

Adds a 4-dimensional vector to another in place.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);

a.add(b);

// Outputs [30, 30, 30, 30]
console.log("The result of the addition is: " + a.toString());

add2

add2(lhs: Vec4, rhs: Vec4): Vec4

Adds two 4-dimensional vectors together and returns the result.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
const r = new Vec4();

r.add2(a, b);
// Outputs [30, 30, 30, 30]

console.log("The result of the addition is: " + r.toString());

addScalar

addScalar(scalar: number): Vec4

Adds a number to each element of a vector.

Parameters

Returns Vec4: Self for chaining.

Example

const vec = new Vec4(3, 4, 5, 6);

vec.addScalar(2);

// Outputs [5, 6, 7, 8]
console.log("The result of the addition is: " + vec.toString());

addScaled

addScaled(rhs: Vec4, scalar: number): Vec4

Adds a 4-dimensional vector scaled by scalar value. Does not modify the vector being added.

Parameters

Returns Vec4: Self for chaining.

Example

const vec = new Vec4(1, 2, 3, 4);

vec.addScaled(Vec4.ONE, 2);

// Outputs [3, 4, 5, 6]
console.log("The result of the addition is: " + vec.toString());

ceil

ceil(src?: Vec4): Vec4

Each element is rounded up to the next largest integer.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4(1.2, 3.1, 5.9, 7.4);
v.ceil();
// v is now [2, 4, 6, 8]

clone

clone(): Vec4

Returns an identical copy of the specified 4-dimensional vector.

Returns Vec4: A 4-dimensional vector containing the result of the cloning.

Example

const v = new Vec4(10, 20, 30, 40);
const vclone = v.clone();
console.log("The result of the cloning is: " + vclone.toString());

copy

copy(rhs: Vec4): Vec4

Copies the contents of a source 4-dimensional vector to a destination 4-dimensional vector.

Parameters

Returns Vec4: Self for chaining.

Example

const src = new Vec4(10, 20, 30, 40);
const dst = new Vec4();

dst.copy(src);

console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different"));

div

div(rhs: Vec4): Vec4

Divides a 4-dimensional vector by another in place.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(4, 9, 16, 25);
const b = new Vec4(2, 3, 4, 5);

a.div(b);

// Outputs [2, 3, 4, 5]
console.log("The result of the division is: " + a.toString());

div2

div2(lhs: Vec4, rhs: Vec4): Vec4

Divides one 4-dimensional vector by another and writes the result to the specified vector.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(4, 9, 16, 25);
const b = new Vec4(2, 3, 4, 5);
const r = new Vec4();

r.div2(a, b);

// Outputs [2, 3, 4, 5]
console.log("The result of the division is: " + r.toString());

divScalar

divScalar(scalar: number): Vec4

Divides each element of a vector by a number.

Parameters

Returns Vec4: Self for chaining.

Example

const vec = new Vec4(3, 6, 9, 12);

vec.divScalar(3);

// Outputs [1, 2, 3, 4]
console.log("The result of the division is: " + vec.toString());

dot

dot(rhs: Vec4): number

Returns the result of a dot product operation performed on the two specified 4-dimensional vectors.

Parameters

Returns number: The result of the dot product operation.

Example

const v1 = new Vec4(5, 10, 20, 40);
const v2 = new Vec4(10, 20, 40, 80);
const v1dotv2 = v1.dot(v2);
console.log("The result of the dot product is: " + v1dotv2);

equals

equals(rhs: Vec4): boolean

Reports whether two vectors are equal.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec4(1, 2, 3, 4);
const b = new Vec4(5, 6, 7, 8);
console.log("The two vectors are " + (a.equals(b) ? "equal" : "different"));

equalsApprox

equalsApprox(rhs: Vec4, epsilon?: number): boolean

Reports whether two vectors are equal using an absolute error tolerance.

Parameters

Returns boolean: True if the vectors are equal and false otherwise.

Example

const a = new Vec4();
const b = new Vec4();
console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different"));

floor

floor(src?: Vec4): Vec4

Each element is set to the largest integer less than or equal to its value.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4(1.2, 3.9, 5.5, 7.8);
v.floor();
// v is now [1, 3, 5, 7]

fromArray

fromArray(arr: number[] | ArrayBufferView<ArrayBufferLike>, offset?: number): Vec4

Set the values of the vector from an array.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4();
v.fromArray([20, 10, 5, 0]);
// v is set to [20, 10, 5, 0]

length

length(): number

Returns the magnitude of the specified 4-dimensional vector.

Returns number: The magnitude of the specified 4-dimensional vector.

Example

const vec = new Vec4(3, 4, 0, 0);
const len = vec.length();
// Outputs 5
console.log("The length of the vector is: " + len);

lengthSq

lengthSq(): number

Returns the magnitude squared of the specified 4-dimensional vector.

Returns number: The magnitude squared of the specified 4-dimensional vector.

Example

const vec = new Vec4(3, 4, 0, 0);
const len = vec.lengthSq();
// Outputs 25
console.log("The length squared of the vector is: " + len);

lerp

lerp(lhs: Vec4, rhs: Vec4, alpha: number): Vec4

Returns the result of a linear interpolation between two specified 4-dimensional vectors.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(0, 0, 0, 0);
const b = new Vec4(10, 10, 10, 10);
const r = new Vec4();

r.lerp(a, b, 0);   // r is equal to a
r.lerp(a, b, 0.5); // r is 5, 5, 5, 5
r.lerp(a, b, 1);   // r is equal to b

max

max(rhs: Vec4): Vec4

Each element is assigned a value from rhs parameter if it is larger.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(5, 1, 7, 3);
const b = new Vec4(2, 8, 3, 9);
a.max(b);
// a is now [5, 8, 7, 9]

min

min(rhs: Vec4): Vec4

Each element is assigned a value from rhs parameter if it is smaller.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(5, 1, 7, 3);
const b = new Vec4(2, 8, 3, 9);
a.min(b);
// a is now [2, 1, 3, 3]

mul

mul(rhs: Vec4): Vec4

Multiplies a 4-dimensional vector to another in place.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(2, 3, 4, 5);
const b = new Vec4(4, 5, 6, 7);

a.mul(b);

// Outputs 8, 15, 24, 35
console.log("The result of the multiplication is: " + a.toString());

mul2

mul2(lhs: Vec4, rhs: Vec4): Vec4

Returns the result of multiplying the specified 4-dimensional vectors together.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(2, 3, 4, 5);
const b = new Vec4(4, 5, 6, 7);
const r = new Vec4();

r.mul2(a, b);

// Outputs 8, 15, 24, 35
console.log("The result of the multiplication is: " + r.toString());

mulScalar

mulScalar(scalar: number): Vec4

Multiplies each element of a vector by a number.

Parameters

Returns Vec4: Self for chaining.

Example

const vec = new Vec4(3, 6, 9, 12);

vec.mulScalar(3);

// Outputs [9, 18, 27, 36]
console.log("The result of the multiplication is: " + vec.toString());

normalize

normalize(src?: Vec4): Vec4

Returns this 4-dimensional vector converted to a unit vector in place. If the vector has a length of zero, the vector's elements will be set to zero.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4(25, 0, 0, 0);

v.normalize();

// Outputs 1, 0, 0, 0
console.log("The result of the vector normalization is: " + v.toString());

round

round(src?: Vec4): Vec4

Each element is rounded up or down to the nearest integer.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4(1.4, 3.6, 5.5, 7.2);
v.round();
// v is now [1, 4, 6, 7]

set

set(x: number, y: number, z: number, w: number): Vec4

Sets the specified 4-dimensional vector to the supplied numerical values.

Parameters

Returns Vec4: Self for chaining.

Example

const v = new Vec4();
v.set(5, 10, 20, 40);

// Outputs 5, 10, 20, 40
console.log("The result of the vector set is: " + v.toString());

sub

sub(rhs: Vec4): Vec4

Subtracts a 4-dimensional vector from another in place.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);

a.sub(b);

// Outputs [-10, -10, -10, -10]
console.log("The result of the subtraction is: " + a.toString());

sub2

sub2(lhs: Vec4, rhs: Vec4): Vec4

Subtracts two 4-dimensional vectors from one another and returns the result.

Parameters

Returns Vec4: Self for chaining.

Example

const a = new Vec4(10, 10, 10, 10);
const b = new Vec4(20, 20, 20, 20);
const r = new Vec4();

r.sub2(a, b);

// Outputs [-10, -10, -10, -10]
console.log("The result of the subtraction is: " + r.toString());

subScalar

subScalar(scalar: number): Vec4

Subtracts a number from each element of a vector.

Parameters

Returns Vec4: Self for chaining.

Example

const vec = new Vec4(3, 4, 5, 6);

vec.subScalar(2);

// Outputs [1, 2, 3, 4]
console.log("The result of the subtraction is: " + vec.toString());

toArray

toArray(arr?: number[], offset?: number): number[]

Parameters

Returns number[]: The vector as an array.

toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView

Parameters

Returns ArrayBufferView: The vector as an array.

toString

toString(): string

Converts the vector to string form.

Returns string: The vector in string form.

Example

const v = new Vec4(20, 10, 5, 0);
// Outputs [20, 10, 5, 0]
console.log(v.toString());

math.bytesToInt24

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L89

bytesToInt24(r: number, g: number, b: number): number

Convert 3 8 bit Numbers into a single unsigned 24 bit Number.

Parameters

Returns number: A single unsigned 24 bit Number.

Example

// Set result1 to 0x112233 from an array of 3 values
const result1 = math.bytesToInt24([0x11, 0x22, 0x33]);

// Set result2 to 0x112233 from 3 discrete values
const result2 = math.bytesToInt24(0x11, 0x22, 0x33);

math.bytesToInt32

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L113

bytesToInt32(r: number, g: number, b: number, a: number): number

Convert 4 1-byte Numbers into a single unsigned 32bit Number.

Parameters

Returns number: A single unsigned 32bit Number.

Example

// Set result1 to 0x11223344 from an array of 4 values
const result1 = math.bytesToInt32([0x11, 0x22, 0x33, 0x44]);

// Set result2 to 0x11223344 from 4 discrete values
const result2 = math.bytesToInt32(0x11, 0x22, 0x33, 0x44);

math.clamp

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L34

clamp(value: number, min: number, max: number): number

Clamp a number between min and max inclusive.

Parameters

Returns number: The clamped value.

Example

math.clamp(5, 0, 10);  // returns 5
math.clamp(-5, 0, 10); // returns 0
math.clamp(15, 0, 10); // returns 10

math.intToBytes24

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L49

intToBytes24(i: number): number[]

Convert a 24-bit integer into an array of 3 bytes.

Parameters

Returns number[]: An array of 3 bytes.

Example

// Set bytes to [0x11, 0x22, 0x33]
const bytes = math.intToBytes24(0x112233);

math.intToBytes32

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L66

intToBytes32(i: number): number[]

Convert a 32-bit integer into an array of 4 bytes.

Parameters

Returns number[]: An array of 4 bytes.

Example

// Set bytes to [0x11, 0x22, 0x33, 0x44]
const bytes = math.intToBytes32(0x11223344);

math.lerp

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L140

lerp(a: number, b: number, alpha: number): number

Calculates the linear interpolation of two numbers.

Parameters

Returns number: The linear interpolation of two numbers.

Example

math.lerp(0, 10, 0);   // returns 0
math.lerp(0, 10, 0.5); // returns 5
math.lerp(0, 10, 1);   // returns 10

math.lerpAngle

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L175

lerpAngle(a: number, b: number, alpha: number): number

Calculates the linear interpolation of two angles ensuring that interpolation is correctly performed across the 360 to 0 degree boundary. Angles are supplied in degrees.

Parameters

Returns number: The linear interpolation of two angles.

Example

math.lerpAngle(350, 10, 0.5); // returns 0 (shortest path crosses 360/0 boundary)
math.lerpAngle(0, 90, 0.5);   // returns 45

math.lerpUnclamped

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L157

lerpUnclamped(a: number, b: number, alpha: number): number

Calculates the unclamped linear interpolation of two numbers.

Parameters

Returns number: The linear interpolation of two numbers.

Example

math.lerpUnclamped(0, 10, -0.5); // returns -5
math.lerpUnclamped(0, 10, 0.5);  // returns 5
math.lerpUnclamped(0, 10, 1.5);  // returns 15

math.nearestPowerOfTwo

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L227

nearestPowerOfTwo(val: number): number

Returns the nearest (smaller or larger) power of 2 for the specified value.

Parameters

Returns number: The nearest power of 2.

Example

math.nearestPowerOfTwo(17); // returns 16
math.nearestPowerOfTwo(24); // returns 32

math.nextPowerOfTwo

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L207

nextPowerOfTwo(val: number): number

Returns the next power of 2 for the specified value.

Parameters

Returns number: The next power of 2.

Example

math.nextPowerOfTwo(17); // returns 32
math.nextPowerOfTwo(32); // returns 32

math.powerOfTwo

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L194

powerOfTwo(x: number): boolean

Returns true if argument is a power-of-two and false otherwise.

Parameters

Returns boolean: true if power-of-two and false otherwise.

Example

math.powerOfTwo(32); // returns true
math.powerOfTwo(17); // returns false

math.random

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L241

random(min: number, max: number): number

Return a pseudo-random number between min and max. The number generated is in the range [min, max), that is inclusive of the minimum but exclusive of the maximum.

Parameters

Returns number: Pseudo-random number between the supplied range.

Example

math.random(0, 10); // returns a random number between 0 and 10

math.roundUp

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L304

roundUp(numToRound: number, multiple: number): number

Rounds a number up to nearest multiple.

Parameters

Returns number: A number rounded up to nearest multiple.

Example

math.roundUp(17, 4); // returns 20
math.roundUp(16, 4); // returns 16

math.smootherstep

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L285

smootherstep(min: number, max: number, x: number): number

An improved version of the math.smoothstep function which has zero 1st and 2nd order derivatives at t=0 and t=1.

See https://en.wikipedia.org/wiki/Smoothstep#Variations for more details.

Parameters

Returns number: The smoothly interpolated value clamped between zero and one.

Example

math.smootherstep(0, 10, 5); // returns 0.5

math.smoothstep

Function · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L263

smoothstep(min: number, max: number, x: number): number

The function interpolates smoothly between two input values based on a third one that should be between the first two. The returned value is clamped between 0 and 1.

The slope (i.e. derivative) of the smoothstep function starts at 0 and ends at 0. This makes it easy to create a sequence of transitions using smoothstep to interpolate each segment rather than using a more sophisticated or expensive interpolation technique.

See https://en.wikipedia.org/wiki/Smoothstep for more details.

Parameters

Returns number: The smoothly interpolated value clamped between zero and one.

Example

math.smoothstep(0, 10, 5); // returns 0.5

math

Namespace · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L7

Math API.

Members

AmmoPhysicsWorld

Class · extends PhysicsWorld · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/ammo/ammo-physics-world.js#L164

The Ammo.js (Bullet) physics backend. The Ammo global must be available when the world is constructed - load the library first, then supply the backend to the application:

WasmModule.setConfig('Ammo', {
    glueUrl: 'ammo.wasm.js',
    wasmUrl: 'ammo.wasm.wasm',
    fallbackUrl: 'ammo.js'
});
await new Promise((resolve) => {
    WasmModule.getInstance('Ammo', () => resolve());
});

const options = new AppOptions();
options.physicsWorld = new AmmoPhysicsWorld();

When AppOptions#physicsWorld is omitted, the engine creates this backend automatically once application libraries have loaded, if the Ammo global is present.

Constructors

constructor

new AmmoPhysicsWorld()

Create a new AmmoPhysicsWorld instance. The Ammo library must be loaded before the backend is constructed.

Inherited from NullPhysicsWorld

CollisionComponent

Class · extends Component · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/component.js#L65

The CollisionComponent enables an Entity to act as a collision volume. Use it on its own to define a trigger volume. Or use it in conjunction with a RigidBodyComponent to make a collision volume that can be simulated using the physics engine.

When an entity is configured as a trigger volume, if an entity with a dynamic or kinematic body enters or leaves that trigger volume, both entities will receive trigger events.

You should never need to use the CollisionComponent constructor directly. To add a CollisionComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('collision'); // This defaults to 1x1x1 box-shaped trigger volume

To create a 0.5 radius dynamic rigid body sphere:

const entity = new Entity();
entity.addComponent('collision', {
    type: 'sphere'
});
entity.addComponent('rigidbody', {
    type: 'dynamic'
});

Once the CollisionComponent is added to the entity, you can access it via the Entity#collision property:

entity.collision.type = 'cylinder'; // Set the collision volume to a cylinder

console.log(entity.collision.type); // Get the collision volume type and print it

Relevant Engine API examples:

Accessors

angularOffset

get angularOffset(): Readonly<Quat>
set angularOffset(arg: Readonly<Quat>)

Gets the rotational offset of the collision shape from the Entity rotation in local space. Use the setter to update the collision shape.

asset

get asset(): number | Asset<string> | null
set asset(arg: number | Asset<string> | null)

Gets the asset or asset id for the model of the mesh collision volume.

axis

get axis(): number
set axis(arg: number)

Gets the local space axis with which the capsule, cylinder or cone-shaped collision volume's length is aligned.

checkVertexDuplicates

get checkVertexDuplicates(): boolean
set checkVertexDuplicates(arg: boolean)

Gets whether checking for duplicate vertices should be enabled when creating collision meshes.

convexHull

get convexHull(): boolean
set convexHull(arg: boolean)

Gets whether the collision mesh should be treated as a convex hull.

halfExtents

get halfExtents(): Readonly<Vec3>
set halfExtents(arg: Readonly<Vec3>)

Gets the half-extents of the box-shaped collision volume in the x, y and z axes. Use the setter to update the collision shape.

height

get height(): number
set height(arg: number)

Gets the total height of the capsule, cylinder or cone-shaped collision volume from tip to tip.

linearOffset

get linearOffset(): Readonly<Vec3>
set linearOffset(arg: Readonly<Vec3>)

Gets the positional offset of the collision shape from the Entity position along the local axes. Use the setter to update the collision shape.

model

get model(): Model | null
set model(arg: Model | null)

Gets the model that is added to the scene graph for the mesh collision volume.

radius

get radius(): number
set radius(arg: number)

Gets the radius of the sphere, capsule, cylinder or cone-shaped collision volumes.

renderAsset

get renderAsset(): number | Asset<string> | null
set renderAsset(arg: number | Asset<string> | null)

Gets the render asset id of the mesh collision volume.

type

get type(): "mesh" | "box" | "capsule" | "compound" | "cone" | "cylinder" | "sphere"
set type(arg: "mesh" | "box" | "capsule" | "compound" | "cone" | "cylinder" | "sphere")

Gets the type of the collision volume.

Methods

getShapePosition

getShapePosition(): Vec3

Returns the world position for the collision shape, taking into account of any offsets.

Returns Vec3: The world position for the collision shape.

getShapeRotation

getShapeRotation(): Quat

Returns the world rotation for the collision shape, taking into account of any offsets.

Returns Quat: The world rotation for the collision.

Events

EVENT_COLLISIONEND

static EVENT_COLLISIONEND: string = 'collisionend'

Fired when two rigid bodies stop touching. The handler is passed an Entity that represents the other rigid body involved in the collision.

Example

entity.collision.on('collisionend', (other) => {
    console.log(`${entity.name} stopped touching ${other.name}`);
});

EVENT_COLLISIONSTART

static EVENT_COLLISIONSTART: string = 'collisionstart'

Fired when two rigid bodies start touching. The handler is passed the ContactResult object which contains details of the contact between the two rigid bodies.

Example

entity.collision.on('collisionstart', (result) => {
   console.log(`${entity.name} started touching ${result.other.name}`);
});

EVENT_CONTACT

static EVENT_CONTACT: string = 'contact'

Fired when a contact occurs between two rigid bodies. The handler is passed a ContactResult object which contains details of the contact between the two rigid bodies.

Example

entity.collision.on('contact', (result) => {
   console.log(`Contact between ${entity.name} and ${result.other.name}`);
});

EVENT_TRIGGERENTER

static EVENT_TRIGGERENTER: string = 'triggerenter'

Fired when a rigid body enters a trigger volume. The handler is passed an Entity representing the rigid body that entered this collision volume.

Example

entity.collision.on('triggerenter', (other) => {
    console.log(`${other.name} entered trigger volume ${entity.name}`);
});

EVENT_TRIGGERLEAVE

static EVENT_TRIGGERLEAVE: string = 'triggerleave'

Fired when a rigid body exits a trigger volume. The handler is passed an Entity representing the rigid body that exited this collision volume.

Example

entity.collision.on('triggerleave', (other) => {
    console.log(`${other.name} exited trigger volume ${entity.name}`);
});

Inherited from Component

CollisionComponentSystem

Class · extends ComponentSystem · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/system.js#L600

Manages the CollisionComponents of an application. Reach it through app.systems.collision; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ContactPoint

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/contact-point.js#L38

Represents a single point of contact between two colliding rigid bodies in the physics simulation. Each contact point stores detailed spatial information about the collision, including both local and world space coordinates of the exact contact points on both entities, the contact normal direction, and the collision impulse force.

Contact points are generated by the physics engine during collision detection and are typically accessed through a ContactResult object, which can contain multiple contact points for a single collision between two entities. Multiple contact points commonly occur when objects collide along edges or faces rather than at a single point.

The impulse property can be particularly useful for gameplay mechanics that need to respond differently based on the force of impact, such as damage calculations or sound effect volume.

Contact points are pooled and reused by the physics system, so a contact point and its vectors are only valid inside the event handler that receives them. Copy any values that are needed later, for example with Vec3#clone.

Example

// Access contact points from a collision event
entity.collision.on('contact', (result) => {
    // Get the first contact point
    const contact = result.contacts[0];

    // Get the contact position in world space
    const worldPos = contact.point;

    // Check how hard the collision was
    if (contact.impulse > 10) {
        console.log("That was a hard impact!");
    }
});

Properties

impulse

impulse: number

The total accumulated impulse applied by the constraint solver during the last sub-step. This value represents how hard two objects collided. Higher values indicate stronger impacts.

localPoint

localPoint: Vec3

The point on the entity where the contact occurred, in the local space of its rigid body. That space has the entity's world position and rotation, with any CollisionComponent#linearOffset and CollisionComponent#angularOffset applied, and ignores the entity's scale.

localPointOther

localPointOther: Vec3

The point on the other entity where the contact occurred, in the local space of the other entity's rigid body (see ContactPoint#localPoint).

normal

normal: Vec3

The normal vector of the contact on the other entity, in world space. This vector points away from the surface of the other entity at the point of contact.

point

point: Vec3

The point on the entity where the contact occurred, in world space.

pointOther

pointOther: Vec3

The point on the other entity where the contact occurred, in world space.

ContactResult

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/contact-result.js#L32

Represents a collection of contact points between two entities in a physics collision. When rigid bodies collide, this object stores the entity involved in the collision and an array of specific contact points where the collision occurred. This information is used by the physics system to resolve collisions and notify components through events.

Instances of this class are passed to event handlers for the contact and collisionstart events on individual RigidBodyComponent and CollisionComponent instances.

Unlike SingleContactResult which is used for global contact events, ContactResult objects provide information about collision from the perspective of one entity, with information about which other entity was involved and all points of contact.

Contact results are pooled and reused by the physics system, so a result and its contact points are only valid inside the event handler that receives them. Copy any values that are needed later.

Please refer to the following event documentation for more information:

Properties

contacts

contacts: ContactPoint[]

An array of ContactPoints with the other entity.

other

other: Entity

The entity that was involved in the contact with this entity.

JointComponent

Class · extends Component · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/component.js#L110

The JointComponent constrains the relative motion of two rigid bodies. The entity holding the joint component is not itself constrained - instead, its world transform defines the joint frame: the anchor point and axes that the constraint operates about. The constrained bodies are assigned via entityA and entityB, both of which must have a RigidBodyComponent. If entityB is null, entityA is constrained to a fixed point in world space.

A joint's primary axis is the joint entity's local X axis: a hinge rotates about X, a slider translates along X and a ball joint twists about X. To aim a joint, rotate the joint entity. A common pattern is to parent the joint entity to entityA at the pivot point.

The joint frames are captured when the underlying constraint is created - typically when the component is enabled and both bodies are present in the physics simulation. Moving the joint entity afterwards has no effect on an existing constraint. Call refreshFrames to re-capture the frames from the current world transforms. Entity scale is ignored, matching the behavior of rigid bodies.

At creation the two joint frames coincide, so every degree of freedom reads zero: limits and equilibrium values are measured from the initial relative pose of the two bodies, not from the joint entity's transform or any absolute separation. Linear degrees of freedom are positive when entityB (or the world anchor when entityB is null) moves along the joint's positive axes relative to entityA. Angular degrees of freedom measure the opposite body: they are positive when entityA rotates counter-clockwise about the joint's axes relative to entityB or the world anchor, viewed from each axis's positive end (right-handed). In the door hinge example below, the limits of [0, 110] let the door swing counter-clockwise, viewed from above, up to 110 degrees from its starting pose.

Many properties apply only to specific joint types; each one documents the types it affects, and properties without such a note (for example entityA, enableCollision and breakImpulse) apply to all types.

To add a JointComponent to an Entity, use Entity#addComponent:

// Create a door hinge: the joint entity's position is the hinge point and its
// local X axis (rotated here to point up) is the hinge axis
const hinge = new Entity('hinge');
hinge.setPosition(1, 1, 0);
hinge.setEulerAngles(0, 0, 90);
hinge.addComponent('joint', {
    type: JOINTTYPE_HINGE,
    entityA: door,
    entityB: doorFrame,
    enableLimits: true,
    limits: new Vec2(0, 110)
});
app.root.addChild(hinge);

Accessors

angularDamping

get angularDamping(): Vec3
set angularDamping(arg: Vec3)

angularEquilibrium

get angularEquilibrium(): Vec3
set angularEquilibrium(arg: Vec3)

angularLimitsX

get angularLimitsX(): Vec2
set angularLimitsX(arg: Vec2)

angularLimitsY

get angularLimitsY(): Vec2
set angularLimitsY(arg: Vec2)

angularLimitsZ

get angularLimitsZ(): Vec2
set angularLimitsZ(arg: Vec2)

angularMotionX

get angularMotionX(): "free" | "limited" | "locked"
set angularMotionX(arg: "free" | "limited" | "locked")

angularMotionY

get angularMotionY(): "free" | "limited" | "locked"
set angularMotionY(arg: "free" | "limited" | "locked")

angularMotionZ

get angularMotionZ(): "free" | "limited" | "locked"
set angularMotionZ(arg: "free" | "limited" | "locked")

angularStiffness

get angularStiffness(): Vec3
set angularStiffness(arg: Vec3)

breakImpulse

get breakImpulse(): number
set breakImpulse(impulse: number)

enableCollision

get enableCollision(): boolean
set enableCollision(enableCollision: boolean)

enableLimits

get enableLimits(): boolean
set enableLimits(arg: boolean)

entityA

get entityA(): Entity | null
set entityA(arg: Entity | null)

entityB

get entityB(): Entity | null
set entityB(arg: Entity | null)

isBroken

get isBroken(): boolean

limits

get limits(): Vec2
set limits(arg: Vec2)

linearDamping

get linearDamping(): Vec3
set linearDamping(arg: Vec3)

linearEquilibrium

get linearEquilibrium(): Vec3
set linearEquilibrium(arg: Vec3)

linearLimitsX

get linearLimitsX(): Vec2
set linearLimitsX(arg: Vec2)

linearLimitsY

get linearLimitsY(): Vec2
set linearLimitsY(arg: Vec2)

linearLimitsZ

get linearLimitsZ(): Vec2
set linearLimitsZ(arg: Vec2)

linearMotionX

get linearMotionX(): "free" | "limited" | "locked"
set linearMotionX(arg: "free" | "limited" | "locked")

linearMotionY

get linearMotionY(): "free" | "limited" | "locked"
set linearMotionY(arg: "free" | "limited" | "locked")

linearMotionZ

get linearMotionZ(): "free" | "limited" | "locked"
set linearMotionZ(arg: "free" | "limited" | "locked")

linearStiffness

get linearStiffness(): Vec3
set linearStiffness(arg: Vec3)

maxMotorForce

get maxMotorForce(): number
set maxMotorForce(arg: number)

motorSpeed

get motorSpeed(): number
set motorSpeed(arg: number)

swingLimitY

get swingLimitY(): number
set swingLimitY(arg: number)

swingLimitZ

get swingLimitZ(): number
set swingLimitZ(arg: number)

twistLimit

get twistLimit(): number
set twistLimit(arg: number)

type

get type(): "fixed" | "ball" | "hinge" | "slider" | "6dof"
set type(type: "fixed" | "ball" | "hinge" | "slider" | "6dof")

Methods

onBeforeRemove

onBeforeRemove(): void

refreshFrames

refreshFrames(): void

Destroys and recreates the underlying constraint, re-capturing the joint frames from the current world transforms of the joint entity, entityA and entityB. Call this after moving the joint entity to re-anchor the joint, or to re-attach a joint that has broken.

Events

EVENT_BREAK

static EVENT_BREAK: string = 'break'

Fired when the applied impulse on the joint exceeds breakImpulse and the constraint breaks. The broken joint no longer constrains its bodies and isBroken becomes true. Call refreshFrames to re-attach it. Note that on ammo builds that expose no constraint state, breakage of 6dof joints cannot be detected, so this event does not fire for them - other joint types are unaffected.

Example

entity.joint.on('break', () => {
    console.log('The joint broke');
});

Inherited from Component

JointComponentSystem

Class · extends ComponentSystem · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/system.js#L31

Manages the JointComponents of an application. Reach it through app.systems.joint; components are created with Entity#addComponent, never by calling the system directly.

Properties

ComponentType

ComponentType: typeof JointComponent

Methods

destroy

destroy(): void

Inherited from ComponentSystem

NullPhysicsWorld

Class · extends PhysicsWorld · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/null/null-physics-world.js#L20

A no-op physics backend. The PhysicsWorld base class is a functional no-op - bodies, shapes and joints are created but inert, raycasts miss and stepping does nothing - so this subclass adds nothing. It exists to let physics component lifecycle run without a physics engine loaded, and is installed explicitly:

const options = new AppOptions();
options.physicsWorld = new NullPhysicsWorld();

It is never auto-selected - without it, an application with no physics library keeps the default behavior where physics components are inert placeholders.

Inherited from PhysicsWorld

PhysicsWorld

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/physics/physics-world.js#L171

The base class for physics backends. A PhysicsWorld owns the lifecycle of a physics engine's simulation world: stepping, gravity, body and shape factories, joints, raycasts and contact reporting. Backends subclass it and override every method.

The base implementation is a functional no-op: bodies and joints are created but inert, raycasts miss and stepping does nothing. NullPhysicsWorld uses this to let physics component lifecycle run without a physics engine loaded.

Supply a backend to an application with AppOptions#physicsWorld.

Applications drive physics through the physics components - the methods of this class form the internal contract between the engine and a backend and are not called directly.

Constructors

constructor

new PhysicsWorld()

Properties

nativeWorld

nativeWorld: any = null

The backend-native world object - btDiscreteDynamicsWorld when the Ammo backend is active, null otherwise.

RaycastResult

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/raycast-result.js#L17

Contains the result of a successful raycast intersection with a rigid body. When a ray intersects with a rigid body in the physics simulation, this class stores the complete information about that intersection including the entity, the exact point of impact, the normal at the impact point, and the fractional distance along the ray where the intersection occurred.

Instances of this class are created and returned by RigidBodyComponentSystem#raycastFirst and RigidBodyComponentSystem#raycastAll methods when performing physics raycasts.

Properties

entity

entity: Entity

The entity that was hit.

hitFraction

hitFraction: number

The normalized distance (between 0 and 1) at which the ray hit occurred from the starting point.

normal

normal: Vec3

The normal vector of the surface where the ray hit in world space.

point

point: Vec3

The point at which the ray hit the entity in world space.

RigidBodyComponent

Class · extends Component · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/component.js#L76

The RigidBodyComponent, when combined with a CollisionComponent, allows your entities to be simulated using realistic physics. A RigidBodyComponent will fall under gravity and collide with other rigid bodies. Using scripts, you can apply forces and impulses to rigid bodies.

You should never need to use the RigidBodyComponent constructor directly. To add a RigidBodyComponent to an Entity, use Entity#addComponent:

// Create a static 1x1x1 box-shaped rigid body
const entity = new Entity();
entity.addComponent('collision'); // Without options, this defaults to a 1x1x1 box shape
entity.addComponent('rigidbody'); // Without options, this defaults to a 'static' body

To create a dynamic sphere with mass of 10, do:

const entity = new Entity();
entity.addComponent('collision', {
    type: 'sphere'
});
entity.addComponent('rigidbody', {
    type: 'dynamic',
    mass: 10
});

Once the RigidBodyComponent is added to the entity, you can access it via the Entity#rigidbody property:

entity.rigidbody.mass = 10;
console.log(entity.rigidbody.mass);

For player movement, playcanvas/scripts/esm/first-person-controller.mjs and playcanvas/scripts/esm/third-person-controller.mjs ship complete rigidbody character controllers with capsule collision, damped ground and air movement, sprinting, jumping and camera control. Attach one instead of driving the body by hand.

Relevant Engine API examples:

Accessors

angularDamping

get angularDamping(): number
set angularDamping(damping: number)

Gets the rate at which a body loses angular velocity over time.

angularFactor

get angularFactor(): Readonly<Vec3>
set angularFactor(factor: Readonly<Vec3>)

Gets the scaling factor for angular movement of the body in each axis. Use the setter to update the physics body.

angularVelocity

get angularVelocity(): Readonly<Vec3>
set angularVelocity(velocity: Readonly<Vec3>)

Gets the rotational speed of the body around each world axis. Use the setter to update the physics body.

friction

get friction(): number
set friction(friction: number)

Gets the friction value used when contacts occur between two bodies.

gravityScale

get gravityScale(): number
set gravityScale(scale: number)

Gets the scale applied to the world gravity for this body.

group

get group(): number
set group(group: number)

Gets the collision group this body belongs to.

linearDamping

get linearDamping(): number
set linearDamping(damping: number)

Gets the rate at which a body loses linear velocity over time.

linearFactor

get linearFactor(): Readonly<Vec3>
set linearFactor(factor: Readonly<Vec3>)

Gets the scaling factor for linear movement of the body in each axis. Use the setter to update the physics body.

linearVelocity

get linearVelocity(): Readonly<Vec3>
set linearVelocity(velocity: Readonly<Vec3>)

Gets the speed of the body in a given direction. Use the setter to update the physics body.

mask

get mask(): number
set mask(mask: number)

Gets the collision mask sets which groups this body collides with.

mass

get mass(): number
set mass(mass: number)

Gets the mass of the body.

restitution

get restitution(): number
set restitution(restitution: number)

Gets the value that controls the amount of energy lost when two rigid bodies collide.

rollingFriction

get rollingFriction(): number
set rollingFriction(friction: number)

Gets the torsional friction orthogonal to the contact point.

type

get type(): "static" | "dynamic" | "kinematic"
set type(type: "static" | "dynamic" | "kinematic")

Gets the rigid body type determines how the body is simulated.

Methods

activate

activate(): void

Forcibly activate the rigid body simulation. Only affects rigid bodies of type BODYTYPE_DYNAMIC.

applyForce

applyForce(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void

Apply a force to the body at a point. By default, the force is applied at the origin of the body. However, the force can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.

Parameters

Returns void

Example

// Apply an approximation of gravity at the body's center
this.entity.rigidbody.applyForce(0, -10, 0);

Example

// Apply an approximation of gravity at 1 unit down the world Z from the center of the body
this.entity.rigidbody.applyForce(0, -10, 0, 0, 0, 1);
applyForce(force: Vec3, relativePoint?: Vec3): void

Apply a force to the body at a point. By default, the force is applied at the origin of the body. However, the force can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.

Parameters

Returns void

Example

// Calculate a force vector pointing in the world space direction of the entity
const force = this.entity.forward.clone().mulScalar(100);

// Apply the force at the body's center
this.entity.rigidbody.applyForce(force);

Example

// Apply a force at some relative offset from the body's center
// Calculate a force vector pointing in the world space direction of the entity
const force = this.entity.forward.clone().mulScalar(100);

// Calculate the world space relative offset
const relativePoint = new Vec3();
const childEntity = this.entity.findByName('Engine');
relativePoint.sub2(childEntity.getPosition(), this.entity.getPosition());

// Apply the force
this.entity.rigidbody.applyForce(force, relativePoint);

applyImpulse

applyImpulse(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void

Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the impulse is applied at the origin of the body. However, the impulse can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.

Parameters

Returns void

Example

// Apply an impulse along the world space positive y-axis at the body's origin
entity.rigidbody.applyImpulse(0, 10, 0);

Example

// Apply an impulse along the world space positive y-axis at 1 unit along the world space
// positive z-axis from the body's origin
entity.rigidbody.applyImpulse(0, 10, 0, 0, 0, 1);
applyImpulse(impulse: Vec3, relativePoint?: Vec3): void

Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the impulse is applied at the origin of the body. However, the impulse can be applied at an offset from this point by specifying a world space vector from the body's origin to the point of application. The body's origin is the entity's world position, shifted by the collision component's CollisionComponent#linearOffset.

Parameters

Returns void

Example

// Apply an impulse along the world space positive y-axis at the body's origin
const impulse = new Vec3(0, 10, 0);
entity.rigidbody.applyImpulse(impulse);

Example

// Apply an impulse along the world space positive y-axis at 1 unit along the world space
// positive z-axis from the body's origin
const impulse = new Vec3(0, 10, 0);
const relativePoint = new Vec3(0, 0, 1);
entity.rigidbody.applyImpulse(impulse, relativePoint);

Example

// Apply an impulse at an offset given in the entity's local space, by first rotating the
// offset into world space
const impulse = new Vec3(0, 10, 0);
const relativePoint = entity.getRotation().transformVector(new Vec3(0, 0, 1));
entity.rigidbody.applyImpulse(impulse, relativePoint);

applyTorque

applyTorque(x: number, y: number, z: number): void

Apply torque (rotational force) to the body.

Parameters

Returns void

Example

entity.rigidbody.applyTorque(0, 10, 0);
applyTorque(torque: Vec3): void

Apply torque (rotational force) to the body.

Parameters

Returns void

Example

const torque = new Vec3(0, 10, 0);
entity.rigidbody.applyTorque(torque);

applyTorqueImpulse

applyTorqueImpulse(x: number, y: number, z: number): void

Apply a torque impulse (rotational force applied instantaneously) to the body.

Parameters

Returns void

Example

entity.rigidbody.applyTorqueImpulse(0, 10, 0);
applyTorqueImpulse(torque: Vec3): void

Apply a torque impulse (rotational force applied instantaneously) to the body.

Parameters

Returns void

Example

const torque = new Vec3(0, 10, 0);
entity.rigidbody.applyTorqueImpulse(torque);

isActive

isActive(): boolean

Returns true if the rigid body is currently actively being simulated. I.e. Not 'sleeping'.

Returns boolean: True if the body is active.

isKinematic

isKinematic(): boolean

Returns true if the rigid body is of type BODYTYPE_KINEMATIC.

Returns boolean: True if kinematic.

isStatic

isStatic(): boolean

Returns true if the rigid body is of type BODYTYPE_STATIC.

Returns boolean: True if static.

isStaticOrKinematic

isStaticOrKinematic(): boolean

Returns true if the rigid body is of type BODYTYPE_STATIC or BODYTYPE_KINEMATIC.

Returns boolean: True if static or kinematic.

teleport

teleport(x: number, y: number, z: number, rx?: number, ry?: number, rz?: number): void

Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.

Parameters

Returns void

Example

// Teleport the entity to the origin
entity.rigidbody.teleport(0, 0, 0);

Example

// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
entity.rigidbody.teleport(1, 2, 3, 0, 0, 0);
teleport(position: Vec3, angles?: Vec3): void

Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.

Parameters

Returns void

Example

// Teleport the entity to the origin
entity.rigidbody.teleport(Vec3.ZERO);

Example

// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
const position = new Vec3(1, 2, 3);
entity.rigidbody.teleport(position, Vec3.ZERO);
teleport(position: Vec3, rotation?: Quat): void

Teleport an entity to a new world space position, optionally setting orientation. This function should only be called for rigid bodies that are dynamic.

Parameters

Returns void

Example

// Teleport the entity to the origin
entity.rigidbody.teleport(Vec3.ZERO);

Example

// Teleport the entity to world space coordinate [1, 2, 3] and reset orientation
const position = new Vec3(1, 2, 3);
entity.rigidbody.teleport(position, Quat.IDENTITY);

Events

EVENT_COLLISIONEND

static EVENT_COLLISIONEND: string = 'collisionend'

Fired when two rigid bodies stop touching. The handler is passed an Entity that represents the other rigid body involved in the collision.

Example

entity.rigidbody.on('collisionend', (other) => {
    console.log(`${entity.name} stopped touching ${other.name}`);
});

EVENT_COLLISIONSTART

static EVENT_COLLISIONSTART: string = 'collisionstart'

Fired when two rigid bodies start touching. The handler is passed a ContactResult object containing details of the contact between the two rigid bodies.

Example

entity.rigidbody.on('collisionstart', (result) => {
    console.log(`Collision started between ${entity.name} and ${result.other.name}`);
});

EVENT_CONTACT

static EVENT_CONTACT: string = 'contact'

Fired when a contact occurs between two rigid bodies. The handler is passed a ContactResult object containing details of the contact between the two rigid bodies.

Example

entity.rigidbody.on('contact', (result) => {
   console.log(`Contact between ${entity.name} and ${result.other.name}`);
});

EVENT_TRIGGERENTER

static EVENT_TRIGGERENTER: string = 'triggerenter'

Fired when a rigid body enters a trigger volume. The handler is passed an Entity representing the trigger volume that this rigid body entered.

Example

entity.rigidbody.on('triggerenter', (trigger) => {
    console.log(`Entity ${entity.name} entered trigger volume ${trigger.name}`);
});

EVENT_TRIGGERLEAVE

static EVENT_TRIGGERLEAVE: string = 'triggerleave'

Fired when a rigid body exits a trigger volume. The handler is passed an Entity representing the trigger volume that this rigid body exited.

Example

entity.rigidbody.on('triggerleave', (trigger) => {
    console.log(`Entity ${entity.name} exited trigger volume ${trigger.name}`);
});

Inherited from Component

RigidBodyComponentSystem

Class · extends ComponentSystem · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/system.js#L74

The RigidBodyComponentSystem manages the physics simulation for all rigid body components in the application and is accessed as app.systems.rigidbody. It owns the physics world, creates and destroys the bodies behind rigid body and collision components, steps the simulation once per frame and writes the resulting transforms back to their entities. It also holds global settings such as RigidBodyComponentSystem#gravity, performs raycasts and reports collisions.

The system is only functional once a physics backend is installed: either by supplying AppOptions#physicsWorld when creating the application, or automatically when the application has loaded the Ammo.js WasmModule. Use a recent Ammo.js build: mesh colliders only follow entity scale with a build that exposes btScaledBvhTriangleMeshShape.

Set RigidBodyComponentSystem#timeScale to slow the simulation down, speed it up or pause it, for example while a pause menu is open, and call RigidBodyComponentSystem#step to advance it manually.

Properties

gravity

gravity: Vec3

The world space vector representing global gravity in the physics simulation. Defaults to [0, -9.81, 0] which is an approximation of the gravitational force on Earth.

The value is applied to the physics backend at the start of the next step, whether the vector is modified in place or replaced with a new one.

Example

// Set the gravity in the physics world to simulate a planet with low gravity
app.systems.rigidbody.gravity = new Vec3(0, -3.7, 0);

timeScale

timeScale: number = 1

Scales the time the simulation is advanced by each frame. Defaults to 1. Values below 1 run physics in slow motion and values above 1 speed it up. 0 pauses the simulation: the system stops advancing it, bodies freeze in place, entity transforms are no longer driven by their bodies and no contact or trigger events fire. The rest of the application keeps running, so this suits a pause menu or inventory screen that must stay interactive while the game world stands still. Negative values are treated as 0.

This scale is applied on top of AppBase#timeScale. The simulation can still be advanced manually with RigidBodyComponentSystem#step while paused, for example to drive it from a custom time source.

How slow motion below one fixed substep per frame looks depends on the backend: the Ammo backend interpolates body transforms between substeps so motion stays smooth, while other backends may only move bodies on the frames in which a substep runs. Fast forward is limited by the maximum number of substeps the simulation may take per frame, beyond which it runs slower than requested.

Forces applied with RigidBodyComponent#applyForce while paused accumulate on the body and are applied together on the next step, because forces are only cleared when the simulation steps. Impulses and velocity changes take effect immediately.

Example

// Freeze the game world while the pause menu is open
app.systems.rigidbody.timeScale = 0;

Example

// Run physics at quarter speed for a slow motion effect
app.systems.rigidbody.timeScale = 0.25;

Accessors

physicsWorld

get physicsWorld(): PhysicsWorld | null

Gets the installed physics backend, or null when no backend is installed. Supply a backend via AppOptions#physicsWorld, or load the Ammo.js library to have one installed automatically.

Methods

raycastAll

raycastAll(start: Vec3, end: Vec3, options?: object): RaycastResult[]

Raycast the world and return all entities the ray hits. It returns an array of RaycastResult, one for each hit. If no hits are detected, the returned array will be of length 0. Results are returned in no particular order unless options.sort is true, in which case they are sorted by distance with the closest first.

Parameters

Returns RaycastResult[]: An array of raycast hit results (0 length if there were no hits or no physics backend is installed).

Example

// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2));

Example

// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity is tagged with `bird` OR `mammal`
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
    filterTags: [ "bird", "mammal" ]
});

Example

// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity has a `camera` component
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
    filterCallback: (entity) => entity && entity.camera
});

Example

// Return all results of a raycast between 0, 2, 2 and 0, -2, -2, skipping the back faces
// of mesh colliders so a ray through a closed mesh hits it only where it enters
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
    hitBackFaces: false
});

Example

// Return all results of a raycast between 0, 2, 2 and 0, -2, -2
// where hit entity is tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`)
// and the entity has an `anim` component
const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), {
    filterTags: [
        [ "carnivore", "mammal" ],
        [ "carnivore", "reptile" ]
    ],
    filterCallback: (entity) => entity && entity.anim
});

raycastFirst

raycastFirst(start: Vec3, end: Vec3, options?: object): RaycastResult | null

Raycast the world and return the first entity the ray hits. Fire a ray into the world from start to end, if the ray hits an entity with a collision component, it returns a RaycastResult, otherwise returns null.

Parameters

Returns RaycastResult | null: The result of the raycasting, or null if there was no hit or no physics backend is installed.

step

step(dt: number): void

Advances the physics simulation by dt seconds. Synchronizes triggers, compound shapes and kinematic bodies from their entities, steps the backend in fixed-length substeps (up to a maximum number per call), writes the resulting transforms of dynamic bodies back to their entities and fires contact and trigger events.

The system calls this once per frame with the frame delta time multiplied by RigidBodyComponentSystem#timeScale, unless that is 0. Call it directly to step the simulation manually: to advance it while paused, to fast forward it by stepping several times in one frame, or to drive it from a custom time source. Automatic stepping continues while timeScale is above 0, so calling this every frame as well advances the simulation twice per frame. Set timeScale to 0 first when taking over stepping entirely. The delta is used as given, without applying timeScale. Does nothing when no physics backend is installed.

Parameters

Example

// Pause automatic stepping and advance the simulation by 1/60 s per key press
const physics = app.systems.rigidbody;
physics.timeScale = 0;
app.keyboard.on('keydown', (event) => {
    if (event.key === KEY_SPACE) {
        physics.step(1 / 60);
    }
});

Events

EVENT_CONTACT

static EVENT_CONTACT: string = 'contact'

Fired when a contact occurs between two rigid bodies. The handler is passed a SingleContactResult object containing details of the contact between the two bodies.

Example

app.systems.rigidbody.on('contact', (result) => {
    console.log(`Contact between ${result.a.name} and ${result.b.name}`);
});

Inherited from ComponentSystem

SingleContactResult

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/single-contact-result.js#L28

Represents the detailed data of a single contact point between two rigid bodies in the physics simulation. This class provides comprehensive information about the contact, including the entities involved, the exact contact points in both local and world space coordinates, the contact normal, and the collision impulse force.

Instances of this class are created by the physics engine when collision events occur and are passed to event handlers only through the global contact event on the RigidBodyComponentSystem. Individual rigid body components receive instances of ContactResult instead.

Instances are pooled and reused by the physics system, so a result and its vectors are only valid inside the event handler that receives them. Copy any values that are needed later.

Example

app.systems.rigidbody.on('contact', (result) => {
    console.log(`Contact between ${result.a.name} and ${result.b.name}`);
});

Properties

a

a: Entity

The first entity involved in the contact.

b

b: Entity

The second entity involved in the contact.

impulse

impulse: number

The total accumulated impulse applied by the constraint solver during the last sub-step. Describes how hard two bodies collided.

localPointA

localPointA: Vec3

The point on Entity A where the contact occurred, in the local space of A's rigid body (see ContactPoint#localPoint).

localPointB

localPointB: Vec3

The point on Entity B where the contact occurred, in the local space of B's rigid body.

normal

normal: Vec3

The normal vector of the contact on Entity B, in world space.

pointA

pointA: Vec3

The point on Entity A where the contact occurred, in world space.

pointB

pointB: Vec3

The point on Entity B where the contact occurred, in world space.

Trigger

Class · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/collision/trigger.js#L19

Creates a trigger object used to create internal physics objects that interact with rigid bodies and trigger collision events with no collision response.

Constructors

constructor

new Trigger(app: AppBase, component: CollisionComponent)

Create a new Trigger instance.

Parameters

Script

Class · extends EventHandler · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script.js#L54

The Script class is the fundamental base class for all scripts within PlayCanvas. It provides the minimal interface required for a script to be compatible with both the Engine and the Editor.

At its core, a script is simply a collection of methods that are called at various points in the Engine's lifecycle. These methods are:

These methods are entirely optional, but provide a useful way to manage the lifecycle of a script and perform any necessary setup and cleanup.

Below is a simple example of a script that rotates an entity every frame.

Example

import { Script } from 'playcanvas';

export class Rotator extends Script {
    static scriptName = 'rotator';

    update(dt) {
        this.entity.rotateLocal(0, 1, 0);
    }
}

When this script is attached to an entity, the update will be called every frame, slowly rotating the entity around the Y-axis.

For more information on how to create scripts, see the Scripting Overview.

The playcanvas package also ships a library of ready-to-use Script subclasses under the playcanvas/scripts/esm/ subpath — camera and character controllers, post-processing, water, sky, grid, shadow catcher, planar reflections, XR and Gaussian-splat effects. Import them directly, for example import { CameraControls } from 'playcanvas/scripts/esm/camera-controls.mjs'.

Constructors

constructor

new Script(args: object)

Create a new Script instance.

Parameters

Properties

app

app: AppBase

The AppBase that the instance of this script belongs to.

entity

entity: Entity

The Entity that the instance of this script belongs to.

Accessors

enabled

get enabled(): boolean
set enabled(value: boolean)

Gets the running state of the script instance. Returns true when the script instance is enabled and its owning Entity (and all ancestors) and ScriptComponent are also enabled; otherwise false.

scriptName

static get scriptName(): string | null
static set scriptName(value: string | null)

Gets the unique name of the script.

Methods

initScript

protected initScript(args: ScriptInitializationArgs): void

Parameters

Events

EVENT_ATTR

static EVENT_ATTR: string = 'attr'

Fired when script attributes have changed. This event is available in two forms. They are as follows:

  1. attr - Fired for any attribute change. The handler is passed the name of the attribute that changed, the value of the attribute before the change and the value of the attribute after the change.
  2. attr:[name] - Fired for a specific attribute change. The handler is passed the value of the attribute before the change and the value of the attribute after the change.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('attr', (name, newValue, oldValue) => {
            console.log(`Attribute '${name}' changed from '${oldValue}' to '${newValue}'`);
        });
    }
};

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('attr:speed', (newValue, oldValue) => {
            console.log(`Attribute 'speed' changed from '${oldValue}' to '${newValue}'`);
        });
    }
};

EVENT_DESTROY

static EVENT_DESTROY: string = 'destroy'

Fired when a script instance is destroyed and removed from component.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('destroy', () => {
            // no longer part of the entity
            // this is a good place to clean up allocated resources used by the script
        });
    }
};

EVENT_DISABLE

static EVENT_DISABLE: string = 'disable'

Fired when a script instance becomes disabled.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('disable', () => {
            // Script Instance is now disabled
        });
    }
};

EVENT_ENABLE

static EVENT_ENABLE: string = 'enable'

Fired when a script instance becomes enabled.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('enable', () => {
            // Script Instance is now enabled
        });
    }
};

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when a script instance had an exception. The script instance will be automatically disabled. The handler is passed an Error object containing the details of the exception and the name of the method that threw the exception.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('error', (err, method) => {
            // caught an exception
            console.log(err.stack);
        });
    }
};

EVENT_STATE

static EVENT_STATE: string = 'state'

Fired when a script instance changes state to enabled or disabled. The handler is passed a boolean parameter that states whether the script instance is now enabled or disabled.

Example

export class PlayerController extends Script {
    static scriptName = 'playerController';
    initialize() {
        this.on('state', (enabled) => {
            console.log(`Script Instance is now ${enabled ? 'enabled' : 'disabled'}`);
        });
    }
};

Inherited from EventHandler

ScriptAttributes

Class · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-attributes.js#L215

Container of Script Attribute definitions. Implements an interface to add/remove attributes and store their definition for a ScriptType. Note: An instance of ScriptAttributes is created automatically by each ScriptType.

Constructors

constructor

new ScriptAttributes(scriptType: typeof ScriptType)

Create a new ScriptAttributes instance.

Parameters

Methods

add

add(name: string, args: object): void

Add Attribute.

Parameters

Example

PlayerController.attributes.add('fullName', {
    type: 'string'
});

Example

PlayerController.attributes.add('speed', {
    type: 'number',
    title: 'Speed',
    placeholder: 'km/h',
    default: 22.2
});

Example

PlayerController.attributes.add('resolution', {
    type: 'number',
    default: 32,
    enum: [
        { '32x32': 32 },
        { '64x64': 64 },
        { '128x128': 128 }
    ]
});

Example

PlayerController.attributes.add('config', {
    type: 'json',
    schema: [{
        name: 'speed',
        type: 'number',
        title: 'Speed',
        placeholder: 'km/h',
        default: 22.2
    }, {
        name: 'resolution',
        type: 'number',
        default: 32,
        enum: [
            { '32x32': 32 },
            { '64x64': 64 },
            { '128x128': 128 }
        ]
    }]
});

get

get(name: string): any

Get object with attribute arguments. Note: Changing argument properties will not affect existing Script Instances.

Parameters

Returns any: Arguments with attribute properties.

Example

// changing default value for an attribute 'fullName'
var attr = PlayerController.attributes.get('fullName');
if (attr) attr.default = 'Unknown';

has

has(name: string): boolean

Detect if Attribute is added.

Parameters

Returns boolean: True if Attribute is defined.

Example

if (PlayerController.attributes.has('fullName')) {
    // attribute fullName is defined
}

remove

remove(name: string): boolean

Remove Attribute.

Parameters

Returns boolean: True if removed or false if not defined.

Example

PlayerController.attributes.remove('fullName');

ScriptComponent

Class · extends Component · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/script/component.js#L47

The ScriptComponent enables an Entity to have custom behavior by attaching scripts written in JavaScript (or TypeScript).

You should never need to use the ScriptComponent constructor directly. To add a ScriptComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('script');

Once the ScriptComponent is added to the entity, you can access it via the Entity#script property:

// Option 1: Add a script using the name registered in the ScriptRegistry
entity.script.create('cameraControls');

// Option 2: Add a script using the script class
entity.script.create(CameraControls);

For more details on scripting see the Scripting Section of the User Manual.

Accessors

scripts

get scripts(): readonly Script[]
set scripts(value: readonly Script[])

Gets the array of all script instances attached to an entity. Use create, destroy and move to change attached scripts or their order.

Methods

create

create<T extends Script>(type: Object, args?: object): T | null

Create a script instance of the specified class and attach it to the entity's script component. The result is typed as an instance of that class, so no cast is needed.

Parameters

Returns T | null: Returns an instance of the class if successfully attached to the entity, or null if it failed because a script with the same name has already been added.

Example

const controller = entity.script.create(PlayerController, {
    properties: {
        speed: 4
    }
}); // PlayerController | null
create(name: string, args?: object): Script | null

Create a script instance by name and attach it to the entity's script component. The name is looked up in the application's ScriptRegistry.

Parameters

Returns Script | null: Returns the script instance if successfully attached to the entity, or null if it failed because a script with the same name has already been added or if the name cannot be found in the ScriptRegistry.

Example

entity.script.create('playerController', {
    attributes: {
        speed: 4
    }
});

destroy

destroy(nameOrType: string | typeof Script): boolean

Destroy the script instance that is attached to an entity.

Parameters

Returns boolean: If it was successfully destroyed.

Example

entity.script.destroy('playerController');

get

get<T extends Script>(type: Object): T | null

Get a script instance (if attached) by its class. The result is typed as an instance of that class, so no cast is needed.

Parameters

Returns T | null: If a script of the class is attached, the instance is returned. Otherwise null is returned.

Example

const controller = entity.script.get(PlayerController); // PlayerController | null
get(name: string): Script | null

Get a script instance (if attached) by its name.

Parameters

Returns Script | null: If a script with the name is attached, the instance is returned. Otherwise null is returned, including while a script declared by name is still awaiting its class to be added to the ScriptRegistry.

Example

const controller = entity.script.get('playerController');

has

has(nameOrType: string | typeof Script): boolean

Detect if script is attached to an entity.

Parameters

Returns boolean: If script is attached to an entity.

Example

if (entity.script.has('playerController')) {
    // entity has script
}

move

move(nameOrType: string | typeof Script, ind: number): boolean

Move script instance to different position to alter update order of scripts within entity.

Parameters

Returns boolean: If it was successfully moved.

Example

entity.script.move('playerController', 0);

Events

EVENT_CREATE

static EVENT_CREATE: string = 'create'

Fired when a Script instance is created and attached to the script component. This event is available in two forms. They are as follows:

  1. create - Fired when a script instance is created. The name of the script type and the script type instance are passed as arguments.
  2. create:[name] - Fired when a script instance is created that has the specified script type name. The script instance is passed as an argument to the handler.

Example

entity.script.on('create', (name, scriptInstance) => {
    console.log(`Instance of script '${name}' created`);
});

Example

entity.script.on('create:player', (scriptInstance) => {
    console.log(`Instance of script 'player' created`);
});

EVENT_DESTROY

static EVENT_DESTROY: string = 'destroy'

Fired when a Script instance is destroyed and removed from the script component. This event is available in two forms. They are as follows:

  1. destroy - Fired when a script instance is destroyed. The name of the script type and the script type instance are passed as arguments.
  2. destroy:[name] - Fired when a script instance is destroyed that has the specified script type name. The script instance is passed as an argument.

Example

entity.script.on('destroy', (name, scriptInstance) => {
    console.log(`Instance of script '${name}' destroyed`);
});

Example

entity.script.on('destroy:player', (scriptInstance) => {
    console.log(`Instance of script 'player' destroyed`);
});

EVENT_DISABLE

static EVENT_DISABLE: string = 'disable'

Fired when the script component becomes disabled. This event does not take into account the enabled state of the entity or any of its ancestors.

Example

entity.script.on('disable', () => {
    console.log(`Script component of entity '${entity.name}' has been disabled`);
});

EVENT_ENABLE

static EVENT_ENABLE: string = 'enable'

Fired when the script component becomes enabled. This event does not take into account the enabled state of the entity or any of its ancestors.

Example

entity.script.on('enable', () => {
    console.log(`Script component of entity '${entity.name}' has been enabled`);
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when a Script instance had an exception. The handler is passed the script instance, the exception and the method name that the exception originated from.

Example

entity.script.on('error', (scriptInstance, exception, methodName) => {
    console.log(`Script error: ${exception} in method '${methodName}'`);
});

EVENT_MOVE

static EVENT_MOVE: string = 'move'

Fired when the index of a Script instance is changed in the script component. This event is available in two forms. They are as follows:

  1. move - Fired when a script instance is moved. The name of the script type, the script type instance, the new index and the old index are passed as arguments.
  2. move:[name] - Fired when a specifically named script instance is moved. The script instance, the new index and the old index are passed as arguments.

Example

entity.script.on('move', (name, scriptInstance, newIndex, oldIndex) => {
    console.log(`Script '${name}' moved from index '${oldIndex}' to '${newIndex}'`);
});

Example

entity.script.on('move:player', (scriptInstance, newIndex, oldIndex) => {
    console.log(`Script 'player' moved from index '${oldIndex}' to '${newIndex}'`);
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when the script component has been removed from its entity.

Example

entity.script.on('remove', () => {
    console.log(`Script component removed from entity '${entity.name}'`);
});

EVENT_STATE

static EVENT_STATE: string = 'state'

Fired when the script component changes state to enabled or disabled. The handler is passed the new boolean enabled state of the script component. This event does not take into account the enabled state of the entity or any of its ancestors.

Example

entity.script.on('state', (enabled) => {
    console.log(`Script component of entity '${entity.name}' changed state to '${enabled}'`);
});

Inherited from Component

ScriptComponentSystem

Class · extends ComponentSystem · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/script/system.js#L43

Manages the ScriptComponents of an application. Reach it through app.systems.script; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ScriptRegistry

Class · extends EventHandler · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-registry.js#L19

Container for all Script classes that are available to this application. Note that PlayCanvas scripts can access the Script Registry from inside the application with AppBase#scripts.

Constructors

constructor

new ScriptRegistry(app: AppBase)

Create a new ScriptRegistry instance.

Parameters

Methods

add

add(script: typeof Script): boolean

Add a script to the registry, keyed by its name. The name is taken from the script's static scriptName property (for Script classes), or assigned by createScript / registerScript. Note: when createScript or registerScript is called, the script is added to the registry automatically, so calling this method directly is only required when registering a Script class manually (e.g. in an engine-only project).

If a script with the same name already exists in the registry, and the new script has a swap method defined, it will perform code hot swapping automatically in an async manner.

Parameters

Returns boolean: True if the script was added for the first time. False if a script with the same name already exists, or if the script has no resolvable name.

Example

var PlayerController = createScript('playerController');
// playerController Script Type will be added to ScriptRegistry automatically
console.log(app.scripts.has('playerController')); // outputs true

Example

// engine-only: register an ESM Script class manually
class Rotator extends Script {
    static scriptName = 'rotator';
}
app.scripts.add(Rotator);
console.log(app.scripts.has('rotator')); // outputs true

addSchema

addSchema(id: string, schema: AttributeSchema): void

Registers a schema against a script instance.

Parameters

get

get(name: string): typeof Script | null

Get a Script class by name.

Parameters

Returns typeof Script | null: The script class if it exists in the registry or null otherwise.

Example

var PlayerController = app.scripts.get('playerController');

getSchema

getSchema(id: string): AttributeSchema | undefined

Returns a schema for a given script name.

Parameters

Returns AttributeSchema | undefined: - The schema stored under the key

has

has(nameOrType: string | typeof Script): boolean

Check if a Script class with the specified name is in the registry.

Parameters

Returns boolean: True if the Script class is in the registry.

Example

if (app.scripts.has('playerController')) {
    // playerController is in ScriptRegistry
}

list

list(): typeof Script[]

Get list of all Script classes from registry.

Returns typeof Script[]: list of all Script classes in registry.

Example

// logs array of all Script Type names available in registry
console.log(app.scripts.list().map(function (o) {
    return o.name;
}));

remove

remove(nameOrType: string | typeof Script): boolean

Remove a Script class from the registry.

Parameters

Returns boolean: True if removed or False if already not in registry.

Example

app.scripts.remove('playerController');

Inherited from EventHandler

ScriptType

Class · extends Script · category: Script · deprecated

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-type.js#L16

This is the legacy format for creating a PlayCanvas script returned when calling createScript(). Do not inherit from this class directly.

Deprecated: Use Script instead.

Constructors

constructor

new ScriptType(args: object)

Create a new ScriptType instance.

Parameters

Accessors

attributes

static get attributes(): ScriptAttributes

The interface to define attributes for Script Types. Refer to ScriptAttributes.

Example

var PlayerController = createScript('playerController');

PlayerController.attributes.add('speed', {
    type: 'number',
    title: 'Speed',
    placeholder: 'km/h',
    default: 22.2
});

Methods

initScript

protected initScript(args: any): void

Parameters

initScriptType

protected initScriptType(args: any): void

Expose initScript as initScriptType for backwards compatibility

Parameters

extend

static extend(methods: any): void

Shorthand function to extend Script Type prototype with list of methods.

Parameters

Example

var PlayerController = createScript('playerController');

PlayerController.extend({
    initialize: function () {
        // called once on initialize
    },
    update: function (dt) {
        // called each tick
    }
});

Inherited from Script

createScript

Function · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-create.js#L48

createScript(name: string, app?: AppBase): typeof ScriptType | null

Create and register a new ScriptType. It returns new class type (constructor function), which is auto-registered to ScriptRegistry using its name. This is the main interface to create Script Types, to define custom logic using JavaScript, that is used to create interaction for entities.

Parameters

Returns typeof ScriptType | null: A class type (constructor function) that inherits ScriptType, which the developer is meant to further extend by adding attributes and prototype methods. Returns null if there was an error.

Example

var Turning = createScript('turn');

// define 'speed' attribute that is available in Editor UI
Turning.attributes.add('speed', {
    type: 'number',
    default: 180,
    placeholder: 'deg/s'
});

// runs every tick
Turning.prototype.update = function (dt) {
    this.entity.rotate(0, this.speed * dt, 0);
};

registerScript

Function · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-create.js#L113

registerScript(script: typeof ScriptType, name?: string, app?: AppBase): void

Register an existing class type as a Script Type with ScriptRegistry. Useful when defining an ES6 script class that extends ScriptType (see example).

Parameters

Example

// define an ES6 script class
class PlayerController extends ScriptType {

    initialize() {
        // called once on initialize
    }

    update(dt) {
        // called each tick
    }
}

// register the class as a script
registerScript(PlayerController);

// declare script attributes (Must be after registerScript())
PlayerController.attributes.add('attribute1', {type: 'number'});

script.createLoadingScreen

Function · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L47

createLoadingScreen(callback: CreateScreenCallback): void

Handles the creation of the loading screen of the application. A script can subscribe to the events of a AppBase to show a loading screen, progress bar etc. In order for this to work you need to set the project's loading screen script to the script that calls this method.

Parameters

Example

script.createLoadingScreen((app) => {
    const showSplashScreen = () => {};
    const hideSplashScreen = () => {};
    const showProgress = (progress) => {};
    app.on("preload:start", showSplashScreen);
    app.on("preload:progress", showProgress);
    app.on("start", hideSplashScreen);
});

script

Namespace · category: Script

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L25

The script namespace holds the createLoadingScreen function that is used to override the default PlayCanvas loading screen.

Members

AudioListenerComponent

Class · extends Component · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/audio-listener/component.js#L32

The AudioListenerComponent enables an Entity to represent the point from where positional SoundComponents are heard. This is typically the main camera Entity in your scene. And typically, you will only have one AudioListenerComponent in your scene.

You should never need to use the AudioListenerComponent constructor directly. To add a AudioListenerComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('audiolistener');

Once the AudioListenerComponent is added to the entity, you can access it via the Entity#audiolistener property:

entity.audiolistener.enabled = false; // Disable the audio listener

console.log(entity.audiolistener.enabled); // Get the enabled state and print it

Relevant Engine API examples:

Inherited from Component

AudioListenerComponentSystem

Class · extends ComponentSystem · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/audio-listener/system.js#L16

Manages the AudioListenerComponents of an application. Reach it through app.systems.audiolistener; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

Sound

Class · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/sound.js#L12

Represents the raw audio data of a playable sound. A Sound is the resource of an audio Asset. An audio asset can be assigned to a SoundSlot owned by a SoundComponent.

The buffer is the decoded Web Audio AudioBuffer, so duration is known as soon as the asset has loaded. Playing a sound creates one SoundInstance per playback, normally through a slot rather than by constructing the instance directly.

Constructors

constructor

new Sound(buffer: AudioBuffer)

Create a new Sound instance.

Parameters

Properties

buffer

buffer: AudioBuffer

Contains the decoded audio data.

Accessors

duration

get duration(): number

Gets the duration of the sound. If the sound is not loaded it returns 0.

SoundComponent

Class · extends Component · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/component.js#L56

The SoundComponent enables an Entity to play audio. The SoundComponent can manage multiple SoundSlots, each of which can play a different audio asset with its own set of properties such as volume, pitch, and looping behavior.

The SoundComponent supports positional audio, meaning that the sound can be played relative to the Entity's position in 3D space. This is useful for creating immersive audio experiences where the sound's volume and panning are affected by the listener's position and orientation. Positional audio requires that an Entity with an AudioListenerComponent be added to the scene.

You should never need to use the SoundComponent constructor directly. To add a SoundComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('sound', {
    volume: 0.8,
    positional: true
});

Once the SoundComponent is added to the entity, you can access it via the Entity#sound property:

entity.sound.volume = 0.9;  // Set the volume for all sounds

console.log(entity.sound.volume); // Get the volume and print it

Add individual sounds by creating sound slots on the component:

entity.sound.addSlot('beep', {
    asset: asset
});

Relevant Engine API examples:

Accessors

distanceModel

get distanceModel(): string
set distanceModel(value: string)

Gets which algorithm to use to reduce the volume of the sound as it moves away from the listener.

maxDistance

get maxDistance(): number
set maxDistance(value: number)

Gets the maximum distance from the listener at which audio falloff stops.

pitch

get pitch(): number
set pitch(value: number)

Gets the pitch modifier to play the audio with.

positional

get positional(): boolean
set positional(newValue: boolean)

Gets whether the component plays positional sound.

refDistance

get refDistance(): number
set refDistance(value: number)

Gets the reference distance for reducing volume as the sound source moves further from the listener.

rollOffFactor

get rollOffFactor(): number
set rollOffFactor(value: number)

Gets the factor used in the falloff equation.

slots

get slots(): Readonly<Record<string, SoundSlot>>
set slots(newValue: Readonly<Record<string, SoundSlot>>)

Gets a dictionary that contains the SoundSlots managed by this SoundComponent. Use addSlot and removeSlot to change slots.

volume

get volume(): number
set volume(value: number)

Gets the volume modifier to play the audio with.

Methods

addSlot

addSlot(name: string, options?: object): SoundSlot | null

Creates a new SoundSlot with the specified name.

Parameters

Returns SoundSlot | null: The new slot or null if the slot already exists.

Example

// get an asset by id
const asset = app.assets.get(10);
// add a slot
this.entity.sound.addSlot('beep', {
    asset: asset
});
// play
this.entity.sound.play('beep');

isLoaded

isLoaded(name: string): boolean

Returns true if the asset of the slot with the specified name is loaded..

Parameters

Returns boolean: True if the slot with the specified name exists and its asset is loaded.

isPaused

isPaused(name: string): boolean

Returns true if the slot with the specified name is currently paused.

Parameters

Returns boolean: True if the slot with the specified name exists and is currently paused.

isPlaying

isPlaying(name: string): boolean

Returns true if the slot with the specified name is currently playing.

Parameters

Returns boolean: True if the slot with the specified name exists and is currently playing.

isStopped

isStopped(name: string): boolean

Returns true if the slot with the specified name is currently stopped.

Parameters

Returns boolean: True if the slot with the specified name exists and is currently stopped.

pause

pause(name?: string): void

Pauses playback of the slot with the specified name. If the name is undefined then all slots currently played will be paused. The slots can be resumed by calling resume.

Parameters

Example

// pause all sounds
this.entity.sound.pause();
// pause a specific sound
this.entity.sound.pause('beep');

play

play(name: string): SoundInstance | null

Begins playing the sound slot with the specified name. The slot will restart playing if it is already playing unless the overlap field is true in which case a new sound will be created and played.

Parameters

Returns SoundInstance | null: The sound instance that will be played. Returns null if the component or its parent entity is disabled or if the SoundComponent has no slot with the specified name.

Example

// get asset by id
const asset = app.assets.get(10);
// create a slot and play it
this.entity.sound.addSlot('beep', {
    asset: asset
});
this.entity.sound.play('beep');

removeSlot

removeSlot(name: string): void

Removes the SoundSlot with the specified name.

Parameters

Example

// remove a slot called 'beep'
this.entity.sound.removeSlot('beep');

resume

resume(name?: string): void

Resumes playback of the sound slot with the specified name if it's paused. If no name is specified all slots will be resumed.

Parameters

Example

// resume all sounds
this.entity.sound.resume();
// resume a specific sound
this.entity.sound.resume('beep');

slot

slot(name: string): SoundSlot | undefined

Returns the slot with the specified name.

Parameters

Returns SoundSlot | undefined: The slot.

Example

// get a slot and set its volume
this.entity.sound.slot('beep').volume = 0.5;

stop

stop(name?: string): void

Stops playback of the sound slot with the specified name if it's paused. If no name is specified all slots will be stopped.

Parameters

Example

// stop all sounds
this.entity.sound.stop();
// stop a specific sound
this.entity.sound.stop('beep');

Events

EVENT_END

static EVENT_END: string = 'end'

Fired when a sound instance stops playing because it reached its end. The handler is passed the SoundSlot and the SoundInstance that ended.

Example

entity.sound.on('end', (slot, instance) => {
    console.log(`Sound ${slot.name} ended`);
});

EVENT_PAUSE

static EVENT_PAUSE: string = 'pause'

Fired when a sound instance is paused. The handler is passed the SoundSlot and the SoundInstance that was paused.

Example

entity.sound.on('pause', (slot, instance) => {
    console.log(`Sound ${slot.name} paused`);
});

EVENT_PLAY

static EVENT_PLAY: string = 'play'

Fired when a sound instance starts playing. The handler is passed the SoundSlot and the SoundInstance that started playing.

Example

entity.sound.on('play', (slot, instance) => {
    console.log(`Sound ${slot.name} started playing`);
});

EVENT_RESUME

static EVENT_RESUME: string = 'resume'

Fired when a sound instance is resumed. The handler is passed the SoundSlot and the SoundInstance that was resumed.

Example

entity.sound.on('resume', (slot, instance) => {
    console.log(`Sound ${slot.name} resumed`);
});

EVENT_STOP

static EVENT_STOP: string = 'stop'

Fired when a sound instance is stopped. The handler is passed the SoundSlot and the SoundInstance that was stopped.

Example

entity.sound.on('stop', (slot, instance) => {
    console.log(`Sound ${slot.name} stopped`);
});

Inherited from Component

SoundComponentSystem

Class · extends ComponentSystem · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/system.js#L42

Manages the SoundComponents of an application. Reach it through app.systems.sound; components are created with Entity#addComponent, never by calling the system directly.

Properties

manager

manager: SoundManager

Gets / sets the sound manager.

Accessors

context

get context(): AudioContext | null

Gets the AudioContext currently used by the sound manager.

volume

get volume(): number
set volume(volume: number)

Gets the volume for the entire Sound system.

Inherited from ComponentSystem

SoundInstance

Class · extends EventHandler · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/instance.js#L47

A SoundInstance plays a Sound.

One instance is one playback. It wraps an AudioBufferSourceNode, available as source once playing, with a gain for volume, and carries pitch, loop, startTime and duration to select the region of the sound it plays. play, pause, resume and stop drive it and fire the events of the same names, with end fired when playback finishes on its own; isPlaying, isPaused and isStopped report the state, and currentTime can be read or set to seek. Instances are normally created by SoundSlot#play on a SoundComponent, which returns the instance so a script can adjust or stop that one playback. setExternalNodes inserts Web Audio nodes such as filters between the source and the destination.

Example

const instance = entity.sound.play('engine');
instance.pitch = 1.5;
instance.once('end', () => console.log('finished'));

Constructors

constructor

new SoundInstance(manager: SoundManager, sound: Sound, options: object)

Create a new SoundInstance instance.

Parameters

Properties

source

source: AudioBufferSourceNode | null = null

Gets the source that plays the sound resource. Source is only available after calling play.

Accessors

currentTime

get currentTime(): number
set currentTime(value: number)

Gets the current time of the sound that is playing, relative to startTime.

duration

get duration(): number
set duration(value: number)

Gets the duration of the sound that the instance will play starting from startTime. The returned value is clamped to the time available after the normalized start time.

isPaused

get isPaused(): boolean

Gets whether the instance is currently paused.

isPlaying

get isPlaying(): boolean

Gets whether the instance is currently playing.

isStopped

get isStopped(): boolean

Gets whether the instance is currently stopped.

isSuspended

get isSuspended(): boolean

Gets whether the instance is currently suspended because the window is not focused.

loop

get loop(): boolean
set loop(value: boolean)

Gets whether the instance will restart when it finishes playing.

pitch

get pitch(): number
set pitch(pitch: number)

Gets the pitch modifier to play the sound with.

sound

get sound(): Sound
set sound(value: Sound)

Gets the sound resource that the instance will play.

startTime

get startTime(): number
set startTime(value: number)

Gets the start time from which the sound will start playing.

volume

get volume(): number
set volume(volume: number)

Gets the volume modifier to play the sound with. In range 0-1.

Methods

clearExternalNodes

clearExternalNodes(): void

Clears any external nodes set by setExternalNodes.

getExternalNodes

getExternalNodes(): AudioNode[]

Gets any external nodes set by setExternalNodes.

Returns AudioNode[]: Returns an array that contains the two nodes set by setExternalNodes.

pause

pause(): boolean

Pauses playback of sound. Call resume() to resume playback from the same position.

Returns boolean: Returns true if the sound was paused.

play

play(): boolean

Attempt to begin playback the sound. If the AudioContext is suspended, the audio will only start once it's resumed. If the sound is already playing, this will restart the sound.

Returns boolean: True if the sound was started immediately.

resume

resume(): boolean

Resumes playback of the sound. Playback resumes at the point that the audio was paused.

Returns boolean: Returns true if the sound was resumed.

setExternalNodes

setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void

Connects external Web Audio API nodes. You need to pass the first node of the node graph that you created externally and the last node of that graph. The first node will be connected to the audio source and the last node will be connected to the destination of the AudioContext (e.g. speakers). Requires Web Audio API support.

Parameters

Example

const context = app.systems.sound.context;
const analyzer = context.createAnalyzer();
const distortion = context.createWaveShaper();
const filter = context.createBiquadFilter();
analyzer.connect(distortion);
distortion.connect(filter);
instance.setExternalNodes(analyzer, filter);

stop

stop(): boolean

Stops playback of sound. Calling play() again will restart playback from the beginning of the sound.

Returns boolean: Returns true if the sound was stopped.

Events

EVENT_END

static EVENT_END: string = 'end'

Fired when the sound currently played by the instance ends.

Example

instance.on('end', () => {
    console.log('Instance ended');
});

EVENT_PAUSE

static EVENT_PAUSE: string = 'pause'

Fired when the instance is paused.

Example

instance.on('pause', () => {
    console.log('Instance paused');
});

EVENT_PLAY

static EVENT_PLAY: string = 'play'

Fired when the instance starts playing its source.

Example

instance.on('play', () => {
    console.log('Instance started playing');
});

EVENT_RESUME

static EVENT_RESUME: string = 'resume'

Fired when the instance is resumed.

Example

instance.on('resume', () => {
    console.log('Instance resumed');
});

EVENT_STOP

static EVENT_STOP: string = 'stop'

Fired when the instance is stopped.

Example

instance.on('stop', () => {
    console.log('Instance stopped');
});

Inherited from EventHandler

SoundInstance3d

Class · extends SoundInstance · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/instance3d.js#L26

A SoundInstance3d plays a Sound in 3D.

It is what a positional SoundComponent creates. The sound is placed at position and its volume falls off with distance from the AudioListenerComponent according to distanceModel, one of DISTANCE_LINEAR, DISTANCE_INVERSE and DISTANCE_EXPONENTIAL, shaped by refDistance, maxDistance and rollOffFactor. The owning slot keeps position in step with its entity, so these properties are usually set on the component rather than on each instance.

Constructors

constructor

new SoundInstance3d(manager: SoundManager, sound: Sound, options?: object)

Create a new SoundInstance3d instance.

Parameters

Accessors

distanceModel

get distanceModel(): string
set distanceModel(value: string)

Gets which algorithm to use to reduce the volume of the audio as it moves away from the listener.

maxDistance

get maxDistance(): number
set maxDistance(value: number)

Gets the maximum distance from the listener at which audio falloff stops.

position

get position(): Vec3
set position(value: Vec3)

Gets the position of the sound in 3D space.

refDistance

get refDistance(): number
set refDistance(value: number)

Gets the reference distance for reducing volume as the sound source moves further from the listener.

rollOffFactor

get rollOffFactor(): number
set rollOffFactor(value: number)

Gets the factor used in the falloff equation.

Inherited from SoundInstance

SoundManager

Class · extends EventHandler · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/manager.js#L26

The SoundManager is used to load and play audio. It also applies system-wide settings like global volume, suspend and resume.

There is one per application at app.soundManager. It owns the Web Audio context that every SoundInstance plays through and the listener from which positional sounds are heard, applies the master volume on top of each instance's own, and suspend and resume silence and restart all audio at once, for example when the page loses focus.

Constructors

constructor

new SoundManager()

Create a new SoundManager instance.

Properties

listener

listener: Listener

The listener associated with this manager.

Accessors

volume

get volume(): number
set volume(volume: number)

Gets the global volume for the manager.

Inherited from EventHandler

SoundSlot

Class · extends EventHandler · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sound/slot.js#L54

The SoundSlot controls the playback of SoundInstances. SoundSlots are managed by SoundComponents. To add and remove SoundSlots on a SoundComponent, use SoundComponent#addSlot and SoundComponent#removeSlot respectively.

A slot holds one audio asset and the settings applied to every instance it creates: volume, pitch, loop, startTime and duration, plus autoPlay to start as soon as the asset has loaded and overlap to let several instances play at once instead of stopping the previous one. play returns the new SoundInstance and instances lists those currently playing. The slot forwards the instances' play, pause, resume, stop and end events and fires load when its asset is ready.

Example

const slot = entity.sound.slot('footsteps');
slot.overlap = true;   // let quick steps overlap rather than cut each other off
slot.volume = 0.6;
slot.play();
@hideconstructor

Properties

instances

instances: SoundInstance[] = []

An array that contains all the SoundInstances currently being played by the slot.

name

name: string

The name of the slot.

Accessors

asset

get asset(): number | null
set asset(value: number | null)

Gets the asset id.

autoPlay

get autoPlay(): boolean
set autoPlay(value: boolean)

Gets whether the slot will begin playing as soon as it is loaded.

duration

get duration(): number
set duration(value: number)

Gets the duration of the sound that the slot will play starting from startTime. The returned value is clamped to the time available after the normalized start time.

isLoaded

get isLoaded(): boolean

Gets whether the asset of the slot is loaded.

isPaused

get isPaused(): boolean

Gets whether the slot is currently paused.

isPlaying

get isPlaying(): boolean

Gets whether the slot is currently playing.

isStopped

get isStopped(): boolean

Gets whether the slot is currently stopped.

loop

get loop(): boolean
set loop(value: boolean)

Gets whether the slot will restart when it finishes playing.

overlap

get overlap(): boolean
set overlap(value: boolean)

Gets whether the sounds played from this slot will be played independently of each other.

pitch

get pitch(): number
set pitch(value: number)

Gets the pitch modifier to play the sound with.

startTime

get startTime(): number
set startTime(value: number)

Gets the start time from which the sound will start playing.

volume

get volume(): number
set volume(value: number)

Gets the volume modifier to play the sound with.

Methods

clearExternalNodes

clearExternalNodes(): void

Clears any external nodes set by setExternalNodes.

getExternalNodes

getExternalNodes(): AudioNode[]

Gets an array that contains the two external nodes set by setExternalNodes.

Returns AudioNode[]: An array of 2 elements that contains the first and last nodes set by setExternalNodes.

load

load(): void

Loads the asset assigned to this slot.

pause

pause(): boolean

Pauses all sound instances. To continue playback call resume.

Returns boolean: True if the sound instances paused successfully, false otherwise.

play

play(): SoundInstance

Plays a sound. If overlap is true the new sound instance will be played independently of any other instances already playing. Otherwise existing sound instances will stop before playing the new sound.

Returns SoundInstance: The new sound instance.

resume

resume(): boolean

Resumes playback of all paused sound instances.

Returns boolean: True if any instances were resumed.

setExternalNodes

setExternalNodes(firstNode: AudioNode, lastNode?: AudioNode): void

Connect external Web Audio API nodes. Any sound played by this slot will automatically attach the specified nodes to the source that plays the sound. You need to pass the first node of the node graph that you created externally and the last node of that graph. The first node will be connected to the audio source and the last node will be connected to the destination of the AudioContext (e.g. speakers).

Parameters

Example

const context = app.systems.sound.context;
const analyzer = context.createAnalyzer();
const distortion = context.createWaveShaper();
const filter = context.createBiquadFilter();
analyzer.connect(distortion);
distortion.connect(filter);
slot.setExternalNodes(analyzer, filter);

stop

stop(): boolean

Stops playback of all sound instances.

Returns boolean: True if any instances were stopped.

Events

EVENT_END

static EVENT_END: string = 'end'

Fired when a sound instance stops playing because it reached its end. The handler is passed the SoundInstance that ended.

Example

slot.on('end', (instance) => {
    console.log('Sound instance playback ended');
});

EVENT_LOAD

static EVENT_LOAD: string = 'load'

Fired when the sound Asset assigned to the slot is loaded. The handler is passed the loaded Sound resource.

Example

slot.on('load', (sound) => {
    console.log('Sound resource loaded');
});

EVENT_PAUSE

static EVENT_PAUSE: string = 'pause'

Fired when a SoundInstance is paused on a slot. The handler is passed the sound instance that is paused.

Example

slot.on('pause', (instance) => {
    console.log('Sound instance paused');
});

EVENT_PLAY

static EVENT_PLAY: string = 'play'

Fired when a SoundInstance starts playing on a slot. The handler is passed the sound instance that started playing.

Example

slot.on('play', (instance) => {
    console.log('Sound instance started playing');
});

EVENT_RESUME

static EVENT_RESUME: string = 'resume'

Fired when a SoundInstance is resumed on a slot. The handler is passed the sound instance that is resumed.

Example

slot.on('resume', (instance) => {
    console.log('Sound instance resumed');
});

EVENT_STOP

static EVENT_STOP: string = 'stop'

Fired when a SoundInstance is stopped on a slot. The handler is passed the sound instance that is stopped.

Example

slot.on('stop', (instance) => {
    console.log('Sound instance stopped');
});

Inherited from EventHandler

ButtonComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/component.js#L82

The ButtonComponent enables an Entity to behave like a button, with different visual states for hover and press interactions. It is designed to be used together with an ElementComponent on the same entity, which provides the button's visual appearance and input hit area. Set imageEntity, usually to the button's own entity, to choose the element that is tinted, or has its sprite changed, for each visual state.

You should never need to use the ButtonComponent constructor directly. To add a ButtonComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('element', {
    type: ELEMENTTYPE_IMAGE,
    useInput: true
});
entity.addComponent('button', {
    imageEntity: entity
});

Once the ButtonComponent is added to the entity, you can access it via the Entity#button property:

entity.button.hoverTint = Color.YELLOW; // Set the hover tint color

console.log(entity.button.hoverTint);      // Get the hover tint color and print it

Relevant Engine API examples:

Accessors

active

get active(): boolean
set active(arg: boolean)

Gets the button's active state.

fadeDuration

get fadeDuration(): number
set fadeDuration(arg: number)

Gets the duration to be used when fading between tints, in milliseconds.

hitPadding

get hitPadding(): Vec4
set hitPadding(arg: Vec4)

Gets the padding to be used in hit-test calculations.

hoverSpriteAsset

get hoverSpriteAsset(): Asset<string> | null
set hoverSpriteAsset(arg: Asset<string> | null)

Gets the sprite to be used as the button image when the user hovers over it.

hoverSpriteFrame

get hoverSpriteFrame(): number
set hoverSpriteFrame(arg: number)

Gets the frame to be used from the hover sprite.

hoverTint

get hoverTint(): Color
set hoverTint(arg: Color)

Gets the tint color to be used on the button image when the user hovers over it.

imageEntity

get imageEntity(): Entity | null
set imageEntity(arg: Entity | null)

Gets the entity to be used as the button background.

inactiveSpriteAsset

get inactiveSpriteAsset(): Asset<string> | null
set inactiveSpriteAsset(arg: Asset<string> | null)

Gets the sprite to be used as the button image when the button is not interactive.

inactiveSpriteFrame

get inactiveSpriteFrame(): number
set inactiveSpriteFrame(arg: number)

Gets the frame to be used from the inactive sprite.

inactiveTint

get inactiveTint(): Color
set inactiveTint(arg: Color)

Gets the tint color to be used on the button image when the button is not interactive.

pressedSpriteAsset

get pressedSpriteAsset(): Asset<string> | null
set pressedSpriteAsset(arg: Asset<string> | null)

Gets the sprite to be used as the button image when the user presses it.

pressedSpriteFrame

get pressedSpriteFrame(): number
set pressedSpriteFrame(arg: number)

Gets the frame to be used from the pressed sprite.

pressedTint

get pressedTint(): Color
set pressedTint(arg: Color)

Gets the tint color to be used on the button image when the user presses it.

transitionMode

get transitionMode(): number
set transitionMode(arg: number)

Gets the button transition mode.

Events

EVENT_CLICK

static EVENT_CLICK: string = 'click'

Fired when the mouse is pressed and released on the component or when a touch starts and ends on the component. The handler is passed a ElementMouseEvent or ElementTouchEvent.

Example

entity.button.on('click', (event) => {
    console.log(`Clicked entity ${entity.name}`);
});

EVENT_HOVEREND

static EVENT_HOVEREND: string = 'hoverend'

Fired when the button changes state to be not hovered.

Example

entity.button.on('hoverend', () => {
    console.log(`Entity ${entity.name} unhovered`);
});

EVENT_HOVERSTART

static EVENT_HOVERSTART: string = 'hoverstart'

Fired when the button changes state to be hovered.

Example

entity.button.on('hoverstart', () => {
    console.log(`Entity ${entity.name} hovered`);
});

EVENT_MOUSEDOWN

static EVENT_MOUSEDOWN: string = 'mousedown'

Fired when the mouse is pressed while the cursor is on the component. The handler is passed a ElementMouseEvent.

Example

entity.button.on('mousedown', (event) => {
    console.log(`Mouse down on entity ${entity.name}`);
});

EVENT_MOUSEENTER

static EVENT_MOUSEENTER: string = 'mouseenter'

Fired when the mouse cursor enters the component. The handler is passed a ElementMouseEvent.

Example

entity.button.on('mouseenter', (event) => {
    console.log(`Mouse entered entity ${entity.name}`);
});

EVENT_MOUSELEAVE

static EVENT_MOUSELEAVE: string = 'mouseleave'

Fired when the mouse cursor leaves the component. The handler is passed a ElementMouseEvent.

Example

entity.button.on('mouseleave', (event) => {
    console.log(`Mouse left entity ${entity.name}`);
});

EVENT_MOUSEUP

static EVENT_MOUSEUP: string = 'mouseup'

Fired when the mouse is released while the cursor is on the component. The handler is passed a ElementMouseEvent.

Example

entity.button.on('mouseup', (event) => {
    console.log(`Mouse up on entity ${entity.name}`);
});

EVENT_PRESSEDEND

static EVENT_PRESSEDEND: string = 'pressedend'

Fired when the button changes state to be not pressed.

Example

entity.button.on('pressedend', () => {
    console.log(`Entity ${entity.name} unpressed`);
});

EVENT_PRESSEDSTART

static EVENT_PRESSEDSTART: string = 'pressedstart'

Fired when the button changes state to be pressed.

Example

entity.button.on('pressedstart', () => {
    console.log(`Entity ${entity.name} pressed`);
});

EVENT_SELECTEND

static EVENT_SELECTEND: string = 'selectend'

Fired when a xr select ends on the component. The handler is passed a ElementSelectEvent.

Example

entity.button.on('selectend', (event) => {
    console.log(`Select ended on entity ${entity.name}`);
});

EVENT_SELECTENTER

static EVENT_SELECTENTER: string = 'selectenter'

Fired when a xr select now hovering over the component. The handler is passed a ElementSelectEvent.

Example

entity.button.on('selectenter', (event) => {
    console.log(`Select entered entity ${entity.name}`);
});

EVENT_SELECTLEAVE

static EVENT_SELECTLEAVE: string = 'selectleave'

Fired when a xr select not hovering over the component. The handler is passed a ElementSelectEvent.

Example

entity.button.on('selectleave', (event) => {
    console.log(`Select left entity ${entity.name}`);
});

EVENT_SELECTSTART

static EVENT_SELECTSTART: string = 'selectstart'

Fired when a xr select starts on the component. The handler is passed a ElementSelectEvent.

Example

entity.button.on('selectstart', (event) => {
    console.log(`Select started on entity ${entity.name}`);
});

EVENT_TOUCHCANCEL

static EVENT_TOUCHCANCEL: string = 'touchcancel'

Fired when a touch is canceled on the component. The handler is passed a ElementTouchEvent.

Example

entity.button.on('touchcancel', (event) => {
    console.log(`Touch canceled on entity ${entity.name}`);
});

EVENT_TOUCHEND

static EVENT_TOUCHEND: string = 'touchend'

Fired when a touch ends on the component. The handler is passed a ElementTouchEvent.

Example

entity.button.on('touchend', (event) => {
    console.log(`Touch ended on entity ${entity.name}`);
});

EVENT_TOUCHLEAVE

static EVENT_TOUCHLEAVE: string = 'touchleave'

Fired when a touch leaves the component. The handler is passed a ElementTouchEvent.

Example

entity.button.on('touchleave', (event) => {
    console.log(`Touch left entity ${entity.name}`);
});

EVENT_TOUCHSTART

static EVENT_TOUCHSTART: string = 'touchstart'

Fired when a touch starts on the component. The handler is passed a ElementTouchEvent.

Example

entity.button.on('touchstart', (event) => {
    console.log(`Touch started on entity ${entity.name}`);
});

Inherited from Component

ButtonComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/system.js#L45

Manages the ButtonComponents of an application. Reach it through app.systems.button; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ElementComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/component.js#L100

ElementComponents are used to construct user interfaces. The type property can be configured in 3 main ways: as a text element, as an image element or as a group element. If the ElementComponent has a ScreenComponent ancestor in the hierarchy, it will be transformed with respect to the coordinate system of the screen. If there is no ScreenComponent ancestor, the ElementComponent will be transformed like any other entity.

You should never need to use the ElementComponent constructor directly. To add an ElementComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('element'); // This defaults to a 'group' element

To create a simple text-based element:

entity.addComponent('element', {
    anchor: new Vec4(0.5, 0.5, 0.5, 0.5), // centered anchor
    fontAsset: fontAsset,
    fontSize: 128,
    pivot: new Vec2(0.5, 0.5),            // centered pivot
    text: 'Hello World!',
    type: ELEMENTTYPE_TEXT
});

Once the ElementComponent is added to the entity, you can access it via the Entity#element property:

entity.element.color = Color.RED; // Set the element's color to red

console.log(entity.element.color);   // Get the element's color and print it

Relevant Engine API examples:

Properties

screen

screen: Entity | null

The Entity with a ScreenComponent that this component belongs to. This is automatically set when the component is a child of a ScreenComponent.

Accessors

aabb

get aabb(): BoundingBox | null

Gets the world space axis-aligned bounding box for this element component.

alignment

get alignment(): Vec2
set alignment(arg: Vec2)

Gets the horizontal and vertical alignment of the text.

anchor

get anchor(): Readonly<Vec4>
set anchor(value: Readonly<Vec4>)

Gets the anchor for this element component. Use the setter to update the anchor.

autoFitHeight

get autoFitHeight(): boolean
set autoFitHeight(arg: boolean)

Gets whether the font size and line height will scale so that the text fits inside the height of the Element.

autoFitWidth

get autoFitWidth(): boolean
set autoFitWidth(arg: boolean)

Gets whether the font size and line height will scale so that the text fits inside the width of the Element.

autoHeight

get autoHeight(): boolean
set autoHeight(arg: boolean)

Gets whether to automatically set the height of the component to be the same as the textHeight.

autoWidth

get autoWidth(): boolean
set autoWidth(arg: boolean)

Gets whether to automatically set the width of the component to be the same as the textWidth.

batchGroupId

get batchGroupId(): number
set batchGroupId(value: number)

Gets the batch group (see BatchGroup) for this element.

bottom

get bottom(): number
set bottom(value: number)

Gets the distance from the bottom edge of the anchor.

calculatedHeight

get calculatedHeight(): number
set calculatedHeight(value: number)

Gets the height at which the element will be rendered.

calculatedWidth

get calculatedWidth(): number
set calculatedWidth(value: number)

Gets the width at which the element will be rendered.

canvasCorners

get canvasCorners(): Vec2[]

Gets the array of 4 Vec2s that represent the bottom left, bottom right, top right and top left corners of the component in canvas pixels. Only works for screen space element components.

color

get color(): Readonly<Color>
set color(arg: Readonly<Color>)

Gets the color of the element. Use the setter to update the color.

drawOrder

get drawOrder(): number
set drawOrder(value: number)

Gets the draw order of the component.

enableMarkup

get enableMarkup(): boolean
set enableMarkup(arg: boolean)

Gets whether markup processing is enabled for this element.

fitMode

get fitMode(): string
set fitMode(value: string)

Gets the fit mode of the element.

font

get font(): Font | CanvasFont
set font(arg: Font | CanvasFont)

Gets the font used for rendering the text.

fontAsset

get fontAsset(): number | Asset<string> | null
set fontAsset(arg: number | Asset<string> | null)

Gets the id of the font asset used for rendering the text.

fontSize

get fontSize(): number
set fontSize(arg: number)

Gets the size of the font.

height

get height(): number
set height(value: number)

Gets the height of the element.

justify

get justify(): boolean
set justify(arg: boolean)

Gets whether wrapped lines are stretched to be flush with both edges of the element.

key

get key(): string
set key(arg: string)

Gets the localization key to use to get the localized text from Application#i18n.

layers

get layers(): readonly number[]
set layers(value: readonly number[])

Gets the array of layer IDs (Layer#id) to which this element belongs.

left

get left(): number
set left(value: number)

Gets the distance from the left edge of the anchor.

lineHeight

get lineHeight(): number
set lineHeight(arg: number)

Gets the height of each line of text.

lines

get lines(): string[]

Gets the lines of rendered text, split by line breaks and word wrapping. Only works for ELEMENTTYPE_TEXT elements, and is populated when the text is laid out, so it reads as undefined until the first update.

margin

get margin(): Readonly<Vec4>
set margin(value: Readonly<Vec4>)

Gets the distance from the left, bottom, right and top edges of the anchor. Use the setter to update the margin.

mask

get mask(): boolean
set mask(arg: boolean)

Gets whether the Image Element should be treated as a mask.

material

get material(): Material
set material(arg: Material)

Gets the material to use when rendering an image.

materialAsset

get materialAsset(): number | Asset<string> | null
set materialAsset(arg: number | Asset<string> | null)

Gets the id of the material asset to use when rendering an image.

maxFontSize

get maxFontSize(): number
set maxFontSize(arg: number)

Gets the maximum size that the font can scale to when autoFitWidth or autoFitHeight are true.

maxLines

get maxLines(): number | null
set maxLines(arg: number | null)

Gets the maximum number of lines that the Element can wrap to. Returns -1 if there is no limit.

minFontSize

get minFontSize(): number
set minFontSize(arg: number)

Gets the minimum size that the font can scale to when autoFitWidth or autoFitHeight are true.

opacity

get opacity(): number
set opacity(arg: number)

Gets the opacity of the element.

outlineColor

get outlineColor(): Color
set outlineColor(arg: Color)

Gets the text outline effect color and opacity.

outlineThickness

get outlineThickness(): number
set outlineThickness(arg: number)

Gets the width of the text outline effect.

pivot

get pivot(): Readonly<Vec2>
set pivot(value: Readonly<Vec2>)

Gets the position of the pivot of the component relative to its anchor. Use the setter to update the pivot.

pixelsPerUnit

get pixelsPerUnit(): number | null
set pixelsPerUnit(arg: number | null)

Gets the number of pixels that map to one PlayCanvas unit.

rangeEnd

get rangeEnd(): number
set rangeEnd(arg: number)

Gets the index of the last character to render.

rangeStart

get rangeStart(): number
set rangeStart(arg: number)

Gets the index of the first character to render.

rect

get rect(): Readonly<Vec4> | null
set rect(arg: Readonly<Vec4> | null)

Gets the region of the texture to use in order to render an image. Use the setter to update the region.

right

get right(): number
set right(value: number)

Gets the distance from the right edge of the anchor.

rtlReorder

get rtlReorder(): boolean
set rtlReorder(arg: boolean)

Gets whether to reorder the text for RTL languages.

screenCorners

get screenCorners(): Vec3[]

Gets the array of 4 Vec3s that represent the bottom left, bottom right, top right and top left corners of the component relative to its parent ScreenComponent.

shadowColor

get shadowColor(): Color
set shadowColor(arg: Color)

Gets the text shadow effect color and opacity.

shadowOffset

get shadowOffset(): Vec2
set shadowOffset(arg: Vec2)

Gets the offset of the text shadow, relative to the text.

spacing

get spacing(): number
set spacing(arg: number)

Gets the spacing between the letters of the text.

sprite

get sprite(): Sprite
set sprite(arg: Sprite)

Gets the sprite to render.

spriteAsset

get spriteAsset(): number | Asset<string> | null
set spriteAsset(arg: number | Asset<string> | null)

Gets the id of the sprite asset to render.

spriteFrame

get spriteFrame(): number
set spriteFrame(arg: number)

Gets the frame of the sprite to render.

text

get text(): string
set text(arg: string)

Gets the text to render.

textHeight

get textHeight(): number

Gets the height of the text rendered by the component. Only works for ELEMENTTYPE_TEXT elements.

texture

get texture(): Texture
set texture(arg: Texture)

Gets the texture to render.

textureAsset

get textureAsset(): number | Asset<string> | null
set textureAsset(arg: number | Asset<string> | null)

Gets the id of the texture asset to render.

textWidth

get textWidth(): number

Gets the width of the text rendered by the component. Only works for ELEMENTTYPE_TEXT elements.

top

get top(): number
set top(value: number)

Gets the distance from the top edge of the anchor.

type

get type(): string
set type(value: string)

Gets the type of the ElementComponent.

unicodeConverter

get unicodeConverter(): boolean
set unicodeConverter(arg: boolean)

Gets whether to convert unicode characters.

useInput

get useInput(): boolean
set useInput(value: boolean)

Gets whether the component will receive mouse and touch input events.

width

get width(): number
set width(value: number)

Gets the width of the element.

worldCorners

get worldCorners(): Vec3[]

Gets the array of 4 Vec3s that represent the bottom left, bottom right, top right and top left corners of the component in world space. Only works for 3D element components.

wrapLines

get wrapLines(): boolean
set wrapLines(arg: boolean)

Gets whether to automatically wrap lines based on the element width.

Events

EVENT_CLICK

static EVENT_CLICK: string = 'click'

Fired when the mouse is pressed and released on the component, when a touch starts and ends on the component, or when an XR input source starts and ends a select action on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent, ElementTouchEvent or ElementSelectEvent.

Example

entity.element.on('click', (event) => {
    console.log(`Click event on entity ${entity.name}`);
});

EVENT_MOUSEDOWN

static EVENT_MOUSEDOWN: string = 'mousedown'

Fired when the mouse is pressed while the cursor is on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mousedown', (event) => {
    console.log(`Mouse down event on entity ${entity.name}`);
});

EVENT_MOUSEENTER

static EVENT_MOUSEENTER: string = 'mouseenter'

Fired when the mouse cursor enters the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mouseenter', (event) => {
    console.log(`Mouse enter event on entity ${entity.name}`);
});

EVENT_MOUSELEAVE

static EVENT_MOUSELEAVE: string = 'mouseleave'

Fired when the mouse cursor leaves the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mouseleave', (event) => {
    console.log(`Mouse leave event on entity ${entity.name}`);
});

EVENT_MOUSEMOVE

static EVENT_MOUSEMOVE: string = 'mousemove'

Fired when the mouse cursor is moved on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mousemove', (event) => {
    console.log(`Mouse move event on entity ${entity.name}`);
});

EVENT_MOUSEUP

static EVENT_MOUSEUP: string = 'mouseup'

Fired when the mouse is released while the cursor is on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mouseup', (event) => {
    console.log(`Mouse up event on entity ${entity.name}`);
});

EVENT_MOUSEWHEEL

static EVENT_MOUSEWHEEL: string = 'mousewheel'

Fired when the mouse wheel is scrolled on the component. Only fired when useInput is true. The handler is passed an ElementMouseEvent.

Example

entity.element.on('mousewheel', (event) => {
    console.log(`Mouse wheel event on entity ${entity.name}`);
});

EVENT_SELECTEND

static EVENT_SELECTEND: string = 'selectend'

Fired when an XR input source ends a select action that started on the component, even if its ray no longer points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.

Example

entity.element.on('selectend', (event) => {
    console.log(`Select end event on entity ${entity.name}`);
});

EVENT_SELECTENTER

static EVENT_SELECTENTER: string = 'selectenter'

Fired when the ray of an XR input source starts pointing at the component. Only fired when useInput is true and the input source's XrInputSource#elementInput is true. The handler is passed an ElementSelectEvent.

Example

entity.element.on('selectenter', (event) => {
    console.log(`Select enter event on entity ${entity.name}`);
});

EVENT_SELECTLEAVE

static EVENT_SELECTLEAVE: string = 'selectleave'

Fired when the ray of an XR input source stops pointing at the component, or when the input source is removed while its ray points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.

Example

entity.element.on('selectleave', (event) => {
    console.log(`Select leave event on entity ${entity.name}`);
});

EVENT_SELECTMOVE

static EVENT_SELECTMOVE: string = 'selectmove'

Fired every XR frame while an XR input source holds a select action that started on the component, even if its ray no longer points at the component. Only fired when useInput is true. The handler is passed an ElementSelectEvent.

Example

entity.element.on('selectmove', (event) => {
    console.log(`Select move event on entity ${entity.name}`);
});

EVENT_SELECTSTART

static EVENT_SELECTSTART: string = 'selectstart'

Fired when an XR input source starts a select action, such as pulling a controller trigger or pinching, while its ray points at the component. Only fired when useInput is true and the input source's XrInputSource#elementInput is true. The handler is passed an ElementSelectEvent.

Example

entity.element.on('selectstart', (event) => {
    console.log(`Select start event on entity ${entity.name}`);
});

EVENT_TOUCHCANCEL

static EVENT_TOUCHCANCEL: string = 'touchcancel'

Fired when a touch is canceled on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.

Example

entity.element.on('touchcancel', (event) => {
    console.log(`Touch cancel event on entity ${entity.name}`);
});

EVENT_TOUCHEND

static EVENT_TOUCHEND: string = 'touchend'

Fired when a touch ends on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.

Example

entity.element.on('touchend', (event) => {
    console.log(`Touch end event on entity ${entity.name}`);
});

EVENT_TOUCHMOVE

static EVENT_TOUCHMOVE: string = 'touchmove'

Fired when a touch moves after it started touching the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.

Example

entity.element.on('touchmove', (event) => {
    console.log(`Touch move event on entity ${entity.name}`);
});

EVENT_TOUCHSTART

static EVENT_TOUCHSTART: string = 'touchstart'

Fired when a touch starts on the component. Only fired when useInput is true. The handler is passed an ElementTouchEvent.

Example

entity.element.on('touchstart', (event) => {
    console.log(`Touch start event on entity ${entity.name}`);
});

Inherited from Component

ElementComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/system.js#L43

Manages the ElementComponents of an application. Reach it through app.systems.element; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ElementDragHelper

Class · extends EventHandler · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/element-drag-helper.js#L36

Helper class that makes it easy to create Elements that can be dragged by the mouse or touch.

Relevant Engine API examples:

Constructors

constructor

new ElementDragHelper(element: ElementComponent, axis?: string)

Create a new ElementDragHelper instance.

Parameters

Events

EVENT_DRAGEND

static EVENT_DRAGEND: string = 'drag:end'

Fired when the current new drag operation ends.

Example

elementDragHelper.on('drag:end', () => {
    console.log('Drag ended');
});

EVENT_DRAGMOVE

static EVENT_DRAGMOVE: string = 'drag:move'

Fired whenever the position of the dragged element changes. The handler is passed the current Vec3 position of the dragged element.

Example

elementDragHelper.on('drag:move', (position) => {
    console.log(`Dragged element position is ${position}`);
});

EVENT_DRAGSTART

static EVENT_DRAGSTART: string = 'drag:start'

Fired when a new drag operation starts.

Example

elementDragHelper.on('drag:start', () => {
    console.log('Drag started');
});

Inherited from EventHandler

ElementInput

Class · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L356

Handles mouse and touch events for ElementComponents. When input events occur on an ElementComponent this fires the appropriate events on the ElementComponent.

Relevant Engine API examples:

Constructors

constructor

new ElementInput(domElement: Element, options?: object)

Create a new ElementInput instance.

Parameters

Methods

addElement

addElement(element: ElementComponent): void

Add a ElementComponent to the internal list of ElementComponents that are being checked for input.

Parameters

attach

attach(domElement: Element): void

Attach mouse and touch events to a DOM element.

Parameters

detach

detach(): void

Remove mouse and touch events from the DOM element that it is attached to.

removeElement

removeElement(element: ElementComponent): void

Remove a ElementComponent from the internal list of ElementComponents that are being checked for input.

Parameters

ElementInputEvent

Class · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L124

Represents an input event fired on a ElementComponent. When an event is raised on an ElementComponent it bubbles up to its parent ElementComponents unless we call stopPropagation().

Constructors

constructor

new ElementInputEvent(event: MouseEvent | TouchEvent | XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent)

Create a new ElementInputEvent instance.

Parameters

Properties

camera

camera: CameraComponent

The CameraComponent that this event was originally raised via.

element

element: ElementComponent

The ElementComponent that this event was originally raised on.

event

event: MouseEvent | TouchEvent | XRInputSourceEvent | null

The browser event that was originally raised: a MouseEvent, TouchEvent or XRInputSourceEvent. It is null when no browser event caused this one, as for selectmove.

Methods

stopPropagation

stopPropagation(): void

Stop propagation of the event to parent ElementComponents. This also stops propagation of the event to other event listeners of the original DOM Event.

ElementMouseEvent

Class · extends ElementInputEvent · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L180

Represents a Mouse event fired on a ElementComponent.

Constructors

constructor

new ElementMouseEvent(event: MouseEvent | WheelEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, lastX: number, lastY: number)

Create an instance of an ElementMouseEvent.

Parameters

Properties

altKey

altKey: boolean

Whether the alt key was pressed.

button

button: number

The mouse button.

ctrlKey

ctrlKey: boolean

Whether the ctrl key was pressed.

dx

dx: number

The amount of horizontal movement of the cursor.

dy

dy: number

The amount of vertical movement of the cursor.

metaKey

metaKey: boolean

Whether the meta key was pressed.

shiftKey

shiftKey: boolean

Whether the shift key was pressed.

wheelDelta

wheelDelta: number

The amount of the wheel movement.

Inherited from ElementInputEvent

ElementSelectEvent

Class · extends ElementInputEvent · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L321

Represents a XRInputSourceEvent fired on a ElementComponent.

Constructors

constructor

new ElementSelectEvent(event: XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent, inputSource: XrInputSource)

Create an instance of an ElementSelectEvent.

Parameters

Properties

inputSource

inputSource: XrInputSource

The XR input source that this event was originally raised from.

Inherited from ElementInputEvent

ElementTouchEvent

Class · extends ElementInputEvent · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/input/element-input.js#L274

Represents a TouchEvent fired on a ElementComponent. It carries the browser's own TouchEvent and Touch objects.

Constructors

constructor

new ElementTouchEvent(event: TouchEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, touch: Touch)

Create an instance of an ElementTouchEvent.

Parameters

Properties

changedTouches

changedTouches: TouchList

The Touch objects representing individual points of contact whose states changed between the previous touch event and this one.

touch

touch: Touch

The browser Touch that triggered the event. Match a touch across events by its identifier.

touches

touches: TouchList

The Touch objects representing all current points of contact with the surface, regardless of target or changed status.

Inherited from ElementInputEvent

Font

Class · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/font/font.js#L13

Represents the resource of a font asset.

Constructors

constructor

new Font(textures: Texture[], data: any)

Create a new Font instance.

Parameters

Properties

intensity

intensity: number

The font intensity.

textures

textures: Texture[]

The font textures.

Methods

destroy

destroy(): void

Frees the GPU textures owned by the font and removes them from the resource loader cache. Called automatically when the owning font asset is unloaded (see Asset#unload).

LayoutChildComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-child/component.js#L35

The LayoutChildComponent enables an Entity to control the sizing and fitting behavior applied to it by its parent LayoutGroupComponent. It allows per-child overrides of minimum and maximum dimensions as well as fit proportions.

You should never need to use the LayoutChildComponent constructor directly. To add a LayoutChildComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('element', {
    type: ELEMENTTYPE_IMAGE
});
entity.addComponent('layoutchild', {
    minWidth: 50,
    maxWidth: 200,
    fitWidthProportion: 1
});

Once the LayoutChildComponent is added to the entity, you can access it via the Entity#layoutchild property:

entity.layoutchild.minWidth = 80; // Increase the minimum width

console.log(entity.layoutchild.minWidth); // Get the minimum width and print it

Accessors

excludeFromLayout

get excludeFromLayout(): boolean
set excludeFromLayout(value: boolean)

Gets whether the child will be excluded from all layout calculations.

fitHeightProportion

get fitHeightProportion(): number
set fitHeightProportion(value: number)

Gets the amount of additional vertical space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation.

fitWidthProportion

get fitWidthProportion(): number
set fitWidthProportion(value: number)

Gets the amount of additional horizontal space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation.

maxHeight

get maxHeight(): number | null
set maxHeight(value: number | null)

Gets the maximum height the element should be rendered at.

maxWidth

get maxWidth(): number | null
set maxWidth(value: number | null)

Gets the maximum width the element should be rendered at.

minHeight

get minHeight(): number
set minHeight(value: number)

Gets the minimum height the element should be rendered at.

minWidth

get minWidth(): number
set minWidth(value: number)

Gets the minimum width the element should be rendered at.

Inherited from Component

LayoutChildComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-child/system.js#L15

Manages the LayoutChildComponents of an application. Reach it through app.systems.layoutchild; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

LayoutGroupComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/component.js#L57

The LayoutGroupComponent enables an Entity to position and scale its child ElementComponents according to configurable layout rules. It supports horizontal and vertical orientations and a variety of alignment, spacing, wrapping and sizing options.

You should never need to use the LayoutGroupComponent constructor directly. To add a LayoutGroupComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('element', {
    type: ELEMENTTYPE_GROUP
});
entity.addComponent('layoutgroup', {
    orientation: ORIENTATION_HORIZONTAL,
    spacing: new Vec2(10, 0)
});

Once the LayoutGroupComponent is added to the entity, you can access it via the Entity#layoutgroup property:

entity.layoutgroup.spacing = new Vec2(20, 0); // Increase spacing between children

console.log(entity.layoutgroup.spacing);         // Get the spacing and print it

Relevant Engine API examples:

Accessors

alignment

get alignment(): Vec2
set alignment(value: Vec2)

Gets the horizontal and vertical alignment of child elements.

heightFitting

get heightFitting(): number
set heightFitting(value: number)

Gets the height fitting mode to be applied when positioning and scaling child elements.

orientation

get orientation(): number
set orientation(value: number)

Gets whether the layout should run horizontally or vertically.

padding

get padding(): Vec4
set padding(value: Vec4)

Gets the padding to be applied inside the container before positioning any children.

reverseX

get reverseX(): boolean
set reverseX(value: boolean)

Gets whether to reverse the order of children along the x axis.

reverseY

get reverseY(): boolean
set reverseY(value: boolean)

Gets whether to reverse the order of children along the y axis.

spacing

get spacing(): Vec2
set spacing(value: Vec2)

Gets the spacing to be applied between each child element.

widthFitting

get widthFitting(): number
set widthFitting(value: number)

Gets the width fitting mode to be applied when positioning and scaling child elements.

wrap

get wrap(): boolean
set wrap(value: boolean)

Gets whether or not to wrap children onto a new row/column when the size of the container is exceeded.

Inherited from Component

LayoutGroupComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/system.js#L36

Manages the LayoutGroupComponents of an application. Reach it through app.systems.layoutgroup; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ScreenComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/component.js#L56

A ScreenComponent defines a rectangular area where user interfaces can be constructed. Screens can either be 2D (screen space) or 3D (world space) - see screenSpace. It is possible to create an Entity hierarchy underneath an Entity with a ScreenComponent to create complex user interfaces using the following components:

You should never need to use the ScreenComponent constructor directly. To add a ScreenComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('screen', {
    referenceResolution: new Vec2(1280, 720),
    screenSpace: false
});

Once the ScreenComponent is added to the entity, you can access it via the Entity#screen property:

entity.screen.scaleBlend = 0.6; // Set the screen's scale blend to 0.6

console.log(entity.screen.scaleBlend); // Get the screen's scale blend and print it

Relevant Engine API examples:

Properties

cull

cull: boolean = false

If true, then elements inside this screen will not be rendered when outside of the screen (only valid when screenSpace is true).

Accessors

priority

get priority(): number
set priority(value: number)

Gets the screen's render priority.

referenceResolution

get referenceResolution(): Vec2
set referenceResolution(value: Vec2)

Gets the resolution that the ScreenComponent is designed for.

resolution

get resolution(): Vec2
set resolution(value: Vec2)

Gets the width and height of the ScreenComponent.

scaleBlend

get scaleBlend(): number
set scaleBlend(value: number)

Gets the scale blend.

scaleMode

get scaleMode(): string
set scaleMode(value: string)

Gets the scale mode.

screenSpace

get screenSpace(): boolean
set screenSpace(value: boolean)

Gets whether the ScreenComponent will render its child ElementComponents in screen space instead of world space.

Methods

syncDrawOrder

syncDrawOrder(): void

Set the drawOrder of each child ElementComponent so that ElementComponents which are last in the hierarchy are rendered on top. Draw Order sync is queued and will be updated by the next update loop.

Inherited from Component

ScreenComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/system.js#L31

Manages the ScreenComponents of an application. Reach it through app.systems.screen; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ScrollbarComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scrollbar/component.js#L63

The ScrollbarComponent enables an Entity to behave like a draggable scrollbar. It is typically used together with a ScrollViewComponent to allow the user to scroll the contents of a scroll view area.

You should never need to use the ScrollbarComponent constructor directly. To add a ScrollbarComponent to an Entity, use Entity#addComponent. A draggable scrollbar requires a child handle entity with an input-enabled ElementComponent, wired up via the scrollbar's handleEntity property:

// Create a child handle entity that the user can drag
const handle = new Entity();
handle.addComponent('element', {
    type: ELEMENTTYPE_IMAGE,
    useInput: true
});

// Create the scrollbar entity and wire in the handle
const entity = new Entity();
entity.addChild(handle);
entity.addComponent('element', {
    type: ELEMENTTYPE_IMAGE
});
entity.addComponent('scrollbar', {
    orientation: ORIENTATION_VERTICAL,
    value: 0,
    handleSize: 0.5,
    handleEntity: handle
});

Once the ScrollbarComponent is added to the entity, you can access it via the Entity#scrollbar property:

entity.scrollbar.value = 0.25; // Scroll the bar to 25%

console.log(entity.scrollbar.value); // Get the scroll value and print it

Relevant Engine API examples:

Accessors

handleEntity

get handleEntity(): Entity | null
set handleEntity(arg: Entity | null)

Gets the entity to be used as the scrollbar handle.

handleSize

get handleSize(): number
set handleSize(arg: number)

Gets the size of the handle relative to the size of the track.

orientation

get orientation(): number
set orientation(arg: number)

Gets whether the scrollbar moves horizontally or vertically.

value

get value(): number
set value(arg: number)

Gets the current position value of the scrollbar.

Events

EVENT_SETVALUE

static EVENT_SETVALUE: string = 'set:value'

Fired whenever the scroll value changes. The handler is passed a number representing the current scroll value.

Example

entity.scrollbar.on('set:value', (value) => {
    console.log(`Scroll value is now ${value}`);
});

Inherited from Component

ScrollbarComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scrollbar/system.js#L17

Manages the ScrollbarComponents of an application. Reach it through app.systems.scrollbar; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

ScrollViewComponent

Class · extends Component · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/component.js#L59

The ScrollViewComponent enables an Entity to behave like a masked scrolling area, with optional horizontal and vertical scroll bars. The component exposes references to child entities that represent the viewport, the content, and the (optional) horizontal and vertical ScrollbarComponents.

You should never need to use the ScrollViewComponent constructor directly. To add a ScrollViewComponent to an Entity, use Entity#addComponent:

const entity = new Entity();
entity.addComponent('element', {
    type: ELEMENTTYPE_GROUP,
    useInput: true
});
entity.addComponent('scrollview', {
    horizontal: false,
    vertical: true,
    bounceAmount: 0.1
});

Once the ScrollViewComponent is added to the entity, you can access it via the Entity#scrollview property:

entity.scrollview.scroll = new Vec2(0, 1); // Scroll to the bottom

console.log(entity.scrollview.scroll);        // Get the scroll position and print it

Relevant Engine API examples:

Accessors

bounceAmount

get bounceAmount(): number
set bounceAmount(arg: number)

Gets how far the content should move before bouncing back.

contentEntity

get contentEntity(): Entity | null
set contentEntity(arg: Entity | null)

Gets the entity which contains the scrolling content itself.

friction

get friction(): number
set friction(arg: number)

Gets how freely the content should move if thrown.

horizontal

get horizontal(): boolean
set horizontal(arg: boolean)

Gets whether horizontal scrolling is enabled.

horizontalScrollbarEntity

get horizontalScrollbarEntity(): Entity | null
set horizontalScrollbarEntity(arg: Entity | null)

Gets the entity to be used as the horizontal scrollbar.

horizontalScrollbarVisibility

get horizontalScrollbarVisibility(): number
set horizontalScrollbarVisibility(arg: number)

Gets whether the horizontal scrollbar should be visible all the time, or only visible when the content exceeds the size of the viewport.

mouseWheelSensitivity

get mouseWheelSensitivity(): Vec2
set mouseWheelSensitivity(arg: Vec2)

Gets the mouse wheel horizontal and vertical sensitivity.

scroll

get scroll(): Vec2
set scroll(value: Vec2)

Gets the scroll value.

scrollMode

get scrollMode(): number
set scrollMode(arg: number)

Gets the scroll mode of the scroll viewer.

useMouseWheel

get useMouseWheel(): boolean
set useMouseWheel(arg: boolean)

Gets whether to use mouse wheel for scrolling (horizontally and vertically).

vertical

get vertical(): boolean
set vertical(arg: boolean)

Gets whether vertical scrolling is enabled.

verticalScrollbarEntity

get verticalScrollbarEntity(): Entity | null
set verticalScrollbarEntity(arg: Entity | null)

Gets the entity to be used as the vertical scrollbar.

verticalScrollbarVisibility

get verticalScrollbarVisibility(): number
set verticalScrollbarVisibility(arg: number)

Gets whether the vertical scrollbar should be visible all the time, or only visible when the content exceeds the size of the viewport.

viewportEntity

get viewportEntity(): Entity | null
set viewportEntity(arg: Entity | null)

Gets the entity to be used as the masked viewport area, within which the content will scroll.

Events

EVENT_SETSCROLL

static EVENT_SETSCROLL: string = 'set:scroll'

Fired whenever the scroll position changes. The handler is passed a Vec2 containing the horizontal and vertical scroll values in the range 0..1.

Example

entity.scrollview.on('set:scroll', (scroll) => {
    console.log(`Horizontal scroll position: ${scroll.x}`);
    console.log(`Vertical scroll position: ${scroll.y}`);
});

Inherited from Component

ScrollViewComponentSystem

Class · extends ComponentSystem · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/system.js#L50

Manages the ScrollViewComponents of an application. Reach it through app.systems.scrollview; components are created with Entity#addComponent, never by calling the system directly.

Inherited from ComponentSystem

XrAnchor

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L34

An anchor keeps track of a position and rotation that is fixed relative to the real world. This allows the application to adjust the location of virtual objects placed in the scene in a way that helps with maintaining the illusion that the placed objects are really present in the user's environment.

Accessors

persistent

get persistent(): boolean

Gets whether an anchor is persistent.

uuid

get uuid(): string | null

Gets the UUID string of a persisted anchor or null if the anchor is not persisted.

Methods

destroy

destroy(): void

Destroy an anchor.

forget

forget(callback?: XrAnchorForgetCallback): void

Removes the persistent UUID of an anchor from the underlying system. This effectively makes the anchor non-persistent, so it will not be restored in future WebXR sessions.

Parameters

Example

// Forget the anchor and log the result or error
anchor.forget((err) => {
    if (err) {
        console.error('Failed to forget anchor:', err);
    } else {
        console.log('Anchor has been forgotten');
    }
});

getPosition

getPosition(): Vec3

Get the world space position of an anchor.

Returns Vec3: The world space position of an anchor.

getRotation

getRotation(): Quat

Get the world space rotation of an anchor.

Returns Quat: The world space rotation of an anchor.

persist

persist(callback?: XrAnchorPersistCallback): void

Persists the anchor between WebXR sessions by generating a universally unique identifier (UUID) for the anchor. This UUID can be used later to restore the anchor from the underlying system. Note that the underlying system may have a limit on the number of anchors that can be persisted per origin.

Parameters

Example

// Persist the anchor and log the UUID or error
anchor.persist((err, uuid) => {
    if (err) {
        console.error('Failed to persist anchor:', err);
    } else {
        console.log('Anchor persisted with UUID:', uuid);
    }
});

Events

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when an anchor's position and/or rotation is changed.

Example

anchor.on('change', () => {
    // anchor has been updated
    entity.setPosition(anchor.getPosition());
    entity.setRotation(anchor.getRotation());
});

EVENT_DESTROY

static EVENT_DESTROY: string = 'destroy'

Fired when an anchor is destroyed.

Example

// once anchor is destroyed
anchor.once('destroy', () => {
    // destroy its related entity
    entity.destroy();
});

EVENT_FORGET

static EVENT_FORGET: string = 'forget'

Fired when an anchor has been forgotten.

Example

anchor.on('forget', () => {
    // anchor has been forgotten
});

EVENT_PERSIST

static EVENT_PERSIST: string = 'persist'

Fired when an anchor has been persisted. The handler is passed the UUID string that can be used to restore this anchor.

Example

anchor.on('persist', (uuid) => {
    // anchor has been persisted
});

Inherited from EventHandler

XrAnchors

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchors.js#L35

Anchors provide an ability to specify a point in the world that needs to be updated to correctly reflect the evolving understanding of the world by the underlying AR system, such that the anchor remains aligned with the same place in the physical world. Anchors tend to persist better relative to the real world, especially during a longer session with lots of movement.

app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
    anchors: true
});

Accessors

available

get available(): boolean

True if Anchors are available. This information is available only when session has started.

list

get list(): XrAnchor[]

List of available XrAnchors.

persistence

get persistence(): boolean

True if Anchors support persistence.

supported

get supported(): boolean

True if Anchors are supported.

uuids

get uuids(): string[] | null

Array of UUID strings of persistent anchors, or null if not available.

Methods

create

create(position: XRHitTestResult | Vec3, rotation?: Quat | XrAnchorCreateCallback, callback?: XrAnchorCreateCallback): void

Create an anchor using position and rotation, or from hit test result.

Parameters

Example

// create an anchor using a position and rotation
app.xr.anchors.create(position, rotation, (err, anchor) => {
    if (!err) {
        // new anchor has been created
    }
});

Example

// create an anchor from a hit test result
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
    app.xr.anchors.create(hitTestResult, (err, anchor) => {
        if (!err) {
            // new anchor has been created
        }
    });
});

forget

forget(uuid: string, callback?: XrAnchorForgetCallback): void

Forget an anchor by removing its UUID from underlying systems.

Parameters

Example

// forget all available anchors
const uuids = app.xr.anchors.uuids;
for (let i = 0; i < uuids.length; i++) {
    app.xr.anchors.forget(uuids[i]);
}

restore

restore(uuid: string, callback?: XrAnchorCreateCallback): void

Restore anchor using persistent UUID.

Parameters

Example

// restore an anchor using uuid string
app.xr.anchors.restore(uuid, (err, anchor) => {
    if (!err) {
        // new anchor has been created
    }
});

Example

// restore all available persistent anchors
const uuids = app.xr.anchors.uuids;
for(let i = 0; i < uuids.length; i++) {
    app.xr.anchors.restore(uuids[i]);
}

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when a new XrAnchor is added. The handler is passed the XrAnchor that was added.

Example

app.xr.anchors.on('add', (anchor) => {
    console.log('Anchor added');
});

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when anchors become available.

Example

app.xr.anchors.on('available', () => {
    console.log('Anchors are available');
});

EVENT_DESTROY

static EVENT_DESTROY: string = 'destroy'

Fired when an XrAnchor is destroyed. The handler is passed the XrAnchor that was destroyed.

Example

app.xr.anchors.on('destroy', (anchor) => {
    console.log('Anchor destroyed');
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when an anchor failed to be created. The handler is passed an Error object.

Example

app.xr.anchors.on('error', (err) => {
    console.error(err.message);
});

EVENT_UNAVAILABLE

static EVENT_UNAVAILABLE: string = 'unavailable'

Fired when anchors become unavailable.

Example

app.xr.anchors.on('unavailable', () => {
    console.log('Anchors are unavailable');
});

Inherited from EventHandler

XrDomOverlay

Class · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-dom-overlay.js#L30

DOM Overlay provides the ability to use DOM elements as an overlay in a WebXR AR session. It requires that the root DOM element is provided for session start. That way, input source select events are first tested against DOM Elements and then propagated down to the XR Session. If this propagation is not desirable, use the beforexrselect event on a DOM element and the preventDefault function to stop propagation.

app.xr.domOverlay.root = element;
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR);
// Disable input source firing `select` event when some descendant element of DOM overlay root
// is touched/clicked. This is useful when the user interacts with UI elements and there should
// not be `select` events behind UI.
someElement.addEventListener('beforexrselect', (evt) => {
    evt.preventDefault();
});

Accessors

available

get available(): boolean

True if DOM Overlay is available. This information becomes available only when the session has started and a valid root DOM element has been provided.

root

get root(): Element | null
set root(value: Element | null)

Gets the DOM element to be used as the root for DOM Overlay.

state

get state(): "screen" | "floating" | "head-locked" | null

State of the DOM Overlay, which defines how the root DOM element is rendered. Can be:

supported

get supported(): boolean

True if DOM Overlay is supported.

XrFinger

Class · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-finger.js#L11

Represents a finger of a tracked XrHand with related joints and index.

Accessors

hand

get hand(): XrHand

Gets the hand that the finger belongs to.

index

get index(): number

Gets the index of the finger. Enumeration is: thumb, index, middle, ring, little.

joints

get joints(): XrJoint[]

Array of joints that belong to this finger, starting from joint closest to wrist all the way to the tip of a finger.

tip

get tip(): XrJoint | null

Tip joint of the finger, or null if not available.

XrHand

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hand.js#L37

Represents a hand with fingers and joints.

Accessors

fingers

get fingers(): XrFinger[]

Array of fingers of the hand.

joints

get joints(): XrJoint[]

Array of joints in the hand.

tips

get tips(): XrJoint[]

Array of joints that are fingertips.

tracking

get tracking(): boolean

True if tracking is available, otherwise tracking might be lost.

wrist

get wrist(): XrJoint | null

Wrist of a hand, or null if it is not available by WebXR underlying system.

Methods

getJointById

getJointById(id: string): XrJoint | null

Returns joint by its XRHand id.

Parameters

Returns XrJoint | null: Joint or null if not available.

Events

EVENT_TRACKING

static EVENT_TRACKING: string = 'tracking'

Fired when tracking becomes available.

Example

hand.on('tracking', () => {
    console.log('Hand tracking is available');
});

EVENT_TRACKINGLOST

static EVENT_TRACKINGLOST: string = 'trackinglost'

Fired when tracking is lost.

Example

hand.on('trackinglost', () => {
    console.log('Hand tracking is lost');
});

Inherited from EventHandler

XrHitTest

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test.js#L28

The Hit Test interface allows initiating hit testing against real-world geometry from various sources: the view, input sources, or an arbitrary ray in space. Results reflect the underlying AR system's understanding of the real world.

Properties

sources

sources: XrHitTestSource[] = []

List of active XrHitTestSource.

Accessors

available

get available(): boolean

True if Hit Test is available. This information is available only when the session has started.

supported

get supported(): boolean

True if AR Hit Test is supported.

Methods

start

start(options?: object): void

Attempts to start hit test with provided reference space.

Parameters

Example

// start hit testing from viewer position facing forwards
app.xr.hitTest.start({
    spaceType: XRSPACE_VIEWER,
    callback: (err, hitTestSource) => {
        if (err) return;
        hitTestSource.on('result', (position, rotation) => {
            // position and rotation of hit test result
        });
    }
});

Example

// start hit testing using an arbitrary ray
const ray = new Ray(new Vec3(0, 0, 0), new Vec3(0, -1, 0));
app.xr.hitTest.start({
    spaceType: XRSPACE_LOCAL,
    offsetRay: ray,
    callback: (err, hitTestSource) => {
        // hit test source that will sample real world geometry straight down
        // from the position where AR session started
    }
});

Example

// start hit testing for touch screen taps
app.xr.hitTest.start({
    profile: 'generic-touchscreen',
    callback: (err, hitTestSource) => {
        if (err) return;
        hitTestSource.on('result', (position, rotation, inputSource) => {
            // position and rotation of hit test result
            // that will be created from touch on mobile devices
        });
    }
});

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when new XrHitTestSource is added to the list. The handler is passed the XrHitTestSource object that has been added.

Example

app.xr.hitTest.on('add', (hitTestSource) => {
    // new hit test source is added
});

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when hit test becomes available.

Example

app.xr.hitTest.on('available', () => {
    console.log('Hit Testing is available');
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when failed create hit test source. The handler is passed the Error object.

Example

app.xr.hitTest.on('error', (err) => {
    console.error(err.message);
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when XrHitTestSource is removed to the list. The handler is passed the XrHitTestSource object that has been removed.

Example

app.xr.hitTest.on('remove', (hitTestSource) => {
    // hit test source is removed
});

EVENT_RESULT

static EVENT_RESULT: string = 'result'

Fired when hit test source receives new results. It provides transform information that tries to match real world picked geometry. The handler is passed the XrHitTestSource that produced the hit result, the Vec3 position, the Quat rotation and the XrInputSource (if it is a transient hit test source).

Example

app.xr.hitTest.on('result', (hitTestSource, position, rotation, inputSource) => {
    target.setPosition(position);
    target.setRotation(rotation);
});

EVENT_UNAVAILABLE

static EVENT_UNAVAILABLE: string = 'unavailable'

Fired when hit test becomes unavailable.

Example

app.xr.hitTest.on('unavailable', () => {
    console.log('Hit Testing is unavailable');
});

Inherited from EventHandler

XrHitTestSource

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test-source.js#L40

Represents XR hit test source, which provides access to hit results of real world geometry from AR session.

// start a hit test from a viewer origin forward
app.xr.hitTest.start({
    spaceType: XRSPACE_VIEWER,
    callback: (err, hitTestSource) => {
        if (err) return;
        // subscribe to hit test results
        hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
            // position and rotation of hit test result
        });
    }
});

Methods

remove

remove(): void

Stop and remove hit test source.

Events

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when XrHitTestSource is removed.

Example

hitTestSource.once('remove', () => {
    // hit test source has been removed
});

EVENT_RESULT

static EVENT_RESULT: string = 'result'

Fired when the hit test source receives new results. It provides transform information that tries to match real world geometry. Callback provides the Vec3 position, the Quat rotation, the XrInputSource (if it is a transient hit test source) and the XRHitTestResult object that is created by WebXR API.

Example

hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
    target.setPosition(position);
    target.setRotation(rotation);
});

Inherited from EventHandler

XrImageTracking

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-image-tracking.js#L17

Image Tracking provides the ability to track real world images using provided image samples and their estimated sizes. The underlying system will assume that the tracked image can move and rotate in the real world and will try to provide transformation estimates and its tracking state.

Accessors

available

get available(): boolean

True if Image Tracking is available. This information is only available when the XR session has started, and will be true if image tracking is supported and images were provided and they have been processed successfully.

images

get images(): XrTrackedImage[]

List of XrTrackedImage that contain tracking information.

supported

get supported(): boolean

True if Image Tracking is supported.

Methods

add

add(image: Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData, width: number): XrTrackedImage | null

Add an image for image tracking. A width can also be provided to help the underlying system estimate the appropriate transformation. Modifying the tracked images list is only possible before an AR session is started.

Parameters

Returns XrTrackedImage | null: Tracked image object that will contain tracking information. Returns null if image tracking is not supported or if the XR manager is not active.

Example

// image of a book cover that has width of 20cm (0.2m)
app.xr.imageTracking.add(bookCoverImg, 0.2);

remove

remove(trackedImage: XrTrackedImage): void

Remove an image from image tracking.

Parameters

Events

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when the XR session is started, but image tracking failed to process the provided images. The handler is passed the Error object.

Example

app.xr.imageTracking.on('error', (err) => {
    console.error(err.message);
});

Inherited from EventHandler

XrInput

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-input.js#L20

Provides access to input sources for WebXR.

Input sources represent:

Accessors

inputSources

get inputSources(): XrInputSource[]

List of active XrInputSource instances.

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when a new XrInputSource is added to the list. The handler is passed the XrInputSource that has been added.

Example

app.xr.input.on('add', (inputSource) => {
    // new input source is added
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when an XrInputSource is removed from the list. The handler is passed the XrInputSource that has been removed.

Example

app.xr.input.on('remove', (inputSource) => {
    // input source is removed
});

EVENT_SELECT

static EVENT_SELECT: string = 'select'

Fired when XrInputSource has triggered primary action. This could be pressing a trigger button, or touching a screen. The handler is passed the XrInputSource that triggered the select event and the XRInputSourceEvent event from the WebXR API.

Example

const ray = new Ray();
app.xr.input.on('select', (inputSource, evt) => {
    ray.set(inputSource.getOrigin(), inputSource.getDirection());
    if (obj.intersectsRay(ray)) {
        // selected an object with input source
    }
});

EVENT_SELECTEND

static EVENT_SELECTEND: string = 'selectend'

Fired when XrInputSource has ended triggering primary action. The handler is passed the XrInputSource that triggered the selectend event and the XRInputSourceEvent event from the WebXR API.

Example

app.xr.input.on('selectend', (inputSource, evt) => {
    console.log('Select ended');
});

EVENT_SELECTSTART

static EVENT_SELECTSTART: string = 'selectstart'

Fired when XrInputSource has started to trigger primary action. The handler is passed the XrInputSource that triggered the selectstart event and the XRInputSourceEvent event from the WebXR API.

Example

app.xr.input.on('selectstart', (inputSource, evt) => {
    console.log('Select started');
});

EVENT_SQUEEZE

static EVENT_SQUEEZE: string = 'squeeze'

Fired when XrInputSource has triggered squeeze action. This is associated with "grabbing" action on the controllers. The handler is passed the XrInputSource that triggered the squeeze event and the XRInputSourceEvent event from the WebXR API.

Example

app.xr.input.on('squeeze', (inputSource, evt) => {
    console.log('Squeeze');
});

EVENT_SQUEEZEEND

static EVENT_SQUEEZEEND: string = 'squeezeend'

Fired when XrInputSource has ended triggering squeeze action. The handler is passed the XrInputSource that triggered the squeezeend event and the XRInputSourceEvent event from the WebXR API.

Example

app.xr.input.on('squeezeend', (inputSource, evt) => {
    console.log('Squeeze ended');
});

EVENT_SQUEEZESTART

static EVENT_SQUEEZESTART: string = 'squeezestart'

Fired when XrInputSource has started to trigger squeeze action. The handler is passed the XrInputSource that triggered the squeezestart event and the XRInputSourceEvent event from the WebXR API.

Example

app.xr.input.on('squeezestart', (inputSource, evt) => {
    if (obj.containsPoint(inputSource.getPosition())) {
        // grabbed an object
    }
});

Inherited from EventHandler

XrInputSource

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-input-source.js#L29

Represents XR input source, which is any input mechanism which allows the user to perform targeted actions in the same virtual space as the viewer. Example XR input sources include, but are not limited to: handheld controllers, optically tracked hands, touch screen taps, and gaze-based input methods that operate on the viewer's pose.

Accessors

elementEntity

get elementEntity(): Entity | null

If elementInput is true, this property will hold entity with Element component at which this input source is hovering, or null if not hovering over any element.

elementInput

get elementInput(): boolean
set elementInput(value: boolean)

Gets whether the input source can interact with ElementComponents.

gamepad

get gamepad(): Gamepad | null

If input source has buttons, triggers, thumbstick or touchpad, then this object provides access to its states.

grip

get grip(): boolean

If input source can be held, then it will have node with its world transformation, that can be used to position and rotate visual object based on it.

hand

get hand(): XrHand | null

If input source is a tracked hand, then it will point to XrHand otherwise it is null.

handedness

get handedness(): string

Describes which hand input source is associated with. Can be one of the following:

hitTestSources

get hitTestSources(): XrHitTestSource[]

List of active XrHitTestSource instances associated with this input source.

id

get id(): number

Unique number associated with instance of input source. Same physical devices when reconnected will not share this ID.

inputSource

get inputSource(): XRInputSource

XRInputSource object that is associated with this input source.

profiles

get profiles(): string[]

List of input profile names indicating both the preferred visual representation and behavior of the input source.

selecting

get selecting(): boolean

True if input source is in active primary action between selectstart and selectend events.

squeezing

get squeezing(): boolean

True if input source is in active squeeze action between squeezestart and squeezeend events.

targetRayMode

get targetRayMode(): string

Type of ray Input Device is based on. Can be one of the following:

Methods

getDirection

getDirection(): Vec3

Get the world space direction of input source ray.

Returns Vec3: The world space direction of input source ray.

getLinearVelocity

getLinearVelocity(): Vec3 | null

Get the linear velocity (units per second) of the input source if it is handheld (grip is true). Otherwise it will return null. The velocity is relative to the parent of the XR camera, so it does not include the motion of the parent.

Returns Vec3 | null: The world space linear velocity of the handheld input source.

getLocalPosition

getLocalPosition(): Vec3 | null

Get the local space position of input source if it is handheld (grip is true). Local space is relative to parent of the XR camera. Otherwise it will return null.

Returns Vec3 | null: The local space position of handheld input source.

getLocalRotation

getLocalRotation(): Quat | null

Get the local space rotation of input source if it is handheld (grip is true). Local space is relative to parent of the XR camera. Otherwise it will return null.

Returns Quat | null: The local space rotation of handheld input source.

getOrigin

getOrigin(): Vec3

Get the world space origin of input source ray.

Returns Vec3: The world space origin of input source ray.

getPosition

getPosition(): Vec3 | null

Get the world space position of input source if it is handheld (grip is true). Otherwise it will return null.

Returns Vec3 | null: The world space position of handheld input source.

getRotation

getRotation(): Quat | null

Get the world space rotation of input source if it is handheld (grip is true). Otherwise it will return null.

Returns Quat | null: The world space rotation of handheld input source.

hitTestStart

hitTestStart(options?: object): void

Attempts to start hit test source based on this input source.

Parameters

Example

app.xr.input.on('add', (inputSource) => {
    inputSource.hitTestStart({
        callback: (err, hitTestSource) => {
            if (err) return;
            hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
                // position and rotation of hit test result
                // that will be created from touch on mobile devices
            });
        }
    });
});

Events

EVENT_HITTESTADD

static EVENT_HITTESTADD: string = 'hittest:add'

Fired when new XrHitTestSource is added to the input source. The handler is passed the XrHitTestSource object that has been added.

Example

inputSource.on('hittest:add', (hitTestSource) => {
    // new hit test source is added
});

EVENT_HITTESTREMOVE

static EVENT_HITTESTREMOVE: string = 'hittest:remove'

Fired when XrHitTestSource is removed from the input source. The handler is passed the XrHitTestSource object that has been removed.

Example

inputSource.on('hittest:remove', (hitTestSource) => {
    // hit test source is removed
});

EVENT_HITTESTRESULT

static EVENT_HITTESTRESULT: string = 'hittest:result'

Fired when hit test source receives new results. It provides transform information that tries to match real world picked geometry. The handler is passed the XrHitTestSource object that produced the hit result, the Vec3 position, the Quat rotation and the XRHitTestResult object that is created by the WebXR API.

Example

inputSource.on('hittest:result', (hitTestSource, position, rotation, hitTestResult) => {
    target.setPosition(position);
    target.setRotation(rotation);
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when XrInputSource is removed.

Example

inputSource.once('remove', () => {
    // input source is not available anymore
});

EVENT_SELECT

static EVENT_SELECT: string = 'select'

Fired when input source has triggered primary action. This could be pressing a trigger button, or touching a screen. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

const ray = new Ray();
inputSource.on('select', (evt) => {
    ray.set(inputSource.getOrigin(), inputSource.getDirection());
    if (obj.intersectsRay(ray)) {
        // selected an object with input source
    }
});

EVENT_SELECTEND

static EVENT_SELECTEND: string = 'selectend'

Fired when input source has ended triggering primary action. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

inputSource.on('selectend', (evt) => {
    console.log('Select ended');
});

EVENT_SELECTSTART

static EVENT_SELECTSTART: string = 'selectstart'

Fired when input source has started to trigger primary action. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

inputSource.on('selectstart', (evt) => {
    console.log('Select started');
});

EVENT_SQUEEZE

static EVENT_SQUEEZE: string = 'squeeze'

Fired when input source has triggered squeeze action. This is associated with "grabbing" action on the controllers. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

inputSource.on('squeeze', (evt) => {
    console.log('Squeeze');
});

EVENT_SQUEEZEEND

static EVENT_SQUEEZEEND: string = 'squeezeend'

Fired when input source has ended triggering squeeze action. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

inputSource.on('squeezeend', (evt) => {
    console.log('Squeeze ended');
});

EVENT_SQUEEZESTART

static EVENT_SQUEEZESTART: string = 'squeezestart'

Fired when input source has started to trigger squeeze action. The handler is passed an XRInputSourceEvent object from the WebXR API.

Example

inputSource.on('squeezestart', (evt) => {
    if (obj.containsPoint(inputSource.getPosition())) {
        // grabbed an object
    }
});

Inherited from EventHandler

XrJoint

Class · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-joint.js#L30

Represents the joint of a finger.

Accessors

finger

get finger(): XrFinger | null

Finger that joint relates to.

hand

get hand(): XrHand

Hand that joint relates to.

id

get id(): XRHandJoint

Id of a joint based on WebXR Hand Input Specs.

index

get index(): number

Index of a joint within a finger, starting from 0 (root of a finger) all the way to tip of the finger.

radius

get radius(): number

The radius of a joint, which is a distance from joint to the edge of a skin.

tip

get tip(): boolean

True if joint is a tip of a finger.

wrist

get wrist(): boolean

True if joint is a wrist.

Methods

getPosition

getPosition(): Vec3

Get the world space position of a joint.

Returns Vec3: The world space position of a joint.

getRotation

getRotation(): Quat

Get the world space rotation of a joint.

Returns Quat: The world space rotation of a joint.

XrLightEstimation

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-light-estimation.js#L26

Light Estimation provides illumination data from the real world, which is estimated by the underlying AR system. It provides a reflection Cube Map, that represents the reflection estimation from the viewer position. A more simplified approximation of light is provided by L2 Spherical Harmonics data. And the most simple level of light estimation is the most prominent directional light, its rotation, intensity and color.

Accessors

available

get available(): boolean

True if estimated light information is available.

Example

if (app.xr.lightEstimation.available) {
    entity.light.intensity = app.xr.lightEstimation.intensity;
}

color

get color(): Color | null

Color of what is estimated to be the most prominent directional light. Or null if data is not available.

intensity

get intensity(): number | null

Intensity of what is estimated to be the most prominent directional light. Or null if data is not available.

rotation

get rotation(): Quat | null

Rotation of what is estimated to be the most prominent directional light. Or null if data is not available.

sphericalHarmonics

get sphericalHarmonics(): Float32Array<ArrayBufferLike> | null

Spherical harmonic coefficients of estimated ambient light. Or null if data is not available.

supported

get supported(): boolean

True if Light Estimation is supported. This information is available only during an active AR session.

Methods

end

end(): void

End estimation of illumination data.

start

start(): void

Start estimation of illumination data. Availability of such data will come later and an available event will be fired. If it failed to start estimation, an error event will be fired.

Example

app.xr.on('start', () => {
    if (app.xr.lightEstimation.supported) {
        app.xr.lightEstimation.start();
    }
});

Events

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when light estimation data becomes available.

Example

app.xr.lightEstimation.on('available', () => {
    console.log('Light estimation is available');
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when light estimation has failed to start. The handler is passed the Error object related to failure of light estimation start.

Example

app.xr.lightEstimation.on('error', (error) => {
    console.error(error.message);
});

Inherited from EventHandler

XrManager

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L69

XrManager provides a comprehensive interface for WebXR integration in PlayCanvas applications. It manages the full lifecycle of XR sessions (VR/AR), handles device capabilities, and provides access to various XR features through specialized subsystems.

In order for XR to be available, ensure that your application is served over HTTPS or localhost.

The AppBase class automatically creates an instance of this class and makes it available as AppBase#xr.

Ready-made XR building blocks ship under playcanvas/scripts/esm/xr/: xr-session.mjs for session lifecycle and camera rig transforms, xr-controllers.mjs for WebXR controller and hand models, xr-navigation.mjs for teleportation, smooth locomotion and turning, xr-manipulation.mjs for two-handed drag, rotate and scale of the world, and xr-menu.mjs for hand-tracked and controller-driven 3D menus.

Properties

anchors

anchors: XrAnchors

Provides access to Anchors.

domOverlay

domOverlay: XrDomOverlay

Provides access to DOM overlay capabilities.

hitTest

hitTest: XrHitTest

Provides the ability to perform hit tests on the representation of real world geometry of the underlying AR system.

imageTracking

imageTracking: XrImageTracking

Provides access to image tracking capabilities.

input

input: XrInput

Provides access to Input Sources.

lightEstimation

lightEstimation: XrLightEstimation

Provides access to light estimation capabilities.

meshDetection

meshDetection: XrMeshDetection

Provides access to mesh detection capabilities.

planeDetection

planeDetection: XrPlaneDetection

Provides access to plane detection capabilities.

views

views: XrViews

Provides access to views and their capabilities.

Accessors

active

get active(): boolean

True if XR session is running.

camera

get camera(): Entity | null

Active camera for which XR session is running or null.

fixedFoveation

get fixedFoveation(): number | null
set fixedFoveation(value: number | null)

Gets the current fixed foveation level, which is between 0 and 1. 0 is no foveation and 1 is highest foveation. If fixed foveation is not supported, this value returns null.

framebufferScaleFactor

get framebufferScaleFactor(): number

Framebuffer scale factor. This value is read-only and can only be set when starting a new XR session.

frameRate

get frameRate(): number | null

XR session frameRate or null if this information is not available. This value can change during an active XR session.

graphicsBinding

get graphicsBinding(): any

Backend-specific XR binding for GPU camera/depth paths when available (for example WebGL XRWebGLBinding or WebGPU XRGPUBinding when exposed by the user agent).

session

get session(): XRSession | null

Provides access to XRSession of WebXR.

spaceType

get spaceType(): string | null

Returns reference space type of currently running XR session or null if no session is running. Can be any of XRSPACE_*.

supported

get supported(): boolean

True if XR is supported.

supportedFrameRates

get supportedFrameRates(): number[] | null

List of supported frame rates, or null if this data is not available.

type

get type(): string | null

Returns type of currently running XR session or null if no session is running. Can be any of XRTYPE_*.

Methods

end

end(callback?: XrErrorCallback): void

Attempts to end XR session and optionally fires callback when session is ended or failed to end.

Parameters

Example

app.keyboard.on('keydown', (evt) => {
    if (evt.key === KEY_ESCAPE && app.xr.active) {
        app.xr.end();
    }
});

initiateRoomCapture

initiateRoomCapture(callback: XrRoomCaptureCallback): void

Initiate manual room capture. If the underlying XR system supports manual capture of the room, it will start the capturing process, which can affect plane and mesh detection, and improve hit-test quality against real-world geometry.

Parameters

Example

this.app.xr.initiateRoomCapture((err) => {
    if (err) {
        // capture failed
        return;
    }
    // capture was successful
});

isAvailable

isAvailable(type: string): boolean

Check if the specified type of session is available.

Parameters

Returns boolean: True if the specified session type is available.

Example

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

start

start(camera: CameraComponent, type: string, spaceType: string, options?: object): void

Attempts to start XR session for provided CameraComponent and optionally fires callback when session is created or failed to create. Integrated XR APIs need to be enabled by providing relevant options.

Note that the start method needs to be called in response to user action, such as a button click. It will not work if called in response to a timer or other event.

Parameters

Example

button.on('click', () => {
    app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR);
});

Example

button.on('click', () => {
    app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
        anchors: true,
        imageTracking: true,
        depthSensing: { }
    });
});

updateTargetFrameRate

updateTargetFrameRate(frameRate: number, callback?: Function): void

Update target frame rate of an XR session to one of supported value provided by supportedFrameRates list.

Parameters

isDeviceSupported

static isDeviceSupported(deviceType: string, type: string): Promise<boolean>

Tests whether an immersive WebXR session of the given type can run on the specified graphics backend. Unlike XrManager#isAvailable, this is a static method that can be called before a graphics device (or the AppBase) is created, which makes it useful for deciding which device type to create for XR - for example WebGPU vs WebGL2.

This is a best-effort preflight check. The only authoritative test remains a successful XrManager#start, so a fallback path should always be kept.

Parameters

Returns Promise<boolean>: Promise that resolves to true if a session of the given type is reported supported on the given backend, false otherwise.

Example

const supported = await XrManager.isDeviceSupported(DEVICETYPE_WEBGPU, XRTYPE_VR);
if (supported) {
    // a WebGPU device can be created and used to offer VR
}

Events

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when availability of the XR type is changed. This event is available in two forms. They are as follows:

  1. available - Fired when availability of any XR type is changed. The handler is passed the session type that has changed availability and a boolean representing the availability.
  2. available:[type] - Fired when availability of specific XR type is changed. The handler is passed a boolean representing the availability.

Example

app.xr.on('available', (type, available) => {
    console.log(`XR type ${type} is now ${available ? 'available' : 'unavailable'}`);
});

Example

app.xr.on(`available:${XRTYPE_VR}`, (available) => {
    console.log(`XR type VR is now ${available ? 'available' : 'unavailable'}`);
});

EVENT_END

static EVENT_END: string = 'end'

Fired when XR session is ended. While the handlers run, XrManager#camera, XrManager#type and XrManager#spaceType still describe the session that has ended, and they are reset once all handlers have run.

Example

app.xr.on('end', () => {
    // XR session has ended
});

EVENT_ERROR

static EVENT_ERROR: string = 'error'

Fired when XR session is failed to start or failed to check for session type support. The handler is passed the Error object related to failure of session start or check of session type support.

Example

app.xr.on('error', (error) => {
    console.error(error.message);
});

EVENT_START

static EVENT_START: string = 'start'

Fired when XR session is started.

Example

app.xr.on('start', () => {
    // XR session has started
});

EVENT_UPDATE

static EVENT_UPDATE: string = 'update'

Fired when XR session is updated, providing relevant XRFrame object. The handler is passed XRFrame object that can be used for interfacing directly with WebXR APIs.

Example

app.xr.on('update', (frame) => {
    console.log('XR frame updated');
});

Inherited from EventHandler

XrMesh

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-mesh.js#L15

Detected Mesh instance that provides its transform (position, rotation), triangles (vertices, indices) and its semantic label. Any of its properties can change during its lifetime.

Accessors

indices

get indices(): Uint32Array<ArrayBufferLike>

Array of mesh indices.

label

get label(): string

Semantic Label of a mesh that is provided by underlying system. Current list includes (but not limited to): https://github.com/immersive-web/semantic-labels/blob/master/labels.json

vertices

get vertices(): Float32Array<ArrayBufferLike>

Array of mesh vertices. This array contains 3 components per vertex (x, y, z).

Methods

getPosition

getPosition(): Vec3

Get the world space position of a mesh.

Returns Vec3: The world space position of a mesh.

getRotation

getRotation(): Quat

Get the world space rotation of a mesh.

Returns Quat: The world space rotation of a mesh.

Events

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when XrMesh attributes such as vertices, indices and/or label have been changed. Position and rotation can change at any time without triggering a change event.

Example

mesh.on('change', () => {
    // mesh attributes have been changed
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when an XrMesh is removed. Its attributes, such as its vertices and label, keep their last values.

Example

mesh.once('remove', () => {
    // mesh is no longer available
});

Inherited from EventHandler

XrMeshDetection

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-mesh-detection.js#L28

Mesh Detection provides the ability to detect real world meshes based on the scanning and reconstruction by the underlying AR system.

// start session with plane detection enabled
app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, {
    meshDetection: true
});
app.xr.meshDetection.on('add', (mesh) => {
    // new mesh been added
});

Accessors

available

get available(): boolean

True if Mesh Detection is available. This information is available only when session has started.

meshes

get meshes(): XrMesh[]

Array of XrMesh instances that contain transform, vertices and label information.

supported

get supported(): boolean

True if Mesh Detection is supported.

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when new XrMesh is added to the list. The handler is passed the XrMesh instance that has been added.

Example

app.xr.meshDetection.on('add', (mesh) => {
    // a new XrMesh has been added
});

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when mesh detection becomes available.

Example

app.xr.meshDetection.on('available', () => {
    console.log('Mesh detection is available');
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when a XrMesh is removed from the list. The handler is passed the XrMesh instance that has been removed.

Example

app.xr.meshDetection.on('remove', (mesh) => {
    // XrMesh has been removed
});

EVENT_UNAVAILABLE

static EVENT_UNAVAILABLE: string = 'unavailable'

Fired when mesh detection becomes unavailable.

Example

app.xr.meshDetection.on('unavailable', () => {
    console.log('Mesh detection is unavailable');
});

Inherited from EventHandler

XrPlane

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-plane.js#L19

Represents a detected plane in the real world, providing its position, rotation, polygon points, and semantic label. The plane data may change over time as the system updates its understanding of the environment. Instances of this class are created and managed by the XrPlaneDetection system.

Accessors

id

get id(): number

Unique identifier of a plane.

label

get label(): string

Gets the semantic label of the plane provided by the underlying system. The label describes the type of surface the plane represents, such as "floor", "wall", "ceiling", etc. The list of possible labels can be found in the semantic labels repository.

Example

if (plane.label === 'floor') {
    console.log('This plane represents the floor.');
} else if (plane.label === 'wall') {
    console.log('This plane represents a wall.');
}

orientation

get orientation(): "horizontal" | "vertical" | null

Gets the plane's specific orientation. This can be "horizontal" for planes that are parallel to the ground, "vertical" for planes that are perpendicular to the ground, or null if the orientation is different or unknown.

Example

if (plane.orientation === 'horizontal') {
    console.log('This plane is horizontal.');
} else if (plane.orientation === 'vertical') {
    console.log('This plane is vertical.');
} else {
    console.log('Orientation of this plane is unknown or different.');
}

points

get points(): DOMPointReadOnly[]

Gets the array of points that define the polygon of the plane in its local coordinate space. Each point is represented as a DOMPointReadOnly object with x, y, and z properties. These points can be transformed to world coordinates using the plane's position and rotation.

Example

// prepare reusable objects
const transform = new Mat4();
const vecA = new Vec3();
const vecB = new Vec3();

// update Mat4 to plane position and rotation
transform.setTRS(plane.getPosition(), plane.getRotation(), Vec3.ONE);

// draw lines between points
for (let i = 0; i < plane.points.length; i++) {
    vecA.copy(plane.points[i]);
    vecB.copy(plane.points[(i + 1) % plane.points.length]);

    // transform points to world space
    transform.transformPoint(vecA, vecA);
    transform.transformPoint(vecB, vecB);

    // render line
    app.drawLine(vecA, vecB, Color.WHITE);
}

Methods

getPosition

getPosition(): Vec3

Get the world space position of a plane.

Returns Vec3: The world space position of a plane.

getRotation

getRotation(): Quat

Get the world space rotation of a plane.

Returns Quat: The world space rotation of a plane.

Events

EVENT_CHANGE

static EVENT_CHANGE: string = 'change'

Fired when XrPlane attributes such as: orientation and/or points have been changed. Position and rotation can change at any time without triggering a change event.

Example

plane.on('change', () -> {
    // plane has been changed
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when an XrPlane is removed. Its attributes, such as its points and label, keep their last values.

Example

plane.once('remove', () => {
    // plane is not available anymore
});

Inherited from EventHandler

XrPlaneDetection

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-plane-detection.js#L28

Plane Detection provides the ability to detect real world surfaces based on estimations of the underlying AR system.

// start session with plane detection enabled
app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR, {
    planeDetection: true
});
app.xr.planeDetection.on('add', (plane) => {
    // new plane been added
});

Accessors

available

get available(): boolean

True if Plane Detection is available. This information is available only when the session has started.

planes

get planes(): XrPlane[]

Array of XrPlane instances that contain individual plane information.

supported

get supported(): boolean

True if Plane Detection is supported.

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when new XrPlane is added to the list. The handler is passed the XrPlane instance that has been added.

Example

app.xr.planeDetection.on('add', (plane) => {
    // new plane is added
});

EVENT_AVAILABLE

static EVENT_AVAILABLE: string = 'available'

Fired when plane detection becomes available.

Example

app.xr.planeDetection.on('available', () => {
    console.log('Plane detection is available');
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when a XrPlane is removed from the list. The handler is passed the XrPlane instance that has been removed.

Example

app.xr.planeDetection.on('remove', (plane) => {
    // new plane is removed
});

EVENT_UNAVAILABLE

static EVENT_UNAVAILABLE: string = 'unavailable'

Fired when plane detection becomes unavailable.

Example

app.xr.planeDetection.on('unavailable', () => {
    console.log('Plane detection is unavailable');
});

Inherited from EventHandler

XrTrackedImage

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-tracked-image.js#L12

The tracked image interface that is created by the Image Tracking system and is provided as a list from XrImageTracking#images. It contains information about the tracking state as well as the position and rotation of the tracked image.

Accessors

emulated

get emulated(): boolean

True if image was recently tracked but currently is not actively tracked due to inability of identifying the image by the underlying AR system. Position and rotation will be based on the previously known transformation assuming the tracked image has not moved.

image

get image(): Blob | ImageBitmap | HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | ImageData

Image that is used for tracking.

trackable

get trackable(): boolean

True if image is trackable. A too small resolution or invalid images can be untrackable by the underlying AR system.

tracking

get tracking(): boolean

True if image is in tracking state and being tracked in real world by the underlying AR system.

width

get width(): number
set width(value: number)

Get the width (in meters) of image in real world.

Methods

getPosition

getPosition(): Vec3

Get the world position of the tracked image.

Returns Vec3: Position in world space.

Example

// update entity position to match tracked image position
entity.setPosition(trackedImage.getPosition());

getRotation

getRotation(): Quat

Get the world rotation of the tracked image.

Returns Quat: Rotation in world space.

Example

// update entity rotation to match tracked image rotation
entity.setRotation(trackedImage.getRotation());

Events

EVENT_TRACKED

static EVENT_TRACKED: string = 'tracked'

Fired when image becomes actively tracked.

Example

trackedImage.on('tracked', () => {
    console.log('Image is now tracked');
});

EVENT_UNTRACKED

static EVENT_UNTRACKED: string = 'untracked'

Fired when image is no longer actively tracked.

Example

trackedImage.on('untracked', () => {
    console.log('Image is no longer tracked');
});

Inherited from EventHandler

XrView

Class · extends RenderView · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-view.js#L18

Represents an XR View which represents a screen (monoscopic scenario such as a mobile phone) or an eye (stereoscopic scenario such as an HMD context). It provides access to the view's color and depth information based on the capabilities of underlying AR system.

Accessors

depthUvMatrix

get depthUvMatrix(): Mat4

4x4 matrix that should be used to transform depth texture UVs to normalized UVs in a shader. It is updated when the depth texture is resized. Refer to EVENT_DEPTHRESIZE.

Example

material.setParameter('matrix_depth_uv', view.depthUvMatrix.data);

depthValueToMeters

get depthValueToMeters(): number

Multiply this coefficient number by raw depth value to get depth in meters.

Example

material.setParameter('depth_to_meters', view.depthValueToMeters);

eye

get eye(): string

An eye with which this view is associated. Can be any of:

textureColor

get textureColor(): Texture | null

Texture associated with this view's camera color. Equals to null if camera color is not available or is not supported.

textureDepth

get textureDepth(): Texture | null

Texture that contains packed depth information which is reconstructed using the underlying AR system. This texture can be used (not limited to) for reconstructing real world geometry, virtual object placement, occlusion of virtual object by the real world geometry, and more. The format of this texture is any of PIXELFORMAT_LA8, PIXELFORMAT_DEPTH, or PIXELFORMAT_R32F based on XrViews#depthPixelFormat. It is UV transformed based on the underlying AR system which can be normalized using depthUvMatrix. Equals to null if camera depth is not supported.

Example

// GPU path, attaching texture to material
material.setParameter('texture_depthSensingMap', view.textureDepth);
material.setParameter('matrix_depth_uv', view.depthUvMatrix.data);
material.setParameter('depth_to_meters', view.depthValueToMeters);

Example

// GLSL shader to unpack depth texture
// when depth information is provided in form of LA8
varying vec2 vUv0;

uniform sampler2D texture_depthSensingMap;
uniform mat4 matrix_depth_uv;
uniform float depth_to_meters;

void main(void) {
    // transform UVs using depth matrix
    vec2 texCoord = (matrix_depth_uv * vec4(vUv0.xy, 0.0, 1.0)).xy;

    // get luminance alpha components from depth texture
    vec2 packedDepth = texture2D(texture_depthSensingMap, texCoord).ra;

    // unpack into single value in millimeters
    float depth = dot(packedDepth, vec2(255.0, 256.0 * 255.0)) * depth_to_meters; // m

    // normalize: 0m to 8m distance
    depth = min(depth / 8.0, 1.0); // 0..1 = 0m..8m

    // paint scene from black to white based on distance
    gl_FragColor = vec4(depth, depth, depth, 1.0);
}

Methods

getDepth

getDepth(u: number, v: number): number | null

Get a depth value from depth information in meters. The specified UV is in the range 0..1, with the origin in the top-left corner of the depth texture.

Parameters

Returns number | null: Depth in meters or null if depth information is currently not available.

Example

const depth = view.getDepth(u, v);
if (depth !== null) {
    // depth in meters
}

Events

EVENT_DEPTHRESIZE

static EVENT_DEPTHRESIZE: string = 'depth:resize'

Fired when the depth sensing texture has been resized. The depthUvMatrix needs to be updated for relevant shaders. The handler is passed the new width and height of the depth texture in pixels.

Example

view.on('depth:resize', () => {
    material.setParameter('matrix_depth_uv', view.depthUvMatrix);
});

Inherited from RenderView

XrViews

Class · extends EventHandler · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-views.js#L17

Provides access to list of XrViews and information about their capabilities, such as support and availability of view's camera color texture, depth texture and other parameters.

Accessors

availableColor

get availableColor(): boolean

Check if Camera Color is available. This information becomes available only after session has started.

availableDepth

get availableDepth(): boolean

Check if Camera Depth is available. This information becomes available only after session has started.

depthGpuOptimized

get depthGpuOptimized(): boolean

Whether the depth sensing is GPU optimized.

depthPixelFormat

get depthPixelFormat(): 2 | 15 | null

The depth sensing pixel format. Can be:

list

get list(): XrView[]

An array of XrViews of this session. Views are not available straight away on session start, and can be added/removed mid-session. So use of add/remove events is required for accessing views.

supportedColor

get supportedColor(): boolean

Check if Camera Color is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions.

supportedDepth

get supportedDepth(): boolean

Check if Camera Depth is supported. It might be still unavailable even if requested, based on hardware capabilities and granted permissions.

Methods

get

get(eye: string): XrView | null

Get an XrView by its associated eye constant.

Parameters

Returns XrView | null: View or null if view of such eye is not available.

Events

EVENT_ADD

static EVENT_ADD: string = 'add'

Fired when a view has been added. Views are not available straight away on session start and are added mid-session. They can be added/removed mid session by the underlying system. The handler is passed the XrView that has been added.

Example

xr.views.on('add', (view) => {
    console.log('View added');
});

EVENT_REMOVE

static EVENT_REMOVE: string = 'remove'

Fired when a view has been removed. They can be added/removed mid session by the underlying system. The handler is passed the XrView that has been removed.

Example

xr.views.on('remove', (view) => {
    console.log('View removed');
});

Inherited from EventHandler

AnimCurvePath

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/evaluator/anim-curve.js#L5

Properties

component

component: string

The name of the component that owns the property, or graph for a transform on the entity itself.

entityPath

entityPath: string[]

The names of the entities from the animation root down to the target entity.

propertyPath

propertyPath: string[]

The property name segments, for example ['localPosition'] or ['weight.Smile'].

ArcShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/arc-shape.js#L13

Properties

ringRadius

ringRadius?: number

The ring radius.

sectorAngle

sectorAngle?: number

The sector angle.

tubeRadius

tubeRadius?: number

The tube radius.

ArrowShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/arrow-shape.js#L18

Properties

arrowLength

arrowLength?: number

The length of the arrow head

arrowThickness

arrowThickness?: number

The thickness of the arrow head

gap

gap?: number

The gap between the arrow base and the center

lineLength

lineLength?: number

The length of the line

lineThickness

lineThickness?: number

The thickness of the line

tolerance

tolerance?: number

The tolerance for intersection tests

AssetMap

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L65

Properties

animation

animation: Animation | AnimTrack

An animation: an AnimTrack when loaded from a glTF or GLB file, or a legacy Animation when loaded from JSON.

animclip

animclip: AnimTrack

An animation clip.

animstategraph

animstategraph: AnimStateGraph

An animation state graph.

audio

audio: Sound

A sound.

binary

binary: ArrayBuffer

The raw contents of the file.

bundle

bundle: Bundle

A bundle: an archive whose files back other assets.

container

container: ContainerResource

The renders, materials, textures, animations and gsplats of a glTF or GLB file.

css

css: string

The CSS text.

cubemap

cubemap: Texture | null

The cube map, or null when the asset provides only prefiltered levels. Asset#resources holds the cube map followed by its six prefiltered levels, with null for each level the asset does not provide.

folder

folder: null

Folders hold no resource.

font

font: Font | CanvasFont

A Font loaded from a font file.

gsplat

gsplat: GSplatResourceBase | GSplatOctreeResource

A Gaussian splat resource, or the octree resource of a level-of-detail splat scene.

hierarchy

hierarchy: Entity

The root entity of an instantiated scene hierarchy.

html

html: string

The HTML text.

json

json: unknown

The parsed JSON data.

material

material: Material

A material, a StandardMaterial unless a custom parser creates another kind.

model

model: Model

A model.

render

render: Render

The meshes of one glTF mesh, created when a container asset loads.

scene

scene: Scene

A scene.

scenesettings

scenesettings: any

The settings block of a scene file.

script

script: Record<string, typeof Script>

The script classes declared by a script file, keyed by class name.

shader

shader: string

The shader source text.

sprite

sprite: Sprite

A sprite.

template

template: Template

A template.

text

text: string

The text of the file.

texture

texture: Texture

A texture.

textureatlas

textureatlas: TextureAtlas

A texture atlas.

AttributeDescription

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/vertex-format.js#L71

Properties

asInt

asInt?: boolean

If true, vertex attribute data will be accessible as integer numbers in shader code. Defaults to false, which means that vertex attribute data will be accessible as floating point numbers. Can be only used with INT and UINT data types.

components

components: number

The number of components of the vertex attribute. Can be 1, 2, 3 or 4.

normalize

normalize?: boolean

If true, vertex attribute data will be mapped from a 0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data is left unchanged. If this property is unspecified, false is assumed. This property is ignored when asInt is true.

semantic

semantic: string

The meaning of the vertex element. This is used to link the vertex data to a shader input. Can be:

If vertex data has a meaning other that one of those listed above, use the user-defined semantics: SEMANTIC_ATTR0 to SEMANTIC_ATTR15.

type

type: number

The data type of the attribute. Can be:

AttributeSchema

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script-attributes.js#L160

Properties

array

array?: boolean

True if this attribute is an array of type

type

type: "string" | "number" | "boolean" | "rgb" | "curve" | "json" | "vec2" | "vec3" | "vec4" | "entity" | "asset" | "rgba"

The Attribute type

Bloom

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L82

Properties related to the HDR bloom effect, a postprocessing technique that simulates the natural glow of bright light sources by spreading their intensity beyond their boundaries, creating a soft and realistic blooming effect.

Properties

blurLevel

blurLevel: number

The number of iterations for blurring the bloom effect, with each level doubling the blur size. Once the blur size matches the dimensions of the render target, further blur passes are skipped. The default value is 16.

intensity

intensity: number

The intensity of the bloom effect, 0-0.1 range. Defaults to 0, making it disabled.

threshold

threshold: number

The brightness below which the scene does not contribute to bloom. Zero, the default, blooms the whole scene, which is the physically based behaviour; raising it restricts the glow to the brightest parts, with a soft transition below the threshold. The value is in the scene-referred units the scene is rendered in, before the exposure and tone mapping applied when the bloom is composited, so a scene lit for an exposure far from 1 needs the threshold scaled to match.

BoxLineShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/boxline-shape.js#L18

Properties

boxSize

boxSize?: number

The size of the box

gap

gap?: number

The gap between the box and the line

lineLength

lineLength?: number

The length of the line

lineThickness

lineThickness?: number

The thickness of the line

tolerance

tolerance?: number

The tolerance for intersection tests

BoxShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/box-shape.js#L10

Properties

size

size?: number

The size of the box.

ChunkValidation

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/shader-lib/shader-chunk-map.js#L5

Properties

callback

callback?: (arg0: string, arg1: string) => void

Validation callback receiving chunk name and code.

defaultCodeGLSL

defaultCodeGLSL?: string

Default GLSL code. If matches, no warning.

defaultCodeWGSL

defaultCodeWGSL?: string

Default WGSL code. If matches, no warning.

message

message?: string

Deprecation message to display.

ColorEnhance

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L170

Properties related to the color enhancement effect, a postprocessing technique that provides HDR-aware adjustments for shadows, highlights, vibrance, and dehaze. Shadows and highlights allow selective adjustment of dark and bright areas of the image, vibrance is a smart saturation that boosts less-saturated colors more than already-saturated ones, and dehaze removes atmospheric haze to increase clarity and contrast.

Properties

dehaze

dehaze: number

The dehaze adjustment, -1 to 1 range. Positive values remove atmospheric haze, increasing clarity and contrast. Negative values add a haze effect. Defaults to 0.

enabled

enabled: boolean

Whether color enhancement is enabled. Defaults to false.

highlights

highlights: number

The highlight adjustment, -3 to 3 range. Uses an exponential curve where -3 gives 0.125x, 0 gives 1x, and +3 gives 8x brightness on bright areas. Defaults to 0.

midtones

midtones: number

The midtone adjustment, -1 to 1 range. Positive values brighten midtones, negative values darken midtones, with shadows and highlights more strongly preserved than by a linear exposure change. Defaults to 0.

shadows

shadows: number

The shadow adjustment, -3 to 3 range. Uses an exponential curve where -3 gives 0.125x, 0 gives 1x, and +3 gives 8x brightness on dark areas. Defaults to 0.

vibrance

vibrance: number

The vibrance (smart saturation), -1 to 1 range. Positive values boost saturation of less-saturated colors more than already-saturated ones. Negative values desaturate. Defaults to 0.

ColorLUT

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L112

Properties related to the color lookup table (LUT) effect, a postprocessing technique used to apply a color transformation to the image. Two LUT slots are supported, which makes it easy to crossfade between two graded looks.

Properties

blend

blend: number

Crossfade between the two graded results, 0-1 range. 0 shows only the primary LUT, 1 shows only the secondary LUT, intermediate values produce a linear-space mix. Only used when texture2 is set. Defaults to 0.

intensity

intensity: number

The strength of the primary LUT, blended against the original color, 0-1 range. Defaults to 1.

intensity2

intensity2: number

The strength of the secondary LUT, blended against the original color, 0-1 range. Only used when texture2 is set. Defaults to 1.

texture

texture: Texture | null

The primary LUT texture. This must be a 256×16 2D "horizontal strip" texture representing an unwrapped 16×16×16 3D LUT in Unreal Engine layout: 16 horizontal slices along the blue axis, with each slice mapping red to the X-axis and green to the Y-axis. Note that HALD LUTs (e.g. from ImageMagick) and Unity LUTs use different layouts and are not compatible. The texture must be loaded with srgb: true (LUTs are authored in sRGB display space — the Unreal / Photoshop workflow stores sRGB-encoded values indexed by sRGB-encoded coordinates), mipmaps: false (sampled at LOD 0 only), and minFilter: FILTER_LINEAR / magFilter: FILTER_LINEAR (bilinear filtering between LUT entries is required to avoid visible banding). The engine emits a debug-build warning if any of these are misconfigured. Defaults to null.

texture2

texture2: Texture | null

The optional secondary LUT texture, same format and requirements as texture. When set, both LUTs are sampled and the two graded results are crossfaded according to blend. Defaults to null.

Dof

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L203

Properties related to Depth of Field (DOF), a technique used to simulate the optical effect where objects at certain distances appear sharp while others are blurred, enhancing the perception of focus and depth in the rendered scene.

Properties

blurRadius

blurRadius: number

The radius of the blur effect, typically 2-10 range. Defaults to 3.

blurRingPoints

blurRingPoints: number

The number of points in each ring of the blur effect, typically 3-8 range. Defaults to 5.

blurRings

blurRings: number

The number of rings in the blur effect, typically 3-8 range. Defaults to 4.

enabled

enabled: boolean

Whether DoF is enabled. Defaults to false.

focusDistance

focusDistance: number

The distance at which the focus is set. Defaults to 100.

focusRange

focusRange: number

The range around the focus distance where the focus is sharp. Defaults to 10.

highQuality

highQuality: boolean

Whether the high quality implementation is used. This will have a higher performance cost, but will produce better quality results. Defaults to true.

nearBlur

nearBlur: boolean

Whether the near blur is enabled. Defaults to false.

Fringing

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L162

Properties related to the fringing effect, a chromatic aberration phenomenon where the red, green, and blue color channels diverge increasingly with greater distance from the center of the screen.

Properties

intensity

intensity: number

The intensity of the fringing effect, 0-100 range. Defaults to 0, making it disabled.

GizmoTheme

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/transform-gizmo.js#L28

Properties

disabled

disabled: Color

The disabled color.

guideBase

guideBase: { x: Color; y: Color; z: Color }

The guide line colors.

Properties

guideOcclusion

guideOcclusion: number

The guide occlusion value. Defaults to 0.8.

shapeBase

shapeBase: { f: Color; x: Color; xyz: Color; y: Color; z: Color }

The axis colors.

Properties

shapeHover

shapeHover: { f: Color; x: Color; xyz: Color; y: Color; z: Color }

The hover colors.

Properties

Grading

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L100

Properties related to the color grading effect, a postprocessing technique used to adjust and the visual tone of an image. This effect modifies brightness, contrast, saturation, and overall color balance to achieve a specific aesthetic or mood.

Properties

brightness

brightness: number

The brightness of the grading effect, 0-3 range. Defaults to 1.

contrast

contrast: number

The contrast of the grading effect, 0.5-1.5 range. Defaults to 1.

enabled

enabled: boolean

Whether grading is enabled. Defaults to false.

saturation

saturation: number

The saturation of the grading effect, 0-2 range. Defaults to 1.

tint

tint: Color

The tint color of the grading effect. Defaults to white.

GSplatProcessorBinding

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/gsplat/gsplat-processor.js#L23

Configuration object specifying a data binding for GSplatProcessor. Defines where to read from (source) or write to (destination) including the resource, component for instance textures, and which streams to access.

Properties

component

component?: GSplatComponent

Component for instance textures. If provided, resource is automatically resolved from the component.

resource

resource?: GSplatResourceBase

Resource to read/write from.

streams

streams?: string[]

Names of streams to read/write. For destination, this is required. For source, if omitted, all format streams except destination streams are used automatically, providing getCenter/getColor/etc functions. Specify explicitly to limit which streams are bound.

GSplatStreamDescriptor

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat/gsplat-format.js#L31

Properties

format

format: number

The pixel format of the texture (e.g. PIXELFORMAT_RGBA32F). When used as an extra stream for work buffers or as a destination stream for GSplatProcessor, the format must be renderable as these textures are used as render targets. Ensure the format is renderable on all target devices. See Texture for details on renderable formats and device capabilities.

name

name: string

The name of the stream (used as texture uniform name).

storage

storage?: number

Storage type: GSPLAT_STREAM_RESOURCE (default, shared across instances) or GSPLAT_STREAM_INSTANCE (per-component instance). Note: Work buffer formats (accessed via app.scene.gsplat.format) do not support GSPLAT_STREAM_INSTANCE.

GSplatVaryingDescriptor

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/gsplat-unified/gsplat-varyings.js#L24

Properties

components

components: number

The number of components, 1 to 4.

name

name: string

The varying name. Must be a valid shader identifier.

type

type: number

The component data type: TYPE_FLOAT32, TYPE_INT32 or TYPE_UINT32.

MiniStatsGraphOptions

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L66

Properties

decimalPlaces

decimalPlaces?: number

Number of decimal places (defaults to none).

multiplier

multiplier?: number

Multiplier applied to sampled values, for example to convert bytes to megabytes.

name

name: string

Display name.

stats

stats: string[]

Path to data inside Application.stats.

unitsName

unitsName?: string

Units (defaults to "").

watermark

watermark?: number

Watermark - shown as a line on the graph, useful for displaying a budget.

MiniStatsOptions

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L78

Properties

cpu

cpu: MiniStatsProcessorOptions

CPU graph options.

cpuTimingMinSize

cpuTimingMinSize?: number

Minimum size index at which to show CPU sub-timing graphs (script, anim, physics, render). Defaults to 1.

gpu

gpu: MiniStatsProcessorOptions

GPU graph options.

gpuTimingMinSize

gpuTimingMinSize?: number

Minimum size index at which to show GPU pass timing graphs. Defaults to 1.

resourcesCollapsed

resourcesCollapsed?: boolean

Initially collapse the Resources section.

resourcesEnabled

resourcesEnabled?: boolean

Show tracked resource counts in detailed views.

sizes

sizes: MiniStatsSizeOptions[]

Sizes of area to render individual graphs in and spacing between individual graphs.

startSizeIndex

startSizeIndex: number

Index into sizes array for initial setting.

stats

stats: MiniStatsGraphOptions[]

Array of options to render additional graphs based on stats collected into Application.stats. Counters sourced exclusively from AppStats.user are displayed in a collapsible User section in the detailed views. Other additional counters are grouped under Engine, including DrawCalls and Frame. VRAM keeps its own category.

textRefreshRate

textRefreshRate: number

Text update interval and averaging window in ms (500 in the default options). Each update shows the arithmetic mean and peak of the frame samples collected since the previous update, then starts a new window. Graph history samples every frame.

vramTimingMinSize

vramTimingMinSize?: number

Minimum size index at which to show VRAM subcategory graphs. Defaults to 1.

MiniStatsProcessorOptions

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L59

Properties

enabled

enabled: boolean

Whether to show the graph.

watermark

watermark: number

Watermark - shown as a line on the graph, useful for displaying a budget.

MiniStatsSizeOptions

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/mini-stats/mini-stats.js#L48

Properties

detailed

detailed?: boolean

Show category headers and sub-counters. Defaults to true for sizes after the first, or when graphs are enabled.

graphs

graphs: boolean

Whether to show graphs.

height

height: number

Height of the graph area.

peak

peak?: boolean

Show a peak column in the detailed view. Defaults to the graphs setting.

spacing

spacing: number

Spacing between graphs.

width

width: number

Width of the graph area.

ParserContext

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L22

Properties

app

app: AppBase

The running AppBase.

asset

asset: Asset<string> | undefined

The asset being loaded, if any.

basename

basename: string

The lower-cased file name (for example 'lod-meta.json'), or an empty string.

ext

ext: string

The lower-cased file extension without a leading dot (for example 'json'), or an empty string if there is none.

url

url: string | null

The original resource URL with any query string removed, or null.

PlaneShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/plane-shape.js#L14

Properties

gap

gap?: number

The gap between the plane and the center

size

size?: number

The size of the plane

PlyElement

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L26

Properties

count

count: number

Given count.

name

name: string

E.g. 'vertex'.

properties

properties: PlyProperty[]

The properties.

PlyProperty

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L18

Properties

byteSize

byteSize: number

BYTES_PER_ELEMENT of given data type.

name

name: string

E.g. 'x', 'y', 'z', 'f_dc_0' etc.

storage

storage: DataType

Data type, e.g. instance of Float32Array.

type

type: string

E.g. 'float'.

Rendering

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L18

Properties related to scene rendering, encompassing settings that control the rendering resolution, pixel format, multi-sampling for anti-aliasing, tone-mapping and similar.

Properties

renderFormats

renderFormats: number[]

The preferred render formats of the frame buffer, in order of preference. First format from this list that is supported by the hardware is used. When none of the formats are supported, PIXELFORMAT_RGBA8 is used, but this automatically disables bloom effect, which requires HDR format. The list can contain the following formats: PIXELFORMAT_111110F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F and PIXELFORMAT_RGBA8. Typically the default option should be used, which prefers the faster formats, but if higher dynamic range is needed, the list can be adjusted to prefer higher precision formats. Defaults to [PIXELFORMAT_111110F, PIXELFORMAT_RGBA16F, PIXELFORMAT_RGBA32F].

renderTargetScale

renderTargetScale: number

The scale of the render target, 0.1-1 range. This allows the scene to be rendered to a lower resolution render target as an optimization. The post-processing is also applied at this lower resolution. The image is then up-scaled to the full resolution and any UI rendering that follows is applied at the full resolution. Defaults to 1 which represents full resolution rendering.

samples

samples: number

The number of samples of the RenderTarget used for the scene rendering, in 1-4 range. Value of 1 disables multisample anti-aliasing, other values enable anti-aliasing, Typically set to 1 when TAA is used, even though both anti-aliasing options can be used together at a higher cost. Defaults to 1.

sceneColorMap

sceneColorMap: boolean

Whether rendering generates a scene color map. Defaults to false.

sceneDepthMap

sceneDepthMap: boolean

Whether rendering generates a scene depth map. Defaults to false.

sharpness

sharpness: number

The sharpening intensity, 0-1 range. This can be used to increase the sharpness of the rendered image. Often used to counteract the blurriness of the TAA effect, but also blurriness caused by rendering to a lower resolution render target by using rendering.renderTargetScale property. Defaults to 0.

stencil

stencil: boolean

Whether the render buffer has a stencil buffer. Defaults to false.

toneMapping

toneMapping: number

The tone mapping. Can be:

Defaults to TONEMAP_LINEAR.

ResourceParser

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L39

Properties

canParse

canParse: (context: ParserContext) => boolean

Returns true if this parser can handle the described resource. Parsers are consulted newest-first; the first to return true is used.

handler

handler?: ResourceHandler

Assigned by the owning handler on registration; available in load/open (for example this.handler.fetch(...)).

load

load: (url: string | { load: string; original: string }, callback: ResourceHandlerCallback, asset?: Asset<string>) => void

Fetches (typically via this.handler.fetch) and produces the resource, then invokes the callback.

open

open?: (url: string, data: any, asset?: Asset<string>) => any

Optional. Called by the default ResourceHandler#open when parsers are registered. Handlers that override open may call it with an extended signature - for example the texture handler calls open(url, data, device, textureOptions) on its parsers.

ScriptInitializationArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script/script.js#L278

Properties

app

app: AppBase

The AppBase that is running the script.

enabled

enabled?: boolean

True if the script instance is in running state.

entity

entity: Entity

The Entity that the script is attached to.

ShaderDesc

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/shader-material.js#L12

Defines the vertex and fragment shader source for ShaderMaterial, supporting both GLSL and WGSL formats. WebGL always uses the GLSL code. WebGPU prefers the WGSL code if available, otherwise it automatically transpiles the provided GLSL code at runtime.

Properties

attributes

attributes?: {}

Object detailing the mapping of vertex shader attribute names to semantics SEMANTIC_*. This enables the engine to match vertex buffer data as inputs to the shader. Defaults to undefined, which generates the default attributes.

fragmentGLSL

fragmentGLSL?: string

The fragment shader code in GLSL.

fragmentOutputTypes

fragmentOutputTypes?: string | string[]

Fragment shader output types, which default to vec4. Passing a string will set the output type for all color attachments. Passing an array will set the output type for each color attachment.

fragmentWGSL

fragmentWGSL?: string

The fragment shader code in WGSL.

uniqueName

uniqueName: string

Unique name for the shader. If a shader with this name already exists, it will be returned instead of a new shader instance.

vertexGLSL

vertexGLSL?: string

The vertex shader code in GLSL.

vertexWGSL

vertexWGSL?: string

The vertex shader code in WGSL.

ShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/shape.js#L24

Properties

axis

axis?: string

The axis of the shape (e.g., 'x', 'y', 'z').

cull

cull?: number

The culling mode of the shape.

defaultColor

defaultColor?: Color

The default color of the shape.

depth

depth?: number

The depth of the shape. -1 = interpolated depth.

disabled

disabled?: boolean

Whether the shape is disabled.

disabledColor

disabledColor?: Color

The disabled color of the shape.

hoverColor

hoverColor?: Color

The hover color of the shape.

layers

layers?: number[]

The layers the shape belongs to.

position

position?: Vec3

The position of the shape.

rotation

rotation?: Vec3

The rotation of the shape.

scale

scale?: Vec3

The scale of the shape.

visible

visible?: boolean

Whether the shape is visible.

SphereShapeArgs

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/shape/sphere-shape.js#L10

Properties

radius

radius?: number

The radius of the sphere.

Ssao

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L58

Properties related to the Screen Space Ambient Occlusion (SSAO) effect, a postprocessing technique that approximates ambient occlusion by calculating how exposed each point in the screen space is to ambient light, enhancing depth perception and adding subtle shadowing in crevices and between objects.

Properties

blurEnabled

blurEnabled: boolean

Whether the SSAO effect is blurred. Defaults to true.

intensity

intensity: number

The intensity of the SSAO effect, 0-1 range. Defaults to 0.5.

minAngle

minAngle: number

The minimum angle of the SSAO effect, 1-90 range. Defaults to 10.

power

power: number

The power of the SSAO effect, 0.1-10 range. Defaults to 6.

radius

radius: number

The radius of the SSAO effect, 0-100 range. Defaults to 30.

randomize

randomize: boolean

Whether the SSAO sampling is randomized. Useful when used instead of blur effect together with TAA. Defaults to false.

samples

samples: number

The number of samples of the SSAO effect, 1-64 range. Defaults to 12.

scale

scale: number

The scale of the SSAO effect, 0.5-1 range. Defaults to 1.

type

type: string

The type of the SSAO determines how it is applied in the rendering process. Defaults to SSAOTYPE_NONE. Can be:

Taa

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L192

Properties related to temporal anti-aliasing (TAA), which is a technique used to reduce aliasing in the rendered image by blending multiple frames together over time.

Properties

enabled

enabled: boolean

Whether TAA is enabled. Defaults to false.

jitter

jitter: number

The intensity of the camera jitter, 0-1 range. The larger the value, the more jitter is applied to the camera, making the anti-aliasing effect more pronounced. This also makes the image more blurry, and rendering.sharpness parameter can be used to counteract. Defaults to 1.

TransformFeedbackStream

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/transform-feedback.js#L16

Properties

input

input?: VertexBuffer

A buffer read by the shader as a vertex stream.

output

output?: VertexBuffer

A buffer written by transform feedback.

Vignette

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L139

Properties related to the vignette effect, a postprocessing technique that darkens the image edges, creating a gradual falloff in brightness from the center outward. The effect can be also reversed, making the center of the image darker than the edges, by specifying the outer distance smaller than the inner distance.

Properties

color

color: Color

The color of the vignette effect. Defaults to black.

curvature

curvature: number

The curvature of the vignette effect, 0.01-10 range. The vignette is rendered using a rectangle with rounded corners, and this parameter controls the curvature of the corners. Value of 1 represents a circle. Smaller values make the corners more square, while larger values make them more rounded. Defaults to 0.5.

inner

inner: number

The inner distance of the vignette effect measured from the center of the screen, 0-3 range. This is where the vignette effect starts. Value larger than 1 represents the value off screen, which allows more control. Defaults to 0.5, representing half the distance from center.

intensity

intensity: number

The intensity of the vignette effect, 0-1 range. Defaults to 0, making it disabled.

outer

outer: number

The outer distance of the vignette effect measured from the center of the screen, 0-3 range. This is where the vignette reaches full intensity. Value larger than 1 represents the value off screen, which allows more control. Defaults to 1, representing the full screen.

VolumetricFog

Interface · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/camera-frame.js#L222

Properties related to volumetric fog, a raymarched height fog lit by a directional light. The fog samples the light's cascaded shadow map along each view ray, forming visible shafts of light. The raymarch runs at a reduced resolution and is blended into the scene before TAA, so when TAA is enabled, its noise is temporally resolved to a smooth result. Optionally the clustered omni and spot lights scatter light in the fog as well, see localOmniLights and localSpotLights.

Properties

ambientColor

ambientColor: Color

The color of the ambient in-scattered light, which keeps the fog in shadowed areas visible. Defaults to white.

ambientIntensity

ambientIntensity: number

The intensity of the ambient in-scattered light. Defaults to 0.02.

anisotropy

anisotropy: number

The anisotropy of the scattering, 0-0.95 range. Larger values scatter more light forward, making the fog brighter when looking towards the light. Defaults to 0.6.

density

density: number

The fog density at the base height. Defaults to 0.01.

enabled

enabled: boolean

Whether the volumetric fog is enabled. Defaults to false.

extinction

extinction: number

A scale of how quickly the fog absorbs the light passing through it, without affecting how much light it scatters. A value of 1 is physically consistent, where the fog absorbs as much as it scatters, and distant fog and light shafts fade out exponentially with the density. Lower values keep them visible over a longer distance while the fog itself stays as bright, which is not physically correct but is often preferable. Defaults to 1.

heightBase

heightBase: number

The world space height at which the fog density starts to fall off. Below it the density is constant. Defaults to 0.

heightFalloff

heightFalloff: number

The exponential falloff of the fog density with height above the base height. Value of 0 makes the fog uniform. Defaults to 0.05.

intensity

intensity: number

The intensity of the light scattering. Defaults to 1.

light

light: LightComponent | null

The directional light providing the scattered light, or null when the fog is lit by the local lights and the ambient term only. When a light of a type other than directional is assigned, the effect is disabled. Defaults to null.

localIntensity

localIntensity: number

The intensity of the light scattering of the local lights. Defaults to 1.

localOmniLights

localOmniLights: boolean

Whether the clustered omni lights scatter light in the fog. Each light adds a raymarch over the part of the view rays inside its volume, sampling the shadow and the cookie atlas of the clustered lighting, and so the cost scales with the screen space size of the light volumes. As an omni light fills its whole bounding sphere, its volume is typically much larger on the screen than the volume of a spot light. Requires clustered lighting, which is enabled by default. Individual lights can scatter more or less light using LightComponent#volumetricScattering. Defaults to false.

localSpotLights

localSpotLights: boolean

Whether the clustered spot lights scatter light in the fog, forming visible beams. See localOmniLights for details, both types are rendered the same way and share the localIntensity and localSteps settings. Defaults to false.

localSteps

localSteps: number

The number of raymarching steps taken inside the volume of each local light, 2-64 range. Defaults to 12.

maxDistance

maxDistance: number

The maximum world space distance the fog is raymarched to. Defaults to 300.

scale

scale: number

The resolution scale of the fog texture relative to the scene render target, 0.25-1 range. Defaults to 0.5.

steps

steps: number

The number of raymarching steps, 4-128 range. Higher values improve the quality at a higher performance cost. Defaults to 24.

tint

tint: Color

The albedo of the fog. Defaults to white.

AssetReadyCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L126

Callback used by Asset#ready and called when an asset is ready.

type AssetReadyCallback<K extends AssetType | string & {}> = (asset: Asset<K>) => void

AssetResource

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L121

type AssetResource<K extends AssetType | string & {}> = K extends AssetType ? AssetMap[K] : unknown

AssetType

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset.js#L112

type AssetType = keyof AssetMap & string

BundlesFilterCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L36

Callback used by ResourceLoader#load and called when an asset is choosing a bundle to load from. Return a single bundle to ensure asset is loaded from it.

type BundlesFilterCallback = (bundles: Asset[]) => Asset

CalculateMatrixCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/component.js#L27

Callback used by CameraComponent#calculateTransform and CameraComponent#calculateProjection.

type CalculateMatrixCallback = (transformMatrix: Mat4, view: number) => void

CalculateSortDistanceCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh-instance.js#L190

Callback used by Layer to calculate the "sort distance" for a MeshInstance, which determines its place in the render order.

type CalculateSortDistanceCallback = (meshInstance: MeshInstance, cameraPosition: Vec3, cameraForward: Vec3) => number

ChangeSceneCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L27

Callback used by SceneRegistry#changeScene.

type ChangeSceneCallback = (err: string | null, entity?: Entity) => void

ComponentMap

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L52

type ComponentMap = { [K in keyof Entity as NonNullable<Entity[K]> extends Component ? K : never]: NonNullable<Entity[K]> }

ComponentName

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L65

type ComponentName = keyof ComponentMap & string

ComponentOptions

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/entity.js#L77

type ComponentOptions<K extends ComponentName> = { [P in keyof MergedComponentOptions<K>]: MergedComponentOptions<K>[P] }

ConfigureAppCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L69

Callback used by AppBase#configure when configuration file is loaded and parsed (or an error occurs).

type ConfigureAppCallback = Object

CreateScreenCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/script.js#L8

Callback used by script.createLoadingScreen.

type CreateScreenCallback = (app: AppBase) => void

DataType

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/ply.js#L14

type DataType = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array

FilterAssetCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L18

Callback used by AssetRegistry#filter to filter assets.

type FilterAssetCallback = (asset: Asset) => boolean

FindNodeCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L72

Callback used by GraphNode#find and GraphNode#findOne to search through a graph node and all of its descendants.

type FindNodeCallback = (node: GraphNode) => boolean

ForEachNodeCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/graph-node.js#L81

Callback used by GraphNode#forEach to iterate through a graph node and all of its descendants.

type ForEachNodeCallback = (node: GraphNode) => void

GizmoAxis

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L24

type GizmoAxis = "x" | "y" | "z" | "yz" | "xz" | "xy" | "xyz" | "f"

GizmoDragMode

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L35

type GizmoDragMode = "show" | "hide" | "selected"

GizmoSpace

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/gizmo/constants.js#L8

type GizmoSpace = "local" | "world"

HandleEventCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/event-handler.js#L4

Callback used by EventHandler functions. Note the callback is limited to 8 arguments.

type HandleEventCallback = (arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any) => void

HttpResponseCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/net/http.js#L13

Callback used by Http#get, Http#post, Http#put, Http#del, and Http#request.

type HttpResponseCallback = (err: number | string | Error | null, response?: any) => void

LoadAssetCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/asset-registry.js#L26

Callback used by AssetRegistry#loadFromUrl and called when an asset is loaded (or an error occurs).

type LoadAssetCallback<K extends AssetType | string & {}> = (err: string | null, asset?: Asset<K>) => void

LoadHierarchyCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L12

Callback used by SceneRegistry#loadSceneHierarchy.

type LoadHierarchyCallback = (err: string | null, entity?: Entity) => void

LoadSceneCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L35

Callback used by SceneRegistry#loadScene.

type LoadSceneCallback = (err: string | null, entity?: Entity) => void

LoadSceneDataCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L43

Callback used by SceneRegistry#loadSceneData.

type LoadSceneDataCallback = (err: string | null, sceneItem?: SceneRegistryItem) => void

LoadSettingsCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/scene-registry.js#L20

Callback used by SceneRegistry#loadSceneSettings.

type LoadSettingsCallback = (err: string | null) => void

LockMouseCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/mouse.js#L6

Callback used by Mouse#enablePointerLock and Mouse#disablePointerLock.

type LockMouseCallback = () => void

ModuleErrorCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L113

Callback used by WasmModule.setConfig.

type ModuleErrorCallback = (error: string) => void

ModuleInstanceCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/wasm-module.js#L120

Callback used by WasmModule.getInstance.

type ModuleInstanceCallback = (moduleInstance: any) => void

NumericArray

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/mesh.js#L30

type NumericArray = number[] | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array

PreloadAppCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/app-base.js#L77

Callback used by AppBase#preload when all assets (marked as 'preload') are loaded.

type PreloadAppCallback = Object

ResourceHandlerCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/handler.js#L12

Callback used by ResourceHandler#load when a resource is loaded (or an error occurs).

type ResourceHandlerCallback = (err: string | null, response?: any) => void

ResourceLoaderCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/loader.js#L14

Callback used by ResourceLoader#load when a resource is loaded (or an error occurs).

type ResourceLoaderCallback = (err: string | null, resource?: any) => void

UpdateShaderCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/materials/standard-material.js#L157

Callback used by StandardMaterial#onUpdateShader.

type UpdateShaderCallback = (options: StandardMaterialOptions) => StandardMaterialOptions

XrAnchorCreateCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchors.js#L13

Callback used by XrAnchors#create.

type XrAnchorCreateCallback = (err: Error | null, anchor: XrAnchor | null) => void

XrAnchorForgetCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L19

Callback used by XrAnchor#forget.

type XrAnchorForgetCallback = (err: Error | null) => void

XrAnchorPersistCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-anchor.js#L10

Callback used by XrAnchor#persist.

type XrAnchorPersistCallback = (err: Error | null, uuid: string | null) => void

XrErrorCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L38

Callback used by XrManager#start and XrManager#end.

type XrErrorCallback = (err: Error | null) => void

XrHitTestStartCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-hit-test.js#L13

Callback used by XrHitTest#start and XrInputSource#hitTestStart.

type XrHitTestStartCallback = (err: Error | null, hitTestSource: XrHitTestSource | null) => void

XrRoomCaptureCallback

Type alias · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/xr-manager.js#L45

Callback used by XrManager#initiateRoomCapture.

type XrRoomCaptureCallback = (err: Error | null) => void

basisInitialize

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/handlers/basis.js#L268

basisInitialize(config?: object): void

Initialize the Basis transcode worker.

Parameters

dracoDecode

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/draco-decoder.js#L266

dracoDecode(buffer: ArrayBuffer, callback: Function): boolean

Enqueue a buffer for decoding.

Parameters

Returns boolean: True if the draco worker was initialized and false otherwise.

dracoInitialize

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/parsers/draco-decoder.js#L251

dracoInitialize(config?: object): void

Initialize the Draco mesh decoder.

Parameters

guid.create

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/guid.js#L13

create(): string

Create an RFC4122 version 4 compliant GUID.

Returns string: A new GUID.

path.extractPath

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L180

extractPath(pathname: string): string

Return the path without file name. If path is relative path, start with period.

Parameters

Returns string: The path without a last element from list split by slash.

Example

path.extractPath("path/to/file.txt");    // returns "./path/to"
path.extractPath("./path/to/file.txt");  // returns "./path/to"
path.extractPath("../path/to/file.txt"); // returns "../path/to"
path.extractPath("/path/to/file.txt");   // returns "/path/to"

path.getBasename

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L116

getBasename(pathname: string): string

Return the basename of the path. That is the second element of the pair returned by passing path into path.split.

Parameters

Returns string: The basename.

Example

path.getBasename("/path/to/file.txt"); // returns "file.txt"
path.getBasename("/path/to/dir"); // returns "dir"

path.getDirectory

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L127

getDirectory(pathname: string): string

Get the directory name from the path. This is everything up to the final instance of path.delimiter.

Parameters

Returns string: The directory part of the path.

path.getExtension

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L142

getExtension(pathname: string): string

Return the extension of the path. Pop the last value of a list after path is split by question mark and comma.

Parameters

Returns string: The extension.

Example

path.getExtension("/path/to/file.txt"); // returns ".txt"
path.getExtension("/path/to/file.jpg"); // returns ".jpg"
path.getExtension("/path/to/file.txt?function=getExtension"); // returns ".txt"

path.isRelativePath

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L165

isRelativePath(pathname: string): boolean

Check if a string s is relative path.

Parameters

Returns boolean: True if s doesn't start with slash and doesn't include colon and double slash.

Example

path.isRelativePath("file.txt"); // returns true
path.isRelativePath("path/to/file.txt"); // returns true
path.isRelativePath("./path/to/file.txt"); // returns true
path.isRelativePath("../path/to/file.jpg"); // returns true
path.isRelativePath("/path/to/file.jpg"); // returns false
path.isRelativePath("http://path/to/file.jpg"); // returns false

path.join

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L26

join(...sections: string[]): string

Join two or more sections of file path together, inserting a delimiter if needed.

Parameters

Returns string: The joined file path.

Example

const joinedPath = path.join('foo', 'bar');
console.log(joinedPath); // Prints 'foo/bar'

Example

const joinedPath = path.join('alpha', 'beta', 'gamma');
console.log(joinedPath); // Prints 'alpha/beta/gamma'

path.normalize

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L54

normalize(pathname: string): string

Normalize the path by removing '.' and '..' instances.

Parameters

Returns string: The normalized path.

path.split

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L98

split(pathname: string): string[]

Split the pathname path into a pair [head, tail] where tail is the final part of the path after the last delimiter and head is everything leading up to that. tail will never contain a slash.

Parameters

Returns string[]: The split path which is an array of two strings, the path and the filename.

string.format

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L137

format(s: string, ...args: any[]): string

Return a string with {n} replaced with the n-th argument.

Parameters

Returns string: The formatted string.

Example

const s = string.format("Hello {0}", "world");
console.log(s); // Prints "Hello world"

string.getCodePoint

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L152

getCodePoint(string: string, i?: number): number

Get the code point number for a character in a string. Polyfill for [codePointAt]https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt.

Parameters

Returns number: The code point value for the character in the string.

string.getCodePoints

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L163

getCodePoints(string: string): number[]

Gets an array of all code points in a string.

Parameters

Returns number[]: The code points in the string.

string.getSymbols

Function · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L186

getSymbols(string: string): string[]

Gets an array of all grapheme clusters (visible symbols) in a string. This is needed because some symbols (such as emoji or accented characters) are actually made up of multiple character codes. See here for more info.

Parameters

Returns string[]: The symbols in the string.

path.delimiter

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L12

The character that separates path segments.

const delimiter: string = '/'

platform.android

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L111

True if running on an Android device.

const android: boolean

platform.browser

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L75

Convenience boolean indicating whether we're running in the browser.

const browser: boolean

platform.desktop

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L90

True if running on a desktop or laptop device.

const desktop: boolean

platform.environment

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L57

String identifying the current runtime environment. Either 'browser', 'node' or 'worker'.

const environment: "worker" | "browser" | "node" = environment

platform.gamepads

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L133

True if the platform supports gamepads.

const gamepads: boolean = gamepads

platform.global

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L65

The global object. This will be the window object when running in a browser and the global object when running in nodejs and self when running in a worker.

const global: any

platform.ios

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L104

True if running on an iOS device.

const ios: boolean

platform.mobile

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L97

True if running on a mobile or tablet device.

const mobile: boolean

platform.touch

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L140

True if the platform supports touch input.

const touch: boolean = touch

platform.workers

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L147

True if the platform supports Web Workers.

const workers: boolean = workers

platform.xbox

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L126

True if running on an Xbox device.

const xbox: boolean = xbox

revision

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/core.js#L10

The engine revision number. This is the Git hash of the last commit made to the branch from which the engine was built.

const revision: "$_CURRENT_SDK_REVISION" = '$_CURRENT_SDK_REVISION'

version

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/core.js#L4

The engine version number. This is in semantic versioning format (MAJOR.MINOR.PATCH).

const version: "$_CURRENT_SDK_VERSION" = '$_CURRENT_SDK_VERSION'

guid

Namespace · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/guid.js#L7

Basically a very large random number (128-bit) which means the probability of creating two that clash is vanishingly small. GUIDs are used as the unique identifiers for Entities.

Members

path

Namespace · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/path.js#L6

File path API.

Members

platform

Namespace · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/platform.js#L42

Global namespace that stores flags regarding platform environment and features support.

Example

if (platform.touch) {
    // touch is supported
}

Members

string

Namespace · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L105

Extended String API.

Members

PlayCanvas Engine API: Other Types

78 interfaces and type aliases without a category, mostly the types of other symbols' parameters and results.

Engine API Reference: Constants

679 constants by category, grouped by prefix, with their values. The page of each constant, with its description, is at https://api.playcanvas.com/engine/variables/<NAME>.md.

Animation

Asset

Debug

Graphics

Input Devices

Math

Physics

Sound

User Interface

XR

Other

math.DEG_TO_RAD

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L13

Conversion factor between degrees and radians.

const DEG_TO_RAD: number

math.RAD_TO_DEG

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/math.js#L20

Conversion factor between radians and degrees.

const RAD_TO_DEG: number

string.ASCII_LETTERS

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L125

All ASCII letters.

const ASCII_LETTERS: string = ASCII_LETTERS

string.ASCII_LOWERCASE

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L111

All lowercase letters.

const ASCII_LOWERCASE: string = ASCII_LOWERCASE

string.ASCII_UPPERCASE

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/string.js#L118

All uppercase letters.

const ASCII_UPPERCASE: string = ASCII_UPPERCASE

ADDRESS_CLAMP_TO_EDGE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L13

Clamps texture coordinate to the range 0 to 1.

const ADDRESS_CLAMP_TO_EDGE: 1 = 1

ADDRESS_MIRRORED_REPEAT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L21

Texture coordinate to be set to the fractional part if the integer part is even. If the integer part is odd, then the texture coordinate is set to 1 minus the fractional part.

const ADDRESS_MIRRORED_REPEAT: 2 = 2

ADDRESS_REPEAT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L6

Ignores the integer part of texture coordinates, using only the fractional part.

const ADDRESS_REPEAT: 0 = 0

ANIM_BLEND_1D

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L112

const ANIM_BLEND_1D: string = '1D'

ANIM_BLEND_2D_CARTESIAN

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L124

const ANIM_BLEND_2D_CARTESIAN: string = '2D_CARTESIAN'

ANIM_BLEND_2D_DIRECTIONAL

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L118

const ANIM_BLEND_2D_DIRECTIONAL: string = '2D_DIRECTIONAL'

ANIM_BLEND_DIRECT

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L130

const ANIM_BLEND_DIRECT: string = 'DIRECT'

ANIM_EQUAL_TO

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L71

Used to set an anim state graph transition condition predicate as '==='.

const ANIM_EQUAL_TO: "EQUAL_TO" = 'EQUAL_TO'

ANIM_GREATER_THAN

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L43

Used to set an anim state graph transition condition predicate as '>'.

const ANIM_GREATER_THAN: "GREATER_THAN" = 'GREATER_THAN'

ANIM_GREATER_THAN_EQUAL_TO

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L57

Used to set an anim state graph transition condition predicate as '>='.

const ANIM_GREATER_THAN_EQUAL_TO: "GREATER_THAN_EQUAL_TO" = 'GREATER_THAN_EQUAL_TO'

ANIM_INTERRUPTION_NEXT

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L20

Used to set the anim state graph transition interruption source as the next state only.

const ANIM_INTERRUPTION_NEXT: "NEXT_STATE" = 'NEXT_STATE'

ANIM_INTERRUPTION_NEXT_PREV

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L36

Used to set the anim state graph transition interruption sources as the next state followed by the previous state.

const ANIM_INTERRUPTION_NEXT_PREV: "NEXT_STATE_PREV_STATE" = 'NEXT_STATE_PREV_STATE'

ANIM_INTERRUPTION_NONE

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L6

Used to set the anim state graph transition interruption source to no state.

const ANIM_INTERRUPTION_NONE: "NONE" = 'NONE'

ANIM_INTERRUPTION_PREV

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L13

Used to set the anim state graph transition interruption source as the previous state only.

const ANIM_INTERRUPTION_PREV: "PREV_STATE" = 'PREV_STATE'

ANIM_INTERRUPTION_PREV_NEXT

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L28

Used to set the anim state graph transition interruption sources as the previous state followed by the next state.

const ANIM_INTERRUPTION_PREV_NEXT: "PREV_STATE_NEXT_STATE" = 'PREV_STATE_NEXT_STATE'

ANIM_LAYER_ADDITIVE

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L167

Used to indicate that a layers animations should blend additively with previous layers.

const ANIM_LAYER_ADDITIVE: "ADDITIVE" = 'ADDITIVE'

ANIM_LAYER_OVERWRITE

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L160

Used to indicate that a layers animations should overwrite all previous layers.

const ANIM_LAYER_OVERWRITE: "OVERWRITE" = 'OVERWRITE'

ANIM_LESS_THAN

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L50

Used to set an anim state graph transition condition predicate as '<'.

const ANIM_LESS_THAN: "LESS_THAN" = 'LESS_THAN'

ANIM_LESS_THAN_EQUAL_TO

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L64

Used to set an anim state graph transition condition predicate as '<='.

const ANIM_LESS_THAN_EQUAL_TO: "LESS_THAN_EQUAL_TO" = 'LESS_THAN_EQUAL_TO'

ANIM_NOT_EQUAL_TO

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L78

Used to set an anim state graph transition condition predicate as '!=='.

const ANIM_NOT_EQUAL_TO: "NOT_EQUAL_TO" = 'NOT_EQUAL_TO'

ANIM_PARAMETER_BOOLEAN

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L99

Used to set an anim state graph parameter as type boolean.

const ANIM_PARAMETER_BOOLEAN: "BOOLEAN" = 'BOOLEAN'

ANIM_PARAMETER_FLOAT

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L92

Used to set an anim state graph parameter as type float.

const ANIM_PARAMETER_FLOAT: "FLOAT" = 'FLOAT'

ANIM_PARAMETER_INTEGER

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L85

Used to set an anim state graph parameter as type integer.

const ANIM_PARAMETER_INTEGER: "INTEGER" = 'INTEGER'

ANIM_PARAMETER_TRIGGER

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L106

Used to set an anim state graph parameter as type trigger.

const ANIM_PARAMETER_TRIGGER: "TRIGGER" = 'TRIGGER'

ANIM_STATE_ANY

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L151

Used to indicate any state in an anim state graph layer.

const ANIM_STATE_ANY: "ANY" = 'ANY'

ANIM_STATE_END

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L144

The ending state in an anim state graph layer.

const ANIM_STATE_END: "END" = 'END'

ANIM_STATE_START

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/controller/constants.js#L137

The starting state in an anim state graph layer.

const ANIM_STATE_START: "START" = 'START'

ASPECT_AUTO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1047

Automatically set aspect ratio to current render target's width divided by height.

const ASPECT_AUTO: 0 = 0

ASPECT_MANUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1054

Use the manual aspect ratio value.

const ASPECT_MANUAL: 1 = 1

ASSET_ANIMATION

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L29

Asset type name for animation.

const ASSET_ANIMATION: "animation" = 'animation'

ASSET_AUDIO

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L36

Asset type name for audio.

const ASSET_AUDIO: "audio" = 'audio'

ASSET_CONTAINER

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L129

Asset type name for a container.

const ASSET_CONTAINER: "container" = 'container'

ASSET_CSS

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L108

Asset type name for CSS.

const ASSET_CSS: "css" = 'css'

ASSET_CUBEMAP

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L94

Asset type name for cubemap.

const ASSET_CUBEMAP: "cubemap" = 'cubemap'

ASSET_HTML

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L115

Asset type name for HTML.

const ASSET_HTML: "html" = 'html'

ASSET_IMAGE

Variable · category: Asset · deprecated

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L45

Asset type name for image.

Deprecated: No resource handler is registered for 'image' assets. Use ASSET_TEXTURE instead.

const ASSET_IMAGE: "image" = 'image'

ASSET_JSON

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L52

Asset type name for json.

const ASSET_JSON: "json" = 'json'

ASSET_MATERIAL

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L66

Asset type name for material.

const ASSET_MATERIAL: "material" = 'material'

ASSET_MODEL

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L59

Asset type name for model.

const ASSET_MODEL: "model" = 'model'

ASSET_SCRIPT

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L122

Asset type name for script.

const ASSET_SCRIPT: "script" = 'script'

ASSET_SHADER

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L101

Asset type name for shader.

const ASSET_SHADER: "shader" = 'shader'

ASSET_TEXT

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L73

Asset type name for text.

const ASSET_TEXT: "text" = 'text'

ASSET_TEXTURE

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L80

Asset type name for texture.

const ASSET_TEXTURE: "texture" = 'texture'

ASSET_TEXTUREATLAS

Variable · category: Asset

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/asset/constants.js#L87

Asset type name for textureatlas.

const ASSET_TEXTUREATLAS: "textureatlas" = 'textureatlas'

BAKE_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L966

Single color lightmap.

const BAKE_COLOR: 0 = 0

BAKE_COLORDIR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L973

Single color lightmap + dominant light direction (used for bump/specular).

const BAKE_COLORDIR: 1 = 1

BLEND_ADDITIVE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L17

Add the color of the source fragment to the destination fragment and write the result to the frame buffer.

const BLEND_ADDITIVE: 1 = 1

BLEND_ADDITIVEALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L56

Same as BLEND_ADDITIVE except the source RGB is multiplied by the source alpha.

const BLEND_ADDITIVEALPHA: 6 = 6

BLEND_MAX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L84

Maximum color.

const BLEND_MAX: 10 = 10

BLEND_MIN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L77

Minimum color.

const BLEND_MIN: 9 = 9

BLEND_MULTIPLICATIVE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L49

Multiply the color of the source fragment by the color of the destination fragment and write the result to the frame buffer.

const BLEND_MULTIPLICATIVE: 5 = 5

BLEND_MULTIPLICATIVE2X

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L63

Multiplies colors and doubles the result.

const BLEND_MULTIPLICATIVE2X: 7 = 7

BLEND_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L33

Disable blending.

const BLEND_NONE: 3 = 3

BLEND_NORMAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L26

Enable simple translucency for materials such as glass. This is equivalent to enabling a source blend mode of BLENDMODE_SRC_ALPHA and a destination blend mode of BLENDMODE_ONE_MINUS_SRC_ALPHA.

const BLEND_NORMAL: 2 = 2

BLEND_PREMULTIPLIED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L41

Similar to BLEND_NORMAL expect the source fragment is assumed to have already been multiplied by the source alpha value.

const BLEND_PREMULTIPLIED: 4 = 4

BLEND_SCREEN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L70

Softer version of additive.

const BLEND_SCREEN: 8 = 8

BLEND_SUBTRACTIVE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L9

Subtract the color of the source fragment from the destination fragment and write the result to the frame buffer.

const BLEND_SUBTRACTIVE: 0 = 0

BLENDEQUATION_ADD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L151

Add the results of the source and destination fragment multiplies.

const BLENDEQUATION_ADD: 0 = 0

BLENDEQUATION_MAX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L179

Use the largest value.

const BLENDEQUATION_MAX: 4 = 4

BLENDEQUATION_MIN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L172

Use the smallest value.

const BLENDEQUATION_MIN: 3 = 3

BLENDEQUATION_REVERSE_SUBTRACT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L165

Reverse and subtract the results of the source and destination fragment multiplies.

const BLENDEQUATION_REVERSE_SUBTRACT: 2 = 2

BLENDEQUATION_SUBTRACT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L158

Subtract the results of the source and destination fragment multiplies.

const BLENDEQUATION_SUBTRACT: 1 = 1

BLENDMODE_CONSTANT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L105

Multiplies all fragment components by a constant.

const BLENDMODE_CONSTANT: 11 = 11

BLENDMODE_DST_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L91

Multiply all fragment components by the alpha value of the destination fragment.

const BLENDMODE_DST_ALPHA: 9 = 9

BLENDMODE_DST_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L56

Multiply all fragment components by the components of the destination fragment.

const BLENDMODE_DST_COLOR: 4 = 4

BLENDMODE_ONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L35

Multiply all fragment components by one.

const BLENDMODE_ONE: 1 = 1

BLENDMODE_ONE_MINUS_CONSTANT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L112

Multiplies all fragment components by 1 minus a constant.

const BLENDMODE_ONE_MINUS_CONSTANT: 12 = 12

BLENDMODE_ONE_MINUS_DST_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L98

Multiply all fragment components by one minus the alpha value of the destination fragment.

const BLENDMODE_ONE_MINUS_DST_ALPHA: 10 = 10

BLENDMODE_ONE_MINUS_DST_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L63

Multiply all fragment components by one minus the components of the destination fragment.

const BLENDMODE_ONE_MINUS_DST_COLOR: 5 = 5

BLENDMODE_ONE_MINUS_SRC_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L84

Multiply all fragment components by one minus the alpha value of the source fragment.

const BLENDMODE_ONE_MINUS_SRC_ALPHA: 8 = 8

BLENDMODE_ONE_MINUS_SRC_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L49

Multiply all fragment components by one minus the components of the source fragment.

const BLENDMODE_ONE_MINUS_SRC_COLOR: 3 = 3

BLENDMODE_ONE_MINUS_SRC1_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L144

Multiply all fragment components by one minus the alpha value of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.

const BLENDMODE_ONE_MINUS_SRC1_ALPHA: 16 = 16

BLENDMODE_ONE_MINUS_SRC1_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L128

Multiply all fragment components by one minus the components of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.

const BLENDMODE_ONE_MINUS_SRC1_COLOR: 14 = 14

BLENDMODE_SRC_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L70

Multiply all fragment components by the alpha value of the source fragment.

const BLENDMODE_SRC_ALPHA: 6 = 6

BLENDMODE_SRC_ALPHA_SATURATE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L77

Multiply all fragment components by the alpha value of the source fragment.

const BLENDMODE_SRC_ALPHA_SATURATE: 7 = 7

BLENDMODE_SRC_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L42

Multiply all fragment components by the components of the source fragment.

const BLENDMODE_SRC_COLOR: 2 = 2

BLENDMODE_SRC1_ALPHA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L136

Multiply all fragment components by the alpha value of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.

const BLENDMODE_SRC1_ALPHA: 15 = 15

BLENDMODE_SRC1_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L120

Multiply all fragment components by the components of the secondary source fragment. This can only be used when GraphicsDevice#supportsDualSourceBlending is true.

const BLENDMODE_SRC1_COLOR: 13 = 13

BLENDMODE_ZERO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L28

Multiply all fragment components by zero.

const BLENDMODE_ZERO: 0 = 0

BLUR_BOX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L451

Box filter.

const BLUR_BOX: 0 = 0

BLUR_GAUSSIAN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L458

Gaussian filter. May look smoother than box, but requires more samples.

const BLUR_GAUSSIAN: 1 = 1

BODYTYPE_DYNAMIC

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L13

Rigid body is simulated according to applied forces.

const BODYTYPE_DYNAMIC: "dynamic" = 'dynamic'

BODYTYPE_KINEMATIC

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L21

Rigid body has infinite mass and does not respond to forces. It is moved by setting the position and rotation of its entity.

const BODYTYPE_KINEMATIC: "kinematic" = 'kinematic'

BODYTYPE_STATIC

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/rigid-body/constants.js#L6

Rigid body has infinite mass and cannot move.

const BODYTYPE_STATIC: "static" = 'static'

BUFFER_DYNAMIC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L269

The data store contents will be modified repeatedly and used many times.

const BUFFER_DYNAMIC: 1 = 1

BUFFER_GPUDYNAMIC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L284

The data store contents will be modified repeatedly on the GPU and used many times. Optimal for transform feedback usage.

const BUFFER_GPUDYNAMIC: 3 = 3

BUFFER_STATIC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L262

The data store contents will be modified once and used many times.

const BUFFER_STATIC: 0 = 0

BUFFER_STREAM

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L276

The data store contents will be modified once and used at most a few times.

const BUFFER_STREAM: 2 = 2

BUFFERUSAGE_COPY_DST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L211

A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a destination of a copy operation, or as a target of a write operation.

const BUFFERUSAGE_COPY_DST: 8 = 0x0008

BUFFERUSAGE_COPY_SRC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L203

A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a source of a copy operation.

const BUFFERUSAGE_COPY_SRC: 4 = 0x0004

BUFFERUSAGE_INDEX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L219

A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as an index buffer.

const BUFFERUSAGE_INDEX: 16 = 0x0010

BUFFERUSAGE_READ

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L187

A flag utilized during the construction of a StorageBuffer to make it available for read access by CPU.

const BUFFERUSAGE_READ: 1 = 0x0001

BUFFERUSAGE_UNIFORM

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L235

A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as an uniform buffer.

const BUFFERUSAGE_UNIFORM: 64 = 0x0040

BUFFERUSAGE_VERTEX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L227

A flag utilized during the construction of a StorageBuffer to ensure its compatibility when used as a vertex buffer.

const BUFFERUSAGE_VERTEX: 32 = 0x0020

BUFFERUSAGE_WRITE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L195

A flag utilized during the construction of a StorageBuffer to make it available for write access by CPU.

const BUFFERUSAGE_WRITE: 2 = 0x0002

BUTTON_TRANSITION_MODE_SPRITE_CHANGE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/constants.js#L13

Specifies different sprites for the hover, pressed and inactive states.

const BUTTON_TRANSITION_MODE_SPRITE_CHANGE: 1 = 1

BUTTON_TRANSITION_MODE_TINT

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/button/constants.js#L6

Specifies different color tints for the hover, pressed and inactive states.

const BUTTON_TRANSITION_MODE_TINT: 0 = 0

CLEARFLAG_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L305

Clear the color buffer.

const CLEARFLAG_COLOR: 1 = 1

CLEARFLAG_DEPTH

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L312

Clear the depth buffer.

const CLEARFLAG_DEPTH: 2 = 2

CLEARFLAG_STENCIL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L319

Clear the stencil buffer.

const CLEARFLAG_STENCIL: 4 = 4

CUBEFACE_NEGX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L333

The negative X face of a cubemap.

const CUBEFACE_NEGX: 1 = 1

CUBEFACE_NEGY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L347

The negative Y face of a cubemap.

const CUBEFACE_NEGY: 3 = 3

CUBEFACE_NEGZ

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L361

The negative Z face of a cubemap.

const CUBEFACE_NEGZ: 5 = 5

CUBEFACE_POSX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L326

The positive X face of a cubemap.

const CUBEFACE_POSX: 0 = 0

CUBEFACE_POSY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L340

The positive Y face of a cubemap.

const CUBEFACE_POSY: 2 = 2

CUBEFACE_POSZ

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L354

The positive Z face of a cubemap.

const CUBEFACE_POSZ: 4 = 4

CUBEPROJ_BOX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L574

The cube map is box-projected based on a world space axis-aligned bounding box.

const CUBEPROJ_BOX: 1 = 1

CUBEPROJ_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L567

The cube map is treated as if it is infinitely far away.

const CUBEPROJ_NONE: 0 = 0

CULLFACE_BACK

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L430

Triangles facing away from the view direction are culled.

const CULLFACE_BACK: 1 = 1

CULLFACE_FRONT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L437

Triangles facing the view direction are culled.

const CULLFACE_FRONT: 2 = 2

CULLFACE_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L423

No triangles are culled.

const CULLFACE_NONE: 0 = 0

CURVE_LINEAR

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L6

A linear interpolation scheme.

const CURVE_LINEAR: 0 = 0

CURVE_SMOOTHSTEP

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L13

A smooth step interpolation scheme.

const CURVE_SMOOTHSTEP: 1 = 1

CURVE_SPLINE

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L20

Cardinal spline interpolation scheme. For a Catmull-Rom spline, specify a curve tension of 0.5.

const CURVE_SPLINE: 4 = 4

CURVE_STEP

Variable · category: Math

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/math/constants.js#L27

A stepped interpolator that does not perform any blending.

const CURVE_STEP: 5 = 5

DEPTHRESOLVE_MAX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L416

The depth value of the multisampled depth buffer is resolved by taking the maximum value of all samples - with a standard depth buffer this selects the farthest surface. See RenderTarget#depthResolveMode.

const DEPTHRESOLVE_MAX: "max" = 'max'

DEPTHRESOLVE_MIN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L407

The depth value of the multisampled depth buffer is resolved by taking the minimum value of all samples - with a standard depth buffer this selects the nearest surface, which is a conservative and stable choice for depth-consuming effects. This is the default. See RenderTarget#depthResolveMode.

const DEPTHRESOLVE_MIN: "min" = 'min'

DEPTHRESOLVE_SAMPLE0

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L397

The depth value of the multisampled depth buffer is resolved by taking its sample at index 0. See RenderTarget#depthResolveMode.

const DEPTHRESOLVE_SAMPLE0: "sample0" = 'sample0'

DETAILMODE_ADD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L594

Add together the primary and secondary colors.

const DETAILMODE_ADD: "add" = 'add'

DETAILMODE_MAX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L622

Select whichever of the primary and secondary colors is lighter, component-wise.

const DETAILMODE_MAX: "max" = 'max'

DETAILMODE_MIN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L615

Select whichever of the primary and secondary colors is darker, component-wise.

const DETAILMODE_MIN: "min" = 'min'

DETAILMODE_MUL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L587

Multiply together the primary and secondary colors.

const DETAILMODE_MUL: "mul" = 'mul'

DETAILMODE_OVERLAY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L608

Multiplies or screens the colors, depending on the primary color.

const DETAILMODE_OVERLAY: "overlay" = 'overlay'

DETAILMODE_SCREEN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L601

Softer version of DETAILMODE_ADD.

const DETAILMODE_SCREEN: "screen" = 'screen'

DEVICETYPE_NULL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2309

A Null device type.

const DEVICETYPE_NULL: "null" = 'null'

DEVICETYPE_WEBGL2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2276

A WebGL 2 device type.

const DEVICETYPE_WEBGL2: "webgl2" = 'webgl2'

DEVICETYPE_WEBGL2_BARE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2286

A WebGL 2 device type with only the extensions available on 99%+ of devices exposed, and capabilities clamped to the values 99%+ of devices report. Useful for testing engine behavior on the most constrained WebGL 2 devices (e.g. no multi-draw, no float texture filtering, no compressed textures, 4k textures).

const DEVICETYPE_WEBGL2_BARE: "webgl2:bare" = 'webgl2:bare'

DEVICETYPE_WEBGPU

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2293

A WebGPU device type.

const DEVICETYPE_WEBGPU: "webgpu" = 'webgpu'

DEVICETYPE_WEBGPU_BARE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2302

A WebGPU device type with no optional features requested and default spec limits. Useful for testing engine behavior on the most constrained WebGPU devices (e.g. no compressed textures, no float32-filterable, no timestamp-query).

const DEVICETYPE_WEBGPU_BARE: "webgpu:bare" = 'webgpu:bare'

DISPLAYFORMAT_HDR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2360

Display format for high dynamic range data, using 16bit floating point values. Note: This is supported on WebGPU platform only, and ignored on other platforms. On displays without HDR support, it silently falls back to DISPLAYFORMAT_LDR. Use GraphicsDevice.isHdr to see if the HDR format is used. When it is, it's recommended to use TONEMAP_NONE for the tonemapping mode, to avoid it clipping the high dynamic range.

const DISPLAYFORMAT_HDR: "hdr" = 'hdr'

DISPLAYFORMAT_LDR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2339

Display format for low dynamic range data. This is always supported; however, due to the cost, it does not implement linear alpha blending on the main framebuffer. Instead, alpha blending occurs in sRGB space.

const DISPLAYFORMAT_LDR: "ldr" = 'ldr'

DISPLAYFORMAT_LDR_SRGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2349

Display format for low dynamic range data in the sRGB color space. This format correctly implements linear alpha blending on the main framebuffer, with the alpha blending occurring in linear space. This is currently supported on WebGPU platform only. On unsupported platforms, it silently falls back to DISPLAYFORMAT_LDR.

const DISPLAYFORMAT_LDR_SRGB: "ldr_srgb" = 'ldr_srgb'

DISTANCE_EXPONENTIAL

Variable · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L20

Exponential distance model.

const DISTANCE_EXPONENTIAL: "exponential" = 'exponential'

DISTANCE_INVERSE

Variable · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L13

Inverse distance model.

const DISTANCE_INVERSE: "inverse" = 'inverse'

DISTANCE_LINEAR

Variable · category: Sound

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/sound/constants.js#L6

Linear distance model.

const DISTANCE_LINEAR: "linear" = 'linear'

DITHER_BAYER16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1126

Opacity is dithered using a Bayer 16 matrix.

const DITHER_BAYER16: "bayer16" = 'bayer16'

DITHER_BAYER2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1105

Opacity is dithered using a Bayer 2 matrix.

const DITHER_BAYER2: "bayer2" = 'bayer2'

DITHER_BAYER4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1112

Opacity is dithered using a Bayer 4 matrix.

const DITHER_BAYER4: "bayer4" = 'bayer4'

DITHER_BAYER8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1119

Opacity is dithered using a Bayer 8 matrix.

const DITHER_BAYER8: "bayer8" = 'bayer8'

DITHER_BLUENOISE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1133

Opacity is dithered using a blue noise.

const DITHER_BLUENOISE: "bluenoise" = 'bluenoise'

DITHER_IGNNOISE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1140

Opacity is dithered using an interleaved gradient noise.

const DITHER_IGNNOISE: "ignnoise" = 'ignnoise'

DITHER_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1098

Opacity dithering is disabled.

const DITHER_NONE: "none" = 'none'

ELEMENTTYPE_GROUP

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L6

A ElementComponent that contains child ElementComponents.

const ELEMENTTYPE_GROUP: "group" = 'group'

ELEMENTTYPE_IMAGE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L13

A ElementComponent that displays an image.

const ELEMENTTYPE_IMAGE: "image" = 'image'

ELEMENTTYPE_TEXT

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L20

A ElementComponent that displays text.

const ELEMENTTYPE_TEXT: "text" = 'text'

EMITTERSHAPE_BOX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L496

Box shape parameterized by emitterExtents. Initial velocity is directed towards local Z axis.

const EMITTERSHAPE_BOX: 0 = 0

EMITTERSHAPE_SPHERE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L504

Sphere shape parameterized by emitterRadius. Initial velocity is directed outwards from the center.

const EMITTERSHAPE_SPHERE: 1 = 1

FILLMODE_FILL_WINDOW

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L9

When resizing the window the size of the canvas will change to fill the window exactly.

const FILLMODE_FILL_WINDOW: "FILL_WINDOW" = 'FILL_WINDOW'

FILLMODE_KEEP_ASPECT

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L15

When resizing the window the size of the canvas will change to fill the window as best it can, while maintaining the same aspect ratio.

const FILLMODE_KEEP_ASPECT: "KEEP_ASPECT" = 'KEEP_ASPECT'

FILLMODE_NONE

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L4

When resizing the window the size of the canvas will not change.

const FILLMODE_NONE: "NONE" = 'NONE'

FILTER_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L474

Bilinear filtering.

const FILTER_LINEAR: 1 = 1

FILTER_LINEAR_MIPMAP_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L502

Linearly interpolate both the mipmap levels and between texels.

const FILTER_LINEAR_MIPMAP_LINEAR: 5 = 5

FILTER_LINEAR_MIPMAP_NEAREST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L495

Use the nearest neighbor after linearly interpolating between mipmap levels.

const FILTER_LINEAR_MIPMAP_NEAREST: 4 = 4

FILTER_NEAREST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L467

Point sample filtering.

const FILTER_NEAREST: 0 = 0

FILTER_NEAREST_MIPMAP_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L488

Linearly interpolate in the nearest mipmap level.

const FILTER_NEAREST_MIPMAP_LINEAR: 3 = 3

FILTER_NEAREST_MIPMAP_NEAREST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L481

Use the nearest neighbor in the nearest mipmap level.

const FILTER_NEAREST_MIPMAP_NEAREST: 2 = 2

FITMODE_CONTAIN

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L34

Fit the content within the Element's bounding box while preserving its Aspect Ratio.

const FITMODE_CONTAIN: "contain" = 'contain'

FITMODE_COVER

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L41

Fit the content to cover the entire Element's bounding box while preserving its Aspect Ratio.

const FITMODE_COVER: "cover" = 'cover'

FITMODE_STRETCH

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/element/constants.js#L27

Fit the content exactly to Element's bounding box.

const FITMODE_STRETCH: "stretch" = 'stretch'

FITTING_BOTH

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L27

Apply both STRETCH and SHRINK fitting logic where applicable.

const FITTING_BOTH: 3 = 3

FITTING_NONE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L6

Disable all fitting logic.

const FITTING_NONE: 0 = 0

FITTING_SHRINK

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L20

Shrink child elements to fit the parent container.

const FITTING_SHRINK: 2 = 2

FITTING_STRETCH

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/layout-group/constants.js#L13

Stretch child elements to fit the parent container.

const FITTING_STRETCH: 1 = 1

FOG_EXP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L119

Fog rises according to an exponential curve controlled by a density value.

const FOG_EXP: "exp" = 'exp'

FOG_EXP2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L126

Fog rises according to an exponential curve controlled by a density value.

const FOG_EXP2: "exp2" = 'exp2'

FOG_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L112

Fog rises linearly from zero to 1 between a start and end depth.

const FOG_LINEAR: "linear" = 'linear'

FOG_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L105

No fog is applied to the scene.

const FOG_NONE: "none" = 'none'

FRESNEL_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L133

No Fresnel.

const FRESNEL_NONE: 0 = 0

FRESNEL_SCHLICK

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L140

Schlick's approximation of Fresnel.

const FRESNEL_SCHLICK: 2 = 2

FRONTFACE_CCW

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L453

The counterclockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation.

const FRONTFACE_CCW: 0 = 0

FRONTFACE_CW

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L460

The clockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation.

const FRONTFACE_CW: 1 = 1

FUNC_ALWAYS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L558

Always pass.

const FUNC_ALWAYS: 7 = 7

FUNC_EQUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L523

Pass if (ref & mask) == (stencil & mask).

const FUNC_EQUAL: 2 = 2

FUNC_GREATER

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L537

Pass if (ref & mask) > (stencil & mask).

const FUNC_GREATER: 4 = 4

FUNC_GREATEREQUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L551

Pass if (ref & mask) >= (stencil & mask).

const FUNC_GREATEREQUAL: 6 = 6

FUNC_LESS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L516

Pass if (ref & mask) < (stencil & mask).

const FUNC_LESS: 1 = 1

FUNC_LESSEQUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L530

Pass if (ref & mask) <= (stencil & mask).

const FUNC_LESSEQUAL: 3 = 3

FUNC_NEVER

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L509

Never pass.

const FUNC_NEVER: 0 = 0

FUNC_NOTEQUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L544

Pass if (ref & mask) != (stencil & mask).

const FUNC_NOTEQUAL: 5 = 5

GAMMA_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L629

No gamma correction.

const GAMMA_NONE: 0 = 0

GAMMA_SRGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L636

Apply sRGB gamma correction.

const GAMMA_SRGB: 1 = 1

GSPLAT_BUDGET_LIMIT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1337

The splat budget is a limit: the LOD distances of each GSplat decide the detail, and GSplatParams#splatBudget only lowers it when they would ask for more splats than it allows. A distant GSplat uses only the few splats its distance calls for, leaving the rest of the budget unused.

const GSPLAT_BUDGET_LIMIT: "limit" = 'limit'

GSPLAT_BUDGET_TARGET

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1327

The splat budget is a target: LOD detail is raised until GSplatParams#splatBudget is used up, wherever the camera is. The LOD distances of each GSplat still shape how detail falls off with distance and how it divides between GSplats, but not how much of it there is. The default.

const GSPLAT_BUDGET_TARGET: "target" = 'target'

GSPLAT_DEBUG_AABBS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1377

Debug rendering that draws world-space AABBs for each GSplat, colorized by LOD.

const GSPLAT_DEBUG_AABBS: number = 4

GSPLAT_DEBUG_LOD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1357

Debug rendering that colorizes Gaussian splats by their selected LOD level.

const GSPLAT_DEBUG_LOD: number = 1

GSPLAT_DEBUG_NODE_AABBS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1386

Debug rendering that draws world-space AABBs for each octree node of streamed GSplats, colorized by the currently selected LOD.

const GSPLAT_DEBUG_NODE_AABBS: number = 5

GSPLAT_DEBUG_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1349

No debug rendering for Gaussian splats. Normal rendering mode.

const GSPLAT_DEBUG_NONE: number = 0

GSPLAT_DEBUG_SH_UPDATE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1366

Debug rendering that assigns a random color per spherical harmonics update pass, visualizing when SH color updates occur.

const GSPLAT_DEBUG_SH_UPDATE: number = 2

GSPLAT_RENDERER_AUTO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1298

Automatically selects the best rendering pipeline for the current platform.

const GSPLAT_RENDERER_AUTO: number = 0

GSPLAT_RENDERER_RASTER_CPU_SORT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1306

Rasterization-based rendering with CPU-side sorting.

const GSPLAT_RENDERER_RASTER_CPU_SORT: number = 1

GSPLAT_RENDERER_RASTER_GPU_SORT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1314

Rasterization-based rendering with GPU-side culling and sorting. WebGPU only.

const GSPLAT_RENDERER_RASTER_GPU_SORT: number = 2

GSPLAT_STREAM_INSTANCE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1272

Stream texture is stored per gsplat component instance.

const GSPLAT_STREAM_INSTANCE: number = 1

GSPLAT_STREAM_RESOURCE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1264

Stream texture is stored at resource level, shared across all component instances.

const GSPLAT_STREAM_RESOURCE: number = 0

GSPLATDATA_COMPACT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1290

Compact work buffer data format optimized for reduced memory and bandwidth. Uses 11+11+10 bit RGB color, half-angle quaternion rotation and log-encoded scale. 20 bytes per splat.

const GSPLATDATA_COMPACT: string = 'compact'

GSPLATDATA_LARGE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1281

Large work buffer data format with full precision. Uses RGBA16F color, float16 rotation and float16 scale. 32 bytes per splat.

const GSPLATDATA_LARGE: string = 'large'

INDEXFORMAT_UINT16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L572

16-bit unsigned vertex indices (0 to 65,535).

const INDEXFORMAT_UINT16: 1 = 1

INDEXFORMAT_UINT32

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L579

32-bit unsigned vertex indices (0 to 4,294,967,295).

const INDEXFORMAT_UINT32: 2 = 2

INDEXFORMAT_UINT8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L565

8-bit unsigned vertex indices (0 to 255).

const INDEXFORMAT_UINT8: 0 = 0

INTERPOLATION_CUBIC

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L20

A cubic spline interpolation scheme.

const INTERPOLATION_CUBIC: 2 = 2

INTERPOLATION_LINEAR

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L13

A linear interpolation scheme.

const INTERPOLATION_LINEAR: 1 = 1

INTERPOLATION_STEP

Variable · category: Animation

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/anim/constants.js#L6

A stepped interpolation scheme.

const INTERPOLATION_STEP: 0 = 0

JOINTTYPE_6DOF

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L43

Generic 6 degrees of freedom joint. Each linear and angular axis can be independently locked, limited or free, with optional springs.

const JOINTTYPE_6DOF: "6dof" = '6dof'

JOINTTYPE_BALL

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L16

Ball and socket joint. The bodies can rotate freely about the joint's anchor point. Optional limits constrain the swing (cone) and twist angles.

const JOINTTYPE_BALL: "ball" = 'ball'

JOINTTYPE_FIXED

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L7

Joint rigidly locks all degrees of freedom, welding the two bodies together.

const JOINTTYPE_FIXED: "fixed" = 'fixed'

JOINTTYPE_HINGE

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L25

Hinge joint. The bodies can rotate about the joint's X axis, like a door hinge or a wheel axle. Supports optional rotation limits and a motor.

const JOINTTYPE_HINGE: "hinge" = 'hinge'

JOINTTYPE_SLIDER

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L34

Slider (prismatic) joint. The bodies can translate along the joint's X axis, like a drawer runner or a piston. Supports optional travel limits and a motor.

const JOINTTYPE_SLIDER: "slider" = 'slider'

KEY_0

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L149

const KEY_0: number = 48

KEY_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L155

const KEY_1: number = 49

KEY_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L161

const KEY_2: number = 50

KEY_3

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L167

const KEY_3: number = 51

KEY_4

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L173

const KEY_4: number = 52

KEY_5

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L179

const KEY_5: number = 53

KEY_6

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L185

const KEY_6: number = 54

KEY_7

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L191

const KEY_7: number = 55

KEY_8

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L197

const KEY_8: number = 56

KEY_9

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L203

const KEY_9: number = 57

KEY_A

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L221

const KEY_A: number = 65

KEY_ADD

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L455

const KEY_ADD: number = 107

KEY_ALT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L53

const KEY_ALT: number = 18

KEY_B

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L227

const KEY_B: number = 66

KEY_BACK_SLASH

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L581

const KEY_BACK_SLASH: number = 220

KEY_BACKSPACE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L17

const KEY_BACKSPACE: number = 8

KEY_C

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L233

const KEY_C: number = 67

KEY_CAPS_LOCK

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L65

const KEY_CAPS_LOCK: number = 20

KEY_CLOSE_BRACKET

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L587

const KEY_CLOSE_BRACKET: number = 221

KEY_COMMA

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L557

const KEY_COMMA: number = 188

KEY_CONTEXT_MENU

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L383

const KEY_CONTEXT_MENU: number = 93

KEY_CONTROL

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L47

const KEY_CONTROL: number = 17

KEY_D

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L239

const KEY_D: number = 68

KEY_DECIMAL

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L473

const KEY_DECIMAL: number = 110

KEY_DELETE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L143

const KEY_DELETE: number = 46

KEY_DIVIDE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L479

const KEY_DIVIDE: number = 111

KEY_DOWN

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L125

const KEY_DOWN: number = 40

KEY_E

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L245

const KEY_E: number = 69

KEY_END

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L95

const KEY_END: number = 35

KEY_ENTER

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L35

const KEY_ENTER: number = 13

KEY_EQUAL

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L215

const KEY_EQUAL: number = 61

KEY_ESCAPE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L71

const KEY_ESCAPE: number = 27

KEY_F

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L251

const KEY_F: number = 70

KEY_F1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L485

const KEY_F1: number = 112

KEY_F10

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L539

const KEY_F10: number = 121

KEY_F11

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L545

const KEY_F11: number = 122

KEY_F12

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L551

const KEY_F12: number = 123

KEY_F2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L491

const KEY_F2: number = 113

KEY_F3

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L497

const KEY_F3: number = 114

KEY_F4

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L503

const KEY_F4: number = 115

KEY_F5

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L509

const KEY_F5: number = 116

KEY_F6

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L515

const KEY_F6: number = 117

KEY_F7

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L521

const KEY_F7: number = 118

KEY_F8

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L527

const KEY_F8: number = 119

KEY_F9

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L533

const KEY_F9: number = 120

KEY_G

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L257

const KEY_G: number = 71

KEY_H

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L263

const KEY_H: number = 72

KEY_HOME

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L101

const KEY_HOME: number = 36

KEY_I

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L269

const KEY_I: number = 73

KEY_INSERT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L137

const KEY_INSERT: number = 45

KEY_J

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L275

const KEY_J: number = 74

KEY_K

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L281

const KEY_K: number = 75

KEY_L

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L287

const KEY_L: number = 76

KEY_LEFT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L107

const KEY_LEFT: number = 37

KEY_M

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L293

const KEY_M: number = 77

KEY_META

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L593

const KEY_META: number = 224

KEY_MULTIPLY

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L449

const KEY_MULTIPLY: number = 106

KEY_N

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L299

const KEY_N: number = 78

KEY_NUMPAD_0

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L389

const KEY_NUMPAD_0: number = 96

KEY_NUMPAD_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L395

const KEY_NUMPAD_1: number = 97

KEY_NUMPAD_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L401

const KEY_NUMPAD_2: number = 98

KEY_NUMPAD_3

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L407

const KEY_NUMPAD_3: number = 99

KEY_NUMPAD_4

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L413

const KEY_NUMPAD_4: number = 100

KEY_NUMPAD_5

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L419

const KEY_NUMPAD_5: number = 101

KEY_NUMPAD_6

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L425

const KEY_NUMPAD_6: number = 102

KEY_NUMPAD_7

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L431

const KEY_NUMPAD_7: number = 103

KEY_NUMPAD_8

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L437

const KEY_NUMPAD_8: number = 104

KEY_NUMPAD_9

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L443

const KEY_NUMPAD_9: number = 105

KEY_O

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L305

const KEY_O: number = 79

KEY_OPEN_BRACKET

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L575

const KEY_OPEN_BRACKET: number = 219

KEY_P

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L311

const KEY_P: number = 80

KEY_PAGE_DOWN

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L89

const KEY_PAGE_DOWN: number = 34

KEY_PAGE_UP

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L83

const KEY_PAGE_UP: number = 33

KEY_PAUSE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L59

const KEY_PAUSE: number = 19

KEY_PERIOD

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L563

const KEY_PERIOD: number = 190

KEY_PRINT_SCREEN

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L131

const KEY_PRINT_SCREEN: number = 44

KEY_Q

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L317

const KEY_Q: number = 81

KEY_R

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L323

const KEY_R: number = 82

KEY_RETURN

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L29

const KEY_RETURN: number = 13

KEY_RIGHT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L119

const KEY_RIGHT: number = 39

KEY_S

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L329

const KEY_S: number = 83

KEY_SEMICOLON

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L209

const KEY_SEMICOLON: number = 59

KEY_SEPARATOR

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L461

const KEY_SEPARATOR: number = 108

KEY_SHIFT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L41

const KEY_SHIFT: number = 16

KEY_SLASH

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L569

const KEY_SLASH: number = 191

KEY_SPACE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L77

const KEY_SPACE: number = 32

KEY_SUBTRACT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L467

const KEY_SUBTRACT: number = 109

KEY_T

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L335

const KEY_T: number = 84

KEY_TAB

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L23

const KEY_TAB: number = 9

KEY_U

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L341

const KEY_U: number = 85

KEY_UP

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L113

const KEY_UP: number = 38

KEY_V

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L347

const KEY_V: number = 86

KEY_W

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L353

const KEY_W: number = 87

KEY_WINDOWS

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L377

const KEY_WINDOWS: number = 91

KEY_X

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L359

const KEY_X: number = 88

KEY_Y

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L365

const KEY_Y: number = 89

KEY_Z

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L371

const KEY_Z: number = 90

LAYERID_DEPTH

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L166

The depth layer.

const LAYERID_DEPTH: 1 = 1

LAYERID_IMMEDIATE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L180

The immediate layer.

const LAYERID_IMMEDIATE: 3 = 3

LAYERID_SKYBOX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L173

The skybox layer.

const LAYERID_SKYBOX: 2 = 2

LAYERID_UI

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L187

The UI layer.

const LAYERID_UI: 4 = 4

LAYERID_WORLD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L159

The world layer.

const LAYERID_WORLD: 0 = 0

LIGHTFALLOFF_INVERSESQUARED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L277

Inverse squared distance falloff model for light attenuation.

const LIGHTFALLOFF_INVERSESQUARED: 1 = 1

LIGHTFALLOFF_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L270

Linear distance falloff model for light attenuation.

const LIGHTFALLOFF_LINEAR: 0 = 0

LIGHTSHAPE_DISK

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L249

Disk shape of light source.

const LIGHTSHAPE_DISK: 2 = 2

LIGHTSHAPE_PUNCTUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L235

Infinitesimally small point light source shape.

const LIGHTSHAPE_PUNCTUAL: 0 = 0

LIGHTSHAPE_RECT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L242

Rectangle shape of light source.

const LIGHTSHAPE_RECT: 1 = 1

LIGHTSHAPE_SPHERE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L256

Sphere shape of light source.

const LIGHTSHAPE_SPHERE: 3 = 3

LIGHTTYPE_DIRECTIONAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L194

Directional (global) light source.

const LIGHTTYPE_DIRECTIONAL: 0 = 0

LIGHTTYPE_OMNI

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L201

Omni-directional (local) light source.

const LIGHTTYPE_OMNI: 1 = 1

LIGHTTYPE_SPOT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L216

Spot (local) light source.

const LIGHTTYPE_SPOT: 2 = 2

LINECAP_BUTT

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L8

Butt line caps stop exactly at the first and last points.

const LINECAP_BUTT: 0 = 0

LINECAP_ROUND

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L14

Round line caps extend past line and dash ends by half the line width.

const LINECAP_ROUND: 2 = 2

LINECAP_SQUARE

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L11

Square line caps extend past the first and last points by half the line width.

const LINECAP_SQUARE: 1 = 1

LINEJOIN_BEVEL

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L20

Bevel joins connect segment edges directly.

const LINEJOIN_BEVEL: 1 = 1

LINEJOIN_MITER

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L17

Miter joins extend edges until they intersect.

const LINEJOIN_MITER: 0 = 0

LINEJOIN_ROUND

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line.js#L23

Round joins connect segments using a circular edge.

const LINEJOIN_ROUND: 2 = 2

LINEWIDTH_SCREEN

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L17

Line widths are measured in screen pixels.

const LINEWIDTH_SCREEN: 0 = 0

LINEWIDTH_WORLD

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/renderers/wide-line-renderer.js#L20

Line widths are measured in world units.

const LINEWIDTH_WORLD: 1 = 1

MOTION_FREE

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L51

Specified degree of freedom has free movement.

const MOTION_FREE: "free" = 'free'

MOTION_LIMITED

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L59

Specified degree of freedom has limited movement.

const MOTION_LIMITED: "limited" = 'limited'

MOTION_LOCKED

Variable · category: Physics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/joint/constants.js#L67

Specified degree of freedom is locked and allows no movement.

const MOTION_LOCKED: "locked" = 'locked'

MOUSEBUTTON_LEFT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L607

The left mouse button.

const MOUSEBUTTON_LEFT: 0 = 0

MOUSEBUTTON_MIDDLE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L614

The middle mouse button.

const MOUSEBUTTON_MIDDLE: 1 = 1

MOUSEBUTTON_NONE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L600

No mouse buttons pressed.

const MOUSEBUTTON_NONE: -1 = -1

MOUSEBUTTON_RIGHT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L621

The right mouse button.

const MOUSEBUTTON_RIGHT: 2 = 2

ORIENTATION_HORIZONTAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1061

Horizontal orientation.

const ORIENTATION_HORIZONTAL: 0 = 0

ORIENTATION_VERTICAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1068

Vertical orientation.

const ORIENTATION_VERTICAL: 1 = 1

PAD_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L628

Index for pad 1.

const PAD_1: 0 = 0

PAD_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L635

Index for pad 2.

const PAD_2: 1 = 1

PAD_3

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L642

Index for pad 3.

const PAD_3: 2 = 2

PAD_4

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L649

Index for pad 4.

const PAD_4: 3 = 3

PAD_DOWN

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L747

Direction pad down.

const PAD_DOWN: 13 = 13

PAD_FACE_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L656

The first face button, from bottom going clockwise.

const PAD_FACE_1: 0 = 0

PAD_FACE_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L663

The second face button, from bottom going clockwise.

const PAD_FACE_2: 1 = 1

PAD_FACE_3

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L670

The third face button, from bottom going clockwise.

const PAD_FACE_3: 2 = 2

PAD_FACE_4

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L677

The fourth face button, from bottom going clockwise.

const PAD_FACE_4: 3 = 3

PAD_L_SHOULDER_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L684

The first shoulder button on the left.

const PAD_L_SHOULDER_1: 4 = 4

PAD_L_SHOULDER_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L698

The second shoulder button on the left.

const PAD_L_SHOULDER_2: 6 = 6

PAD_L_STICK_BUTTON

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L726

The button when depressing the left analogue stick.

const PAD_L_STICK_BUTTON: 10 = 10

PAD_L_STICK_X

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L775

Horizontal axis on the left analogue stick.

const PAD_L_STICK_X: 0 = 0

PAD_L_STICK_Y

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L782

Vertical axis on the left analogue stick.

const PAD_L_STICK_Y: 1 = 1

PAD_LEFT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L754

Direction pad left.

const PAD_LEFT: 14 = 14

PAD_R_SHOULDER_1

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L691

The first shoulder button on the right.

const PAD_R_SHOULDER_1: 5 = 5

PAD_R_SHOULDER_2

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L705

The second shoulder button on the right.

const PAD_R_SHOULDER_2: 7 = 7

PAD_R_STICK_BUTTON

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L733

The button when depressing the right analogue stick.

const PAD_R_STICK_BUTTON: 11 = 11

PAD_R_STICK_X

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L789

Horizontal axis on the right analogue stick.

const PAD_R_STICK_X: 2 = 2

PAD_R_STICK_Y

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L796

Vertical axis on the right analogue stick.

const PAD_R_STICK_Y: 3 = 3

PAD_RIGHT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L761

Direction pad right.

const PAD_RIGHT: 15 = 15

PAD_SELECT

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L712

The select button.

const PAD_SELECT: 8 = 8

PAD_START

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L719

The start button.

const PAD_START: 9 = 9

PAD_UP

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L740

Direction pad up.

const PAD_UP: 12 = 12

PAD_VENDOR

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L768

Vendor specific button.

const PAD_VENDOR: 16 = 16

PARALLAX_OCCLUSION

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1157

Parallax occlusion mapping marches the view ray through the height field to find where it meets the displaced surface. This costs more than PARALLAX_OFFSET, but represents deeper displacement without smearing the texture.

const PARALLAX_OCCLUSION: "occlusion" = 'occlusion'

PARALLAX_OFFSET

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1148

Parallax mapping computes the uv offset from a single tap of the height map. This is the cheapest option, and suits shallow surface detail.

const PARALLAX_OFFSET: "offset" = 'offset'

PARTICLEORIENTATION_EMITTER

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L525

Similar to previous, but the normal is affected by emitter(entity) transformation.

const PARTICLEORIENTATION_EMITTER: 2 = 2

PARTICLEORIENTATION_SCREEN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L511

Particles are facing camera.

const PARTICLEORIENTATION_SCREEN: 0 = 0

PARTICLEORIENTATION_WORLD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L518

User defines world space normal (particleNormal) to set planes orientation.

const PARTICLEORIENTATION_WORLD: 1 = 1

PARTICLESORT_DISTANCE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L472

Sorting based on distance to the camera. CPU only.

const PARTICLESORT_DISTANCE: 1 = 1

PARTICLESORT_NEWER_FIRST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L479

Newer particles are drawn first. CPU only.

const PARTICLESORT_NEWER_FIRST: 2 = 2

PARTICLESORT_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L465

No sorting, particles are drawn in arbitrary order. Can be simulated on GPU.

const PARTICLESORT_NONE: 0 = 0

PARTICLESORT_OLDER_FIRST

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L486

Older particles are drawn first. CPU only.

const PARTICLESORT_OLDER_FIRST: 3 = 3

PIXELFORMAT_111110F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L709

A floating-point color-only format with 11 bits for red and green channels and 10 bits for the blue channel.

const PIXELFORMAT_111110F: 18 = 18

PIXELFORMAT_ATC_RGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L786

ATC compressed format with no alpha channel.

const PIXELFORMAT_ATC_RGB: 29 = 29

PIXELFORMAT_ATC_RGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L793

ATC compressed format with alpha channel.

const PIXELFORMAT_ATC_RGBA: 30 = 30

PIXELFORMAT_BC6F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1013

Compressed high dynamic range signed floating point format storing RGB values.

const PIXELFORMAT_BC6F: 65 = 65

PIXELFORMAT_BC6UF

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1020

Compressed high dynamic range unsigned floating point format storing RGB values.

const PIXELFORMAT_BC6UF: 66 = 66

PIXELFORMAT_BC7

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1027

Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA data.

const PIXELFORMAT_BC7: 67 = 67

PIXELFORMAT_BC7_SRGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1035

Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of SRGB_ALPHA data.

const PIXELFORMAT_BC7_SRGBA: 68 = 68

PIXELFORMAT_DEPTH

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L694

A readable depth buffer format.

const PIXELFORMAT_DEPTH: 16 = 16

PIXELFORMAT_DEPTH16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1042

A 16-bit depth buffer format.

const PIXELFORMAT_DEPTH16: 69 = 69

PIXELFORMAT_DEPTHSTENCIL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L701

A readable depth/stencil buffer format.

const PIXELFORMAT_DEPTHSTENCIL: 17 = 17

PIXELFORMAT_DXT1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L634

Block compressed format storing 16 input pixels in 64 bits of output, consisting of two 16-bit RGB 5:6:5 color values and a 4x4 two bit lookup table.

const PIXELFORMAT_DXT1: 8 = 8

PIXELFORMAT_DXT1_SRGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L963

Format equivalent to PIXELFORMAT_DXT1 but sampled in linear color space.

const PIXELFORMAT_DXT1_SRGB: 54 = 54

PIXELFORMAT_DXT3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L643

Block compressed format storing 16 input pixels (corresponding to a 4x4 pixel block) into 128 bits of output, consisting of 64 bits of alpha channel data (4 bits for each pixel) followed by 64 bits of color data; encoded the same way as DXT1.

const PIXELFORMAT_DXT3: 9 = 9

PIXELFORMAT_DXT3_SRGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L970

Format equivalent to PIXELFORMAT_DXT3 but sampled in linear color space.

const PIXELFORMAT_DXT3_SRGBA: 55 = 55

PIXELFORMAT_DXT5

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L652

Block compressed format storing 16 input pixels into 128 bits of output, consisting of 64 bits of alpha channel data (two 8 bit alpha values and a 4x4 3 bit lookup table) followed by 64 bits of color data (encoded the same way as DXT1).

const PIXELFORMAT_DXT5: 10 = 10

PIXELFORMAT_DXT5_SRGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L977

Format equivalent to PIXELFORMAT_DXT5 but sampled in linear color space.

const PIXELFORMAT_DXT5_SRGBA: 56 = 56

PIXELFORMAT_ETC1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L730

ETC1 compressed format.

const PIXELFORMAT_ETC1: 21 = 21

PIXELFORMAT_ETC2_RGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L737

ETC2 (RGB) compressed format.

const PIXELFORMAT_ETC2_RGB: 22 = 22

PIXELFORMAT_ETC2_RGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L744

ETC2 (RGBA) compressed format.

const PIXELFORMAT_ETC2_RGBA: 23 = 23

PIXELFORMAT_ETC2_SRGB

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L984

Format equivalent to PIXELFORMAT_ETC2_RGB but sampled in linear color space.

const PIXELFORMAT_ETC2_SRGB: 61 = 61

PIXELFORMAT_ETC2_SRGBA

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L991

Format equivalent to PIXELFORMAT_ETC2_RGBA but sampled in linear color space.

const PIXELFORMAT_ETC2_SRGBA: 62 = 62

PIXELFORMAT_PVRTC_2BPP_RGB_1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L751

PVRTC (2BPP RGB) compressed format.

const PIXELFORMAT_PVRTC_2BPP_RGB_1: 24 = 24

PIXELFORMAT_PVRTC_2BPP_RGBA_1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L758

PVRTC (2BPP RGBA) compressed format.

const PIXELFORMAT_PVRTC_2BPP_RGBA_1: 25 = 25

PIXELFORMAT_PVRTC_4BPP_RGB_1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L765

PVRTC (4BPP RGB) compressed format.

const PIXELFORMAT_PVRTC_4BPP_RGB_1: 26 = 26

PIXELFORMAT_PVRTC_4BPP_RGBA_1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L772

PVRTC (4BPP RGBA) compressed format.

const PIXELFORMAT_PVRTC_4BPP_RGBA_1: 27 = 27

PIXELFORMAT_R16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L935

16-bit floating point R (16-bit float for red channel).

const PIXELFORMAT_R16F: 50 = 50

PIXELFORMAT_R16I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L823

16-bit signed integer single-channel (R) format.

const PIXELFORMAT_R16I: 34 = 34

PIXELFORMAT_R16U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L830

16-bit unsigned integer single-channel (R) format.

const PIXELFORMAT_R16U: 35 = 35

PIXELFORMAT_R32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L687

32-bit floating point single channel format.

const PIXELFORMAT_R32F: 15 = 15

PIXELFORMAT_R32I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L837

32-bit signed integer single-channel (R) format.

const PIXELFORMAT_R32I: 36 = 36

PIXELFORMAT_R32U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L844

32-bit unsigned integer single-channel (R) format.

const PIXELFORMAT_R32U: 37 = 37

PIXELFORMAT_R8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L949

8-bit per-channel (R) format.

const PIXELFORMAT_R8: 52 = 52

PIXELFORMAT_R8I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L809

8-bit signed integer single-channel (R) format.

const PIXELFORMAT_R8I: 32 = 32

PIXELFORMAT_R8U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L816

8-bit unsigned integer single-channel (R) format.

const PIXELFORMAT_R8U: 33 = 33

PIXELFORMAT_RG16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L942

16-bit floating point RG (16-bit float for each red and green channels).

const PIXELFORMAT_RG16F: 51 = 51

PIXELFORMAT_RG16I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L865

16-bit per-channel signed integer (RG) format.

const PIXELFORMAT_RG16I: 40 = 40

PIXELFORMAT_RG16U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L872

16-bit per-channel unsigned integer (RG) format.

const PIXELFORMAT_RG16U: 41 = 41

PIXELFORMAT_RG32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1049

32-bit floating point RG (32-bit float for each red and green channels). WebGPU only.

const PIXELFORMAT_RG32F: 70 = 70

PIXELFORMAT_RG32I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L879

32-bit per-channel signed integer (RG) format.

const PIXELFORMAT_RG32I: 42 = 42

PIXELFORMAT_RG32U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L886

32-bit per-channel unsigned integer (RG) format.

const PIXELFORMAT_RG32U: 43 = 43

PIXELFORMAT_RG8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L956

8-bit per-channel (RG) format.

const PIXELFORMAT_RG8: 53 = 53

PIXELFORMAT_RG8I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L851

8-bit per-channel signed integer (RG) format.

const PIXELFORMAT_RG8I: 38 = 38

PIXELFORMAT_RG8S

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1063

8-bit per-channel signed normalized (RG) format.

const PIXELFORMAT_RG8S: 72 = 72

PIXELFORMAT_RG8U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L858

8-bit per-channel unsigned integer (RG) format.

const PIXELFORMAT_RG8U: 39 = 39

PIXELFORMAT_RGB10A2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1077

10-bit RGB with 2-bit alpha unsigned normalized format.

const PIXELFORMAT_RGB10A2: 74 = 74

PIXELFORMAT_RGB10A2U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1084

10-bit RGB with 2-bit alpha unsigned integer format.

const PIXELFORMAT_RGB10A2U: 75 = 75

PIXELFORMAT_RGB16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L659

16-bit floating point RGB (16-bit float for each red, green and blue channels).

const PIXELFORMAT_RGB16F: 11 = 11

PIXELFORMAT_RGB32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L673

32-bit floating point RGB (32-bit float for each red, green and blue channels).

const PIXELFORMAT_RGB32F: 13 = 13

PIXELFORMAT_RGB565

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L598

16-bit RGB (5-bits for red channel, 6 for green and 5 for blue).

const PIXELFORMAT_RGB565: 3 = 3

PIXELFORMAT_RGB8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L619

24-bit RGB (8-bits for red channel, 8 for green and 8 for blue).

const PIXELFORMAT_RGB8: 6 = 6

PIXELFORMAT_RGB9E5

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1056

32-bit RGB format with shared 5-bit exponent (9 bits each for RGB mantissa). HDR format.

const PIXELFORMAT_RGB9E5: 71 = 71

PIXELFORMAT_RGBA16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L666

16-bit floating point RGBA (16-bit float for each red, green, blue and alpha channels).

const PIXELFORMAT_RGBA16F: 12 = 12

PIXELFORMAT_RGBA16I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L907

16-bit per-channel signed integer (RGBA) format.

const PIXELFORMAT_RGBA16I: 46 = 46

PIXELFORMAT_RGBA16U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L914

16-bit per-channel unsigned integer (RGBA) format.

const PIXELFORMAT_RGBA16U: 47 = 47

PIXELFORMAT_RGBA32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L680

32-bit floating point RGBA (32-bit float for each red, green, blue and alpha channels).

const PIXELFORMAT_RGBA32F: 14 = 14

PIXELFORMAT_RGBA32I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L921

32-bit per-channel signed integer (RGBA) format.

const PIXELFORMAT_RGBA32I: 48 = 48

PIXELFORMAT_RGBA32U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L928

32-bit per-channel unsigned integer (RGBA) format.

const PIXELFORMAT_RGBA32U: 49 = 49

PIXELFORMAT_RGBA4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L612

16-bit RGBA (4-bits for red channel, 4 for green, 4 for blue with 4-bit alpha).

const PIXELFORMAT_RGBA4: 5 = 5

PIXELFORMAT_RGBA5551

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L605

16-bit RGBA (5-bits for red channel, 5 for green, 5 for blue with 1-bit alpha).

const PIXELFORMAT_RGBA5551: 4 = 4

PIXELFORMAT_RGBA8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L626

32-bit RGBA (8-bits for red channel, 8 for green, 8 for blue with 8-bit alpha).

const PIXELFORMAT_RGBA8: 7 = 7

PIXELFORMAT_RGBA8I

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L893

8-bit per-channel signed integer (RGBA) format.

const PIXELFORMAT_RGBA8I: 44 = 44

PIXELFORMAT_RGBA8S

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1070

8-bit per-channel signed normalized (RGBA) format.

const PIXELFORMAT_RGBA8S: 73 = 73

PIXELFORMAT_RGBA8U

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L900

8-bit per-channel unsigned integer (RGBA) format.

const PIXELFORMAT_RGBA8U: 45 = 45

PIXELFORMAT_SRGB8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L716

Color-only sRGB format.

const PIXELFORMAT_SRGB8: 19 = 19

PIXELFORMAT_SRGBA8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L723

Color sRGB format with additional alpha channel.

const PIXELFORMAT_SRGBA8: 20 = 20

PRIMITIVE_LINELOOP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1376

List of points that are linked sequentially by line segments, with a closing line segment between the last and first points.

const PRIMITIVE_LINELOOP: 2 = 2

PRIMITIVE_LINES

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1368

Discrete list of line segments.

const PRIMITIVE_LINES: 1 = 1

PRIMITIVE_LINESTRIP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1383

List of points that are linked sequentially by line segments.

const PRIMITIVE_LINESTRIP: 3 = 3

PRIMITIVE_POINTS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1361

List of distinct points.

const PRIMITIVE_POINTS: 0 = 0

PRIMITIVE_TRIANGLES

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1390

Discrete list of triangles.

const PRIMITIVE_TRIANGLES: 4 = 4

PRIMITIVE_TRIFAN

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1404

Connected fan of triangles where the first vertex forms triangles with the following pairs of vertices.

const PRIMITIVE_TRIFAN: 6 = 6

PRIMITIVE_TRISTRIP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1397

Connected strip of triangles where a specified vertex forms a triangle using the previous two.

const PRIMITIVE_TRISTRIP: 5 = 5

PROJECTION_ORTHOGRAPHIC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L539

An orthographic camera projection where the frustum shape is essentially a cuboid.

const PROJECTION_ORTHOGRAPHIC: 1 = 1

PROJECTION_PERSPECTIVE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L532

A perspective camera projection where the frustum shape is essentially pyramidal.

const PROJECTION_PERSPECTIVE: 0 = 0

RENDERSTYLE_POINTS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L560

Render mesh instance as points.

const RENDERSTYLE_POINTS: 2 = 2

RENDERSTYLE_SOLID

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L546

Render mesh instance as solid geometry.

const RENDERSTYLE_SOLID: 0 = 0

RENDERSTYLE_WIREFRAME

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L553

Render mesh instance as wireframe.

const RENDERSTYLE_WIREFRAME: 1 = 1

RENDERTARGET_ORIGIN_BOTTOM

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L379

The render target stores the image with row 0 being the bottom row of the rendered image, on all graphics APIs - replicating WebGL2's native layout. See the origin option of the RenderTarget constructor for guidance on which origin to use.

const RENDERTARGET_ORIGIN_BOTTOM: "bottom" = 'bottom'

RENDERTARGET_ORIGIN_NATIVE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L389

The render target stores the image in the native orientation of the graphics API - bottom-up on WebGL2, top-down on WebGPU - so the stored row order differs between the APIs. This is the default. See the origin option of the RenderTarget constructor for guidance on which origin to use.

const RENDERTARGET_ORIGIN_NATIVE: "native" = 'native'

RENDERTARGET_ORIGIN_TOP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L370

The render target stores the image with row 0 being the top row of the rendered image, on all graphics APIs - the same layout image textures use. See the origin option of the RenderTarget constructor for guidance on which origin to use.

const RENDERTARGET_ORIGIN_TOP: "top" = 'top'

RESOLUTION_AUTO

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L21

When the canvas is resized the resolution of the canvas will change to match the size of the canvas.

const RESOLUTION_AUTO: "AUTO" = 'AUTO'

RESOLUTION_FIXED

Variable · category: Other

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/constants.js#L27

When the canvas is resized the resolution of the canvas will remain at the same value and the output will just be scaled to fit the canvas.

const RESOLUTION_FIXED: "FIXED" = 'FIXED'

SAMPLETYPE_DEPTH

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1803

A sampler type of a texture that contains depth data. Typically used for depth textures.

const SAMPLETYPE_DEPTH: 2 = 2

SAMPLETYPE_FLOAT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1788

A sampler type of a texture that contains floating-point data. Typically stored for color textures, where data can be filtered.

const SAMPLETYPE_FLOAT: 0 = 0

SAMPLETYPE_INT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1810

A sampler type of a texture that contains signed integer data.

const SAMPLETYPE_INT: 3 = 3

SAMPLETYPE_UINT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1817

A sampler type of a texture that contains unsigned integer data.

const SAMPLETYPE_UINT: 4 = 4

SAMPLETYPE_UNFILTERABLE_FLOAT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1796

A sampler type of a texture that contains floating-point data, but cannot be filtered. Typically used for textures storing data that cannot be interpolated.

const SAMPLETYPE_UNFILTERABLE_FLOAT: 1 = 1

SCALEMODE_BLEND

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/constants.js#L14

Scale the ScreenComponent when the application's resolution is different than the ScreenComponent's referenceResolution.

const SCALEMODE_BLEND: "blend" = 'blend'

SCALEMODE_NONE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/screen/constants.js#L6

Always use the application's resolution as the resolution for the ScreenComponent.

const SCALEMODE_NONE: "none" = 'none'

SCROLL_MODE_BOUNCE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L13

Content scrolls past its bounds and then gently bounces back.

const SCROLL_MODE_BOUNCE: 1 = 1

SCROLL_MODE_CLAMP

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L6

Content does not scroll any further than its bounds.

const SCROLL_MODE_CLAMP: 0 = 0

SCROLL_MODE_INFINITE

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L20

Content can scroll forever.

const SCROLL_MODE_INFINITE: 2 = 2

SCROLLBAR_VISIBILITY_SHOW_ALWAYS

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L27

The scrollbar will be visible all the time.

const SCROLLBAR_VISIBILITY_SHOW_ALWAYS: 0 = 0

SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED

Variable · category: User Interface

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/scroll-view/constants.js#L34

The scrollbar will be visible only when content exceeds the size of the viewport.

const SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED: 1 = 1

SEMANTIC_ATTR0

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1512

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR0: "ATTR0" = 'ATTR0'

SEMANTIC_ATTR1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1519

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR1: "ATTR1" = 'ATTR1'

SEMANTIC_ATTR10

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1582

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR10: "ATTR10" = 'ATTR10'

SEMANTIC_ATTR11

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1589

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR11: "ATTR11" = 'ATTR11'

SEMANTIC_ATTR12

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1596

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR12: "ATTR12" = 'ATTR12'

SEMANTIC_ATTR13

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1603

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR13: "ATTR13" = 'ATTR13'

SEMANTIC_ATTR14

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1610

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR14: "ATTR14" = 'ATTR14'

SEMANTIC_ATTR15

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1617

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR15: "ATTR15" = 'ATTR15'

SEMANTIC_ATTR2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1526

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR2: "ATTR2" = 'ATTR2'

SEMANTIC_ATTR3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1533

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR3: "ATTR3" = 'ATTR3'

SEMANTIC_ATTR4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1540

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR4: "ATTR4" = 'ATTR4'

SEMANTIC_ATTR5

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1547

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR5: "ATTR5" = 'ATTR5'

SEMANTIC_ATTR6

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1554

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR6: "ATTR6" = 'ATTR6'

SEMANTIC_ATTR7

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1561

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR7: "ATTR7" = 'ATTR7'

SEMANTIC_ATTR8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1568

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR8: "ATTR8" = 'ATTR8'

SEMANTIC_ATTR9

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1575

Vertex attribute with a user defined semantic.

const SEMANTIC_ATTR9: "ATTR9" = 'ATTR9'

SEMANTIC_BLENDINDICES

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1439

Vertex attribute to be treated as skin blend indices.

const SEMANTIC_BLENDINDICES: "BLENDINDICES" = 'BLENDINDICES'

SEMANTIC_BLENDWEIGHT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1432

Vertex attribute to be treated as skin blend weights.

const SEMANTIC_BLENDWEIGHT: "BLENDWEIGHT" = 'BLENDWEIGHT'

SEMANTIC_COLOR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1446

Vertex attribute to be treated as a color.

const SEMANTIC_COLOR: "COLOR" = 'COLOR'

SEMANTIC_NORMAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1418

Vertex attribute to be treated as a normal.

const SEMANTIC_NORMAL: "NORMAL" = 'NORMAL'

SEMANTIC_POSITION

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1411

Vertex attribute to be treated as a position.

const SEMANTIC_POSITION: "POSITION" = 'POSITION'

SEMANTIC_TANGENT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1425

Vertex attribute to be treated as a tangent.

const SEMANTIC_TANGENT: "TANGENT" = 'TANGENT'

SEMANTIC_TEXCOORD0

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1456

Vertex attribute to be treated as a texture coordinate (set 0).

const SEMANTIC_TEXCOORD0: "TEXCOORD0" = 'TEXCOORD0'

SEMANTIC_TEXCOORD1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1463

Vertex attribute to be treated as a texture coordinate (set 1).

const SEMANTIC_TEXCOORD1: "TEXCOORD1" = 'TEXCOORD1'

SEMANTIC_TEXCOORD2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1470

Vertex attribute to be treated as a texture coordinate (set 2).

const SEMANTIC_TEXCOORD2: "TEXCOORD2" = 'TEXCOORD2'

SEMANTIC_TEXCOORD3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1477

Vertex attribute to be treated as a texture coordinate (set 3).

const SEMANTIC_TEXCOORD3: "TEXCOORD3" = 'TEXCOORD3'

SEMANTIC_TEXCOORD4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1484

Vertex attribute to be treated as a texture coordinate (set 4).

const SEMANTIC_TEXCOORD4: "TEXCOORD4" = 'TEXCOORD4'

SEMANTIC_TEXCOORD5

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1491

Vertex attribute to be treated as a texture coordinate (set 5).

const SEMANTIC_TEXCOORD5: "TEXCOORD5" = 'TEXCOORD5'

SEMANTIC_TEXCOORD6

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1498

Vertex attribute to be treated as a texture coordinate (set 6).

const SEMANTIC_TEXCOORD6: "TEXCOORD6" = 'TEXCOORD6'

SEMANTIC_TEXCOORD7

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1505

Vertex attribute to be treated as a texture coordinate (set 7).

const SEMANTIC_TEXCOORD7: "TEXCOORD7" = 'TEXCOORD7'

SHADER_FORWARD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L840

Render shaded materials using forward rendering.

const SHADER_FORWARD: 0 = 0

SHADERLANGUAGE_GLSL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1852

Shader source code uses GLSL language.

const SHADERLANGUAGE_GLSL: "glsl" = 'glsl'

SHADERLANGUAGE_WGSL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1859

Shader source code uses WGSL language.

const SHADERLANGUAGE_WGSL: "wgsl" = 'wgsl'

SHADERPASS_ALBEDO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L865

Shader used for debug rendering of albedo.

const SHADERPASS_ALBEDO: "debug_albedo" = 'debug_albedo'

SHADERPASS_AO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L907

Shader used for debug rendering of ao.

const SHADERPASS_AO: "debug_ao" = 'debug_ao'

SHADERPASS_EMISSION

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L914

Shader used for debug rendering of emission.

const SHADERPASS_EMISSION: "debug_emission" = 'debug_emission'

SHADERPASS_FORWARD

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L858

Shader that performs forward rendering.

const SHADERPASS_FORWARD: "forward" = 'forward'

SHADERPASS_GLOSS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L893

Shader used for debug rendering of gloss.

const SHADERPASS_GLOSS: "debug_gloss" = 'debug_gloss'

SHADERPASS_LIGHTING

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L921

Shader used for debug rendering of lighting.

const SHADERPASS_LIGHTING: "debug_lighting" = 'debug_lighting'

SHADERPASS_METALNESS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L900

Shader used for debug rendering of metalness.

const SHADERPASS_METALNESS: "debug_metalness" = 'debug_metalness'

SHADERPASS_OPACITY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L879

Shader used for debug rendering of opacity.

const SHADERPASS_OPACITY: "debug_opacity" = 'debug_opacity'

SHADERPASS_SPECULARITY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L886

Shader used for debug rendering of specularity.

const SHADERPASS_SPECULARITY: "debug_specularity" = 'debug_specularity'

SHADERPASS_UV0

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L928

Shader used for debug rendering of UV0 texture coordinates.

const SHADERPASS_UV0: "debug_uv0" = 'debug_uv0'

SHADERPASS_WORLDNORMAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L872

Shader used for debug rendering of world normal.

const SHADERPASS_WORLDNORMAL: "debug_world_normal" = 'debug_world_normal'

SHADERSTAGE_COMPUTE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2330

The resource is visible to the compute shader.

const SHADERSTAGE_COMPUTE: 4 = 4

SHADERSTAGE_FRAGMENT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2323

The resource is visible to the fragment shader.

const SHADERSTAGE_FRAGMENT: 2 = 2

SHADERSTAGE_VERTEX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2316

The resource is visible to the vertex shader.

const SHADERSTAGE_VERTEX: 1 = 1

SHADOW_CASCADE_0

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L416

The flag that controls shadow rendering for the 0 cascade

const SHADOW_CASCADE_0: 1 = 1

SHADOW_CASCADE_1

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L423

The flag that controls shadow rendering for the 1 cascade

const SHADOW_CASCADE_1: 2 = 2

SHADOW_CASCADE_2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L430

The flag that controls shadow rendering for the 2 cascade

const SHADOW_CASCADE_2: 4 = 4

SHADOW_CASCADE_3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L437

The flag that controls shadow rendering for the 3 cascade

const SHADOW_CASCADE_3: 8 = 8

SHADOW_CASCADE_ALL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L444

The flag that controls shadow rendering for the all cascades

const SHADOW_CASCADE_ALL: 255 = 255

SHADOW_PCF1_16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L375

A shadow sampling technique using a 16-bit shadow map that performs a single depth comparison for sharp shadow edges.

const SHADOW_PCF1_16F: 7 = 7

SHADOW_PCF1_32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L350

A shadow sampling technique using a 32-bit shadow map that performs a single depth comparison for sharp shadow edges.

const SHADOW_PCF1_32F: 5 = 5

SHADOW_PCF3_16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L383

A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.

const SHADOW_PCF3_16F: 8 = 8

SHADOW_PCF3_32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L290

A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.

const SHADOW_PCF3_32F: 0 = 0

SHADOW_PCF5_16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L391

A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 grid of texels for softened shadow edges.

const SHADOW_PCF5_16F: 9 = 9

SHADOW_PCF5_32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L336

A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 5x5 grid of texels for softened shadow edges.

const SHADOW_PCF5_32F: 4 = 4

SHADOW_PCSS_32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L367

A shadow sampling technique using a 32-bit shadow map that adjusts filter size based on blocker distance, producing realistic, soft shadow edges that vary with the light's occlusion. Note that this technique requires both GraphicsDevice#textureFloatRenderable and GraphicsDevice#textureFloatFilterable to be true, and falls back to SHADOW_PCF3_32F otherwise.

const SHADOW_PCSS_32F: 6 = 6

SHADOW_VSM_16F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L306

A shadow sampling technique using a 16-bit exponential variance shadow map that leverages variance to approximate shadow boundaries, enabling soft shadows. Only supported when GraphicsDevice#textureHalfFloatRenderable is true. Falls back to SHADOW_PCF3_32F, if not supported.

const SHADOW_VSM_16F: 2 = 2

SHADOW_VSM_32F

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L322

A shadow sampling technique using a 32-bit exponential variance shadow map that leverages variance to approximate shadow boundaries, enabling soft shadows. Only supported when GraphicsDevice#textureFloatRenderable is true. Falls back to SHADOW_VSM_16F, if not supported.

const SHADOW_VSM_32F: 3 = 3

SHADOWUPDATE_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L783

The shadow map is not to be updated.

const SHADOWUPDATE_NONE: 0 = 0

SHADOWUPDATE_REALTIME

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L797

The shadow map is regenerated every frame.

const SHADOWUPDATE_REALTIME: 2 = 2

SHADOWUPDATE_THISFRAME

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L790

The shadow map is regenerated this frame and not on subsequent frames.

const SHADOWUPDATE_THISFRAME: 1 = 1

SKYTYPE_BOX

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1083

A sky texture is rendered using a box projection. This is generally suitable for interior environments.

const SKYTYPE_BOX: "box" = 'box'

SKYTYPE_DOME

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1091

A sky texture is rendered using a dome projection. This is generally suitable for exterior environments.

const SKYTYPE_DOME: "dome" = 'dome'

SKYTYPE_INFINITE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1075

A sky texture is rendered using an infinite projection.

const SKYTYPE_INFINITE: "infinite" = 'infinite'

SORTMODE_BACK2FRONT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1024

Mesh instances are sorted back to front. This is the way to properly render many semi-transparent objects on different depth, one is blended on top of another.

const SORTMODE_BACK2FRONT: 3 = 3

SORTMODE_FRONT2BACK

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1032

Mesh instances are sorted front to back. Depending on GPU and the scene, this option may give better performance than SORTMODE_MATERIALMESH due to reduced overdraw.

const SORTMODE_FRONT2BACK: 4 = 4

SORTMODE_MANUAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1008

Mesh instances are sorted based on MeshInstance#drawOrder.

const SORTMODE_MANUAL: 1 = 1

SORTMODE_MATERIALMESH

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1016

Mesh instances are sorted to minimize switching between materials and meshes to improve rendering performance.

const SORTMODE_MATERIALMESH: 2 = 2

SORTMODE_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1001

No sorting is applied. Mesh instances are rendered in the same order they were added to a layer.

const SORTMODE_NONE: 0 = 0

SPECOCC_AO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L716

Use AO directly to occlude specular.

const SPECOCC_AO: 1 = 1

SPECOCC_GLOSSDEPENDENT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L723

Modify AO based on material glossiness/view angle to occlude specular.

const SPECOCC_GLOSSDEPENDENT: 2 = 2

SPECOCC_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L709

No specular occlusion.

const SPECOCC_NONE: 0 = 0

SPRITE_RENDERMODE_SIMPLE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L935

This mode renders a sprite as a simple quad.

const SPRITE_RENDERMODE_SIMPLE: 0 = 0

SPRITE_RENDERMODE_SLICED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L944

This mode renders a sprite using 9-slicing in 'sliced' mode. Sliced mode stretches the top and bottom regions of the sprite horizontally, the left and right regions vertically and the middle region both horizontally and vertically.

const SPRITE_RENDERMODE_SLICED: 1 = 1

SPRITE_RENDERMODE_TILED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L953

This mode renders a sprite using 9-slicing in 'tiled' mode. Tiled mode tiles the top and bottom regions of the sprite horizontally, the left and right regions vertically and the middle region both horizontally and vertically.

const SPRITE_RENDERMODE_TILED: 2 = 2

SPRITETYPE_ANIMATED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/constants.js#L13

A SpriteComponent that renders sprite animations.

const SPRITETYPE_ANIMATED: "animated" = 'animated'

SPRITETYPE_SIMPLE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/sprite/constants.js#L6

A SpriteComponent that displays a single frame from a sprite asset.

const SPRITETYPE_SIMPLE: "simple" = 'simple'

SSAOTYPE_COMBINE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L24

SSAO is applied as a standalone effect after the scene is rendered. This method uniformly overlays ambient occlusion across the image, disregarding direct lighting interactions. While this may sacrifice some realism, it can be advantageous for achieving specific artistic styles.

const SSAOTYPE_COMBINE: "combine" = 'combine'

SSAOTYPE_LIGHTING

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L15

SSAO is applied during the lighting calculation stage, allowing it to blend seamlessly with scene lighting. This results in ambient occlusion being more pronounced in areas where direct light is obstructed, enhancing realism.

const SSAOTYPE_LIGHTING: "lighting" = 'lighting'

SSAOTYPE_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/extras/render-passes/constants.js#L6

SSAO is disabled.

const SSAOTYPE_NONE: "none" = 'none'

STENCILOP_DECREMENT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1661

Decrement the value.

const STENCILOP_DECREMENT: 5 = 5

STENCILOP_DECREMENTWRAP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1668

Decrement the value but wrap it to a maximum representable value if the current value is 0.

const STENCILOP_DECREMENTWRAP: 6 = 6

STENCILOP_INCREMENT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1647

Increment the value.

const STENCILOP_INCREMENT: 3 = 3

STENCILOP_INCREMENTWRAP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1654

Increment the value but wrap it to zero when it's larger than a maximum representable value.

const STENCILOP_INCREMENTWRAP: 4 = 4

STENCILOP_INVERT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1675

Invert the value bitwise.

const STENCILOP_INVERT: 7 = 7

STENCILOP_KEEP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1626

Don't change the stencil buffer value.

const STENCILOP_KEEP: 0 = 0

STENCILOP_REPLACE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1640

Replace value with the reference value (see StencilParameters).

const STENCILOP_REPLACE: 2 = 2

STENCILOP_ZERO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1633

Set value to zero.

const STENCILOP_ZERO: 1 = 1

TEXTUREDIMENSION_1D

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1745

Texture data is stored in a 1-dimensional texture.

const TEXTUREDIMENSION_1D: "1d" = '1d'

TEXTUREDIMENSION_2D

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1752

Texture data is stored in a 2-dimensional texture.

const TEXTUREDIMENSION_2D: "2d" = '2d'

TEXTUREDIMENSION_2D_ARRAY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1759

Texture data is stored in an array of 2-dimensional textures.

const TEXTUREDIMENSION_2D_ARRAY: "2d-array" = '2d-array'

TEXTUREDIMENSION_3D

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1780

Texture data is stored in a 3-dimensional texture.

const TEXTUREDIMENSION_3D: "3d" = '3d'

TEXTUREDIMENSION_CUBE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1766

Texture data is stored in a cube texture.

const TEXTUREDIMENSION_CUBE: "cube" = 'cube'

TEXTUREDIMENSION_CUBE_ARRAY

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1773

Texture data is stored in an array of cube textures.

const TEXTUREDIMENSION_CUBE_ARRAY: "cube-array" = 'cube-array'

TEXTURELOCK_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1682

The texture is not in a locked state.

const TEXTURELOCK_NONE: 0 = 0

TEXTURELOCK_READ

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1689

Read only. Any changes to the locked mip level's pixels will not update the texture.

const TEXTURELOCK_READ: 1 = 1

TEXTURELOCK_WRITE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1696

Write only. The contents of the specified mip level will be entirely replaced.

const TEXTURELOCK_WRITE: 2 = 2

TEXTUREPROJECTION_CUBE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1831

Texture data is stored in cubemap projection format.

const TEXTUREPROJECTION_CUBE: "cube" = 'cube'

TEXTUREPROJECTION_EQUIRECT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1838

Texture data is stored in equirectangular projection format.

const TEXTUREPROJECTION_EQUIRECT: "equirect" = 'equirect'

TEXTUREPROJECTION_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1824

Texture data is not stored a specific projection format.

const TEXTUREPROJECTION_NONE: "none" = 'none'

TEXTUREPROJECTION_OCTAHEDRAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1845

Texture data is stored in octahedral projection format.

const TEXTUREPROJECTION_OCTAHEDRAL: "octahedral" = 'octahedral'

TEXTURETYPE_DEFAULT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1703

Texture is a default type.

const TEXTURETYPE_DEFAULT: "default" = 'default'

TEXTURETYPE_RGBE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1717

Texture stores high dynamic range data in RGBE format.

const TEXTURETYPE_RGBE: "rgbe" = 'rgbe'

TEXTURETYPE_RGBM

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1710

Texture stores high dynamic range data in RGBM format.

const TEXTURETYPE_RGBM: "rgbm" = 'rgbm'

TEXTURETYPE_RGBP

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1724

Texture stores high dynamic range data in RGBP encoding.

const TEXTURETYPE_RGBP: "rgbp" = 'rgbp'

TEXTURETYPE_SWIZZLEGGGR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1733

Texture stores normalmap data swizzled in GGGR format. This is used for tangent space normal maps. The R component is stored in alpha and G is stored in RGB. This packing can result in higher quality when the texture data is compressed.

const TEXTURETYPE_SWIZZLEGGGR: "swizzleGGGR" = 'swizzleGGGR'

TONEMAP_ACES

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L670

ACES filmic tonemapping curve.

const TONEMAP_ACES: 3 = 3

TONEMAP_ACES2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L677

ACES v2 filmic tonemapping curve.

const TONEMAP_ACES2: 4 = 4

TONEMAP_FILMIC

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L656

Filmic tonemapping curve.

const TONEMAP_FILMIC: 1 = 1

TONEMAP_HEJL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L663

Hejl filmic tonemapping curve.

const TONEMAP_HEJL: 2 = 2

TONEMAP_LINEAR

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L649

Linear tonemapping. The colors are preserved, but the exposure is applied.

const TONEMAP_LINEAR: 0 = 0

TONEMAP_NEUTRAL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L684

Khronos PBR Neutral tonemapping curve.

const TONEMAP_NEUTRAL: 5 = 5

TONEMAP_NONE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L691

No tonemapping or exposure is applied. Used for HDR rendering.

const TONEMAP_NONE: 6 = 6

TRACEID_ASSETS

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L162

Logs all assets in the asset registry.

const TRACEID_ASSETS: "Assets" = 'Assets'

TRACEID_BINDGROUP_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L98

Logs the creation of bind groups.

const TRACEID_BINDGROUP_ALLOC: "BindGroupAlloc" = 'BindGroupAlloc'

TRACEID_BINDGROUPFORMAT_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L113

Logs the creation of bind group formats.

const TRACEID_BINDGROUPFORMAT_ALLOC: "BindGroupFormatAlloc" = 'BindGroupFormatAlloc'

TRACEID_BUFFERS

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L155

Logs GPU buffer memory tracked on the graphics device (vertex, index, storage).

const TRACEID_BUFFERS: "Buffers" = 'Buffers'

TRACEID_COMPUTEPIPELINE_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L127

Logs the creation of compute pipelines. WebGPU only.

const TRACEID_COMPUTEPIPELINE_ALLOC: "ComputePipelineAlloc" = 'ComputePipelineAlloc'

TRACEID_ELEMENT

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L141

Logs the internal debug information for Elements.

const TRACEID_ELEMENT: "Element" = 'Element'

TRACEID_GPU_TIMINGS

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L183

Logs the GPU timings.

const TRACEID_GPU_TIMINGS: "GpuTimings" = 'GpuTimings'

TRACEID_MATERIAL_UPDATE

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L106

Records where a material was created and last changed, so that the debug build can report them when a material property is changed without a subsequent call to Material#update.

const TRACEID_MATERIAL_UPDATE: "MaterialUpdate" = 'MaterialUpdate'

TRACEID_OCTREE_RESOURCES

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L176

Logs the loaded GSplat resources for individual LOD levels of an octree.

const TRACEID_OCTREE_RESOURCES: "OctreeResources" = 'OctreeResources'

TRACEID_PIPELINELAYOUT_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L134

Logs the creation of pipeline layouts. WebGPU only.

const TRACEID_PIPELINELAYOUT_ALLOC: "PipelineLayoutAlloc" = 'PipelineLayoutAlloc'

TRACEID_RENDER_ACTION

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L35

Logs render actions created by the layer composition. Only executes when the layer composition changes.

const TRACEID_RENDER_ACTION: "RenderAction" = 'RenderAction'

TRACEID_RENDER_FRAME

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L6

Logs a frame number.

const TRACEID_RENDER_FRAME: "RenderFrame" = 'RenderFrame'

TRACEID_RENDER_FRAME_TIME

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L13

Logs a frame time.

const TRACEID_RENDER_FRAME_TIME: "RenderFrameTime" = 'RenderFrameTime'

TRACEID_RENDER_PASS

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L20

Logs basic information about generated render passes.

const TRACEID_RENDER_PASS: "RenderPass" = 'RenderPass'

TRACEID_RENDER_PASS_DETAIL

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L27

Logs additional detail for render passes.

const TRACEID_RENDER_PASS_DETAIL: "RenderPassDetail" = 'RenderPassDetail'

TRACEID_RENDER_QUEUE

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L169

Logs the render queue commands.

const TRACEID_RENDER_QUEUE: "RenderQueue" = 'RenderQueue'

TRACEID_RENDER_TARGET_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L42

Logs the allocation of render targets.

const TRACEID_RENDER_TARGET_ALLOC: "RenderTargetAlloc" = 'RenderTargetAlloc'

TRACEID_RENDERPIPELINE_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L120

Logs the creation of render pipelines. WebGPU only.

const TRACEID_RENDERPIPELINE_ALLOC: "RenderPipelineAlloc" = 'RenderPipelineAlloc'

TRACEID_SHADER_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L56

Logs the creation of shaders.

const TRACEID_SHADER_ALLOC: "ShaderAlloc" = 'ShaderAlloc'

TRACEID_SHADER_COMPILE

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L63

Logs the compilation time of shaders.

const TRACEID_SHADER_COMPILE: "ShaderCompile" = 'ShaderCompile'

TRACEID_TEXTURE_ALLOC

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L49

Logs the allocation of textures.

const TRACEID_TEXTURE_ALLOC: "TextureAlloc" = 'TextureAlloc'

TRACEID_TEXTURES

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L148

Logs the vram use by all textures in memory.

const TRACEID_TEXTURES: "Textures" = 'Textures'

TRACEID_VRAM_IB

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L84

Logs the vram use by the index buffers.

const TRACEID_VRAM_IB: "VRAM.Ib" = 'VRAM.Ib'

TRACEID_VRAM_SB

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L91

Logs the vram use by the storage buffers.

const TRACEID_VRAM_SB: "VRAM.Sb" = 'VRAM.Sb'

TRACEID_VRAM_TEXTURE

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L70

Logs the vram use by the textures.

const TRACEID_VRAM_TEXTURE: "VRAM.Texture" = 'VRAM.Texture'

TRACEID_VRAM_VB

Variable · category: Debug

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/core/constants.js#L77

Logs the vram use by the vertex buffers.

const TRACEID_VRAM_VB: "VRAM.Vb" = 'VRAM.Vb'

TRANSFORM_FEEDBACK_INTERLEAVED

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L291

Captures all varyings into one interleaved transform feedback buffer.

const TRANSFORM_FEEDBACK_INTERLEAVED: 0 = 0

TRANSFORM_FEEDBACK_SEPARATE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L298

Captures each varying into its own transform feedback buffer.

const TRANSFORM_FEEDBACK_SEPARATE: 1 = 1

TYPE_FLOAT16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1915

16-bit floating point vertex element type.

const TYPE_FLOAT16: 7 = 7

TYPE_FLOAT32

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1908

Floating point vertex element type.

const TYPE_FLOAT32: 6 = 6

TYPE_INT16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1880

Signed short vertex element type.

const TYPE_INT16: 2 = 2

TYPE_INT32

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1894

Signed integer vertex element type.

const TYPE_INT32: 4 = 4

TYPE_INT8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1866

Signed byte vertex element type.

const TYPE_INT8: 0 = 0

TYPE_UINT16

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1887

Unsigned short vertex element type.

const TYPE_UINT16: 3 = 3

TYPE_UINT32

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1901

Unsigned integer vertex element type.

const TYPE_UINT32: 5 = 5

TYPE_UINT8

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1873

Unsigned byte vertex element type.

const TYPE_UINT8: 1 = 1

UNIFORMTYPE_BOOL

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1927

Boolean uniform type.

const UNIFORMTYPE_BOOL: 0 = 0

UNIFORMTYPE_BVEC2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1990

2 x Boolean uniform type.

const UNIFORMTYPE_BVEC2: 9 = 9

UNIFORMTYPE_BVEC3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1997

3 x Boolean uniform type.

const UNIFORMTYPE_BVEC3: 10 = 10

UNIFORMTYPE_BVEC4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2004

4 x Boolean uniform type.

const UNIFORMTYPE_BVEC4: 11 = 11

UNIFORMTYPE_FLOAT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1941

Float uniform type.

const UNIFORMTYPE_FLOAT: 2 = 2

UNIFORMTYPE_INT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1934

Integer uniform type.

const UNIFORMTYPE_INT: 1 = 1

UNIFORMTYPE_IVEC2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1969

2 x Integer uniform type.

const UNIFORMTYPE_IVEC2: 6 = 6

UNIFORMTYPE_IVEC3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1976

3 x Integer uniform type.

const UNIFORMTYPE_IVEC3: 7 = 7

UNIFORMTYPE_IVEC4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1983

4 x Integer uniform type.

const UNIFORMTYPE_IVEC4: 8 = 8

UNIFORMTYPE_MAT2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2011

2 x 2 x Float uniform type.

const UNIFORMTYPE_MAT2: 12 = 12

UNIFORMTYPE_MAT3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2018

3 x 3 x Float uniform type.

const UNIFORMTYPE_MAT3: 13 = 13

UNIFORMTYPE_MAT4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2025

4 x 4 x Float uniform type.

const UNIFORMTYPE_MAT4: 14 = 14

UNIFORMTYPE_UINT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2046

Unsigned integer uniform type.

const UNIFORMTYPE_UINT: 26 = 26

UNIFORMTYPE_UVEC2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2053

2 x Unsigned integer uniform type.

const UNIFORMTYPE_UVEC2: 27 = 27

UNIFORMTYPE_UVEC3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2060

3 x Unsigned integer uniform type.

const UNIFORMTYPE_UVEC3: 28 = 28

UNIFORMTYPE_UVEC4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L2067

4 x Unsigned integer uniform type.

const UNIFORMTYPE_UVEC4: 29 = 29

UNIFORMTYPE_VEC2

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1948

2 x Float uniform type.

const UNIFORMTYPE_VEC2: 3 = 3

UNIFORMTYPE_VEC3

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1955

3 x Float uniform type.

const UNIFORMTYPE_VEC3: 4 = 4

UNIFORMTYPE_VEC4

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/graphics/constants.js#L1962

4 x Float uniform type.

const UNIFORMTYPE_VEC4: 5 = 5

VIEW_CENTER

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L980

Center of view.

const VIEW_CENTER: 0 = 0

VIEW_LEFT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L987

Left of view. Only used in stereo rendering.

const VIEW_LEFT: 1 = 1

VIEW_RIGHT

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L994

Right of view. Only used in stereo rendering.

const VIEW_RIGHT: 2 = 2

WORKBUFFER_UPDATE_ALWAYS

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1256

Work buffer is updated every frame. Useful for custom shader code via GSplatComponent#setWorkBufferModifier that depends on time or animated uniforms.

const WORKBUFFER_UPDATE_ALWAYS: number = 2

WORKBUFFER_UPDATE_AUTO

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1238

Work buffer is updated only when needed (transform, format, LOD changes, new gsplat etc).

const WORKBUFFER_UPDATE_AUTO: number = 0

WORKBUFFER_UPDATE_ONCE

Variable · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/scene/constants.js#L1247

Work buffer is updated once on the next frame, then automatically switches to WORKBUFFER_UPDATE_AUTO.

const WORKBUFFER_UPDATE_ONCE: number = 1

XRDEPTHSENSINGFORMAT_F32

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L204

Float 32 - indicates that depth sensing preferred raw data format is Float (32 bit).

const XRDEPTHSENSINGFORMAT_F32: "float32" = 'float32'

XRDEPTHSENSINGFORMAT_L8A8

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L190

Luminance Alpha - indicates that depth sensing preferred raw data format is Luminance Alpha (8bit + 8bit). This format is guaranteed to be supported.

const XRDEPTHSENSINGFORMAT_L8A8: "luminance-alpha" = 'luminance-alpha'

XRDEPTHSENSINGFORMAT_R16U

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L197

Unsigned Short - indicates that depth sensing preferred raw data format is Unsigned Short (16 bit).

const XRDEPTHSENSINGFORMAT_R16U: "unsigned-short" = 'unsigned-short'

XRDEPTHSENSINGUSAGE_CPU

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L175

CPU - indicates that depth sensing preferred usage is CPU. This usage path is guaranteed to be supported.

const XRDEPTHSENSINGUSAGE_CPU: "cpu-optimized" = 'cpu-optimized'

XRDEPTHSENSINGUSAGE_GPU

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L182

GPU - indicates that depth sensing preferred usage is GPU.

const XRDEPTHSENSINGUSAGE_GPU: "gpu-optimized" = 'gpu-optimized'

XREYE_LEFT

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L115

Left - view associated with left eye.

const XREYE_LEFT: "left" = 'left'

XREYE_NONE

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L108

None - view associated with a monoscopic screen, such as mobile phone screens.

const XREYE_NONE: "none" = 'none'

XREYE_RIGHT

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L122

Right - view associated with right eye.

const XREYE_RIGHT: "right" = 'right'

XRHAND_LEFT

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L136

Left - indicates that input source is meant to be held in left hand.

const XRHAND_LEFT: "left" = 'left'

XRHAND_NONE

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L129

None - input source is not meant to be held in hands.

const XRHAND_NONE: "none" = 'none'

XRHAND_RIGHT

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L143

Right - indicates that input source is meant to be held in right hand.

const XRHAND_RIGHT: "right" = 'right'

XRPAD_A

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L859

The A button from XR pad.

const XRPAD_A: 4 = 4

XRPAD_B

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L866

The B button from XR pad.

const XRPAD_B: 5 = 5

XRPAD_SQUEEZE

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L845

The squeeze button from XR pad.

const XRPAD_SQUEEZE: 1 = 1

XRPAD_STICK_BUTTON

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L852

The button when pressing the XR pad's stick.

const XRPAD_STICK_BUTTON: 3 = 3

XRPAD_STICK_X

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L817

Horizontal axis on the stick of an XR pad.

const XRPAD_STICK_X: 2 = 2

XRPAD_STICK_Y

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L824

Vertical axis on the stick of an XR pad.

const XRPAD_STICK_Y: 3 = 3

XRPAD_TOUCHPAD_BUTTON

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L831

The button when pressing the XR pad's touchpad.

const XRPAD_TOUCHPAD_BUTTON: 2 = 2

XRPAD_TOUCHPAD_X

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L803

Horizontal axis on the touchpad of an XR pad.

const XRPAD_TOUCHPAD_X: 0 = 0

XRPAD_TOUCHPAD_Y

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L810

Vertical axis on the touchpad of an XR pad.

const XRPAD_TOUCHPAD_Y: 1 = 1

XRPAD_TRIGGER

Variable · category: Input Devices

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/platform/input/constants.js#L838

The trigger button from XR pad.

const XRPAD_TRIGGER: 0 = 0

XRSPACE_BOUNDEDFLOOR

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L65

Bounded Floor - represents a tracking space with its native origin at the floor, where the user is expected to move within a pre-established boundary. Tracking in a bounded-floor reference space is optimized for keeping the native origin and bounds geometry stable relative to the user's environment.

const XRSPACE_BOUNDEDFLOOR: "bounded-floor" = 'bounded-floor'

XRSPACE_LOCAL

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L42

Local - represents a tracking space with a native origin near the viewer at the time of creation. The exact position and orientation will be initialized based on the conventions of the underlying platform. When using this reference space the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with 6DoF tracking, local reference spaces should emphasize keeping the origin stable relative to the user's environment.

const XRSPACE_LOCAL: "local" = 'local'

XRSPACE_LOCALFLOOR

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L55

Local Floor - represents a tracking space with a native origin at the floor in a safe position for the user to stand. The y axis equals 0 at floor level, with the x and z position and orientation initialized based on the conventions of the underlying platform. Floor level value might be estimated by the underlying platform. When using this reference space, the user is not expected to move beyond their initial position much, if at all, and tracking is optimized for that purpose. For devices with 6DoF tracking, local-floor reference spaces should emphasize keeping the origin stable relative to the user's environment.

const XRSPACE_LOCALFLOOR: "local-floor" = 'local-floor'

XRSPACE_UNBOUNDED

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L75

Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially even long distances from their starting point. Tracking in an unbounded reference space is optimized for stability around the user's current position, and as such the native origin may drift over time.

const XRSPACE_UNBOUNDED: "unbounded" = 'unbounded'

XRSPACE_VIEWER

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L30

Viewer - always supported space with some basic tracking capabilities.

const XRSPACE_VIEWER: "viewer" = 'viewer'

XRTARGETRAY_GAZE

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L84

Gaze - indicates the target ray will originate at the viewer and follow the direction it is facing. This is commonly referred to as a "gaze input" device in the context of head-mounted displays.

const XRTARGETRAY_GAZE: "gaze" = 'gaze'

XRTARGETRAY_POINTER

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L101

Tracked Pointer - indicates that the target ray originates from either a handheld device or other hand-tracking mechanism and represents that the user is using their hands or the held device for pointing.

const XRTARGETRAY_POINTER: "tracked-pointer" = 'tracked-pointer'

XRTARGETRAY_SCREEN

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L92

Screen - indicates that the input source was an interaction with the canvas element associated with an inline session's output context, such as a mouse click or touch event.

const XRTARGETRAY_SCREEN: "screen" = 'screen'

XRTRACKABLE_MESH

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L167

Mesh - indicates that the hit test results will be computed based on the meshes detected by the underlying Augmented Reality system.

const XRTRACKABLE_MESH: "mesh" = 'mesh'

XRTRACKABLE_PLANE

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L159

Plane - indicates that the hit test results will be computed based on the planes detected by the underlying Augmented Reality system.

const XRTRACKABLE_PLANE: "plane" = 'plane'

XRTRACKABLE_POINT

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L151

Point - indicates that the hit test results will be computed based on the feature points detected by the underlying Augmented Reality system.

const XRTRACKABLE_POINT: "point" = 'point'

XRTYPE_AR

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L23

Immersive AR - session that provides exclusive access to VR/AR device that is intended to be blended with real-world environment.

const XRTYPE_AR: "immersive-ar" = 'immersive-ar'

XRTYPE_INLINE

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L7

Inline - always available type of session. It has limited features availability and is rendered into HTML element.

const XRTYPE_INLINE: "inline" = 'inline'

XRTYPE_VR

Variable · category: XR

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/xr/constants.js#L15

Immersive VR - session that provides exclusive access to VR device with best available tracking features.

const XRTYPE_VR: "immersive-vr" = 'immersive-vr'