@zardoy/flying-squid 0.0.92 → 0.0.93

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.
@@ -6,24 +6,26 @@
6
6
  "logging": true,
7
7
  "gameMode": 1,
8
8
  "difficulty": 1,
9
- "worldFolder":"world",
9
+ "worldFolder": "world",
10
10
  "generation": {
11
11
  "name": "diamond_square",
12
- "options":{
12
+ "options": {
13
13
  "worldHeight": 80
14
14
  }
15
15
  },
16
16
  "kickTimeout": 10000,
17
- "plugins": {
18
-
19
- },
17
+ "plugins": {},
20
18
  "modpe": false,
21
19
  "view-distance": 10,
22
20
  "player-list-text": {
23
- "header":{"text": "Flying squid"},
24
- "footer":{"text": "Test server"}
21
+ "header": {
22
+ "text": "Flying squid"
23
+ },
24
+ "footer": {
25
+ "text": "Test server"
26
+ }
25
27
  },
26
28
  "everybody-op": false,
27
- "max-entities":100,
28
- "version": "1.16.1"
29
+ "max-entities": 100,
30
+ "version": "1.18.2"
29
31
  }
@@ -14,6 +14,9 @@ export type BehaviorEventMap<M extends BehaviorInputMap, MK extends keyof M = ke
14
14
  [K in MK | `${MK & string}_cancel` | `${MK & string}_done`]: K extends `${MK & string}_cancel` ? (data: M[MK]['_input'], cancel: CancelFunction) => MaybePromise<void> : K extends `${MK & string}_done` ? (data: M[MK]['_input'], resp: any, cancelled: boolean) => MaybePromise<void> : (data: M[MK]['_input'], cancelled: boolean, cancelCount: number) => MaybePromise<void>;
15
15
  };
16
16
  export type BehaviorCallFunction<M extends BehaviorInputMap> = <E extends keyof M, D = M[E]['_input'], DF extends D = D, R = void>(eventName: E, data: D, func?: BehaviorFunction<DF, R>, cancelFunc?: BehaviorFunction<DF, R>) => Promise<BehaviorResult<R>>;
17
- type BehaviorResult<R> = R extends void ? void : R;
17
+ type BehaviorResult<R> = {
18
+ data: R extends void ? void : R;
19
+ cancelled: boolean;
20
+ };
18
21
  declare const _default: (obj: CustomEventEmitter) => <D = any, DF extends D = D, R = void>(eventName: string, data: D, func?: BehaviorFunction<DF>, cancelFunc?: BehaviorFunction<DF>) => Promise<BehaviorResult<R>>;
19
22
  export default _default;
@@ -84,7 +84,10 @@ exports.default = (obj) => {
84
84
  catch (err) {
85
85
  handleError(err, eventName + '_done', true);
86
86
  }
87
- return resp;
87
+ return {
88
+ data: resp,
89
+ cancelled
90
+ };
88
91
  };
89
92
  return behavior;
90
93
  };
@@ -2,12 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.player = void 0;
4
4
  const player = function (player) {
5
- player._client.on('arm_animation', () => player.behavior('armSwing', {}, () => {
6
- player._writeOthersNearby('animation', {
7
- entityId: player.id,
8
- animation: 0
5
+ player._client.on('arm_animation', () => {
6
+ player.behavior('armSwing', {}, () => {
7
+ player._writeOthersNearby('animation', {
8
+ entityId: player.id,
9
+ animation: 0
10
+ });
9
11
  });
10
- }));
12
+ });
11
13
  player._client.on('entity_action', ({ actionId }) => {
12
14
  if (actionId === 3) {
13
15
  player.setAndUpdateMetadata([{ key: 0, type: 0, value: 0x08 }]);
@@ -153,7 +153,9 @@ const server = (serv, { version }) => {
153
153
  const time = perf_hooks_1.performance.now() - start;
154
154
  const fraction = (time * 100 / 50).toFixed(2);
155
155
  const sentUpdates = chunkUpdates.updateCount();
156
- serv.info(`[Block Update] Made ${updatesCount} (${sentUpdates}) updates, ${updateQueue.length} remainings (${fraction}% of tickTime)`);
156
+ if (updatesCount > 150) {
157
+ serv.info(`[Block Update] Made ${updatesCount} (${sentUpdates}) updates, ${updateQueue.length} remainings (${fraction}% of tickTime)`);
158
+ }
157
159
  }
158
160
  }
159
161
  });
@@ -9,36 +9,65 @@ declare global {
9
9
  system?: boolean;
10
10
  }) => void;
11
11
  "chatColor": {
12
- black: string;
13
- dark_blue: string;
14
- dark_green: string;
15
- dark_cyan: string;
16
- dark_red: string;
17
- purple: string;
18
- dark_purple: string;
19
- gold: string;
20
- gray: string;
21
- dark_gray: string;
22
- blue: string;
23
- green: string;
24
- aqua: string;
25
- cyan: string;
26
- red: string;
27
- pink: string;
28
- light_purple: string;
29
- yellow: string;
30
- white: string;
31
- random: string;
32
- obfuscated: string;
33
- bold: string;
34
- strikethrough: string;
35
- underlined: string;
36
- underline: string;
37
- italic: string;
38
- italics: string;
39
- reset: string;
12
+ black: "&0";
13
+ dark_blue: "&1";
14
+ dark_green: "&2";
15
+ dark_cyan: "&3";
16
+ dark_red: "&4";
17
+ purple: "&5";
18
+ dark_purple: "&5";
19
+ gold: "&6";
20
+ gray: "&7";
21
+ dark_gray: "&8";
22
+ blue: "&9";
23
+ green: "&a";
24
+ aqua: "&b";
25
+ cyan: "&b";
26
+ red: "&c";
27
+ pink: "&d";
28
+ light_purple: "&d";
29
+ yellow: "&e";
30
+ white: "&f";
31
+ random: "&k";
32
+ obfuscated: "&k";
33
+ bold: "&l";
34
+ strikethrough: "&m";
35
+ underlined: "&n";
36
+ underline: "&n";
37
+ italic: "&o";
38
+ italics: "&o";
39
+ reset: "&r";
40
+ };
41
+ "color": {
42
+ black: "§0";
43
+ dark_blue: "§1";
44
+ dark_green: "§2";
45
+ dark_cyan: "§3";
46
+ dark_red: "§4";
47
+ purple: "§5";
48
+ dark_purple: "§5";
49
+ gold: "§6";
50
+ gray: "§7";
51
+ dark_gray: "§8";
52
+ blue: "§9";
53
+ green: "§a";
54
+ aqua: "§b";
55
+ cyan: "§b";
56
+ red: "§c";
57
+ pink: "§d";
58
+ light_purple: "§d";
59
+ yellow: "§e";
60
+ white: "§f";
61
+ random: "§k";
62
+ obfuscated: "§k";
63
+ bold: "§l";
64
+ strikethrough: "§m";
65
+ underlined: "§n";
66
+ underline: "§n";
67
+ italic: "§o";
68
+ italics: "§o";
69
+ reset: "§r";
40
70
  };
41
- "color": Server['chatColor'];
42
71
  }
43
72
  interface Player {
44
73
  /** sends `message` to the player */
@@ -1,13 +1,15 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.player = exports.server = void 0;
4
7
  const utils_1 = require("../../utils");
8
+ const prismarine_nbt_1 = __importDefault(require("prismarine-nbt"));
5
9
  const server = function (serv) {
6
10
  serv.broadcast = (message, { whitelist = serv.players, blacklist = [], system = false } = {}) => {
7
11
  if (whitelist.type === 'player')
8
12
  whitelist = [whitelist];
9
- if (typeof message === 'string')
10
- message = serv.parseClassic(message);
11
13
  whitelist.filter(w => blacklist.indexOf(w) === -1).forEach(player => {
12
14
  if (!system)
13
15
  player.chat(message);
@@ -75,7 +77,8 @@ const server = function (serv) {
75
77
  italics: '§o',
76
78
  reset: '§r'
77
79
  };
78
- serv.parseClassic = (message) => {
80
+ // TODO: update and use prismarine-chat (doesn't yet support NBT chat components beyond decoding them)
81
+ serv._createJsonChat = (message) => {
79
82
  if (typeof message === 'object')
80
83
  return message;
81
84
  const messageList = [];
@@ -160,6 +163,34 @@ const server = function (serv) {
160
163
  else
161
164
  return { text: '' };
162
165
  };
166
+ serv._createChatComponent = (text) => {
167
+ if (serv.supportFeature('chatPacketsUseNbtComponents')) {
168
+ if (typeof text !== 'string') {
169
+ if (text.text)
170
+ text = text.text;
171
+ else {
172
+ serv.debug?.('Cannot yet convert JSON chat messages to NBT ; re-call in plaintext: ' + JSON.stringify(text));
173
+ text = JSON.stringify(text);
174
+ }
175
+ }
176
+ const tag = prismarine_nbt_1.default.comp({
177
+ text: prismarine_nbt_1.default.string(text)
178
+ });
179
+ //@ts-ignore
180
+ tag.toNetworkFormat = () => tag;
181
+ return tag;
182
+ }
183
+ else {
184
+ if (typeof text === 'object') {
185
+ text.toNetworkFormat = () => JSON.stringify(text);
186
+ return text;
187
+ }
188
+ const ret = serv._createJsonChat(text);
189
+ ret.toNetworkFormat = () => JSON.stringify(ret);
190
+ return ret;
191
+ }
192
+ };
193
+ serv._createNetworkEncodedChatComponent = (val) => serv._createChatComponent(val).toNetworkFormat();
163
194
  };
164
195
  exports.server = server;
165
196
  const player = function (player, serv, settings) {
@@ -176,10 +207,10 @@ const player = function (player, serv, settings) {
176
207
  whitelist: serv.players,
177
208
  blacklist: []
178
209
  }, ({ prefix, text, whitelist, blacklist }) => {
179
- const obj = serv.parseClassic(prefix);
210
+ const obj = serv._createJsonChat(prefix);
180
211
  if (!obj.extra)
181
212
  obj.extra = [];
182
- obj.extra.push(serv.parseClassic(text));
213
+ obj.extra.push(serv._createJsonChat(text));
183
214
  serv.info(`<${player.getDisplayName('log')}> ${message}`);
184
215
  serv.broadcast(obj, {
185
216
  whitelist,
@@ -188,15 +219,33 @@ const player = function (player, serv, settings) {
188
219
  });
189
220
  }
190
221
  };
191
- player._client.on('chat', chatHandler);
192
- player._client.on('chat_message', chatHandler);
193
- player._client.on('chat_command', ({ command }) => {
194
- // serv.info(`${player.username} issued command: ${command}`)
195
- chatHandler({ message: `/${command}` });
222
+ // 1.19+ -- from nmp server example - not implementing chat singing yet, so all messages are sent as system_chat
223
+ function handleChatMessage(data) {
224
+ const fmtMessage = `<${player.username}> ${data.message}`;
225
+ serv.broadcast(fmtMessage, { whitelist: serv.players, blacklist: [] });
226
+ }
227
+ player._client.on('chat_message', (data) => {
228
+ player.behavior('chat', {
229
+ message: data.message,
230
+ prefix: '<' + player.username + '> ',
231
+ text: data.message,
232
+ whitelist: serv.players,
233
+ blacklist: [],
234
+ data
235
+ }, ({ data }) => {
236
+ handleChatMessage(data);
237
+ });
196
238
  });
239
+ player._client.on('chat_command', (data) => {
240
+ const command = data.command;
241
+ player.behavior('command', { command }, ({ command }) => {
242
+ player.handleCommand(command);
243
+ });
244
+ });
245
+ player._client.on('chat', chatHandler);
197
246
  const sendChat = (message, isSystem) => {
198
247
  if (typeof message === 'string')
199
- message = serv.parseClassic(message);
248
+ message = serv._createJsonChat(message);
200
249
  if ((0, utils_1.versionToNumber)(settings.version) >= (0, utils_1.versionToNumber)('1.19')) {
201
250
  player._client.write('systemChat', { formattedMessage: JSON.stringify(message), position: isSystem ? 2 : 0, sender: '0' });
202
251
  }
@@ -205,7 +254,17 @@ const player = function (player, serv, settings) {
205
254
  }
206
255
  };
207
256
  player.chat = message => {
208
- sendChat(message, false);
257
+ if (serv.supportFeature('signedChat')) {
258
+ return player.system(message);
259
+ }
260
+ else {
261
+ const chatComponent = typeof message === 'string' ? serv._createJsonChat(message) : message;
262
+ player._client.write('chat', {
263
+ message: JSON.stringify(chatComponent),
264
+ position: 0,
265
+ sender: '0'
266
+ });
267
+ }
209
268
  };
210
269
  player.emptyChat = (count = 1) => {
211
270
  for (let i = 0; i < count; i++) {
@@ -213,7 +272,22 @@ const player = function (player, serv, settings) {
213
272
  }
214
273
  };
215
274
  player.system = message => {
216
- sendChat(message, true);
275
+ const chatComponent = serv._createChatComponent(message);
276
+ if (serv.supportFeature('signedChat')) {
277
+ player._client.write('system_chat', {
278
+ // 1.20.3+ writes NBT in chat packets ; below is stringified JSON chat components
279
+ content: chatComponent.toNetworkFormat(),
280
+ type: 1, // chat
281
+ isActionBar: false
282
+ });
283
+ }
284
+ else {
285
+ player._client.write('chat', {
286
+ message: chatComponent.toNetworkFormat(),
287
+ position: 2,
288
+ sender: '0'
289
+ });
290
+ }
217
291
  };
218
292
  };
219
293
  exports.player = player;
@@ -54,7 +54,7 @@ const server = (serv, { version }) => {
54
54
  player._client.write('open_window', {
55
55
  windowId: player.windowId,
56
56
  inventoryType: invType,
57
- windowTitle: JSON.stringify(title)
57
+ windowTitle: serv._createChatComponent(title).toNetworkFormat()
58
58
  });
59
59
  // Sending container content
60
60
  player._client.write('window_items', {
@@ -35,7 +35,7 @@ const server = (serv, { version }) => {
35
35
  player._client.write('open_window', {
36
36
  windowId: player.windowId,
37
37
  inventoryType: window.type,
38
- windowTitle: JSON.stringify('Crafting')
38
+ windowTitle: serv._createChatComponent('Crafting').toNetworkFormat()
39
39
  });
40
40
  const sendItems = () => {
41
41
  // Sending container content
@@ -7,7 +7,7 @@ const player = function (player, serv, { version }) {
7
7
  function cancelDig({ position, block }) {
8
8
  player.sendBlock(position, block.type);
9
9
  }
10
- player._client.on('block_dig', ({ location, status, face }) => {
10
+ player._client.on('block_dig', ({ location, status, face, sequence }) => {
11
11
  if (status === 3 || status === 4) {
12
12
  const heldItem = player.inventory.slots[36 + player.heldItemSlot];
13
13
  if (!heldItem || heldItem.type === -1)
@@ -70,14 +70,14 @@ const player = function (player, serv, { version }) {
70
70
  creativeDigging(pos);
71
71
  }
72
72
  else {
73
- startDigging(pos);
73
+ startDigging(pos, sequence);
74
74
  }
75
75
  }
76
76
  else if (status === 1 || player.gameMode >= 2) {
77
- cancelDigging(pos);
77
+ cancelDigging(pos, sequence);
78
78
  }
79
79
  else if (status === 2) {
80
- completeDigging(pos, directionVector);
80
+ completeDigging(pos, directionVector, sequence);
81
81
  }
82
82
  }
83
83
  });
@@ -94,7 +94,7 @@ const player = function (player, serv, { version }) {
94
94
  let expectedDiggingTime;
95
95
  let lastDestroyState;
96
96
  let currentAnimationId;
97
- function startDigging(location) {
97
+ function startDigging(location, sequenceId) {
98
98
  serv.entityMaxId++;
99
99
  currentAnimationId = serv.entityMaxId;
100
100
  expectedDiggingTime = diggingTime();
@@ -125,6 +125,7 @@ const player = function (player, serv, { version }) {
125
125
  }
126
126
  if (serv.supportFeature('acknowledgePlayerDigging')) {
127
127
  player._client.write('acknowledge_player_digging', {
128
+ sequenceId, // 1.19
128
129
  location,
129
130
  block: currentlyDugBlock.stateId,
130
131
  status: 0,
@@ -132,7 +133,7 @@ const player = function (player, serv, { version }) {
132
133
  });
133
134
  }
134
135
  }
135
- function cancelDigging(location) {
136
+ function cancelDigging(location, sequenceId) {
136
137
  clearInterval(animationInterval);
137
138
  player._writeOthersNearby('block_break_animation', {
138
139
  entityId: currentAnimationId,
@@ -141,6 +142,7 @@ const player = function (player, serv, { version }) {
141
142
  });
142
143
  if (serv.supportFeature('acknowledgePlayerDigging')) {
143
144
  player._client.write('acknowledge_player_digging', {
145
+ sequenceId, // 1.19
144
146
  location,
145
147
  block: currentlyDugBlock.stateId,
146
148
  status: 1,
@@ -149,7 +151,7 @@ const player = function (player, serv, { version }) {
149
151
  }
150
152
  }
151
153
  const blockDropVelocity = new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2);
152
- async function completeDigging(location, directionVector) {
154
+ async function completeDigging(location, directionVector, sequenceId) {
153
155
  clearInterval(animationInterval);
154
156
  const diggingTime = Date.now() - startDiggingTime;
155
157
  let stop = false;
@@ -218,6 +220,7 @@ const player = function (player, serv, { version }) {
218
220
  }
219
221
  if (serv.supportFeature('acknowledgePlayerDigging')) {
220
222
  player._client.write('acknowledge_player_digging', {
223
+ sequenceId, // 1.19
221
224
  location,
222
225
  block: 0,
223
226
  status: 2,
@@ -233,6 +236,7 @@ const player = function (player, serv, { version }) {
233
236
  });
234
237
  if (serv.supportFeature('acknowledgePlayerDigging')) {
235
238
  player.writePacket('acknowledge_player_digging', {
239
+ sequenceId, // 1.19
236
240
  location,
237
241
  block: currentlyDugBlock.stateId,
238
242
  status: 2,
@@ -7,7 +7,7 @@ declare global {
7
7
  duration: number;
8
8
  particles: boolean;
9
9
  end: number;
10
- timeout: NodeJS.Timeout;
10
+ timeout?: NodeJS.Timeout;
11
11
  } | null>;
12
12
  "addEffect": (effectId: number, opt?: {
13
13
  amplifier?: number;
@@ -44,20 +44,22 @@ const entity = function (entity, serv) {
44
44
  duration: opt.duration || 30 * 20,
45
45
  particles: opt.particles || true,
46
46
  end: Date.now() + (opt.duration || 30 * 20) * 1000 / 20, // 1000/20 === convert from ticks to milliseconds,
47
- timeout: setTimeout(() => entity.removeEffect(effectId, {}), (opt.duration || 30 * 20) * 1000 / 20)
47
+ timeout: opt.duration === -1 ? undefined : setTimeout(() => entity.removeEffect(effectId, {}), (opt.duration || 30 * 20) * 1000 / 20)
48
48
  };
49
- entity.sendEffect(effectId, opt);
49
+ entity.sendEffect(effectId, { ...opt, whitelist: [entity] });
50
50
  return true;
51
51
  }
52
52
  else
53
53
  return false;
54
54
  };
55
55
  entity.removeEffect = (effectId, opt) => {
56
- if (!entity.effects[effectId])
56
+ const effect = entity.effects[effectId];
57
+ if (!effect)
57
58
  return;
58
- clearTimeout(entity.effects[effectId].timeout);
59
+ if (effect.timeout)
60
+ clearTimeout(effect.timeout);
59
61
  entity.effects[effectId] = null;
60
- entity.sendRemoveEffect(effectId, opt);
62
+ entity.sendRemoveEffect(effectId, { ...opt, whitelist: [entity] });
61
63
  };
62
64
  };
63
65
  exports.entity = entity;
@@ -2,12 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.player = void 0;
4
4
  const player = function (player, serv, settings) {
5
- player.playerlistUpdateText = (header, footer) => player._client.write('playerlist_header', {
6
- header: JSON.stringify(header),
7
- footer: JSON.stringify(footer)
8
- });
5
+ player.playerlistUpdateText = function (header, footer) {
6
+ player._client.write('playerlist_header', {
7
+ header: serv._createChatComponent(header).toNetworkFormat(),
8
+ footer: serv._createChatComponent(footer).toNetworkFormat()
9
+ });
10
+ };
9
11
  if (settings['player-list-text']) {
10
- player.playerlistUpdateText(settings['player-list-text'].header || { text: '' }, settings['player-list-text'].footer || { text: '' });
12
+ const header = settings['player-list-text'].header || '';
13
+ const footer = settings['player-list-text'].footer || '';
14
+ player.playerlistUpdateText(header, footer);
11
15
  }
12
16
  };
13
17
  exports.player = player;
@@ -2,9 +2,24 @@ import { Item } from 'prismarine-item';
2
2
  import { Window } from 'prismarine-windows';
3
3
  export declare const player: (player: Player, serv: Server, { version }: Options) => void;
4
4
  declare global {
5
+ interface Entity {
6
+ setEquipment: (slot: number, item: any) => void;
7
+ }
5
8
  interface Player {
6
- "heldItem": Item;
7
- "inventory": Window;
8
- "customWindow": Window | undefined;
9
+ heldItemSlot: number;
10
+ heldItem: Item;
11
+ inventory: Window;
12
+ customWindow: Window | undefined;
13
+ "collect": (collectEntity: Entity & {
14
+ itemId: number;
15
+ damage: number;
16
+ }) => void;
17
+ }
18
+ interface PlayerBehaviorInputMap {
19
+ 'changeHeldItemSlot': {
20
+ _input: {
21
+ slot: number;
22
+ };
23
+ };
9
24
  }
10
25
  }
@@ -13,7 +13,12 @@ const player = function (player, serv, { version }) {
13
13
  player.heldItemSlot = 0;
14
14
  // player.heldItem = new Item(256, 1)
15
15
  player.inventory = windows.createWindow(1, 'minecraft:inventory', 'inv', 36);
16
- player._client.on('held_item_slot', ({ slotId } = {}) => {
16
+ player._client.on('held_item_slot', async ({ slotId } = {}) => {
17
+ const { cancelled } = await player.behavior('changeHeldItemSlot', { slot: slotId, item: player.inventory.slots[36 + slotId] });
18
+ if (cancelled) {
19
+ player.writePacket('held_item_slot', { slotId: player.heldItemSlot });
20
+ return;
21
+ }
17
22
  player.heldItemSlot = slotId;
18
23
  player.setEquipment(0, player.inventory.slots[36 + player.heldItemSlot]);
19
24
  if (serv.supportFeature('allEntityEquipmentInOne')) {
@@ -22,7 +22,7 @@ const player = function (player, serv, { worldFolder }) {
22
22
  entityIds: entities.map(e => e.id)
23
23
  });
24
24
  player._client.on('end', async (endReason) => {
25
- if (player) {
25
+ if (!player.disconnected) {
26
26
  player._unloadAllChunks?.();
27
27
  if (player.username) {
28
28
  serv.broadcast(serv.chatColor.yellow + player.username + ' left the game.');
@@ -43,6 +43,7 @@ const player = function (player, serv, { worldFolder }) {
43
43
  serv.players.splice(index, 1);
44
44
  }
45
45
  delete serv.uuidToPlayer[player.uuid];
46
+ player.disconnected = true;
46
47
  }
47
48
  player.save?.();
48
49
  });
@@ -22,7 +22,13 @@ const server = function (serv) {
22
22
  offsetZ: size.z,
23
23
  particleData: 1.0,
24
24
  particles: count,
25
- data: []
25
+ amount: count, // 1.20.5+
26
+ data: [],
27
+ velocityOffset: 0, // 1.20.5+
28
+ particle: {
29
+ type: 'bubble',
30
+ data: null
31
+ }
26
32
  }, players.filter(p => blacklist.indexOf(p) === -1));
27
33
  };
28
34
  serv.commands.add({
@@ -66,6 +66,12 @@ const server = function (serv, options) {
66
66
  client.on('error', error => {
67
67
  serv.emit('clientError', client, error);
68
68
  });
69
+ client.on('state', (now) => {
70
+ if (now === 'configuration') {
71
+ client.write('feature_flags', { features: ['minecraft:vanilla'] });
72
+ client.write('select_known_packs', { packs: [] });
73
+ }
74
+ });
69
75
  });
70
76
  const patchClient = (client, player) => {
71
77
  client.oldAddListener ??= client.on.bind(client);
@@ -201,7 +207,10 @@ const player = async function (player, serv, settings) {
201
207
  // Set world based on saved dimension data, fallback to overworld
202
208
  const savedDimension = (playerData?.player?.Dimension?.value ?? 'overworld').replace('minecraft:', '');
203
209
  player.world = (savedDimension === 'the_nether' || savedDimension === 'nether') ? serv.netherworld : (serv.worlds[savedDimension] ?? serv.overworld);
204
- serv.players.push(player);
210
+ if (!player.disconnected) {
211
+ // it's possible player gets kicked during login process ; don't add them to the server
212
+ serv.players.push(player);
213
+ }
205
214
  serv.uuidToPlayer[player.uuid] = player;
206
215
  player.loadedChunks = {};
207
216
  player.setLoadingStatus(null);
@@ -274,7 +283,8 @@ const player = async function (player, serv, settings) {
274
283
  maxPlayers: Math.min(255, serv._server.maxPlayers),
275
284
  enableRespawnScreen: true,
276
285
  isDebug: false,
277
- isFlat: settings.generation?.name === 'superflat'
286
+ isFlat: settings.generation?.name === 'superflat',
287
+ enforcesSecureChat: serv._server.options?.enforcesSecureChat
278
288
  });
279
289
  player.emit('login');
280
290
  if (serv.supportFeature('difficultySentSeparately')) {
@@ -8,8 +8,8 @@ const vec3_1 = require("vec3");
8
8
  const THRESHOLD = 0.5;
9
9
  const PLAYER_SIZE = new vec3_1.Vec3(0.6, 1.8, 0.6); // Standard Minecraft player hitbox
10
10
  // Vanilla-like movement validation constants (from ServerGamePacketListenerImpl.java)
11
- const VANILLA_SPEED_LIMIT_NORMAL = 100.0; // Normal movement limit (squared distance)
12
- const VANILLA_SPEED_LIMIT_FLYING = 300.0; // Elytra/flying limit (squared distance)
11
+ const VANILLA_SPEED_LIMIT_NORMAL = 0.3 / 1.69; // Normal movement limit (squared distance)
12
+ const VANILLA_SPEED_LIMIT_FLYING = 0.8 / 1.69; // Elytra/flying limit (squared distance)
13
13
  const KNOCKBACK_VELOCITY = 8; // From pvp.ts KNOCKBACK_MULTIPLIER
14
14
  const KNOCKBACK_GRACE_PERIOD = 2000; // Allow higher speed for 2 seconds after damage
15
15
  const server = (serv) => {
@@ -42,7 +42,7 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
42
42
  if (player.pendingTeleport) {
43
43
  if (position.distanceTo(player.pendingTeleport) < 0.1) {
44
44
  lastMovementTime = currentTime;
45
- player.knownPosition = position.clone();
45
+ // player.knownPosition = position.clone()
46
46
  player.pendingTeleport = null;
47
47
  }
48
48
  return;
@@ -55,14 +55,14 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
55
55
  const deltaTime = (currentTime - lastMovementTime) / 1000; // Convert to seconds
56
56
  lastMovementTime = currentTime;
57
57
  // Anti-cheat: Block collision detection
58
- // if (basePositionAntiCheat && isPlayerInsideBlock(player, serv, position)) {
59
- // cancel(false)
60
- // if (positionAntiCheatNotifyPlayer) {
61
- // player.chat(`[safeZones] Block collision detected. Teleporting to safe position.`)
62
- // }
63
- // player.teleport(lastPosition ?? findSafePosition(player, serv, position))
64
- // return
65
- // }
58
+ if (basePositionAntiCheat && isPlayerInsideBlock(player, serv, position) && lastPosition) {
59
+ cancel(false);
60
+ if (positionAntiCheatNotifyPlayer) {
61
+ player.chat(`[safeZones] Block collision detected. Teleporting to safe position.`);
62
+ }
63
+ player.teleport(isPlayerInsideBlock(player, serv, lastPosition) ? lastPosition : findSafePosition(player, serv, position));
64
+ return;
65
+ }
66
66
  // Anti-cheat: Movement speed limit (vanilla-like approach)
67
67
  if (basePositionAntiCheat && lastPosition && !teleport) {
68
68
  packetCount++;
@@ -71,12 +71,29 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
71
71
  packetCount = 1;
72
72
  }
73
73
  const speedCheck = validateMovementSpeed(player, lastPosition, position, packetCount);
74
+ // Add debug fields to player
75
+ player['debugMaxVelocity'] = speedCheck.distanceSquared;
76
+ player['debugVelocityAllowanceMax'] = speedCheck.speedLimit;
77
+ player['debugVelocityDiff'] = speedCheck.distanceSquared - speedCheck.speedLimit;
78
+ player['debugExcessMovement'] = speedCheck.distanceSquared - speedCheck.currentVelocitySquared;
79
+ player['debugIsValid'] = speedCheck.isValid;
80
+ player['debugPacketCount'] = packetCount;
81
+ // Debug output for all movements (temporary)
82
+ // if (positionAntiCheatNotifyPlayer && speedCheck.distanceSquared > 0.001) {
83
+ // player.chat(
84
+ // `[DEBUG] distance²=${speedCheck.distanceSquared.toFixed(3)}, ` +
85
+ // `limit=${speedCheck.speedLimit.toFixed(3)}, ` +
86
+ // `excess=${player['debugExcessMovement'].toFixed(3)}, ` +
87
+ // `valid=${speedCheck.isValid}, packets=${packetCount}`
88
+ // )
89
+ // }
74
90
  if (!speedCheck.isValid) {
75
91
  if (positionAntiCheatNotifyPlayer) {
76
92
  player.chat(`[safeZones] ${speedCheck.reason} ` +
77
93
  `(distance²=${speedCheck.distanceSquared.toFixed(2)}, ` +
78
94
  `limit=${speedCheck.speedLimit.toFixed(2)}, ` +
79
- `velocity²=${speedCheck.currentVelocitySquared.toFixed(2)})`);
95
+ `velocity²=${speedCheck.currentVelocitySquared.toFixed(2)}, ` +
96
+ `excess=${player['debugExcessMovement'].toFixed(2)})`);
80
97
  }
81
98
  cancel(false);
82
99
  player.teleport(lastPosition);
@@ -122,15 +139,15 @@ function isPlayerInsideBlock(player, serv, position) {
122
139
  const chunk = player.world.getLoadedColumnAt(position);
123
140
  if (!chunk)
124
141
  return false;
125
- // Check collision points around player hitbox
142
+ // Player hitbox is 0.6 x 1.8 x 0.6, so check the two blocks that could contain the player
143
+ // Floor the position to get the base block coordinates
144
+ const baseX = Math.floor(position.x);
145
+ const baseY = Math.floor(position.y);
146
+ const baseZ = Math.floor(position.z);
147
+ // Check the two blocks: base block and the block above (since player height is 1.8)
126
148
  const checkPositions = [
127
- position, // Center
128
- position.offset(PLAYER_SIZE.x / 2, 0, PLAYER_SIZE.z / 2), // Top-right corner
129
- position.offset(-PLAYER_SIZE.x / 2, 0, PLAYER_SIZE.z / 2), // Top-left corner
130
- position.offset(PLAYER_SIZE.x / 2, 0, -PLAYER_SIZE.z / 2), // Bottom-right corner
131
- position.offset(-PLAYER_SIZE.x / 2, 0, -PLAYER_SIZE.z / 2), // Bottom-left corner
132
- position.offset(0, PLAYER_SIZE.y / 2, 0), // Top center
133
- position.offset(0, PLAYER_SIZE.y, 0) // Head position
149
+ new vec3_1.Vec3(baseX & 15, baseY, baseZ & 15), // Base block (feet level)
150
+ new vec3_1.Vec3(baseX & 15, baseY + 1, baseZ & 15) // Block above (head level)
134
151
  ];
135
152
  for (const checkPos of checkPositions) {
136
153
  try {
@@ -201,10 +218,12 @@ function validateMovementSpeed(player, lastPosition, newPosition, packetCount) {
201
218
  function findSafePosition(player, serv, attemptedPosition) {
202
219
  // Start from the attempted position and search nearby for a safe spot
203
220
  const basePosition = attemptedPosition.floored();
204
- const chunks = player.world.getColumns();
205
- const chunk = chunks[basePosition.x >> 4][basePosition.z >> 4];
206
- if (!chunk)
207
- return basePosition;
221
+ const getBlock = (pos) => {
222
+ const chunk = player.world.getLoadedColumnAt(pos);
223
+ if (!chunk)
224
+ return null;
225
+ return chunk.getBlockStateId(new vec3_1.Vec3(Math.floor(pos.x) & 15, Math.floor(pos.y), Math.floor(pos.z) & 15));
226
+ };
208
227
  // Search in expanding radius for a safe position
209
228
  for (let radius = 0; radius <= 3; radius++) {
210
229
  for (let x = -radius; x <= radius; x++) {
@@ -215,10 +234,9 @@ function findSafePosition(player, serv, attemptedPosition) {
215
234
  let isSafe = true;
216
235
  for (let y = 0; y < Math.ceil(PLAYER_SIZE.y); y++) {
217
236
  const checkPos = testPos.offset(0, y, 0);
218
- const pos = new vec3_1.Vec3(Math.floor(checkPos.x) & 15, Math.floor(checkPos.y), Math.floor(checkPos.z) & 15);
219
237
  try {
220
- const blockStateId = chunk.getBlockStateId(pos);
221
- if (serv.mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
238
+ const blockStateId = getBlock(checkPos);
239
+ if (blockStateId === null || serv.mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
222
240
  isSafe = false;
223
241
  break;
224
242
  }
@@ -236,6 +254,7 @@ function findSafePosition(player, serv, attemptedPosition) {
236
254
  }
237
255
  }
238
256
  }
257
+ serv.warn('[safeZones] no safe position found');
239
258
  // If no safe position found, return player's current position
240
259
  return player.position;
241
260
  }
@@ -31,16 +31,35 @@ const server = function (serv) {
31
31
  .forEach(player => {
32
32
  const iniPos = position ? position.scaled(1 / 32) : player.position.scaled(1 / 32);
33
33
  const pos = iniPos.scaled(8).floored();
34
- // only packet still in fixed position in all versions
35
- player._client.write('named_sound_effect', {
36
- soundName: finalSoundName,
37
- soundCategory,
38
- x: pos.x,
39
- y: pos.y,
40
- z: pos.z,
41
- volume,
42
- pitch: Math.round(pitch * 63)
43
- });
34
+ if (serv.supportFeature('removedNamedSoundEffectPacket')) { // 1.19.3 removes named_sound_effect
35
+ player._client.write('sound_effect', {
36
+ soundId: 0,
37
+ soundEvent: {
38
+ resource: finalSoundName,
39
+ range: undefined
40
+ },
41
+ soundCategory,
42
+ x: pos.x,
43
+ y: pos.y,
44
+ z: pos.z,
45
+ volume,
46
+ pitch: Math.round(pitch * 63),
47
+ seed: 0
48
+ });
49
+ }
50
+ else {
51
+ // only packet still in fixed position in all versions
52
+ player._client.write('named_sound_effect', {
53
+ soundName: finalSoundName,
54
+ soundCategory,
55
+ x: pos.x,
56
+ y: pos.y,
57
+ z: pos.z,
58
+ volume,
59
+ pitch: Math.round(pitch * 63),
60
+ seed: 0
61
+ });
62
+ }
44
63
  });
45
64
  };
46
65
  serv.playNoteBlock = (pitch, world, position, { instrument = 'harp', particle = true } = {}) => {
@@ -63,7 +82,8 @@ const server = function (serv) {
63
82
  player._client.write('stop_sound', {
64
83
  flags: 3, // Both source and sound
65
84
  source: soundInfo.soundCategory,
66
- sound: soundInfo.soundName
85
+ sound: soundInfo.soundName,
86
+ seed: 0
67
87
  });
68
88
  delete player.savedSounds[soundId];
69
89
  }
@@ -134,7 +154,8 @@ const player = function (player, serv) {
134
154
  player._client.write('stop_sound', {
135
155
  flags: 3, // Both source and sound
136
156
  source: soundInfo.soundCategory,
137
- sound: soundInfo.soundName
157
+ sound: soundInfo.soundName,
158
+ seed: 0
138
159
  });
139
160
  delete player.savedSounds[soundId];
140
161
  }
@@ -142,7 +163,8 @@ const player = function (player, serv) {
142
163
  else {
143
164
  // Stop all sounds
144
165
  player._client.write('stop_sound', {
145
- flags: 0 // Stop all sounds
166
+ flags: 0, // Stop all sounds
167
+ seed: 0
146
168
  });
147
169
  // Clear saved sounds storage
148
170
  player.savedSounds = {};
@@ -332,8 +332,12 @@ const entity = function (entity, serv) {
332
332
  entity.spawnPacketName = 'named_entity_spawn';
333
333
  else if (entity.type === 'object')
334
334
  entity.spawnPacketName = 'spawn_entity';
335
- else if (entity.type === 'mob')
336
- entity.spawnPacketName = 'spawn_entity_living';
335
+ else if (entity.type === 'mob') {
336
+ if (serv.supportFeature('consolidatedEntitySpawnPacket'))
337
+ entity.spawnPacketName = 'spawn_entity';
338
+ else
339
+ entity.spawnPacketName = 'spawn_entity_living';
340
+ }
337
341
  };
338
342
  entity.getSpawnPacket = () => {
339
343
  let scaledVelocity = entity.velocity.scaled(8000 / 20); // from fixed-position/second to unit => 1/8000 blocks per tick
@@ -361,52 +365,25 @@ const entity = function (entity, serv) {
361
365
  // Ensure we stay within protocol limits
362
366
  return Math.max(-128, Math.min(127, b));
363
367
  }
364
- if (entity.type === 'player') {
365
- return {
366
- entityId: entity.id,
367
- playerUUID: entity.uuid,
368
- x: entityPosition.x,
369
- y: entityPosition.y,
370
- z: entityPosition.z,
371
- yaw: convToProtocol(entity.yaw),
372
- pitch: convToProtocol(entity.pitch),
373
- currentItem: 0,
374
- metadata: entity.metadata
375
- };
376
- }
377
- else if (entity.type === 'object') {
378
- return {
379
- entityId: entity.id,
380
- objectUUID: entity.uuid,
381
- type: entity.entityType,
382
- x: entityPosition.x,
383
- y: entityPosition.y,
384
- z: entityPosition.z,
385
- pitch: convToProtocol(entity.pitch),
386
- yaw: convToProtocol(entity.yaw),
387
- objectData: entity.data,
388
- velocityX: scaledVelocity.x,
389
- velocityY: scaledVelocity.y,
390
- velocityZ: scaledVelocity.z
391
- };
392
- }
393
- else if (entity.type === 'mob') {
394
- return {
395
- entityId: entity.id,
396
- entityUUID: entity.uuid,
397
- type: entity.entityType,
398
- x: entityPosition.x,
399
- y: entityPosition.y,
400
- z: entityPosition.z,
401
- yaw: convToProtocol(entity.yaw),
402
- pitch: convToProtocol(entity.pitch),
403
- headPitch: convToProtocol(entity.headPitch),
404
- velocityX: scaledVelocity.x,
405
- velocityY: scaledVelocity.y,
406
- velocityZ: scaledVelocity.z,
407
- metadata: entity.metadata
408
- };
409
- }
368
+ return {
369
+ entityId: entity.id,
370
+ playerUUID: entity.uuid,
371
+ entityUUID: entity.uuid,
372
+ objectUUID: entity.uuid,
373
+ type: entity.entityType,
374
+ x: entityPosition.x,
375
+ y: entityPosition.y,
376
+ z: entityPosition.z,
377
+ yaw: convToProtocol(entity.yaw),
378
+ pitch: convToProtocol(entity.pitch),
379
+ headPitch: convToProtocol(entity.headPitch),
380
+ currentItem: 0,
381
+ objectData: entity.data,
382
+ velocityX: scaledVelocity.x,
383
+ velocityY: scaledVelocity.y,
384
+ velocityZ: scaledVelocity.z,
385
+ metadata: entity.metadata
386
+ };
410
387
  };
411
388
  const isPlayer = (arg) => arg.type === 'player';
412
389
  entity.updateAndSpawn = () => {
@@ -462,6 +462,7 @@ const player = function (player, serv, settings) {
462
462
  groundUp: bitMap !== undefined ? true : undefined,
463
463
  //note: it's a flag that tells the client to trust the edges of the chunk, meaning that the client can render the chunk without having to wait for the edges to be sent
464
464
  trustEdges: true, // should be false when a chunk section is updated instead of the whole chunk being overwritten, do we ever do that?
465
+ suppressLightUpdates: true, // 1.19.2
465
466
  bitMap: bitMap,
466
467
  ...serv.supportFeature('blockStateId') && serv.looseProtocolMode ? {
467
468
  // groundUp: false,
package/dist/modules.d.ts CHANGED
@@ -51,6 +51,7 @@ declare global {
51
51
  }>> {
52
52
  dimension: string | number;
53
53
  _client: Client;
54
+ disconnected?: boolean;
54
55
  }
55
56
  interface Entity extends EventEmitter {
56
57
  _client: Client;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zardoy/flying-squid",
3
3
  "description": "A minecraft server written in TS",
4
- "version": "0.0.92",
4
+ "version": "0.0.93",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",