@zardoy/flying-squid 0.0.123 → 0.0.125

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.
Files changed (42) hide show
  1. package/config/default-settings.json +2 -4
  2. package/dist/app.js +18 -0
  3. package/dist/index.js +1 -1
  4. package/dist/lib/generations.d.ts +1 -1
  5. package/dist/lib/generations.js +2 -2
  6. package/dist/lib/generatorForWorldHeight.d.ts +5 -0
  7. package/dist/lib/generatorForWorldHeight.js +11 -0
  8. package/dist/lib/modules/dimensionCodec.d.ts +2 -0
  9. package/dist/lib/modules/dimensionCodec.js +121 -0
  10. package/dist/lib/modules/effects.js +3 -0
  11. package/dist/lib/modules/index.js +3 -1
  12. package/dist/lib/modules/playerLogin.js +3 -2
  13. package/dist/lib/modules/players.d.ts +6 -0
  14. package/dist/lib/modules/players.js +42 -16
  15. package/dist/lib/modules/players.test.d.ts +1 -0
  16. package/dist/lib/modules/players.test.js +30 -0
  17. package/dist/lib/modules/portal.d.ts +5 -0
  18. package/dist/lib/modules/portal.js +179 -0
  19. package/dist/lib/modules/recipes.d.ts +12 -0
  20. package/dist/lib/modules/recipes.js +266 -0
  21. package/dist/lib/modules/title.d.ts +4 -2
  22. package/dist/lib/modules/title.js +33 -16
  23. package/dist/lib/modules/title.test.d.ts +1 -0
  24. package/dist/lib/modules/title.test.js +102 -0
  25. package/dist/lib/modules/world.d.ts +36 -3
  26. package/dist/lib/modules/world.js +265 -46
  27. package/dist/lib/modules/worldManager.d.ts +1 -0
  28. package/dist/lib/modules/worldManager.js +119 -0
  29. package/dist/lib/playerDat.d.ts +1 -8
  30. package/dist/lib/playerDat.js +13 -2
  31. package/dist/lib/worldGenerations/biomeFix.d.ts +10 -0
  32. package/dist/lib/worldGenerations/biomeFix.js +19 -0
  33. package/dist/lib/worldGenerations/empty.js +4 -1
  34. package/dist/lib/worldGenerations/noise.d.ts +22 -0
  35. package/dist/lib/worldGenerations/noise.js +248 -0
  36. package/dist/minigames/oneblock.d.ts +1 -0
  37. package/dist/minigames/oneblock.js +41 -0
  38. package/dist/minigames/tntRun.d.ts +1 -0
  39. package/dist/minigames/tntRun.js +14 -0
  40. package/dist/modules.d.ts +2 -2
  41. package/dist/types.d.ts +2 -0
  42. package/package.json +2 -2
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.usedServerPathsV1 = exports.player = exports.server = void 0;
40
+ const generatorForWorldHeight_1 = require("../generatorForWorldHeight");
40
41
  const node_gzip_1 = require("node-gzip");
41
42
  const prismarine_nbt_1 = __importDefault(require("prismarine-nbt"));
42
43
  const util_1 = require("util");
@@ -44,23 +45,28 @@ const fs_1 = __importDefault(require("fs"));
44
45
  const prismarine_provider_anvil_1 = require("prismarine-provider-anvil");
45
46
  const playerDat = __importStar(require("../playerDat"));
46
47
  const prismarine_world_1 = __importDefault(require("prismarine-world"));
48
+ const prismarine_chunk_1 = __importDefault(require("prismarine-chunk"));
47
49
  const prismarine_registry_1 = __importDefault(require("prismarine-registry"));
48
50
  const generations_1 = __importDefault(require("../generations"));
51
+ const dimensionCodec_1 = require("./dimensionCodec");
52
+ const biomeFix_1 = require("../worldGenerations/biomeFix");
49
53
  const template_1 = require("../worldGenerations/template");
50
54
  const vec3_1 = require("vec3");
55
+ const user_error_1 = __importDefault(require("../user_error"));
51
56
  const utils_1 = require("../../utils");
52
57
  const levelDat_1 = require("../../levelDat");
53
58
  const blockRenames_1 = require("../../blockRenames");
59
+ const random_1 = require("minecraft-worldgen/dist/rng/random");
54
60
  const fsStat = (0, util_1.promisify)(fs_1.default.stat);
55
61
  const fsMkdir = (0, util_1.promisify)(fs_1.default.mkdir);
56
62
  const server = async function (serv, options) {
57
63
  const { version, worldSaveVersion: _worldSaveVersion, worldFolder, noWorldRegion, generation: _generation } = options;
58
- let generation = _generation ?? { name: 'diamond_square', options: {} };
64
+ let generation = _generation ?? { name: 'noise', options: {} };
59
65
  if (generation.name === 'flat') {
60
66
  generation.name = 'superflat';
61
67
  }
62
- if (generation.name === 'default') {
63
- generation.name = 'diamond_square';
68
+ if (generation.name === 'default' || generation.name === 'diamond_square') {
69
+ generation.name = 'noise';
64
70
  }
65
71
  // Detect world type from level.dat
66
72
  if (worldFolder && !noWorldRegion) {
@@ -81,12 +87,15 @@ const server = async function (serv, options) {
81
87
  if (levelData.generatorName === 'flat') {
82
88
  generation.name = 'superflat';
83
89
  }
90
+ else if (levelData.generatorName === 'default' || levelData.generatorName === 'diamond_square') {
91
+ generation.name = 'noise';
92
+ }
84
93
  else if (generations_1.default[levelData.generatorName]) {
85
94
  generation.name = levelData.generatorName;
86
95
  }
87
96
  else {
88
97
  console.warn(`Unsupported world chunks generator type: ${levelData.generatorName}`);
89
- generation.name = 'diamond_square';
98
+ generation.name = 'noise';
90
99
  }
91
100
  }
92
101
  }
@@ -97,12 +106,26 @@ const server = async function (serv, options) {
97
106
  generation.options ??= {};
98
107
  generation.options.worldHeight = serv.supportFeature('tallWorld') ? 384 : 256;
99
108
  generation.options.minY = serv.supportFeature('tallWorld') ? -64 : 0;
109
+ const requestedGenerator = generation.name;
110
+ generation.name = (0, generatorForWorldHeight_1.generatorForWorldHeight)(generation.name, generation.options.minY, generation.options.worldHeight);
111
+ if (generation.name !== requestedGenerator) {
112
+ console.warn(`The ${requestedGenerator} generator builds 1.18+ worlds only, using the ${generation.name} generator for ${version}: saved chunks load as they are, new ones are empty`);
113
+ }
100
114
  levelDatWriter(serv, options);
101
115
  const World = (0, prismarine_world_1.default)(version);
102
116
  const registry = (0, prismarine_registry_1.default)(version);
103
117
  const worldSaveVersion = _worldSaveVersion ?? version;
104
118
  const Anvil = worldFolder ? (0, prismarine_provider_anvil_1.Anvil)(worldSaveVersion) : undefined;
105
- const newSeed = serv.seed ?? (generation.options.seed || Math.floor(Math.random() * Math.pow(2, 31)));
119
+ const newSeed = (0, random_1.parseWorldSeed)(serv.seed ?? generation.options.seed);
120
+ const worldsFile = worldFolder && !noWorldRegion ? `${worldFolder}/flyingsquid-worlds.json` : undefined;
121
+ // read (async fs: browser file systems have no sync calls) before any world is created, creating worlds rewrites the file; no await may be added between the
122
+ // `setTimeout(() => serv.writeLevelDat())` below and the end of this module (it would run before the seed exists)
123
+ const savedSpecs = await (async () => { try {
124
+ return worldsFile ? JSON.parse(await fs_1.default.promises.readFile(worldsFile, 'utf8')) : [];
125
+ }
126
+ catch {
127
+ return [];
128
+ } })();
106
129
  let seed;
107
130
  let regionFolder;
108
131
  if (worldFolder && !noWorldRegion) {
@@ -119,7 +142,7 @@ const server = async function (serv, options) {
119
142
  if ([SpawnY, SpawnX, SpawnZ].every(x => x !== undefined)) {
120
143
  serv.spawnPoint ??= new vec3_1.Vec3(SpawnX, SpawnY, SpawnZ);
121
144
  }
122
- seed = serv.levelData?.RandomSeed?.[0] ?? newSeed;
145
+ seed = (0, random_1.seedFromLevelDat)(serv.levelData?.RandomSeed) ?? newSeed;
123
146
  if (serv.levelData?.Version?.Name !== worldSaveVersion) {
124
147
  console.warn(`World save version mismatch: you select: ${worldSaveVersion} actual stored: ${serv.levelData?.Version?.Name}`);
125
148
  }
@@ -151,6 +174,38 @@ const server = async function (serv, options) {
151
174
  world['min_y'] = generation.options.minY;
152
175
  world['height'] = generation.options.worldHeight;
153
176
  };
177
+ /**
178
+ * `World#getColumn` (prismarine-world) does `await Promise.resolve()` and only then checks
179
+ * `this.columns[key]` before deciding to invoke the chunk generator. If two callers ask for the
180
+ * same chunk before either has reached that point — e.g. our own world-gen code writing custom
181
+ * blocks into a spawn-adjacent chunk racing the player's own chunk-loading requesting the same
182
+ * chunk — BOTH calls see no cached column and BOTH invoke the generator. Whichever `setColumn`
183
+ * resolves last silently replaces `this.columns[key]`, discarding any edits already made to the
184
+ * other (now-orphaned) chunk instance. This wraps `getColumn` so concurrent requests for the same
185
+ * (chunkX, chunkZ) share a single in-flight generation instead of racing.
186
+ */
187
+ const dedupeGetColumn = (world) => {
188
+ // prismarine-world stores whatever the chunk generator returned: an async generator (noise) would leave a Promise in `columns`, which then reaches the Anvil
189
+ // storage (toNBT(Promise): "Cannot convert undefined or null to object") and nothing is ever saved. Store the resolved chunk.
190
+ const originalSetColumn = world.setColumn.bind(world);
191
+ world.setColumn = async (chunkX, chunkZ, chunk, save) => originalSetColumn(chunkX, chunkZ, await chunk, save);
192
+ const pending = new Map();
193
+ const original = world.getColumn.bind(world);
194
+ world.getColumn = (chunkX, chunkZ) => {
195
+ const loaded = world.getLoadedColumn(chunkX, chunkZ);
196
+ if (loaded)
197
+ return Promise.resolve(loaded);
198
+ const key = `${chunkX},${chunkZ}`;
199
+ const existing = pending.get(key);
200
+ if (existing)
201
+ return existing;
202
+ const promise = Promise.resolve(original(chunkX, chunkZ)).finally(() => {
203
+ pending.delete(key);
204
+ });
205
+ pending.set(key, promise);
206
+ return promise;
207
+ };
208
+ };
154
209
  const generationModule = generations_1.default[generation.name] ? generations_1.default[generation.name] : require(generation.name);
155
210
  const genOpts = generation.options;
156
211
  const templateStr = typeof options.chunkTemplate === 'string' ? options.chunkTemplate
@@ -170,27 +225,169 @@ const server = async function (serv, options) {
170
225
  serv.overworld.seed = serv.seed = generationOptions.seed;
171
226
  serv.overworld.generatorName = generation.name;
172
227
  patchWorld(serv.overworld);
173
- serv.netherworld = new World(generations_1.default.nether(generationOptions));
174
- patchWorld(serv.netherworld);
175
- serv.netherworld.seed = generationOptions.seed;
176
- serv.netherworld.generatorName = 'nether';
177
- // serv.endworld = new World(generations["end"]({}));
178
- serv.worlds = {
179
- 'overworld': serv.overworld,
180
- 'nether': serv.netherworld
181
- // 'end': serv.endworld
228
+ dedupeGetColumn(serv.overworld);
229
+ // ---- world registry (Multiverse-style): any number of worlds; each has an environment (= client dimension type) and a generator
230
+ const ENV_DIMENSION = { normal: 0, nether: -1, end: 1 };
231
+ const ENV_NOISE_DIM = { normal: 'overworld', nether: 'nether', end: 'end' };
232
+ const baseGeneratorName = generation.name;
233
+ const ChunkClass = (0, prismarine_chunk_1.default)(version);
234
+ /** per-world Anvil storage: nether `DIM-1`, end `DIM1`, other worlds `dimensions/flyingsquid/<name>`. Chunks of non-overworld sizes are converted on load (Anvil always yields -64..320 columns). */
235
+ const regionDirOf = (name, environment) => !worldFolder || noWorldRegion ? undefined
236
+ : name === 'nether' && environment === 'nether' ? `${worldFolder}/DIM-1/region`
237
+ : name === 'end' && environment === 'end' ? `${worldFolder}/DIM1/region`
238
+ : `${worldFolder}/dimensions/flyingsquid/${name}/region`;
239
+ /** deletes the saved chunks of an extra world (used when a world is regenerated from another recipe) */
240
+ serv.deleteWorldData = (name) => {
241
+ const dir = regionDirOf(name, 'normal');
242
+ if (dir)
243
+ try {
244
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
245
+ }
246
+ catch (e) {
247
+ serv.warn(`Could not delete saved chunks of '${name}': ${e.message}`);
248
+ }
249
+ };
250
+ const storageFor = (name, environment, minY, height) => {
251
+ if (!worldFolder || noWorldRegion || !Anvil)
252
+ return null;
253
+ const dir = regionDirOf(name, environment);
254
+ // browser file systems (IndexedDB) only have the async fs calls: the directory is created before the first load / save instead of synchronously here
255
+ const ready = fsMkdir(dir, { recursive: true }).then(() => true, async () => {
256
+ const exists = await fsStat(dir).then(() => true, () => false);
257
+ if (!exists)
258
+ serv.warn?.(`No storage for world '${name}' (cannot create ${dir}); it will not be saved`);
259
+ return exists;
260
+ });
261
+ const anvil = new Anvil(dir);
262
+ const sameSize = minY === generation.options.minY && height === generation.options.worldHeight;
263
+ return {
264
+ save: async (x, z, chunk) => { if (await ready)
265
+ await anvil.save(x, z, chunk); },
266
+ load: async (x, z) => {
267
+ if (!await ready)
268
+ return null;
269
+ const c = await anvil.load(x, z);
270
+ if (!c || sameSize || (c.minY === minY && c.worldHeight === height))
271
+ return c;
272
+ const out = (0, biomeFix_1.fixSetBiome)(new ChunkClass({ minY, worldHeight: height }));
273
+ const pos = new vec3_1.Vec3(0, 0, 0);
274
+ for (let y = Math.max(minY, c.minY); y < Math.min(minY + height, c.minY + c.worldHeight); y++) {
275
+ pos.y = y;
276
+ for (let zz = 0; zz < 16; zz++) {
277
+ pos.z = zz;
278
+ for (let xx = 0; xx < 16; xx++) {
279
+ pos.x = xx;
280
+ const id = c.getBlockStateId(pos);
281
+ if (id !== 0)
282
+ out.setBlockStateId(pos, id);
283
+ out.setSkyLight(pos, 15);
284
+ out.setBlockLight(pos, 15);
285
+ if ((y & 3) === 0 && (xx & 3) === 0 && (zz & 3) === 0)
286
+ out.setBiome(pos, c.getBiome(pos));
287
+ }
288
+ }
289
+ }
290
+ return out;
291
+ }
292
+ };
293
+ };
294
+ let loadingSaved = true;
295
+ const saveWorldSpecs = () => {
296
+ if (loadingSaved)
297
+ return;
298
+ if (!worldsFile)
299
+ return;
300
+ const extra = Object.values(serv.worldSpecs).filter(sp => !['overworld', 'nether', 'end'].includes(sp.name));
301
+ fs_1.default.promises.writeFile(worldsFile, JSON.stringify(extra, (_k, v) => typeof v === 'bigint' ? v.toString() : v, 2)).catch((e) => serv.warn('Could not save worlds: ' + e.message));
302
+ };
303
+ const createWorld = (spec) => {
304
+ if (serv.worlds[spec.name])
305
+ throw new user_error_1.default(`World '${spec.name}' already exists`);
306
+ const environment = spec.environment ?? 'normal';
307
+ if (!(environment in ENV_DIMENSION))
308
+ throw new user_error_1.default(`Unknown environment '${environment}' (normal | nether | end)`);
309
+ // default generator: the server's generator for the overworld; the noise generator also builds nether / end, others fall back to the simple ones
310
+ const genName = spec.generator ?? (environment === 'normal' || baseGeneratorName === 'noise' ? baseGeneratorName : environment === 'nether' ? 'nether' : 'empty');
311
+ const module = generations_1.default[genName] ?? require(genName);
312
+ const worldSeed = spec.seed === undefined ? generationOptions.seed : (0, random_1.parseWorldSeed)(spec.seed);
313
+ const tall = environment === 'normal';
314
+ const opts = {
315
+ ...generationOptions,
316
+ ...spec.options,
317
+ seed: worldSeed,
318
+ dimension: ENV_NOISE_DIM[environment],
319
+ preset: spec.preset,
320
+ recipe: spec.recipe,
321
+ minY: tall ? generation.options.minY : 0,
322
+ worldHeight: tall ? generation.options.worldHeight : 256
323
+ };
324
+ const generator = module(opts);
325
+ const world = new World(generator, storageFor(spec.name, environment, opts.minY, opts.worldHeight), options.savingInterval);
326
+ world['min_y'] = opts.minY;
327
+ world.disposeGenerator = generator?.dispose;
328
+ world['height'] = opts.worldHeight;
329
+ dedupeGetColumn(world);
330
+ world.seed = worldSeed;
331
+ world.generatorName = genName;
332
+ world.environment = environment;
333
+ world.dimensionId = ENV_DIMENSION[environment];
334
+ world.worldName = spec.name;
335
+ world.blockEntityData = {};
336
+ world.portals = [];
337
+ serv.worlds[spec.name] = world;
338
+ serv.worldSpecs[spec.name] = { ...spec, environment, generator: genName };
339
+ saveWorldSpecs();
340
+ serv.emit('worldCreated', world);
341
+ return world;
342
+ };
343
+ serv.worldSpecs = {};
344
+ serv.worlds = { overworld: serv.overworld };
345
+ serv.overworld.environment = 'normal';
346
+ serv.overworld.dimensionId = 0;
347
+ serv.overworld.worldName = 'overworld';
348
+ serv.worldSpecs.overworld = { name: 'overworld', environment: 'normal', generator: generation.name, seed: generationOptions.seed };
349
+ serv.createWorld = createWorld;
350
+ serv.netherworld = createWorld({ name: 'nether', environment: 'nether' });
351
+ serv.endworld = createWorld({ name: 'end', environment: 'end' });
352
+ // worlds created at runtime (/mv create) in an earlier session, then the ones declared in the options
353
+ for (const spec of [...savedSpecs, ...(options.worlds ?? [])]) {
354
+ if (serv.worlds[spec.name])
355
+ continue;
356
+ try {
357
+ createWorld(spec);
358
+ }
359
+ catch (e) {
360
+ serv.warn(`Could not create world '${spec.name}': ${e.message}`);
361
+ }
362
+ }
363
+ loadingSaved = false;
364
+ saveWorldSpecs();
365
+ serv.removeWorld = async (name) => {
366
+ const world = serv.worlds[name];
367
+ if (!world)
368
+ throw new user_error_1.default(`World '${name}' does not exist`);
369
+ if (world === serv.overworld || world === serv.netherworld || world === serv.endworld)
370
+ throw new user_error_1.default(`World '${name}' is a core world and cannot be removed`);
371
+ for (const player of serv.players.filter(p => p.world === world)) {
372
+ await player.changeWorld(serv.overworld, { dimension: 0 });
373
+ }
374
+ world.stopSaving();
375
+ try {
376
+ await world.disposeGenerator?.();
377
+ }
378
+ catch { }
379
+ delete serv.worlds[name];
380
+ delete serv.worldSpecs[name];
381
+ saveWorldSpecs();
382
+ serv.emit('worldRemoved', name);
182
383
  };
183
384
  serv.dimensionNames = {
184
- '-1': 'minecraft:nether',
185
- 0: 'minecraft:overworld'
186
- // 1: 'minecraft:end'
385
+ '-1': 'minecraft:the_nether',
386
+ 0: 'minecraft:overworld',
387
+ 1: 'minecraft:the_end'
187
388
  };
188
- // WILL BE REMOVED WHEN ACTUALLY IMPLEMENTED
189
389
  serv.overworld.blockEntityData = {};
190
- serv.netherworld.blockEntityData = {};
191
390
  serv.overworld.portals = [];
192
- serv.netherworld.portals = [];
193
- /// ///////////
194
391
  serv.pregenWorld = (world, size = 3) => {
195
392
  const promises = [];
196
393
  for (let x = -size; x < size; x++) {
@@ -256,14 +453,14 @@ const server = async function (serv, options) {
256
453
  serv.commands.add({
257
454
  base: 'changeworld',
258
455
  info: 'to change world',
259
- usage: '/changeworld overworld|nether',
456
+ usage: '/changeworld <world> (overworld | nether | end | any world created with /mv create)',
260
457
  onlyPlayer: true,
261
458
  op: true,
262
- action(world, ctx) {
263
- if (world === 'nether')
264
- ctx.player.changeWorld(serv.netherworld, { dimension: -1 });
265
- if (world === 'overworld')
266
- ctx.player.changeWorld(serv.overworld, { dimension: 0 });
459
+ action(name, ctx) {
460
+ const world = serv.worlds[String(name).trim()];
461
+ if (!world)
462
+ throw new user_error_1.default(`Unknown world '${name}'. Worlds: ${Object.keys(serv.worlds).join(', ')}`);
463
+ return ctx.player.changeWorld(world, { dimension: world.dimensionId });
267
464
  }
268
465
  });
269
466
  serv.commands.add({
@@ -355,6 +552,11 @@ const server = async function (serv, options) {
355
552
  if (!worldFolder) {
356
553
  serv.writeLevelDat();
357
554
  }
555
+ else if (!noWorldRegion && !serv.levelData) {
556
+ // a new world folder: write level.dat right away. It used to appear only with the first autosave (60 s), a world closed earlier had chunks but no level.dat
557
+ // and was listed as broken (and not loadable) by the web client.
558
+ setTimeout(() => { serv.writeLevelDat().catch((e) => serv.warn(`Could not write level.dat: ${e.message}`)); });
559
+ }
358
560
  console.log('worlds init done');
359
561
  // Periodic autosave: world and all players
360
562
  const autosaveMs = options.savingInterval === false ? 0 : (typeof options.savingInterval === 'number' ? options.savingInterval : 60_000);
@@ -400,14 +602,14 @@ const levelDatWriter = (serv, options) => {
400
602
  const original = serv.worlds[world].generatorName;
401
603
  if (original === 'superflat')
402
604
  return 'flat';
403
- if (original === 'diamond_square')
605
+ if (original === 'noise')
404
606
  return 'default';
405
607
  if (original === 'customized')
406
608
  return 'customized';
407
609
  return original;
408
610
  };
409
611
  const newLevelDat = {
410
- RandomSeed: serv.levelData?.RandomSeed ?? [serv.seed, 0],
612
+ RandomSeed: (0, levelDat_1.numberToLongArray)(serv.seed),
411
613
  Version: serv.levelData?.Version ?? { Name: options.version },
412
614
  generatorName: serv.levelData?.generatorName ?? getGeneratorName('overworld'),
413
615
  // WorldGenSettings: {
@@ -493,11 +695,11 @@ const player = function (player, serv, settings) {
493
695
  }, // FIXME: fake heightmap
494
696
  chunkData: chunkBuffer,
495
697
  blockEntities: [],
496
- skyLightMask: chunk.skyLightMask,
497
- // skyLightMask: [chunk.skyLightMask.data],
498
- emptySkyLightMask: chunk.emptySkyLightMask,
499
- blockLightMask: chunk.blockLightMask,
500
- emptyBlockLightMask: chunk.emptyBlockLightMask,
698
+ // long-array masks (dumpLight): the BitArray objects of the column are not what the client / serializer expect (in-process clients got no light at all)
699
+ skyLightMask: dumpedLights.skyLightMask ?? chunk.skyLightMask,
700
+ emptySkyLightMask: dumpedLights.emptySkyLightMask ?? chunk.emptySkyLightMask,
701
+ blockLightMask: dumpedLights.blockLightMask ?? chunk.blockLightMask,
702
+ emptyBlockLightMask: dumpedLights.emptyBlockLightMask ?? chunk.emptyBlockLightMask,
501
703
  ...newLightsData
502
704
  });
503
705
  if (serv.supportFeature('lightSentSeparately') && !serv.supportFeature('newLightingDataFormat')) {
@@ -505,10 +707,10 @@ const player = function (player, serv, settings) {
505
707
  chunkX: x,
506
708
  chunkZ: z,
507
709
  trustEdges: true, // should be false when a chunk section is updated instead of the whole chunk being overwritten, do we ever do that?
508
- skyLightMask: chunk.skyLightMask,
509
- blockLightMask: chunk.blockLightMask,
510
- emptySkyLightMask: chunk.emptySkyLightMask,
511
- emptyBlockLightMask: chunk.emptyBlockLightMask,
710
+ skyLightMask: dumpedLights.skyLightMask ?? chunk.skyLightMask,
711
+ blockLightMask: dumpedLights.blockLightMask ?? chunk.blockLightMask,
712
+ emptySkyLightMask: dumpedLights.emptySkyLightMask ?? chunk.emptySkyLightMask,
713
+ emptyBlockLightMask: dumpedLights.emptyBlockLightMask ?? chunk.emptyBlockLightMask,
512
714
  ...newLightsData ? newLightsData : {
513
715
  data: dumpedLights
514
716
  }
@@ -551,6 +753,7 @@ const player = function (player, serv, settings) {
551
753
  return Promise.resolve();
552
754
  });
553
755
  };
756
+ const CHUNK_PREFETCH = 8;
554
757
  player.sendNearbyChunks = (viewDistance, group = false, abortSignal) => {
555
758
  player.lastPositionChunkUpdated = player.position;
556
759
  const playerChunkX = Math.floor(player.position.x / 16);
@@ -559,19 +762,34 @@ const player = function (player, serv, settings) {
559
762
  .map((key) => key.split(',').map(a => parseInt(a)))
560
763
  .filter(([x, z]) => Math.abs(x - playerChunkX) > viewDistance || Math.abs(z - playerChunkZ) > viewDistance)
561
764
  .forEach(([x, z]) => player._unloadChunk(x, z));
562
- return (0, utils_1.generateSpiralMatrix)(viewDistance)
765
+ const todo = (0, utils_1.generateSpiralMatrix)(viewDistance)
563
766
  .map(t => ({
564
767
  chunkX: playerChunkX + t[0],
565
768
  chunkZ: playerChunkZ + t[1]
566
769
  }))
567
- .filter(({ chunkX, chunkZ }) => !player.loadedChunks[`${chunkX},${chunkZ}`])
568
- .reduce((acc, { chunkX, chunkZ }) => {
770
+ .filter(({ chunkX, chunkZ }) => !player.loadedChunks[`${chunkX},${chunkZ}`]);
771
+ // chunks are sent in spiral order, but generation of the next few is requested ahead of time so a multi-worker generator (staged pipeline) has work for all its workers
772
+ const ahead = new Map();
773
+ const request = (i) => {
774
+ let p = ahead.get(i);
775
+ if (!p && i < todo.length) {
776
+ p = Promise.resolve(player.world.getColumn(todo[i].chunkX, todo[i].chunkZ));
777
+ p.catch(() => { }); // reported when its turn comes
778
+ ahead.set(i, p);
779
+ }
780
+ return p;
781
+ };
782
+ return todo.reduce((acc, { chunkX, chunkZ }, i) => {
569
783
  const p = acc
570
784
  .then(() => {
571
785
  if (abortSignal?.aborted)
572
786
  return;
573
787
  serv.abortSignal.throwIfAborted();
574
- return player.world.getColumn(chunkX, chunkZ);
788
+ for (let k = 1; k <= CHUNK_PREFETCH; k++)
789
+ request(i + k);
790
+ const col = request(i);
791
+ ahead.delete(i);
792
+ return col;
575
793
  })
576
794
  .then((column) => {
577
795
  if (!column || abortSignal?.aborted)
@@ -620,8 +838,9 @@ const player = function (player, serv, settings) {
620
838
  }
621
839
  player._client.write('respawn', {
622
840
  previousGameMode: player.prevGameMode,
623
- dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[opt.dimension || 0] : opt.dimension || 0,
624
- worldName: serv.dimensionNames[opt.dimension || 0],
841
+ dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[opt.dimension || 0] : serv.supportFeature('dimensionIsAnInt') ? opt.dimension || 0 : (0, dimensionCodec_1.dimensionNbt)(opt.dimension || 0),
842
+ // custom worlds get their own level identifier so the client rebuilds its level even when the dimension type is the same
843
+ worldName: ['overworld', 'nether', 'end'].includes(world.worldName) || !world.worldName ? serv.dimensionNames[opt.dimension || 0] : `flyingsquid:${world.worldName.toLowerCase()}`,
625
844
  difficulty: opt.difficulty || serv.difficulty,
626
845
  hashedSeed: serv.hashedSeed,
627
846
  gamemode: opt.gamemode || player.gameMode,
@@ -631,7 +850,7 @@ const player = function (player, serv, settings) {
631
850
  copyMetadata: true
632
851
  });
633
852
  await player.findSpawnPoint();
634
- player.position = player.spawnPoint;
853
+ player.position = opt.position ?? player.spawnPoint;
635
854
  player.sendSpawnPosition();
636
855
  player.updateAndSpawn();
637
856
  await player.sendMap();
@@ -0,0 +1 @@
1
+ export declare const server: (serv: Server) => void;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.server = void 0;
7
+ const user_error_1 = __importDefault(require("../user_error"));
8
+ const builtin_1 = require("minecraft-worldgen/dist/recipe/builtin");
9
+ /**
10
+ * Multiverse-style world management commands on top of `serv.createWorld` / `serv.removeWorld` / `player.changeWorld`:
11
+ * /mv create <name> <normal|nether|end> [-s <seed>] [-g <generator>] [-t <preset>]
12
+ * /mv list | /mv info [world] | /mv who [world] | /mv tp <world> [player] | /mv remove <world>
13
+ * (plus the short forms /mvcreate /mvlist /mvinfo /mvwho /mvtp /mvremove)
14
+ */
15
+ const PRESETS = ['default', 'amplified', 'large_biomes', 'caves', 'floating_islands', ...Object.keys(builtin_1.BUILTIN_RECIPES)];
16
+ const ENV_ALIASES = { normal: 'normal', overworld: 'normal', nether: 'nether', end: 'end', the_end: 'end', the_nether: 'nether' };
17
+ const tokenize = (input) => input.trim().split(/\s+/).filter(Boolean);
18
+ function parseFlags(tokens) {
19
+ const positional = [];
20
+ const flags = {};
21
+ for (let i = 0; i < tokens.length; i++) {
22
+ const t = tokens[i];
23
+ if (/^-[sgt]$/.test(t)) {
24
+ if (i + 1 >= tokens.length)
25
+ throw new user_error_1.default(`Flag ${t} needs a value`);
26
+ flags[t[1]] = tokens[++i];
27
+ }
28
+ else
29
+ positional.push(t);
30
+ }
31
+ return { positional, flags };
32
+ }
33
+ const server = function (serv) {
34
+ const worldOf = (name) => {
35
+ const w = serv.worlds[name];
36
+ if (!w)
37
+ throw new user_error_1.default(`Unknown world '${name}'. Worlds: ${Object.keys(serv.worlds).join(', ')}`);
38
+ return w;
39
+ };
40
+ const describe = (name) => {
41
+ const w = worldOf(name);
42
+ const spec = serv.worldSpecs[name];
43
+ const players = serv.players.filter(p => p.world === w).length;
44
+ return `${name}: ${w.environment}, generator ${w.generatorName}${spec?.preset && spec.preset !== 'default' ? ` (${spec.preset})` : ''}, seed ${w.seed}, ${players} player${players === 1 ? '' : 's'}`;
45
+ };
46
+ const actions = {
47
+ create(args) {
48
+ const { positional, flags } = parseFlags(args);
49
+ const [name, envName] = positional;
50
+ if (!name || !envName)
51
+ throw new user_error_1.default('Usage: /mv create <name> <normal|nether|end> [-s <seed>] [-g <generator>] [-t <preset>]');
52
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(name))
53
+ throw new user_error_1.default('World names may only contain letters, digits, _ and - (max 32 characters)');
54
+ const environment = ENV_ALIASES[envName.toLowerCase()];
55
+ if (!environment)
56
+ throw new user_error_1.default(`Unknown environment '${envName}' (normal | nether | end)`);
57
+ if (flags.t && !PRESETS.includes(flags.t))
58
+ throw new user_error_1.default(`Unknown preset '${flags.t}' (${PRESETS.join(' | ')})`);
59
+ if (flags.t && flags.t !== 'default' && environment !== 'normal')
60
+ throw new user_error_1.default('Presets only apply to normal worlds');
61
+ const world = serv.createWorld({ name, environment, generator: flags.g, seed: flags.s, preset: flags.t });
62
+ return `Created world '${name}' (${world.environment}, generator ${world.generatorName}, seed ${world.seed}). Use /mv tp ${name}`;
63
+ },
64
+ list() {
65
+ return Object.keys(serv.worlds).map(describe).join('\n');
66
+ },
67
+ info([name], ctx) {
68
+ return describe(name ?? Object.keys(serv.worlds).find(n => serv.worlds[n] === ctx.player?.world) ?? 'overworld');
69
+ },
70
+ who([name]) {
71
+ const names = name ? [name] : Object.keys(serv.worlds);
72
+ return names.map(n => `${n}: ${serv.players.filter(p => p.world === worldOf(n)).map(p => p.username).join(', ') || '-'}`).join('\n');
73
+ },
74
+ async tp([name, target], ctx) {
75
+ if (!name)
76
+ throw new user_error_1.default('Usage: /mv tp <world> [player]');
77
+ const world = worldOf(name);
78
+ const player = target ? serv.getPlayer(target) : ctx.player;
79
+ if (!player)
80
+ throw new user_error_1.default(target ? `Player '${target}' is not online` : 'Specify a player when using this from the console');
81
+ await player.changeWorld(world, { dimension: world.dimensionId });
82
+ return `Teleported ${player.username} to ${name}`;
83
+ },
84
+ async remove([name]) {
85
+ if (!name)
86
+ throw new user_error_1.default('Usage: /mv remove <world>');
87
+ await serv.removeWorld(name);
88
+ return `Removed world '${name}'`;
89
+ }
90
+ };
91
+ actions.teleport = actions.tp;
92
+ actions.unload = actions.remove;
93
+ actions.delete = actions.remove;
94
+ serv.commands.add({
95
+ base: 'mv',
96
+ info: 'Multiverse-style world management',
97
+ usage: '/mv <create|list|info|who|tp|remove> ...',
98
+ op: true,
99
+ parse: (str) => tokenize(str),
100
+ async action(tokens, ctx) {
101
+ const [sub, ...args] = tokens;
102
+ const fn = actions[(sub ?? 'list').toLowerCase()];
103
+ if (!fn)
104
+ throw new user_error_1.default(`Unknown subcommand '${sub}'. Try: create, list, info, who, tp, remove`);
105
+ return await fn(args, ctx);
106
+ }
107
+ });
108
+ for (const sub of ['create', 'list', 'info', 'who', 'tp', 'remove']) {
109
+ serv.commands.add({
110
+ base: 'mv' + sub,
111
+ info: `/mv ${sub}`,
112
+ usage: `/mv${sub} ...`,
113
+ op: true,
114
+ parse: (str) => tokenize(str),
115
+ action: async (tokens, ctx) => await actions[sub](tokens, ctx)
116
+ });
117
+ }
118
+ };
119
+ exports.server = server;
@@ -5,14 +5,7 @@
5
5
  * @param {boolean} useInMemoryStorage
6
6
  */
7
7
  export function read(uuid: string, getSpawnPoint: () => Promise<Vec3>, worldFolder: string | false, useInMemoryStorage: boolean): Promise<any>;
8
- /**
9
- * @param {Player} player
10
- * @param {string | undefined} worldFolder
11
- * @param {boolean} snakeCase
12
- * @param {boolean} theFlattening
13
- * @param {boolean} useInMemoryStorage
14
- */
15
- export function save(player: Player, worldFolder: string | undefined, snakeCase: boolean, theFlattening: boolean, useInMemoryStorage: boolean): Promise<any>;
8
+ export function save(player: any, worldFolder: any, snakeCase: any, theFlattening: any, useInMemoryStorage: any): Promise<any>;
16
9
  export namespace playerDefaults {
17
10
  let health: number;
18
11
  let food: number;
@@ -120,6 +120,17 @@ function playerInventoryToNBT(playerInventory, theFlattening) {
120
120
  * @param {boolean} theFlattening
121
121
  * @param {boolean} useInMemoryStorage
122
122
  */
123
+ /** Dimension tag of the world the player is in: vanilla ids, `flyingsquid:<name>` for extra worlds */
124
+ function dimensionOf(player) {
125
+ const w = player.world;
126
+ if (!w || w.worldName === 'overworld' || !w.worldName)
127
+ return 'minecraft:overworld';
128
+ if (w.worldName === 'nether' && w.environment === 'nether')
129
+ return 'minecraft:the_nether';
130
+ if (w.worldName === 'end' && w.environment === 'end')
131
+ return 'minecraft:the_end';
132
+ return `flyingsquid:${w.worldName}`;
133
+ }
123
134
  async function save(player, worldFolder, snakeCase, theFlattening, useInMemoryStorage) {
124
135
  if (worldFolder === undefined) {
125
136
  if (useInMemoryStorage) {
@@ -130,7 +141,7 @@ async function save(player, worldFolder, snakeCase, theFlattening, useInMemorySt
130
141
  gameMode: player.gameMode,
131
142
  xp: player.xp,
132
143
  heldItemSlot: player.heldItemSlot,
133
- dimension: player.dimension ?? 0,
144
+ dimension: dimensionOf(player),
134
145
  position: player.position,
135
146
  yaw: player.yaw,
136
147
  pitch: player.pitch,
@@ -153,7 +164,7 @@ async function save(player, worldFolder, snakeCase, theFlattening, useInMemorySt
153
164
  newUncompressedData.value.playerGameType.value = player.gameMode;
154
165
  newUncompressedData.value.XpTotal.value = player.xp;
155
166
  newUncompressedData.value.SelectedItemSlot.value = player.heldItemSlot;
156
- newUncompressedData.value.Dimension.value = player.dimension ?? 0;
167
+ newUncompressedData.value.Dimension = { type: 'string', value: dimensionOf(player) };
157
168
  newUncompressedData.value.Pos.value.value = [player.position.x, player.position.y, player.position.z];
158
169
  newUncompressedData.value.Rotation.value.value = [player.yaw, player.pitch];
159
170
  newUncompressedData.value.OnGround.value = Number(player.onGround);
@@ -0,0 +1,10 @@
1
+ /**
2
+ * prismarine-chunk (1.18+ chunks) `setBiome` computes the biome cell with `toBiomePos(pos)` without the chunk's minY, so every biome lands in the first
3
+ * 4-block row of its section and the rest stays biome id 0 (the_void): wrong grass / foliage / water tints in the client. Replaces `setBiome` of the
4
+ * instance by a version that uses the same cell as `getBiome`.
5
+ */
6
+ export declare function fixSetBiome<T extends {
7
+ biomes?: any[];
8
+ minY?: number;
9
+ setBiome?: (pos: any, id: number) => void;
10
+ }>(chunk: T): T;