跳到內容

aiecsjs — 實體元件系統

aiecsjs 是一個 TypeScript 優先的 archetype ECS(Entity Component System)。核心特性是 archetype table:擁有相同 component 組合的 entity 存在同一個連續陣列裡,查詢時以直線 for 迴圈走 TypedArray,cache 友善。

終端機視窗
npm install aiecsjs
import {
createWorld,
createEntity,
addComponent,
defineComponent,
defineQuery,
pipe,
forEachEntityIndexed,
Types,
} from "aiecsjs";
// 1. 定義 components(SoA 欄位)
const Position = defineComponent({ x: Types.f32, y: Types.f32 });
const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });
// 2. 建立 world 與 entity
const world = createWorld();
const eid = createEntity(world);
addComponent(world, eid, Position, { x: 0, y: 0 });
addComponent(world, eid, Velocity, { x: 1, y: 2 });
// 3. 定義 query:有 Position + Velocity 的所有 entity
const movers = defineQuery([Position, Velocity]);
// 4. System 是純函數,用 pipe 串接
const movement = (w: typeof world, dt: number) => {
forEachEntityIndexed(w, movers, (e, i, pos, vel) => {
// i 是安全的欄位下標,不要用 e(entity id ≠ column index)
pos.x[i] += vel.x[i] * dt;
pos.y[i] += vel.y[i] * dt;
});
return w;
};
// 每幀
pipe(movement)(world, 1 / 60);

子彈、粒子群、RTS 單位這類大量同形狀的 entity,正是 SoA 欄位最能發揮的場景。下方示範 2,000 個帶 Position 與 Velocity 的 entity,每幀用 pipe 串起轉向、移動(超出邊界從另一側繞回)與繪製三個 system,繪製 system 直接把 Position 欄位寫進 PixiJS 的 ParticleContainer,狀態列顯示 entity 數與每幀 system 耗時。

互動示範載入中…

SwarmSimulation:2,000 個 entity 的移動系統
示範原始碼
src/demos/ecs-swarm.ts
/**
* SwarmSimulation: a movement system over 2,000 entities with aiecsjs.
*
* Every entity has two SoA components, Position and Velocity: aiecsjs stores each field as one
* TypedArray column, and a system walks those columns in a plain loop. Every frame one pipeline
* of plain-function systems runs:
* 1. steer: a slowly drifting flow field turns each velocity, so the swarm moves in bands;
* 2. move: integrate the position and wrap it around the arena edges;
* 3. draw: copy the Position columns straight into the matching PixiJS particles.
*
* The readout shows the live entity count and the average time the pipeline takes per frame.
*/
import {
Types,
addComponent,
createEntity,
createWorld,
defineComponent,
defineQuery,
destroyWorld,
forEachEntityIndexed,
getWorldSize,
pipe,
type World,
} from 'aiecsjs';
import { Container, Graphics, Particle, ParticleContainer, type Application } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const ENTITY_COUNT = 2000;
const TURN_RATE = 1.5; // how fast a velocity turns toward the flow field, per second
const MAX_STEP_MS = 50; // clamp long frames (tab switches, hiccups) so entities do not jump
const REPORT_EVERY_MS = 250;
// Components and queries are defined once per module: aiecsjs keeps them in a process-wide
// registry, and a world allocates the columns when an entity first gets the component.
const Position = defineComponent({ x: Types.f32, y: Types.f32 });
const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });
const movers = defineQuery([Position, Velocity]);
const positioned = defineQuery([Position]);
/** What every system receives besides the world: the frame step and the elapsed time. */
interface Tick {
seconds: number;
time: number;
}
/** Direction of the flow field at (x, y), in radians. Two sine waves that drift over time. */
function flowAngle(x: number, y: number, time: number): number {
return Math.sin(x * 0.009 + time * 0.35) * Math.PI + Math.cos(y * 0.014 - time * 0.25);
}
function wrap(value: number, size: number): number {
return ((value % size) + size) % size;
}
/** System 1: turn every velocity toward the flow field, keeping its speed. */
function steer(world: World, { seconds, time }: Tick): World {
const blend = Math.min(1, TURN_RATE * seconds);
forEachEntityIndexed(world, movers, (_e, i, pos, vel) => {
// `i` is the column index. `_e` is the packed EntityId and must never index a column.
const speed = Math.hypot(vel.x[i], vel.y[i]);
const heading = Math.atan2(vel.y[i], vel.x[i]);
const delta = flowAngle(pos.x[i], pos.y[i], time) - heading;
const next = heading + Math.atan2(Math.sin(delta), Math.cos(delta)) * blend; // shortest turn
vel.x[i] = Math.cos(next) * speed;
vel.y[i] = Math.sin(next) * speed;
});
return world;
}
/** System 2: integrate and wrap around the arena bounds. */
function move(world: World, { seconds }: Tick): World {
forEachEntityIndexed(world, movers, (_e, i, pos, vel) => {
pos.x[i] = wrap(pos.x[i] + vel.x[i] * seconds, ARENA.width);
pos.y[i] = wrap(pos.y[i] + vel.y[i] * seconds, ARENA.height);
});
return world;
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
border: cssColor('--sl-color-gray-4'),
swarm: cssColor('--sl-color-accent'),
scout: cssColor('--sl-color-text'),
};
}
const READOUT = {
'zh-TW': (count: string, ms: string) => `entity:${count} 個|3 個 system 每幀共 ${ms} ms`,
en: (count: string, ms: string) => `Entities: ${count} | 3 systems per frame: ${ms} ms`,
};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle {
const world = createWorld({ initialCapacity: ENTITY_COUNT + 1 }); // slot 0 is reserved
for (let n = 0; n < ENTITY_COUNT; n++) {
const eid = createEntity(world);
const angle = Math.random() * Math.PI * 2;
const speed = 30 + Math.random() * 60; // px per second
addComponent(world, eid, Position, { x: Math.random() * ARENA.width, y: Math.random() * ARENA.height });
addComponent(world, eid, Velocity, { x: Math.cos(angle) * speed, y: Math.sin(angle) * speed });
}
// One small white dot, rendered to a texture once and shared by every particle (tinted).
const dot = new Graphics().circle(0, 0, 2.5).fill(0xffffff);
const texture = app.renderer.generateTexture({ target: dot, resolution: 2, antialias: true });
dot.destroy();
// Only `position` is uploaded every frame; tint and scale are static until update() is called.
const layer = new ParticleContainer({ texture, dynamicProperties: { position: true } });
const border = new Graphics();
const arena = new Container();
arena.addChild(border, layer);
app.stage.addChild(arena);
// particles[i] belongs to the entity in column slot i, so the draw system needs no lookup.
const particles: Particle[] = [];
forEachEntityIndexed(world, positioned, (_e, i) => {
const scale = 0.6 + Math.random() * 0.6;
particles[i] = new Particle({ texture, anchorX: 0.5, anchorY: 0.5, scaleX: scale, scaleY: scale, alpha: 0.85 });
layer.addParticle(particles[i]);
});
/** System 3: copy the Position columns into the particles. */
const draw = (w: World): World => {
forEachEntityIndexed(w, positioned, (_e, i, pos) => {
const particle = particles[i];
particle.x = pos.x[i];
particle.y = pos.y[i];
});
return w;
};
const systems = pipe<World, Tick>(steer, move, draw);
let colors = readColors(cssColor);
const paint = () => {
border.clear().rect(0, 0, ARENA.width, ARENA.height).stroke({ width: 1, color: colors.border, alpha: 0.6 });
particles.forEach((particle, i) => {
particle.tint = i % 10 === 0 ? colors.scout : colors.swarm;
});
layer.update(); // re-upload the static tint
};
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 tick: Tick = { seconds: 0, time: 0 };
let systemMs = 0;
let frames = 0;
let sinceReport = 0;
const frame = (seconds: number) => {
tick.seconds = seconds;
tick.time += seconds;
const started = performance.now();
systems(world, tick);
systemMs += performance.now() - started;
frames++;
};
const report = () => {
const ms = frames > 0 ? systemMs / frames : 0;
setStatus(READOUT[lang](getWorldSize(world).toLocaleString(lang), ms.toFixed(2)));
systemMs = 0;
frames = 0;
};
paint();
frame(0); // the first frame is drawn even if the demo never plays (reduced motion)
report();
return {
update(deltaMS) {
frame(Math.min(deltaMS, MAX_STEP_MS) / 1000);
sinceReport += deltaMS;
if (sinceReport >= REPORT_EVERY_MS) {
sinceReport = 0;
report();
}
},
onThemeChange() {
colors = readColors(cssColor);
paint();
},
dispose() {
app.renderer.off('resize', fit);
destroyWorld(world);
arena.destroy({ children: true });
texture.destroy(true);
},
};
}
World
└── Archetype Table(每種 component 組合一張表)
└── TypedArray 欄位(SoA:同類型資料連續存放)
Entity 重用 EntityId 的 generation bits(ABA 安全)
  • defineComponent:定義一個 SoA component,欄位型別用 Types.f32 / i32 / u32 / f64 等
  • defineQuery:宣告查詢,回傳可在 forEachEntityIndexed 中使用的 query 物件
  • pipe:將多個 system 串成一條執行管線
  • forEachEntityIndexed:推薦的欄位走訪 API,callback 同時提供 e(EntityId)與 i(欄位下標)
Subpath 用途
aiecsjs 核心 API
aiecsjs/loop createLoop() 固定步長迴圈
aiecsjs/commands createCommandBuffer()、flush()、withCommandBuffer(),延遲 structural change
aiecsjs/observers onAdd / onRemove / onSet / observe 觀察 component 變化(enterQuery / exitQuery 在核心 entry)
aiecsjs/serialize toJSON / fromJSON、serializeWorld / deserializeWorld 與 delta serializer(snapshot 格式 2)
aiecsjs/worker SAB snapshot transport,跨 Worker 傳輸
aiecsjs/relations defineRelation、ChildOf 與 addRelation 等 entity 關係輔助

0.6.0 起 toJSON / serializeWorld 與 delta capture 會寫出格式 2:entity 資料加上一張 component 表(key、種類、SoA 欄位)。所有 loader(fromJSON、deserializeWorld、delta apply()、adoptSnapshot、attachWorld)都會依穩定 key 解析 component(沒有 key 時依建立順序的 id),遇到這個 process 沒定義或種類、欄位不符的 component 會丟出 EcsError。要存檔的 component 都請給一個 key:

import { defineComponent, defineTag, Types } from "aiecsjs";
import { serializeWorld, deserializeWorld } from "aiecsjs/serialize";
const Position = defineComponent({ x: Types.f32, y: Types.f32 }, { key: "position" });
const Player = defineTag({ key: "player" });
const bytes = serializeWorld(world);
const restored = deserializeWorld(bytes); // 或 fromJSON(toJSON(world))
  • key 必須是非空字串;defineObjectComponent(factory, { key }) 也適用。以相同種類與欄位配置再次定義同一個 key(HMR、編輯器重新載入指令碼)會回傳既有的 component,只有配置不同時才丟出 EcsError。
  • 0.5.x 的 snapshot 預設會被拒絕。舊存檔請用 { onUnknownVersion: "best-effort" } 載入一次再重新存檔;確定要丟掉未知 component 的資料時傳入 { onUnknownComponent: "skip" }。完整步驟見 repo 內的 docs/MIGRATION.md。
  • 來自外部的 snapshot 仍應視為不可信輸入。
  • 誤用與不變量錯誤會在任何變更前丟出 EcsError(訊息以 aiecsjs: 開頭,建構子支援 { cause }):非整數的 initialCapacity / maxEntities / indexBits / generationBits、dead entity、未註冊的 component、無效的 component key,以及不是函式的 observer handler、forEachEntity / withCommandBuffer callback、pipe system 與 AoS factory。AoS factory 回傳 null / undefined 也會丟出。
  • addRelation 的 source 或 target 已經不存在時丟出 EcsError;endpoint 可能過期時先用 entityExists 檢查。
  • attachWorld(buffer, { readOnly: true }) 得到的唯讀 world 會拒絕所有 mutator,包含 resetWorld。
  • createLoop 缺少 options 或 onUpdate / onRender 不是函式時丟出 TypeError,fixed / maxSubSteps 無效時丟出 RangeError。
  • 與 aipooljs 搭配:Pool 管理 PixiJS Sprite 物件,ECS 管理資料邏輯
  • 與 aiquadtreejs 搭配:ECS entity 的 AABB 欄位直接 insert 進 quadtree 做廣泛相碰撞查詢
  • 與 aifsmjs 搭配:entity 的行為狀態(idle/walk/attack)存成 FSM snapshot component
  • 與 aibridgejs 搭配:用 aiecsjs/serialize 序列化 world snapshot,再透過 bridge 傳到另一個 context