UNPKG

@thi.ng/ecs

Version:

Entity Component System based around typed arrays & sparse sets

120 lines (119 loc) 2.99 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; import { INotifyMixin } from "@thi.ng/api/mixins/inotify"; import { isFunction } from "@thi.ng/checks/is-function"; import { EVENT_ADDED, EVENT_CHANGED, EVENT_PRE_DELETE } from "../api.js"; let AComponent = class { id; sparse; dense; vals; n; default; owner; constructor(id, sparse, dense, vals) { this.id = id; this.sparse = sparse; this.dense = dense; this.vals = vals; this.n = 0; } keys() { return this.dense.slice(0, this.n); } *values() { for (let i = this.n; i-- > 0; ) { yield this.getIndex(i); } } has(id) { const i = this.sparse[id]; return i < this.n && this.dense[i] === id; } valueIndexForID(id) { const i = this.sparse[id]; return i < this.n && this.dense[i] === id ? i * this.stride : -1; } valueIndexForIDUnsafe(id) { return this.sparse[id] * this.stride; } set(id, val) { const i = this.sparse[id]; if (i < this.n && this.dense[i] === id) { this.setIndexUnsafe(i, val); return true; } return false; } setIndex(i, val) { const id = this.dense[i]; if (i < this.n && this.sparse[id] === i) { this.setIndexUnsafe(i, val); return true; } return false; } add(id, val) { const { dense, sparse, n } = this; const max = dense.length; const i = sparse[id]; if (id < max && n < max && !(i < n && dense[i] === id)) { dense[n] = id; sparse[id] = n; this.n++; const def = this.default; const initVal = val || (isFunction(def) ? def() : def); initVal !== void 0 && this.setIndexUnsafe(n, initVal, false); this.notify({ id: EVENT_ADDED, target: this, value: id }); return true; } return false; } delete(id) { let { dense, sparse, n } = this; let i = sparse[id]; if (i < n && dense[i] === id) { this.notify({ id: EVENT_PRE_DELETE, target: this, value: id }); i = sparse[id]; const j = dense[--n]; dense[i] = j; sparse[j] = i; this.n = n; this.moveIndex(n, i); return true; } return false; } // @ts-ignore: mixin // prettier-ignore addListener(id, fn, scope) { } // @ts-ignore: mixin // prettier-ignore removeListener(id, fn, scope) { } // @ts-ignore: mixin notify(event) { } notifyChange(id) { return this.notify({ id: EVENT_CHANGED, target: this, value: id }); } }; AComponent = __decorateClass([ INotifyMixin ], AComponent); export { AComponent };