avocado-old/packages/graphics/container.js

109 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-03-18 20:06:47 -05:00
const PIXI = 'undefined' !== typeof window ? require('pixi.js') : undefined;
import {Renderable} from './renderable';
export class Container extends Renderable {
constructor() {
super();
this._children = [];
this._childrenIndexes = new Map();
this._isDirty = false;
this.container = PIXI ? new PIXI.Container() : undefined;
2019-03-18 20:06:47 -05:00
}
addChild(child) {
child.parent = this;
this.isDirty = true;
const index = this._children.push(child) - 1;
this._childrenIndexes.set(child, index);
this.container.addChild(child.internal);
2019-03-18 20:06:47 -05:00
}
2019-03-19 18:29:11 -05:00
get children() {
2019-03-18 20:06:47 -05:00
return this._children;
}
2019-03-19 18:29:11 -05:00
destroy() {
this.children.forEach((child) => {
child.destroy();
});
super.destroy();
}
get internal() {
return this.container;
}
get isDirty() {
return this._isDirty;
}
set isDirty(isDirty) {
if (this.parent) {
this.parent.isDirty = isDirty;
}
this._isDirty = isDirty;
}
_removeChild(child) {
2019-03-18 20:06:47 -05:00
const index = this._children.indexOf(child);
if (-1 === index) {
return;
}
this._children.splice(index, 1);
this.container.removeChild(child.internal);
2019-03-18 20:06:47 -05:00
}
2019-03-27 01:50:05 -05:00
removeChild(child) {
this._removeChild(child);
2019-03-27 01:50:05 -05:00
this._resetChildrenIndexes();
}
2019-03-18 20:06:47 -05:00
removeAllChildren() {
for (const child of this._children) {
this._removeChild(child);
2019-03-18 20:06:47 -05:00
}
this._childrenIndexes = new Map();
2019-03-18 20:06:47 -05:00
}
2019-03-27 01:50:05 -05:00
_resetChildrenIndexes() {
this._childrenIndexes = new Map();
for (const i in this._children) {
const child = this._children[i];
this._childrenIndexes.set(child, i);
}
}
tick() {
if (!this.isDirty) {
return;
}
let needsSort = false;
for (const child of this._children) {
if (0 !== child.zIndex) {
needsSort = true;
}
if (child instanceof Container) {
child.tick();
}
}
if (!needsSort) {
return;
}
this._children.sort((l, r) => {
if (l.zIndex !== r.zIndex) {
return l.zIndex - r.zIndex;
}
const lIndex = this._childrenIndexes.get(l);
const rIndex = this._childrenIndexes.get(r);
return lIndex - rIndex;
});
this.container.children = this._children.map((child) => {
return child.internal;
});
2019-03-27 01:50:05 -05:00
this._resetChildrenIndexes();
}
2019-03-18 20:06:47 -05:00
}