aiecsjs 0.1.1
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 +102 -0
- package/LICENSE +21 -0
- package/README.md +881 -0
- package/README_ZHTW.md +891 -0
- package/STABILITY.md +145 -0
- package/STABILITY_ZHTW.md +145 -0
- package/api.json +1087 -0
- package/dist/commands.cjs +2 -0
- package/dist/commands.cjs.map +1 -0
- package/dist/commands.d.cts +7 -0
- package/dist/commands.d.ts +7 -0
- package/dist/commands.js +2 -0
- package/dist/commands.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +43 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/loop.cjs +2 -0
- package/dist/loop.cjs.map +1 -0
- package/dist/loop.d.cts +13 -0
- package/dist/loop.d.ts +13 -0
- package/dist/loop.js +2 -0
- package/dist/loop.js.map +1 -0
- package/dist/observers.cjs +2 -0
- package/dist/observers.cjs.map +1 -0
- package/dist/observers.d.cts +8 -0
- package/dist/observers.d.ts +8 -0
- package/dist/observers.js +2 -0
- package/dist/observers.js.map +1 -0
- package/dist/relations.cjs +2 -0
- package/dist/relations.cjs.map +1 -0
- package/dist/relations.d.cts +11 -0
- package/dist/relations.d.ts +11 -0
- package/dist/relations.js +2 -0
- package/dist/relations.js.map +1 -0
- package/dist/serialize.cjs +2 -0
- package/dist/serialize.cjs.map +1 -0
- package/dist/serialize.d.cts +9 -0
- package/dist/serialize.d.ts +9 -0
- package/dist/serialize.js +2 -0
- package/dist/serialize.js.map +1 -0
- package/dist/types-Bbv2u6kb.d.cts +227 -0
- package/dist/types-Bbv2u6kb.d.ts +227 -0
- package/dist/worker.cjs +2 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.cts +10 -0
- package/dist/worker.d.ts +10 -0
- package/dist/worker.js +2 -0
- package/dist/worker.js.map +1 -0
- package/docs/MIGRATION.md +252 -0
- package/docs/MIGRATION_ZHTW.md +252 -0
- package/llms-full.txt +579 -0
- package/llms.txt +31 -0
- package/package.json +93 -0
|
@@ -0,0 +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,CAA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E,CAAI,CAAA,CAAA,CAE7C,IAAMkC,CAAAA,CAAuB,CAAE,MAAAD,CAAAA,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.js","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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var f=new Map;function d(o){let i=f.get(o.id);if(!i)throw new Error(`aiecsjs: world ${o.id} is destroyed or unknown`);if(i.destroyed)throw new Error(`aiecsjs: world ${o.id} is destroyed`);return i}var m=1;function g(o){return {__kind:"relation",__id:m++,__exclusive:o?.exclusive??false,__hasData:false}}var W=g({exclusive:true});function x(o,i){let r=o.relationStorage.get(i.__id);return r||(r={rel:i,exclusive:i.__exclusive?new Int32Array(o.capacity).fill(-1):null,outgoing:new Map,data:new Map},o.relationStorage.set(i.__id,r),r)}function I(o,i,r,s,t){let n=d(o);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=x(n,r),c=i,l=s;if(e.exclusive){if(c>=e.exclusive.length){let a=new Int32Array(Math.max(c+1,e.exclusive.length*2)).fill(-1);a.set(e.exclusive),e.exclusive=a;}e.exclusive[c]=l;}else {let a=e.outgoing.get(c);a||(a=[],e.outgoing.set(c,a)),a.includes(l)||a.push(l);}if(t!==void 0){let a=c*n.capacity+l;e.data.set(a,t);}}function E(o,i,r,s){let t=d(o);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let n=t.relationStorage.get(r.__id);if(!n)return;let e=i,c=s;if(n.exclusive)e<n.exclusive.length&&n.exclusive[e]===c&&(n.exclusive[e]=-1);else {let a=n.outgoing.get(e);if(a){let u=a.indexOf(c);u>=0&&a.splice(u,1),a.length===0&&n.outgoing.delete(e);}}let l=e*t.capacity+c;n.data.delete(l);}function A(o,i,r){let t=d(o).relationStorage.get(r.__id);if(!t)return [];let n=i;if(t.exclusive){if(n<t.exclusive.length){let c=t.exclusive[n]??-1;return c>=0?[c]:[]}return []}let e=t.outgoing.get(n);return e||[]}exports.ChildOf=W;exports.addRelation=I;exports.defineRelation=g;exports.getRelationTargets=A;exports.removeRelation=E;//# sourceMappingURL=relations.cjs.map
|
|
2
|
+
//# sourceMappingURL=relations.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/world.ts","../src/relations.ts"],"names":["worldRegistry","getWorldState","world","state","nextRelationId","defineRelation","options","ChildOf","getOrCreateStorage","rel","storage","addRelation","source","target","data","src","tgt","next","list","key","removeRelation","idx","getRel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IAAMC,CAAAA,CADQT,CAAAA,CAAcC,CAAK,CAAA,CACX,eAAA,CAAgB,GAAA,CAAIO,CAAAA,CAAI,IAAI,EAClD,GAAI,CAACC,CAAAA,CAAS,OAAO,EAAC,CACtB,IAAMK,CAAAA,CAAMH,CAAAA,CACZ,GAAIF,CAAAA,CAAQ,SAAA,CAAW,CACrB,GAAIK,CAAAA,CAAML,CAAAA,CAAQ,SAAA,CAAU,MAAA,CAAQ,CAClC,IAAMM,CAAAA,CAAMN,CAAAA,CAAQ,SAAA,CAAUK,CAAG,CAAA,EAAK,EAAA,CACtC,OAAOC,CAAAA,EAAO,CAAA,CAAI,CAACA,CAAe,CAAA,CAAI,EACxC,CACA,OAAO,EACT,CACA,IAAME,CAAAA,CAAOR,CAAAA,CAAQ,QAAA,CAAS,GAAA,CAAIK,CAAG,CAAA,CACrC,OAAKG,CAAAA,EAAa,EAEpB","file":"relations.cjs","sourcesContent":["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","// aiecsjs/relations — entity-to-entity relations (experimental in 0.1).\n\nimport type {\n EntityId,\n Relation,\n RelationStorage,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\nimport { registerRelationsCleanup } from './internal/entity.js'\n\nlet nextRelationId = 1\n\nexport function defineRelation<T = void>(options?: { exclusive?: boolean }): Relation<T> {\n const id = nextRelationId++\n return {\n __kind: 'relation',\n __id: id,\n __exclusive: options?.exclusive ?? false,\n __hasData: false,\n } as Relation<T>\n}\n\nexport const ChildOf: Relation = defineRelation({ exclusive: true })\n\nfunction getOrCreateStorage(state: WorldState, rel: Relation<any>): RelationStorage {\n let storage = state.relationStorage.get(rel.__id)\n if (storage) return storage\n storage = {\n rel,\n exclusive: rel.__exclusive ? new Int32Array(state.capacity).fill(-1) : null,\n outgoing: new Map<number, number[]>(),\n data: new Map<number, unknown>(),\n }\n state.relationStorage.set(rel.__id, storage)\n return storage\n}\n\nexport function addRelation<T>(\n world: World,\n source: EntityId,\n rel: Relation<T>,\n target: EntityId,\n data?: T,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = getOrCreateStorage(state, rel as Relation<any>)\n const src = source as number\n const tgt = target as number\n\n if (storage.exclusive) {\n if (src >= storage.exclusive.length) {\n const next = new Int32Array(Math.max(src + 1, storage.exclusive.length * 2)).fill(-1)\n next.set(storage.exclusive)\n storage.exclusive = next\n }\n storage.exclusive[src] = tgt\n } else {\n let list = storage.outgoing.get(src)\n if (!list) {\n list = []\n storage.outgoing.set(src, list)\n }\n if (!list.includes(tgt)) list.push(tgt)\n }\n\n if (data !== undefined) {\n const key = src * state.capacity + tgt\n storage.data.set(key, data)\n }\n}\n\nexport function removeRelation(\n world: World,\n source: EntityId,\n rel: Relation,\n target: EntityId,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return\n const src = source as number\n const tgt = target as number\n if (storage.exclusive) {\n if (src < storage.exclusive.length && storage.exclusive[src] === tgt) {\n storage.exclusive[src] = -1\n }\n } else {\n const list = storage.outgoing.get(src)\n if (list) {\n const idx = list.indexOf(tgt)\n if (idx >= 0) list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n const key = src * state.capacity + tgt\n storage.data.delete(key)\n}\n\nexport function getRelationTargets(\n world: World,\n source: EntityId,\n rel: Relation,\n): readonly EntityId[] {\n const state = getWorldState(world)\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return []\n const src = source as number\n if (storage.exclusive) {\n if (src < storage.exclusive.length) {\n const tgt = storage.exclusive[src] ?? -1\n return tgt >= 0 ? [tgt as EntityId] : []\n }\n return []\n }\n const list = storage.outgoing.get(src)\n if (!list) return []\n return list as EntityId[]\n}\n\n// Cleanup hook: when an entity is destroyed, remove all relations involving it.\nregisterRelationsCleanup((state: WorldState, eid: EntityId) => {\n const e = eid as number\n for (const storage of state.relationStorage.values()) {\n if (storage.exclusive) {\n if (e < storage.exclusive.length) storage.exclusive[e] = -1\n // Also clear any references TO this entity as target\n for (let i = 0; i < storage.exclusive.length; i++) {\n if (storage.exclusive[i] === e) storage.exclusive[i] = -1\n }\n }\n storage.outgoing.delete(e)\n for (const [src, list] of storage.outgoing) {\n const idx = list.indexOf(e)\n if (idx >= 0) {\n list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n // Clear data entries involving this entity\n for (const key of Array.from(storage.data.keys())) {\n const srcKey = Math.floor(key / state.capacity)\n const tgtKey = key % state.capacity\n if (srcKey === e || tgtKey === e) storage.data.delete(key)\n }\n }\n})\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { R as Relation, W as World, E as EntityId } from './types-Bbv2u6kb.cjs';
|
|
2
|
+
|
|
3
|
+
declare function defineRelation<T = void>(options?: {
|
|
4
|
+
exclusive?: boolean;
|
|
5
|
+
}): Relation<T>;
|
|
6
|
+
declare const ChildOf: Relation;
|
|
7
|
+
declare function addRelation<T>(world: World, source: EntityId, rel: Relation<T>, target: EntityId, data?: T): void;
|
|
8
|
+
declare function removeRelation(world: World, source: EntityId, rel: Relation, target: EntityId): void;
|
|
9
|
+
declare function getRelationTargets(world: World, source: EntityId, rel: Relation): readonly EntityId[];
|
|
10
|
+
|
|
11
|
+
export { ChildOf, addRelation, defineRelation, getRelationTargets, removeRelation };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { R as Relation, W as World, E as EntityId } from './types-Bbv2u6kb.js';
|
|
2
|
+
|
|
3
|
+
declare function defineRelation<T = void>(options?: {
|
|
4
|
+
exclusive?: boolean;
|
|
5
|
+
}): Relation<T>;
|
|
6
|
+
declare const ChildOf: Relation;
|
|
7
|
+
declare function addRelation<T>(world: World, source: EntityId, rel: Relation<T>, target: EntityId, data?: T): void;
|
|
8
|
+
declare function removeRelation(world: World, source: EntityId, rel: Relation, target: EntityId): void;
|
|
9
|
+
declare function getRelationTargets(world: World, source: EntityId, rel: Relation): readonly EntityId[];
|
|
10
|
+
|
|
11
|
+
export { ChildOf, addRelation, defineRelation, getRelationTargets, removeRelation };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var f=new Map;function d(o){let i=f.get(o.id);if(!i)throw new Error(`aiecsjs: world ${o.id} is destroyed or unknown`);if(i.destroyed)throw new Error(`aiecsjs: world ${o.id} is destroyed`);return i}var m=1;function g(o){return {__kind:"relation",__id:m++,__exclusive:o?.exclusive??false,__hasData:false}}var W=g({exclusive:true});function x(o,i){let r=o.relationStorage.get(i.__id);return r||(r={rel:i,exclusive:i.__exclusive?new Int32Array(o.capacity).fill(-1):null,outgoing:new Map,data:new Map},o.relationStorage.set(i.__id,r),r)}function I(o,i,r,s,t){let n=d(o);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=x(n,r),c=i,l=s;if(e.exclusive){if(c>=e.exclusive.length){let a=new Int32Array(Math.max(c+1,e.exclusive.length*2)).fill(-1);a.set(e.exclusive),e.exclusive=a;}e.exclusive[c]=l;}else {let a=e.outgoing.get(c);a||(a=[],e.outgoing.set(c,a)),a.includes(l)||a.push(l);}if(t!==void 0){let a=c*n.capacity+l;e.data.set(a,t);}}function E(o,i,r,s){let t=d(o);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let n=t.relationStorage.get(r.__id);if(!n)return;let e=i,c=s;if(n.exclusive)e<n.exclusive.length&&n.exclusive[e]===c&&(n.exclusive[e]=-1);else {let a=n.outgoing.get(e);if(a){let u=a.indexOf(c);u>=0&&a.splice(u,1),a.length===0&&n.outgoing.delete(e);}}let l=e*t.capacity+c;n.data.delete(l);}function A(o,i,r){let t=d(o).relationStorage.get(r.__id);if(!t)return [];let n=i;if(t.exclusive){if(n<t.exclusive.length){let c=t.exclusive[n]??-1;return c>=0?[c]:[]}return []}let e=t.outgoing.get(n);return e||[]}export{W as ChildOf,I as addRelation,g as defineRelation,A as getRelationTargets,E as removeRelation};//# sourceMappingURL=relations.js.map
|
|
2
|
+
//# sourceMappingURL=relations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/world.ts","../src/relations.ts"],"names":["worldRegistry","getWorldState","world","state","nextRelationId","defineRelation","options","ChildOf","getOrCreateStorage","rel","storage","addRelation","source","target","data","src","tgt","next","list","key","removeRelation","idx","getRelationTargets"],"mappings":"AAyBA,IAAMA,CAAAA,CAAgB,IAAI,GAAA,CAEnB,SAASC,CAAAA,CAAcC,CAAAA,CAA0B,CACtD,IAAMC,CAAAA,CAAQH,CAAAA,CAAc,GAAA,CAAIE,CAAAA,CAAM,EAAE,CAAA,CACxC,GAAI,CAACC,CAAAA,CAAO,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkBD,CAAAA,CAAM,EAAE,CAAA,wBAAA,CAA0B,CAAA,CAChF,GAAIC,CAAAA,CAAM,SAAA,CAAW,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkBD,CAAAA,CAAM,EAAE,CAAA,aAAA,CAAe,CAAA,CAC9E,OAAOC,CACT,CCpBA,IAAIC,CAAAA,CAAiB,CAAA,CAEd,SAASC,CAAAA,CAAyBC,CAAAA,CAAgD,CAEvF,OAAO,CACL,MAAA,CAAQ,UAAA,CACR,IAAA,CAHSF,IAIT,WAAA,CAAaE,CAAAA,EAAS,SAAA,EAAa,KAAA,CACnC,SAAA,CAAW,KACb,CACF,CAEO,IAAMC,CAAAA,CAAoBF,CAAAA,CAAe,CAAE,SAAA,CAAW,IAAK,CAAC,EAEnE,SAASG,CAAAA,CAAmBL,CAAAA,CAAmBM,CAAAA,CAAqC,CAClF,IAAIC,CAAAA,CAAUP,CAAAA,CAAM,eAAA,CAAgB,GAAA,CAAIM,CAAAA,CAAI,IAAI,CAAA,CAChD,OAAIC,CAAAA,GACJA,CAAAA,CAAU,CACR,GAAA,CAAAD,CAAAA,CACA,SAAA,CAAWA,CAAAA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AAGR,CAAAA,CAAQ,SAAS,MAAA,CAAOK,CAAG,EACpD,CACF,CACA,IAAMI,CAAAA,CAAMJ,CAAAA,CAAMZ,CAAAA,CAAM,QAAA,CAAWa,CAAAA,CACnCN,CAAAA,CAAQ,IAAA,CAAK,MAAA,CAAOS,CAAG,EACzB,CAEO,SAASG,CAAAA,CACdpB,CAAAA,CACAU,CAAAA,CACAH,CAAAA,CACqB,CAErB,IAAMC,CAAAA,CADQT,CAAAA,CAAcC,CAAK,CAAA,CACX,eAAA,CAAgB,GAAA,CAAIO,CAAAA,CAAI,IAAI,EAClD,GAAI,CAACC,CAAAA,CAAS,OAAO,EAAC,CACtB,IAAMK,CAAAA,CAAMH,CAAAA,CACZ,GAAIF,CAAAA,CAAQ,SAAA,CAAW,CACrB,GAAIK,CAAAA,CAAML,CAAAA,CAAQ,SAAA,CAAU,MAAA,CAAQ,CAClC,IAAMM,CAAAA,CAAMN,CAAAA,CAAQ,SAAA,CAAUK,CAAG,CAAA,EAAK,EAAA,CACtC,OAAOC,CAAAA,EAAO,CAAA,CAAI,CAACA,CAAe,CAAA,CAAI,EACxC,CACA,OAAO,EACT,CACA,IAAME,CAAAA,CAAOR,CAAAA,CAAQ,QAAA,CAAS,GAAA,CAAIK,CAAG,CAAA,CACrC,OAAKG,CAAAA,EAAa,EAEpB","file":"relations.js","sourcesContent":["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","// aiecsjs/relations — entity-to-entity relations (experimental in 0.1).\n\nimport type {\n EntityId,\n Relation,\n RelationStorage,\n World,\n WorldState,\n} from './internal/types.js'\nimport { getWorldState } from './internal/world.js'\nimport { registerRelationsCleanup } from './internal/entity.js'\n\nlet nextRelationId = 1\n\nexport function defineRelation<T = void>(options?: { exclusive?: boolean }): Relation<T> {\n const id = nextRelationId++\n return {\n __kind: 'relation',\n __id: id,\n __exclusive: options?.exclusive ?? false,\n __hasData: false,\n } as Relation<T>\n}\n\nexport const ChildOf: Relation = defineRelation({ exclusive: true })\n\nfunction getOrCreateStorage(state: WorldState, rel: Relation<any>): RelationStorage {\n let storage = state.relationStorage.get(rel.__id)\n if (storage) return storage\n storage = {\n rel,\n exclusive: rel.__exclusive ? new Int32Array(state.capacity).fill(-1) : null,\n outgoing: new Map<number, number[]>(),\n data: new Map<number, unknown>(),\n }\n state.relationStorage.set(rel.__id, storage)\n return storage\n}\n\nexport function addRelation<T>(\n world: World,\n source: EntityId,\n rel: Relation<T>,\n target: EntityId,\n data?: T,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = getOrCreateStorage(state, rel as Relation<any>)\n const src = source as number\n const tgt = target as number\n\n if (storage.exclusive) {\n if (src >= storage.exclusive.length) {\n const next = new Int32Array(Math.max(src + 1, storage.exclusive.length * 2)).fill(-1)\n next.set(storage.exclusive)\n storage.exclusive = next\n }\n storage.exclusive[src] = tgt\n } else {\n let list = storage.outgoing.get(src)\n if (!list) {\n list = []\n storage.outgoing.set(src, list)\n }\n if (!list.includes(tgt)) list.push(tgt)\n }\n\n if (data !== undefined) {\n const key = src * state.capacity + tgt\n storage.data.set(key, data)\n }\n}\n\nexport function removeRelation(\n world: World,\n source: EntityId,\n rel: Relation,\n target: EntityId,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return\n const src = source as number\n const tgt = target as number\n if (storage.exclusive) {\n if (src < storage.exclusive.length && storage.exclusive[src] === tgt) {\n storage.exclusive[src] = -1\n }\n } else {\n const list = storage.outgoing.get(src)\n if (list) {\n const idx = list.indexOf(tgt)\n if (idx >= 0) list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n const key = src * state.capacity + tgt\n storage.data.delete(key)\n}\n\nexport function getRelationTargets(\n world: World,\n source: EntityId,\n rel: Relation,\n): readonly EntityId[] {\n const state = getWorldState(world)\n const storage = state.relationStorage.get(rel.__id)\n if (!storage) return []\n const src = source as number\n if (storage.exclusive) {\n if (src < storage.exclusive.length) {\n const tgt = storage.exclusive[src] ?? -1\n return tgt >= 0 ? [tgt as EntityId] : []\n }\n return []\n }\n const list = storage.outgoing.get(src)\n if (!list) return []\n return list as EntityId[]\n}\n\n// Cleanup hook: when an entity is destroyed, remove all relations involving it.\nregisterRelationsCleanup((state: WorldState, eid: EntityId) => {\n const e = eid as number\n for (const storage of state.relationStorage.values()) {\n if (storage.exclusive) {\n if (e < storage.exclusive.length) storage.exclusive[e] = -1\n // Also clear any references TO this entity as target\n for (let i = 0; i < storage.exclusive.length; i++) {\n if (storage.exclusive[i] === e) storage.exclusive[i] = -1\n }\n }\n storage.outgoing.delete(e)\n for (const [src, list] of storage.outgoing) {\n const idx = list.indexOf(e)\n if (idx >= 0) {\n list.splice(idx, 1)\n if (list.length === 0) storage.outgoing.delete(src)\n }\n }\n // Clear data entries involving this entity\n for (const key of Array.from(storage.data.keys())) {\n const srcKey = Math.floor(key / state.capacity)\n const tgtKey = key % state.capacity\n if (srcKey === e || tgtKey === e) storage.data.delete(key)\n }\n }\n})\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var A="0.1.1";function R(n){return new Uint32Array(n)}function j(n,t){let o=t>>>5;n[o]=(n[o]??0)|1<<(t&31);}function L(n,t){let o=t>>>5;return ((n[o]??0)&1<<(t&31))!==0}function b(n){let t=new Uint32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]??0;return t}function I(n){let t=[];for(let o=0;o<n.length;o++)t.push((n[o]??0).toString(16));return t.join(",")}var g={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},Z=256,K=1,z=new Map;function u(n){let t=z.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function tt(n){z.set(n.id,n);}function nt(n){let t=n??{},o=t.indexBits??g.indexBits,e=t.generationBits??g.generationBits,r=Z;if(o<1||o>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(e<0||e>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<o,s=Math.max(1,Math.min(t.initialCapacity??g.initialCapacity,i)),c=Math.max(s,Math.min(t.maxEntities??g.maxEntities,i));return {initialCapacity:s,maxEntities:c,indexBits:o,generationBits:e,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function et(n,t){return {id:0,mask:R(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function T(n){let t=nt(n),o=K++,e=t.generationBits>8?Uint16Array:Uint8Array,r=new e(t.initialCapacity),i={id:o,capacity:t.initialCapacity,version:A,options:t,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},s=et(t.maskWordCount,t.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(I(s.mask),0),tt(i),ot(i)}function ot(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function F(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let o=n.capacity;for(;o<t;)o=Math.min(o*2,n.options.maxEntities);rt(n,o);}function rt(n,t){n.capacity;let e=n.generations.constructor,r=new e(t);r.set(n.generations),n.generations=r;let i=new Uint32Array(t);i.set(n.entityArchetype),n.entityArchetype=i;let s=n.options.maskWordCount,c=new Uint32Array(t*s);c.set(n.entityMask),n.entityMask=c;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let d=n.componentInfoByBit[a.bit];d&&it(a.soa,d.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function it(n,t,o){for(let e of t){let r=n[e.name];if(!r)continue;let i=o*e.vectorLen;if(r.length>=i)continue;let s=new e.ctor(i);s.set(r),n[e.name]=s;}}function D(n,t){let o=I(t),e=n.archetypeByMaskHash.get(o);if(e!==void 0)return {archId:e,created:false};let r=n.archetypes.length,i={id:r,mask:b(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:st(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(i),n.archetypeByMaskHash.set(o,r),n.queryVersion++,{archId:r,created:true}}function C(n,t){if(t<=n.capacity)return;let o=n.capacity;for(;o<t;)o*=2;let e=new Uint32Array(o);e.set(n.entities),n.entities=e,n.capacity=o;}function st(n){let t=[];for(let o=0;o<n.length;o++){let e=n[o]??0;for(;e!==0;){let r=e&-e,i=(o<<5)+(31-Math.clz32(r));t.push(i),e&=e-1;}}return t}function N(n,t){let o=n.componentBitFor.get(t.id);if(o!==void 0)return o;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let e=n.nextComponentBit++;n.componentBitFor.set(t.id,e),n.componentInfoByBit[e]=t;let r;if(t.kind==="soa"){let i={};for(let s of t.fields)i[s.name]=new s.ctor(n.capacity*s.vectorLen);r={kind:"soa",componentId:t.id,bit:e,soa:i};}else t.kind==="aos"?r={kind:"aos",componentId:t.id,bit:e,aos:new Array(n.capacity)}:r={kind:"tag",componentId:t.id,bit:e};return n.componentStorageByBit[e]=r,e}function P(n,t){let o=n.options.maskWordCount,e=new Uint32Array(o),r=t*o;for(let i=0;i<o;i++)e[i]=n.entityMask[r+i]??0;return e}function V(n,t,o){let e=n.options.maskWordCount,r=t*e;for(let i=0;i<e;i++)n.entityMask[r+i]=o[i]??0;}function v(n){let t=u(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let o;if(t.freeList.length>0)o=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&F(t,t.nextFreshIndex+1),o=t.nextFreshIndex++;}let e=t.archetypes[0];if(!e)throw new Error("aiecsjs: missing empty archetype");C(e,e.size+1);let r=e.size;e.entities[r]=o,e.entityRow.set(o,r),e.size++,t.entityArchetype[o]=0;let i=t.options.maskWordCount,s=o*i;for(let c=0;c<i;c++)t.entityMask[s+c]=0;return t.size++,o}function E(n,t){let o=u(n);return W(o,t)}function W(n,t){if(t<=0||t>=n.capacity)return false;let o=n.entityArchetype[t]??0,e=n.archetypes[o];return e?e.entityRow.has(t):false}var B=new Map;function q(n){let t=B.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function O(n,t,o,e){let r=u(n);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!W(r,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let i=q(o),s=N(r,i),c=P(r,t);if(L(c,s)){e!==void 0&&$(r,t,o,e);return}let a=b(c);j(a,s),at(r,t,a),$(r,t,o,e);}function $(n,t,o,e){let r=q(o),i=n.componentBitFor.get(r.id);if(i===void 0)return;let s=n.componentStorageByBit[i];if(s){if(r.kind==="soa"&&s.soa){if(e==null)return;let c=e;for(let a of r.fields){if(!(a.name in c))continue;let d=s.soa[a.name];if(!d)continue;let f=c[a.name];if(a.vectorLen===1)d[t]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let m=t*a.vectorLen,p=f;for(let l=0;l<a.vectorLen;l++)d[m+l]=Number(p[l]??0);}}}else if(r.kind==="aos"&&s.aos){let c=r.factory??(()=>({})),a=s.aos[t];a===void 0&&(a=c(),s.aos[t]=a),e&&typeof e=="object"&&Object.assign(a,e);}}}function at(n,t,o){let e=n.entityArchetype[t]??0,r=n.archetypes[e];if(!r)return;let s=D(n,o).archId,c=n.archetypes[s];if(c){if(s!==e){let a=r.entityRow.get(t);if(a!==void 0){let f=r.size-1;if(a!==f){let m=r.entities[f]??0;r.entities[a]=m,r.entityRow.set(m,a);}r.entities[f]=0,r.entityRow.delete(t),r.size--;}C(c,c.size+1);let d=c.size;c.entities[d]=t,c.entityRow.set(t,d),c.size++,n.entityArchetype[t]=s;}V(n,t,o);}}function U(n){return B.get(n)}function H(){return Array.from(B.values())}var y="AIEC",J=1;function zt(n,t){let o=G(n);return t?.components&&(o.entities=o.entities.map(e=>({eid:e.eid,components:e.components.filter(r=>t.components.some(i=>i.__id===r.id))}))),Y(o)}function Tt(n,t){let o=Q(n,t);return pt(o)}function G(n){let t=u(n),o=[];for(let e=1;e<t.capacity;e++){if(!E(n,e)||(t.entityArchetype[e]??0)===0)continue;let i=t.options.maskWordCount,s=e*i,c=[];for(let a=0;a<i;a++){let d=t.entityMask[s+a]??0;for(;d!==0;){let f=d&-d,m=(a<<5)+(31-Math.clz32(f)),p=t.componentInfoByBit[m];if(p){let l=t.componentStorageByBit[m],w=null;if(p.kind==="soa"&&l?.soa){let S={};for(let h of p.fields){let x=l.soa[h.name];if(x)if(h.vectorLen===1)S[h.name]=x[e];else {let _=[],X=e*h.vectorLen;for(let k=0;k<h.vectorLen;k++)_.push(x[X+k]??0);S[h.name]=_;}}w=S;}else p.kind==="aos"&&l?.aos?w=l.aos[e]??null:w=true;c.push({kind:p.kind,id:p.id,data:w});}d&=d-1;}}o.push({eid:e,components:c});}return {version:t.version,capacity:t.capacity,entities:o}}function pt(n){let t=T({initialCapacity:n.capacity}),o=new Map;for(let e of n.entities){let r=v(t);o.set(e.eid,r);}for(let e of n.entities){let r=o.get(e.eid);for(let i of e.components){let s=U(i.id);if(!s)continue;let c=M(s);c&&O(t,r,c,i.data);}}return t}function M(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let t=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:t}}return {__kind:"tag",__id:n.id}}function Y(n){let t=JSON.stringify(n),o=new TextEncoder().encode(t),e=new TextEncoder().encode(A),i=12+e.length+4+o.length,s=new Uint8Array(i),c=new DataView(s.buffer),a=0;return s[a++]=y.charCodeAt(0),s[a++]=y.charCodeAt(1),s[a++]=y.charCodeAt(2),s[a++]=y.charCodeAt(3),c.setUint32(a,J,true),a+=4,c.setUint32(a,e.length,true),a+=4,s.set(e,a),a+=e.length,c.setUint32(a,o.length,true),a+=4,s.set(o,a),s}function Q(n,t){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let o=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==y.charCodeAt(0)||n[1]!==y.charCodeAt(1)||n[2]!==y.charCodeAt(2)||n[3]!==y.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let e=4,r=o.getUint32(e,true);e+=4;let i=t?.onUnknownVersion??"throw";if(r!==J&&i==="throw")throw new Error(`aiecsjs: format version ${r} not supported`);let s=o.getUint32(e,true);e+=4,e+=s;let c=o.getUint32(e,true);e+=4;let a=n.subarray(e,e+c),d=new TextDecoder().decode(a);return JSON.parse(d)}function Ft(n,t){let o={world:n,components:t?.components??H().map(e=>M(e)).filter(Boolean),lastSnapshot:null};return {capture(){let e=G(o.world),r;return o.lastSnapshot?r=ut(o.lastSnapshot,e):r=e,o.lastSnapshot=e,Y(r)},apply(e,r){let i=Q(r),s=u(e);for(let c of i.entities)if(!(c.eid>=s.capacity)){if(!E(e,c.eid))for(;s.size<c.eid;)v(e);for(let a of c.components){let d=U(a.id);if(!d)continue;let f=M(d);f&&O(e,c.eid,f,a.data);}}},reset(){o.lastSnapshot=null;}}}function ut(n,t){let o=new Map(n.entities.map(r=>[r.eid,r])),e=[];for(let r of t.entities){let i=o.get(r.eid);if(!i){e.push(r);continue}let s=JSON.stringify(i.components),c=JSON.stringify(r.components);s!==c&&e.push(r);}return {version:t.version,capacity:t.capacity,entities:e}}exports.createDeltaSerializer=Ft;exports.deserializeWorld=Tt;exports.fromJSON=pt;exports.serializeWorld=zt;exports.toJSON=G;//# sourceMappingURL=serialize.cjs.map
|
|
2
|
+
//# sourceMappingURL=serialize.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/internal/bitmask.ts","../src/internal/world.ts","../src/internal/entity.ts","../src/internal/component.ts","../src/serialize.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","testBit","cloneMask","src","out","i","maskHash","m","parts","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","id","generationCtor","generations","empty","makePublicWorld","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","storage","info","growSoAColumns","soa","fields","f","old","newLen","next","findOrCreateArchetype","key","existing","arch","collectBits","ensureArchetypeCapacity","bits","word","lsb","getOrRegisterComponentBit","readEntityMask","eid","base","writeEntityMask","createEntity","row","entityExists","isAliveInternal","archId","componentInfoById","getComponentInfo","component","addComponent","initial","prevMask","writeInitial","migrateEntity","obj","col","val","arr","factory","inst","srcArchId","srcArch","destArchId","destArch","lastRow","moved","newRow","getComponentByInternalId","listAllComponents","MAGIC","FORMAT_VERSION","serializeWorld","snapshot","toJSON","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","entities","components","wi","data","baseI","eidMap","handle","getComponentHandle","json","jsonBytes","versionBytes","total","view","off","formatVersion","onUnknown","verLen","jsonLen","createDeltaSerializer","current","delta","computeDelta","targetWorld","deltaBytes","targetState","e","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"aAAO,IAAMA,EAAU,OAAA,CCEhB,SAASC,CAAAA,CAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,CAAAA,CAAmBC,EAAmB,CAC3D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAM,CAAA,GAAMD,CAAAA,CAAM,IAC1C,CAOO,SAASE,CAAAA,CAAQH,CAAAA,CAAmBC,EAAsB,CAC/D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClB,OAAA,CAAA,CAASD,CAAAA,CAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,EAAA,CAAA,IAAU,CAClD,CAOO,SAASG,CAAAA,CAAUC,CAAAA,CAA+B,CACvD,IAAMC,CAAAA,CAAM,IAAI,WAAA,CAAYD,CAAAA,CAAI,MAAM,CAAA,CACtC,IAAA,IAASE,CAAAA,CAAI,CAAA,CAAGA,EAAIF,CAAAA,CAAI,MAAA,CAAQE,CAAAA,EAAAA,CAAKD,CAAAA,CAAIC,CAAC,CAAA,CAAIF,CAAAA,CAAIE,CAAC,CAAA,EAAK,EACxD,OAAOD,CACT,CASO,SAASE,EAASC,CAAAA,CAAwB,CAE/C,IAAMC,CAAAA,CAAkB,EAAC,CACzB,IAAA,IAASH,CAAAA,CAAI,CAAA,CAAGA,EAAIE,CAAAA,CAAE,MAAA,CAAQF,CAAAA,EAAAA,CAC5BG,CAAAA,CAAM,MAAMD,CAAAA,CAAEF,CAAC,CAAA,EAAK,CAAA,EAAG,SAAS,EAAE,CAAC,CAAA,CAErC,OAAOG,EAAM,IAAA,CAAK,GAAG,CACvB,CC/BA,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CAAKA,CAAC,CAAC,CAAC,CAAA,CACtDI,CAAAA,CAAqC,EAAC,CAC5C,QAAWJ,CAAAA,IAAKE,CAAAA,CAAK,QAAA,CAAU,CAC7B,IAAMG,CAAAA,CAAQF,CAAAA,CAAU,GAAA,CAAIH,CAAAA,CAAE,GAAG,CAAA,CACjC,GAAI,CAACK,CAAAA,CAAO,CACVD,CAAAA,CAAQ,IAAA,CAAKJ,CAAC,CAAA,CACd,QACF,CACA,IAAMM,CAAAA,CAAU,IAAA,CAAK,UAAUD,CAAAA,CAAM,UAAU,CAAA,CACzCE,CAAAA,CAAU,KAAK,SAAA,CAAUP,CAAAA,CAAE,UAAU,CAAA,CACvCM,IAAYC,CAAAA,EAASH,CAAAA,CAAQ,IAAA,CAAKJ,CAAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASE,EAAK,OAAA,CAAS,QAAA,CAAUA,EAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"serialize.cjs","sourcesContent":["export const VERSION = '0.1.1'\n","// 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 { EntityId, World, WorldState } from './types.js'\nimport {\n ensureArchetypeCapacity,\n ensureCapacity,\n getWorldState,\n} from './world.js'\nimport { clearAllEntityStorages } from './component.js'\n\nexport function createEntity(world: World): EntityId {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot createEntity on a read-only world (worker-attached)')\n }\n\n let eid: number\n if (state.freeList.length > 0) {\n eid = state.freeList.pop()!\n } else {\n if (state.nextFreshIndex >= state.options.maxEntities) {\n throw new Error(`aiecsjs: reached maxEntities ${state.options.maxEntities}`)\n }\n if (state.nextFreshIndex >= state.capacity) {\n ensureCapacity(state, state.nextFreshIndex + 1)\n }\n eid = state.nextFreshIndex++\n }\n\n // Move into the empty archetype (0)\n const arch = state.archetypes[0]\n if (!arch) throw new Error('aiecsjs: missing empty archetype')\n ensureArchetypeCapacity(arch, arch.size + 1)\n const row = arch.size\n arch.entities[row] = eid\n arch.entityRow.set(eid, row)\n arch.size++\n\n state.entityArchetype[eid] = 0\n // Reset entityMask row for this eid\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid as EntityId\n}\n\nexport function destroyEntity(world: World, eid: EntityId): void {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot destroyEntity on a read-only world')\n }\n if (!isAliveInternal(state, eid)) return\n\n // Fire onRemove for every component the entity has, plus reactive exit\n // (Late-bound to avoid circular imports — done via observers module.)\n const { dispatchDestroyObservers } = lazyObservers()\n dispatchDestroyObservers(state, eid)\n\n // Clean up relations referring to this entity\n cleanupRelationsOnDestroy(state, eid)\n\n // Zero the SoA columns / undefine the AoS slots the entity owned, before\n // the mask is cleared. Without this, destroyed entities leave stale data\n // visible to snapshots and serialisation.\n clearAllEntityStorages(state, eid)\n\n // Swap-pop from its archetype\n const archId = state.entityArchetype[eid] ?? 0\n const arch = state.archetypes[archId]\n if (arch) {\n const row = arch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = arch.size - 1\n if (row !== lastRow) {\n const moved = arch.entities[lastRow] ?? 0\n arch.entities[row] = moved\n arch.entityRow.set(moved, row)\n }\n arch.entities[lastRow] = 0\n arch.entityRow.delete(eid)\n arch.size--\n }\n }\n\n // Wipe state\n state.entityArchetype[eid] = 0\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // bump generation (wraps within the type)\n ;(state.generations as any)[eid] = (((state.generations as any)[eid] ?? 0) + 1) & 0xFFFF\n\n state.freeList.push(eid)\n state.size--\n}\n\nexport function entityExists(world: World, eid: EntityId): boolean {\n const state = getWorldState(world)\n return isAliveInternal(state, eid)\n}\n\nexport function isAliveInternal(state: WorldState, eid: number): boolean {\n if (eid <= 0) return false\n if (eid >= state.capacity) return false\n // An entity is alive iff it is in some archetype (its row map points somewhere).\n const archId = state.entityArchetype[eid] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n return arch.entityRow.has(eid)\n}\n\nexport function getEntityIndex(eid: EntityId): number {\n return eid as number\n}\n\nexport function getEntityGeneration(_eid: EntityId): number {\n // Unversioned in 0.1: generation not encoded in EntityId.\n return 0\n}\n\nexport function packEntity(index: number, _generation: number): EntityId {\n // Identity in 0.1.\n return index as EntityId\n}\n\nexport function isEntity(world: World, x: unknown): x is EntityId {\n if (typeof x !== 'number') return false\n return entityExists(world, x as EntityId)\n}\n\n// --- Lazy loaders to break import cycles ---\n\ninterface ObserversAPI {\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void\n}\nlet _observersAPI: ObserversAPI | null = null\nexport function registerObserversAPI(api: ObserversAPI): void {\n _observersAPI = api\n}\nfunction lazyObservers(): ObserversAPI {\n if (!_observersAPI) {\n return { dispatchDestroyObservers: () => {} }\n }\n return _observersAPI\n}\n\nlet _relationsCleanup: ((state: WorldState, eid: EntityId) => void) | null = null\nexport function registerRelationsCleanup(fn: (state: WorldState, eid: EntityId) => void): void {\n _relationsCleanup = fn\n}\nfunction cleanupRelationsOnDestroy(state: WorldState, eid: EntityId): void {\n if (_relationsCleanup) _relationsCleanup(state, eid)\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","// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport type {\n ComponentInfo,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { VERSION } from './version.js'\nimport { getWorldState, createWorld } from './internal/world.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentInfo,\n getComponentByInternalId,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, entityExists } from './internal/entity.js'\nimport { testBit } from './internal/bitmask.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map(e => ({\n eid: e.eid,\n components: e.components.filter(c =>\n options.components!.some(comp => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n for (let eid = 1; eid < state.capacity; eid++) {\n if (!entityExists(world, eid as EntityId)) continue\n const archId = state.entityArchetype[eid] ?? 0\n if (archId === 0) continue // unattached (shouldn't happen for alive)\n\n const w = state.options.maskWordCount\n const base = eid * w\n const components: WorldSnapshot['entities'][0]['components'] = []\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 const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[eid]\n } else {\n const arr: number[] = []\n const baseI = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[eid] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n entities.push({ eid, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as any)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true); off += 4\n view.setUint32(off, versionBytes.length, true); off += 4\n out.set(versionBytes, off); off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true); off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true); off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n const verLen = view.getUint32(off, true); off += 4\n off += verLen // skip the aiecsjs version string\n const jsonLen = view.getUint32(off, true); off += 4\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n return JSON.parse(json) as WorldSnapshot\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(\n world: World,\n options?: SerializeOptions,\n): DeltaSerializer {\n const state: DeltaState = {\n world,\n components: options?.components ?? listAllComponents().map(i => getComponentHandle(i)!).filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Apply: ensure entities exist, then add/update their components\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid >= targetState.capacity) continue\n if (!entityExists(targetWorld, e.eid as EntityId)) {\n // Create the entity. For simplicity, we just spawn until we have enough.\n while (targetState.size < e.eid) {\n createEntity(targetWorld)\n }\n }\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle) addComponent(targetWorld, e.eid as EntityId, handle, comp.data as any)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map(e => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-Bbv2u6kb.cjs';
|
|
2
|
+
|
|
3
|
+
declare function serializeWorld(world: World, options?: SerializeOptions): Uint8Array;
|
|
4
|
+
declare function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World;
|
|
5
|
+
declare function toJSON(world: World): WorldSnapshot;
|
|
6
|
+
declare function fromJSON(snapshot: WorldSnapshot): World;
|
|
7
|
+
declare function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer;
|
|
8
|
+
|
|
9
|
+
export { createDeltaSerializer, deserializeWorld, fromJSON, serializeWorld, toJSON };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-Bbv2u6kb.js';
|
|
2
|
+
|
|
3
|
+
declare function serializeWorld(world: World, options?: SerializeOptions): Uint8Array;
|
|
4
|
+
declare function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World;
|
|
5
|
+
declare function toJSON(world: World): WorldSnapshot;
|
|
6
|
+
declare function fromJSON(snapshot: WorldSnapshot): World;
|
|
7
|
+
declare function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer;
|
|
8
|
+
|
|
9
|
+
export { createDeltaSerializer, deserializeWorld, fromJSON, serializeWorld, toJSON };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var A="0.1.1";function R(n){return new Uint32Array(n)}function j(n,t){let o=t>>>5;n[o]=(n[o]??0)|1<<(t&31);}function L(n,t){let o=t>>>5;return ((n[o]??0)&1<<(t&31))!==0}function b(n){let t=new Uint32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]??0;return t}function I(n){let t=[];for(let o=0;o<n.length;o++)t.push((n[o]??0).toString(16));return t.join(",")}var g={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},Z=256,K=1,z=new Map;function u(n){let t=z.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function tt(n){z.set(n.id,n);}function nt(n){let t=n??{},o=t.indexBits??g.indexBits,e=t.generationBits??g.generationBits,r=Z;if(o<1||o>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(e<0||e>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");let i=1<<o,s=Math.max(1,Math.min(t.initialCapacity??g.initialCapacity,i)),c=Math.max(s,Math.min(t.maxEntities??g.maxEntities,i));return {initialCapacity:s,maxEntities:c,indexBits:o,generationBits:e,maxComponents:r,maskWordCount:Math.ceil(r/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function et(n,t){return {id:0,mask:R(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function T(n){let t=nt(n),o=K++,e=t.generationBits>8?Uint16Array:Uint8Array,r=new e(t.initialCapacity),i={id:o,capacity:t.initialCapacity,version:A,options:t,size:0,nextFreshIndex:1,freeList:[],generations:r,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},s=et(t.maskWordCount,t.maxComponents);return s.id=0,i.archetypes.push(s),i.archetypeByMaskHash.set(I(s.mask),0),tt(i),ot(i)}function ot(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function F(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let o=n.capacity;for(;o<t;)o=Math.min(o*2,n.options.maxEntities);rt(n,o);}function rt(n,t){n.capacity;let e=n.generations.constructor,r=new e(t);r.set(n.generations),n.generations=r;let i=new Uint32Array(t);i.set(n.entityArchetype),n.entityArchetype=i;let s=n.options.maskWordCount,c=new Uint32Array(t*s);c.set(n.entityMask),n.entityMask=c;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let d=n.componentInfoByBit[a.bit];d&&it(a.soa,d.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function it(n,t,o){for(let e of t){let r=n[e.name];if(!r)continue;let i=o*e.vectorLen;if(r.length>=i)continue;let s=new e.ctor(i);s.set(r),n[e.name]=s;}}function D(n,t){let o=I(t),e=n.archetypeByMaskHash.get(o);if(e!==void 0)return {archId:e,created:false};let r=n.archetypes.length,i={id:r,mask:b(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:st(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(i),n.archetypeByMaskHash.set(o,r),n.queryVersion++,{archId:r,created:true}}function C(n,t){if(t<=n.capacity)return;let o=n.capacity;for(;o<t;)o*=2;let e=new Uint32Array(o);e.set(n.entities),n.entities=e,n.capacity=o;}function st(n){let t=[];for(let o=0;o<n.length;o++){let e=n[o]??0;for(;e!==0;){let r=e&-e,i=(o<<5)+(31-Math.clz32(r));t.push(i),e&=e-1;}}return t}function N(n,t){let o=n.componentBitFor.get(t.id);if(o!==void 0)return o;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let e=n.nextComponentBit++;n.componentBitFor.set(t.id,e),n.componentInfoByBit[e]=t;let r;if(t.kind==="soa"){let i={};for(let s of t.fields)i[s.name]=new s.ctor(n.capacity*s.vectorLen);r={kind:"soa",componentId:t.id,bit:e,soa:i};}else t.kind==="aos"?r={kind:"aos",componentId:t.id,bit:e,aos:new Array(n.capacity)}:r={kind:"tag",componentId:t.id,bit:e};return n.componentStorageByBit[e]=r,e}function P(n,t){let o=n.options.maskWordCount,e=new Uint32Array(o),r=t*o;for(let i=0;i<o;i++)e[i]=n.entityMask[r+i]??0;return e}function V(n,t,o){let e=n.options.maskWordCount,r=t*e;for(let i=0;i<e;i++)n.entityMask[r+i]=o[i]??0;}function v(n){let t=u(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let o;if(t.freeList.length>0)o=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&F(t,t.nextFreshIndex+1),o=t.nextFreshIndex++;}let e=t.archetypes[0];if(!e)throw new Error("aiecsjs: missing empty archetype");C(e,e.size+1);let r=e.size;e.entities[r]=o,e.entityRow.set(o,r),e.size++,t.entityArchetype[o]=0;let i=t.options.maskWordCount,s=o*i;for(let c=0;c<i;c++)t.entityMask[s+c]=0;return t.size++,o}function E(n,t){let o=u(n);return W(o,t)}function W(n,t){if(t<=0||t>=n.capacity)return false;let o=n.entityArchetype[t]??0,e=n.archetypes[o];return e?e.entityRow.has(t):false}var B=new Map;function q(n){let t=B.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function O(n,t,o,e){let r=u(n);if(r.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!W(r,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let i=q(o),s=N(r,i),c=P(r,t);if(L(c,s)){e!==void 0&&$(r,t,o,e);return}let a=b(c);j(a,s),at(r,t,a),$(r,t,o,e);}function $(n,t,o,e){let r=q(o),i=n.componentBitFor.get(r.id);if(i===void 0)return;let s=n.componentStorageByBit[i];if(s){if(r.kind==="soa"&&s.soa){if(e==null)return;let c=e;for(let a of r.fields){if(!(a.name in c))continue;let d=s.soa[a.name];if(!d)continue;let f=c[a.name];if(a.vectorLen===1)d[t]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let m=t*a.vectorLen,p=f;for(let l=0;l<a.vectorLen;l++)d[m+l]=Number(p[l]??0);}}}else if(r.kind==="aos"&&s.aos){let c=r.factory??(()=>({})),a=s.aos[t];a===void 0&&(a=c(),s.aos[t]=a),e&&typeof e=="object"&&Object.assign(a,e);}}}function at(n,t,o){let e=n.entityArchetype[t]??0,r=n.archetypes[e];if(!r)return;let s=D(n,o).archId,c=n.archetypes[s];if(c){if(s!==e){let a=r.entityRow.get(t);if(a!==void 0){let f=r.size-1;if(a!==f){let m=r.entities[f]??0;r.entities[a]=m,r.entityRow.set(m,a);}r.entities[f]=0,r.entityRow.delete(t),r.size--;}C(c,c.size+1);let d=c.size;c.entities[d]=t,c.entityRow.set(t,d),c.size++,n.entityArchetype[t]=s;}V(n,t,o);}}function U(n){return B.get(n)}function H(){return Array.from(B.values())}var y="AIEC",J=1;function zt(n,t){let o=G(n);return t?.components&&(o.entities=o.entities.map(e=>({eid:e.eid,components:e.components.filter(r=>t.components.some(i=>i.__id===r.id))}))),Y(o)}function Tt(n,t){let o=Q(n,t);return pt(o)}function G(n){let t=u(n),o=[];for(let e=1;e<t.capacity;e++){if(!E(n,e)||(t.entityArchetype[e]??0)===0)continue;let i=t.options.maskWordCount,s=e*i,c=[];for(let a=0;a<i;a++){let d=t.entityMask[s+a]??0;for(;d!==0;){let f=d&-d,m=(a<<5)+(31-Math.clz32(f)),p=t.componentInfoByBit[m];if(p){let l=t.componentStorageByBit[m],w=null;if(p.kind==="soa"&&l?.soa){let S={};for(let h of p.fields){let x=l.soa[h.name];if(x)if(h.vectorLen===1)S[h.name]=x[e];else {let _=[],X=e*h.vectorLen;for(let k=0;k<h.vectorLen;k++)_.push(x[X+k]??0);S[h.name]=_;}}w=S;}else p.kind==="aos"&&l?.aos?w=l.aos[e]??null:w=true;c.push({kind:p.kind,id:p.id,data:w});}d&=d-1;}}o.push({eid:e,components:c});}return {version:t.version,capacity:t.capacity,entities:o}}function pt(n){let t=T({initialCapacity:n.capacity}),o=new Map;for(let e of n.entities){let r=v(t);o.set(e.eid,r);}for(let e of n.entities){let r=o.get(e.eid);for(let i of e.components){let s=U(i.id);if(!s)continue;let c=M(s);c&&O(t,r,c,i.data);}}return t}function M(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let t=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:t}}return {__kind:"tag",__id:n.id}}function Y(n){let t=JSON.stringify(n),o=new TextEncoder().encode(t),e=new TextEncoder().encode(A),i=12+e.length+4+o.length,s=new Uint8Array(i),c=new DataView(s.buffer),a=0;return s[a++]=y.charCodeAt(0),s[a++]=y.charCodeAt(1),s[a++]=y.charCodeAt(2),s[a++]=y.charCodeAt(3),c.setUint32(a,J,true),a+=4,c.setUint32(a,e.length,true),a+=4,s.set(e,a),a+=e.length,c.setUint32(a,o.length,true),a+=4,s.set(o,a),s}function Q(n,t){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let o=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==y.charCodeAt(0)||n[1]!==y.charCodeAt(1)||n[2]!==y.charCodeAt(2)||n[3]!==y.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let e=4,r=o.getUint32(e,true);e+=4;let i=t?.onUnknownVersion??"throw";if(r!==J&&i==="throw")throw new Error(`aiecsjs: format version ${r} not supported`);let s=o.getUint32(e,true);e+=4,e+=s;let c=o.getUint32(e,true);e+=4;let a=n.subarray(e,e+c),d=new TextDecoder().decode(a);return JSON.parse(d)}function Ft(n,t){let o={world:n,components:t?.components??H().map(e=>M(e)).filter(Boolean),lastSnapshot:null};return {capture(){let e=G(o.world),r;return o.lastSnapshot?r=ut(o.lastSnapshot,e):r=e,o.lastSnapshot=e,Y(r)},apply(e,r){let i=Q(r),s=u(e);for(let c of i.entities)if(!(c.eid>=s.capacity)){if(!E(e,c.eid))for(;s.size<c.eid;)v(e);for(let a of c.components){let d=U(a.id);if(!d)continue;let f=M(d);f&&O(e,c.eid,f,a.data);}}},reset(){o.lastSnapshot=null;}}}function ut(n,t){let o=new Map(n.entities.map(r=>[r.eid,r])),e=[];for(let r of t.entities){let i=o.get(r.eid);if(!i){e.push(r);continue}let s=JSON.stringify(i.components),c=JSON.stringify(r.components);s!==c&&e.push(r);}return {version:t.version,capacity:t.capacity,entities:e}}export{Ft as createDeltaSerializer,Tt as deserializeWorld,pt as fromJSON,zt as serializeWorld,G as toJSON};//# sourceMappingURL=serialize.js.map
|
|
2
|
+
//# sourceMappingURL=serialize.js.map
|