@zardoy/flying-squid 0.0.129 → 0.0.131

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.
@@ -9,10 +9,10 @@ module.exports = {
9
9
  'bossBars': require('./bossBars'),
10
10
  'channels': require('./channels'),
11
11
  'chat': require('./chat'),
12
- 'chest': require('./chest'),
13
12
  'commandBlocks': require('./commandBlocks'),
14
13
  'commands': require('./commands'),
15
14
  'communication': require('./communication'),
15
+ 'containers': require('./containers'),
16
16
  'crafting': require('./crafting'),
17
17
  'customBlockBreakTime': require('./customBlockBreakTime'),
18
18
  'customSync': require('./customSync'),
@@ -54,6 +54,7 @@ module.exports = {
54
54
  'scoreboard': require('./scoreboard'),
55
55
  'settings': require('./settings'),
56
56
  'signs': require('./signs'),
57
+ 'smelting': require('./smelting'),
57
58
  'sound': require('./sound'),
58
59
  'spawn': require('./spawn'),
59
60
  'stats': require('./stats'),
@@ -8,7 +8,9 @@ type Post1_14Windows = 'minecraft:inventory' | 'minecraft:generic_9x1' | 'minecr
8
8
  type Pre1_14Windows = 'minecraft:inventory' | 'minecraft:chest' | 'minecraft:crafting_table' | 'minecraft:furnace' | 'minecraft:dispenser' | 'minecraft:enchanting_table' | 'minecraft:brewing_stand' | 'minecraft:container' | 'minecraft:villager' | 'minecraft:beacon' | 'minecraft:anvil' | 'minecraft:hopper' | 'minecraft:dropper' | 'minecraft:shulker_box' | 'EntityHorse';
9
9
  interface OpenCustomWindowOptions {
10
10
  inventoryType: Post1_14Windows | Pre1_14Windows;
11
- title: string;
11
+ title: string | object;
12
+ /** size of the container part for window types without a fixed size (`minecraft:chest` before 1.14) */
13
+ slotCount?: number;
12
14
  windowSlots: Record<number, Item>;
13
15
  resultSlot?: Item;
14
16
  noPlayerInventory?: boolean;
@@ -21,6 +23,8 @@ declare global {
21
23
  }
22
24
  interface Player {
23
25
  lockInventory?: boolean;
26
+ /** id of the window the player has open (counts up with every window) */
27
+ windowId: number;
24
28
  heldItemSlot: number;
25
29
  heldItem: Item;
26
30
  inventory: Window;
@@ -14,13 +14,14 @@ const player = function (player, serv, { version }) {
14
14
  player.inventory = windows.createWindow(1, 'minecraft:inventory', 'inv', 36);
15
15
  player.openCustomWindow = (options) => {
16
16
  const windowInfo = windows.windows[options.inventoryType];
17
- if (!windowInfo) {
17
+ // before 1.14 `minecraft:chest` / `minecraft:container` have no fixed size: the caller gives the slot count
18
+ if (windowInfo === undefined || (!windowInfo && options.slotCount === undefined)) {
18
19
  throw new Error(`Invalid inventory type: ${options.inventoryType}`);
19
20
  }
20
- const craftSlot = windowInfo.craft;
21
- const window = windows.createWindow(1, windowInfo.type, options.title);
21
+ const craftSlot = windowInfo?.craft;
22
+ const window = windows.createWindow(1, windowInfo ? windowInfo.type : options.inventoryType, options.title, options.slotCount);
22
23
  // todo fix in prismarine-windows
23
- window.type = windowInfo.type;
24
+ window.type = windowInfo ? windowInfo.type : options.inventoryType;
24
25
  for (let i = 0; i < window.inventoryStart; i++) {
25
26
  window.slots[i] = options.windowSlots[i] ?? null;
26
27
  }
@@ -46,7 +47,7 @@ const player = function (player, serv, { version }) {
46
47
  inventoryType: window.type,
47
48
  windowTitle: serv._createChatComponent(options.title).toNetworkFormat(),
48
49
  entityId: player.id,
49
- slotCount: window.slots.length,
50
+ slotCount: options.slotCount ?? window.slots.length,
50
51
  useProvidedTitle: true,
51
52
  });
52
53
  const sendItems = () => {
@@ -2,6 +2,10 @@ import { Client } from 'minecraft-protocol';
2
2
  export declare const server: (serv: Server, options: Options) => void;
3
3
  export declare const player: (player: Player, serv: Server, settings: Options) => Promise<void>;
4
4
  declare global {
5
+ interface Options {
6
+ /** ender pearls given to a new player of a survival world, in the first hotbar slot (default 16, `false` = none) */
7
+ startingPearls?: number | false;
8
+ }
5
9
  interface Server {
6
10
  _addPlayer: (client: Client, assignProps?: {
7
11
  isFake?: boolean;
@@ -270,6 +270,12 @@ const player = async function (player, serv, settings) {
270
270
  console.warn(`Failed to restore inventory slot. Error while restoring item ${itemName} (id in player ${player.username} inventory ${itemValue})`, err);
271
271
  }
272
272
  });
273
+ player.loadEnderChest?.(playerData.enderItems ?? []);
274
+ // a new player of a survival world starts with a stack of ender pearls in the first hotbar slot (`startingPearls`: count, false = none)
275
+ const pearls = settings.startingPearls ?? 16;
276
+ if (playerData.new && player.gameMode === 0 && pearls && !player.isFake && mcData.itemsByName.ender_pearl) {
277
+ player.inventory.updateSlot(36, new Item(mcData.itemsByName.ender_pearl.id, Math.min(+pearls, mcData.itemsByName.ender_pearl.stackSize ?? 16)));
278
+ }
273
279
  player._client.write('held_item_slot', {
274
280
  slot: player.heldItemSlot
275
281
  });
@@ -300,8 +306,11 @@ const player = async function (player, serv, settings) {
300
306
  dimensionCodec,
301
307
  levelType: 'default',
302
308
  worldType: 'minecraft:overworld',
303
- worldName: serv.dimensionNames[0],
304
- dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[0] : serv.supportFeature('dimensionIsAnInt') ? 0 : dimensionCodec_1.dimensionOverworld,
309
+ // a player saved in the nether / end / another world joins that world (before, the client was always told "overworld" and got chunks of another dimension)
310
+ ...(player.world && player.world !== serv.overworld ? serv.worldClientInfo(player.world) : {
311
+ worldName: serv.dimensionNames[0],
312
+ dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[0] : serv.supportFeature('dimensionIsAnInt') ? 0 : dimensionCodec_1.dimensionOverworld
313
+ }),
305
314
  hashedSeed: serv.hashedSeed,
306
315
  difficulty: serv.difficulty,
307
316
  viewDistance,
@@ -1,8 +1,12 @@
1
1
  import { Vec3 } from 'vec3';
2
2
  export declare const player: (player: Player, serv: Server, { version }: Options) => void;
3
- export declare const server: (serv: Server, { version }: Options) => void;
3
+ export declare const server: (serv: Server, { version, worldFolder, noWorldRegion }: Options) => void;
4
4
  declare global {
5
5
  interface Server {
6
+ /** standable position in `world` for a player coming from `from` in `fromWorld` (nether coordinates are 1:8) */
7
+ worldEntryPoint: (world: any, fromWorld: any, from: Vec3) => Promise<Vec3>;
8
+ /** writes the registered nether portals of all worlds to `<worldFolder>/flyingsquid-portals.json` (only when changed) */
9
+ savePortals: () => Promise<void>;
6
10
  /** nearest registered portal of `world` within `radius` blocks of (x, z) - a new nether portal is built when there is none; returns the standing position */
7
11
  netherPortalNear: (world: any, x: number, z: number, radius: number) => Promise<Vec3>;
8
12
  }
@@ -8,6 +8,7 @@ const vec3_1 = require("vec3");
8
8
  const user_error_1 = __importDefault(require("../user_error"));
9
9
  const minecraft_data_1 = __importDefault(require("minecraft-data"));
10
10
  const portal_detector_1 = __importDefault(require("../portal_detector"));
11
+ const fs_1 = __importDefault(require("fs"));
11
12
  const player = function (player, serv, { version }) {
12
13
  const mcData = (0, minecraft_data_1.default)(version);
13
14
  const obsidianType = mcData.blocksByName.obsidian.id;
@@ -33,7 +34,7 @@ const player = function (player, serv, { version }) {
33
34
  // })
34
35
  };
35
36
  exports.player = player;
36
- const server = function (serv, { version }) {
37
+ const server = function (serv, { version, worldFolder, noWorldRegion }) {
37
38
  const { generatePortal, addPortalToWorld, detectFrame } = (0, portal_detector_1.default)(version);
38
39
  const mcData = (0, minecraft_data_1.default)(version);
39
40
  const obsidianType = mcData.blocksByName.obsidian.id;
@@ -155,6 +156,60 @@ const server = function (serv, { version }) {
155
156
  return new vec3_1.Vec3(Math.floor(x) + 1, y, Math.floor(z) + 0.5);
156
157
  }
157
158
  serv.netherPortalNear = portalNear;
159
+ /** where a player standing at `from` (in the world `fromWorld`) arrives when sent to `world` without an explicit position (/mv tp, /changeworld) */
160
+ serv.worldEntryPoint = async (world, fromWorld, from) => {
161
+ if (world.environment === 'end')
162
+ return new vec3_1.Vec3(100.5, 49, 0.5);
163
+ const scale = world.environment === 'nether' && fromWorld?.environment === 'normal' ? 1 / 8 : world.environment === 'normal' && fromWorld?.environment === 'nether' ? 8 : 1;
164
+ const x = Math.floor((from?.x ?? 0) * scale);
165
+ const z = Math.floor((from?.z ?? 0) * scale);
166
+ await world.getColumn(x >> 4, z >> 4);
167
+ return new vec3_1.Vec3(x + 0.5, await findStandY(world, x, z), z + 0.5);
168
+ };
169
+ // ---------------------------------------------------------------------------------------------- portals in the save
170
+ // `world.portals` lived in memory only: after a restart every trip through an existing portal built a second one, and the old one was never found again
171
+ const portalsFile = worldFolder && !noWorldRegion ? `${worldFolder}/flyingsquid-portals.json` : undefined;
172
+ const toXyz = (list = []) => list.map(p => [p.x, p.y, p.z]);
173
+ const fromXyz = (list = []) => list.map(([x, y, z]) => new vec3_1.Vec3(x, y, z));
174
+ let lastSavedPortals = '';
175
+ serv.savePortals = async () => {
176
+ if (!portalsFile)
177
+ return;
178
+ const data = {};
179
+ for (const [name, world] of Object.entries(serv.worlds)) {
180
+ if (!world.portals?.length)
181
+ continue;
182
+ data[name] = world.portals.map(({ bottom, left, right, top, air }) => ({ bottom: toXyz(bottom), left: toXyz(left), right: toXyz(right), top: toXyz(top), air: toXyz(air) }));
183
+ }
184
+ const json = JSON.stringify(data);
185
+ if (json === lastSavedPortals)
186
+ return;
187
+ try {
188
+ await fs_1.default.promises.writeFile(portalsFile, json);
189
+ lastSavedPortals = json;
190
+ }
191
+ catch (e) {
192
+ serv.warn('Could not save portals: ' + e.message);
193
+ }
194
+ };
195
+ // the worlds are created by the (async) world module: not yet at 'asap'
196
+ serv.once('pluginsReady', async () => {
197
+ if (!portalsFile)
198
+ return;
199
+ try {
200
+ const data = JSON.parse(await fs_1.default.promises.readFile(portalsFile, 'utf8'));
201
+ lastSavedPortals = JSON.stringify(data);
202
+ for (const [name, portals] of Object.entries(data)) {
203
+ const world = serv.worlds[name];
204
+ if (!world)
205
+ continue;
206
+ for (const p of portals)
207
+ world.portals.push({ bottom: fromXyz(p.bottom), left: fromXyz(p.left), right: fromXyz(p.right), top: fromXyz(p.top), air: fromXyz(p.air) });
208
+ }
209
+ }
210
+ catch { } // no file yet
211
+ serv.setInterval(() => { void serv.savePortals(); }, 10_000);
212
+ });
158
213
  const portalState = new WeakMap();
159
214
  const endPortalType = mcData.blocksByName.end_portal?.id;
160
215
  const netherPortalType = mcData.blocksByName[netherPortalName]?.id;
@@ -13,6 +13,12 @@ const player = function (player, serv) {
13
13
  if (actionId === 0) {
14
14
  player.position = player.spawnPoint;
15
15
  player.behavior('requestRespawn', {}, () => {
16
+ // the respawn point is in the overworld: a player who died in another world (nether, end, /mv world) really changes the world, not only the client's dimension
17
+ const switchingWorld = player.world !== serv.overworld;
18
+ if (switchingWorld) {
19
+ player._unloadAllChunks();
20
+ player.world = serv.overworld;
21
+ }
16
22
  player._client.write('respawn', {
17
23
  previousGameMode: player.prevGameMode,
18
24
  dimension: serv.supportFeature('dimensionIsAWorld') ? {
@@ -94,6 +100,8 @@ const player = function (player, serv) {
94
100
  player.updateHealth(20);
95
101
  player.nearbyEntities = [];
96
102
  player.updateAndSpawn();
103
+ if (switchingWorld)
104
+ player.sendMap().catch((err) => setTimeout(() => { throw err; }));
97
105
  });
98
106
  }
99
107
  });
@@ -0,0 +1,6 @@
1
+ export declare const server: (serv: Server, options: Options) => void;
2
+ declare global {
3
+ interface Server {
4
+ }
5
+ }
6
+ export declare const player: (player: Player, serv: Server) => void;
@@ -0,0 +1,323 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.player = exports.server = void 0;
4
+ const vec3_1 = require("vec3");
5
+ const gameData_1 = require("../containers/gameData");
6
+ const blockRenames_1 = require("../../blockRenames");
7
+ /**
8
+ * Furnaces, blast furnaces and smokers: fuel burns, the input cooks into the output with the cooking recipes of the datapack (see `GameData`), the window shows the
9
+ * progress, the stored experience goes to the player who takes the result. State is the vanilla block entity (`Items`, `BurnTime`, `CookTime`, `CookTimeTotal`), so
10
+ * furnaces of a vanilla world keep working and a running furnace survives a restart. Furnaces cook only while their chunk is loaded (like vanilla).
11
+ */
12
+ const KIND_OF = { furnace: 'smelting', lit_furnace: 'smelting', blast_furnace: 'blasting', smoker: 'smoking' };
13
+ const BASE_NAME = (name) => name.replace(/^lit_/, '');
14
+ /** the NBT of a vanilla furnace stores the numbers as shorts */
15
+ const short = (value) => ({ type: 'short', value });
16
+ const server = (serv, options) => {
17
+ const mcData = serv.mcData;
18
+ const flat = serv.supportFeature('theFlattening');
19
+ const newWindows = serv.supportFeature('village&pillageInventoryWindows');
20
+ const PBlock = serv.PrismarineBlock;
21
+ const active = new Map();
22
+ const stateKey = (world, pos) => `${world.worldName ?? 'world'}:${pos.x},${pos.y},${pos.z}`;
23
+ const renameItem = (name) => {
24
+ try {
25
+ return flat ? (0, blockRenames_1.getRenamedData)('items', name, '26.3', options.version) ?? name : name;
26
+ }
27
+ catch {
28
+ return name;
29
+ }
30
+ };
31
+ // ---------------------------------------------------------------- recipes
32
+ let recipeIndex;
33
+ const recipesFor = (kind) => {
34
+ if (!recipeIndex) {
35
+ recipeIndex = new Map();
36
+ const { gameData } = serv.containers;
37
+ for (const r of gameData.recipes()) {
38
+ const result = mcData.itemsByName[r.result] ?? mcData.itemsByName[renameItem(r.result)];
39
+ if (!result)
40
+ continue;
41
+ let byItem = recipeIndex.get(r.kind);
42
+ if (!byItem)
43
+ recipeIndex.set(r.kind, byItem = new Map());
44
+ const names = r.ingredients.flatMap(i => i.startsWith('#') ? gameData.itemTag(i.slice(1)) : [i]);
45
+ for (const n of names) {
46
+ const item = mcData.itemsByName[n] ?? mcData.itemsByName[renameItem(n)];
47
+ if (item && !byItem.has(item.id))
48
+ byItem.set(item.id, { ...r, resultId: result.id });
49
+ }
50
+ }
51
+ }
52
+ return recipeIndex.get(kind);
53
+ };
54
+ const recipeOf = (st, item) => item ? recipesFor(st.kind)?.get(item.type) : undefined;
55
+ const fuelOf = (item) => item ? (0, gameData_1.fuelTicks)(item.name) : 0;
56
+ const canCook = (st) => {
57
+ const recipe = recipeOf(st, st.slots[0]);
58
+ if (!recipe)
59
+ return undefined;
60
+ const out = st.slots[2];
61
+ if (!out)
62
+ return recipe;
63
+ const same = out.type === recipe.resultId && (out.metadata ?? 0) === 0 && !out.nbt;
64
+ return same && out.count + recipe.count <= (out.stackSize ?? 64) ? recipe : undefined;
65
+ };
66
+ // ---------------------------------------------------------------- block entity <-> state
67
+ async function loadState(world, pos, blockName) {
68
+ const key = stateKey(world, pos);
69
+ const existing = active.get(key);
70
+ if (existing)
71
+ return existing;
72
+ const { containers } = serv;
73
+ const entity = await containers.entityAt(world, pos);
74
+ const num = (...names) => { for (const n of names)
75
+ if (typeof entity?.[n]?.value === 'number')
76
+ return entity[n].value; return 0; };
77
+ const st = {
78
+ world, pos: pos.clone(), blockName: BASE_NAME(blockName), kind: KIND_OF[BASE_NAME(blockName)],
79
+ slots: entity ? containers.readSlots(entity, 3) : [null, null, null],
80
+ burnTime: num('BurnTime', 'lit_time_remaining'), burnDuration: num('lit_total_time') || 0,
81
+ cookTime: num('CookTime', 'cooking_time_spent'), cookTotal: num('CookTimeTotal', 'cooking_total_time'),
82
+ xp: typeof entity?.flyingsquidXp?.value === 'number' ? entity.flyingsquidXp.value : 0,
83
+ lit: false, dirty: false, syncing: false, busy: false, viewers: new Set(), windows: new Map()
84
+ };
85
+ st.lit = st.burnTime > 0;
86
+ if (!st.burnDuration)
87
+ st.burnDuration = st.burnTime;
88
+ active.set(key, st);
89
+ return st;
90
+ }
91
+ async function flush(st) {
92
+ if (!st.dirty)
93
+ return;
94
+ st.dirty = false;
95
+ const entity = (await serv.containers.entityAt(st.world, st.pos, st.blockName));
96
+ serv.containers.writeSlots(entity, st.slots);
97
+ entity.BurnTime = short(st.burnTime);
98
+ entity.CookTime = short(st.cookTime);
99
+ entity.CookTimeTotal = short(st.cookTotal);
100
+ entity.flyingsquidXp = { type: 'float', value: st.xp };
101
+ st.world.saveAt?.(st.pos);
102
+ }
103
+ async function setLit(st, lit) {
104
+ st.lit = lit;
105
+ const block = await st.world.getBlock(st.pos);
106
+ if (!block)
107
+ return;
108
+ if (flat) {
109
+ if (!BASE_NAME(block.name).endsWith(st.blockName) || String(block.getProperties().lit) === String(lit))
110
+ return;
111
+ await serv.setBlock(st.world, st.pos, PBlock.fromProperties(block.name, { ...block.getProperties(), lit }, 0).stateId);
112
+ }
113
+ else {
114
+ const target = mcData.blocksByName[lit ? 'lit_furnace' : 'furnace'];
115
+ if (target && block.type !== target.id)
116
+ await serv.setBlock(st.world, st.pos, (target.id << 4) | (block.metadata ?? 0));
117
+ }
118
+ }
119
+ // ---------------------------------------------------------------- the furnace tick
120
+ async function tick(st) {
121
+ const wasLit = st.burnTime > 0;
122
+ if (wasLit) {
123
+ st.burnTime--;
124
+ st.dirty = true;
125
+ }
126
+ const fuel = st.slots[1];
127
+ const input = st.slots[0];
128
+ if (wasLit || (fuel && input)) {
129
+ let recipe = canCook(st);
130
+ if (st.burnTime <= 0 && recipe && fuelOf(fuel) > 0) {
131
+ st.burnTime = st.burnDuration = fuelOf(fuel);
132
+ if (fuel.name === 'lava_bucket')
133
+ st.slots[1] = new serv.PrismarineItem(mcData.itemsByName.bucket.id, 1);
134
+ else if (--fuel.count <= 0)
135
+ st.slots[1] = null;
136
+ syncSlot(st, 1);
137
+ st.dirty = true;
138
+ }
139
+ if (st.burnTime > 0 && recipe) {
140
+ if (st.cookTotal === 0)
141
+ st.cookTotal = recipe.time;
142
+ st.cookTime++;
143
+ if (st.cookTime >= st.cookTotal) {
144
+ st.cookTime = 0;
145
+ st.cookTotal = recipe.time;
146
+ const out = st.slots[2];
147
+ if (out)
148
+ out.count += recipe.count;
149
+ else
150
+ st.slots[2] = new serv.PrismarineItem(recipe.resultId, recipe.count, 0);
151
+ if (--st.slots[0].count <= 0)
152
+ st.slots[0] = null;
153
+ st.xp += recipe.experience * recipe.count;
154
+ syncSlot(st, 0);
155
+ syncSlot(st, 2);
156
+ }
157
+ st.dirty = true;
158
+ }
159
+ else if (st.cookTime !== 0) {
160
+ st.cookTime = 0;
161
+ st.dirty = true;
162
+ }
163
+ }
164
+ else if (st.cookTime > 0) {
165
+ st.cookTime = Math.max(0, st.cookTime - 2);
166
+ st.dirty = true;
167
+ }
168
+ if ((st.burnTime > 0) !== st.lit) {
169
+ st.dirty = true;
170
+ await setLit(st, st.burnTime > 0);
171
+ }
172
+ sendProgress(st);
173
+ }
174
+ const syncSlot = (st, slot) => {
175
+ for (const [p, win] of st.windows) {
176
+ st.syncing = true;
177
+ try {
178
+ win.updateSlot(slot, st.slots[slot]);
179
+ }
180
+ finally {
181
+ st.syncing = false;
182
+ }
183
+ p.writePacket('set_slot', { windowId: p.windowId, stateId: 1, slot, item: serv.PrismarineItem.toNotch(st.slots[slot]) });
184
+ }
185
+ };
186
+ const sendProgress = (st) => {
187
+ for (const p of st.viewers) {
188
+ const props = [[0, st.burnTime], [1, st.burnDuration], [2, st.cookTime], [3, st.cookTotal || 200]];
189
+ for (const [property, value] of props)
190
+ p.writePacket('craft_progress_bar', { windowId: p.windowId, property, value });
191
+ }
192
+ };
193
+ serv.on('tick', (_delta, count) => {
194
+ for (const [key, st] of active) {
195
+ if (st.busy)
196
+ continue;
197
+ st.busy = true;
198
+ tick(st).then(async () => {
199
+ if (count % 20 === 0)
200
+ await flush(st);
201
+ // a furnace with nothing to do and nobody looking is forgotten until it is touched again
202
+ if (st.burnTime <= 0 && st.cookTime <= 0 && !st.viewers.size && !(st.slots[0] && st.slots[1])) {
203
+ await flush(st);
204
+ active.delete(key);
205
+ }
206
+ else if (!(await st.world.getBlock(st.pos)) || !KIND_OF[(await st.world.getBlock(st.pos)).name]) {
207
+ active.delete(key);
208
+ }
209
+ }).catch(e => serv.warn(`furnace at ${st.pos}: ${e.message}`)).finally(() => { st.busy = false; });
210
+ }
211
+ });
212
+ // furnaces that were burning when their chunk loaded start again
213
+ const watched = new WeakSet();
214
+ const watchWorld = (world) => {
215
+ if (watched.has(world))
216
+ return;
217
+ watched.add(world);
218
+ world.on?.('chunkColumnLoad', async (corner) => {
219
+ try {
220
+ const column = world.getLoadedColumn?.(corner.x >> 4, corner.z >> 4);
221
+ for (const [key, entity] of Object.entries(column?.blockEntities ?? {})) {
222
+ const id = String(entity?.id?.value ?? '').replace(/^minecraft:/, '').toLowerCase();
223
+ if (!['furnace', 'blast_furnace', 'smoker'].includes(id))
224
+ continue;
225
+ const [x, y, z] = key.split(',').map(Number);
226
+ if ((entity.BurnTime?.value ?? 0) > 0 || (entity.CookTime?.value ?? 0) > 0)
227
+ await loadState(world, new vec3_1.Vec3(x, y, z), id);
228
+ }
229
+ }
230
+ catch { }
231
+ });
232
+ };
233
+ serv.once('pluginsReady', () => {
234
+ for (const w of Object.values(serv.worlds ?? {}))
235
+ watchWorld(w);
236
+ // a furnace used before the datapack layers were read indexed the built-in recipes only
237
+ void serv.containers.gameData.ready.then(() => { recipeIndex = undefined; });
238
+ });
239
+ serv.on('worldCreated', watchWorld);
240
+ // ---------------------------------------------------------------- window
241
+ async function open(player, world, pos, blockName) {
242
+ const st = await loadState(world, pos, blockName);
243
+ const inventoryType = newWindows ? `minecraft:${st.blockName}` : 'minecraft:furnace';
244
+ const windowSlots = {};
245
+ st.slots.forEach((item, i) => { if (item)
246
+ windowSlots[i] = item; });
247
+ const window = player.openCustomWindow({
248
+ inventoryType: inventoryType,
249
+ title: { translate: `container.${st.blockName}` },
250
+ windowSlots,
251
+ onSlotClick: (slot, oldItem, newItem) => {
252
+ if (slot > 2 || st.syncing)
253
+ return;
254
+ const revert = () => {
255
+ st.slots[slot] = oldItem;
256
+ syncSlot(st, slot);
257
+ };
258
+ if (slot === 2 && newItem && (!oldItem || newItem.count > oldItem.count || newItem.type !== oldItem.type))
259
+ return revert(); // the output is take-only
260
+ if (slot === 1 && newItem && !fuelOf(newItem) && newItem.name !== 'bucket')
261
+ return revert();
262
+ st.slots[slot] = newItem;
263
+ st.dirty = true;
264
+ if (slot === 2 && oldItem && (!newItem || newItem.count < oldItem.count)) {
265
+ // the experience of the cooked items goes to the one who takes them
266
+ const taken = oldItem.count - (newItem?.count ?? 0);
267
+ const share = newItem ? st.xp * taken / oldItem.count : st.xp;
268
+ st.xp -= share;
269
+ const xp = Math.floor(share) + (Math.random() < share - Math.floor(share) ? 1 : 0);
270
+ if (xp > 0)
271
+ player.setXp(player.xp + xp);
272
+ }
273
+ },
274
+ onClose: () => {
275
+ st.viewers.delete(player);
276
+ st.windows.delete(player);
277
+ void flush(st);
278
+ }
279
+ });
280
+ st.viewers.add(player);
281
+ st.windows.set(player, window);
282
+ player.once('disconnected', () => { st.viewers.delete(player); st.windows.delete(player); });
283
+ sendProgress(st);
284
+ return true;
285
+ }
286
+ serv.once('asap', () => {
287
+ const blocks = ['furnace', 'blast_furnace', 'smoker'].filter(n => mcData.blocksByName[n]);
288
+ for (const name of blocks) {
289
+ serv.onBlockInteraction(name, ({ block, player }) => open(player, player.world, block.position, name));
290
+ }
291
+ if (!flat)
292
+ serv.onBlockInteraction('lit_furnace', ({ block, player }) => open(player, player.world, block.position, 'furnace'));
293
+ });
294
+ // a furnace that is broken drops its contents
295
+ serv.furnaceBroken = async (world, pos, blockName, drop) => {
296
+ const key = stateKey(world, pos);
297
+ const st = active.get(key);
298
+ if (st) {
299
+ st.dirty = true;
300
+ await flush(st);
301
+ for (const p of st.viewers)
302
+ st.windows.get(p)?.close?.();
303
+ active.delete(key);
304
+ }
305
+ const entity = await serv.containers.entityAt(world, pos);
306
+ if (!entity)
307
+ return;
308
+ if (drop) {
309
+ const items = serv.containers.readSlots(entity, 3);
310
+ serv.containers.dropStacks?.(world, pos, items);
311
+ }
312
+ await serv.containers.removeEntity(world, pos);
313
+ };
314
+ };
315
+ exports.server = server;
316
+ const player = (player, serv) => {
317
+ player.on('dug', ({ position, block }, cancelled) => {
318
+ if (cancelled || !block || !KIND_OF[block.name])
319
+ return;
320
+ void serv.furnaceBroken(player.world, position, block.name, player.gameMode !== 1).catch((e) => serv.warn(`furnace break: ${e.message}`));
321
+ });
322
+ };
323
+ exports.player = player;
@@ -61,6 +61,11 @@ declare global {
61
61
  createWorld: (spec: WorldSpec) => CustomWorld;
62
62
  /** Unregisters a world (players inside are moved to the overworld); core worlds cannot be removed */
63
63
  removeWorld: (name: string) => Promise<void>;
64
+ /** `dimension` and `worldName` fields of the login / respawn packet for a world */
65
+ worldClientInfo: (world: CustomWorld, dimension?: number) => {
66
+ dimension: any;
67
+ worldName: string;
68
+ };
64
69
  /** Saves block in world and sends block update to all players of the same world. */
65
70
  "setBlock": (world: CustomWorld, position: Vec3, stateId: number) => Promise<void>;
66
71
  /** Sends a block action to all players of the same world. */