@pixi/core
- Version 6.3.2
- Published
- 6.42 MB
- 1 dependency
- MIT license
Install
npm i @pixi/core
yarn add @pixi/core
pnpm add @pixi/core
Overview
Core PixiJS
Index
Variables
Functions
Classes
BaseTexture
- addToCache()
- alphaMode
- anisotropicLevel
- cacheId
- castToBaseTexture()
- destroy()
- destroyed
- dirtyId
- dirtyStyleId
- dispose()
- format
- from()
- fromBuffer()
- height
- isPowerOfTwo
- mipmap
- onError()
- parentTextureArray
- realHeight
- realWidth
- removeFromCache()
- resolution
- resource
- scaleMode
- setRealSize()
- setResolution()
- setResource()
- setSize()
- setStyle()
- target
- textureCacheIds
- touched
- type
- uid
- update()
- valid
- width
- wrapMode
FramebufferSystem
- bind()
- blit()
- canMultisampleFramebuffer()
- clear()
- CONTEXT_UID
- contextChange()
- current
- destroy()
- detectSamples()
- disposeAll()
- disposeFramebuffer()
- forceStencil()
- gl
- hasMRT
- initFramebuffer()
- managedFramebuffers
- msaaSamples
- renderer
- reset()
- resizeFramebuffer()
- setViewport()
- size
- unknownFramebuffer
- updateFramebuffer()
- viewport
- writeDepthTexture
Interfaces
Type Aliases
Variables
variable BatchRenderer
const BatchRenderer: typeof AbstractBatchRenderer;
variable defaultFilterVertex
const defaultFilterVertex: string;
variable defaultVertex
const defaultVertex: string;
Default filter vertex shader PIXI {string} defaultFilterVertex
variable INSTALLED
const INSTALLED: IResourcePlugin<any, any>[];
Collection of installed resource types, class must extend PIXI.Resource.
Example 1
class CustomResource extends PIXI.Resource { // MUST have source, options constructor signature // for auto-detected resources to be created. constructor(source, options) { super(); } upload(renderer, baseTexture, glTexture) { // upload with GL return true; } // used to auto-detect resource static test(source, extension) { return extension === 'xyz'|| source instanceof SomeClass; } } // Install the new resource type PIXI.INSTALLED.push(CustomResource);
PIXI {Array<PIXI.IResourcePlugin>}
Modifiers
@readonly
variable resources
const resources: {};
PIXI resources
See Also
PIXI
Deprecated
since 6.0.0
variable systems
const systems: {};
PIXI systems
See Also
PIXI
Deprecated
since 6.0.0
variable uniformParsers
const uniformParsers: IUniformParser[];
Functions
function autoDetectRenderer
autoDetectRenderer: (options?: IRendererOptionsAuto) => AbstractRenderer;
This helper function will automatically detect which renderer you should be using. WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by the browser then this function will return a canvas renderer
PIXI autoDetectRenderer
Parameter options
The optional renderer parameters
Parameter
{number} [options.width=800] - the width of the renderers view
Parameter
{number} [options.height=600] - the height of the renderers view
Parameter
{HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
Parameter
{boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context
alpha
property. If you want to set transparency, please usebackgroundAlpha
. This option is for cases where the canvas needs to be opaque, possibly for performance reasons on some older devices.Parameter
{boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for resolutions other than 1
Parameter
{boolean} [options.antialias=false] - sets antialias
Parameter
{boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context
Parameter
{number} [options.backgroundColor=0x000000] - The background color of the rendered area (shown if not transparent).
Parameter
{number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
Parameter
{boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or not before the new render pass.
Parameter
{number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
Parameter
{boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise it is ignored.
Parameter
{string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" for devices with dual graphics card **webgl only** {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer
function autoDetectResource
autoDetectResource: <R extends Resource, RO>(source: unknown, options?: RO) => R;
Create a resource element from a single source element. This auto-detects which type of resource to create. All resources that are auto-detectable must have a static
test
method and a constructor with the arguments(source, options?)
. Currently, the supported resources for auto-detection include: - PIXI.ImageResource - PIXI.CanvasResource - PIXI.VideoResource - PIXI.SVGResource - PIXI.BufferResource PIXI autoDetectResourceParameter source
Resource source, this can be the URL to the resource, a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri or any other resource that can be auto-detected. If not resource is detected, it's assumed to be an ImageResource.
Parameter options
Pass-through options to use for Resource
Parameter
{number} [options.width] - Width of BufferResource or SVG rasterization
Parameter
{number} [options.height] - Height of BufferResource or SVG rasterization
Parameter
{boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading
Parameter
{number} [options.scale=1] - SVG source scale. Overridden by width, height
Parameter
{boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object
Parameter
{boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin
Parameter
{boolean} [options.autoPlay=true] - Video option to start playing video immediately
Parameter
{number} [options.updateFPS=0] - Video option to update how many times a second the texture should be updated from the video. Leave at 0 to update at every render {PIXI.Resource} The created resource.
function checkMaxIfStatementsInShader
checkMaxIfStatementsInShader: (maxIfs: number, gl: IRenderingContext) => number;
function createUBOElements
createUBOElements: (uniformData: IUniformData[]) => { uboElements: UBOElement[]; size: number;};
logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js rewrote it, but this was a great starting point to get a solid understanding of whats going on :)
Parameter uniformData
function generateProgram
generateProgram: (gl: IRenderingContext, program: Program) => GLProgram;
generates a WebGL Program object from a high level Pixi Program.
Parameter gl
a rendering context on which to generate the program
Parameter program
the high level Pixi Program.
function generateUniformBufferSync
generateUniformBufferSync: ( group: UniformGroup, uniformData: Dict<any>) => { size: number; syncFunc: UniformsSyncCallback };
function getTestContext
getTestContext: () => WebGLRenderingContext | WebGL2RenderingContext;
returns a little WebGL context to use for program inspection.
Returns
{WebGLRenderingContext} a gl context to test with
function getUBOData
getUBOData: (uniforms: Dict<any>, uniformData: Dict<any>) => any[];
Classes
class AbstractBatchRenderer
class AbstractBatchRenderer extends ObjectRenderer {}
Renderer dedicated to drawing and batching sprites.
This is the default batch renderer. It buffers objects with texture-based geometries and renders them in batches. It uploads multiple textures to the GPU to reduce to the number of draw calls.
PIXI
constructor
constructor(renderer: Renderer);
This will hook onto the renderer's
contextChange
andprerender
signals.Parameter renderer
The renderer this works for.
property geometryClass
protected geometryClass: typeof BatchGeometry;
The class that represents the geometry of objects that are going to be batched with this.
{object} PIXI.BatchGeometry
property MAX_TEXTURES
MAX_TEXTURES: number;
Maximum number of textures that can be uploaded to the GPU under the current context. It is initialized properly in
this.contextChange
.See Also
PIXI.AbstractBatchRenderer#contextChange
Modifiers
@readonly
property shaderGenerator
protected shaderGenerator: BatchShaderGenerator;
This is used to generate a shader that can color each vertex based on a
aTextureId
attribute that points to an texture inuSampler
.This enables the objects with different textures to be drawn in the same draw call.
You can customize your shader by creating your custom shader generator.
property size
size: number;
The number of bufferable objects before a flush occurs automatically.
settings.SPRITE_BATCH_SIZE * 4
property state
readonly state: State;
The WebGL state in which this renderer will work.
property vertexSize
protected vertexSize: number;
Size of data being buffered per vertex in the attribute buffers (in floats). By default, the batch-renderer plugin uses 6:
| aVertexPosition | 2 | |-----------------|---| | aTextureCoords | 2 | | aColor | 1 | | aTextureId | 1 |
Modifiers
@readonly
method bindAndClearTexArray
bindAndClearTexArray: (texArray: BatchTextureArray) => void;
Bind textures for current rendering
method buildDrawCalls
buildDrawCalls: ( texArray: BatchTextureArray, start: number, finish: number) => void;
Populating drawcalls for rendering
method buildTexturesAndDrawCalls
buildTexturesAndDrawCalls: () => void;
method contextChange
contextChange: () => void;
Handles the
contextChange
signal.It calculates
this.MAX_TEXTURES
and allocating the packed-geometry object pool.
method destroy
destroy: () => void;
Destroys this
AbstractBatchRenderer
. It cannot be used again.
method drawBatches
drawBatches: () => void;
method flush
flush: () => void;
Renders the content _now_ and empties the current batch.
method getAttributeBuffer
getAttributeBuffer: (size: number) => ViewableBuffer;
Fetches an attribute buffer from
this._aBuffers
that can hold atleastsize
floats.Parameter size
minimum capacity required - buffer than can hold atleast
size
floats
method getIndexBuffer
getIndexBuffer: (size: number) => Uint16Array;
Fetches an index buffer from
this._iBuffers
that can have at leastsize
capacity.Parameter size
minimum required capacity - buffer that can fit
size
indices.
method initFlushBuffers
initFlushBuffers: () => void;
Makes sure that static and dynamic flush pooled objects have correct dimensions.
method onPrerender
onPrerender: () => void;
Handles the
prerender
signal.It ensures that flushes start from the first geometry object again.
method packInterleavedGeometry
packInterleavedGeometry: ( element: IBatchableElement, attributeBuffer: ViewableBuffer, indexBuffer: Uint16Array, aIndex: number, iIndex: number) => void;
Takes the four batching parameters of
element
, interleaves and pushes them into the batching attribute/index buffers given.It uses these properties:
vertexData
uvs
,textureId
andindicies
. It also uses the "tint" of the base-texture, if present.Parameter element
element being rendered
Parameter attributeBuffer
attribute buffer.
Parameter indexBuffer
index buffer
Parameter aIndex
number of floats already in the attribute buffer
Parameter iIndex
number of indices already in
indexBuffer
method render
render: (element: IBatchableElement) => void;
Buffers the "batchable" object. It need not be rendered immediately.
Parameter element
the element to render when using this renderer
method start
start: () => void;
Starts a new sprite batch.
method stop
stop: () => void;
Stops and flushes the current batch.
method updateGeometry
updateGeometry: () => void;
class AbstractMultiResource
abstract class AbstractMultiResource extends Resource {}
Resource that can manage several resource (items) inside. All resources need to have the same pixel size. Parent class for CubeResource and ArrayResource
PIXI
constructor
constructor(length: number, options?: ISize);
Parameter length
Parameter options
Options to for Resource constructor
Parameter
{number} [options.width] - Width of the resource
Parameter
{number} [options.height] - Height of the resource
property baseTexture
baseTexture: BaseTexture<Resource, any>;
Bound baseTexture, there can only be one.
property itemDirtyIds
itemDirtyIds: number[];
Dirty IDs for each part.
Modifiers
@readonly
property items
items: BaseTexture<Resource, any>[];
Collection of partial baseTextures that correspond to resources.
Modifiers
@readonly
property length
readonly length: number;
Number of elements in array.
method addBaseTextureAt
abstract addBaseTextureAt: (baseTexture: BaseTexture, index: number) => this;
Set a baseTexture by ID
Parameter baseTexture
Parameter index
Zero-based index of resource to set - Instance for chaining
method addResourceAt
addResourceAt: (resource: Resource, index: number) => this;
Set a resource by ID
Parameter resource
Parameter index
Zero-based index of resource to set - Instance for chaining
method bind
bind: (baseTexture: BaseTexture) => void;
Set the parent base texture.
method dispose
dispose: () => void;
Destroy this BaseImageResource.
method initFromArray
protected initFromArray: ( resources: Array<any>, options?: IAutoDetectOptions) => void;
Used from ArrayResource and CubeResource constructors.
Parameter resources
Can be resources, image elements, canvas, etc. , length should be same as constructor length
Parameter options
Detect options for resources
method load
load: () => Promise<this>;
Load all the resources simultaneously
- When load is resolved
method unbind
unbind: (baseTexture: BaseTexture) => void;
Unset the parent base texture.
class AbstractRenderer
abstract class AbstractRenderer extends EventEmitter {}
The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the PIXI.CanvasRenderer and PIXI.Renderer which can be used for rendering a PixiJS scene.
PIXI.utils.EventEmitter PIXI
constructor
constructor(type?: RENDERER_TYPE, options?: IRendererOptions);
Parameter system
The name of the system this renderer is for.
Parameter options
The optional renderer parameters.
Parameter
{number} [options.width=800] - The width of the screen.
Parameter
{number} [options.height=600] - The height of the screen.
Parameter
{HTMLCanvasElement} [options.view] - The canvas to use as a view, optional.
Parameter
{boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context
alpha
property. If you want to set transparency, please usebackgroundAlpha
. This option is for cases where the canvas needs to be opaque, possibly for performance reasons on some older devices.Parameter
{boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for resolutions other than 1.
Parameter
{boolean} [options.antialias=false] - Sets antialias
Parameter
{number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
Parameter
{boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you need to call toDataUrl on the WebGL context.
Parameter
{boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or not before the new render pass.
Parameter
{number} [options.backgroundColor=0x000000] - The background color of the rendered area (shown if not transparent).
Parameter
{number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
property autoDensity
readonly autoDensity: boolean;
property backgroundAlpha
backgroundAlpha: number;
The background color alpha. Setting this to 0 will make the canvas transparent.
{number}
property backgroundColor
backgroundColor: number;
The background color to fill if not transparent
{number}
property clearBeforeRender
clearBeforeRender?: boolean;
property height
readonly height: number;
Same as view.height, actual number of pixels in the canvas by vertical.
{number}
600
Modifiers
@readonly
property options
readonly options: IRendererOptions;
property plugins
readonly plugins: IRendererPlugins;
property preserveDrawingBuffer
readonly preserveDrawingBuffer: boolean;
property resolution
resolution: number;
property screen
readonly screen: Rectangle;
property type
readonly type: RENDERER_TYPE;
property useContextAlpha
readonly useContextAlpha: boolean | 'notMultiplied';
property view
readonly view: HTMLCanvasElement;
property width
readonly width: number;
Same as view.width, actual number of pixels in the canvas by horizontal.
{number}
800
Modifiers
@readonly
method addSystem
abstract addSystem: (ClassRef: ISystemConstructor, name: string) => this;
Adds a new system to the renderer.
Parameter ClassRef
Class reference
Parameter name
Property name for system Return instance of renderer
method destroy
destroy: (removeView?: boolean) => void;
Removes everything from the renderer and optionally removes the Canvas DOM element.
Parameter removeView
Removes the Canvas element from the DOM.
method generateTexture
generateTexture: { ( displayObject: IRenderableObject, options?: IGenerateTextureOptions ): RenderTexture; ( displayObject: IRenderableObject, scaleMode?: SCALE_MODES, resolution?: number, region?: Rectangle ): RenderTexture;};
Useful function that returns a texture of the display object that can then be used to create sprites This can be quite useful if your displayObject is complicated and needs to be reused multiple times. PIXI.AbstractRenderer#generateTexture
Parameter displayObject
The displayObject the object will be generated from.
Parameter options
Generate texture options.
Parameter
{PIXI.SCALE_MODES} options.scaleMode - The scale mode of the texture.
Parameter
{number} options.resolution - The resolution / device pixel ratio of the texture being generated.
Parameter
{PIXI.Rectangle} options.region - The region of the displayObject, that shall be rendered, if no region is specified, defaults to the local bounds of the displayObject.
Parameter
{PIXI.MSAA_QUALITY} options.multisample - The number of samples of the frame buffer. A texture of the graphics object.
Please use the options argument instead.
PIXI.AbstractRenderer#generateTexture
Parameter displayObject
The displayObject the object will be generated from.
Parameter scaleMode
The scale mode of the texture.
Parameter resolution
The resolution / device pixel ratio of the texture being generated.
Parameter region
The region of the displayObject, that shall be rendered, if no region is specified, defaults to the local bounds of the displayObject. A texture of the graphics object.
Deprecated
Since 6.1.0
method initPlugins
initPlugins: (staticMap: IRendererPlugins) => void;
Initialize the plugins.
Parameter staticMap
The dictionary of statically saved plugins.
method render
abstract render: ( displayObject: IRenderableObject, options?: IRendererRenderOptions) => void;
method resize
resize: (desiredScreenWidth: number, desiredScreenHeight: number) => void;
Resizes the screen and canvas as close as possible to the specified width and height. Canvas dimensions are multiplied by resolution and rounded to the nearest integers. The new canvas dimensions divided by the resolution become the new screen dimensions.
Parameter desiredScreenWidth
The desired width of the screen.
Parameter desiredScreenHeight
The desired height of the screen.
class ArrayResource
class ArrayResource extends AbstractMultiResource {}
A resource that contains a number of sources.
PIXI
constructor
constructor(source: number | any[], options?: ISize);
Parameter source
Number of items in array or the collection of image URLs to use. Can also be resources, image elements, canvas, etc.
Parameter options
Options to apply to PIXI.autoDetectResource
Parameter
{number} [options.width] - Width of the resource
Parameter
{number} [options.height] - Height of the resource
method addBaseTextureAt
addBaseTextureAt: (baseTexture: BaseTexture, index: number) => this;
Set a baseTexture by ID, ArrayResource just takes resource from it, nothing more
Parameter baseTexture
Parameter index
Zero-based index of resource to set - Instance for chaining
method bind
bind: (baseTexture: BaseTexture) => void;
Add binding
method upload
upload: ( renderer: Renderer, texture: BaseTexture, glTexture: GLTexture) => boolean;
Upload the resources to the GPU.
Parameter renderer
Parameter texture
Parameter glTexture
Returns
- whether texture was uploaded
class Attribute
class Attribute {}
Holds the information for a single attribute structure required to render geometry.
This does not contain the actual data, but instead has a buffer id that maps to a PIXI.Buffer This can include anything from positions, uvs, normals, colors etc.
PIXI
constructor
constructor( buffer: number, size?: number, normalized?: boolean, type?: TYPES, stride?: number, start?: number, instance?: boolean);
Parameter buffer
the id of the buffer that this attribute will look for
Parameter size
the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2.
Parameter normalized
should the data be normalized.
Parameter type
what type of number is the attribute. Check PIXI.TYPES to see the ones available
Parameter stride
How far apart, in bytes, the start of each value is. (used for interleaving data)
Parameter start
How far into the array to start reading values (used for interleaving data)
Parameter instance
Whether the geometry is instanced.
property buffer
buffer: number;
property instance
instance: boolean;
property normalized
normalized: boolean;
property size
size: number;
property start
start: number;
property stride
stride: number;
property type
type: TYPES;
method destroy
destroy: () => void;
Destroys the Attribute.
method from
static from: ( buffer: number, size?: number, normalized?: boolean, type?: TYPES, stride?: number) => Attribute;
Helper function that creates an Attribute based on the information provided
Parameter buffer
the id of the buffer that this attribute will look for
Parameter size
the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
Parameter normalized
should the data be normalized.
Parameter type
what type of number is the attribute. Check PIXI.TYPES to see the ones available
Parameter stride
How far apart, in bytes, the start of each value is. (used for interleaving data)
Returns
- A new PIXI.Attribute based on the information provided
class BaseImageResource
class BaseImageResource extends Resource {}
Base for all the image/canvas resources.
PIXI
constructor
constructor(source: ImageSource);
Parameter source
property noSubImage
noSubImage: boolean;
If set to
true
, will forcetexImage2D
overtexSubImage2D
for uploading. Certain types of media (e.g. video) usingtexImage2D
is more performant.false
property source
source: ImageSource;
The source element.
{HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement}
Modifiers
@readonly
method crossOrigin
static crossOrigin: ( element: HTMLImageElement | HTMLVideoElement, url: string, crossorigin?: boolean | string) => void;
Set cross origin based detecting the url and the crossorigin
Parameter element
Element to apply crossOrigin
Parameter url
URL to check
Parameter crossorigin
Cross origin value to use
method dispose
dispose: () => void;
Destroy this BaseImageResource
method update
update: () => void;
Checks if source width/height was changed, resize can cause extra baseTexture update. Triggers one update in any case.
method upload
upload: ( renderer: Renderer, baseTexture: BaseTexture, glTexture: GLTexture, source?: ImageSource) => boolean;
Upload the texture to the GPU.
Parameter renderer
Upload to the renderer
Parameter baseTexture
Reference to parent texture
Parameter glTexture
Parameter source
(optional)
Returns
- true is success
class BaseRenderTexture
class BaseRenderTexture extends BaseTexture {}
A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
__Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded otherwise black rectangles will be drawn instead.
A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example:
let renderer = PIXI.autoDetectRenderer();let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 });let renderTexture = new PIXI.RenderTexture(baseRenderTexture);let sprite = PIXI.Sprite.from("spinObj_01.png");sprite.position.x = 800/2;sprite.position.y = 600/2;sprite.anchor.x = 0.5;sprite.anchor.y = 0.5;renderer.render(sprite, {renderTexture});The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 you can clear the transform
sprite.setTransform()let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 });let renderTexture = new PIXI.RenderTexture(baseRenderTexture);renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexturePIXI
constructor
constructor(options?: IBaseTextureOptions<any>);
Parameter options
Parameter
{number} [options.width=100] - The width of the base render texture.
Parameter
{number} [options.height=100] - The height of the base render texture.
Parameter
{PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See PIXI.SCALE_MODES for possible values.
Parameter
{number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the texture being generated.
Parameter
{PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer.
property clearColor
clearColor: number[];
property filterStack
filterStack: any[];
The data structure for the filters.
property framebuffer
framebuffer: Framebuffer;
property maskStack
maskStack: MaskData[];
The data structure for the stencil masks.
method destroy
destroy: () => void;
Destroys this texture.
method dispose
dispose: () => void;
Frees the texture and framebuffer from WebGL memory without destroying this texture object. This means you can still use the texture later which will upload it to GPU memory again.
PIXI.BaseTexture#dispose
method resize
resize: (desiredWidth: number, desiredHeight: number) => void;
Resizes the BaseRenderTexture.
Parameter desiredWidth
The desired width to resize to.
Parameter desiredHeight
The desired height to resize to.
class BaseTexture
class BaseTexture< R extends Resource = Resource, RO = IAutoDetectOptions> extends EventEmitter {}
A Texture stores the information that represents an image. All textures have a base texture, which contains information about the source. Therefore you can have many textures all using a single BaseTexture
PIXI
constructor
constructor(resource?: any, options?: IBaseTextureOptions<RO>);
Parameter resource
The current resource to use, for things that aren't Resource objects, will be converted into a Resource.
Parameter options
Collection of options
Parameter
{PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture
Parameter
{number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture
Parameter
{PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures
Parameter
{PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest
Parameter
{PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type
Parameter
{PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type
Parameter
{PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target
Parameter
{PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha
Parameter
{number} [options.width=0] - Width of the texture
Parameter
{number} [options.height=0] - Height of the texture
Parameter
{number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture
Parameter
{object} [options.resourceOptions] - Optional resource options, see
property alphaMode
alphaMode?: ALPHA_MODES;
How to treat premultiplied alpha, see PIXI.ALPHA_MODES.
{PIXI.ALPHA_MODES} PIXI.ALPHA_MODES.UNPACK
property anisotropicLevel
anisotropicLevel?: number;
Anisotropic filtering level of texture
{number} PIXI.settings.ANISOTROPIC_LEVEL
property cacheId
cacheId: string;
Currently default cache ID.
{string}
property destroyed
destroyed: boolean;
Flag if BaseTexture has been destroyed.
{boolean}
Modifiers
@readonly
property dirtyId
dirtyId: number;
Used by TextureSystem to only update texture to the GPU when needed. Please call
update()
to increment it.Modifiers
@readonly
property dirtyStyleId
dirtyStyleId: number;
Used by TextureSystem to only update texture style when needed.
property format
format?: FORMATS;
The pixel format of the texture
PIXI.FORMATS.RGBA
property height
height: number;
The height of the base texture set when the image has loaded
Modifiers
@readonly
property isPowerOfTwo
isPowerOfTwo: boolean;
Whether or not the texture is a power of two, try to use power of two textures as much as you can
false
Modifiers
@readonly
property mipmap
mipmap: MIPMAP_MODES;
Mipmap mode of the texture, affects downscaled images
PIXI.settings.MIPMAP_TEXTURES
property parentTextureArray
parentTextureArray: BaseTexture<Resource, any>;
Whether its a part of another texture, handled by ArrayResource or CubeResource
{PIXI.BaseTexture}
property realHeight
readonly realHeight: number;
Pixel height of the source of this texture
Modifiers
@readonly
property realWidth
readonly realWidth: number;
Pixel width of the source of this texture
Modifiers
@readonly
property resolution
resolution: number;
The resolution / device pixel ratio of the texture
PIXI.settings.RESOLUTION
Modifiers
@readonly
property resource
resource: Resource;
The resource used by this BaseTexture, there can only be one resource per BaseTexture, but textures can share resources.
{PIXI.Resource}
Modifiers
@readonly
property scaleMode
scaleMode: SCALE_MODES;
The scale mode to apply when scaling this texture
PIXI.settings.SCALE_MODE
property target
target?: TARGETS;
The target type
PIXI.TARGETS.TEXTURE_2D
property textureCacheIds
textureCacheIds: string[];
The collection of alternative cache ids, since some BaseTextures can have more than one ID, short name and longer full URL
{Array}
Modifiers
@readonly
property touched
touched: number;
Used by automatic texture Garbage Collection, stores last GC tick when it was bound
property type
type?: TYPES;
The type of resource data
PIXI.TYPES.UNSIGNED_BYTE
property uid
readonly uid: number;
Global unique identifier for this BaseTexture
property valid
valid: boolean;
Generally speaking means when resource is loaded.
{boolean}
Modifiers
@readonly
property width
width: number;
The width of the base texture set when the image has loaded
Modifiers
@readonly
property wrapMode
wrapMode: WRAP_MODES;
How the texture wraps
PIXI.settings.WRAP_MODE
method addToCache
static addToCache: (baseTexture: BaseTexture, id: string) => void;
Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
Parameter baseTexture
The BaseTexture to add to the cache.
Parameter id
The id that the BaseTexture will be stored against.
method castToBaseTexture
castToBaseTexture: () => BaseTexture;
Utility function for BaseTexture|Texture cast.
method destroy
destroy: () => void;
Destroys this base texture. The method stops if resource doesn't want this texture to be destroyed. Removes texture from all caches.
method dispose
dispose: () => void;
Frees the texture from WebGL memory without destroying this texture object. This means you can still use the texture later which will upload it to GPU memory again.
PIXI.BaseTexture#dispose
method from
static from: <R extends Resource = Resource, RO = any>( source: ImageSource | string, options?: IBaseTextureOptions<RO>, strict?: boolean) => BaseTexture<R>;
Helper function that creates a base texture based on the source you provide. The source can be - image url, image element, canvas element. If the source is an image url or an image element and not in the base texture cache, it will be created and loaded.
Parameter source
The source to create base texture from.
Parameter options
See PIXI.BaseTexture's constructor for options.
Parameter
{string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
Parameter strict
Enforce strict-mode, see PIXI.settings.STRICT_TEXTURE_CACHE.
Returns
{PIXI.BaseTexture} The new base texture.
method fromBuffer
static fromBuffer: ( buffer: Float32Array | Uint8Array, width: number, height: number, options?: IBaseTextureOptions) => BaseTexture<BufferResource>;
Create a new BaseTexture with a BufferResource from a Float32Array. RGBA values are floats from 0 to 1.
Parameter buffer
The optional array to use, if no data is provided, a new Float32Array is created.
Parameter width
Width of the resource
Parameter height
Height of the resource
Parameter options
See PIXI.BaseTexture's constructor for options. - The resulting new BaseTexture
method onError
onError: (event: ErrorEvent) => void;
Handle errors with resources.
Parameter event
Error event emitted.
method removeFromCache
static removeFromCache: ( baseTexture: string | BaseTexture) => BaseTexture | null;
Remove a BaseTexture from the global BaseTextureCache.
Parameter baseTexture
id of a BaseTexture to be removed, or a BaseTexture instance itself. {PIXI.BaseTexture|null} The BaseTexture that was removed.
method setRealSize
setRealSize: ( realWidth: number, realHeight: number, resolution?: number) => this;
Sets real size of baseTexture, preserves current resolution.
Parameter realWidth
Full rendered width
Parameter realHeight
Full rendered height
Parameter resolution
Optionally set resolution
Returns
- this
method setResolution
setResolution: (resolution: number) => this;
Changes resolution
Parameter resolution
res
Returns
- this
method setResource
setResource: (resource: R) => this;
Sets the resource if it wasn't set. Throws error if resource already present
Parameter resource
that is managing this BaseTexture
Returns
- this
method setSize
setSize: ( desiredWidth: number, desiredHeight: number, resolution?: number) => this;
Changes w/h/resolution. Texture becomes valid if width and height are greater than zero.
Parameter desiredWidth
Desired visual width
Parameter desiredHeight
Desired visual height
Parameter resolution
Optionally set resolution
Returns
- this
method setStyle
setStyle: (scaleMode?: SCALE_MODES, mipmap?: MIPMAP_MODES) => this;
Changes style options of BaseTexture
Parameter scaleMode
Pixi scalemode
Parameter mipmap
enable mipmaps
Returns
- this
method update
update: () => void;
Invalidates the object. Texture becomes valid if width and height are greater than zero.
class BatchDrawCall
class BatchDrawCall {}
Used by the batcher to draw batches. Each one of these contains all information required to draw a bound geometry.
PIXI
class BatchGeometry
class BatchGeometry extends Geometry {}
Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects).
PIXI
constructor
constructor(_static?: boolean);
Parameter _static
Optimization flag, where
false
is updated every frame,true
doesn't change frame-to-frame.
class BatchPluginFactory
class BatchPluginFactory {}
PIXI
property defaultFragmentTemplate
static readonly defaultFragmentTemplate: string;
The default fragment shader source
Modifiers
@readonly
property defaultVertexSrc
static readonly defaultVertexSrc: string;
The default vertex shader source
Modifiers
@readonly
method create
static create: (options?: IBatchFactoryOptions) => typeof AbstractBatchRenderer;
Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way to extend BatchRenderer with all the necessary pieces.
Parameter options
Parameter
{string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source
Parameter
{string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template
Parameter
{number} [options.vertexSize=6] - Vertex size
Parameter
{object} [options.geometryClass=PIXI.BatchGeometry] {*} New batch renderer plugin
Example 1
const fragment = ` varying vec2 vTextureCoord; varying vec4 vColor; varying float vTextureId; uniform sampler2D uSamplers[%count%];
void main(void){ vec4 color; %forloop% gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); } `; const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); PIXI.Renderer.registerPlugin('invert', InvertBatchRenderer); const sprite = new PIXI.Sprite(); sprite.pluginName = 'invert';
class BatchShaderGenerator
class BatchShaderGenerator {}
Helper that generates batching multi-texture shader. Use it with your new BatchRenderer
PIXI
constructor
constructor(vertexSrc: string, fragTemplate: string);
Parameter vertexSrc
Vertex shader
Parameter fragTemplate
Fragment shader template
property defaultGroupCache
defaultGroupCache: { [key: number]: UniformGroup<Dict<any>> };
property fragTemplate
fragTemplate: string;
Reference to the fragment shader template. Must contain "%count%" and "%forloop%".
property programCache
programCache: { [key: number]: Program };
property vertexSrc
vertexSrc: string;
Reference to the vertex shader source.
method generateSampleSrc
generateSampleSrc: (maxTextures: number) => string;
method generateShader
generateShader: (maxTextures: number) => Shader;
class BatchSystem
class BatchSystem implements ISystem {}
System plugin to the renderer to manage batching.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property currentRenderer
currentRenderer: ObjectRenderer;
The currently active ObjectRenderer.
property emptyRenderer
readonly emptyRenderer: ObjectRenderer;
An empty renderer.
method boundArray
boundArray: ( texArray: BatchTextureArray, boundTextures: Array<BaseTexture>, batchId: number, maxTextures: number) => void;
Assigns batch locations to textures in array based on boundTextures state. All textures in texArray should have
_batchEnabled = _batchId
, and their count should be less thanmaxTextures
.Parameter texArray
textures to bound
Parameter boundTextures
current state of bound textures
Parameter batchId
marker for _batchEnabled param of textures in texArray
Parameter maxTextures
number of texture locations to manipulate
method copyBoundTextures
copyBoundTextures: (arr: BaseTexture[], maxTextures: number) => void;
Handy function for batch renderers: copies bound textures in first maxTextures locations to array sets actual _batchLocation for them
Parameter arr
arr copy destination
Parameter maxTextures
number of copied elements
method destroy
destroy: () => void;
method flush
flush: () => void;
This should be called if you wish to do some custom rendering It will basically render anything that may be batched up such as sprites
method reset
reset: () => void;
Reset the system to an empty renderer
method setObjectRenderer
setObjectRenderer: (objectRenderer: ObjectRenderer) => void;
Changes the current renderer to the one given in parameter
Parameter objectRenderer
The object renderer to use.
class BatchTextureArray
class BatchTextureArray {}
Used by the batcher to build texture batches. Holds list of textures and their respective locations.
PIXI
constructor
constructor();
property count
count: number;
Number of filled elements.
property elements
elements: BaseTexture_2[];
Inside textures array.
property ids
ids: number[];
Respective locations for textures.
method clear
clear: () => void;
class Buffer
class Buffer_2 {}
A wrapper for data so that it can be used and uploaded by WebGL
PIXI
constructor
constructor(data?: IArrayBuffer, _static?: boolean, index?: boolean);
Parameter data
the data to store in the buffer.
Parameter _static
true
for static bufferParameter index
true
for index buffer
property data
data: ITypedArray;
The data in the buffer, as a typed array
{ArrayBuffer| SharedArrayBuffer | ArrayBufferView}
property disposeRunner
disposeRunner: Runner;
property id
id: number;
property index
index: boolean;
property static
static: boolean;
property type
type: BUFFER_TYPE;
The type of buffer this is, one of: + ELEMENT_ARRAY_BUFFER - used as an index buffer + ARRAY_BUFFER - used as an attribute buffer + UNIFORM_BUFFER - used as a uniform buffer (if available)
method destroy
destroy: () => void;
Destroys the buffer.
method dispose
dispose: () => void;
Disposes WebGL resources that are connected to this geometry.
method from
static from: (data: IArrayBuffer | number[]) => Buffer_2;
Helper function that creates a buffer based on an array or TypedArray
Parameter data
the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. - A new Buffer based on the data provided.
method update
update: (data?: IArrayBuffer | Array<number>) => void;
Flags this buffer as requiring an upload to the GPU.
Parameter data
the data to update in the buffer.
class BufferResource
class BufferResource extends Resource {}
Buffer resource with data of typed array.
PIXI
constructor
constructor( source: Uint16Array | Float32Array | Uint8Array | Int32Array | Uint32Array, options: ISize);
Parameter source
Source buffer
Parameter options
Options
Parameter
{number} options.width - Width of the texture
Parameter
{number} options.height - Height of the texture
property data
data: Uint16Array | Float32Array | Uint8Array | Int32Array | Uint32Array;
Source array Cannot be because it cant be uploaded to WebGL
method dispose
dispose: () => void;
Destroy and don't use after this.
method test
static test: ( source: unknown) => source is Float32Array | Uint8Array | Uint32Array;
Used to auto-detect the type of resource.
Parameter source
The source object {boolean}
true
if
method upload
upload: ( renderer: Renderer, baseTexture: BaseTexture, glTexture: GLTexture) => boolean;
Upload the texture to the GPU.
Parameter renderer
Upload to the renderer
Parameter baseTexture
Reference to parent texture
Parameter glTexture
glTexture
Returns
- true is success
class CanvasResource
class CanvasResource extends BaseImageResource {}
Resource type for HTMLCanvasElement.
PIXI
constructor
constructor(source: HTMLCanvasElement);
Parameter source
Canvas element to use
method test
static test: (source: unknown) => source is any;
Used to auto-detect the type of resource.
Parameter source
The source object {boolean}
true
if source is HTMLCanvasElement or OffscreenCanvas
class ContextSystem
class ContextSystem implements ISystem {}
System plugin to the renderer to manage the context.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property CONTEXT_UID
protected CONTEXT_UID: number;
property extensions
extensions: WebGLExtensions;
Extensions available.
{object}
{WEBGL_draw_buffers} drawBuffers - WebGL v1 extension {WEBGL_depth_texture} depthTexture - WebGL v1 extension {OES_texture_float} floatTexture - WebGL v1 extension {WEBGL_lose_context} loseContext - WebGL v1 extension {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension
Modifiers
@readonly
property gl
protected gl: IRenderingContext;
property isLost
readonly isLost: boolean;
true
if the context is lostModifiers
@readonly
property supports
readonly supports: ISupportDict;
Features supported by current context.
{object}
{boolean} uint32Indices - Support for 32-bit indices buffer.
Modifiers
@readonly
property webGLVersion
webGLVersion: number;
Either 1 or 2 to reflect the WebGL version being used.
Modifiers
@readonly
method contextChange
protected contextChange: (gl: IRenderingContext) => void;
Handles the context change event.
Parameter gl
New WebGL context.
method createContext
createContext: ( canvas: HTMLCanvasElement, options: WebGLContextAttributes) => IRenderingContext;
Helper class to create a WebGL Context
Parameter canvas
the canvas element that we will get the context from
Parameter options
An options object that gets passed in to the canvas element containing the context attributes
See Also
https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext {WebGLRenderingContext} the WebGL context
method destroy
destroy: () => void;
method getExtensions
protected getExtensions: () => void;
Auto-populate the .
method handleContextLost
protected handleContextLost: (event: WebGLContextEvent) => void;
Handles a lost webgl context
Parameter event
The context lost event.
method handleContextRestored
protected handleContextRestored: () => void;
Handles a restored webgl context.
method initFromContext
initFromContext: (gl: IRenderingContext) => void;
Initializes the context.
Parameter gl
WebGL context
method initFromOptions
initFromOptions: (options: WebGLContextAttributes) => void;
Initialize from context options
Parameter options
context attributes
See Also
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
method postrender
protected postrender: () => void;
Handle the post-render runner event.
method validateContext
protected validateContext: (gl: IRenderingContext) => void;
Validate context.
Parameter gl
Render context.
class CubeResource
class CubeResource extends AbstractMultiResource {}
Resource for a CubeTexture which contains six resources.
PIXI
constructor
constructor( source?: ArrayFixed<string | Resource, 6>, options?: ICubeResourceOptions);
Parameter source
Collection of URLs or resources to use as the sides of the cube.
Parameter options
ImageResource options
Parameter
{number} [options.width] - Width of resource
Parameter
{number} [options.height] - Height of resource
Parameter
{number} [options.autoLoad=true] - Whether to auto-load resources
Parameter
{number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, whether to copy them or use
property items
items: ArrayFixed<BaseTexture<Resource, any>, 6>;
property linkBaseTexture
linkBaseTexture: boolean;
In case BaseTextures are supplied, whether to use same resource or bind baseTexture itself.
property SIDES
static SIDES: number;
Number of texture sides to store for CubeResources.
method addBaseTextureAt
addBaseTextureAt: ( baseTexture: BaseTexture, index: number, linkBaseTexture?: boolean) => this;
method bind
bind: (baseTexture: BaseTexture) => void;
Add binding.
Parameter baseTexture
parent base texture
method test
static test: (source: unknown) => source is ArrayFixed<string | Resource, 6>;
Used to auto-detect the type of resource.
Parameter source
The source object {boolean}
true
if source is an array of 6 elements
method upload
upload: ( renderer: Renderer, _baseTexture: BaseTexture, glTexture: GLTexture) => boolean;
Upload the resource
Returns
{boolean} true is success
class Filter
class Filter extends Shader {}
A filter is a special shader that applies post-processing effects to an input texture and writes into an output render-target.
of the .
### Usage Filters can be applied to any DisplayObject or Container. PixiJS'
FilterSystem
renders the container into temporary Framebuffer, then filter renders it to the screen. Multiple filters can be added to thefilters
array property and stacked on each other.const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 });const container = new PIXI.Container();container.filters = [filter];### Previous Version Differences
In PixiJS **v3**, a filter was always applied to _whole screen_.
In PixiJS **v4**, a filter can be applied _only part of the screen_. Developers had to create a set of uniforms to deal with coordinates.
In PixiJS **v5** combines _both approaches_. Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, bringing those extra uniforms into account.
Also be aware that we have changed default vertex shader, please consult .
### Frames
The following table summarizes the coordinate spaces used in the filtering pipeline:
Coordinate Space Description Texture Coordinates The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along both axes. World Space A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space). Physical Pixels This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture coordinates by the dimensions of the texture.
### Built-in Uniforms
PixiJS viewport uses screen (CSS) coordinates,
(0, 0, renderer.screen.width, renderer.screen.height)
, andprojectionMatrix
uniform maps it to the gl viewport.**uSampler**
The most important uniform is the input texture that container was rendered into. _Important note: as with all Framebuffers in PixiJS, both input and output are premultiplied by alpha._
By default, input normalized coordinates are passed to fragment shader with
vTextureCoord
. Use it to sample the input.const fragment = `varying vec2 vTextureCoord;uniform sampler2D uSampler;void main(void){gl_FragColor = texture2D(uSampler, vTextureCoord);}`;const myFilter = new PIXI.Filter(null, fragment);This filter is just one uniform less than .
**outputFrame**
The
outputFrame
holds the rectangle where filter is applied in screen (CSS) coordinates. It's the same asrenderer.screen
for a fullscreen filter. Only a part ofoutputFrame.zw
size of temporary Framebuffer is used,(0, 0, outputFrame.width, outputFrame.height)
,Filters uses this quad to normalized (0-1) space, its passed into
aVertexPosition
attribute. To calculate vertex position in screen space using normalized (0-1) space:vec4 filterVertexPosition( void ){vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);}**inputSize**
Temporary framebuffer is different, it can be either the size of screen, either power-of-two. The
inputSize.xy
are size of temporary framebuffer that holds input. TheinputSize.zw
is inverted, it's a shortcut to evade division inside the shader.Set
inputSize.xy = outputFrame.zw
for a fullscreen filter.To calculate input normalized coordinate, you have to map it to filter normalized space. Multiply by
outputFrame.zw
to get input coordinate. Divide byinputSize.xy
to get input normalized coordinate.vec2 filterTextureCoord( void ){return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy}**resolution**
The
resolution
is the ratio of screen (CSS) pixels to real pixels.**inputPixel**
inputPixel.xy
is the size of framebuffer in real pixels, same asinputSize.xy * resolution
inputPixel.zw
is invertedinputPixel.xy
.It's handy for filters that use neighbour pixels, like .
**inputClamp**
If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. For displacements, coordinates has to be clamped.
The
inputClamp.xy
is left-top pixel center, you may ignore it, because we use left-top part of FramebufferinputClamp.zw
is bottom-right pixel center.vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw))OR
vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw))### Additional Information
Complete documentation on Filter usage is located in the .
Since PixiJS only had a handful of built-in filters, additional filters can be downloaded from the PixiJS Filters repository.
PIXI
constructor
constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: Dict<any>);
Parameter vertexSrc
The source of the vertex shader.
Parameter fragmentSrc
The source of the fragment shader.
Parameter uniforms
Custom uniforms to use to augment the built-in ones.
property autoFit
autoFit: boolean;
If enabled, PixiJS will fit the filter area into boundaries for better performance. Switch it off if it does not work for specific shader.
true
property blendMode
blendMode: BLEND_MODES;
Sets the blend mode of the filter.
PIXI.BLEND_MODES.NORMAL
property defaultFragmentSrc
static readonly defaultFragmentSrc: string;
The default fragment shader source
property defaultVertexSrc
static readonly defaultVertexSrc: string;
The default vertex shader source
property enabled
enabled: boolean;
If enabled is true the filter is applied, if false it will not.
property legacy
legacy: boolean;
Legacy filters use position and uvs from attributes (set by filter system)
Modifiers
@readonly
property multisample
multisample: MSAA_QUALITY;
The samples of the filter.
property padding
padding: number;
The padding of the filter. Some filters require extra space to breath such as a blur. Increasing this will add extra width and height to the bounds of the object that the filter is applied to.
property resolution
resolution: number;
The resolution of the filter. Setting this to be lower will lower the quality but increase the performance of the filter.
property SOURCE_KEY_MAP
static SOURCE_KEY_MAP: Dict<string>;
Used for caching shader IDs.
property state
state: State;
The WebGL state the filter requires to render.
method apply
apply: ( filterManager: FilterSystem, input: RenderTexture, output: RenderTexture, clearMode?: CLEAR_MODES, _currentState?: FilterState) => void;
Applies the filter
Parameter filterManager
The renderer to retrieve the filter from
Parameter input
The input render target.
Parameter output
The target to output to.
Parameter clearMode
Should the output be cleared before rendering to it.
Parameter currentState
It's current state of filter. There are some useful properties in the currentState : target, filters, sourceFrame, destinationFrame, renderTarget, resolution
class FilterState
class FilterState {}
System plugin to the renderer to manage filter states.
constructor
constructor();
property bindingDestinationFrame
bindingDestinationFrame: Rectangle;
Original render-target destination frame.
property bindingSourceFrame
bindingSourceFrame: Rectangle;
Original render-target source frame.
property destinationFrame
destinationFrame: Rectangle;
Destination frame.
property filters
filters: Filter[];
Collection of filters.
property legacy
legacy: boolean;
Compatibility with PixiJS v4 filters false
property multisample
multisample: MSAA_QUALITY;
Number of samples MSAA_QUALITY.NONE
property renderTexture
renderTexture: RenderTexture;
property resolution
resolution: number;
Resolution of filters 1
property sourceFrame
sourceFrame: Rectangle;
Source frame.
property target
target: IFilterTarget;
Target of the filters We store for case when custom filter wants to know the element it was applied on {PIXI.DisplayObject}
property transform
transform: Matrix;
Projection system transform saved by link.
method clear
clear: () => void;
Clears the state
class FilterSystem
class FilterSystem implements ISystem {}
System plugin to the renderer to manage filters.
## Pipeline
The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its [filters]PIXI.Filter in series, and the last filter outputs into the final render-target.
The filter-frame is the rectangle in world space being filtered, and those contents are mapped into
(0, 0, filterFrame.width, filterFrame.height)
into the filter render-texture. The filter-frame is also called the source-frame, as it is used to bind the filter render-textures. The last filter outputs to thefilterFrame
in the final render-target.## Usage
PIXI.Container#renderAdvanced is an example of how to use the filter system. It is a 3 step process:
* **push**: Use PIXI.FilterSystem#push to push the set of filters to be applied on a filter-target. * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents inside the bounds of the filter-target. NOTE: Using PIXI.Renderer#render is illegal during an existing render cycle, and it may reset the filter system. * **pop**: Use PIXI.FilterSystem#pop to pop & execute the filters you initially pushed. It will apply them serially and output to the bounds of the filter-target.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property activeState
protected activeState: FilterState;
Active state {object}
property defaultFilterStack
readonly defaultFilterStack: FilterState[];
List of filters for the FilterSystem {Object[]}
property forceClear
forceClear: boolean;
Whether to clear output renderTexture in AUTO/BLIT mode. See PIXI.CLEAR_MODES.
property globalUniforms
protected globalUniforms: UniformGroup<Dict<any>>;
This uniform group is attached to filter uniforms when used.
{PIXI.Rectangle} outputFrame {Float32Array} inputSize {Float32Array} inputPixel {Float32Array} inputClamp {Number} resolution {Float32Array} filterArea {Float32Array} filterClamp
property quad
protected quad: Quad;
A very simple geometry used when drawing a filter effect to the screen.
property quadUv
protected quadUv: QuadUv;
Quad UVs
property renderer
renderer: Renderer;
property statePool
statePool: FilterState[];
A pool for storing filter states, save us creating new ones each tick.
property texturePool
texturePool: RenderTexturePool;
Stores a bunch of POT textures used for filtering.
property useMaxPadding
useMaxPadding: boolean;
Old padding behavior is to use the max amount instead of sum padding. Use this flag if you need the old behavior. false
method applyFilter
applyFilter: ( filter: Filter, input: RenderTexture, output: RenderTexture, clearMode?: CLEAR_MODES) => void;
Draws a filter using the default rendering process.
This should be called only by Filter#apply.
Parameter filter
The filter to draw.
Parameter input
The input render target.
Parameter output
The target to output to.
Parameter clearMode
Should the output be cleared before rendering to it
method bindAndClear
bindAndClear: (filterTexture: RenderTexture, clearMode?: CLEAR_MODES) => void;
Binds a renderTexture with corresponding
filterFrame
, clears it if mode corresponds.Parameter filterTexture
renderTexture to bind, should belong to filter pool or filter stack
Parameter clearMode
clearMode, by default its CLEAR/YES. See PIXI.CLEAR_MODES
method calculateSpriteMatrix
calculateSpriteMatrix: ( outputMatrix: Matrix, sprite: ISpriteMaskTarget) => Matrix;
Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
Use
outputMatrix * vTextureCoord
in the shader.Parameter outputMatrix
The matrix to output to.
Parameter sprite
The sprite to map to. The mapped matrix.
method destroy
destroy: () => void;
Destroys this Filter System.
method emptyPool
emptyPool: () => void;
Empties the texture pool.
method getFilterTexture
getFilterTexture: ( input?: RenderTexture, resolution?: number, multisample?: MSAA_QUALITY) => RenderTexture;
Gets extra render texture to use inside current filter To be compliant with older filters, you can use params in any order
Parameter input
renderTexture from which size and resolution will be copied
Parameter resolution
override resolution of the renderTexture
Parameter multisample
number of samples of the renderTexture
method getOptimalFilterTexture
protected getOptimalFilterTexture: ( minWidth: number, minHeight: number, resolution?: number, multisample?: MSAA_QUALITY) => RenderTexture;
Gets a Power-of-Two render texture or fullScreen texture
Parameter minWidth
The minimum width of the render texture in real pixels.
Parameter minHeight
The minimum height of the render texture in real pixels.
Parameter resolution
The resolution of the render texture.
Parameter multisample
Number of samples of the render texture. - The new render texture.
method pop
pop: () => void;
Pops off the filter and applies it.
method push
push: (target: IFilterTarget, filters: Array<Filter>) => void;
Pushes a set of filters to be applied later to the system. This will redirect further rendering into an input render-texture for the rest of the filtering pipeline.
Parameter target
The target of the filter to render.
Parameter filters
The filters to apply.
method resize
resize: () => void;
Calls
texturePool.resize()
, affects fullScreen renderTextures.
method returnFilterTexture
returnFilterTexture: (renderTexture: RenderTexture) => void;
Frees a render texture back into the pool.
Parameter renderTexture
The renderTarget to free
class Framebuffer
class Framebuffer {}
A framebuffer can be used to render contents off of the screen. PIXI.BaseRenderTexture uses one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer.
On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES.
PIXI
constructor
constructor(width: number, height: number);
Parameter width
Width of the frame buffer
Parameter height
Height of the frame buffer
property colorTexture
readonly colorTexture: BaseTexture<Resource, any>;
Reference to the colorTexture.
Modifiers
@readonly
property colorTextures
colorTextures: BaseTexture<Resource, any>[];
property depth
depth: boolean;
property depthTexture
depthTexture: BaseTexture<Resource, any>;
property dirtyFormat
dirtyFormat: number;
property dirtyId
dirtyId: number;
property dirtySize
dirtySize: number;
property disposeRunner
disposeRunner: Runner;
property glFramebuffers
glFramebuffers: { [key: string]: GLFramebuffer };
property height
height: number;
Height of framebuffer in pixels.
property multisample
multisample: MSAA_QUALITY;
Desired number of samples for antialiasing. 0 means AA should not be used.
Experimental WebGL2 feature, allows to use antialiasing in individual renderTextures. Antialiasing is the same as for main buffer with renderer
antialias:true
options. Seriously affects GPU memory consumption and GPU performance.renderTexture.framebuffer.multisample = PIXI.MSAA_QUALITY.HIGH;//...renderer.render(myContainer, {renderTexture});renderer.framebuffer.blit(); // copies data from MSAA framebuffer to texturePIXI.MSAA_QUALITY.NONE
property stencil
stencil: boolean;
property width
width: number;
Width of framebuffer in pixels.
method addColorTexture
addColorTexture: (index?: number, texture?: BaseTexture) => this;
Add texture to the colorTexture array.
Parameter index
Index of the array to add the texture to
Parameter texture
Texture to add to the array
method addDepthTexture
addDepthTexture: (texture?: BaseTexture) => this;
Add a depth texture to the frame buffer.
Parameter texture
Texture to add.
method destroyDepthTexture
destroyDepthTexture: () => void;
Destroys and removes the depth texture added to this framebuffer.
method dispose
dispose: () => void;
Disposes WebGL resources that are connected to this geometry.
method enableDepth
enableDepth: () => this;
Enable depth on the frame buffer.
method enableStencil
enableStencil: () => this;
Enable stencil on the frame buffer.
method resize
resize: (width: number, height: number) => void;
Resize the frame buffer
Parameter width
Width of the frame buffer to resize to
Parameter height
Height of the frame buffer to resize to
class FramebufferSystem
class FramebufferSystem implements ISystem {}
System plugin to the renderer to manage framebuffers.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property CONTEXT_UID
protected CONTEXT_UID: number;
property current
current: Framebuffer;
property gl
protected gl: IRenderingContext;
property hasMRT
hasMRT: boolean;
property managedFramebuffers
readonly managedFramebuffers: Framebuffer[];
A list of managed framebuffers.
property msaaSamples
protected msaaSamples: number[];
property renderer
renderer: Renderer;
property size
readonly size: { x: number; y: number; width: number; height: number };
Get the size of the current width and height. Returns object with
width
andheight
values.Modifiers
@readonly
property unknownFramebuffer
protected unknownFramebuffer: Framebuffer;
Framebuffer value that shows that we don't know what is bound.
property viewport
viewport: Rectangle;
property writeDepthTexture
writeDepthTexture: boolean;
method bind
bind: (framebuffer?: Framebuffer, frame?: Rectangle, mipLevel?: number) => void;
Bind a framebuffer.
Parameter framebuffer
Parameter frame
frame, default is framebuffer size
Parameter mipLevel
optional mip level to set on the framebuffer - defaults to 0
method blit
blit: ( framebuffer?: Framebuffer, sourcePixels?: Rectangle, destPixels?: Rectangle) => void;
Only works with WebGL2
blits framebuffer to another of the same or bigger size after that target framebuffer is bound
Fails with WebGL warning if blits multisample framebuffer to different size
Parameter framebuffer
by default it blits "into itself", from renderBuffer to texture.
Parameter sourcePixels
source rectangle in pixels
Parameter destPixels
dest rectangle in pixels, assumed to be the same as sourcePixels
method canMultisampleFramebuffer
protected canMultisampleFramebuffer: (framebuffer: Framebuffer) => boolean;
Returns true if the frame buffer can be multisampled.
method clear
clear: (r: number, g: number, b: number, a: number, mask?: BUFFER_BITS) => void;
Clear the color of the context
Parameter r
Red value from 0 to 1
Parameter g
Green value from 0 to 1
Parameter b
Blue value from 0 to 1
Parameter a
Alpha value from 0 to 1
Parameter mask
Bitwise OR of masks that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
method contextChange
protected contextChange: () => void;
Sets up the renderer context and necessary buffers.
method destroy
destroy: () => void;
method detectSamples
protected detectSamples: (samples: MSAA_QUALITY) => MSAA_QUALITY;
Detects number of samples that is not more than a param but as close to it as possible
Parameter samples
number of samples
Returns
- recommended number of samples
method disposeAll
disposeAll: (contextLost?: boolean) => void;
Disposes all framebuffers, but not textures bound to them.
Parameter contextLost
If context was lost, we suppress all delete function calls
method disposeFramebuffer
disposeFramebuffer: (framebuffer: Framebuffer, contextLost?: boolean) => void;
Disposes framebuffer.
Parameter framebuffer
framebuffer that has to be disposed of
Parameter contextLost
If context was lost, we suppress all delete function calls
method forceStencil
forceStencil: () => void;
Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. Used by MaskSystem, when its time to use stencil mask for Graphics element.
Its an alternative for public lazy
framebuffer.enableStencil
, in case we need stencil without rebind.
method initFramebuffer
initFramebuffer: (framebuffer: Framebuffer) => GLFramebuffer;
Initialize framebuffer for this context
Parameter framebuffer
Returns
- created GLFramebuffer
method reset
reset: () => void;
Resets framebuffer stored state, binds screen framebuffer.
Should be called before renderTexture reset().
method resizeFramebuffer
resizeFramebuffer: (framebuffer: Framebuffer) => void;
Resize the framebuffer
method setViewport
setViewport: (x: number, y: number, width: number, height: number) => void;
Set the WebGLRenderingContext's viewport.
Parameter x
X position of viewport
Parameter y
Y position of viewport
Parameter width
Width of viewport
Parameter height
Height of viewport
method updateFramebuffer
updateFramebuffer: (framebuffer: Framebuffer, mipLevel: number) => void;
Update the framebuffer
class Geometry
class Geometry {}
The Geometry represents a model. It consists of two components: - GeometryStyle - The structure of the model such as the attributes layout - GeometryData - the data of the model - this consists of buffers. This can include anything from positions, uvs, normals, colors etc.
Geometry can be defined without passing in a style or data if required (thats how I prefer!)
let geometry = new PIXI.Geometry();geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2)geometry.addIndex([0,1,2,1,3,2])PIXI
constructor
constructor(buffers?: Buffer_2[], attributes?: { [key: string]: Attribute });
Parameter buffers
An array of buffers. optional.
Parameter attributes
Of the geometry, optional structure of the attributes layout
property attributes
attributes: { [key: string]: Attribute };
property buffers
buffers: Buffer_2[];
property disposeRunner
disposeRunner: Runner;
property glVertexArrayObjects
glVertexArrayObjects: { [key: number]: { [key: string]: WebGLVertexArrayObject };};
A map of renderer IDs to webgl VAOs
{object}
property id
id: number;
property indexBuffer
indexBuffer: Buffer_2;
property instanceCount
instanceCount: number;
Number of instances in this geometry, pass it to
GeometrySystem.draw()
.1
property instanced
instanced: boolean;
Whether the geometry is instanced.
property refCount
refCount: number;
Count of existing (not destroyed) meshes that reference this geometry.
method addAttribute
addAttribute: ( id: string, buffer: Buffer_2 | Float32Array | Uint32Array | Array<number>, size?: number, normalized?: boolean, type?: TYPES, stride?: number, start?: number, instance?: boolean) => this;
Adds an attribute to the geometry Note:
stride
andstart
should beundefined
if you dont know them, not 0!Parameter id
the name of the attribute (matching up to a shader)
Parameter buffer
the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it.
Parameter size
the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
Parameter normalized
should the data be normalized.
Parameter type
what type of number is the attribute. Check {PIXI.TYPES} to see the ones available
Parameter stride
How far apart, in bytes, the start of each value is. (used for interleaving data)
Parameter start
How far into the array to start reading values (used for interleaving data)
Parameter instance
Instancing flag - Returns self, useful for chaining.
method addIndex
addIndex: (buffer?: Buffer_2 | IArrayBuffer | number[]) => Geometry;
Adds an index buffer to the geometry The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer.
Parameter buffer
The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. - Returns self, useful for chaining.
method clone
clone: () => Geometry;
Returns a clone of the geometry.
Returns
- A new clone of this geometry.
method destroy
destroy: () => void;
Destroys the geometry.
method dispose
dispose: () => void;
Disposes WebGL resources that are connected to this geometry.
method getAttribute
getAttribute: (id: string) => Attribute;
Returns the requested attribute.
Parameter id
The name of the attribute required - The attribute requested.
method getBuffer
getBuffer: (id: string) => Buffer_2;
Returns the requested buffer.
Parameter id
The name of the buffer required. - The buffer requested.
method getIndex
getIndex: () => Buffer_2;
Returns the index buffer
- The index buffer.
method getSize
getSize: () => number;
Get the size of the geometries, in vertices.
method interleave
interleave: () => Geometry;
This function modifies the structure so that all current attributes become interleaved into a single buffer This can be useful if your model remains static as it offers a little performance boost
- Returns self, useful for chaining.
method merge
static merge: (geometries: Array<Geometry>) => Geometry;
Merges an array of geometries into a new single one.
Geometry attribute styles must match for this operation to work.
Parameter geometries
array of geometries to merge - Shiny new geometry!
class GeometrySystem
class GeometrySystem implements ISystem {}
System plugin to the renderer to manage geometry.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property canUseUInt32ElementIndex
canUseUInt32ElementIndex: boolean;
true
if supportgl.UNSIGNED_INT
ingl.drawElements
orgl.drawElementsInstanced
.Modifiers
@readonly
property CONTEXT_UID
protected CONTEXT_UID: number;
property gl
protected gl: IRenderingContext;
property hasInstance
hasInstance: boolean;
true
if hasANGLE_instanced_arrays
extension.Modifiers
@readonly
property hasVao
hasVao: boolean;
true
if we has*_vertex_array_object
extension.Modifiers
@readonly
property managedGeometries
readonly managedGeometries: { [key: number]: Geometry };
Cache for all geometries by id, used in case renderer gets destroyed or for profiling.
method activateVao
protected activateVao: (geometry: Geometry, program: Program) => void;
Activate vertex array object.
Parameter geometry
Geometry instance.
Parameter program
Shader program instance.
method bind
bind: (geometry?: Geometry, shader?: Shader) => void;
Binds geometry so that is can be drawn. Creating a Vao if required
Parameter geometry
Instance of geometry to bind.
Parameter shader
Instance of shader to use vao for.
method checkCompatibility
protected checkCompatibility: (geometry: Geometry, program: Program) => void;
Check compatibility between a geometry and a program
Parameter geometry
Geometry instance.
Parameter program
Program instance.
method contextChange
protected contextChange: () => void;
Sets up the renderer context and necessary buffers.
method destroy
destroy: () => void;
method disposeAll
disposeAll: (contextLost?: boolean) => void;
Dispose all WebGL resources of all managed geometries.
Parameter contextLost
If context was lost, we suppress
gl.delete
calls
method disposeGeometry
disposeGeometry: (geometry: Geometry, contextLost?: boolean) => void;
Disposes geometry.
Parameter geometry
Geometry with buffers. Only VAO will be disposed
Parameter contextLost
If context was lost, we suppress deleteVertexArray
method draw
draw: ( type: DRAW_MODES, size?: number, start?: number, instanceCount?: number) => this;
Draws the currently bound geometry.
Parameter type
The type primitive to render.
Parameter size
The number of elements to be rendered. If not specified, all vertices after the starting vertex will be drawn.
Parameter start
The starting vertex in the geometry to start drawing from. If not specified, drawing will start from the first vertex.
Parameter instanceCount
The number of instances of the set of elements to execute. If not specified, all instances will be drawn.
method getSignature
protected getSignature: (geometry: Geometry, program: Program) => string;
Takes a geometry and program and generates a unique signature for them.
Parameter geometry
To get signature from.
Parameter program
To test geometry against. - Unique signature of the geometry and program
method initGeometryVao
protected initGeometryVao: ( geometry: Geometry, shader: Shader, incRefCount?: boolean) => WebGLVertexArrayObject;
Creates or gets Vao with the same structure as the geometry and stores it on the geometry. If vao is created, it is bound automatically. We use a shader to infer what and how to set up the attribute locations.
Parameter geometry
Instance of geometry to to generate Vao for.
Parameter shader
Instance of the shader.
Parameter incRefCount
Increment refCount of all geometry buffers.
method reset
reset: () => void;
Reset and unbind any active VAO and geometry.
method unbind
protected unbind: () => void;
Unbind/reset everything.
method updateBuffers
updateBuffers: () => void;
Update buffers of the currently bound geometry.
class GLFramebuffer
class GLFramebuffer {}
Internal framebuffer for WebGL context.
PIXI
constructor
constructor(framebuffer: WebGLTexture);
property blitFramebuffer
blitFramebuffer: Framebuffer;
In case we use MSAA, this is actual framebuffer that has colorTextures[0] The contents of that framebuffer are read when we use that renderTexture in sprites
property dirtyFormat
dirtyFormat: number;
Latest known version of framebuffer format.
property dirtyId
dirtyId: number;
Latest known version of framebuffer.
property dirtySize
dirtySize: number;
Latest known version of framebuffer size.
property framebuffer
framebuffer: WebGLFramebuffer;
The WebGL framebuffer.
property mipLevel
mipLevel: number;
Store the current mipmap of the textures the framebuffer will write too.
property msaaBuffer
msaaBuffer: WebGLRenderbuffer;
In case MSAA, we use this Renderbuffer instead of colorTextures[0] when we write info.
property multisample
multisample: MSAA_QUALITY;
Detected AA samples number.
property stencil
stencil: WebGLRenderbuffer;
Stencil+depth , usually costs 32bits per pixel.
class GLProgram
class GLProgram {}
Helper class to create a WebGL Program
PIXI
constructor
constructor( program: WebGLProgram, uniformData: { [key: string]: IGLUniformData });
Makes a new Pixi program.
Parameter program
webgl program
Parameter uniformData
uniforms
property program
program: WebGLProgram;
The shader program.
property uniformBufferBindings
uniformBufferBindings: Dict<any>;
A hash that stores where UBOs are bound to on the program.
property uniformData
uniformData: Dict<any>;
Holds the uniform data which contains uniform locations and current uniform values used for caching and preventing unneeded GPU commands.
property uniformDirtyGroups
uniformDirtyGroups: Dict<any>;
A place where dirty ticks are stored for groups If a tick here does not match with the Higher level Programs tick, it means we should re upload the data.
property uniformGroups
uniformGroups: Dict<any>;
UniformGroups holds the various upload functions for the shader. Each uniform group and program have a unique upload function generated.
property uniformSync
uniformSync: Dict<any>;
A hash for lazily-generated uniform uploading functions.
method destroy
destroy: () => void;
Destroys this program.
class GLTexture
class GLTexture {}
Internal texture for WebGL context.
PIXI
constructor
constructor(texture: WebGLTexture);
property dirtyId
dirtyId: number;
Texture contents dirty flag.
property dirtyStyleId
dirtyStyleId: number;
Texture style dirty flag.
property height
height: number;
Height of texture that was used in texImage2D.
property internalFormat
internalFormat: number;
Type copied from baseTexture.
property mipmap
mipmap: boolean;
Whether mip levels has to be generated.
property samplerType
samplerType: number;
Type of sampler corresponding to this texture. See PIXI.SAMPLER_TYPES
property texture
texture: WebGLTexture;
The WebGL texture.
property type
type: number;
Type copied from baseTexture.
property width
width: number;
Width of texture that was used in texImage2D.
property wrapMode
wrapMode: number;
WrapMode copied from baseTexture.
class IGLUniformData
class IGLUniformData {}
class ImageBitmapResource
class ImageBitmapResource extends BaseImageResource {}
Resource type for ImageBitmap.
PIXI
constructor
constructor(source: ImageBitmap);
Parameter source
Image element to use
method test
static test: (source: unknown) => source is ImageBitmap;
Used to auto-detect the type of resource.
Parameter source
The source object {boolean}
true
if source is an ImageBitmap
class ImageResource
class ImageResource extends BaseImageResource {}
Resource type for HTMLImageElement.
PIXI
constructor
constructor(source: string | HTMLImageElement, options?: IImageResourceOptions);
Parameter source
image source or URL
Parameter options
Parameter
{boolean} [options.autoLoad=true] - start loading process
Parameter
{boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create a bitmap before upload
Parameter
{boolean} [options.crossorigin=true] - Load image using cross origin
Parameter
{PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap
property alphaMode
alphaMode: ALPHA_MODES;
Controls texture alphaMode field Copies from options Default is
null
, copies option from baseTextureModifiers
@readonly
property bitmap
bitmap: ImageBitmap;
The ImageBitmap element created for a .
null
property createBitmap
createBitmap: boolean;
If capable, convert the image using createImageBitmap API.
PIXI.settings.CREATE_IMAGE_BITMAP
property preserveBitmap
preserveBitmap: boolean;
If the image should be disposed after upload
false
property url
url: string;
URL of the image source
method dispose
dispose: () => void;
Destroys this resource.
method load
load: (createBitmap?: boolean) => Promise<ImageResource>;
Returns a promise when image will be loaded and processed.
Parameter createBitmap
whether process image into bitmap
method process
process: () => Promise<ImageResource>;
Called when we need to convert image into BitmapImage. Can be called multiple times, real promise is cached inside.
- Cached promise to fill that bitmap
method test
static test: (source: unknown) => source is string | HTMLImageElement;
Used to auto-detect the type of resource.
Parameter source
The source object {boolean}
true
if source is string or HTMLImageElement
method upload
upload: ( renderer: Renderer, baseTexture: BaseTexture, glTexture: GLTexture) => boolean;
Upload the image resource to GPU.
Parameter renderer
Renderer to upload to
Parameter baseTexture
BaseTexture for this resource
Parameter glTexture
GLTexture to use
Returns
{boolean} true is success
class MaskData
class MaskData {}
Component for masked elements.
Holds mask mode and temporary data about current mask.
PIXI
constructor
constructor(maskObject?: IMaskTarget);
Create MaskData
Parameter maskObject
object that describes the mask
property autoDetect
autoDetect: boolean;
Whether we know the mask type beforehand true
property enabled
enabled: boolean;
If enabled is true the mask is applied, if false it will not.
property filter
filter: ISpriteMaskFilter_2;
The sprite mask filter. If set to
null
, the default sprite mask filter is used. null
property isMaskData
isMaskData: boolean;
Indicator of the type (always true for MaskData objects)
property maskObject
maskObject: IMaskTarget;
Which element we use to mask {PIXI.DisplayObject}
property multisample
multisample: MSAA_QUALITY;
Number of samples of the sprite mask filter. If set to
null
, the sample count of the current render target is used. PIXI.settings.FILTER_MULTISAMPLE
property pooled
pooled: boolean;
Whether it belongs to MaskSystem pool
property resolution
resolution: number;
Resolution of the sprite mask filter. If set to
null
or0
, the resolution of the current render target is used. null
property type
type: MASK_TYPES;
Mask type
method copyCountersOrReset
copyCountersOrReset: (maskAbove?: MaskData) => void;
Copies counters from maskData above, called from pushMask().
method reset
reset: () => void;
Resets the mask data after popMask().
class MaskSystem
class MaskSystem implements ISystem {}
System plugin to the renderer to manage masks.
There are three built-in types of masking: * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular. * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks. * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins.
The best type of masking is auto-detected when you
push
one. To use scissor masking, you must pass in aGraphics
object with just a rectangle drawn.## Mask Stacks
In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask stack stores the currently applied masks in order. Each PIXI.BaseRenderTexture holds its own mask stack, i.e. when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property alphaMaskIndex
protected alphaMaskIndex: number;
Current index of alpha mask pool. 0
Modifiers
@readonly
property alphaMaskPool
protected readonly alphaMaskPool: SpriteMaskFilter[][];
Pool of used sprite mask filters.
property enableScissor
enableScissor: boolean;
Flag to enable scissor masking.
true
method destroy
destroy: () => void;
method detect
detect: (maskData: MaskData) => void;
Sets type of MaskData based on its maskObject.
method pop
pop: (target: IMaskTarget) => void;
Removes the last mask from the mask stack and doesn't return it.
NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed.
Parameter target
Display Object to pop the mask from
method popSpriteMask
popSpriteMask: (maskData: MaskData) => void;
Removes the last filter from the filter stack and doesn't return it.
Parameter maskData
Sprite to be used as the mask.
method push
push: (target: IMaskTarget, maskDataOrTarget: MaskData | IMaskTarget) => void;
Enables the mask and appends it to the current mask stack.
NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked.
Parameter target
Display Object to push the mask to
Parameter maskData
The masking data.
method pushSpriteMask
pushSpriteMask: (maskData: MaskData) => void;
Applies the Mask and adds it to the current filter stack.
Parameter maskData
Sprite to be used as the mask.
method setMaskStack
setMaskStack: (maskStack: Array<MaskData>) => void;
Changes the mask stack that is used by this System.
Parameter maskStack
The mask stack
class ObjectRenderer
class ObjectRenderer implements ISystem {}
Base for a common object renderer that can be used as a system renderer plugin.
PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this manager works for.
property renderer
protected renderer: Renderer;
The renderer this manager works for.
method destroy
destroy: () => void;
Generic destruction method that frees all resources. This should be called by subclasses.
method flush
flush: () => void;
Stub method that should be used to empty the current batch by rendering objects now.
method render
render: (_object: any) => void;
Keeps the object to render. It doesn't have to be rendered immediately.
Parameter object
The object to render.
method start
start: () => void;
Stub method that initializes any state required before rendering starts. It is different from the
prerender
signal, which occurs every frame, in that it is called whenever an object requests _this_ renderer specifically.
method stop
stop: () => void;
Stops the renderer. It should free up any state and become dormant.
class Program
class Program {}
Helper class to create a shader program.
PIXI
constructor
constructor(vertexSrc?: string, fragmentSrc?: string, name?: string);
Parameter vertexSrc
The source of the vertex shader.
Parameter fragmentSrc
The source of the fragment shader.
Parameter name
Name for shader
property attributeData
attributeData: { [key: string]: IAttributeData };
Assigned when a program is first bound to the shader system.
property defaultFragmentSrc
static readonly defaultFragmentSrc: string;
The default fragment shader source.
property defaultVertexSrc
static readonly defaultVertexSrc: string;
The default vertex shader source.
property fragmentSrc
fragmentSrc: string;
Source code for the fragment shader.
property glPrograms
glPrograms: { [key: number]: GLProgram };
property id
id: number;
property nameCache
nameCache: any;
property syncUniforms
syncUniforms: any;
property uniformData
uniformData: { [key: string]: IUniformData };
Assigned when a program is first bound to the shader system.
property vertexSrc
vertexSrc: string;
Source code for the vertex shader.
method from
static from: ( vertexSrc?: string, fragmentSrc?: string, name?: string) => Program;
A short hand function to create a program based of a vertex and fragment shader.
This method will also check to see if there is a cached program.
Parameter vertexSrc
The source of the vertex shader.
Parameter fragmentSrc
The source of the fragment shader.
Parameter name
Name for shader
Returns
A shiny new PixiJS shader program!
class ProjectionSystem
class ProjectionSystem implements ISystem {}
System plugin to the renderer to manage the projection matrix.
The
projectionMatrix
is a global uniform provided to all shaders. It is used to transform points in world space to normalized device coordinates.PIXI
constructor
constructor(renderer: Renderer);
Parameter renderer
The renderer this System works for.
property defaultFrame
defaultFrame: Rectangle;
Default destination frame
This is not used internally. It is not advised to use this feature specifically unless you know what you're doing. The
update
method will default to this frame if you do not pass the destination frame.Modifiers
@readonly
property destinationFrame
destinationFrame: Rectangle;
The destination frame used to calculate the current projection matrix.
The destination frame is the rectangle in the render-target into which contents are rendered. If rendering to the screen, the origin is on the top-left. If rendering to a framebuffer, the origin is on the bottom-left. This "flipping" phenomenon is because of WebGL convention for (shader) texture coordinates, where the bottom-left corner is (0,0). It allows display-objects to map their (0,0) position in local-space (top-left) to (0,0) in texture space (bottom-left). In other words, a sprite's top-left corner actually renders the texture's bottom-left corner. You will also notice this when using a tool like SpectorJS to view your textures at runtime.
The destination frame's dimensions (width,height) should be equal to the source frame. This is because, otherwise, the contents will be scaled to fill the destination frame. Similarly, the destination frame's (x,y) coordinates are (0,0) unless you know what you're doing.
Modifiers
@readonly
property projectionMatrix
projectionMatrix: Matrix;
Projection matrix
This matrix can be used to transform points from world space to normalized device coordinates, and is calculated from the sourceFrame → destinationFrame mapping provided.
The renderer's
globalUniforms
keeps a reference to this, and so it is available for all shaders to use as a uniform.Modifiers
@readonly
property sourceFrame
sourceFrame: Rectangle;
The source frame used to calculate the current projection matrix.
The source frame is the rectangle in world space containing the contents to be rendered.
Modifiers
@readonly
property transform
transform: Matrix;
A transform to be appended to the projection matrix.
This can be used to transform points in world-space one last time before they are outputted by the shader. You can use to rotate the whole scene, for example. Remember to clear it once you've rendered everything.
{PIXI.Matrix}
method calculateProjection
calculateProjection: ( _destinationFrame: Rectangle, sourceFrame: Rectangle, _resolution: number, root: boolean) => void;
Calculates the
projectionMatrix
to map points insidesourceFrame
to insidedestinationFrame
.Parameter destinationFrame
The destination frame in the render-target.
Parameter sourceFrame
The source frame in world space.
Parameter resolution
The render-target's resolution, i.e. ratio of CSS to physical pixels.
Parameter root
Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection is y-flipped.
method destroy
destroy: () => void;
method setTransform
setTransform: (_matrix: Matrix) => void;
Sets the transform of the active render target to the given matrix.
Parameter matrix
The transformation matrix
method update
update: ( destinationFrame: Rectangle, sourceFrame: Rectangle,