@zardoy/flying-squid 0.0.123 → 0.0.124

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 (40) 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/modules/dimensionCodec.d.ts +2 -0
  7. package/dist/lib/modules/dimensionCodec.js +121 -0
  8. package/dist/lib/modules/effects.js +3 -0
  9. package/dist/lib/modules/index.js +3 -1
  10. package/dist/lib/modules/playerLogin.js +3 -2
  11. package/dist/lib/modules/players.d.ts +6 -0
  12. package/dist/lib/modules/players.js +42 -16
  13. package/dist/lib/modules/players.test.d.ts +1 -0
  14. package/dist/lib/modules/players.test.js +30 -0
  15. package/dist/lib/modules/portal.d.ts +5 -0
  16. package/dist/lib/modules/portal.js +179 -0
  17. package/dist/lib/modules/recipes.d.ts +12 -0
  18. package/dist/lib/modules/recipes.js +266 -0
  19. package/dist/lib/modules/title.d.ts +4 -2
  20. package/dist/lib/modules/title.js +33 -16
  21. package/dist/lib/modules/title.test.d.ts +1 -0
  22. package/dist/lib/modules/title.test.js +102 -0
  23. package/dist/lib/modules/world.d.ts +36 -3
  24. package/dist/lib/modules/world.js +259 -46
  25. package/dist/lib/modules/worldManager.d.ts +1 -0
  26. package/dist/lib/modules/worldManager.js +119 -0
  27. package/dist/lib/playerDat.d.ts +1 -8
  28. package/dist/lib/playerDat.js +13 -2
  29. package/dist/lib/worldGenerations/biomeFix.d.ts +10 -0
  30. package/dist/lib/worldGenerations/biomeFix.js +19 -0
  31. package/dist/lib/worldGenerations/empty.js +4 -1
  32. package/dist/lib/worldGenerations/noise.d.ts +22 -0
  33. package/dist/lib/worldGenerations/noise.js +248 -0
  34. package/dist/minigames/oneblock.d.ts +1 -0
  35. package/dist/minigames/oneblock.js +41 -0
  36. package/dist/minigames/tntRun.d.ts +1 -0
  37. package/dist/minigames/tntRun.js +14 -0
  38. package/dist/modules.d.ts +2 -2
  39. package/dist/types.d.ts +2 -0
  40. package/package.json +2 -2
@@ -44,23 +44,28 @@ const fs_1 = __importDefault(require("fs"));
44
44
  const prismarine_provider_anvil_1 = require("prismarine-provider-anvil");
45
45
  const playerDat = __importStar(require("../playerDat"));
46
46
  const prismarine_world_1 = __importDefault(require("prismarine-world"));
47
+ const prismarine_chunk_1 = __importDefault(require("prismarine-chunk"));
47
48
  const prismarine_registry_1 = __importDefault(require("prismarine-registry"));
48
49
  const generations_1 = __importDefault(require("../generations"));
50
+ const dimensionCodec_1 = require("./dimensionCodec");
51
+ const biomeFix_1 = require("../worldGenerations/biomeFix");
49
52
  const template_1 = require("../worldGenerations/template");
50
53
  const vec3_1 = require("vec3");
54
+ const user_error_1 = __importDefault(require("../user_error"));
51
55
  const utils_1 = require("../../utils");
52
56
  const levelDat_1 = require("../../levelDat");
53
57
  const blockRenames_1 = require("../../blockRenames");
58
+ const random_1 = require("minecraft-worldgen/dist/rng/random");
54
59
  const fsStat = (0, util_1.promisify)(fs_1.default.stat);
55
60
  const fsMkdir = (0, util_1.promisify)(fs_1.default.mkdir);
56
61
  const server = async function (serv, options) {
57
62
  const { version, worldSaveVersion: _worldSaveVersion, worldFolder, noWorldRegion, generation: _generation } = options;
58
- let generation = _generation ?? { name: 'diamond_square', options: {} };
63
+ let generation = _generation ?? { name: 'noise', options: {} };
59
64
  if (generation.name === 'flat') {
60
65
  generation.name = 'superflat';
61
66
  }
62
- if (generation.name === 'default') {
63
- generation.name = 'diamond_square';
67
+ if (generation.name === 'default' || generation.name === 'diamond_square') {
68
+ generation.name = 'noise';
64
69
  }
65
70
  // Detect world type from level.dat
66
71
  if (worldFolder && !noWorldRegion) {
@@ -81,12 +86,15 @@ const server = async function (serv, options) {
81
86
  if (levelData.generatorName === 'flat') {
82
87
  generation.name = 'superflat';
83
88
  }
89
+ else if (levelData.generatorName === 'default' || levelData.generatorName === 'diamond_square') {
90
+ generation.name = 'noise';
91
+ }
84
92
  else if (generations_1.default[levelData.generatorName]) {
85
93
  generation.name = levelData.generatorName;
86
94
  }
87
95
  else {
88
96
  console.warn(`Unsupported world chunks generator type: ${levelData.generatorName}`);
89
- generation.name = 'diamond_square';
97
+ generation.name = 'noise';
90
98
  }
91
99
  }
92
100
  }
@@ -102,7 +110,16 @@ const server = async function (serv, options) {
102
110
  const registry = (0, prismarine_registry_1.default)(version);
103
111
  const worldSaveVersion = _worldSaveVersion ?? version;
104
112
  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)));
113
+ const newSeed = (0, random_1.parseWorldSeed)(serv.seed ?? generation.options.seed);
114
+ const worldsFile = worldFolder && !noWorldRegion ? `${worldFolder}/flyingsquid-worlds.json` : undefined;
115
+ // 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
116
+ // `setTimeout(() => serv.writeLevelDat())` below and the end of this module (it would run before the seed exists)
117
+ const savedSpecs = await (async () => { try {
118
+ return worldsFile ? JSON.parse(await fs_1.default.promises.readFile(worldsFile, 'utf8')) : [];
119
+ }
120
+ catch {
121
+ return [];
122
+ } })();
106
123
  let seed;
107
124
  let regionFolder;
108
125
  if (worldFolder && !noWorldRegion) {
@@ -119,7 +136,7 @@ const server = async function (serv, options) {
119
136
  if ([SpawnY, SpawnX, SpawnZ].every(x => x !== undefined)) {
120
137
  serv.spawnPoint ??= new vec3_1.Vec3(SpawnX, SpawnY, SpawnZ);
121
138
  }
122
- seed = serv.levelData?.RandomSeed?.[0] ?? newSeed;
139
+ seed = (0, random_1.seedFromLevelDat)(serv.levelData?.RandomSeed) ?? newSeed;
123
140
  if (serv.levelData?.Version?.Name !== worldSaveVersion) {
124
141
  console.warn(`World save version mismatch: you select: ${worldSaveVersion} actual stored: ${serv.levelData?.Version?.Name}`);
125
142
  }
@@ -151,6 +168,38 @@ const server = async function (serv, options) {
151
168
  world['min_y'] = generation.options.minY;
152
169
  world['height'] = generation.options.worldHeight;
153
170
  };
171
+ /**
172
+ * `World#getColumn` (prismarine-world) does `await Promise.resolve()` and only then checks
173
+ * `this.columns[key]` before deciding to invoke the chunk generator. If two callers ask for the
174
+ * same chunk before either has reached that point — e.g. our own world-gen code writing custom
175
+ * blocks into a spawn-adjacent chunk racing the player's own chunk-loading requesting the same
176
+ * chunk — BOTH calls see no cached column and BOTH invoke the generator. Whichever `setColumn`
177
+ * resolves last silently replaces `this.columns[key]`, discarding any edits already made to the
178
+ * other (now-orphaned) chunk instance. This wraps `getColumn` so concurrent requests for the same
179
+ * (chunkX, chunkZ) share a single in-flight generation instead of racing.
180
+ */
181
+ const dedupeGetColumn = (world) => {
182
+ // prismarine-world stores whatever the chunk generator returned: an async generator (noise) would leave a Promise in `columns`, which then reaches the Anvil
183
+ // storage (toNBT(Promise): "Cannot convert undefined or null to object") and nothing is ever saved. Store the resolved chunk.
184
+ const originalSetColumn = world.setColumn.bind(world);
185
+ world.setColumn = async (chunkX, chunkZ, chunk, save) => originalSetColumn(chunkX, chunkZ, await chunk, save);
186
+ const pending = new Map();
187
+ const original = world.getColumn.bind(world);
188
+ world.getColumn = (chunkX, chunkZ) => {
189
+ const loaded = world.getLoadedColumn(chunkX, chunkZ);
190
+ if (loaded)
191
+ return Promise.resolve(loaded);
192
+ const key = `${chunkX},${chunkZ}`;
193
+ const existing = pending.get(key);
194
+ if (existing)
195
+ return existing;
196
+ const promise = Promise.resolve(original(chunkX, chunkZ)).finally(() => {
197
+ pending.delete(key);
198
+ });
199
+ pending.set(key, promise);
200
+ return promise;
201
+ };
202
+ };
154
203
  const generationModule = generations_1.default[generation.name] ? generations_1.default[generation.name] : require(generation.name);
155
204
  const genOpts = generation.options;
156
205
  const templateStr = typeof options.chunkTemplate === 'string' ? options.chunkTemplate
@@ -170,27 +219,169 @@ const server = async function (serv, options) {
170
219
  serv.overworld.seed = serv.seed = generationOptions.seed;
171
220
  serv.overworld.generatorName = generation.name;
172
221
  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
222
+ dedupeGetColumn(serv.overworld);
223
+ // ---- world registry (Multiverse-style): any number of worlds; each has an environment (= client dimension type) and a generator
224
+ const ENV_DIMENSION = { normal: 0, nether: -1, end: 1 };
225
+ const ENV_NOISE_DIM = { normal: 'overworld', nether: 'nether', end: 'end' };
226
+ const baseGeneratorName = generation.name;
227
+ const ChunkClass = (0, prismarine_chunk_1.default)(version);
228
+ /** 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). */
229
+ const regionDirOf = (name, environment) => !worldFolder || noWorldRegion ? undefined
230
+ : name === 'nether' && environment === 'nether' ? `${worldFolder}/DIM-1/region`
231
+ : name === 'end' && environment === 'end' ? `${worldFolder}/DIM1/region`
232
+ : `${worldFolder}/dimensions/flyingsquid/${name}/region`;
233
+ /** deletes the saved chunks of an extra world (used when a world is regenerated from another recipe) */
234
+ serv.deleteWorldData = (name) => {
235
+ const dir = regionDirOf(name, 'normal');
236
+ if (dir)
237
+ try {
238
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
239
+ }
240
+ catch (e) {
241
+ serv.warn(`Could not delete saved chunks of '${name}': ${e.message}`);
242
+ }
243
+ };
244
+ const storageFor = (name, environment, minY, height) => {
245
+ if (!worldFolder || noWorldRegion || !Anvil)
246
+ return null;
247
+ const dir = regionDirOf(name, environment);
248
+ // browser file systems (IndexedDB) only have the async fs calls: the directory is created before the first load / save instead of synchronously here
249
+ const ready = fsMkdir(dir, { recursive: true }).then(() => true, async () => {
250
+ const exists = await fsStat(dir).then(() => true, () => false);
251
+ if (!exists)
252
+ serv.warn?.(`No storage for world '${name}' (cannot create ${dir}); it will not be saved`);
253
+ return exists;
254
+ });
255
+ const anvil = new Anvil(dir);
256
+ const sameSize = minY === generation.options.minY && height === generation.options.worldHeight;
257
+ return {
258
+ save: async (x, z, chunk) => { if (await ready)
259
+ await anvil.save(x, z, chunk); },
260
+ load: async (x, z) => {
261
+ if (!await ready)
262
+ return null;
263
+ const c = await anvil.load(x, z);
264
+ if (!c || sameSize || (c.minY === minY && c.worldHeight === height))
265
+ return c;
266
+ const out = (0, biomeFix_1.fixSetBiome)(new ChunkClass({ minY, worldHeight: height }));
267
+ const pos = new vec3_1.Vec3(0, 0, 0);
268
+ for (let y = Math.max(minY, c.minY); y < Math.min(minY + height, c.minY + c.worldHeight); y++) {
269
+ pos.y = y;
270
+ for (let zz = 0; zz < 16; zz++) {
271
+ pos.z = zz;
272
+ for (let xx = 0; xx < 16; xx++) {
273
+ pos.x = xx;
274
+ const id = c.getBlockStateId(pos);
275
+ if (id !== 0)
276
+ out.setBlockStateId(pos, id);
277
+ out.setSkyLight(pos, 15);
278
+ out.setBlockLight(pos, 15);
279
+ if ((y & 3) === 0 && (xx & 3) === 0 && (zz & 3) === 0)
280
+ out.setBiome(pos, c.getBiome(pos));
281
+ }
282
+ }
283
+ }
284
+ return out;
285
+ }
286
+ };
287
+ };
288
+ let loadingSaved = true;
289
+ const saveWorldSpecs = () => {
290
+ if (loadingSaved)
291
+ return;
292
+ if (!worldsFile)
293
+ return;
294
+ const extra = Object.values(serv.worldSpecs).filter(sp => !['overworld', 'nether', 'end'].includes(sp.name));
295
+ 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));
296
+ };
297
+ const createWorld = (spec) => {
298
+ if (serv.worlds[spec.name])
299
+ throw new user_error_1.default(`World '${spec.name}' already exists`);
300
+ const environment = spec.environment ?? 'normal';
301
+ if (!(environment in ENV_DIMENSION))
302
+ throw new user_error_1.default(`Unknown environment '${environment}' (normal | nether | end)`);
303
+ // default generator: the server's generator for the overworld; the noise generator also builds nether / end, others fall back to the simple ones
304
+ const genName = spec.generator ?? (environment === 'normal' || baseGeneratorName === 'noise' ? baseGeneratorName : environment === 'nether' ? 'nether' : 'empty');
305
+ const module = generations_1.default[genName] ?? require(genName);
306
+ const worldSeed = spec.seed === undefined ? generationOptions.seed : (0, random_1.parseWorldSeed)(spec.seed);
307
+ const tall = environment === 'normal';
308
+ const opts = {
309
+ ...generationOptions,
310
+ ...spec.options,
311
+ seed: worldSeed,
312
+ dimension: ENV_NOISE_DIM[environment],
313
+ preset: spec.preset,
314
+ recipe: spec.recipe,
315
+ minY: tall ? generation.options.minY : 0,
316
+ worldHeight: tall ? generation.options.worldHeight : 256
317
+ };
318
+ const generator = module(opts);
319
+ const world = new World(generator, storageFor(spec.name, environment, opts.minY, opts.worldHeight), options.savingInterval);
320
+ world['min_y'] = opts.minY;
321
+ world.disposeGenerator = generator?.dispose;
322
+ world['height'] = opts.worldHeight;
323
+ dedupeGetColumn(world);
324
+ world.seed = worldSeed;
325
+ world.generatorName = genName;
326
+ world.environment = environment;
327
+ world.dimensionId = ENV_DIMENSION[environment];
328
+ world.worldName = spec.name;
329
+ world.blockEntityData = {};
330
+ world.portals = [];
331
+ serv.worlds[spec.name] = world;
332
+ serv.worldSpecs[spec.name] = { ...spec, environment, generator: genName };
333
+ saveWorldSpecs();
334
+ serv.emit('worldCreated', world);
335
+ return world;
336
+ };
337
+ serv.worldSpecs = {};
338
+ serv.worlds = { overworld: serv.overworld };
339
+ serv.overworld.environment = 'normal';
340
+ serv.overworld.dimensionId = 0;
341
+ serv.overworld.worldName = 'overworld';
342
+ serv.worldSpecs.overworld = { name: 'overworld', environment: 'normal', generator: generation.name, seed: generationOptions.seed };
343
+ serv.createWorld = createWorld;
344
+ serv.netherworld = createWorld({ name: 'nether', environment: 'nether' });
345
+ serv.endworld = createWorld({ name: 'end', environment: 'end' });
346
+ // worlds created at runtime (/mv create) in an earlier session, then the ones declared in the options
347
+ for (const spec of [...savedSpecs, ...(options.worlds ?? [])]) {
348
+ if (serv.worlds[spec.name])
349
+ continue;
350
+ try {
351
+ createWorld(spec);
352
+ }
353
+ catch (e) {
354
+ serv.warn(`Could not create world '${spec.name}': ${e.message}`);
355
+ }
356
+ }
357
+ loadingSaved = false;
358
+ saveWorldSpecs();
359
+ serv.removeWorld = async (name) => {
360
+ const world = serv.worlds[name];
361
+ if (!world)
362
+ throw new user_error_1.default(`World '${name}' does not exist`);
363
+ if (world === serv.overworld || world === serv.netherworld || world === serv.endworld)
364
+ throw new user_error_1.default(`World '${name}' is a core world and cannot be removed`);
365
+ for (const player of serv.players.filter(p => p.world === world)) {
366
+ await player.changeWorld(serv.overworld, { dimension: 0 });
367
+ }
368
+ world.stopSaving();
369
+ try {
370
+ await world.disposeGenerator?.();
371
+ }
372
+ catch { }
373
+ delete serv.worlds[name];
374
+ delete serv.worldSpecs[name];
375
+ saveWorldSpecs();
376
+ serv.emit('worldRemoved', name);
182
377
  };
183
378
  serv.dimensionNames = {
184
- '-1': 'minecraft:nether',
185
- 0: 'minecraft:overworld'
186
- // 1: 'minecraft:end'
379
+ '-1': 'minecraft:the_nether',
380
+ 0: 'minecraft:overworld',
381
+ 1: 'minecraft:the_end'
187
382
  };
188
- // WILL BE REMOVED WHEN ACTUALLY IMPLEMENTED
189
383
  serv.overworld.blockEntityData = {};
190
- serv.netherworld.blockEntityData = {};
191
384
  serv.overworld.portals = [];
192
- serv.netherworld.portals = [];
193
- /// ///////////
194
385
  serv.pregenWorld = (world, size = 3) => {
195
386
  const promises = [];
196
387
  for (let x = -size; x < size; x++) {
@@ -256,14 +447,14 @@ const server = async function (serv, options) {
256
447
  serv.commands.add({
257
448
  base: 'changeworld',
258
449
  info: 'to change world',
259
- usage: '/changeworld overworld|nether',
450
+ usage: '/changeworld <world> (overworld | nether | end | any world created with /mv create)',
260
451
  onlyPlayer: true,
261
452
  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 });
453
+ action(name, ctx) {
454
+ const world = serv.worlds[String(name).trim()];
455
+ if (!world)
456
+ throw new user_error_1.default(`Unknown world '${name}'. Worlds: ${Object.keys(serv.worlds).join(', ')}`);
457
+ return ctx.player.changeWorld(world, { dimension: world.dimensionId });
267
458
  }
268
459
  });
269
460
  serv.commands.add({
@@ -355,6 +546,11 @@ const server = async function (serv, options) {
355
546
  if (!worldFolder) {
356
547
  serv.writeLevelDat();
357
548
  }
549
+ else if (!noWorldRegion && !serv.levelData) {
550
+ // 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
551
+ // and was listed as broken (and not loadable) by the web client.
552
+ setTimeout(() => { serv.writeLevelDat().catch((e) => serv.warn(`Could not write level.dat: ${e.message}`)); });
553
+ }
358
554
  console.log('worlds init done');
359
555
  // Periodic autosave: world and all players
360
556
  const autosaveMs = options.savingInterval === false ? 0 : (typeof options.savingInterval === 'number' ? options.savingInterval : 60_000);
@@ -400,14 +596,14 @@ const levelDatWriter = (serv, options) => {
400
596
  const original = serv.worlds[world].generatorName;
401
597
  if (original === 'superflat')
402
598
  return 'flat';
403
- if (original === 'diamond_square')
599
+ if (original === 'noise')
404
600
  return 'default';
405
601
  if (original === 'customized')
406
602
  return 'customized';
407
603
  return original;
408
604
  };
409
605
  const newLevelDat = {
410
- RandomSeed: serv.levelData?.RandomSeed ?? [serv.seed, 0],
606
+ RandomSeed: (0, levelDat_1.numberToLongArray)(serv.seed),
411
607
  Version: serv.levelData?.Version ?? { Name: options.version },
412
608
  generatorName: serv.levelData?.generatorName ?? getGeneratorName('overworld'),
413
609
  // WorldGenSettings: {
@@ -493,11 +689,11 @@ const player = function (player, serv, settings) {
493
689
  }, // FIXME: fake heightmap
494
690
  chunkData: chunkBuffer,
495
691
  blockEntities: [],
496
- skyLightMask: chunk.skyLightMask,
497
- // skyLightMask: [chunk.skyLightMask.data],
498
- emptySkyLightMask: chunk.emptySkyLightMask,
499
- blockLightMask: chunk.blockLightMask,
500
- emptyBlockLightMask: chunk.emptyBlockLightMask,
692
+ // 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)
693
+ skyLightMask: dumpedLights.skyLightMask ?? chunk.skyLightMask,
694
+ emptySkyLightMask: dumpedLights.emptySkyLightMask ?? chunk.emptySkyLightMask,
695
+ blockLightMask: dumpedLights.blockLightMask ?? chunk.blockLightMask,
696
+ emptyBlockLightMask: dumpedLights.emptyBlockLightMask ?? chunk.emptyBlockLightMask,
501
697
  ...newLightsData
502
698
  });
503
699
  if (serv.supportFeature('lightSentSeparately') && !serv.supportFeature('newLightingDataFormat')) {
@@ -505,10 +701,10 @@ const player = function (player, serv, settings) {
505
701
  chunkX: x,
506
702
  chunkZ: z,
507
703
  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,
704
+ skyLightMask: dumpedLights.skyLightMask ?? chunk.skyLightMask,
705
+ blockLightMask: dumpedLights.blockLightMask ?? chunk.blockLightMask,
706
+ emptySkyLightMask: dumpedLights.emptySkyLightMask ?? chunk.emptySkyLightMask,
707
+ emptyBlockLightMask: dumpedLights.emptyBlockLightMask ?? chunk.emptyBlockLightMask,
512
708
  ...newLightsData ? newLightsData : {
513
709
  data: dumpedLights
514
710
  }
@@ -551,6 +747,7 @@ const player = function (player, serv, settings) {
551
747
  return Promise.resolve();
552
748
  });
553
749
  };
750
+ const CHUNK_PREFETCH = 8;
554
751
  player.sendNearbyChunks = (viewDistance, group = false, abortSignal) => {
555
752
  player.lastPositionChunkUpdated = player.position;
556
753
  const playerChunkX = Math.floor(player.position.x / 16);
@@ -559,19 +756,34 @@ const player = function (player, serv, settings) {
559
756
  .map((key) => key.split(',').map(a => parseInt(a)))
560
757
  .filter(([x, z]) => Math.abs(x - playerChunkX) > viewDistance || Math.abs(z - playerChunkZ) > viewDistance)
561
758
  .forEach(([x, z]) => player._unloadChunk(x, z));
562
- return (0, utils_1.generateSpiralMatrix)(viewDistance)
759
+ const todo = (0, utils_1.generateSpiralMatrix)(viewDistance)
563
760
  .map(t => ({
564
761
  chunkX: playerChunkX + t[0],
565
762
  chunkZ: playerChunkZ + t[1]
566
763
  }))
567
- .filter(({ chunkX, chunkZ }) => !player.loadedChunks[`${chunkX},${chunkZ}`])
568
- .reduce((acc, { chunkX, chunkZ }) => {
764
+ .filter(({ chunkX, chunkZ }) => !player.loadedChunks[`${chunkX},${chunkZ}`]);
765
+ // 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
766
+ const ahead = new Map();
767
+ const request = (i) => {
768
+ let p = ahead.get(i);
769
+ if (!p && i < todo.length) {
770
+ p = Promise.resolve(player.world.getColumn(todo[i].chunkX, todo[i].chunkZ));
771
+ p.catch(() => { }); // reported when its turn comes
772
+ ahead.set(i, p);
773
+ }
774
+ return p;
775
+ };
776
+ return todo.reduce((acc, { chunkX, chunkZ }, i) => {
569
777
  const p = acc
570
778
  .then(() => {
571
779
  if (abortSignal?.aborted)
572
780
  return;
573
781
  serv.abortSignal.throwIfAborted();
574
- return player.world.getColumn(chunkX, chunkZ);
782
+ for (let k = 1; k <= CHUNK_PREFETCH; k++)
783
+ request(i + k);
784
+ const col = request(i);
785
+ ahead.delete(i);
786
+ return col;
575
787
  })
576
788
  .then((column) => {
577
789
  if (!column || abortSignal?.aborted)
@@ -620,8 +832,9 @@ const player = function (player, serv, settings) {
620
832
  }
621
833
  player._client.write('respawn', {
622
834
  previousGameMode: player.prevGameMode,
623
- dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[opt.dimension || 0] : opt.dimension || 0,
624
- worldName: serv.dimensionNames[opt.dimension || 0],
835
+ dimension: serv.supportFeature('dimensionIsAString') ? serv.dimensionNames[opt.dimension || 0] : serv.supportFeature('dimensionIsAnInt') ? opt.dimension || 0 : (0, dimensionCodec_1.dimensionNbt)(opt.dimension || 0),
836
+ // custom worlds get their own level identifier so the client rebuilds its level even when the dimension type is the same
837
+ worldName: ['overworld', 'nether', 'end'].includes(world.worldName) || !world.worldName ? serv.dimensionNames[opt.dimension || 0] : `flyingsquid:${world.worldName.toLowerCase()}`,
625
838
  difficulty: opt.difficulty || serv.difficulty,
626
839
  hashedSeed: serv.hashedSeed,
627
840
  gamemode: opt.gamemode || player.gameMode,
@@ -631,7 +844,7 @@ const player = function (player, serv, settings) {
631
844
  copyMetadata: true
632
845
  });
633
846
  await player.findSpawnPoint();
634
- player.position = player.spawnPoint;
847
+ player.position = opt.position ?? player.spawnPoint;
635
848
  player.sendSpawnPosition();
636
849
  player.updateAndSpawn();
637
850
  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;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fixSetBiome = fixSetBiome;
4
+ /**
5
+ * 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
6
+ * 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
7
+ * instance by a version that uses the same cell as `getBiome`.
8
+ */
9
+ function fixSetBiome(chunk) {
10
+ if (!Array.isArray(chunk.biomes) || typeof chunk.setBiome !== 'function')
11
+ return chunk;
12
+ chunk.setBiome = function (pos, id) {
13
+ const minY = this.minY ?? 0;
14
+ const section = this.biomes[(pos.y - minY) >> 4];
15
+ if (section)
16
+ section.set({ x: pos.x >> 2, y: ((pos.y - minY) & 0xF) >> 2, z: pos.z >> 2 }, id);
17
+ };
18
+ return chunk;
19
+ }