# gizgame/world

Authoritative component data. Each archetype has one contiguous column per scalar field, with no object per entity.

```gizlang
import * as World from "gizgame/world";
```

## Types

### `Entity`

```gizlang
type Entity = { index: i64; generation: i64; }
```

An entity slot and its incarnation. A recycled slot never validates a reference to an earlier entity.

- `index`: `i64`
- `generation`: `i64`

### `Field`

```gizlang
type Field = { name: string; kind: string; lanes: i64; }
```

A field's scalar storage and lane count. Kinds are f32, f64, i64, u64, bool and entity.

- `name`: `string`
- `kind`: `string`
- `lanes`: `i64`

### `Schema`

```gizlang
type Schema = { name: string; fields: Vec<Field>; }
```

The schema used by storage, scene validation and the inspector. Component IDs are its registration order.

- `name`: `string`
- `fields`: `Vec<M186.Field>`

### `Data`

```gizlang
type Data = { component: i64; fields: Vec<bytes>; }
```

One component's fields, encoded with the SDK's little-endian scalar writers in schema order.

- `component`: `i64`
- `fields`: `Vec<bytes>`

### `ColumnView`

```gizlang
type ColumnView = { component: i64; field: i64; width: i64; data: bytes; }
```

A component and field column exposed read-only to a system's bulk processing.

- `component`: `i64`
- `field`: `i64`
- `width`: `i64`
- `data`: `bytes`

### `Changed`

```gizlang
type Changed = { entity: Entity; revision: i64; }
```

An entity's structural and component revision, useful for incremental extraction.

- `entity`: `M186.Entity`
- `revision`: `i64`

### `World`

```gizlang
class World { private schemas: Vec<Schema> = []; private editing: i64 = 0; private slots: Vec<Location> = []; private free: Vec<i64> = []; private archetypes: Vec<Archetype> = []; private serial: i64 = 0; private structural: i64 = 0; private versions: Vec<i64> = []; private replacement: i64 = 0; private locked: bool = false; private access: Access | undefined = undefined; private reading(component: i64): void throws string { if (this.access !== undefined && !this.access!.reads.includes(component) && !this.access!.writes.includes(component)) { throw `System read the undeclared component ${this.schemas[component].name }`; } } private writing(component: i64): void throws string { if (this.access !== undefined && !this.access!.writes.includes(component)) { throw `System wrote the undeclared component ${this.schemas[component].name }`; } } private restructuring(): void throws string { if (this.locked) { throw "Structural mutation during a query"; } if (this.access !== undefined && !this.access!.structural) { throw "System made an undeclared structural change"; } } system(reads: Vec<i64>, writes: Vec<i64>, structural: bool, run: () => void throws string): void throws string { if (this.access !== undefined) { throw "Nested system access scope"; } this.access = { reads, writes, structural }; try { run(); } finally { this.access = undefined; } } transaction<T>(edit: (world: World, before: bytes) => T throws string): T throws string { if (this.locked || this.access !== undefined) { throw "Cannot start an editor transaction in a query or system"; } const before = this.snapshot(); this.editing+ = 1; try { return edit(this, before); } catch (error: string) { this.restore(before); throw error; } finally { this.editing- = 1; } } schema(): Vec<Schema> { return this.schemas; } revision(): i64 { return this.serial; } componentRevision(components: Vec<i64>): i64 throws string { let revision = this.structural; for (const component of components) { if (component <0 || component> = this.versions.length) { throw "Unknown component access"; } revision = Math.maxI64(revision, this.versions[component]); } return revision; } epoch(): i64 { return this.replacement; } private admitRevision(): void throws string { if (this.serial === 9223372036854775807) { throw "World revision exhausted"; } } register(component: Schema): i64 throws string { if (this.slots.length> 0 || this.locked || this.access !== undefined || this.editing> 0) { throw "Register schemas before creating entities, editing or running systems"; } if (component.name === "" || component.name.byteLength> 4096 || component.fields.length> 4096 || this.schemas.length> = 4096) { throw "Component schema exceeds its name or field bounds"; } if (this.schemas.some(s => s.name === component.name)) { throw `Duplicate component ${component.name }`; } let names = new Set<string>(); for (const field of component.fields) { width(field); if (field.name.byteLength> 4096) { throw "Component field name is too long"; } if (names.has(field.name)) { throw `Duplicate field ${field.name }`; } names.add(field.name); } const id = this.schemas.length; this.schemas.push(component); this.versions.push(0); return id; } alive(entity: Entity): bool { return entity.index> = 0 && entity.index <this.slots.length && this.slots[entity.index].table> = 0 && this.slots[entity.index].generation === entity.generation; } private location(entity: Entity): Location throws string { if (!this.alive(entity)) { throw "Stale or absent entity"; } return this.slots[entity.index]; } private admit(data: Vec<Data>): Vec<i64> throws string { let ids: Vec<i64> = []; for (const item of data) { if (item.component <0 || item.component> = this.schemas.length || ids.includes(item.component)) { throw "Unknown or duplicate component"; } const schema = this.schemas[item.component]; if (item.fields.length !== schema.fields.length) { throw `Wrong field count for ${schema.name }`; } for (const i of range(0, item.fields.length)) { valid(schema.fields[i], item.fields[i]); } ids.push(item.component); } return ids.toSorted((a, b) => a <b); } private table(ids: Vec<i64>): i64 { for (const i of range(0, this.archetypes.length)) { const own = this.archetypes[i].components; if (sameItems(own, ids)) { return i; } } const id = this.archetypes.length; this.archetypes.push(new Archetype(ids, this.schemas)); return id; } private append(table: i64, entity: Entity, data: Vec<Data>): i64 { const target = this.archetypes[table]; const row = target.entities.length; for (const column of target.columns) { for (const item of data) { if (item.component === column.component) { column.append(item.fields[column.field]); } } } target.entities.push(entity); return row; } private remove(table: i64, row: i64): void { const target = this.archetypes[table]; const last = target.entities.length - 1; const moved = target.entities[last]; for (const column of target.columns) { column.remove(row, last); } if (row !== last) { target.entities[row] = moved; this.slots[moved.index].row = row; } target.entities.pop(); } create(data: Vec<Data>): Entity throws string { this.restructuring(); for (const item of data) { this.writing(item.component); } this.admitRevision(); if (this.free.length === 0 && this.slots.length> = 16777216) { throw "World entity limit exceeded"; } const ids = this.admit(data); const table = this.table(ids); if (this.free.length> 0 && this.slots[this.free[this.free.length - 1]].generation === 9223372036854775807) { throw "Entity generation exhausted"; } const index = this.free.length> 0 ? this.free.pop()!: this.slots.length; const generation = index <this.slots.length ? this.slots[index].generation + 1: 1; const entity: Entity = { index, generation }; const row = this.append(table, entity, data); this.serial + = 1; this.structural = this.serial; for (const id of ids) { this.versions[id] = this.serial; } const location: Location = { generation, table, row, parent: absent(), revision: this.serial }; if (index === this.slots.length) { this.slots.push(location); } else { this.slots[index] = location; } return entity; } destroy(entity: Entity): void throws string { this.restructuring(); this.admitRevision(); const location = this.location(entity); for (const id of this.archetypes[location.table].components) { this.writing(id); } this.serial + = 1; this.structural = this.serial; for (const id of this.archetypes[location.table].components) { this.versions[id] = this.serial; } for (const child of this.entities()) { if (same(this.slots[child.index].parent, entity)) { this.slots[child.index].parent = absent(); this.slots[child.index].revision = this.serial; } } this.remove(location.table, location.row); this.slots[entity.index] = { ...location, table: -1, row: -1, parent: absent(), revision: this.serial }; this.free.push(entity.index); } entities(): Vec<Entity> { let out: Vec<Entity> = []; for (const index of range(0, this.slots.length)) { if (this.slots[index].table> = 0) { out.push({ index, generation: this.slots[index].generation }); } } return out; } has(entity: Entity, component: i64): bool throws string { if (component <0 || component> = this.schemas.length) { throw "Unknown component"; } this.reading(component); const location = this.location(entity); return this.archetypes[location.table].components.includes(component); } data(entity: Entity): Vec<Data> throws string { const location = this.location(entity); const table = this.archetypes[location.table]; let out: Vec<Data> = []; for (const id of table.components) { this.reading(id); let fields: Vec<bytes> = []; for (const column of table.columns) { if (column.component === id) { fields.push(column.read(location.row)); } } out.push({ component: id, fields }); } return out; } replace(entity: Entity, data: Vec<Data>): void throws string { this.restructuring(); this.admitRevision(); const location = this.location(entity); const ids = this.admit(data); for (const id of [...this.archetypes[location.table].components, ...ids]) { this.writing(id); } const table = this.table(ids); if (table === location.table) { for (const column of this.archetypes[table].columns) { for (const item of data) { if (item.component === column.component) { column.write(location.row, item.fields[column.field]); } } } this.serial + = 1; for (const id of ids) { this.versions[id] = this.serial; } this.slots[entity.index] = { ...location, revision: this.serial }; return; } const row = this.append(table, entity, data); this.remove(location.table, location.row); this.serial + = 1; this.structural = this.serial; for (const id of [...this.archetypes[location.table].components, ...ids]) { this.versions[id] = this.serial; } this.slots[entity.index] = { ...location, table, row, revision: this.serial }; } read(entity: Entity, component: i64, field: i64): bytes throws string { this.reading(component); const location = this.location(entity); for (const column of this.archetypes[location.table].columns) { if (column.component === component && column.field === field) { return column.read(location.row); } } throw "Entity has no such component field"; } write(entity: Entity, component: i64, field: i64, value: bytes): void throws string { this.writing(component); const location = this.location(entity); if (component <0 || component> = this.schemas.length || field <0 || field> = this.schemas[component].fields.length) { throw "Unknown component field"; } valid(this.schemas[component].fields[field], value); for (const column of this.archetypes[location.table].columns) { if (column.component === component && column.field === field) { if (column.read(location.row) === value) { return; } this.admitRevision(); column.write(location.row, value); this.serial + = 1; this.versions[component] = this.serial; this.slots[entity.index] = { ...location, revision: this.serial }; return; } } throw "Entity has no such component field"; } reparent(entity: Entity, parent: Entity): void throws string { this.restructuring(); this.admitRevision(); const location = this.location(entity); let ancestor = parent; while (ancestor.index> = 0) { if (same(ancestor, entity)) { throw "Cyclic entity hierarchy"; } ancestor = this.location(ancestor).parent; } if (parent.index <0 && !same(parent, absent())) { throw "Invalid absent parent"; } this.serial + = 1; this.structural = this.serial; this.slots[entity.index] = { ...location, parent, revision: this.serial }; } parent(entity: Entity): Entity throws string { return this.location(entity).parent; } query(required: Vec<i64>, excluded: Vec<i64>, visit: (entities: Vec<Entity>, columns: Vec<ColumnView>) => void throws string): void throws string { if (this.locked) { throw "Nested world query"; } for (const id of [...required, ...excluded]) { if (id <0 || id> = this.schemas.length) { throw "Unknown query component"; } this.reading(id); } this.locked = true; try { for (const table of this.archetypes) { if (!required.every(id => table.components.includes(id)) || excluded.some(id => table.components.includes(id))) { continue; } let columns: Vec<ColumnView> = []; for (const column of table.columns) { if (this.access !== undefined && !this.access!.reads.includes(column.component) && !this.access!.writes.includes(column.component)) { continue; } columns.push({ component: column.component, field: column.field, width: column.width, data: column.data }); } if (table.entities.length> 0) { visit(table.entities, columns); } } } finally { this.locked = false; } } changes(since: i64): Vec<Changed> { let out: Vec<Changed> = []; for (const entity of this.entities()) { const revision = this.slots[entity.index].revision; if (revision> since) { out.push({ entity, revision }); } } return out; } snapshot(): bytes { let out = b"GIZWORLD\u0001"; put(out, this.schemas.length); for (const schema of this.schemas) { putText(out, schema.name); put(out, schema.fields.length); for (const field of schema.fields) { putText(out, field.name); putText(out, field.kind); put(out, field.lanes); } } put(out, this.serial); put(out, this.slots.length); for (const index of range(0, this.slots.length)) { const slot = this.slots[index]; put(out, slot.generation); put(out, slot.revision); put(out, slot.table> = 0 ? 1: 0); if (slot.table <0) { continue; } put(out, slot.parent.index + 1); put(out, slot.parent.generation); const data = this.data({ index, generation: slot.generation })!; put(out, data.length); for (const item of data) { put(out, item.component); for (const value of item.fields) { out + = value; } } } put(out, this.free.length); for (const index of this.free) { put(out, index); } put(out, this.structural); for (const revision of this.versions) { put(out, revision); } return out; } restore(data: bytes): void throws string { if (this.locked || this.access !== undefined) { throw "Restore during a query or system"; } if (this.replacement === 9223372036854775807) { throw "World replacement epoch exhausted"; } const replacement = new World(); replacement.decode(data); if (this.schemas.length> 0 && schemaKey(this.schemas) !== schemaKey(replacement.schemas)) { throw "Snapshot component schema differs"; } this.schemas = replacement.schemas; this.slots = replacement.slots; this.free = replacement.free; this.archetypes = replacement.archetypes; this.serial = replacement.serial; this.structural = replacement.structural; this.versions = replacement.versions; this.replacement+ = 1; } private decode(data: bytes): void throws string { const reader = new Reader(data); if (reader.take(9) !== b"GIZWORLD\u0001") { throw "Unknown world snapshot"; } const schemas = reader.count(4096); for (const at of range(0, schemas)) { const name = reader.text(); let fields: Vec<Field> = []; const count = reader.count(4096); for (const f of range(0, count)) { fields.push({ name: reader.text(), kind: reader.text(), lanes: reader.count(4096) }); } this.register({ name, fields }); } this.serial = reader.integer(); const slots = reader.count(16777216); for (const index of range(0, slots)) { const generation = reader.integer(); const revision = reader.integer(); const live = reader.count(1); if (generation <1 || revision> this.serial) { throw "Invalid entity generation or revision"; } if (live === 0) { this.slots.push({ generation, revision, table: -1, row: -1, parent: absent() }); continue; } const parent: Entity = { index: reader.integer() - 1, generation: reader.integer() }; let values: Vec<Data> = []; const count = reader.count(this.schemas.length); for (const n of range(0, count)) { const component = reader.count(this.schemas.length - 1); let fields: Vec<bytes> = []; for (const field of this.schemas[component].fields) { fields.push(reader.take(width(field))); } values.push({ component, fields }); } const table = this.table(this.admit(values)); const entity: Entity = { index, generation }; const row = this.append(table, entity, values); this.slots.push({ generation, revision, table, row, parent }); } const free = reader.count(slots); let seen = new Set<i64>(); for (const at of range(0, free)) { const index = reader.count(slots - 1); if (this.slots[index].table> = 0 || seen.has(index)) { throw "Invalid free entity slot"; } seen.add(index); this.free.push(index); } this.structural = reader.integer(); if (this.structural> this.serial) { throw "Invalid structural revision"; } for (const component of range(0, this.schemas.length)) { const revision = reader.integer(); if (revision> this.serial) { throw "Invalid component revision"; } this.versions[component] = revision; } if (reader.remaining() !== 0 || free !== slots - this.entities().length) { throw "Invalid snapshot size or free list"; } for (const entity of this.entities()) { let parent = this.parent(entity); let depth: i64 = 0; while (parent.index> = 0) { if (same(parent, entity) || depth> = slots) { throw "Cyclic snapshot hierarchy"; } parent = this.location(parent).parent; depth + = 1; } if (!same(parent, absent())) { throw "Invalid absent parent"; } } } }
```

One simulation or editing instance. All structural changes and scalar writes pass through this owner.

- `schemas`: `Vec<M186.Schema>`
- `editing`: `i64`
- `slots`: `Vec<M186.Location>`
- `free`: `Vec<i64>`
- `archetypes`: `Vec<Ref<M186.Archetype>>`
- `serial`: `i64`
- `structural`: `i64`
- `versions`: `Vec<i64>`
- `replacement`: `i64`
- `locked`: `bool`
- `access`: `_gizlang_sdk_core.Option<M186.Access>`

## Functions

### `absent`

```gizlang
function absent(): Entity
```

No entity, used for roots and optional references.

Effects: fail.

### `same`

```gizlang
function same(a: Entity, b: Entity): bool
```

Exact identity, including the incarnation.

### `entityBytes`

```gizlang
function entityBytes(entity: Entity): bytes
```

An entity field's exact little-endian representation. Zero/zero represents no reference.

Effects: fail, alloc.

### `entityFrom`

```gizlang
function entityFrom(value: bytes): Entity throws string
```

Decodes an entity field without lossy f64 or JavaScript number conversion.

Effects: fail.

### `width`

```gizlang
function width(field: Field): i64 throws string
```

The byte width of FIELD. Invalid schemas fail before an archetype is allocated.

Effects: fail, alloc.

### `schemaKey`

```gizlang
function schemaKey(schemas: Vec<Schema>): string
```

The structural schema identity, independent of a world's data.

Effects: fail, alloc.

## Methods

### `World.system`

```gizlang
system(reads: Vec<i64>, writes: Vec<i64>, structural: bool, run: () => void throws string): void throws string
```

Runs one declared system access scope. Edit operations outside a system use the same validation without a scope.

Effects: fail, read, write, console, io, alloc.

### `World.transaction`

```gizlang
transaction<T>(edit: (world: World, before: bytes) => T throws string): T throws string
```

Applies an editor operation atomically against a fixed schema. BEFORE is the same snapshot used for rollback.

### `World.schema`

```gizlang
schema(): Vec<Schema>
```

A world's component schemas, in their stable registration order.

Effects: fail, read.

### `World.revision`

```gizlang
revision(): i64
```

The latest committed change number. Reads and queries do not change it.

Effects: fail, read.

### `World.componentRevision`

```gizlang
componentRevision(components: Vec<i64>): i64 throws string
```

Changes to the declared component set, plus entity/hierarchy structural changes.

Effects: fail, read.

### `World.epoch`

```gizlang
epoch(): i64
```

A local cache invalidation epoch. It changes on state replacement and is not serialized as game state.

Effects: fail, read.

### `World.register`

```gizlang
register(component: Schema): i64 throws string
```

Registers a component before any entity is created. Duplicate names or fields are refused.

Effects: fail, read, write, alloc.

### `World.alive`

```gizlang
alive(entity: Entity): bool
```

Whether ENTITY still identifies a live row of this world.

Effects: fail, read.

### `World.create`

```gizlang
create(data: Vec<Data>): Entity throws string
```

Creates a validated bundle. A free slot receives a new generation; physical rows may move freely.

Effects: fail, read, write, alloc.

### `World.destroy`

```gizlang
destroy(entity: Entity): void throws string
```

Deletes an entity and detaches its children. The next use of this identity is refused.

Effects: fail, read, write, alloc.

### `World.entities`

```gizlang
entities(): Vec<Entity>
```

The live entities in slot order, independent of physical row movement.

Effects: fail, read, alloc.

### `World.has`

```gizlang
has(entity: Entity, component: i64): bool throws string
```

Whether ENTITY has COMPONENT. A stale identity fails rather than matching another row.

Effects: fail, read, alloc.

### `World.data`

```gizlang
data(entity: Entity): Vec<Data> throws string
```

All component data of ENTITY, in schema ID order. Returned bytes are owned values.

Effects: fail, read, alloc.

### `World.replace`

```gizlang
replace(entity: Entity, data: Vec<Data>): void throws string
```

Replaces an entity's bundle atomically after validation. Identity and parent stay unchanged.

Effects: fail, read, write, alloc.

### `World.read`

```gizlang
read(entity: Entity, component: i64, field: i64): bytes throws string
```

Reads one field; no implicit zero or missing-component fallback.

Effects: fail, read, alloc.

### `World.write`

```gizlang
write(entity: Entity, component: i64, field: i64, value: bytes): void throws string
```

Writes one validated field and records its entity's revision.

Effects: fail, read, write, alloc.

### `World.reparent`

```gizlang
reparent(entity: Entity, parent: Entity): void throws string
```

Changes the parent after checking liveness and cycles. Hierarchy never owns a second entity store.

Effects: fail, read, write, alloc.

### `World.parent`

```gizlang
parent(entity: Entity): Entity throws string
```

The parent of a live entity, or absent for a root.

Effects: fail, read.

### `World.query`

```gizlang
query(required: Vec<i64>, excluded: Vec<i64>, visit: (entities: Vec<Entity>, columns: Vec<ColumnView>) => void throws string): void throws string
```

Visits matching chunks. Structural changes are refused until every chunk is released, including after a throw.

Effects: fail, read, write, console, io, alloc.

### `World.changes`

```gizlang
changes(since: i64): Vec<Changed>
```

Live entities changed after SINCE. Deletion is detected through revision plus a fresh entity list.

Effects: fail, read, alloc.

### `World.snapshot`

```gizlang
snapshot(): bytes
```

Canonical binary state, including schemas, dead generations and free-list order. No GPU or host handles.

Effects: fail, read, alloc.

### `World.restore`

```gizlang
restore(data: bytes): void throws string
```

Restores in place only after the complete replacement validates. Existing references retain this World.

Effects: fail, read, write, alloc.

