aiecsjs 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +1 -1
- package/dist/commands.d.ts +1 -1
- package/dist/commands.js +1 -1
- package/dist/commands.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -5
- package/dist/index.d.ts +4 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/observers.cjs +1 -1
- package/dist/observers.cjs.map +1 -1
- package/dist/observers.d.cts +1 -1
- package/dist/observers.d.ts +1 -1
- package/dist/observers.js +1 -1
- package/dist/observers.js.map +1 -1
- package/dist/relations.cjs +1 -1
- package/dist/relations.cjs.map +1 -1
- package/dist/relations.d.cts +1 -1
- package/dist/relations.d.ts +1 -1
- package/dist/relations.js +1 -1
- package/dist/relations.js.map +1 -1
- package/dist/serialize.cjs +1 -1
- package/dist/serialize.cjs.map +1 -1
- package/dist/serialize.d.cts +1 -1
- package/dist/serialize.d.ts +1 -1
- package/dist/serialize.js +1 -1
- package/dist/serialize.js.map +1 -1
- package/dist/{types-Bbv2u6kb.d.cts → types-B3YUJZEg.d.cts} +1 -103
- package/dist/{types-Bbv2u6kb.d.ts → types-B3YUJZEg.d.ts} +1 -103
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/observers.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';function l(e){return new Uint32Array(e)}function p(e,n){let
|
|
1
|
+
'use strict';function l(e){return new Uint32Array(e)}function p(e,n){let t=n>>>5;e[t]=(e[t]??0)|1<<(n&31);}function I(e){for(let n=0;n<e.length;n++)if((e[n]??0)!==0)return false;return true}function g(e,n,t,r,o,i){let s=!o;for(let c=0;c<i;c++){let a=e[c]??0,u=n[c]??0,d=t[c]??0,h=r[c]??0;if((a&u)!==u||(a&h)!==0)return false;!s&&(a&d)!==0&&(s=true);}return s}function m(e){let n=[];for(let t=0;t<e.length;t++){let r=e[t]??0;for(;r!==0;){let o=(t<<5)+A(r);n.push(o),r&=r-1;}}return n}function A(e){return 31-Math.clz32(e&-e)}var Q=new Map;function y(e){let n=Q.get(e.id);if(!n)throw new Error(`aiecsjs: world ${e.id} is destroyed or unknown`);if(n.destroyed)throw new Error(`aiecsjs: world ${e.id} is destroyed`);return n}function f(e,n){let t=e.componentBitFor.get(n.id);if(t!==void 0)return t;if(e.nextComponentBit>=e.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${e.options.maxComponents}`);let r=e.nextComponentBit++;e.componentBitFor.set(n.id,r),e.componentInfoByBit[r]=n;let o;if(n.kind==="soa"){let i={};for(let s of n.fields)i[s.name]=new s.ctor(e.capacity*s.vectorLen);o={kind:"soa",componentId:n.id,bit:r,soa:i};}else n.kind==="aos"?o={kind:"aos",componentId:n.id,bit:r,aos:new Array(e.capacity)}:o={kind:"tag",componentId:n.id,bit:r};return e.componentStorageByBit[r]=o,r}var _=new Map;function x(e){let n=_.get(e.__id);if(!n)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return n}function W(e,n){if(e.queries[n.id]===n&&e.queryMasks.has(n.id))return;let t=e.options.maskWordCount,r=l(t),o=l(t),i=l(t);for(let a of n.all){let u=b(a),d=f(e,u);p(r,d);}for(let a of n.any){let u=b(a),d=f(e,u);p(o,d);}for(let a of n.none){let u=b(a),d=f(e,u);p(i,d);}let s={withMask:r,anyMask:o,noneMask:i,anyHasBits:!I(o)};e.queryMasks.set(n.id,s),e.queries[n.id]=n,e.queryArchetypeCache[n.id]=null,e.queryArchetypeStamp[n.id]=-1;let c=[...m(r),...m(o),...m(i)];for(let a of c){let u=e.bitToQueries.get(a);u||(u=new Set,e.bitToQueries.set(a,u)),u.add(n.id);}n.reactiveKind!=="normal"&&(e.reactiveBuffers.has(n.id)||e.reactiveBuffers.set(n.id,{entered:[],exited:[]}),n.sourceQuery&&W(e,n.sourceQuery));}function j(e,n){if(W(e,n),e.queryArchetypeCache[n.id]&&e.queryArchetypeStamp[n.id]===e.queryVersion)return e.queryArchetypeCache[n.id];let t=e.queryMasks.get(n.id),r=e.options.maskWordCount,o=[];for(let i=0;i<e.archetypes.length;i++){let s=e.archetypes[i];g(s.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,r)&&o.push(i);}return e.queryArchetypeCache[n.id]=o,e.queryArchetypeStamp[n.id]=e.queryVersion,o}function S(e,n){let t=y(e),r=n,o=[];if(r.reactiveKind==="enter"){let s=t.reactiveBuffers.get(r.id);if(s){for(let c of s.entered)o.push(c);s.entered.length=0;}return o}if(r.reactiveKind==="exit"){let s=t.reactiveBuffers.get(r.id);if(s){for(let c of s.exited)o.push(c);s.exited.length=0;}return o}let i=j(t,r);for(let s of i){let c=t.archetypes[s];for(let a=0;a<c.size;a++)o.push(c.entities[a]);}return o}function b(e){throw new Error(`aiecsjs: component id ${e} not registered`);}function ne(e,n,t){return v(e,n,"add",t)}function te(e,n,t){return v(e,n,"remove",t)}function oe(e,n,t){return v(e,n,"set",t)}function re(e,n,t,r){let o=y(e);S(e,n);let i={event:t,componentBit:-1,queryId:n.id,handler:r};return o.observers.push(i),()=>{let s=o.observers.indexOf(i);s>=0&&o.observers.splice(s,1);}}function v(e,n,t,r){let o=y(e),i=x(n),s=o.componentBitFor.get(i.id);s===void 0&&(s=f(o,i));let c={event:t,componentBit:s,queryId:-1,handler:r};return o.observers.push(c),()=>{let a=o.observers.indexOf(c);a>=0&&o.observers.splice(a,1);}}exports.observe=re;exports.onAdd=ne;exports.onRemove=te;exports.onSet=oe;//# sourceMappingURL=observers.cjs.map
|
|
2
2
|
//# sourceMappingURL=observers.cjs.map
|
package/dist/observers.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/bitmask.ts","../src/internal/world.ts","../src/internal/component.ts","../src/internal/query.ts","../src/observers.ts"],"names":["createMask","wordCount","setBit","mask","bit","w","isMaskZero","m","i","matches","withMask","anyMask","noneMask","anyHasBits","words","anyHit","wm","am","nm","listBits","out","word","ctz32","v","worldRegistry","getWorldState","world","state","getOrRegisterComponentBit","info","existing","storage","soa","f","componentInfoById","getComponentInfo","component","ensureQueryRegistered","q","ww","compId","getComponentInfoById","involvedBits","b","s","getQueryArchetypes","list","arch","runQuery","query","buf","e","archIds","id","r","componentId","onAdd","handler","registerComponentObserver","onRemove","onSet","observe","event","entry","idx"],"mappings":"aAEO,SAASA,CAAAA,CAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,CAAAA,CAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,CAAAA,CAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,EAAA,EAC1C,CAuCO,SAASE,CAAAA,CAAWC,CAAAA,CAAyB,CAClD,IAAA,IAASC,EAAI,CAAA,CAAGA,CAAAA,CAAID,CAAAA,CAAE,MAAA,CAAQC,IAAK,GAAA,CAAKD,CAAAA,CAAEC,CAAC,CAAA,EAAK,KAAO,CAAA,CAAG,OAAO,MAAA,CACjE,OAAO,KACT,CAcO,SAASC,CAAAA,CACdN,CAAAA,CACAO,EACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACS,CACT,IAAIC,CAAAA,CAAS,CAACF,CAAAA,CACd,QAASR,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIS,CAAAA,CAAOT,IAAK,CAC9B,IAAME,C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AAAA,CAAO,YAAA,CAAc1D,CAAAA,CAAK,OAAA,CAAS,GAAI,OAAA,CAAAqD,CAAQ,CAAA,CAC9E,OAAA9B,EAAM,SAAA,CAAU,IAAA,CAAKoC,CAAK,CAAA,CACnB,IAAM,CACX,IAAMC,CAAAA,CAAMrC,CAAAA,CAAM,UAAU,OAAA,CAAQoC,CAAK,CAAA,CACrCC,CAAAA,EAAO,GAAGrC,CAAAA,CAAM,SAAA,CAAU,MAAA,CAAOqC,CAAAA,CAAK,CAAC,EAC7C,CACF","file":"observers.cjs","sourcesContent":["// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\n/**\n * Test whether an archetype's mask matches a query.\n * - withMask: all of these bits must be present\n * - anyMask: if anyHasBits, at least one of these bits must be present\n * - noneMask: none of these bits may be present\n */\nexport function matches(\n mask: Uint32Array,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n words: number,\n): boolean {\n let anyHit = !anyHasBits\n for (let w = 0; w < words; w++) {\n const m = mask[w] ?? 0\n const wm = withMask[w] ?? 0\n const am = anyMask[w] ?? 0\n const nm = noneMask[w] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const bit = (w << 5) + ctz32(word)\n out.push(bit)\n word &= word - 1\n }\n }\n return out\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","import { VERSION } from '../version.js'\nimport {\n type World,\n type WorldOptions,\n type ResolvedWorldOptions,\n type WorldState,\n type ArchetypeState,\n type ComponentInfo,\n type WorldComponentStorage,\n type FieldInfo,\n} from './types.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(1, Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex))\n const maxEntities = Math.max(initialCapacity, Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex))\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() { return state.capacity },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new Error(`aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`)\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n const oldCap = state.capacity\n // generations\n const genCtor: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n void oldCap // keep reference for clarity; unused after growth\n}\n\nfunction growSoAColumns(soa: Record<string, any>, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(state: WorldState, mask: Uint32Array): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new Error(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: Record<string, any> = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const base = eid * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAComponent,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldState,\n WorldComponentStorage,\n SoAColumns,\n} from './types.js'\nimport { setBit, clearBit, testBit, cloneMask } from './bitmask.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\nimport { isAliveInternal } from './entity.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema)) {\n let type: keyof typeof TYPE_CTOR\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({} as T))\n const info: ComponentInfo = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info) throw new Error('aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)')\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n writeInitial(state, eid, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n fireRemoveObservers(state, eid, bit)\n\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, eid)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[eid] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') return storage.aos?.[eid]\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(state: WorldState, eid: number, component: ComponentLike, initial: unknown): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[eid] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = eid * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[eid]\n if (inst === undefined) {\n inst = factory()\n storage.aos[eid] = inst\n }\n if (initial && typeof initial === 'object') {\n Object.assign(inst as object, initial as object)\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const base = (eid as number) * wordCount\n for (let wi = 0; wi < wordCount; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, eid as number)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[eid as number] = undefined\n }\n word &= word - 1\n }\n }\n}\n\nfunction migrateEntity(state: WorldState, eid: number, newMask: Uint32Array): void {\n const srcArchId = state.entityArchetype[eid] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src\n const row = srcArch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(eid)\n srcArch.size--\n }\n\n // Append to dest\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = eid\n destArch.entityRow.set(eid, newRow)\n destArch.size++\n\n state.entityArchetype[eid] = destArchId\n }\n\n writeEntityMask(state, eid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (state: WorldState, eid: EntityId, bit: number, prev: Uint32Array, next: Uint32Array) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(state: WorldState, eid: number, bit: number, prev: Uint32Array, next: Uint32Array): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","import type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport { createMask, matches, setBit, testBit, isMaskZero, listBits } from './bitmask.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\nimport { getComponentInfo } from './component.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n const any = (d.any ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n const none = (d.none ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map(c => c.__id),\n any: (desc.any ?? []).map(c => c.__id),\n none: (desc.none ?? []).map(c => c.__id),\n withMask: createMask(8),\n anyMask: createMask(8),\n noneMask: createMask(8),\n anyHasBits: (desc.any ?? []).length > 0,\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n withMask: createMask(8),\n anyMask: createMask(8),\n noneMask: createMask(8),\n anyHasBits: q.anyHasBits,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n withMask: createMask(8),\n anyMask: createMask(8),\n noneMask: createMask(8),\n anyHasBits: q.anyHasBits,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n q.withMask = withMask\n q.anyMask = anyMask\n q.noneMask = noneMask\n q.anyHasBits = !isMaskZero(anyMask)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [...listBits(withMask), ...listBits(anyMask), ...listBits(noneMask)]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (\n state.queryArchetypeCache[q.id] &&\n state.queryArchetypeStamp[q.id] === state.queryVersion\n ) {\n return state.queryArchetypeCache[q.id]!\n }\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (matches(arch.mask, q.withMask, q.anyMask, q.noneMask, q.anyHasBits, words)) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(fn: (eid: EntityId, ...cols: any[]) => void, eid: EntityId, cols: any[]): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0: fn(eid); break\n case 1: fn(eid, cols[0]); break\n case 2: fn(eid, cols[0], cols[1]); break\n case 3: fn(eid, cols[0], cols[1], cols[2]); break\n case 4: fn(eid, cols[0], cols[1], cols[2], cols[3]); break\n case 5: fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4]); break\n default: fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) { out.push(undefined); continue }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const wasMatch = matches(prevMask, q.withMask, q.anyMask, q.noneMask, q.anyHasBits, words)\n const isMatch = matches(nextMask, q.withMask, q.anyMask, q.noneMask, q.anyHasBits, words)\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(state: WorldState, queryId: number, kind: 'enter' | 'exit', eid: EntityId): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n","// aiecsjs/observers — observe component add/remove/set events.\n\nimport type {\n ComponentLike,\n EntityId,\n ObserverEntry,\n ObserverEvent,\n Query,\n QueryInternal,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getWorldState, getOrRegisterComponentBit } from './internal/world.js'\nimport {\n registerObserverDispatch,\n getComponentInfo,\n} from './internal/component.js'\nimport { runQuery } from './internal/query.js'\nimport { registerObserversAPI } from './internal/entity.js'\nimport { matches } from './internal/bitmask.js'\n\nexport function onAdd(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n): () => void {\n return registerComponentObserver(world, component, 'add', handler)\n}\n\nexport function onRemove(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n): () => void {\n return registerComponentObserver(world, component, 'remove', handler)\n}\n\nexport function onSet<C extends ComponentLike>(\n world: World,\n component: C,\n handler: (eid: EntityId, value: unknown) => void,\n): () => void {\n return registerComponentObserver(world, component, 'set', handler)\n}\n\nexport function observe(\n world: World,\n query: Query,\n event: ObserverEvent,\n handler: (eid: EntityId) => void,\n): () => void {\n const state = getWorldState(world)\n // Force registration of the query into this world so dispatch can find it.\n runQuery(world, query)\n const entry: ObserverEntry = {\n event,\n componentBit: -1,\n queryId: (query as QueryInternal).id,\n handler: handler as (eid: EntityId, value?: unknown) => void,\n }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\nfunction registerComponentObserver(\n world: World,\n component: ComponentLike,\n event: ObserverEvent,\n handler: (eid: EntityId, value?: unknown) => void,\n): () => void {\n const state = getWorldState(world)\n const info = getComponentInfo(component)\n let bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n bit = getOrRegisterComponentBit(state, info)\n }\n const entry: ObserverEntry = { event, componentBit: bit, queryId: -1, handler }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\n// --- Dispatch impls (wired into component.ts) ---\n\nfunction fireAdd(state: WorldState, eid: EntityId, bit: number): void {\n // Component-targeted observers\n for (const obs of state.observers) {\n if (obs.event !== 'add') continue\n if (obs.componentBit === bit) obs.handler(eid)\n }\n // Query-targeted observers: check if the entity's mask now matches the query\n // (uses the post-mutation mask, which the caller already wrote)\n dispatchQueryObservers(state, eid, 'add', /*prev*/null, /*current*/true)\n}\n\nfunction fireRemove(state: WorldState, eid: EntityId, bit: number): void {\n for (const obs of state.observers) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit === bit) obs.handler(eid)\n }\n dispatchQueryObservers(state, eid, 'remove', /*prev*/true, /*current*/null)\n}\n\nfunction fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void {\n for (const obs of state.observers) {\n if (obs.event !== 'set') continue\n if (obs.componentBit === bit) obs.handler(eid, value)\n else if (obs.queryId !== -1) {\n const q = state.queries[obs.queryId]\n if (q && q.all.includes(state.componentInfoByBit[bit]?.id ?? -1)) {\n obs.handler(eid, value)\n }\n }\n }\n}\n\n// Helper: when a component changes, walk query observers to see if their query\n// match status changed. For simplicity, we re-check each query observer's query\n// against the entity's current mask.\nfunction dispatchQueryObservers(\n state: WorldState,\n eid: EntityId,\n event: 'add' | 'remove',\n _prev: unknown,\n _current: unknown,\n): void {\n // Use entityMask directly\n const w = state.options.maskWordCount\n const base = (eid as number) * w\n const tmpMask = new Uint32Array(w)\n for (let i = 0; i < w; i++) tmpMask[i] = state.entityMask[base + i] ?? 0\n for (const obs of state.observers) {\n if (obs.event !== event) continue\n if (obs.queryId === -1) continue\n const q = state.queries[obs.queryId]\n if (!q) continue\n const isMatch = matches(tmpMask, q.withMask, q.anyMask, q.noneMask, q.anyHasBits, w)\n // For 'add' event, fire if newly matched. For 'remove', fire if newly unmatched.\n // We approximate \"newly\" by always firing on event when match status agrees;\n // duplicates are acceptable for 0.1 query observers.\n if (event === 'add' && isMatch) obs.handler(eid)\n if (event === 'remove' && !isMatch) obs.handler(eid)\n }\n}\n\n// Wire the dispatch into component.ts\nregisterObserverDispatch({ fireAdd, fireRemove, fireSet })\n\n// Register destroy hook so onRemove fires for every component on destroy\nregisterObserversAPI({\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void {\n // Walk every bit currently set in the entity's mask\n const w = state.options.maskWordCount\n const base = (eid as number) * w\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n for (const obs of state.observers) {\n if (obs.event === 'remove' && obs.componentBit === bit) obs.handler(eid)\n }\n word &= word - 1\n }\n }\n },\n})\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/bitmask.ts","../src/internal/world.ts","../src/internal/component.ts","../src/internal/query.ts","../src/observers.ts"],"names":["createMask","wordCount","setBit","mask","bit","w","isMaskZero","m","i","matches","withMask","anyMask","noneMask","anyHasBits","words","anyHit","wm","am","nm","listBits","out","word","ctz32","v","worldRegistry","getWorldState","world","state","getOrRegisterComponentBit","info","existing","storage","soa","f","componentInfoById","getComponentInfo","component","ensureQueryRegistered","q","ww","compId","getComponentInfoById","bundle","involvedBits","b","s","getQueryArchetypes","list","arch","runQuery","query","buf","e","archIds","id","r","componentId","onAdd","handler","registerComponentObserver","onRemove","onSet","observe","event","entry","idx"],"mappings":"aAEO,SAASA,EAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,YAAYA,CAAS,CAClC,CAEO,SAASC,EAAOC,CAAAA,CAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,IAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,EAAKE,CAAC,CAAA,EAAK,CAAA,EAAM,CAAA,GAAMD,EAAM,EAAA,EAC1C,CAuCO,SAASE,CAAAA,CAAWC,EAAyB,CAClD,IAAA,IAASC,EAAI,CAAA,CAAGA,CAAAA,CAAID,EAAE,MAAA,CAAQC,CAAAA,EAAAA,CAAK,GAAA,CAAKD,CAAAA,CAAEC,CAAC,CAAA,EAAK,CAAA,IAAO,CAAA,CAAG,OAAO,OACjE,OAAO,KACT,CAcO,SAASC,EACdN,CAAAA,CACAO,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACS,CACT,IAAIC,CAAAA,CAAS,CAACF,EACd,IAAA,IAASR,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIS,EAAOT,CAAAA,EAAAA,CAAK,CAC9B,IAAME,CAAAA,CAAIJ,EAAKE,CAAC,CAAA,EAAK,EACfW,CAAAA,CAAKN,CAAAA,CAASL,CAAC,CAAA,EAAK,CAAA,CACpBY,CAAAA,CAAKN,CAAAA,CAAQN,CAAC,CAAA,EAAK,CAAA,CACnBa,CAAAA,CAAKN,CAAAA,CAASP,CAAC,CAAA,EAAK,CAAA,CAE1B,GAAA,CADKE,CAAAA,CAAIS,KAAQA,CAAAA,EAAAA,CACZT,CAAAA,CAAIW,KAAQ,CAAA,CAAG,OAAO,OACv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AM,SAAA,CAAU,MAAA,CAAOsC,EAAK,CAAC,EAC7C,CACF","file":"observers.cjs","sourcesContent":["// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\n/**\n * Test whether an archetype's mask matches a query.\n * - withMask: all of these bits must be present\n * - anyMask: if anyHasBits, at least one of these bits must be present\n * - noneMask: none of these bits may be present\n */\nexport function matches(\n mask: Uint32Array,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n words: number,\n): boolean {\n let anyHit = !anyHasBits\n for (let w = 0; w < words; w++) {\n const m = mask[w] ?? 0\n const wm = withMask[w] ?? 0\n const am = anyMask[w] ?? 0\n const nm = noneMask[w] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const bit = (w << 5) + ctz32(word)\n out.push(bit)\n word &= word - 1\n }\n }\n return out\n}\n\n// Iterate set bits in a slice of a larger Uint32Array starting at `base`.\n// Shared by destroy paths and storage cleanup so the bit-extraction maths\n// lives in exactly one place.\nexport function forEachSetBit(\n mask: Uint32Array,\n base: number,\n words: number,\n fn: (bit: number) => void,\n): void {\n for (let wi = 0; wi < words; wi++) {\n let word = mask[base + wi] ?? 0\n while (word !== 0) {\n const bit = (wi << 5) + ctz32(word)\n fn(bit)\n word &= word - 1\n }\n }\n}\n\n// Match a query against an entity's mask stored as a slice inside a larger\n// Uint32Array. Reading directly from the parent array avoids the temporary\n// Uint32Array allocation on every observer dispatch.\nexport function matchesEntityMask(\n entityMask: Uint32Array,\n base: number,\n words: number,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n): boolean {\n let anyHit = !anyHasBits\n for (let i = 0; i < words; i++) {\n const m = entityMask[base + i] ?? 0\n const wm = withMask[i] ?? 0\n const am = anyMask[i] ?? 0\n const nm = noneMask[i] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","import { VERSION } from '../version.js'\nimport {\n type World,\n type WorldOptions,\n type ResolvedWorldOptions,\n type WorldState,\n type ArchetypeState,\n type ComponentInfo,\n type WorldComponentStorage,\n type FieldInfo,\n} from './types.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(1, Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex))\n const maxEntities = Math.max(initialCapacity, Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex))\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryMasks: new Map(),\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() { return state.capacity },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryMasks.clear()\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new Error(`aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`)\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n // generations\n const genCtor: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n}\n\nfunction growSoAColumns(soa: Record<string, any>, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(state: WorldState, mask: Uint32Array): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new Error(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: Record<string, any> = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const base = eid * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAComponent,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldState,\n WorldComponentStorage,\n SoAColumns,\n} from './types.js'\nimport { setBit, clearBit, testBit, cloneMask, forEachSetBit } from './bitmask.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\nimport { isAliveInternal } from './entity.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema)) {\n let type: keyof typeof TYPE_CTOR\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({} as T))\n const info: ComponentInfo = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info) throw new Error('aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)')\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n writeInitial(state, eid, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n fireRemoveObservers(state, eid, bit)\n\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, eid)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[eid] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') return storage.aos?.[eid]\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(state: WorldState, eid: number, component: ComponentLike, initial: unknown): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[eid] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = eid * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[eid]\n if (inst === undefined) {\n inst = factory()\n storage.aos[eid] = inst\n }\n if (initial && typeof initial === 'object') {\n Object.assign(inst as object, initial as object)\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const idx = eid as number\n const base = idx * wordCount\n forEachSetBit(state.entityMask, base, wordCount, (bit) => {\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n })\n}\n\nfunction migrateEntity(state: WorldState, eid: number, newMask: Uint32Array): void {\n const srcArchId = state.entityArchetype[eid] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src\n const row = srcArch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(eid)\n srcArch.size--\n }\n\n // Append to dest\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = eid\n destArch.entityRow.set(eid, newRow)\n destArch.size++\n\n state.entityArchetype[eid] = destArchId\n }\n\n writeEntityMask(state, eid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (state: WorldState, eid: EntityId, bit: number, prev: Uint32Array, next: Uint32Array) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(state: WorldState, eid: number, bit: number, prev: Uint32Array, next: Uint32Array): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","import type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport { createMask, matches, setBit, isMaskZero, listBits } from './bitmask.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\nimport { getComponentInfo } from './component.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n const any = (d.any ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n const none = (d.none ?? []).map(c => c.__id).sort((a, b) => a - b).join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map(c => c.__id),\n any: (desc.any ?? []).map(c => c.__id),\n none: (desc.none ?? []).map(c => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [...listBits(withMask), ...listBits(anyMask), ...listBits(noneMask)]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (\n state.queryArchetypeCache[q.id] &&\n state.queryArchetypeStamp[q.id] === state.queryVersion\n ) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n const ents = arch.entities\n const n = arch.size\n for (let r = 0; r < n; r++) {\n callWithCols(fn, ents[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(fn: (eid: EntityId, ...cols: any[]) => void, eid: EntityId, cols: any[]): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0: fn(eid); break\n case 1: fn(eid, cols[0]); break\n case 2: fn(eid, cols[0], cols[1]); break\n case 3: fn(eid, cols[0], cols[1], cols[2]); break\n case 4: fn(eid, cols[0], cols[1], cols[2], cols[3]); break\n case 5: fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4]); break\n default: fn(eid, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) { out.push(undefined); continue }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(prevMask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n const isMatch = matches(nextMask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(state: WorldState, queryId: number, kind: 'enter' | 'exit', eid: EntityId): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n","// aiecsjs/observers — observe component add/remove/set events.\n\nimport type {\n ComponentLike,\n EntityId,\n ObserverEntry,\n ObserverEvent,\n Query,\n QueryInternal,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getWorldState, getOrRegisterComponentBit } from './internal/world.js'\nimport {\n registerObserverDispatch,\n getComponentInfo,\n} from './internal/component.js'\nimport { runQuery } from './internal/query.js'\nimport { registerObserversAPI } from './internal/entity.js'\nimport { forEachSetBit, matchesEntityMask } from './internal/bitmask.js'\n\nexport function onAdd(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n): () => void {\n return registerComponentObserver(world, component, 'add', handler)\n}\n\nexport function onRemove(\n world: World,\n component: ComponentLike,\n handler: (eid: EntityId) => void,\n): () => void {\n return registerComponentObserver(world, component, 'remove', handler)\n}\n\nexport function onSet<C extends ComponentLike>(\n world: World,\n component: C,\n handler: (eid: EntityId, value: unknown) => void,\n): () => void {\n return registerComponentObserver(world, component, 'set', handler)\n}\n\nexport function observe(\n world: World,\n query: Query,\n event: ObserverEvent,\n handler: (eid: EntityId) => void,\n): () => void {\n const state = getWorldState(world)\n // Force registration of the query into this world so dispatch can find it.\n runQuery(world, query)\n const entry: ObserverEntry = {\n event,\n componentBit: -1,\n queryId: (query as QueryInternal).id,\n handler: handler as (eid: EntityId, value?: unknown) => void,\n }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\nfunction registerComponentObserver(\n world: World,\n component: ComponentLike,\n event: ObserverEvent,\n handler: (eid: EntityId, value?: unknown) => void,\n): () => void {\n const state = getWorldState(world)\n const info = getComponentInfo(component)\n let bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n bit = getOrRegisterComponentBit(state, info)\n }\n const entry: ObserverEntry = { event, componentBit: bit, queryId: -1, handler }\n state.observers.push(entry)\n return () => {\n const idx = state.observers.indexOf(entry)\n if (idx >= 0) state.observers.splice(idx, 1)\n }\n}\n\n// --- Dispatch impls (wired into component.ts) ---\n\nfunction fireAdd(state: WorldState, eid: EntityId, bit: number): void {\n // Component-targeted observers\n for (const obs of state.observers) {\n if (obs.event !== 'add') continue\n if (obs.componentBit === bit) obs.handler(eid)\n }\n // Query-targeted observers: check if the entity's mask now matches the query\n // (uses the post-mutation mask, which the caller already wrote)\n dispatchQueryObservers(state, eid, 'add', /*prev*/null, /*current*/true)\n}\n\nfunction fireRemove(state: WorldState, eid: EntityId, bit: number): void {\n for (const obs of state.observers) {\n if (obs.event !== 'remove') continue\n if (obs.componentBit === bit) obs.handler(eid)\n }\n dispatchQueryObservers(state, eid, 'remove', /*prev*/true, /*current*/null)\n}\n\nfunction fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void {\n for (const obs of state.observers) {\n if (obs.event !== 'set') continue\n if (obs.componentBit === bit) obs.handler(eid, value)\n else if (obs.queryId !== -1) {\n const q = state.queries[obs.queryId]\n if (q && q.all.includes(state.componentInfoByBit[bit]?.id ?? -1)) {\n obs.handler(eid, value)\n }\n }\n }\n}\n\n// Helper: when a component changes, walk query observers to see if their query\n// match status changed. For simplicity, we re-check each query observer's query\n// against the entity's current mask. Reads state.entityMask in place — the\n// per-call Uint32Array allocation that used to live here is gone.\nfunction dispatchQueryObservers(\n state: WorldState,\n eid: EntityId,\n event: 'add' | 'remove',\n _prev: unknown,\n _current: unknown,\n): void {\n const w = state.options.maskWordCount\n const base = (eid as number) * w\n for (const obs of state.observers) {\n if (obs.event !== event) continue\n if (obs.queryId === -1) continue\n const bundle = state.queryMasks.get(obs.queryId)\n if (!bundle) continue\n const isMatch = matchesEntityMask(\n state.entityMask, base, w,\n bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits,\n )\n // For 'add' event, fire if newly matched. For 'remove', fire if newly unmatched.\n // We approximate \"newly\" by always firing on event when match status agrees;\n // duplicates are acceptable for 0.1 query observers.\n if (event === 'add' && isMatch) obs.handler(eid)\n if (event === 'remove' && !isMatch) obs.handler(eid)\n }\n}\n\n// Wire the dispatch into component.ts\nregisterObserverDispatch({ fireAdd, fireRemove, fireSet })\n\n// Register destroy hook so onRemove fires for every component on destroy\nregisterObserversAPI({\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void {\n // Walk every bit currently set in the entity's mask\n const w = state.options.maskWordCount\n const base = (eid as number) * w\n forEachSetBit(state.entityMask, base, w, (bit) => {\n for (const obs of state.observers) {\n if (obs.event === 'remove' && obs.componentBit === bit) obs.handler(eid)\n }\n })\n },\n})\n"]}
|
package/dist/observers.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as World, Q as Query, O as ObserverEvent, E as EntityId, c as ComponentLike } from './types-
|
|
1
|
+
import { W as World, Q as Query, O as ObserverEvent, E as EntityId, c as ComponentLike } from './types-B3YUJZEg.cjs';
|
|
2
2
|
|
|
3
3
|
declare function onAdd(world: World, component: ComponentLike, handler: (eid: EntityId) => void): () => void;
|
|
4
4
|
declare function onRemove(world: World, component: ComponentLike, handler: (eid: EntityId) => void): () => void;
|
package/dist/observers.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as World, Q as Query, O as ObserverEvent, E as EntityId, c as ComponentLike } from './types-
|
|
1
|
+
import { W as World, Q as Query, O as ObserverEvent, E as EntityId, c as ComponentLike } from './types-B3YUJZEg.js';
|
|
2
2
|
|
|
3
3
|
declare function onAdd(world: World, component: ComponentLike, handler: (eid: EntityId) => void): () => void;
|
|
4
4
|
declare function onRemove(world: World, component: ComponentLike, handler: (eid: EntityId) => void): () => void;
|
package/dist/observers.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function l(e){return new Uint32Array(e)}function p(e,n){let
|
|
1
|
+
function l(e){return new Uint32Array(e)}function p(e,n){let t=n>>>5;e[t]=(e[t]??0)|1<<(n&31);}function I(e){for(let n=0;n<e.length;n++)if((e[n]??0)!==0)return false;return true}function g(e,n,t,r,o,i){let s=!o;for(let c=0;c<i;c++){let a=e[c]??0,u=n[c]??0,d=t[c]??0,h=r[c]??0;if((a&u)!==u||(a&h)!==0)return false;!s&&(a&d)!==0&&(s=true);}return s}function m(e){let n=[];for(let t=0;t<e.length;t++){let r=e[t]??0;for(;r!==0;){let o=(t<<5)+A(r);n.push(o),r&=r-1;}}return n}function A(e){return 31-Math.clz32(e&-e)}var Q=new Map;function y(e){let n=Q.get(e.id);if(!n)throw new Error(`aiecsjs: world ${e.id} is destroyed or unknown`);if(n.destroyed)throw new Error(`aiecsjs: world ${e.id} is destroyed`);return n}function f(e,n){let t=e.componentBitFor.get(n.id);if(t!==void 0)return t;if(e.nextComponentBit>=e.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${e.options.maxComponents}`);let r=e.nextComponentBit++;e.componentBitFor.set(n.id,r),e.componentInfoByBit[r]=n;let o;if(n.kind==="soa"){let i={};for(let s of n.fields)i[s.name]=new s.ctor(e.capacity*s.vectorLen);o={kind:"soa",componentId:n.id,bit:r,soa:i};}else n.kind==="aos"?o={kind:"aos",componentId:n.id,bit:r,aos:new Array(e.capacity)}:o={kind:"tag",componentId:n.id,bit:r};return e.componentStorageByBit[r]=o,r}var _=new Map;function x(e){let n=_.get(e.__id);if(!n)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return n}function W(e,n){if(e.queries[n.id]===n&&e.queryMasks.has(n.id))return;let t=e.options.maskWordCount,r=l(t),o=l(t),i=l(t);for(let a of n.all){let u=b(a),d=f(e,u);p(r,d);}for(let a of n.any){let u=b(a),d=f(e,u);p(o,d);}for(let a of n.none){let u=b(a),d=f(e,u);p(i,d);}let s={withMask:r,anyMask:o,noneMask:i,anyHasBits:!I(o)};e.queryMasks.set(n.id,s),e.queries[n.id]=n,e.queryArchetypeCache[n.id]=null,e.queryArchetypeStamp[n.id]=-1;let c=[...m(r),...m(o),...m(i)];for(let a of c){let u=e.bitToQueries.get(a);u||(u=new Set,e.bitToQueries.set(a,u)),u.add(n.id);}n.reactiveKind!=="normal"&&(e.reactiveBuffers.has(n.id)||e.reactiveBuffers.set(n.id,{entered:[],exited:[]}),n.sourceQuery&&W(e,n.sourceQuery));}function j(e,n){if(W(e,n),e.queryArchetypeCache[n.id]&&e.queryArchetypeStamp[n.id]===e.queryVersion)return e.queryArchetypeCache[n.id];let t=e.queryMasks.get(n.id),r=e.options.maskWordCount,o=[];for(let i=0;i<e.archetypes.length;i++){let s=e.archetypes[i];g(s.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,r)&&o.push(i);}return e.queryArchetypeCache[n.id]=o,e.queryArchetypeStamp[n.id]=e.queryVersion,o}function S(e,n){let t=y(e),r=n,o=[];if(r.reactiveKind==="enter"){let s=t.reactiveBuffers.get(r.id);if(s){for(let c of s.entered)o.push(c);s.entered.length=0;}return o}if(r.reactiveKind==="exit"){let s=t.reactiveBuffers.get(r.id);if(s){for(let c of s.exited)o.push(c);s.exited.length=0;}return o}let i=j(t,r);for(let s of i){let c=t.archetypes[s];for(let a=0;a<c.size;a++)o.push(c.entities[a]);}return o}function b(e){throw new Error(`aiecsjs: component id ${e} not registered`);}function ne(e,n,t){return v(e,n,"add",t)}function te(e,n,t){return v(e,n,"remove",t)}function oe(e,n,t){return v(e,n,"set",t)}function re(e,n,t,r){let o=y(e);S(e,n);let i={event:t,componentBit:-1,queryId:n.id,handler:r};return o.observers.push(i),()=>{let s=o.observers.indexOf(i);s>=0&&o.observers.splice(s,1);}}function v(e,n,t,r){let o=y(e),i=x(n),s=o.componentBitFor.get(i.id);s===void 0&&(s=f(o,i));let c={event:t,componentBit:s,queryId:-1,handler:r};return o.observers.push(c),()=>{let a=o.observers.indexOf(c);a>=0&&o.observers.splice(a,1);}}export{re as observe,ne as onAdd,te as onRemove,oe as onSet};//# sourceMappingURL=observers.js.map
|
|
2
2
|
//# sourceMappingURL=observers.js.map
|