dredless 1.4.0 → 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.
@@ -3427,6 +3427,7 @@
3427
3427
  }
3428
3428
  function toUint8Array(value) {
3429
3429
  if (value instanceof Uint8Array) return value;
3430
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
3430
3431
  if (isArrayBufferLike(value)) return new Uint8Array(value);
3431
3432
  if (ArrayBuffer.isView(value)) {
3432
3433
  return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
@@ -3729,18 +3730,32 @@
3729
3730
  }
3730
3731
  return chacha20Into(out, key, nonce, data.length, data);
3731
3732
  }
3733
+ var WORLD_KEY_CACHE = /* @__PURE__ */ new Map();
3734
+ var WORLD_KEY_CACHE_LIMIT = 64;
3735
+ var MATERIAL_SCRATCH = new Uint8Array(44);
3736
+ function worldKeyBytes(worldId, seed) {
3737
+ const text2 = `${worldId}${seed}`;
3738
+ let bytes = WORLD_KEY_CACHE.get(text2);
3739
+ if (!bytes) {
3740
+ if (WORLD_KEY_CACHE.size >= WORLD_KEY_CACHE_LIMIT) WORLD_KEY_CACHE.clear();
3741
+ bytes = encoder.encode(text2);
3742
+ WORLD_KEY_CACHE.set(text2, bytes);
3743
+ }
3744
+ return bytes;
3745
+ }
3732
3746
  function decryptPayload(wireBytes, worldId, seed) {
3733
3747
  const wire = toUint8Array(wireBytes);
3734
- if (wire.length < 8) throw new Error("payload too short");
3735
- const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
3736
- const packetWordA = view.getUint32(0, true);
3737
- const packetWordB = view.getUint32(wire.length - 4, true);
3738
- const material = Uint8Array.from(SHARED_CHACHA_MATERIAL);
3739
- const worldKey = encoder.encode(`${worldId}${seed}`);
3748
+ const length = wire.length;
3749
+ if (length < 8) throw new Error("payload too short");
3750
+ const packetWordA = readLe32(wire, 0);
3751
+ const packetWordB = readLe32(wire, length - 4);
3752
+ const material = MATERIAL_SCRATCH;
3753
+ const worldKey = worldKeyBytes(worldId, seed);
3754
+ const keyLength = worldKey.length;
3740
3755
  for (let i = 0, l = 0, r = 0; i < 44; i++, l += 7, r += 11) {
3741
- material[i] ^= worldKey[i % worldKey.length] ^ rotl32(packetWordA, l) & 255 ^ rotr32(packetWordB, r) & 255;
3756
+ material[i] = SHARED_CHACHA_MATERIAL[i] ^ worldKey[i % keyLength] ^ rotl32(packetWordA, l) & 255 ^ rotr32(packetWordB, r) & 255;
3742
3757
  }
3743
- const ciphertext = wire.subarray(4, wire.length - 4);
3758
+ const ciphertext = wire.subarray(4, length - 4);
3744
3759
  return chacha20Xor(material.subarray(0, 32), material.subarray(32, 44), ciphertext);
3745
3760
  }
3746
3761
 
@@ -3957,10 +3972,36 @@
3957
3972
  for (let i = 0; i < count; i++) items[i] = readFast(bytes);
3958
3973
  return items;
3959
3974
  }
3975
+ var KEY_CACHE = /* @__PURE__ */ new Map();
3976
+ var KEY_CACHE_LIMIT = 512;
3977
+ function readKeyFast(bytes) {
3978
+ const head = bytes[cursor];
3979
+ if ((head & 224) !== 160) return readFast(bytes);
3980
+ const len = head & 31;
3981
+ const start = cursor + 1;
3982
+ const end = start + len;
3983
+ if (end > bytes.length) return readFast(bytes);
3984
+ let hash = len;
3985
+ for (let i = start; i < end; i++) hash = Math.imul(hash, 31) + bytes[i] | 0;
3986
+ const entry = KEY_CACHE.get(hash);
3987
+ if (entry !== void 0) {
3988
+ const cached = entry.bytes;
3989
+ let same = cached.length === len;
3990
+ for (let i = 0; same && i < len; i++) same = cached[i] === bytes[start + i];
3991
+ if (same) {
3992
+ cursor = end;
3993
+ return entry.text;
3994
+ }
3995
+ }
3996
+ cursor = start;
3997
+ const text2 = readStrFast(bytes, len);
3998
+ if (entry === void 0 && KEY_CACHE.size < KEY_CACHE_LIMIT) KEY_CACHE.set(hash, { bytes: bytes.slice(start, end), text: text2 });
3999
+ return text2;
4000
+ }
3960
4001
  function readMapFast(bytes, count) {
3961
4002
  const obj = {};
3962
4003
  for (let i = 0; i < count; i++) {
3963
- const key = readFast(bytes);
4004
+ const key = readKeyFast(bytes);
3964
4005
  obj[typeof key === "string" ? key : String(key)] = readFast(bytes);
3965
4006
  }
3966
4007
  return obj;
@@ -4547,14 +4588,18 @@
4547
4588
  return this.bytes[this.offset++];
4548
4589
  }
4549
4590
  readUnsigned() {
4550
- let result = 0;
4551
- let shift = 0;
4591
+ const first = this.readByte();
4592
+ if (first < 128) return first;
4593
+ let result = first & 127;
4594
+ let multiplier = 128;
4595
+ let shift = 7;
4552
4596
  while (true) {
4553
4597
  const byte = this.readByte();
4554
- result += (byte & 127) * 2 ** shift;
4598
+ result += (byte & 127) * multiplier;
4555
4599
  if ((byte & 128) === 0) return result;
4556
4600
  shift += 7;
4557
4601
  if (shift > 70) throw new Error("model_data varint too large");
4602
+ multiplier *= 128;
4558
4603
  }
4559
4604
  }
4560
4605
  readStreamInt() {
@@ -4605,12 +4650,14 @@
4605
4650
  if (!resolved) {
4606
4651
  cached = compute();
4607
4652
  resolved = true;
4653
+ compute = null;
4608
4654
  }
4609
4655
  return cached;
4610
4656
  },
4611
4657
  set(value) {
4612
4658
  cached = value;
4613
4659
  resolved = true;
4660
+ compute = null;
4614
4661
  }
4615
4662
  });
4616
4663
  return target;
@@ -5011,6 +5058,7 @@
5011
5058
  for (const blob of spec.blobs || []) blob.key = blobKey(blob.offset);
5012
5059
  for (const item of spec.packedBits || []) item.key = qKey(item.offset);
5013
5060
  if (spec.packedOffsets) spec.packedOffsetKeys = spec.packedOffsets.map(qKey);
5061
+ spec.packedAnyMask = (spec.packedBits || []).reduce((mask, item) => mask | item.bit, spec.packedMask || 0);
5014
5062
  if (spec.orderedValues) {
5015
5063
  spec.orderedItems = [
5016
5064
  ...(spec.blobs || []).map((item) => ({ bit: item.bit, offset: item.offset, key: item.key, kind: "blob" })),
@@ -6464,7 +6512,7 @@
6464
6512
  entity(entityId) {
6465
6513
  const id = Number(entityId);
6466
6514
  if (!Number.isFinite(id)) return null;
6467
- return this.#derivedState().entitiesById.get(id) || null;
6515
+ return this.#derivedEntityIndex().entitiesById.get(id) || null;
6468
6516
  }
6469
6517
  entities() {
6470
6518
  return this.#derivedState().entities.slice();
@@ -6476,7 +6524,7 @@
6476
6524
  // O(1) point lookup. Callers previously had to materialise and scan the whole
6477
6525
  // block list to answer this.
6478
6526
  blockAt(x, y) {
6479
- this.#derivedState();
6527
+ this.#derivedEntityIndex();
6480
6528
  return this.#blocksIndex().get(blockKey2(x, y)) || null;
6481
6529
  }
6482
6530
  apply(bytes, { full = false } = {}) {
@@ -6652,18 +6700,38 @@
6652
6700
  this._derived = null;
6653
6701
  }
6654
6702
  #updateDerived(update) {
6655
- if (!this._derived) return;
6703
+ const derived = this._derived;
6704
+ if (!derived) return;
6656
6705
  if (!update.removals.length && !update.changedEntities.size) return;
6657
6706
  for (const section2 of update.sections) {
6658
6707
  for (const record of section2.records || []) this.#addDerivedEntityTable(record.entity, section2.table);
6659
6708
  }
6709
+ const dirty = derived.dirtyEntities ??= /* @__PURE__ */ new Set();
6660
6710
  if (update.sections.some((section2) => section2.table === 12)) {
6661
6711
  for (const entityId of this.table(55).keys()) update.changedEntities.add(entityId);
6662
6712
  }
6663
- for (const entityId of update.removals) this.#removeDerivedEntity(entityId);
6664
- for (const entityId of update.changedEntities) this.#refreshDerivedEntity(entityId);
6665
- this._derived.summariesDirty = true;
6666
- this._derived.tableSummariesDirty = true;
6713
+ for (const entityId of update.removals) {
6714
+ derived.entityTableIds.delete(entityId);
6715
+ dirty.add(entityId);
6716
+ }
6717
+ for (const entityId of update.changedEntities) dirty.add(entityId);
6718
+ }
6719
+ #flushDerivedEntities() {
6720
+ const derived = this._derived;
6721
+ const dirty = derived.dirtyEntities;
6722
+ if (!dirty || dirty.size === 0) return;
6723
+ derived.dirtyEntities = null;
6724
+ for (const entityId of dirty) this.#refreshDerivedEntity(entityId);
6725
+ derived.summariesDirty = true;
6726
+ derived.tableSummariesDirty = true;
6727
+ }
6728
+ // Current entity summaries without the per-category lists. Point lookups go
6729
+ // through here: rebuilding those lists is O(total entities) and was the whole
6730
+ // cost of entity(id) on a large world.
6731
+ #derivedEntityIndex() {
6732
+ if (!this._derived) return this.#derivedState();
6733
+ this.#flushDerivedEntities();
6734
+ return this._derived;
6667
6735
  }
6668
6736
  #updateNavigationUnitAutoWarp(update) {
6669
6737
  const trackedBeforeUpdate = new Set(this.#navigationUnitAutoWarp.keys());
@@ -6778,6 +6846,7 @@
6778
6846
  }
6779
6847
  #derivedState() {
6780
6848
  if (this._derived) {
6849
+ this.#flushDerivedEntities();
6781
6850
  this.#ensureDerivedSummaries();
6782
6851
  return this._derived;
6783
6852
  }
@@ -6855,7 +6924,7 @@
6855
6924
  if (old) this.#removeEntityFromDerivedBlocks(derived, old);
6856
6925
  const next = this.#summarizeEntity(entityId, rows);
6857
6926
  derived.entitiesById.set(entityId, next);
6858
- if (!derived.entityIds.includes(entityId)) insertSorted(derived.entityIds, entityId);
6927
+ if (!old) insertSorted(derived.entityIds, entityId);
6859
6928
  this.#addEntityToDerivedBlocks(derived, next);
6860
6929
  derived.entityCount = derived.entityIds.length;
6861
6930
  }
@@ -7360,6 +7429,7 @@
7360
7429
  }
7361
7430
  #readSectionRecords(reader, tag, tableId, spec) {
7362
7431
  const section2 = { tag, table: tableId, name: spec?.name || null, records: [] };
7432
+ let records = this.tables.get(tableId);
7363
7433
  let entity = 0;
7364
7434
  while (reader.remaining > 0) {
7365
7435
  const recordOffset = reader.offset;
@@ -7377,7 +7447,9 @@
7377
7447
  } catch (error) {
7378
7448
  throw new Error(`model table ${tableId} tag ${tag} entity ${entity} mask offset ${reader.offset}: ${error.message}`);
7379
7449
  }
7380
- const record = this.#getRecord(tableId, entity);
7450
+ if (!records) this.tables.set(tableId, records = /* @__PURE__ */ new Map());
7451
+ let record = records.get(entity);
7452
+ if (!record) records.set(entity, record = { ...spec?.defaults });
7381
7453
  record.lastMask = mask;
7382
7454
  try {
7383
7455
  if (spec) this.#applyRecordSpec(reader, record, mask, spec);
@@ -7390,21 +7462,13 @@
7390
7462
  }
7391
7463
  return section2;
7392
7464
  }
7393
- #getRecord(tableId, entity) {
7394
- if (!this.tables.has(tableId)) this.tables.set(tableId, /* @__PURE__ */ new Map());
7395
- const records = this.tables.get(tableId);
7396
- if (!records.has(entity)) records.set(entity, { ...MODEL_TABLE_SPECS2.get(tableId)?.defaults });
7397
- return records.get(entity);
7398
- }
7399
7465
  #applyRecordSpec(reader, record, mask, spec) {
7400
7466
  if (typeof spec.read === "function") {
7401
7467
  spec.read(reader, record, mask);
7402
7468
  if (spec.scale) record.scaled = spec.scale(record);
7403
7469
  return;
7404
7470
  }
7405
- const hasPacked = Boolean(
7406
- spec.packedMask && mask & spec.packedMask || spec.packedBits?.some((item) => mask & item.bit)
7407
- );
7471
+ const hasPacked = (mask & spec.packedAnyMask) !== 0;
7408
7472
  let packed = null;
7409
7473
  if (hasPacked && spec.packedBeforeValues) packed = reader.readUnsigned();
7410
7474
  let packedIndex = 0;
@@ -7669,10 +7733,58 @@
7669
7733
  target.push(value);
7670
7734
  if (target.length > limit) target.splice(0, target.length - limit);
7671
7735
  }
7672
- var TILE_KEY_OFFSET = 1 << 24;
7673
- var TILE_KEY_STRIDE = 1 << 25;
7736
+ var CHUNK_SIZE = 64;
7737
+ var CHUNK_CELLS = CHUNK_SIZE * CHUNK_SIZE;
7738
+ var COLUMN_SHAPE = CHUNK_CELLS;
7739
+ var COLUMN_HP = CHUNK_CELLS * 2;
7740
+ var COLUMN_COLOR = CHUNK_CELLS * 3;
7741
+ var COLUMN_FLAGS = CHUNK_CELLS * 4;
7742
+ var CHUNK_COORD_LIMIT = 1 << 15;
7743
+ var TILE_COORD_LIMIT = CHUNK_COORD_LIMIT * CHUNK_SIZE;
7744
+ var TILE_OBJECT_KEY_COUNT = 13;
7745
+ var CONCAT_BATCH = 4096;
7746
+ var TileFlags = Object.freeze({
7747
+ /** The cell holds a tile. Zero means the cell is empty. */
7748
+ Present: 1,
7749
+ /** The tile was sent without a color; its `color` is null. */
7750
+ NoColor: 2
7751
+ });
7752
+ var SHAPE_NAMES_BY_ID = Array.from({ length: 256 }, (_, shape) => TILE_SHAPE_NAMES.get(shape) ?? null);
7753
+ var isByte = (value) => typeof value === "number" && (value & 255) === value;
7754
+ var isCellIndex = (value) => Number.isInteger(value) && value >= 0 && value < CHUNK_SIZE;
7755
+ var isChunkCoord = (value) => Number.isInteger(value) && value >= -CHUNK_COORD_LIMIT && value < CHUNK_COORD_LIMIT;
7756
+ var isTileCoord = (value) => Number.isInteger(value) && value >= -TILE_COORD_LIMIT && value < TILE_COORD_LIMIT;
7757
+ var chunkKey = (chunkX, chunkY) => (chunkY + CHUNK_COORD_LIMIT) * (CHUNK_COORD_LIMIT * 2) + (chunkX + CHUNK_COORD_LIMIT);
7758
+ var looseTileKey = (x, y) => `${x},${y}`;
7759
+ var TileCollection = class {
7760
+ #count;
7761
+ #objects;
7762
+ constructor(count, objects) {
7763
+ this.#count = count;
7764
+ this.#objects = objects;
7765
+ }
7766
+ get size() {
7767
+ return this.#count();
7768
+ }
7769
+ // A fresh array of every tile.
7770
+ toArray() {
7771
+ return this.#objects().slice();
7772
+ }
7773
+ };
7674
7774
  var WorldState = class {
7675
- #materialCounts = /* @__PURE__ */ new Map();
7775
+ #chunkGrids = /* @__PURE__ */ new Map();
7776
+ // Tiles the columns cannot hold: non-byte values, out-of-range coordinates,
7777
+ // or extra caller fields. Only reachable through setTile()/malformed patches.
7778
+ #looseTiles = /* @__PURE__ */ new Map();
7779
+ #chunkViews = null;
7780
+ #tileVersion = 0;
7781
+ #tileStats = null;
7782
+ #tileStatsVersion = -1;
7783
+ #tileObjects = null;
7784
+ #tileObjectsVersion = -1;
7785
+ #tileObjectsRequestedVersion = -1;
7786
+ #materialDefs = null;
7787
+ #materialDefsTileset = null;
7676
7788
  constructor(id, limits = {}) {
7677
7789
  this.historyLimits = {
7678
7790
  eventHistory: normalizeLimit(limits.eventHistory, DEFAULT_HISTORY_LIMITS.eventHistory),
@@ -7689,7 +7801,7 @@
7689
7801
  this.blockHeight = null;
7690
7802
  this.parentWorld = null;
7691
7803
  this.parentEntity = null;
7692
- this.tiles = /* @__PURE__ */ new Map();
7804
+ this.tiles = new TileCollection(() => this.#readTileStats().count, () => this.#readTileObjects());
7693
7805
  this.chunks = [];
7694
7806
  this.events = [];
7695
7807
  this.modelPackets = [];
@@ -7750,6 +7862,12 @@
7750
7862
  return this.setTile({ x, y, material, shape, hp, integrity: hp, color });
7751
7863
  }
7752
7864
  applyChunk(value) {
7865
+ const patch = this.applyChunkPatch(value);
7866
+ return patch ? patch.tiles : null;
7867
+ }
7868
+ // Applies a chunk patch and returns its history entry. The entry's `tiles`
7869
+ // array is built on first read, so ingestion never allocates tile objects.
7870
+ applyChunkPatch(value) {
7753
7871
  if (!Array.isArray(value) || value.length !== 7) return null;
7754
7872
  const [chunkX, chunkY, minX, minY, maxX, maxY, compressedPatch] = value;
7755
7873
  const patch = decompressWorldChunk(compressedPatch);
@@ -7757,32 +7875,143 @@
7757
7875
  const height = maxY - minY + 1;
7758
7876
  const count = width * height;
7759
7877
  const hasColor = patch.length >= count * 4;
7760
- const tiles = new Array(count);
7761
7878
  const baseX = chunkX << 6;
7762
7879
  const baseY = chunkY << 6;
7763
- for (let i = 0; i < count; i++) {
7764
- const localX = minX + i % width;
7765
- const localY = minY + Math.floor(i / width);
7766
- const hp = patch[i + count * 2];
7767
- tiles[i] = this.#storeTile(this.#buildTile(
7768
- baseX + localX,
7769
- baseY + localY,
7770
- patch[i],
7771
- patch[i + count],
7772
- hp,
7773
- hasColor ? patch[i + count * 3] : null
7774
- ));
7880
+ const entry = { chunkX, chunkY, minX, minY, maxX, maxY };
7881
+ const wellFormed = isChunkCoord(chunkX) && isChunkCoord(chunkY) && isCellIndex(minX) && isCellIndex(minY) && isCellIndex(maxX) && isCellIndex(maxY) && width > 0 && height > 0 && patch.length >= count * 3;
7882
+ if (wellFormed) {
7883
+ this.#writeChunkColumns(this.#chunkGrid(chunkX, chunkY), patch, minX, minY, width, height, hasColor);
7884
+ defineLazyProperty(entry, "tiles", () => {
7885
+ const tiles = new Array(count);
7886
+ for (let i = 0; i < count; i++) {
7887
+ tiles[i] = this.#buildTile(
7888
+ baseX + minX + i % width,
7889
+ baseY + minY + Math.floor(i / width),
7890
+ patch[i],
7891
+ patch[i + count],
7892
+ patch[i + count * 2],
7893
+ hasColor ? patch[i + count * 3] : null
7894
+ );
7895
+ }
7896
+ return tiles;
7897
+ });
7898
+ } else {
7899
+ const tiles = new Array(count);
7900
+ for (let i = 0; i < count; i++) {
7901
+ tiles[i] = this.#storeTile(this.#buildTile(
7902
+ baseX + minX + i % width,
7903
+ baseY + minY + Math.floor(i / width),
7904
+ patch[i],
7905
+ patch[i + count],
7906
+ patch[i + count * 2],
7907
+ hasColor ? patch[i + count * 3] : null
7908
+ ));
7909
+ }
7910
+ entry.tiles = tiles;
7775
7911
  }
7776
7912
  this.totalChunkCount += 1;
7777
- pushBounded(this.chunks, { chunkX, chunkY, minX, minY, maxX, maxY, tiles }, this.historyLimits.chunkHistory);
7913
+ pushBounded(this.chunks, entry, this.historyLimits.chunkHistory);
7778
7914
  this.lastChunkPatch = { chunkX, chunkY, minX, minY, maxX, maxY, count, hasColor };
7779
- return tiles;
7915
+ return entry;
7780
7916
  }
7781
7917
  setTile(tile) {
7782
7918
  return this.#storeTile(this.normalizeTile(tile));
7783
7919
  }
7784
- // Chunk decoding produces millions of tiles at join time, so build the final
7785
- // object in one pass instead of a literal plus a spread copy.
7920
+ /** Bumped on every tile write; compare to skip work when nothing changed. */
7921
+ get tileVersion() {
7922
+ return this.#tileVersion;
7923
+ }
7924
+ // Zero-copy access for consumers that scan tiles every tick. The returned
7925
+ // views are live and stable for the life of the chunk: read the typed arrays
7926
+ // directly and use each view's `version` to skip chunks that have not changed.
7927
+ tileChunks() {
7928
+ return this.#chunkViews ??= Array.from(this.#chunkGrids.values(), (grid) => grid.view);
7929
+ }
7930
+ tileAt(x, y) {
7931
+ if (this.#looseTiles.size > 0) {
7932
+ const loose = this.#looseTiles.get(looseTileKey(x, y));
7933
+ if (loose) return loose;
7934
+ }
7935
+ if (!isTileCoord(x) || !isTileCoord(y)) return null;
7936
+ const grid = this.#chunkGrids.get(chunkKey(x >> 6, y >> 6));
7937
+ if (!grid) return null;
7938
+ const data = grid.data;
7939
+ const cell = (y & 63) << 6 | x & 63;
7940
+ const flags = data[COLUMN_FLAGS + cell];
7941
+ if (flags === 0) return null;
7942
+ return this.#buildTile(
7943
+ x,
7944
+ y,
7945
+ data[cell],
7946
+ data[COLUMN_SHAPE + cell],
7947
+ data[COLUMN_HP + cell],
7948
+ flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell]
7949
+ );
7950
+ }
7951
+ // Drops tile objects retained for repeated `tiles.toArray()` reads. They are
7952
+ // rebuilt on the next read.
7953
+ releaseTileObjects() {
7954
+ this.#tileObjects = null;
7955
+ this.#tileObjectsRequestedVersion = -1;
7956
+ for (const grid of this.#chunkGrids.values()) {
7957
+ grid.objects = null;
7958
+ grid.objectsRequestedVersion = -1;
7959
+ }
7960
+ }
7961
+ #chunkGrid(chunkX, chunkY) {
7962
+ const key = chunkKey(chunkX, chunkY);
7963
+ let grid = this.#chunkGrids.get(key);
7964
+ if (!grid) {
7965
+ const data = new Uint8Array(CHUNK_CELLS * 5);
7966
+ grid = {
7967
+ data,
7968
+ stats: null,
7969
+ objects: null,
7970
+ objectsRequestedVersion: -1,
7971
+ view: {
7972
+ chunkX,
7973
+ chunkY,
7974
+ originX: chunkX << 6,
7975
+ originY: chunkY << 6,
7976
+ version: 0,
7977
+ material: data.subarray(0, COLUMN_SHAPE),
7978
+ shape: data.subarray(COLUMN_SHAPE, COLUMN_HP),
7979
+ hp: data.subarray(COLUMN_HP, COLUMN_COLOR),
7980
+ color: data.subarray(COLUMN_COLOR, COLUMN_FLAGS),
7981
+ flags: data.subarray(COLUMN_FLAGS, COLUMN_FLAGS + CHUNK_CELLS)
7982
+ }
7983
+ };
7984
+ this.#chunkGrids.set(key, grid);
7985
+ this.#chunkViews = null;
7986
+ }
7987
+ return grid;
7988
+ }
7989
+ // The only bookkeeping a tile write does. Counts and tile objects are derived
7990
+ // later, on demand, from whichever chunks were touched.
7991
+ #touchChunk(grid) {
7992
+ grid.stats = null;
7993
+ grid.objects = null;
7994
+ grid.view.version = ++this.#tileVersion;
7995
+ }
7996
+ #writeChunkColumns(grid, patch, minX, minY, width, height, hasColor) {
7997
+ const data = grid.data;
7998
+ const count = width * height;
7999
+ const columns = hasColor ? 4 : 3;
8000
+ const flag = hasColor ? TileFlags.Present : TileFlags.Present | TileFlags.NoColor;
8001
+ const rows = width === CHUNK_SIZE ? 1 : height;
8002
+ const span = width === CHUNK_SIZE ? count : width;
8003
+ for (let row = 0; row < rows; row++) {
8004
+ const start = (minY + row << 6) + minX;
8005
+ const from = row * width;
8006
+ for (let column = 0; column < columns; column++) {
8007
+ const source = column * count + from;
8008
+ data.set(patch.subarray(source, source + span), column * CHUNK_CELLS + start);
8009
+ }
8010
+ if (!hasColor) data.fill(0, COLUMN_COLOR + start, COLUMN_COLOR + start + span);
8011
+ data.fill(flag, COLUMN_FLAGS + start, COLUMN_FLAGS + start + span);
8012
+ }
8013
+ this.#touchChunk(grid);
8014
+ }
7786
8015
  #buildTile(x, y, material, shape, hp, color) {
7787
8016
  const def = this.tileDefinition(material);
7788
8017
  const maxHp = def?.hp ?? null;
@@ -7803,22 +8032,147 @@
7803
8032
  hpValue: typeof value === "number" && typeof maxHp === "number" ? Math.round(value / 255 * maxHp) : null
7804
8033
  };
7805
8034
  }
7806
- // Numeric key: a template string per tile was a measurable share of chunk
7807
- // decode. The map is only ever read through values()/size, so the key format
7808
- // is internal.
7809
- #storeTile(normalized) {
7810
- const key = (normalized.y + TILE_KEY_OFFSET) * TILE_KEY_STRIDE + (normalized.x + TILE_KEY_OFFSET);
7811
- const previous = this.tiles.get(key);
7812
- if (previous !== void 0) this.#countMaterial(previous.material, -1);
7813
- this.#countMaterial(normalized.material, 1);
7814
- this.tiles.set(key, normalized);
7815
- return normalized;
7816
- }
7817
- #countMaterial(material, delta) {
7818
- const id = Number(material);
7819
- const next = (this.#materialCounts.get(id) || 0) + delta;
7820
- if (next > 0) this.#materialCounts.set(id, next);
7821
- else this.#materialCounts.delete(id);
8035
+ #storeTile(tile) {
8036
+ const { x, y } = tile;
8037
+ const inRange = isTileCoord(x) && isTileCoord(y);
8038
+ const columnar = inRange && isByte(tile.material) && isByte(tile.shape) && isByte(tile.hp) && (tile.color === null || isByte(tile.color)) && Object.keys(tile).length === TILE_OBJECT_KEY_COUNT;
8039
+ if (this.#looseTiles.size > 0 && this.#looseTiles.delete(looseTileKey(x, y))) this.#tileVersion++;
8040
+ if (columnar) {
8041
+ const grid2 = this.#chunkGrid(x >> 6, y >> 6);
8042
+ const data = grid2.data;
8043
+ const cell = (y & 63) << 6 | x & 63;
8044
+ data[cell] = tile.material;
8045
+ data[COLUMN_SHAPE + cell] = tile.shape;
8046
+ data[COLUMN_HP + cell] = tile.hp;
8047
+ data[COLUMN_COLOR + cell] = tile.color ?? 0;
8048
+ data[COLUMN_FLAGS + cell] = tile.color === null ? TileFlags.Present | TileFlags.NoColor : TileFlags.Present;
8049
+ this.#touchChunk(grid2);
8050
+ return tile;
8051
+ }
8052
+ const grid = inRange ? this.#chunkGrids.get(chunkKey(x >> 6, y >> 6)) : void 0;
8053
+ if (grid) {
8054
+ const cell = (y & 63) << 6 | x & 63;
8055
+ if (grid.data[COLUMN_FLAGS + cell] !== 0) {
8056
+ grid.data[COLUMN_FLAGS + cell] = 0;
8057
+ this.#touchChunk(grid);
8058
+ }
8059
+ }
8060
+ this.#looseTiles.set(looseTileKey(x, y), tile);
8061
+ this.#tileVersion++;
8062
+ return tile;
8063
+ }
8064
+ // Tile and material counts, derived from the columns on first read after a
8065
+ // write. Only chunks touched since the last read are rescanned.
8066
+ #readTileStats() {
8067
+ if (this.#tileStats && this.#tileStatsVersion === this.#tileVersion) return this.#tileStats;
8068
+ const totals = new Int32Array(256);
8069
+ let count = 0;
8070
+ for (const grid of this.#chunkGrids.values()) {
8071
+ let stats = grid.stats;
8072
+ if (!stats) {
8073
+ const data = grid.data;
8074
+ const histogram2 = new Uint16Array(256);
8075
+ let present = 0;
8076
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
8077
+ if (data[COLUMN_FLAGS + cell] === 0) continue;
8078
+ histogram2[data[cell]]++;
8079
+ present++;
8080
+ }
8081
+ stats = grid.stats = { count: present, histogram: histogram2 };
8082
+ }
8083
+ count += stats.count;
8084
+ const histogram = stats.histogram;
8085
+ for (let material = 0; material < 256; material++) totals[material] += histogram[material];
8086
+ }
8087
+ const materials = /* @__PURE__ */ new Map();
8088
+ for (let material = 0; material < 256; material++) {
8089
+ if (totals[material] > 0) materials.set(material, totals[material]);
8090
+ }
8091
+ for (const tile of this.#looseTiles.values()) {
8092
+ const id = Number(tile.material);
8093
+ materials.set(id, (materials.get(id) || 0) + 1);
8094
+ count++;
8095
+ }
8096
+ this.#tileStatsVersion = this.#tileVersion;
8097
+ return this.#tileStats = { count, materials };
8098
+ }
8099
+ // Per-material fields of a tile object, resolved once per tileset instead of
8100
+ // once per tile.
8101
+ #readMaterialDefs() {
8102
+ if (this.#materialDefs && this.#materialDefsTileset === this.tileset) return this.#materialDefs;
8103
+ const defs = new Array(256);
8104
+ for (let material = 0; material < 256; material++) {
8105
+ const def = this.tileDefinition(material);
8106
+ defs[material] = { name: def?.name ?? null, solid: def?.solid ?? null, maxHp: def?.hp ?? null };
8107
+ }
8108
+ this.#materialDefsTileset = this.tileset;
8109
+ return this.#materialDefs = defs;
8110
+ }
8111
+ #buildChunkTiles(grid) {
8112
+ const defs = this.#readMaterialDefs();
8113
+ const data = grid.data;
8114
+ const baseX = grid.view.originX;
8115
+ const baseY = grid.view.originY;
8116
+ const tiles = [];
8117
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
8118
+ const flags = data[COLUMN_FLAGS + cell];
8119
+ if (flags === 0) continue;
8120
+ const material = data[cell];
8121
+ const shape = data[COLUMN_SHAPE + cell];
8122
+ const hp = data[COLUMN_HP + cell];
8123
+ const def = defs[material];
8124
+ const maxHp = def.maxHp;
8125
+ tiles.push({
8126
+ x: baseX + (cell & 63),
8127
+ y: baseY + (cell >> 6),
8128
+ material,
8129
+ shape,
8130
+ hp,
8131
+ integrity: hp,
8132
+ color: flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell],
8133
+ materialName: def.name,
8134
+ shapeName: SHAPE_NAMES_BY_ID[shape],
8135
+ solid: def.solid,
8136
+ maxHp,
8137
+ hpRatio: hp / 255,
8138
+ hpValue: typeof maxHp === "number" ? Math.round(hp / 255 * maxHp) : null
8139
+ });
8140
+ }
8141
+ return tiles;
8142
+ }
8143
+ // Every tile as an object. Objects are retained only once a caller asks a
8144
+ // second time for the same unchanged data, so a one-off dump leaves nothing
8145
+ // behind while a caller that polls pays only for chunks that changed.
8146
+ #readTileObjects() {
8147
+ if (this.#materialDefsTileset !== this.tileset) {
8148
+ this.releaseTileObjects();
8149
+ this.#materialDefs = null;
8150
+ }
8151
+ const version = this.#tileVersion;
8152
+ if (this.#tileObjects && this.#tileObjectsVersion === version) return this.#tileObjects;
8153
+ const parts = [];
8154
+ for (const grid of this.#chunkGrids.values()) {
8155
+ let tiles = grid.objects;
8156
+ if (!tiles) {
8157
+ tiles = this.#buildChunkTiles(grid);
8158
+ if (grid.objectsRequestedVersion === grid.view.version) grid.objects = tiles;
8159
+ else grid.objectsRequestedVersion = grid.view.version;
8160
+ }
8161
+ parts.push(tiles);
8162
+ }
8163
+ if (this.#looseTiles.size > 0) parts.push([...this.#looseTiles.values()]);
8164
+ let out = [];
8165
+ for (let start = 0; start < parts.length; start += CONCAT_BATCH) {
8166
+ out = out.concat(...parts.slice(start, start + CONCAT_BATCH));
8167
+ }
8168
+ if (this.#tileObjectsRequestedVersion === version) {
8169
+ this.#tileObjects = out;
8170
+ this.#tileObjectsVersion = version;
8171
+ } else {
8172
+ this.#tileObjects = null;
8173
+ this.#tileObjectsRequestedVersion = version;
8174
+ }
8175
+ return out;
7822
8176
  }
7823
8177
  normalizeTile(tile) {
7824
8178
  const def = this.tileDefinition(tile.material);
@@ -7836,10 +8190,8 @@
7836
8190
  hpValue: typeof hp === "number" && typeof maxHp === "number" ? Math.round(hp / 255 * maxHp) : null
7837
8191
  };
7838
8192
  }
7839
- // Counts are maintained as tiles are stored; this used to rescan every tile
7840
- // on each call and ran on every snapshot.
7841
8193
  materials() {
7842
- return [...this.#materialCounts.entries()].sort((a, b) => a[0] - b[0]).map(([material, count]) => {
8194
+ return [...this.#readTileStats().materials.entries()].sort((a, b) => a[0] - b[0]).map(([material, count]) => {
7843
8195
  const def = this.tileDefinition(material);
7844
8196
  return {
7845
8197
  material,
@@ -7864,7 +8216,7 @@
7864
8216
  block_h: this.blockHeight,
7865
8217
  parent_world: this.parentWorld,
7866
8218
  parent_ent: this.parentEntity,
7867
- tileCount: this.tiles.size,
8219
+ tileCount: this.#readTileStats().count,
7868
8220
  chunkCount: this.totalChunkCount,
7869
8221
  lastChunkPatch: this.lastChunkPatch,
7870
8222
  lastPacket: this.lastPacket,
@@ -7885,7 +8237,7 @@
7885
8237
  pvpEvent: model.pvpEvent,
7886
8238
  pvpParties: model.pvpParties,
7887
8239
  commsBubbles: this.commsBubbles.slice(),
7888
- tiles: includeTiles ? [...this.tiles.values()] : void 0
8240
+ tiles: includeTiles ? this.tiles.toArray() : void 0
7889
8241
  };
7890
8242
  }
7891
8243
  table(id) {
@@ -8035,8 +8387,10 @@
8035
8387
  if (decoded && typeof decoded === "object") {
8036
8388
  for (const [kind, value] of Object.entries(decoded)) {
8037
8389
  try {
8038
- if (kind === "0") updates.push({ kind, tiles: world.applyChunk(value) });
8039
- else if (kind === "1") updates.push({ kind, tile: world.applyTile(value) });
8390
+ if (kind === "0") {
8391
+ const patch = world.applyChunkPatch(value);
8392
+ updates.push(defineLazyProperty({ kind }, "tiles", () => patch ? patch.tiles : null));
8393
+ } else if (kind === "1") updates.push({ kind, tile: world.applyTile(value) });
8040
8394
  else updates.push({ kind, value });
8041
8395
  } catch (error) {
8042
8396
  errors.push(error);
@@ -9599,6 +9953,7 @@
9599
9953
  this.recyclers = new EntitySummaryCollection(client, scope, "recyclers");
9600
9954
  this.blocks = new BlockCollection(client, scope);
9601
9955
  this.materials = new MaterialCollection(client, scope);
9956
+ this.tiles = new TileDomain(client, scope);
9602
9957
  }
9603
9958
  get id() {
9604
9959
  return worldStateFor(this.client, this.scope)?.id ?? null;
@@ -9799,6 +10154,27 @@
9799
10154
  return worldStateFor(this.client, this.scope)?.materials() || [];
9800
10155
  }
9801
10156
  };
10157
+ var TileDomain = class {
10158
+ constructor(client, scope) {
10159
+ this.client = client;
10160
+ this.scope = scope;
10161
+ }
10162
+ get count() {
10163
+ return worldStateFor(this.client, this.scope)?.tiles.size ?? 0;
10164
+ }
10165
+ get version() {
10166
+ return worldStateFor(this.client, this.scope)?.tileVersion ?? 0;
10167
+ }
10168
+ chunks() {
10169
+ return worldStateFor(this.client, this.scope)?.tileChunks() || [];
10170
+ }
10171
+ at(x, y) {
10172
+ return worldStateFor(this.client, this.scope)?.tileAt(x, y) ?? null;
10173
+ }
10174
+ all() {
10175
+ return worldStateFor(this.client, this.scope)?.tiles.toArray() || [];
10176
+ }
10177
+ };
9802
10178
  var MachineCollection = class {
9803
10179
  constructor(client, scope) {
9804
10180
  this.client = client;