跳到內容

aipooljs — 物件池

aipooljs 解決的問題很具體:遊戲熱路徑(子彈、粒子、特效)每幀都在大量建立與銷毀相同形狀的物件,讓 GC 不斷追著跑。object pool 用一個固定大小的預配置緩衝區取代這些配置,讓 acquire() / release() 都是 O(1),不產生 GC 壓力。

終端機視窗
npm install aipooljs
import { createPool } from "aipooljs";
// 1. 預配置固定大小的緩衝區
const bullets = createPool({
create: () => ({ x: 0, y: 0, vx: 0, vy: 0, active: false }),
reset: (b) => {
// reset 必須用賦值,不要用 delete(會讓 V8 降格 hidden class)
b.x = 0;
b.y = 0;
b.vx = 0;
b.vy = 0;
b.active = false;
},
size: 256,
});
// 2. 熱路徑:acquire — O(1),不配置
function fireBullet(x: number, y: number, vx: number, vy: number) {
const b = bullets.acquire();
b.x = x;
b.y = y;
b.vx = vx;
b.vy = vy;
b.active = true;
return b;
}
// 3. 子彈消失時 release — O(1),reset() 先跑再歸還
function recycleBullet(b: ReturnType<typeof fireBullet>) {
bullets.release(b);
}

子彈、粒子、命中特效在熱路徑上反覆建立與銷毀,最適合交給 object pool。下方示範的砲台從 256 格的池子 acquire 子彈,子彈飛出場地就 release;每隔幾秒的齊射需要的子彈超過池子容量,onOverflow: 'null' 讓 acquire() 回傳 null,這一發就直接丟棄。狀態列顯示 alive、available、create() 的累計呼叫次數(池子建好後就不再增加)與丟棄數。

互動示範載入中…

BulletSpawner:256 發子彈的物件池
示範原始碼
src/demos/pool-bullets.ts
/**
* BulletSpawner: a 256-bullet object pool with aipooljs.
*
* A turret sweeps its aim and fires glowing bullets (additive blend) into the arena. Each bullet
* is a Sprite `acquire()`d from a 256-slot pool and `release()`d the moment it leaves the arena:
* all 256 sprites are created with the pool and stay in the scene, hidden while they are free,
* so nothing is allocated or added to the scene graph after the pool is built. Every few seconds the turret fires a
* burst whose rate needs more than 256 bullets in flight; with `onOverflow: 'null'`, `acquire()`
* then returns null and the shot is dropped instead of growing the pool or throwing.
*
* The readout shows the pool's `alive` and `available`, how many times `create()` has run
* (256, all at construction, and flat after that), and the dropped shots.
*/
import { createPool } from 'aipooljs';
import { Container, Graphics, Sprite, type Application } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const POOL_SIZE = 256;
const MUZZLE = { x: 70, y: 200 };
const BULLET_SPEED = 330; // px per second: about 2.2 s to cross the arena
const STEADY_RATE = 55; // shots per second, about 120 in flight
const BURST_RATE = 260; // shots per second during a burst, more than the pool can hold
const CYCLE_MS = 5000; // one steady stretch plus one burst
const BURST_MS = 1300; // the last part of each cycle
const WARM_UP_MS = 1500; // simulated before the first frame, so a paused demo is not empty
const MAX_STEP_MS = 50;
const REPORT_EVERY_MS = 250;
/** The pooled object: a sprite plus the per-shot state. */
interface Bullet {
sprite: Sprite;
vx: number;
vy: number;
burst: boolean; // fired during a burst; drawn in the second colour
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
steady: cssColor('--sl-color-accent'),
burst: cssColor('--sl-color-orange'),
turret: cssColor('--sl-color-text'),
border: cssColor('--sl-color-gray-4'),
};
}
interface Stats {
alive: number;
available: number;
creates: number;
dropped: string;
rate: number;
}
const READOUT = {
'zh-TW': (s: Stats) =>
`存活 ${s.alive}|可用 ${s.available}|create() 呼叫 ${s.creates} 次|丟棄 ${s.dropped} 發|射速 ${s.rate} 發/秒`,
en: (s: Stats) =>
`Alive ${s.alive} | available ${s.available} | create() calls ${s.creates} | dropped ${s.dropped} | fire rate ${s.rate}/s`,
};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle {
// A soft dot: a faint halo under a bright core, white so each sprite can be tinted.
const dot = new Graphics().circle(0, 0, 6).fill({ color: 0xffffff, alpha: 0.25 }).circle(0, 0, 2.5).fill(0xffffff);
const texture = app.renderer.generateTexture({ target: dot, resolution: 2, antialias: true });
dot.destroy();
const layer = new Container();
const border = new Graphics();
const turret = new Graphics();
turret.position.set(MUZZLE.x, MUZZLE.y);
const arena = new Container();
arena.addChild(border, layer, turret);
app.stage.addChild(arena);
let colors = readColors(cssColor);
let creates = 0;
const pool = createPool<Bullet>({
size: POOL_SIZE,
create: () => {
creates++;
// Additive blending: overlapping bullets add up and glow.
const sprite = new Sprite({ texture, anchor: 0.5, blendMode: 'add', visible: false });
layer.addChild(sprite);
return { sprite, vx: 0, vy: 0, burst: false };
},
// Reset by assignment, never `delete`, so every bullet keeps the same hidden class.
reset: (bullet) => {
bullet.sprite.visible = false;
bullet.vx = 0;
bullet.vy = 0;
bullet.burst = false;
},
onOverflow: 'null', // acquire() returns null when all 256 are in flight
});
const live: Bullet[] = [];
let dropped = 0;
let clock = 0;
let owed = 0; // fractional shots carried to the next frame
let aim = 0;
const inBurst = () => clock % CYCLE_MS >= CYCLE_MS - BURST_MS;
function fire(): void {
const bullet = pool.acquire();
if (!bullet) {
dropped++; // the pool is empty: skip this shot
return;
}
bullet.burst = inBurst();
const angle = aim + (bullet.burst ? (Math.random() - 0.5) * 0.9 : 0);
bullet.vx = Math.cos(angle) * BULLET_SPEED;
bullet.vy = Math.sin(angle) * BULLET_SPEED;
bullet.sprite.position.set(MUZZLE.x + Math.cos(angle) * 24, MUZZLE.y + Math.sin(angle) * 24);
bullet.sprite.tint = bullet.burst ? colors.burst : colors.steady;
bullet.sprite.visible = true;
live.push(bullet);
}
/** Advances the simulation: sweep the aim, fire what the rate allows, move, recycle. */
function step(ms: number): void {
clock += ms;
aim = Math.sin(clock / 700) * 0.6;
owed += ((inBurst() ? BURST_RATE : STEADY_RATE) * ms) / 1000;
for (; owed >= 1; owed--) fire();
for (let i = live.length - 1; i >= 0; i--) {
const bullet = live[i];
const { position } = bullet.sprite;
position.x += (bullet.vx * ms) / 1000;
position.y += (bullet.vy * ms) / 1000;
if (position.x < 0 || position.x > ARENA.width || position.y < 0 || position.y > ARENA.height) {
live[i] = live[live.length - 1]; // swap-remove: order does not matter
live.pop();
pool.release(bullet); // reset() hides the sprite
}
}
}
const paint = () => {
border.clear().rect(0, 0, ARENA.width, ARENA.height).stroke({ width: 1, color: colors.border, alpha: 0.6 });
turret.clear().circle(0, 0, 14).fill({ color: colors.turret, alpha: 0.2 }).stroke({ width: 2, color: colors.turret });
turret.rect(8, -4, 18, 8).fill(colors.turret);
for (const bullet of live) bullet.sprite.tint = bullet.burst ? colors.burst : colors.steady;
};
const fit = () => {
const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height);
arena.scale.set(scale);
arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2);
};
fit();
app.renderer.on('resize', fit);
const report = () =>
setStatus(
READOUT[lang]({
alive: pool.alive,
available: pool.available,
creates,
dropped: dropped.toLocaleString(lang),
rate: inBurst() ? BURST_RATE : STEADY_RATE,
}),
);
for (let t = 0; t < WARM_UP_MS; t += MAX_STEP_MS) step(MAX_STEP_MS);
paint();
turret.rotation = aim;
report();
let sinceReport = 0;
return {
update(deltaMS) {
step(Math.min(deltaMS, MAX_STEP_MS));
turret.rotation = aim;
sinceReport += deltaMS;
if (sinceReport >= REPORT_EVERY_MS) {
sinceReport = 0;
report();
}
},
onThemeChange() {
colors = readColors(cssColor);
paint();
},
dispose() {
app.renderer.off('resize', fit);
pool.dispose();
arena.destroy({ children: true }); // also the 256 pooled sprites
texture.destroy(true);
},
};
}

固定大小,溢出即丟錯:acquire() 在池空時會丟出 PoolError,強迫你調整上游產生速率,而不是讓池暗自擴張讓最壞情況難以預測。若確實需要彈性,可傳入 onOverflow: 'grow'。

雙重釋放偵測:release() 同一個物件兩次是 object pool 的經典 bug,aipooljs 用 Set 追蹤存活物件,第二次 release 直接丟出 PoolError。

參數在建構時就驗證:create 與 reset 都必須是函式,options 物件不可省略;create() 或 overflow handler 回傳 null / undefined 會丟出 PoolError 並保持池子不變,需要「沒有物件」的語義時請用 onOverflow: 'null'。borrow(fn, { signal }) 的 fn 不是函式或 signal 不是 AbortSignal 時,會在取出物件前丟出 PoolError。所有 PoolError 訊息都以 aipooljs: 開頭,請以 error class 加 regex 比對,不要比對完整字串。

reset 不用 delete:刪除屬性會讓 V8 將物件降格成 dictionary mode,破壞 hidden class 最佳化,讓整個熱路徑從 monomorphic 變成 megamorphic。JSDoc 有明確標注這個規則。

createPool({
create, // () => T — 初始建立物件(必須是函式,不可回傳 null / undefined)
reset, // (obj: T) => void — 歸還時重設(必須是函式)
size, // number — 池子大小(必填,非負整數)
onOverflow, // 'throw'(預設)| 'null' | 'grow' | (pool) => T
})
  • 子彈/粒子池:最典型的用法,搭配 aiecsjs 的 entity 管理
  • 與 aiquadtreejs 搭配:pool 管理物件生命週期,quadtree 管理空間查詢
  • DOM 節點回收:<li> 列表項目、畫布繪圖物件等可以用同樣模式管理