Coder Social home page Coder Social logo

layers's Introduction

@pixi/layers - PixiJS Layers Kit

Build CI npm version

This package provides an extension to scene tree - layers. These layers allows you to change the rendering order of items in your scene without moving them around in your scene. It's like {@link PIXI.DisplayObject#zIndex zIndex}, but supercharged.

It has been ported to PixiJS 7 since @pixi/layers 2.0.0 (formerly pixi-layers).

Nothing will work if you dont create Stage and set it as root. Please do it or read full explanation.

Installation

npm install --save @pixi/layers

Examples

Usage

{@link Layer} extends {@link PIXI.Container}:

import { Layer } from '@pixi/layers';

const layer = new Layer();

A DisplayObject/Container can be rendered inside its layer instead of direct parent

bunnySprite.parentLayer = layer;

Layer can order elements inside of it, by zOrder increase

bunnySprite.zOrder = 2;
cloudSprite.zOrder = 1;
badCloudSprite.zOrder = 1.01;
layer.group.enableSort = true;

You can check which objects were picked up into layer

stage.updateStage();
console.log(layer._sortedChildren);

// Order of rendering: 
//   bunnySprite (index=1)
//   badCloudSprite (index=2, order=1)
//   cloudSprite (index=2, order=0)

{@link Group} sorts its items after emitting the {@link Group#sort} event for each item. You can intercept it and set the z-order on each item.

layer.group.on('sort', function onWillSort(sprite) {
    sprite.zOrder = sprite.y 
});

@pixi/layer applies a mixin on {@link PIXI.Renderer} so it calls "updateStage" automatically if you use a {@link Stage} for your scene's root, so you can check it after render too:

renderer.render(stage);
console.log(layer._sortedChildren);

When you move a character with attached sprites from different layers to a new stage, you have to change their layers.

Instead, you can create a new display Group:

const lightGroup = new Group();

bunnySprite.parentGroup = lightGroup;
const lightLayer = new Layer(lightGroup); // only one layer per stage can be bound to same group

Groups are working between different stages, so when you move bunny it will be rendered in its light layer.

Layer is representation of global Group in this particular stage.

Vanilla JS,

All PixiJS has a special bundle suited for vanilla JavaScript in the browser.
Navigate pixi-layers npm package, take dist/pixi-layers.js file.

<script src="./pixi.min.js"></script>
<script src="./pixi-layers.js"></script>
const layer = new PIXI.layers.Layer();

Usage with canvas and particles

Due to changes in PixiJS architecture that allowed to build custom bundles, certain operations has to be called from your bundle or from your app.

The important thing is to call it when you know that corresponding module is loaded. You can call it multiple times if you are not sure :) Welcome to es6 imports!

If you use @pixi/canvas-renderer

import { CanvasRenderer } from 'pixi.js-legacy';
import { applyCanvasMixin } from '@pixi/layers';

applyCanvasMixin(CanvasRenderer);

If you use @pixi/particles

import { ParticleContainer } from 'pixi.js';
import { applyCanvasMixin } from '@pixi/layers';

applyParticleMixin(ParticleContainer);

Advanced sorting

If you want sorting to affect children that have different parentLayer than their direct parent, please set the group sortPriority. For now, it has two values - 0 by default and 1 for special cases.

Look at Normals with sorting

Important notice about filters

If you add filters to layer, or use layer itself as a mask - it might not work!

The reason is that layer getBounds() does not take into account its active children.

If you use filters on layer, there are three ways:

  1. add a filterArea, its global screen rect for filters, layer.filterArea = renderer.screen.
  2. works with both: Add a child graphics rect of certain size with alpha=0
  3. if you know how to pixi: override calculateBounds that way it takes _activeChildren into account.

If you use layer as a stencil mask (render all graphics inside it, only ways 2 and 3 can work.

The legend

Stage is the city. Containers are buildings, simple sprites are people.

Layers are office buildings. Office for googlers, office for bakers, office for account workers.

Groups are occupation. If there's a googler, he's looking for google office in the same town.

In render stage, some people are going to their offices and arrange by z-order/z-index/their rank in corporation.

People who dont have occupation or office are working from home. And some people are actually living in offices, that happens ;)

We can combine multiple Stage's into each other, like downtown, and child suburbs.

In that case, people will look for offices in the same suburb, and if they dont find it, they'll go search one in the downtown.

The only problem with this legend is that "people" and "buildings" are actually the same ;) Whole building can be "home for googlers", but one person in it has its own occupation, he's from Yandex. It happens.

Pros

  1. compatible with other implementations: does not change "container.children" order
  2. faster than just sorting: if there are 1000 elements with the same z-index, you can create extra Layer for them, and they wont be compared with each other
  3. Compared to pixi-display it doesn't care about filters or masks, they just work. You can use them to add lighting effects to the stage.

Cons

  1. Interaction is different, there might be bugs. Performance of processInteractive() can drop a bit.
  2. Non-renderable elements are not interactable. Elements with alpha=0 are interactable but their children are not.
  3. Plugin does not support new @pixi/events package yet.

How to build

npm install
npm run build

layers's People

Contributors

bigtimebuddy avatar casmo avatar dependabot[bot] avatar dev7355608 avatar elizavetta avatar ivanpopelyshev avatar johnsongnow avatar jonlepage avatar namark avatar shukantpal avatar snowycoder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

layers's Issues

Static container as a background.

Hello, first of all thanks for awesome work with layers and lighting.

I'm trying to migrate my project on a new version of pixi-layers and pixi-lighting and got some issue.

My application consists of several parts:

  1. rootStage (PIXI.display.Stage) - just a rootContainer.
  2. bgStage (PIXI.Container) - container with a background and some sprites on it without any effects.
  3. mainStage (PIXI.display.Stage) - this one is using Pixi-lights.

So, i've got some issue with mainStage opacity, I can't understand why is this happening and tried to use layers, groups, change bgStage type to layer or stage, nothing fix it.

Can you help me?

Here is example:
https://codepen.io/Fire7/pen/zaPKNQ
So, background and bunny should not be visible

Support for pixi v5

I was wondering, because of migration issues, if there will be support for pixi v5 when it's released?

I have problem in Angular 7

import 'pixi-layers';

import * as PIXI from 'pixi.js';

import Application = PIXI.Application;

ERROR in node_modules/@types/pixi.js/index.d.ts(7,1): error TS6200: Definitions of the following identifiers conflict with those in another file: VERSION, PI_2, RAD_TO_DEG, DEG_TO_RAD, RENDERER_TYPE, BLEND_MODES, DRAW_MODES, SCALE_MODES, WRAP_MODES, TRANSFORM_MODE, PRECISION, GC_MODES, SHAPES, TEXT_GRADIENT, UPDATE_PRIORITY, loader, TARGET_FPMS, MIPMAP_TEXTURES, RESOLUTION, FILTER_RESOLUTION, SPRITE_MAX_TEXTURES, SPRITE_BATCH_SIZE, RETINA_PREFIX, RENDER_OPTIONS, GC_MODE, GC_MAX_IDLE, GC_MAX_CHECK_COUNT, WRAP_MODE, SCALE_MODE, PRECISION_VERTEX, PRECISION_FRAGMENT, UPLOADS_PER_FRAME, CAN_UPLOAD_SAME_BUFFER, MESH_CANVAS_PADDING, AccessibilityManager, URL_FILE_EXTENSION, DATA_URI, SVG_SIZE, Application, Bounds, Container, DisplayObject, TransformBase, TransformStatic, Transform, GraphicsData, Graphics, CanvasGraphicsRenderer, GraphicsRenderer, WebGLGraphicsData, PrimitiveShader, E, SE, S, SW, W, NW, N, NE, MIRROR_HORIZONTAL, MIRROR_VERTICAL, Matrix, PointLike, ObservablePoint, Point, Circle, Ellipse, Polygon, Rectangle, RoundedRectangle, SystemRenderer, CanvasRenderer, CanvasMaskManager, CanvasRenderTarget, WebGLRenderer, WebGLState, TextureManager, TextureGarbageCollector, ObjectRenderer, Quad, RenderTarget, BlendModeManager, FilterManager, StencilMaskStack, MaskManager, StencilManager, WebGLManager, UniformDataMap, Filter, SpriteMaskFilter, Sprite, BatchBuffer, SpriteRenderer, CanvasSpriteRenderer, cacheStepsPerColorChannel, convertTintToImage, canUseMultiply, tintMethod, TextStyle, TextMetrics, Text, BaseRenderTexture, BaseTexture, RenderTexture, Texture, TextureMatrix, TextureUvs, Spritesheet, VideoBaseTexture, shared, TickerListener, Ticker, Shader, CanvasExtract, WebGLExtract, BitmapText, AnimatedSprite, TilingSprite, TilingSpriteRenderer, MovieClip, TextureTranform, FXAAFilter, BlurFilter, BlurXFilter, BlurYFilter, ColorMatrixFilter, DisplacementFilter, AlphaFilter, NoiseFilter, VoidFilter, InteractionData, InteractionPointerEvents, InteractionTouchEvents, InteractionMouseEvents, InteractionPixiEvents, InteractionEventTypes, InteractionManager, MiniSignalBinding, MiniSignal, Loader, Resource, Mesh, CanvasMeshRenderer, MeshRenderer, Plane, NineSlicePlane, Rope, ParticleContainer, ParticleBuffer, ParticleRenderer, AddHook, UploadHook, BasePrepare, CanvasPrepare, WebGLPrepare, CountLimiter, TimeLimiter, GLBuffer, GLFramebuffer, GLShader, GLTexture, VertexArrayObject, premultiplyBlendMode, TextureCache, BaseTextureCache, apple, android, amazon, windows, seven_inch, other, any, phone, tablet, EventEmitter, SpriteBatch, AssetLoader, Stage, DisplayObjectContainer, Strip, math, AbstractFilter, TransformManual, DEFAULT_RENDER_OPTIONS, gl, PIXI
node_modules/@types/pixi.js/index.d.ts(3092,13): error TS2374: Duplicate string index signature.
node_modules/@types/pixi.js/index.d.ts(3234,13): error TS2374: Duplicate string index signature.
node_modules/pixi.js/dist/pixi.d.ts(7,1): error TS6200: Definitions of the following identifiers conflict with those in another file: VERSION, PI_2, RAD_TO_DEG, DEG_TO_RAD, RENDERER_TYPE, BLEND_MODES, DRAW_MODES, SCALE_MODES, WRAP_MODES, TRANSFORM_MODE, PRECISION, GC_MODES, SHAPES, TEXT_GRADIENT, UPDATE_PRIORITY, loader, TARGET_FPMS, MIPMAP_TEXTURES, RESOLUTION, FILTER_RESOLUTION, SPRITE_MAX_TEXTURES, SPRITE_BATCH_SIZE, RETINA_PREFIX, RENDER_OPTIONS, GC_MODE, GC_MAX_IDLE, GC_MAX_CHECK_COUNT, WRAP_MODE, SCALE_MODE, PRECISION_VERTEX, PRECISION_FRAGMENT, UPLOADS_PER_FRAME, CAN_UPLOAD_SAME_BUFFER, MESH_CANVAS_PADDING, AccessibilityManager, URL_FILE_EXTENSION, DATA_URI, SVG_SIZE, Application, Bounds, Container, DisplayObject, TransformBase, TransformStatic, Transform, GraphicsData, Graphics, CanvasGraphicsRenderer, GraphicsRenderer, WebGLGraphicsData, PrimitiveShader, E, SE, S, SW, W, NW, N, NE, MIRROR_HORIZONTAL, MIRROR_VERTICAL, Matrix, PointLike, ObservablePoint, Point, Circle, Ellipse, Polygon, Rectangle, RoundedRectangle, SystemRenderer, CanvasRenderer, CanvasMaskManager, CanvasRenderTarget, WebGLRenderer, WebGLState, TextureManager, TextureGarbageCollector, ObjectRenderer, Quad, RenderTarget, BlendModeManager, FilterManager, StencilMaskStack, MaskManager, StencilManager, WebGLManager, UniformDataMap, Filter, SpriteMaskFilter, Sprite, BatchBuffer, SpriteRenderer, CanvasSpriteRenderer, cacheStepsPerColorChannel, convertTintToImage, canUseMultiply, tintMethod, TextStyle, TextMetrics, Text, BaseRenderTexture, BaseTexture, RenderTexture, Texture, TextureMatrix, TextureUvs, Spritesheet, VideoBaseTexture, shared, TickerListener, Ticker, Shader, CanvasExtract, WebGLExtract, BitmapText, AnimatedSprite, TilingSprite, TilingSpriteRenderer, MovieClip, TextureTranform, FXAAFilter, BlurFilter, BlurXFilter, BlurYFilter, ColorMatrixFilter, DisplacementFilter, AlphaFilter, NoiseFilter, VoidFilter, InteractionData, InteractionPointerEvents, InteractionTouchEvents, InteractionMouseEvents, InteractionPixiEvents, InteractionEventTypes, InteractionManager, MiniSignalBinding, MiniSignal, Loader, Resource, Mesh, CanvasMeshRenderer, MeshRenderer, Plane, NineSlicePlane, Rope, ParticleContainer, ParticleBuffer, ParticleRenderer, AddHook, UploadHook, BasePrepare, CanvasPrepare, WebGLPrepare, CountLimiter, TimeLimiter, GLBuffer, GLFramebuffer, GLShader, GLTexture, VertexArrayObject, premultiplyBlendMode, TextureCache, BaseTextureCache, apple, android, amazon, windows, seven_inch, other, any, phone, tablet, EventEmitter, SpriteBatch, AssetLoader, Stage, DisplayObjectContainer, Strip, math, AbstractFilter, TransformManual, DEFAULT_RENDER_OPTIONS, gl, PIXI
src/app/components/place/place.component.ts(30,31): error TS2339: Property 'display' does not exist on type 'typeof display'.

Support for Pixi 5.0.0

Pixi 5.0.0 is released now. Any plans to support it? We'd like to use Pixi v5 in our project because of its new features, but we use layers a lot too.

how to use sort for Group

thanks you ~
How to use sort for Group,
look this code,i use homepage demo code for my code,but it not to work...i don't understand。

//this demo for pixi.js homepage 
var greenGroup = new PIXI.display.Group(0, true);
greenGroup.on('sort', function (sprite) {
  //no work,sprite.zIndex is diy arrt
  sprite.zOrder = sprite.zIndex;
});

when i fix sprite.zIndex,sortfunction will auto run ? or i must be to run Group.sort()
this render who Container?? new PIXI.display.Stage() ornew Container()?

Not support pixi.js 5.1.4 with using webpack

Hello. I am using webpack

//like in Readme
import * as PIXI from 'pixi.js'
window.PIXI = PIXI
require('pixi-layers')

After updating pixi.js to 5.1.4, I get error:

Uncaught TypeError: renderer.incDisplayOrder is not a function
    at Stage.Layer._preRender (pixi-layers.js:563)
    at Stage.Layer.render (pixi-layers.js:583)
    at Renderer.render (core.es.js:11310)
    at Application.render (app.es.js:77)
    at TickerListener.emit (ticker.es.js:139)
    at Ticker.update (ticker.es.js:678)
    at Ticker._tick (ticker.es.js:377)

Please deal with this problem. So far rolled back to 5.1.3. Thank you!

rendering stage snap got weird cropped reverse bitmap ?

Am not sure if it come from the last update of module pixi-display or the pixi-light with normal.
But now if i try snap rendering the Stage, I got a strange mirror bitmap cropped and not the full stage rendering !?

the current stage i try to snap
image

it look weird and coped like this !
image

    function snapMap(options) {
        const fs = require('fs');
        const pathName = `img/parallaxes/${$dataMap.parallaxName}.png`;
        const snap = Bitmap.snap2(Scene);
        const urlData = snap._canvas.toDataURL();
        const base64Data = urlData.replace(/^data:image\/png;base64,/, "");
        fs.writeFile(pathName, base64Data, 'base64', function(error){
            if (error !== undefined && error !== null) {  console.error('An error occured while saving the screenshot', error); } 
        });

   };

   Bitmap.snap2 = function(stage) {
    var width =  $dataMap.width*48;
    var height = $dataMap.height*48;
    var bitmap = new Bitmap(width, height);
    var context = bitmap._context;
    var renderTexture = PIXI.RenderTexture.create(width, height);
    if (stage) {
        Renderer.render(stage, renderTexture);
        stage.worldTransform.identity();
        var canvas = null;
        if (Graphics.isWebGL()) {
            canvas = Renderer.extract.canvas(renderTexture);
        } else {
            canvas = renderTexture.baseTexture._canvasRenderTarget.canvas;
        }
        context.drawImage(canvas, 0, 0);
    } else {

    }
    renderTexture.destroy({ destroyBase: true });
    bitmap._setDirty();
    return bitmap;
};

am trying add multi options rendering
image

is it come from me , or it maybe a bug inside one of two pixi module ?

data object missing from InteractionManager

this was fixed in pixi.js as addressed in
"Make Interaction events closer to Browser behavior #3963"
and originally in
"Expose event properties on InteractionData (originally from #3890)"

exception thrown in pixi.js line 34546
"InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) {
var data = interactionEvent.data;
"
with interactionEvent.data being undefined.

again at pixi.js 34614
"InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) {
var data = interactionEvent.data;
"
for the same reason.

thanks

Tilemap won't render when stage.displayList is set

I've been trying to get my tilemap to render underneath all of the sprites but it always comes out on top no matter what z-index I set the DisplayGroup to be. Also, once I set stage.displayList = new PIXI.DisplayList(); the tilemap won't render at all.

Here is a code snippet:

        // Basic pixi-tilemap example from https://github.com/pixijs/pixi-tilemap
        var loader = new PIXI.loaders.Loader();
        loader.add('atlas', 'basic/atlas.json');
        loader.load(function(loader, resources) {
	        //third parameter is "true" ONLY IF YOUR TILES ARE SQUARES
	        var tilemap = new PIXI.tilemap.CompositeRectTileLayer(0, [resources['atlas_image'].texture], true);
                var size = 32;
                // bah, im too lazy, i just want to specify filenames from atlas
                for (var i=0;i<7;i++)
                    for (var j=0;j<7;j++) {
                        tilemap.addFrame("grass.png", i*size, j*size);
                        if (i%2==1 && j%2==1)
                            tilemap.addFrame("tough.png", i*size, j*size);
                    }

            var ground =  new PIXI.DisplayGroup(0, false)
            var groundContainer = new PIXI.Container()
            groundContainer.displayGroup = ground
            groundContainer.addChild(tilemap)
            stage.addChild(groundContainer)
        })

Here I even tried adding a tilemap to a container and then adding the container to the stage but it still either

  • Won't render at all if stage.displayList is set, or
  • Renders on top of everything if stage.displayList is not set

Any idea as to why this is happening? I'm pretty sure I've followed the examples correctly but of course I could be missing something.

Some (lots) of items disappear in internet explorer

Very strange: some items just disappear completely in internet explorer. Don't know exactly why, but it seems to be related to the zOrder property.

The elements disappearing al have a zOrder lower then ~180, elements with a higher zIndex seem to work. (I'm calculating zIndex by distance from the bottom of the screen)

I've attached two screenshots, one in chrome and another, from the same game, in IE (11).
screenshot chrome
screenshot ie

Anyway, I don't have more information right now, I'll probably look further into it later. (Maybe I'm doing something strange, I dunno)

Could pixi-display cause event propagation issues?

I'm hunting an event propagation issue, even though I don't .stopPropagation, the event doesn't bubble under an entity

I've created a small test case, however, in the test case, event bubbles as expected

I'm just wondering whether the way pixi-display shuffles entities could cause the event issue I'm experiencing

Unable to import

Hello there,

both...
require('pixi-layers)
...and...
import {Stage, Layer} from 'pixi-layers', or import * as Layers from 'pixi-layers'
...fails.

Uncaught ReferenceError: PIXI is not defined

I did import PIXI before the import call.
import 'pixi.js'
or import PIXI from 'pixi.js'

I also tried require.

Nothing works... same error. The layers plugin is not compatible with cjs and es imports?

AnimatedSprite can't be a child of Container in TypeScript

both pixi.js & pixi-layers are installed by npm packages
After importing pixi-layers, the AnimatedSprite can't pass type check when being added as a child of Container.

It seems that the error is caused by different function signatures. The paramter renderer of function renderWebGL in class Layer is of type PIXI.WebGLRenderer, whereas it's PIXI.Renderer in Container.

Which one is correct? And how can I make a quick fix for this temperorily?


Here's the compiling error:

TS2345: Argument of type 'AnimatedSprite' is not assignable to parameter of type 'DisplayObject'.
  Types of property 'renderWebGL' are incompatible.
    Type '(renderer: Renderer) => void' is not assignable to type '(renderer: WebGLRenderer) => void'.
      Types of parameters 'renderer' and 'renderer' are incompatible.
        Type 'WebGLRenderer' is missing the following properties from type 'Renderer': globalUniforms, mask, context, shader, and 10 more.

sorting video BG with sprites normal

hey, am not remember if it possible or how to do a sorting if i have a simple video element (Background) and if a need rendering sprites elements hover video, with diffuse,normal.

What i can do for make video rendering below all elements diffuse and normal?

example script here, in order i create createBackground and createTitleLogo :
Asignet to parentGroup .
But the cage of the title seem are rendering below the cage of video ?
maybe i do something wrong or am not remember the triks.

Scene_Title.prototype.createBackground = function() {
    const cage =  new PIXI.Container();
    // setup : see custom PIXI _this.autoPlay = false; from video source
    const video = $Loader.ress.video.original_intro1Loop;
    const video_texture = PIXI.Texture.fromVideo(video.data);
    const video_controler = video_texture.baseTexture; // controler from source
    const video_sprite =  new PIXI.Sprite(video_texture);
    // asign group display
    cage.parentGroup = $displayGroup.group[0];
    cage.zIndex = 1;
     // parenting
     cage.addChild(video_sprite);
     this.addChild(cage);
     //reference
     this.bgVideo = video_controler;
    // setup or hack
    video_sprite.width = 1920, video_sprite.height = 1080;
};

Scene_Title.prototype.createTitleLogo = function() {
    const data = $Loader.ress.tmp.titleLogoAni;
    const cage = new PIXI.Container(); // TODO: MAKE CUSTOM CONTROLER ANI CLASS
    const tex_d = data.textures;
    const tex_n = data.textures_n;
    const sprite_d = new PIXI.extras.AnimatedSprite(tex_d);
    const sprite_n = new PIXI.Sprite(tex_n[0]);
        sprite_d.normalWith(sprite_n, tex_n); // convert ani to [diff,normal]
    // asign group display
    sprite_n.parentGroup = PIXI.lights.normalGroup;
    sprite_d.parentGroup = PIXI.lights.diffuseGroup;
    cage.parentGroup = $displayGroup.group[0];
    cage.zIndex = 2;
    // parenting
    cage.addChild(sprite_d, sprite_n);
    this.addChild(cage);
    // reference
    cage.name = data.name;
    // setup or hack
    sprite_d.play();
};

here how the stage look like in children
a3tgbva3g

thanks

Import in Angular 9

import * as PIXI from 'pixi.js';
import 'pixi-layers';

doesn't work, tried a lot of other variations also but to no avail.

Please advise how we can import it with Angular 9, thanks!

mask parent container

any solution to add a single mask to parent container instead of each children ?

in this scenario , i would like to assign mask to master.mask
But it only work if a asign mask to each child's.
Any solution or suggest ? i search issue, but can't find code example.

_menu_items.prototype.initialize = function() {
    const dataBase = $Loader.Data2.menueItems;
    const master = new PIXI.Container();
    var d = new PIXI.Sprite(dataBase.textures.bgMaster);
    var n = new PIXI.Sprite(dataBase.textures_n.bgDiag_n);
        d.parentGroup = PIXI.lights.diffuseGroup;
        n.parentGroup = PIXI.lights.normalGroup;
        master.addChild(d,n);

 // FIXME: add single mask to master.mask instead of d,n
    const mask_d = new PIXI.Sprite(PIXI.Texture.WHITE);
    mask_d.width = d.width/2, mask_d.height = d.height/2;
    const mask_n = new PIXI.Sprite(PIXI.Texture.WHITE); 
    mask_n.width = d.width/2, mask_n.height = d.height/2;
    // add mask to diffuse,normal
    d.mask = mask_d;
    n.mask = mask_n;
    
    this.parentGroup = $displayGroup.group[4];
    this.addChild(master,mask_d,mask_n); 
    this.position.set(260,460);
};

Typescript

I added to pixi.js.d.ts the bare minimum to integrate pixi-display, you can see it here.

There doesn't seem to be a nice way to share this kind of change until Typescript 2.0 which implements module augmentation.

Render resolution

Hello I'm trying to pass resolution param in that example https://pixijs.io/examples/#/layers/normals.js, for correct support retina and etc.

 const options = {
    width,
    height,
    resolution: window.devicePixelRatio || 1
};

const app = new PIXI.Application(options);
document.body.appendChild(app.view);
...

But unfortunately cursor position is incorrect detected. Could you please chech it.
Thanks!

FPS drops about 10 frames after using DisplayList and DisplayGroup

In my setup the app.stage owns a DipslayList object and each player has its own DisplayGroup. I will add new sprites onto the player and new ones will be covered by its existing sprites. I have compared with and without using pixi-display plugin. Sometimes it drops about 10 frames. Sometimes it's OK. Is there a recommended use of this plugin?

lib/pixi.js/index.d.ts was outdated

Since several interfaces have renamed from "types/pixi.js" v4.5.0+, lib/pixi.js/index.d.ts was outdated in this repo.
When I'm using pixi-layers with "types/pixi.js" v4.5.0+, there will be an error in my console:

ERROR in [at-loader] ./node_modules/pixi-layers/bin/pixi-layers.d.ts:99:35
    TS2694: Namespace 'PIXI' has no exported member 'IDestroyOptions'.

pixi-display or pixi-layers

Hey Ivan,

I've stumbled upon this library when trying to do some work to create a image/content editor with Pixi as the rendering engine. Basically Fabric.js/Illustrator but with Pixi for the WebGL.

I was going to write a lot of my own stuff but I saw the pixi-layers branch and all the great work/demos that went into that. Great job and docs too!

I then also saw that pixi-display had a few commits as well. Are you forking the projects? The way the pixi-layers readme reads pixi-layers has a more advanced version of pixi-display in it.

I'm going to start with pixi-layers as a starting point but I'd like to know/understand your plans moving forward and if in my using this library I can be of any help.

Typescript Module Augmentation

I saw in #5 you were referring to what's happening with the core library but in the meantime I can't for the life of me get my project to let your Augments work... I can pull in pixi_display but it won't merge up with the core PIXI namespace.

For the moment I'm manually adjusting a .d.ts file but I didn't know if you had a trick to get it to work

sprite lightGroup patterns ?

I am experimenting something.
Is it possible to create our own patterns of light with sprites?
How i can perform this ?
example here
image

new PIXI.lights.PointLight(0xffffff, 2, texturePatterns); ??
or a way to convert a sprite to a light patern ?
Patterns.parentGroup = PIXI.lights.lightGroup not work
image
thank

Replicated children - Severe if it's actually the case

So in my game there is a character, character carries around it's name on top of it's head

I've noticed that after some time playing, that name became bolder and bolder, extremely bold at one point

I think pixi-display might somehow be replicating the children, is this possible?

(Couldn't verify the issue yet, will update the thread if it's something else or if it's definitely pixi-display)

pixi loader 'normal map'

hi @ivanpopelyshev , i know you're really busy, but i just want tell you that the dev from texturePacker just add new update to v4.7 for support normal map and make easy to manage in pixi loader.

Version 4.7.0 (2018-05-09)
Features
Added support for FaceBook AR Studio
Added normal_map reference to json file's meta section (Pixi, Phaser, Generic)
Enabled support for rotated sprites in Phaser

So now the meta has a new property called normal_map:
That will allow the loader to detect and make special textures tag.
image

do you think you will have the time to update this soon ?
thank a lot for all your work my friend.

Please mention pixi-layers requires PIXI.Stage

pixi-layers does not work if the containers it works on are not within PIXI.Stage. It just happened my app does not use Stage (nor Application) at all. It was not a problem to change it to have one Stage instead of Viewport, but I have had no clue it is needed.

Would it be possible to add this mention in readme? Thanks!

pixi-layers npm?

pixi-layers doesn't seem to be added to npm yet, only pixi-display. Any ETA on this? Should I put it there myself?

pixi-display + pixi-light Crash

Hi ivan
I have a small crash experimenting with pixi light and the layer system.
I do not know if these my group system would cause this?
I separated the process in 2 steps for easy debug.

Step1, the loader will inject resource in a global variable.
at this step are all fine.

// ┌------------------------------------------------------------------------------┐
// PIXI LOADER for light ressources (testing)
//└------------------------------------------------------------------------------┘
_SLL.prototype.load_pixiLight = function() {
    const loader_light = new PIXI.loaders.Loader();
    loader_light.add('bg_diffuse', 'lightIMG/BGTextureTest.jpg')
        .add('bg_normal', 'lightIMG/BGTextureNORM.jpg')
        .add('block_diffuse', 'lightIMG/block.png')
        .add('block_normal', 'lightIMG/blockNormalMap.png');
    loader_light.load(onAssetsLoaded);

    function onAssetsLoaded(loader, res) {
        $SLL.resourceLight = { // add reference to $SLL global (debug only)
             bg:[res.bg_diffuse.texture, res.bg_normal.texture],
             block:[res.block_diffuse.texture, res.block_normal.texture],
             block1:[res.block_diffuse.texture, res.block_normal.texture],
             block2:[res.block_diffuse.texture, res.block_normal.texture]
        }
    };

    loader_light.onComplete.add(() => {$SLL.setLightLoaded()}); // tell the light loader are finish
};

step2 i initialise my layers system (original)
and after inject light feature in the stage.
the stage "this" are initialise before in other module.
stage

Stage.prototype = Object.create(PIXI.display.Stage.prototype);
Stage.prototype.constructor = Stage;
Stage.prototype.initialize = function() {
    PIXI.display.Stage.call(this);
    this.interactive = false; // The interactive flag causes a memory leak.
};

step2 look at end on // PIXI LIGHT TEST IMPLEMENTATION

// LAYER ASIGNATION TO MAP STAGE
Spriteset_Map.prototype.createLowerLayer = function() {
    Spriteset_Base.prototype.createLowerLayer.call(this);
    // TODO: create global display.Group for avoid init each time new map loaded
    this.displayGroup = [
        new PIXI.display.Group(0, false), // backgroud Map. BG tile elements will no update and no interaction
        new PIXI.display.Group(1, true), // map elements default player, chara and all basic sprite update z and interaction
        new PIXI.display.Group(2, true), // map elements 2er
        new PIXI.display.Group(3, true), // map elements 3er
        new PIXI.display.Group(4, false), //levelGui: GUI Elements over maps
        new PIXI.display.Group(5, false), //levelMenu: MENU Elements over maps
        new PIXI.display.Group(6, false), //levelTxt: txt bubble, or SFX over all
    ];
    this.displayLayers = [];
    for (let l = 0, len = this.displayGroup.length; l < len; l++) {
        const DG = this.displayGroup[l];
        const DL = new PIXI.display.Layer(DG);
        this.displayLayers.push(DL);//(debugOnly) reference acces ref
        this.addChild(DL); // add to Stage PIXI.display
    };

    // PIXI LIGHT TEST IMPLEMENTATION
    var light = new PIXI.lights.PointLight(0xffffff, 1);
    this.addChild(new PIXI.display.Layer(PIXI.lights.diffuseGroup));
    this.addChild(new PIXI.display.Layer(PIXI.lights.normalGroup));
    this.addChild(new PIXI.display.Layer(PIXI.lights.lightGroup));
    // create ligth and normal
    function createPair(diffuseTex, normalTex) {
        var container = new PIXI.Container();
        var diffuseSprite = new PIXI.Sprite(diffuseTex);
        diffuseSprite.parentGroup = PIXI.lights.diffuseGroup;
        var normalSprite = new PIXI.Sprite(normalTex);
        normalSprite.parentGroup = PIXI.lights.normalGroup;
        container.addChild(diffuseSprite);
        container.addChild(normalSprite);
        return container;
    }

    let PAIR = {};
    for (const key in $SLL.resourceLight) {
        const res = $SLL.resourceLight[key];
        PAIR[key] = createPair(res[0], res[1]);
    }
    console.log('PAIR: ', PAIR); // add to stage
    this.addChild(PAIR.bg);
    this.addChild(PAIR.block);
    this.addChild(PAIR.block1);
    this.addChild(PAIR.block2);


    this.addChild(new PIXI.lights.AmbientLight(null, 0.4)); // GET ERROR !!!


    //... other stuff
};

at the line this.addChild(new PIXI.lights.AmbientLight(null, 0.4));
i get a error texLayer.getRenderTexture is not a function

image

if i remove this line, i can see all the element normal seem loaded.
image

did you know what i'm doing wrong in my context ?
i think it where and how i add light with new PIXI.display.Group?
thank

Pixi-display - worth using for simple depth sorting?

Is pixi-display recommended to use for basic z-index management?
In my case I have a simple tile-engine where I need to handle z-index for the game character.
Similar to this http://labs.phaser.io/view.html?src=src\depth%20sorting\Depth%20Sorting.js
The charater is only one image (no shadows etc).

I understand that pixi-display has a lot of clever features for handling z-index. But I am wondering if it worth using for more simple depth sorting as the one above.

My own idea was just to keep all displayobjects in a array and sort them on yPos and then re-add them to the displaylist on each update.

Attaching a DisplayList ignores mask

Something like;

this.displayList = new PIXI.DisplayList(); // if this line is present, mask ignored.
var mask = new PIXI.Graphics();
mask.beginFill(0xFFFFFF);
mask.drawRect(0, 0, 100, 100);
this.mask = mask;
var sprite = new PIXI.Sprite(someTexture);
sprite.displayGroup = new PIXI.DisplayGroup();
this.addChild(sprite);
sprite.position.set(300, 300); // visible

How can I use this lib with ES6 import?

I'm trying to use this addon, but I'm getting errors like this one: DisplayGroup is not a constructor when I try to import from pixi-display.

How can I use it if there is no export statement?

Thank you

Sharing sprite between two layers?

I am trying to create a mesh that has layers of series of sprites both horizontal and vertical.

image

All the boxes are sprites. I have two layer L1 and L2. And there is one sprite shared between two layers.

But looks like the common sprite can only belong to either L1 or L2.

Is there a way to share sprite between two layers?

Thank you in advance! :)

add sprite to layers ?

@ivanpopelyshev
hey, thank you first and bravos.
I just rewrote all Update core Rmmv with pixi-display.js
Your plugin allows me to get amazing performances in my little project RMMV!
Performance && setup preview:
https://youtu.be/8oGkRMTnReQ

Now my project can old more than 400 interactive events on a map with spines
Before only 100!! and a lot fps drop with the basic rmmv z rendering core.
My actual config on my map are:

  • all tree have 32 vertice * 6 bones * 400!
  • all element are auto update by detect Y for z-Index
  • 8MB gpu memory only for the live map rendering!
  • 1600*900 Resolution
  • map a 3400 * 2000 px
  • fake physic update for hairs and hands

i have question about how add i can add elements to a layer groups
in my example i have

var groupMap = new PIXI.display.Group(0, true);// all element type map 
var lG_groupMap = new PIXI.display.Layer(groupMap);
this.addChild(lG_groupMap); //ELEMENTS MAPS

why i can add specific element to lG_groupMap
example i need to do

this.addChild(spriteElement); // work
//but 
lG_groupMap.addChild(spriteElement); // not Work ??

full code experimental code

Stage.prototype = Object.create(PIXI.display.Stage.prototype); // 
Stage.prototype.constructor = Stage;

Stage.prototype.initialize = function() {
    PIXI.display.Stage.call(this);
    // The interactive flag causes a memory leak.
    this.interactive = false;
    this.group.enableSort = true;
};
// LAYERS SYSTEM ASIGNATION FOR ZINDEX ZORDER :see pixi-display.js
//↓↓↓□-▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇-□-Spriteset_Map-□-▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇-□↓↓↓//
Spriteset_Base.prototype.initialize = function() {
    Sprite.prototype.initialize.call(this);
    //this.setFrame(0, 0, Graphics.width, Graphics.height);
    //this._tone = [0, 0, 0, 0];
    this.opaque = true;
    this.createLowerLayer();
    //this.createToneChanger();
    //this.createUpperLayer();
    this.update();
};

Spriteset_Base.prototype.update = function() {
    Sprite.prototype.update.call(this);
    //this.updateScreenSprites();
    //this.updateToneChanger();
    this.updatePosition();
};

Spriteset_Map.prototype.update = function() {
    Spriteset_Base.prototype.update.call(this);
    //this.updateTileset();
    this.updateParallax();
    //this.updateTilemap();
    //this.updateShadow();
    //this.updateWeather();
};


// LAYER ASIGNATION TO MAP
Spriteset_Map.prototype.createLowerLayer = function() {
    Spriteset_Base.prototype.createLowerLayer.call(this);
    var groupMap = new PIXI.display.Group(0, true);// all element type map 
    var groupGui = new PIXI.display.Group(1, true);// all element type guy over map
    var groupMenu = new PIXI.display.Group(2, true);// all element menue show
    var lG_groupMap = new PIXI.display.Layer(groupMap);
    var lG_groupGui = new PIXI.display.Layer(groupGui);
    var lG_groupMenu = new PIXI.display.Layer(groupMenu);

    this.addChild(lG_groupMap); //ELEMENTS MAPS
    this.addChild(lG_groupGui); // GUI
    this.addChild(lG_groupMenu); // MENU
    this.createParallax(); // Create parralaxe and add parralaxe layers
    //this.createTilemap();
    this.createCharacters(lG_groupMap, groupMap); // pass as para the groupe 
    //this.createShadow();
    //this.createDestination(); // TODO: OK
    //this.createWeather();
    this.createPixiSA(groupMap);
};

    Spriteset_Map.prototype.createParallax = function() {
        this._parallax = new TilingSprite();
        this._parallax.move(0, 0, Graphics.width, Graphics.height);
        this._baseSprite.addChild(this._parallax);
    };

// create and assign a elements to groupe 
    Spriteset_Map.prototype.createCharacters = function(lG, G) { // lG_groupMap, group
        this._characterSprites = [];
        $gameMap.events().forEach(function(event) {
            this._characterSprites.push(new Sprite_Character(event));
        }, this);
        $gamePlayer.followers().reverseEach(function(follower) {
            this._characterSprites.push(new Sprite_Character(follower));
        }, this);
        this._characterSprites.push(new Sprite_Character($gamePlayer));
        for (var i = 0; i < this._characterSprites.length; i++) {
            var element = this._characterSprites[i];
            this.addChild(element); // add self 
            element.parentGroup = G; // zIndex= local , zOrder = global
            element.zIndex = 0;
            element.y
            console.log(' element.y: ',  element.y);
            console.log(' this._characterSprites[i]: ',  this._characterSprites[i],this._characterSprites[i]._characterName);
        }
    };

    Sprite_Character.prototype.updatePosition = function() {
        this.x = this._character.screenX();
        this.y = this._character.screenY();
        //this.z = this._character.screenZ();
        this.zIndex = this.y; // PIXI-LAYER.JS UPDATE INDEX GROUPE
    };

    // ADD ALL ELEMENT PIXI SPRITE 
    Spriteset_Map.prototype.createPixiSA = function() {
        console.log('createPixiSA: ', 'createPixiSA');
        
      
    };

thank for help if you have time

Children don't undermine their parents

So I'm experiencing this problem right now:

screen shot 2018-09-21 at 10 35 03

[1-Major] Basically, no matter what I tried, I couldn't make childrens of a sprite, appear below the sprite (they are on the same layer, aka, PIXI.DisplayGroup) - so basically I want wings to appear behind the body, but just doesn't happen

[2-Minor] I had pixi-layers 0.1.7 - now I got the latest 0.1.7 - it's a lengthier one, has some sortPriority code - I tried setting it to several places but didn't change anything - I think the version should've increased it at one point, to 0.1.8

[3-Major-Opinion-Request] I could solve this problem with tools at hand, make the body a children of the container, rather than the container itself, but looking for the optimal solution, I also apply filters to the body, I want the additional parts like the head etc. to have the filters too, if they were actually one Sprite, this would be the case, but I'm guessing there's no actual solution to this problem now? Example: If I applied an outline filter to sprites, the head and body will be outlined individually now?

Adding viewport to layers

Hi,

I tried to put pixi-layers in a viewport (with pixi-viewport).

I have achivied a render but interactions are not working...

  • when panning -> light move (it's supposed to be attach to the red dot...)
  • ambiant light is only defined on the initial viewport (zoom out and there is a gray square)

see source sample : https://stackblitz.com/edit/rxjs-xupagq

oddly when commenting the line 74 (lighting not working) -> interactions are working again

Amplified Exceptions?

So one of the most common exceptions of PIXI is going outside the texture boundaries with a frame

I think pixi-display might be amplifying the situation when this happens, the exception is replicated by pixi-display, things freeze

I don't know whether anything can or should be done about this, just sharing my experience - the solution is obviously to hunt and prevent exceptions

Need way to handle mask as single layer

I have code like below which creates many masked hearts.

public createHeart(index: number) {
        let container = new PIXI.Container();

        let heartFull = new PIXI.Sprite();
        heartFull.position = new PIXI.Point(index * 2.5, 0);
        heartFull.texture = PIXI.utils.TextureCache["healthGauge.png"]
        heart.parentGroup = uiGroup

        let heart = new PIXI.Sprite();
        heart.position = new PIXI.Point(index * 2.5, 0);
        heart.texture = PIXI.utils.TextureCache["heartMask.png"]
        heart.parentGroup = uiMaskGroup

       container.addChild(heartFull, heart);

       app.stage.addChild(container);

        heartFull.mask = heart
    }

which creates output as below.

2018-11-07 1 04 50

But when inspected from WebGL inspector extension of chrome,
I checked webGL useProgram() for masking operation is called n times for n hearts.

Is there any way to execute multiple mask operation as single operation?
Or should I merge masking sprites using renderTexture?
Thank you!

Masks prevent interactions regardless of layers/groups.

I'm using the layers branch and I've got this very basic setup:

const stage = new PIXI.display.Stage();
stage.group.enableSort = true;

const overlay = new PIXI.display.Group(10, false);
stage.addChild(new PIXI.display.Layer(overlay));

If I set the parentGroup of a display object to overlay it works just fine visually, the object is rendered on top of anything else in the stage, but if the parent of that object has a mask, while still displayed correctly, the interactions don't work unless the object is within the bounds of the mask.

Seems like a pretty nasty problem since the decision is made before even getting to the object that has a parentGroup set
https://github.com/pixijs/pixi-display/blob/25a2a0e06269c6fde4241308a54727bffb9405d2/src/InteractionManagerMixin.ts#L45
so I'm hoping that I just overlooked some easy way around this.

Please change pixi-layers to a new repo or make it the main branch

Ok, so I installed this through npm i pixi-display and it took me a few hours to discover that actually the branch being used right now is the Layer branch. So I had to run github:pixijs/pixi-display#layers to make things actually work.

So please move it to a new repo or make the layer the main branch. It's non sense to keep it like this with the code examples being in a huge difference between the main branch right now.

Import error when using React along with Typescript

Hello,

I installed pixi.js and pixi-layers by

yarn add pixi.js pixi-layers

and then I tried following code:

import 'pixi-layers'
import * as PIXI from 'pixi.js'

const test = new PIXI.display.Group(100, false)

but it throws an error:

./src/index.tsx
Attempted import error: 'display' is not exported from 'pixi.js' (imported as 'PIXI').

Children are not visible

Hi

So I've just started using pixi-display, first thing I noticed is that the children of a sprite are not directly visible, they are invisible, I should probably give them a displayGroup too, however, I think shouldn't need to

Any ideas?

Can't apply mask to Container who has children with parentGroup

I've just migrated from pixi-display to pixi-layers and my masks become broken.
Previously all I need to do is just applying Rectangle mask to Container with multiple children and all worked fine regardless of their displayGroups.

https://jsfiddle.net/SvDenys/2om9fn3s/

Now I can't understand how to do this. I made a fiddle from the bunny example. The most important here is this line:
bunniesOdd.mask = mask

Interactivity works fine, but displaying are not. Could you please help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.