aiecsjs 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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,E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,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.2'\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"]}
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,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AE,UAAA,CAAY,CAC/B,IAAMvF,EAAOgD,CAAAA,CAAyBQ,CAAAA,CAAK,EAAE,CAAA,CAC7C,GAAI,CAACxD,CAAAA,CAAM,SACX,IAAMoE,EAASC,CAAAA,CAAmBrE,CAAI,CAAA,CAClCoE,CAAAA,EAAQtC,EAAasD,CAAAA,CAAaG,CAAAA,CAAE,GAAA,CAAiBnB,CAAAA,CAAQZ,EAAK,IAAW,EACnF,EAEJ,CAAA,CACA,KAAA,EAAc,CACZtF,CAAAA,CAAM,YAAA,CAAe,KACvB,CACF,CACF,CAEA,SAASiH,EAAAA,CAAaK,CAAAA,CAAqBC,EAAoC,CAC7E,IAAMC,CAAAA,CAAY,IAAI,IAAIF,CAAAA,CAAK,QAAA,CAAS,GAAA,CAAID,CAAAA,EAAK,CAACA,CAAAA,CAAE,GAAA,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.3'\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\n// Iterate set bits in a slice of a larger Uint32Array starting at `base`.\n// Shared by destroy paths and storage cleanup so the bit-extraction maths\n// lives in exactly one place.\nexport function forEachSetBit(\n mask: Uint32Array,\n base: number,\n words: number,\n fn: (bit: number) => void,\n): void {\n for (let wi = 0; wi < words; wi++) {\n let word = mask[base + wi] ?? 0\n while (word !== 0) {\n const bit = (wi << 5) + ctz32(word)\n fn(bit)\n word &= word - 1\n }\n }\n}\n\n// Match a query against an entity's mask stored as a slice inside a larger\n// Uint32Array. Reading directly from the parent array avoids the temporary\n// Uint32Array allocation on every observer dispatch.\nexport function matchesEntityMask(\n entityMask: Uint32Array,\n base: number,\n words: number,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n): boolean {\n let anyHit = !anyHasBits\n for (let i = 0; i < words; i++) {\n const m = entityMask[base + i] ?? 0\n const wm = withMask[i] ?? 0\n const am = anyMask[i] ?? 0\n const nm = noneMask[i] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","import { VERSION } from '../version.js'\nimport {\n type World,\n type WorldOptions,\n type ResolvedWorldOptions,\n type WorldState,\n type ArchetypeState,\n type ComponentInfo,\n type WorldComponentStorage,\n type FieldInfo,\n} from './types.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(1, Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex))\n const maxEntities = Math.max(initialCapacity, Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex))\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryMasks: new Map(),\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() { return state.capacity },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryMasks.clear()\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new Error(`aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`)\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n // generations\n const genCtor: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n}\n\nfunction growSoAColumns(soa: Record<string, any>, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(state: WorldState, mask: Uint32Array): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new Error(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: Record<string, any> = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const base = eid * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const base = eid * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import type { 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 (Uint8Array wraps to 8 bits naturally; Uint16Array to 16)\n const idx = eid as number\n state.generations[idx] = ((state.generations[idx] ?? 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, forEachSetBit } from './bitmask.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\nimport { isAliveInternal } from './entity.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema)) {\n let type: keyof typeof TYPE_CTOR\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({} as T))\n const info: ComponentInfo = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info) throw new Error('aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)')\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n writeInitial(state, eid, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n fireRemoveObservers(state, eid, bit)\n\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid, newMask)\n\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, eid)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[eid] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(world: World, eid: EntityId, component: C): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') return storage.aos?.[eid]\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid, component, value as any)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(state: WorldState, eid: number, component: ComponentLike, initial: unknown): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[eid] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = eid * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[eid]\n if (inst === undefined) {\n inst = factory()\n storage.aos[eid] = inst\n }\n if (initial && typeof initial === 'object') {\n Object.assign(inst as object, initial as object)\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const idx = eid as number\n const base = idx * wordCount\n forEachSetBit(state.entityMask, base, wordCount, (bit) => {\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n })\n}\n\nfunction migrateEntity(state: WorldState, eid: number, newMask: Uint32Array): void {\n const srcArchId = state.entityArchetype[eid] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src\n const row = srcArch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(eid)\n srcArch.size--\n }\n\n // Append to dest\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = eid\n destArch.entityRow.set(eid, newRow)\n destArch.size++\n\n state.entityArchetype[eid] = destArchId\n }\n\n writeEntityMask(state, eid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (state: WorldState, eid: EntityId, bit: number, prev: Uint32Array, next: Uint32Array) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(state: WorldState, eid: number, bit: number, prev: Uint32Array, next: Uint32Array): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","// 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"]}
@@ -1,4 +1,4 @@
1
- import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-Bbv2u6kb.cjs';
1
+ import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-B3YUJZEg.cjs';
2
2
 
3
3
  declare function serializeWorld(world: World, options?: SerializeOptions): Uint8Array;
4
4
  declare function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World;
@@ -1,4 +1,4 @@
1
- import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-Bbv2u6kb.js';
1
+ import { W as World, S as SerializeOptions, D as DeltaSerializer, e as DeserializeOptions, p as WorldSnapshot } from './types-B3YUJZEg.js';
2
2
 
3
3
  declare function serializeWorld(world: World, options?: SerializeOptions): Uint8Array;
4
4
  declare function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World;
package/dist/serialize.js CHANGED
@@ -1,2 +1,2 @@
1
- var A="0.1.2";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
1
+ var A="0.1.3";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)),a=Math.max(s,Math.min(t.maxEntities??g.maxEntities,i));return {initialCapacity:s,maxEntities:a,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:[],queryMasks:new Map,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){let o=n.generations.constructor,e=new o(t);e.set(n.generations),n.generations=e;let r=new Uint32Array(t);r.set(n.entityArchetype),n.entityArchetype=r;let i=n.options.maskWordCount,s=new Uint32Array(t*i);s.set(n.entityMask),n.entityMask=s;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let c=n.componentInfoByBit[a.bit];c&&it(a.soa,c.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 a=0;a<i;a++)t.entityMask[s+a]=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 $(n){let t=B.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function U(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=$(o),s=N(r,i),a=P(r,t);if(L(a,s)){e!==void 0&&q(r,t,o,e);return}let c=b(a);j(c,s),at(r,t,c),q(r,t,o,e);}function q(n,t,o,e){let r=$(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 a=e;for(let c of r.fields){if(!(c.name in a))continue;let d=s.soa[c.name];if(!d)continue;let f=a[c.name];if(c.vectorLen===1)d[t]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let m=t*c.vectorLen,p=f;for(let l=0;l<c.vectorLen;l++)d[m+l]=Number(p[l]??0);}}}else if(r.kind==="aos"&&s.aos){let a=r.factory??(()=>({})),c=s.aos[t];c===void 0&&(c=a(),s.aos[t]=c),e&&typeof e=="object"&&Object.assign(c,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,a=n.archetypes[s];if(a){if(s!==e){let c=r.entityRow.get(t);if(c!==void 0){let f=r.size-1;if(c!==f){let m=r.entities[f]??0;r.entities[c]=m,r.entityRow.set(m,c);}r.entities[f]=0,r.entityRow.delete(t),r.size--;}C(a,a.size+1);let d=a.size;a.entities[d]=t,a.entityRow.set(t,d),a.size++,n.entityArchetype[t]=s;}V(n,t,o);}}function O(n){return B.get(n)}function H(){return Array.from(B.values())}var y="AIEC",J=1;function Tt(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 Ft(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,a=[];for(let c=0;c<i;c++){let d=t.entityMask[s+c]??0;for(;d!==0;){let f=d&-d,m=(c<<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;a.push({kind:p.kind,id:p.id,data:w});}d&=d-1;}}o.push({eid:e,components:a});}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=O(i.id);if(!s)continue;let a=M(s);a&&U(t,r,a,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),a=new DataView(s.buffer),c=0;return s[c++]=y.charCodeAt(0),s[c++]=y.charCodeAt(1),s[c++]=y.charCodeAt(2),s[c++]=y.charCodeAt(3),a.setUint32(c,J,true),c+=4,a.setUint32(c,e.length,true),c+=4,s.set(e,c),c+=e.length,a.setUint32(c,o.length,true),c+=4,s.set(o,c),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 a=o.getUint32(e,true);e+=4;let c=n.subarray(e,e+a),d=new TextDecoder().decode(c);return JSON.parse(d)}function Dt(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 a of i.entities)if(!(a.eid>=s.capacity)){if(!E(e,a.eid))for(;s.size<a.eid;)v(e);for(let c of a.components){let d=O(c.id);if(!d)continue;let f=M(d);f&&U(e,a.eid,f,c.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),a=JSON.stringify(r.components);s!==a&&e.push(r);}return {version:t.version,capacity:t.capacity,entities:e}}export{Dt as createDeltaSerializer,Ft as deserializeWorld,pt as fromJSON,Tt as serializeWorld,G as toJSON};//# sourceMappingURL=serialize.js.map
2
2
  //# sourceMappingURL=serialize.js.map