dredless 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/EVENTS.md CHANGED
@@ -66,7 +66,7 @@ These events receive an update object with `.world` referencing the already-upda
66
66
  | Event | Callback arguments | Important fields |
67
67
  |-----------------|--------------------|-------------------------------------------------------------------------------|
68
68
  | `world` | `(update)` | `update.world` with metadata applied |
69
- | `tiles` | `(update)` | `world`, `decoded`, `updates`, `errors` |
69
+ | `tiles` | `(update)` | `world`, `decoded`, `updates`, `errors`; chunk `tiles` are built when read |
70
70
  | `model` | `(update)` | `world`, `result` with model changes, side events, command number, timing |
71
71
  | `comms-bubble` | `(update)` | `world`, `packet`, `bubble` |
72
72
  | `world-removed` | See below | World removed from store |
@@ -27,7 +27,7 @@ The ship world describes its interior. The overworld contains ship entities and
27
27
  represented in the overworld without their interiors being decoded. An entity ID is meaningful only together with its
28
28
  world.
29
29
 
30
- A `WorldDomain` exposes `id`, `exists()`, `entities`, `machines`, `players`, `blocks`, and `materials`, plus
30
+ A `WorldDomain` exposes `id`, `exists()`, `entities`, `machines`, `players`, `blocks`, `materials`, and `tiles`, plus
31
31
  `snapshot(options?)`. A `ShipDomain` adds `metadata`, `entity()`, and `overworldEntity`. These refer to the ship's
32
32
  associated overworld entity when available, not its local player.
33
33
 
@@ -107,6 +107,50 @@ not freeze them.
107
107
  Materials summarize decoded blocks; they are not an authoritative ship inventory. A missing collection or component can
108
108
  reflect incomplete decoding, not an absent server object.
109
109
 
110
+ ### Tiles
111
+
112
+ ```ts
113
+ world.tiles.count: number;
114
+ world.tiles.version: number; // Bumped on every tile write.
115
+ world.tiles.chunks(): TileChunkView[]; // Live typed-array views; no allocation.
116
+ world.tiles.at(x: number, y: number): Tile | null;
117
+ world.tiles.all(): Tile[]; // Builds tile objects.
118
+ ```
119
+
120
+ Tiles are stored as byte columns per 64x64 chunk, not as objects. `chunks()` reads that storage directly, so it is the
121
+ read to use when scanning every tile each tick: it allocates nothing and does not add garbage-collection work to packet
122
+ handling. `all()` builds `Tile` objects; use it for occasional reads. Each kind of read has one entry point. On a
123
+ `WorldState` the same reads are `tileChunks()`, `tileAt()`, `tileVersion`, `tiles.size`, and `tiles.toArray()`;
124
+ `WorldState.tiles` is not a `Map` and is not iterable.
125
+
126
+ A `TileChunkView` has `chunkX`, `chunkY`, `originX`, `originY`, `version`, and the `material`, `shape`, `hp`, `color`,
127
+ and `flags` byte arrays. Cell `i` is the tile at `(originX + (i & 63), originY + (i >> 6))`. A `flags` value of `0`
128
+ means the cell is empty; `TileFlags.NoColor` means the tile has no color. Views stay valid for the life of the chunk and
129
+ always show current state, so treat them as read-only and compare `version` to skip chunks that have not changed.
130
+
131
+ **Fragment:** rescan only the chunks that changed since the last tick:
132
+
133
+ ```js
134
+ import {TileFlags} from "dredless";
135
+
136
+ const seen = new Map();
137
+ function scanChangedTiles(world) {
138
+ for (const chunk of world.tiles.chunks()) {
139
+ if (seen.get(chunk) === chunk.version) continue;
140
+ seen.set(chunk, chunk.version);
141
+ const {material, hp, flags, originX, originY} = chunk;
142
+ for (let i = 0; i < flags.length; i++) {
143
+ if (!(flags[i] & TileFlags.Present)) continue;
144
+ onTile(originX + (i & 63), originY + (i >> 6), material[i], hp[i]);
145
+ }
146
+ }
147
+ }
148
+ ```
149
+
150
+ Tile objects are built on demand, so two reads may return different objects for the same tile and changing a returned
151
+ object does not change client state. A tile set through `WorldState.setTile()` with non-byte values or extra fields is
152
+ kept as given and appears in `at()` and `all()`, but not in chunk views.
153
+
110
154
  ## Projectiles, bots, and special entities
111
155
 
112
156
  Every world domain exposes these collections. They return current component summaries; `get()` returns `null` when
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dredless",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "A fully-featured and from-scratch headless drednot.io client implementation written in pure js.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/certainhuman/dredless#readme",
package/src/browser.d.ts CHANGED
@@ -39,6 +39,7 @@ export {
39
39
  TurretMode,
40
40
  WorldStore,
41
41
  WorldState,
42
+ TileFlags,
42
43
  ModelState,
43
44
  FabricatorType,
44
45
  decodeModelData,
package/src/browser.js CHANGED
@@ -13,7 +13,7 @@ export {
13
13
  export {Connection} from "./network/connection.js";
14
14
  export {DropReason, DisconnectError, normalizeDisconnect} from "./network/disconnect.js";
15
15
  export {DredlessClient, WrenchMode, TurretMode} from "./client/index.js";
16
- export {WorldStore, WorldState} from "./state/world/index.js";
16
+ export {WorldStore, WorldState, TileFlags} from "./state/world/index.js";
17
17
  export {FabricatorType, ModelState, decodeModelData} from "./state/model/index.js";
18
18
  export {generateGeneratorMaze, solveGeneratorMazeSeed, maybeSolveGeneratorMazeSeed} from "./state/generator-maze.js";
19
19
  export {buildBlueprintPlacementMessage} from "./protocol/outbound/blueprint.js";
@@ -435,6 +435,7 @@ export class WorldDomain {
435
435
  this.recyclers = new EntitySummaryCollection(client, scope, "recyclers");
436
436
  this.blocks = new BlockCollection(client, scope);
437
437
  this.materials = new MaterialCollection(client, scope);
438
+ this.tiles = new TileDomain(client, scope);
438
439
  }
439
440
 
440
441
  get id() {
@@ -681,6 +682,36 @@ export class MaterialCollection {
681
682
  }
682
683
  }
683
684
 
685
+ // Tile reads for a world. `chunks()` reads the columnar store directly and
686
+ // allocates nothing, so it is safe to scan every tick; `all()` and `at()` build
687
+ // tile objects.
688
+ export class TileDomain {
689
+ constructor(client, scope) {
690
+ this.client = client;
691
+ this.scope = scope;
692
+ }
693
+
694
+ get count() {
695
+ return worldStateFor(this.client, this.scope)?.tiles.size ?? 0;
696
+ }
697
+
698
+ get version() {
699
+ return worldStateFor(this.client, this.scope)?.tileVersion ?? 0;
700
+ }
701
+
702
+ chunks() {
703
+ return worldStateFor(this.client, this.scope)?.tileChunks() || [];
704
+ }
705
+
706
+ at(x, y) {
707
+ return worldStateFor(this.client, this.scope)?.tileAt(x, y) ?? null;
708
+ }
709
+
710
+ all() {
711
+ return worldStateFor(this.client, this.scope)?.tiles.toArray() || [];
712
+ }
713
+ }
714
+
684
715
  export class MachineCollection {
685
716
  constructor(client, scope) {
686
717
  this.client = client;
@@ -246,19 +246,38 @@ function chacha20Xor(key, nonce, data) {
246
246
  return chacha20Into(out, key, nonce, data.length, data);
247
247
  }
248
248
 
249
+ // A world's key bytes are fixed for its lifetime, so encode them once rather
250
+ // than on every packet.
251
+ const WORLD_KEY_CACHE = new Map();
252
+ const WORLD_KEY_CACHE_LIMIT = 64;
253
+ // Reused per packet: the key and nonce are consumed synchronously.
254
+ const MATERIAL_SCRATCH = new Uint8Array(44);
255
+
256
+ function worldKeyBytes(worldId, seed) {
257
+ const text = `${worldId}${seed}`;
258
+ let bytes = WORLD_KEY_CACHE.get(text);
259
+ if (!bytes) {
260
+ if (WORLD_KEY_CACHE.size >= WORLD_KEY_CACHE_LIMIT) WORLD_KEY_CACHE.clear();
261
+ bytes = encoder.encode(text);
262
+ WORLD_KEY_CACHE.set(text, bytes);
263
+ }
264
+ return bytes;
265
+ }
266
+
249
267
  function decryptPayload(wireBytes, worldId, seed) {
250
268
  const wire = toUint8Array(wireBytes);
251
- if (wire.length < 8) throw new Error("payload too short");
252
- const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
253
- const packetWordA = view.getUint32(0, true);
254
- const packetWordB = view.getUint32(wire.length - 4, true);
255
- const material = Uint8Array.from(SHARED_CHACHA_MATERIAL);
256
- const worldKey = encoder.encode(`${worldId}${seed}`);
269
+ const length = wire.length;
270
+ if (length < 8) throw new Error("payload too short");
271
+ const packetWordA = readLe32(wire, 0);
272
+ const packetWordB = readLe32(wire, length - 4);
273
+ const material = MATERIAL_SCRATCH;
274
+ const worldKey = worldKeyBytes(worldId, seed);
275
+ const keyLength = worldKey.length;
257
276
  for (let i = 0, l = 0, r = 0; i < 44; i++, l += 7, r += 11) {
258
- material[i] ^= worldKey[i % worldKey.length] ^ (rotl32(packetWordA, l) & 0xff) ^ (rotr32(packetWordB, r) & 0xff);
277
+ material[i] = SHARED_CHACHA_MATERIAL[i] ^ worldKey[i % keyLength] ^ (rotl32(packetWordA, l) & 0xff) ^ (rotr32(packetWordB, r) & 0xff);
259
278
  }
260
279
  // subarray, not slice: the key and nonce are only read.
261
- const ciphertext = wire.subarray(4, wire.length - 4);
280
+ const ciphertext = wire.subarray(4, length - 4);
262
281
  return chacha20Xor(material.subarray(0, 32), material.subarray(32, 44), ciphertext);
263
282
  }
264
283
 
package/src/index.d.ts CHANGED
@@ -979,6 +979,7 @@ export interface WorldDomain {
979
979
  recyclers: EntitySummaryCollection<RecyclerSummary>;
980
980
  blocks: BlockCollection;
981
981
  materials: MaterialCollection;
982
+ tiles: TileDomain;
982
983
 
983
984
  exists(): boolean;
984
985
 
@@ -1100,6 +1101,22 @@ export interface MaterialCollection {
1100
1101
  all(): MaterialSummary[];
1101
1102
  }
1102
1103
 
1104
+ /** Tile reads for one world. `chunks()` allocates nothing and is safe to scan every tick. */
1105
+ export interface TileDomain {
1106
+ /** Number of tiles currently stored. */
1107
+ readonly count: number;
1108
+ /** Bumped on every tile write; 0 when the world is unknown. */
1109
+ readonly version: number;
1110
+
1111
+ /** Live, zero-copy views of each 64x64 chunk. Treat as read-only. */
1112
+ chunks(): TileChunkView[];
1113
+
1114
+ at(x: number, y: number): Tile | null;
1115
+
1116
+ /** Every tile as an object. Prefer `chunks()` for per-tick scans. */
1117
+ all(): Tile[];
1118
+ }
1119
+
1103
1120
  export interface MachineCollection {
1104
1121
  state(): MachineSummary;
1105
1122
 
@@ -1812,7 +1829,10 @@ export class WorldState {
1812
1829
  blockHeight: number | null;
1813
1830
  parentWorld: number | null;
1814
1831
  parentEntity: number | null;
1815
- tiles: Map<string, Tile>;
1832
+ /** This world's tiles as objects: `size` and `toArray()`. */
1833
+ tiles: TileCollection;
1834
+ /** Bumped on every tile write. */
1835
+ readonly tileVersion: number;
1816
1836
  chunks: unknown[];
1817
1837
  events: unknown[];
1818
1838
  modelPackets: unknown[];
@@ -1832,6 +1852,18 @@ export class WorldState {
1832
1852
 
1833
1853
  applyChunk(value: unknown): Tile[] | null;
1834
1854
 
1855
+ /** Applies a chunk patch; the returned entry builds its `tiles` array on first read. */
1856
+ applyChunkPatch(value: unknown): TileChunkPatch | null;
1857
+
1858
+ /** Live, zero-copy views of each 64x64 chunk. Stable for the life of the chunk; treat as read-only. */
1859
+ tileChunks(): TileChunkView[];
1860
+
1861
+ /** O(1) lookup of the tile at a coordinate. */
1862
+ tileAt(x: number, y: number): Tile | null;
1863
+
1864
+ /** Drops tile objects retained for repeated `tiles.toArray()` reads. */
1865
+ releaseTileObjects(): void;
1866
+
1835
1867
  setTile(tile: Tile): Tile;
1836
1868
 
1837
1869
  normalizeTile(tile: Tile): Tile;
@@ -1873,6 +1905,58 @@ export interface Tile {
1873
1905
  hpValue?: number | null;
1874
1906
  }
1875
1907
 
1908
+ /**
1909
+ * Tile objects for a world. Objects are built on demand from columnar storage:
1910
+ * they are not identity-stable across writes and mutating one does not change
1911
+ * stored state. There is intentionally no iterator; iterate the array.
1912
+ */
1913
+ export interface TileCollection {
1914
+ readonly size: number;
1915
+
1916
+ /** A fresh array of every tile, ordered by chunk. */
1917
+ toArray(): Tile[];
1918
+ }
1919
+
1920
+ /** Values of `TileChunkView.flags`. Zero means the cell holds no tile. */
1921
+ export const TileFlags: {
1922
+ /** The cell holds a tile. */
1923
+ readonly Present: 1;
1924
+ /** The tile was sent without a color; its `color` is null. */
1925
+ readonly NoColor: 2;
1926
+ };
1927
+
1928
+ /**
1929
+ * One 64x64 chunk of tiles as byte columns. Cell `i` is the tile at
1930
+ * `(originX + (i & 63), originY + (i >> 6))`. The arrays are live views of
1931
+ * client state: they change as packets arrive and must not be written to.
1932
+ */
1933
+ export interface TileChunkView {
1934
+ readonly chunkX: number;
1935
+ readonly chunkY: number;
1936
+ readonly originX: number;
1937
+ readonly originY: number;
1938
+ /** `WorldState.tileVersion` at this chunk's last write. */
1939
+ readonly version: number;
1940
+ readonly material: Uint8Array;
1941
+ readonly shape: Uint8Array;
1942
+ /** Raw 0-255 HP fraction byte. */
1943
+ readonly hp: Uint8Array;
1944
+ /** Meaningful only where `flags` lacks `TileFlags.NoColor`. */
1945
+ readonly color: Uint8Array;
1946
+ readonly flags: Uint8Array;
1947
+ }
1948
+
1949
+ export interface TileChunkPatch {
1950
+ chunkX: number;
1951
+ chunkY: number;
1952
+ minX: number;
1953
+ minY: number;
1954
+ maxX: number;
1955
+ maxY: number;
1956
+ /** Built on first read. */
1957
+ readonly tiles: Tile[];
1958
+ }
1959
+
1876
1960
  export interface MaterialSummary {
1877
1961
  material: number;
1878
1962
  name: string | null;
package/src/index.js CHANGED
@@ -14,7 +14,7 @@ export {Session, AnonSession} from "./network/session.js";
14
14
  export {Connection} from "./network/connection.js";
15
15
  export {DropReason, DisconnectError, normalizeDisconnect} from "./network/disconnect.js";
16
16
  export {DredlessClient, WrenchMode, TurretMode} from "./client/index.js";
17
- export {WorldStore, WorldState} from "./state/world/index.js";
17
+ export {WorldStore, WorldState, TileFlags} from "./state/world/index.js";
18
18
  export {FabricatorType, ModelState, decodeModelData} from "./state/model/index.js";
19
19
  export {generateGeneratorMaze, solveGeneratorMazeSeed, maybeSolveGeneratorMazeSeed} from "./state/generator-maze.js";
20
20
  export {buildBlueprintPlacementMessage} from "./protocol/outbound/blueprint.js";
@@ -11,6 +11,9 @@ function isArrayBufferLike(value) {
11
11
 
12
12
  function toUint8Array(value) {
13
13
  if (value instanceof Uint8Array) return value;
14
+ // Fast path for the websocket's own buffers; the tag check below covers
15
+ // cross-realm ArrayBuffers and SharedArrayBuffer.
16
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
14
17
  if (isArrayBufferLike(value)) return new Uint8Array(value);
15
18
  if (ArrayBuffer.isView(value)) {
16
19
  return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
@@ -430,10 +430,41 @@ function readArrayFast(bytes, count) {
430
430
  return items;
431
431
  }
432
432
 
433
+ // Packet maps repeat the same few dozen short keys. Resolve those through a
434
+ // small byte-keyed cache instead of a TextDecoder call per key.
435
+ const KEY_CACHE = new Map();
436
+ const KEY_CACHE_LIMIT = 512;
437
+
438
+ function readKeyFast(bytes) {
439
+ const head = bytes[cursor];
440
+ if ((head & 0xe0) !== 0xa0) return readFast(bytes);
441
+ const len = head & 0x1f;
442
+ const start = cursor + 1;
443
+ const end = start + len;
444
+ if (end > bytes.length) return readFast(bytes);
445
+ let hash = len;
446
+ for (let i = start; i < end; i++) hash = (Math.imul(hash, 31) + bytes[i]) | 0;
447
+ const entry = KEY_CACHE.get(hash);
448
+ if (entry !== undefined) {
449
+ const cached = entry.bytes;
450
+ let same = cached.length === len;
451
+ for (let i = 0; same && i < len; i++) same = cached[i] === bytes[start + i];
452
+ if (same) {
453
+ cursor = end;
454
+ return entry.text;
455
+ }
456
+ }
457
+ cursor = start;
458
+ const text = readStrFast(bytes, len);
459
+ // A colliding key is simply decoded each time; the first one keeps the slot.
460
+ if (entry === undefined && KEY_CACHE.size < KEY_CACHE_LIMIT) KEY_CACHE.set(hash, {bytes: bytes.slice(start, end), text});
461
+ return text;
462
+ }
463
+
433
464
  function readMapFast(bytes, count) {
434
465
  const obj = {};
435
466
  for (let i = 0; i < count; i++) {
436
- const key = readFast(bytes);
467
+ const key = readKeyFast(bytes);
437
468
  obj[typeof key === "string" ? key : String(key)] = readFast(bytes);
438
469
  }
439
470
  return obj;
@@ -1,3 +1,3 @@
1
- export {WorldStore, WorldState} from "./world/index.js";
1
+ export {WorldStore, WorldState, TileFlags} from "./world/index.js";
2
2
  export {FabricatorType, ModelState, decodeModelData} from "./model/index.js";
3
3
  export {generateGeneratorMaze, solveGeneratorMazeSeed, maybeSolveGeneratorMazeSeed} from "./generator-maze.js";
@@ -21,12 +21,15 @@ export function defineLazyProperty(target, key, compute) {
21
21
  if (!resolved) {
22
22
  cached = compute();
23
23
  resolved = true;
24
+ // Release whatever the closure captured once it has run.
25
+ compute = null;
24
26
  }
25
27
  return cached;
26
28
  },
27
29
  set(value) {
28
30
  cached = value;
29
31
  resolved = true;
32
+ compute = null;
30
33
  }
31
34
  });
32
35
  return target;
@@ -367,6 +370,7 @@ for (const spec of MODEL_TABLE_SPECS.values()) {
367
370
  for (const blob of spec.blobs || []) blob.key = blobKey(blob.offset);
368
371
  for (const item of spec.packedBits || []) item.key = qKey(item.offset);
369
372
  if (spec.packedOffsets) spec.packedOffsetKeys = spec.packedOffsets.map(qKey);
373
+ spec.packedAnyMask = (spec.packedBits || []).reduce((mask, item) => mask | item.bit, spec.packedMask || 0);
370
374
  if (spec.orderedValues) {
371
375
  spec.orderedItems = [
372
376
  ...(spec.blobs || []).map((item) => ({bit: item.bit, offset: item.offset, key: item.key, kind: "blob"})),
@@ -179,7 +179,7 @@ export class ModelState {
179
179
  entity(entityId) {
180
180
  const id = Number(entityId);
181
181
  if (!Number.isFinite(id)) return null;
182
- return this.#derivedState().entitiesById.get(id) || null;
182
+ return this.#derivedEntityIndex().entitiesById.get(id) || null;
183
183
  }
184
184
 
185
185
  entities() {
@@ -194,7 +194,7 @@ export class ModelState {
194
194
  // O(1) point lookup. Callers previously had to materialise and scan the whole
195
195
  // block list to answer this.
196
196
  blockAt(x, y) {
197
- this.#derivedState();
197
+ this.#derivedEntityIndex();
198
198
  return this.#blocksIndex().get(blockKey(x, y)) || null;
199
199
  }
200
200
 
@@ -400,20 +400,48 @@ export class ModelState {
400
400
  }
401
401
 
402
402
  #updateDerived(update) {
403
- if (!this._derived) return;
403
+ const derived = this._derived;
404
+ if (!derived) return;
404
405
  if (!update.removals.length && !update.changedEntities.size) return;
405
406
 
406
407
  for (const section of update.sections) {
407
408
  for (const record of section.records || []) this.#addDerivedEntityTable(record.entity, section.table);
408
409
  }
409
410
 
411
+ // Only record what changed. Re-summarising happens on the next read, so
412
+ // an entity that moves every tick is summarised once per read rather
413
+ // than once per packet, and ingestion costs the same whether or not
414
+ // anything has read derived state.
415
+ const dirty = derived.dirtyEntities ??= new Set();
410
416
  if (update.sections.some((section) => section.table === 12)) {
417
+ // Player summaries embed blueprint previews, so they change too.
411
418
  for (const entityId of this.table(55).keys()) update.changedEntities.add(entityId);
412
419
  }
413
- for (const entityId of update.removals) this.#removeDerivedEntity(entityId);
414
- for (const entityId of update.changedEntities) this.#refreshDerivedEntity(entityId);
415
- this._derived.summariesDirty = true;
416
- this._derived.tableSummariesDirty = true;
420
+ for (const entityId of update.removals) {
421
+ derived.entityTableIds.delete(entityId);
422
+ dirty.add(entityId);
423
+ }
424
+ for (const entityId of update.changedEntities) dirty.add(entityId);
425
+ }
426
+
427
+ #flushDerivedEntities() {
428
+ const derived = this._derived;
429
+ const dirty = derived.dirtyEntities;
430
+ if (!dirty || dirty.size === 0) return;
431
+ derived.dirtyEntities = null;
432
+ // An entity with no remaining rows is dropped by the refresh.
433
+ for (const entityId of dirty) this.#refreshDerivedEntity(entityId);
434
+ derived.summariesDirty = true;
435
+ derived.tableSummariesDirty = true;
436
+ }
437
+
438
+ // Current entity summaries without the per-category lists. Point lookups go
439
+ // through here: rebuilding those lists is O(total entities) and was the whole
440
+ // cost of entity(id) on a large world.
441
+ #derivedEntityIndex() {
442
+ if (!this._derived) return this.#derivedState();
443
+ this.#flushDerivedEntities();
444
+ return this._derived;
417
445
  }
418
446
 
419
447
  #updateNavigationUnitAutoWarp(update) {
@@ -558,6 +586,7 @@ export class ModelState {
558
586
 
559
587
  #derivedState() {
560
588
  if (this._derived) {
589
+ this.#flushDerivedEntities();
561
590
  this.#ensureDerivedSummaries();
562
591
  return this._derived;
563
592
  }
@@ -645,7 +674,7 @@ export class ModelState {
645
674
 
646
675
  const next = this.#summarizeEntity(entityId, rows);
647
676
  derived.entitiesById.set(entityId, next);
648
- if (!derived.entityIds.includes(entityId)) insertSorted(derived.entityIds, entityId);
677
+ if (!old) insertSorted(derived.entityIds, entityId);
649
678
  this.#addEntityToDerivedBlocks(derived, next);
650
679
  derived.entityCount = derived.entityIds.length;
651
680
  }
@@ -1199,10 +1228,7 @@ export class ModelState {
1199
1228
  return;
1200
1229
  }
1201
1230
 
1202
- const hasPacked = Boolean(
1203
- (spec.packedMask && (mask & spec.packedMask)) ||
1204
- spec.packedBits?.some((item) => mask & item.bit)
1205
- );
1231
+ const hasPacked = (mask & spec.packedAnyMask) !== 0;
1206
1232
  let packed = null;
1207
1233
  if (hasPacked && spec.packedBeforeValues) packed = reader.readUnsigned();
1208
1234
 
@@ -1,8 +1,12 @@
1
1
  export {
2
2
  WorldStore,
3
3
  WorldState,
4
+ TileFlags,
4
5
  ModelState,
5
6
  type Tile,
7
+ type TileCollection,
8
+ type TileChunkView,
9
+ type TileChunkPatch,
6
10
  type TileDefinition,
7
11
  type Tileset,
8
12
  type OverworldZoneSummary,
@@ -1,8 +1,9 @@
1
- import {WorldState} from "./state.js";
1
+ import {TileFlags, WorldState} from "./state.js";
2
2
  import {ModelState} from "../model/index.js";
3
+ import {defineLazyProperty} from "../model/decoder.js";
3
4
  import {decodeModelPayload} from "../../protocol/inbound/world-payload.js";
4
5
 
5
- export {WorldState};
6
+ export {WorldState, TileFlags};
6
7
 
7
8
  // Retention limits for per-world history. These arrays previously grew without
8
9
  // bound for the lifetime of a connection. Pass Infinity to restore that.
@@ -143,7 +144,12 @@ export class WorldStore {
143
144
  if (decoded && typeof decoded === "object") {
144
145
  for (const [kind, value] of Object.entries(decoded)) {
145
146
  try {
146
- if (kind === "0") updates.push({kind, tiles: world.applyChunk(value)});
147
+ if (kind === "0") {
148
+ // `tiles` is built on first read: most consumers never
149
+ // look at it, and a full chunk is 4096 objects.
150
+ const patch = world.applyChunkPatch(value);
151
+ updates.push(defineLazyProperty({kind}, "tiles", () => (patch ? patch.tiles : null)));
152
+ }
147
153
  else if (kind === "1") updates.push({kind, tile: world.applyTile(value)});
148
154
  else updates.push({kind, value});
149
155
  } catch (error) {