UNPKG

@thi.ng/ecs

Version:

Entity Component System based around typed arrays & sparse sets

60 lines (59 loc) 1.55 kB
import { assert } from "@thi.ng/errors/assert"; import { AComponent } from "./acomponent.js"; class ObjectComponent extends AComponent { constructor(sparse, dense, opts) { super(opts.id, sparse, dense, new Array(dense.length)); this.default = opts.default; } get size() { return 1; } get stride() { return 1; } packedValues() { return this.vals.slice(0, this.n); } resize(pool, cap) { assert(cap >= this.dense.length, "can't decrease capacity"); if (cap === this.dense.length) return; const sparse = pool.reallocArray(this.sparse, cap); const dense = pool.reallocArray(this.dense, cap); assert(!!(sparse && dense), `couldn't resize component: ${this.id}`); this.sparse = sparse; this.dense = dense; } get(id) { let i = this.sparse[id]; return i < this.n && this.dense[i] === id ? this.vals[i] : void 0; } getIndex(i) { return i < this.n ? this.vals[i] : void 0; } setIndexUnsafe(i, v, notify = true) { this.vals[i] = v; notify && this.notifyChange(this.dense[i]); } swapIndices(src, dest) { if (src === dest) return false; const { dense, sparse, vals } = this; const ss = dense[src]; const sd = dense[dest]; dense[src] = sd; dense[dest] = ss; sparse[ss] = dest; sparse[sd] = src; const tmp = vals[src]; vals[src] = vals[dest]; vals[dest] = tmp; return true; } moveIndex(src, dest) { const vals = this.vals; vals[dest] = vals[src]; delete vals[src]; } } export { ObjectComponent };