@zardoy/flying-squid 0.0.131 → 0.0.133

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.
@@ -158,8 +158,10 @@ const server = function (serv, { version, worldFolder, noWorldRegion }) {
158
158
  serv.netherPortalNear = portalNear;
159
159
  /** where a player standing at `from` (in the world `fromWorld`) arrives when sent to `world` without an explicit position (/mv tp, /changeworld) */
160
160
  serv.worldEntryPoint = async (world, fromWorld, from) => {
161
- if (world.environment === 'end')
161
+ if (world.environment === 'end') {
162
+ await serv.makeEndPlatform();
162
163
  return new vec3_1.Vec3(100.5, 49, 0.5);
164
+ }
163
165
  const scale = world.environment === 'nether' && fromWorld?.environment === 'normal' ? 1 / 8 : world.environment === 'normal' && fromWorld?.environment === 'nether' ? 8 : 1;
164
166
  const x = Math.floor((from?.x ?? 0) * scale);
165
167
  const z = Math.floor((from?.z ?? 0) * scale);
@@ -236,8 +238,10 @@ const server = function (serv, { version, worldFolder, noWorldRegion }) {
236
238
  st.locked = true;
237
239
  if (world.environment === 'end')
238
240
  await player.changeWorld(serv.overworld, { dimension: serv.overworld.dimensionId });
239
- else
241
+ else {
242
+ await serv.makeEndPlatform();
240
243
  await player.changeWorld(serv.endworld, { dimension: serv.endworld.dimensionId, position: new vec3_1.Vec3(100.5, 49, 0.5) });
244
+ }
241
245
  return;
242
246
  }
243
247
  st.ticks += 4;
@@ -273,7 +277,7 @@ const server = function (serv, { version, worldFolder, noWorldRegion }) {
273
277
  for (let i = -1; i <= 1; i++)
274
278
  ringOffsets.push([i, -2], [i, 2], [-2, i], [2, i]);
275
279
  serv.onBlockInteraction('end_portal_frame', async ({ block, player }) => {
276
- if (player.heldItem?.name !== 'ender_eye')
280
+ if (player.inventory.slots[36 + player.heldItemSlot]?.name !== 'ender_eye')
277
281
  return false;
278
282
  const props = block.getProperties?.() ?? {};
279
283
  if (String(props.eye) === 'true')
@@ -0,0 +1,22 @@
1
+ import { Vec3 } from 'vec3';
2
+ /** look direction of a player (the server keeps player yaw / pitch as protocol bytes) */
3
+ export declare const lookDirection: (player: Player) => Vec3;
4
+ export declare const server: (serv: Server, options: Options) => void;
5
+ export declare const player: (player: Player, serv: Server) => void;
6
+ declare global {
7
+ interface Entity {
8
+ /** moved by its own module (projectiles), not by the entity physics */
9
+ customMotion?: boolean;
10
+ burnUntil?: number;
11
+ }
12
+ interface Server {
13
+ /** sets the target on fire for a few seconds (1 half heart per second, none for creative players) */
14
+ ignite: (target: Entity, seconds: number) => void;
15
+ /** block position (x, z) of the stronghold nearest to a point of a world, if it has any */
16
+ nearestStronghold: (world: any, x: number, z: number) => Promise<[number, number] | undefined>;
17
+ releaseBow: (player: Player) => void;
18
+ }
19
+ interface Player {
20
+ bowStart?: number;
21
+ }
22
+ }
@@ -0,0 +1,334 @@
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.player = exports.server = exports.lookDirection = void 0;
7
+ const vec3_1 = require("vec3");
8
+ const uuid_1345_1 = __importDefault(require("uuid-1345"));
9
+ const toDegrees = (v) => ({ yaw: Math.atan2(-v.x, v.z) * 180 / Math.PI, pitch: -Math.asin(Math.max(-1, Math.min(1, v.y / (v.norm() || 1)))) * 180 / Math.PI });
10
+ /** look direction of a player (the server keeps player yaw / pitch as protocol bytes) */
11
+ const lookDirection = (player) => {
12
+ const yaw = player.yaw * 2 * Math.PI / 256;
13
+ const pitch = player.pitch * 2 * Math.PI / 256;
14
+ return new vec3_1.Vec3(-Math.sin(yaw) * Math.cos(pitch), -Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch));
15
+ };
16
+ exports.lookDirection = lookDirection;
17
+ const server = function (serv, options) {
18
+ const mcData = serv.mcData;
19
+ const projectiles = new Set();
20
+ const typeId = (names) => serv.entityTypeId(names, 'object');
21
+ const spawn = (names, world, position, velocity, owner, size = 0.25) => {
22
+ const id = typeId(names);
23
+ if (id === undefined)
24
+ return undefined;
25
+ const e = serv.initEntity('object', id, world, position.clone());
26
+ e.uuid = uuid_1345_1.default.v4();
27
+ e.name = names[0];
28
+ e.velocity = velocity.clone();
29
+ e.size = new vec3_1.Vec3(size, size, size);
30
+ e.gravity = new vec3_1.Vec3(0, 0, 0);
31
+ e.terminalvelocity = new vec3_1.Vec3(99, 99, 99);
32
+ e.friction = new vec3_1.Vec3(0, 0, 0);
33
+ e.noGravity = true;
34
+ e.customMotion = true;
35
+ const { yaw, pitch } = toDegrees(velocity);
36
+ e.yaw = yaw;
37
+ e.pitch = pitch;
38
+ e.yawDeg = yaw;
39
+ e.data = (owner?.id ?? 0);
40
+ e.metadata = [];
41
+ e.updateAndSpawn();
42
+ return e;
43
+ };
44
+ serv.spawnPlain = spawn;
45
+ const launch = (p) => {
46
+ const proj = { ticks: 0, ...p };
47
+ projectiles.add(proj);
48
+ return proj;
49
+ };
50
+ const hitsBox = (e, pt, r) => {
51
+ const w = (e.size?.x ?? 0.6) / 2 + r;
52
+ const h = e.size?.y ?? 1.8;
53
+ return Math.abs(pt.x - e.position.x) <= w && Math.abs(pt.z - e.position.z) <= (e.size?.z ?? e.size?.x ?? 0.6) / 2 + r && pt.y >= e.position.y - r && pt.y <= e.position.y + h + r;
54
+ };
55
+ const finish = (p) => {
56
+ projectiles.delete(p);
57
+ if (serv.entities[p.entity.id])
58
+ p.entity.destroy();
59
+ };
60
+ serv.on('tick', (_delta) => {
61
+ const dt = 0.05;
62
+ for (const p of [...projectiles]) {
63
+ const e = p.entity;
64
+ if (!serv.entities[e.id]) {
65
+ projectiles.delete(p);
66
+ continue;
67
+ }
68
+ p.ticks++;
69
+ if (p.ticks > p.maxTicks) {
70
+ finish(p);
71
+ continue;
72
+ }
73
+ if (p.step) {
74
+ if (!p.step(p))
75
+ finish(p);
76
+ continue;
77
+ }
78
+ const v = e.velocity;
79
+ v.y -= p.gravity * dt;
80
+ const drag = Math.max(0, 1 - p.drag * dt);
81
+ v.x *= drag;
82
+ v.y *= drag;
83
+ v.z *= drag;
84
+ const from = e.position;
85
+ const move = v.scaled(dt);
86
+ const len = move.norm();
87
+ const steps = Math.max(1, Math.ceil(len / 0.25));
88
+ const candidates = Object.values(serv.entities).filter(o => o !== e && o.ready && o.world === e.world && !o.dead && (o.type === 'mob' || o.type === 'player') && o.health !== undefined &&
89
+ (p.hitOwner || o !== p.owner) && o.position.distanceTo(from) < len + 24);
90
+ let last = from.clone();
91
+ let result = { kind: 'none', at: from.plus(move) };
92
+ for (let i = 1; i <= steps; i++) {
93
+ const pt = from.plus(move.scaled(i / steps));
94
+ const block = e.world.sync.getBlock(new vec3_1.Vec3(Math.floor(pt.x), Math.floor(pt.y), Math.floor(pt.z)));
95
+ const solid = !block || (block.shapes ? block.shapes.some((s) => pt.x - Math.floor(pt.x) >= s[0] && pt.x - Math.floor(pt.x) <= s[3] && pt.y - Math.floor(pt.y) >= s[1] && pt.y - Math.floor(pt.y) <= s[4] && pt.z - Math.floor(pt.z) >= s[2] && pt.z - Math.floor(pt.z) <= s[5]) : block.boundingBox === 'block');
96
+ if (solid) {
97
+ result = { kind: 'block', at: last };
98
+ break;
99
+ }
100
+ const hit = candidates.find(o => hitsBox(o, pt, p.radius));
101
+ if (hit) {
102
+ result = { kind: 'entity', at: pt, target: hit };
103
+ break;
104
+ }
105
+ last = pt;
106
+ }
107
+ e.sendPosition(result.at.clone(), false).catch(() => { });
108
+ if (result.kind === 'none')
109
+ continue;
110
+ if (result.kind === 'block')
111
+ p.onBlock?.(result.at, p);
112
+ else
113
+ p.onEntity?.(result.target, result.at, p);
114
+ finish(p);
115
+ }
116
+ });
117
+ // ---------------------------------------------------------------- burning
118
+ serv.ignite = (target, seconds) => {
119
+ if (target.type === 'player' && (target.gameMode === 1 || target.gameMode === 3))
120
+ return;
121
+ target.burnUntil = Math.max(target.burnUntil ?? 0, Date.now() + seconds * 1000);
122
+ };
123
+ serv.on('tick', (_d, count) => {
124
+ if (count % 20 !== 0)
125
+ return;
126
+ const now = Date.now();
127
+ for (const e of Object.values(serv.entities)) {
128
+ if (!e.burnUntil)
129
+ continue;
130
+ if (now > e.burnUntil || e.dead) {
131
+ e.burnUntil = undefined;
132
+ continue;
133
+ }
134
+ serv.hurt(e, 1, { knockback: 0 });
135
+ }
136
+ });
137
+ // ---------------------------------------------------------------- arrows and fireballs
138
+ const arrowNames = ['arrow'];
139
+ serv.projectiles = {
140
+ shootArrow: (shooter, at, { damage = 3, speed = 24 } = {}) => {
141
+ const from = shooter.position.offset(0, (shooter.size?.y ?? 1.8) * 0.8, 0);
142
+ const dir = at.minus(from);
143
+ const dist = dir.norm();
144
+ // arrows drop while they fly: aim higher by the drop over the flight time (gravity 20 b/s^2, a little extra for the drag)
145
+ const t = dist / speed;
146
+ dir.y += 0.5 * 20 * t * t * 1.1;
147
+ const v = dir.normalize().scaled(speed);
148
+ const e = spawn(arrowNames, shooter.world, from, v, shooter, 0.5);
149
+ if (!e)
150
+ return;
151
+ launch({
152
+ entity: e, owner: shooter, gravity: 20, drag: 0.2, maxTicks: 200, radius: 0.15,
153
+ onEntity: (target) => { serv.hurt(target, damage, { source: shooter, from: e.position }); }
154
+ });
155
+ },
156
+ shootFireball: (shooter, at) => {
157
+ const from = shooter.position.offset(0, (shooter.size?.y ?? 1.8) * 0.6, 0);
158
+ const dir = at.minus(from).normalize();
159
+ const e = spawn(['small_fireball', 'smallfireball'], shooter.world, from.plus(dir.scaled(1)), dir.scaled(14), shooter, 0.3125);
160
+ if (!e)
161
+ return;
162
+ launch({
163
+ entity: e, owner: shooter, gravity: 0, drag: 0, maxTicks: 160, radius: 0.1,
164
+ onEntity: (target) => { if (serv.hurt(target, 5, { source: shooter, from: e.position }))
165
+ serv.ignite(target, 4); }
166
+ });
167
+ }
168
+ };
169
+ // ---------------------------------------------------------------- inventory helpers
170
+ const takeOne = (player, slot) => {
171
+ if (player.gameMode === 1)
172
+ return;
173
+ const item = player.inventory.slots[slot];
174
+ if (!item)
175
+ return;
176
+ item.count--;
177
+ player.inventory.updateSlot(slot, item.count > 0 ? item : null);
178
+ };
179
+ const heldSlot = (player, slot) => (slot === 45 ? 45 : 36 + slot);
180
+ // ---------------------------------------------------------------- bow
181
+ serv.once('asap', () => {
182
+ if (mcData.itemsByName.bow)
183
+ serv.onItemUse('bow', ({ player }) => { player.bowStart = Date.now(); });
184
+ });
185
+ /** the use key was released (block_dig status 5): a drawn bow shoots */
186
+ serv.releaseBow = (player) => {
187
+ const held = player.inventory.slots[36 + player.heldItemSlot];
188
+ const started = player.bowStart;
189
+ if (held?.name !== 'bow' || !started)
190
+ return;
191
+ player.bowStart = undefined;
192
+ const t = Math.min(1, (Date.now() - started) / 1000);
193
+ const power = (t * t + t * 2) / 3;
194
+ if (power < 0.1)
195
+ return;
196
+ let arrowSlot = -1;
197
+ if (player.gameMode !== 1) {
198
+ arrowSlot = player.inventory.slots.findIndex(i => i && /^(arrow|tipped_arrow|spectral_arrow)$/.test(i.name));
199
+ if (arrowSlot < 0)
200
+ return;
201
+ }
202
+ const eye = player.position.offset(0, 1.62, 0);
203
+ const dir = (0, exports.lookDirection)(player);
204
+ const e = spawn(arrowNames, player.world, eye.plus(dir.scaled(0.5)), dir.scaled(power * 60), player, 0.5);
205
+ if (!e)
206
+ return;
207
+ if (arrowSlot >= 0)
208
+ takeOne(player, arrowSlot);
209
+ const damage = Math.ceil(2 * power * 3) + (power >= 1 ? 1 : 0);
210
+ launch({
211
+ entity: e, owner: player, gravity: 20, drag: 0.2, maxTicks: 400, radius: 0.15,
212
+ onEntity: (target) => { target.attackedBy?.(player, damage); serv.hurt(target, damage, { source: player, from: e.position, knockback: 4 }); }
213
+ });
214
+ };
215
+ // ---------------------------------------------------------------- ender pearl
216
+ const pearlCooldown = new WeakMap();
217
+ /** a spot where a player (feet + 2 blocks) fits, at or just below `at` */
218
+ const standAt = (world, at) => {
219
+ const free = (x, y, z) => {
220
+ const b = world.sync.getBlock(new vec3_1.Vec3(Math.floor(x), Math.floor(y), Math.floor(z)));
221
+ return !!b && b.boundingBox !== 'block';
222
+ };
223
+ for (const dy of [0, -1, 1, -2, 2]) {
224
+ const y = Math.floor(at.y) + dy;
225
+ if (free(at.x, y, at.z) && free(at.x, y + 1, at.z))
226
+ return new vec3_1.Vec3(at.x, y + (dy === 0 ? at.y - Math.floor(at.y) : 0), at.z);
227
+ }
228
+ return at.clone();
229
+ };
230
+ serv.once('asap', () => {
231
+ serv.onItemUse('ender_pearl', ({ player, slot }) => {
232
+ const now = Date.now();
233
+ if (now - (pearlCooldown.get(player) ?? 0) < 1000)
234
+ return;
235
+ pearlCooldown.set(player, now);
236
+ const eye = player.position.offset(0, 1.62, 0);
237
+ const dir = (0, exports.lookDirection)(player);
238
+ const e = spawn(['ender_pearl', 'thrown_enderpearl', 'thrownenderpearl'], player.world, eye.plus(dir.scaled(0.3)), dir.scaled(30), player);
239
+ if (!e) {
240
+ serv.warn?.('this version has no ender pearl entity');
241
+ return;
242
+ }
243
+ takeOne(player, heldSlot(player, slot));
244
+ const land = (at) => {
245
+ if (!serv.players.includes(player) || player.world !== e.world)
246
+ return;
247
+ void player.teleport(standAt(e.world, at));
248
+ if (player.gameMode === 0 || player.gameMode === 2)
249
+ player.takeDamage({ damage: 5, velocity: new vec3_1.Vec3(0, 0, 0), animation: true, sound: 'mob.endermen.portal' });
250
+ };
251
+ launch({ entity: e, owner: player, gravity: 12, drag: 0.2, maxTicks: 400, radius: 0.1, onBlock: land, onEntity: (_t, at) => land(at) });
252
+ });
253
+ // ---------------------------------------------------------------- eye of ender
254
+ serv.onItemUse('ender_eye', ({ player, slot }) => {
255
+ void throwEye(player, slot);
256
+ });
257
+ });
258
+ /** position of the stronghold nearest to (x, z); undefined outside the overworld / when the generator has none */
259
+ const nearestStronghold = async (world, x, z) => {
260
+ if (world.environment !== 'normal' || !world.strongholds)
261
+ return undefined;
262
+ const nearest = (list) => list.reduce((best, s) => !best || Math.hypot(s[0] - x, s[1] - z) < Math.hypot(best[0] - x, best[1] - z) ? s : best, undefined);
263
+ // the first rings are enough unless the player is far out (the ring list is ordered from the centre outwards)
264
+ let found = nearest(await world.strongholds(9));
265
+ if (!found || Math.hypot(found[0] - x, found[1] - z) > 3200)
266
+ found = nearest(await world.strongholds());
267
+ return found;
268
+ };
269
+ serv.nearestStronghold = (world, x, z) => nearestStronghold(world, x, z);
270
+ const eyeBusy = new WeakSet();
271
+ async function throwEye(player, slot) {
272
+ if (eyeBusy.has(player))
273
+ return;
274
+ eyeBusy.add(player);
275
+ try {
276
+ const target = await nearestStronghold(player.world, player.position.x, player.position.z);
277
+ if (!target) {
278
+ player.chat?.('The eye has nothing to point at here.');
279
+ return;
280
+ }
281
+ const start = player.position.offset(0, 1.62 * 0.5 + 0.2, 0);
282
+ const e = spawn(['eye_of_ender', 'eye_of_ender_signal', 'eyeofendersignal'], player.world, start, new vec3_1.Vec3(0, 0, 0), player);
283
+ if (!e) {
284
+ serv.warn?.('this version has no eye of ender entity');
285
+ return;
286
+ }
287
+ takeOne(player, heldSlot(player, slot));
288
+ // EyeOfEnder.signalTo: further than 12 blocks away it flies 12 blocks towards the target and 8 up, otherwise it flies to it
289
+ const dx = target[0] - start.x;
290
+ const dz = target[1] - start.z;
291
+ const d = Math.hypot(dx, dz);
292
+ const goal = d > 12 ? new vec3_1.Vec3(start.x + dx / d * 12, start.y + 8, start.z + dz / d * 12) : new vec3_1.Vec3(target[0], 30, target[1]);
293
+ const survives = Math.floor(Math.random() * 5) > 0;
294
+ launch({
295
+ entity: e, owner: player, gravity: 0, drag: 0, maxTicks: 90, radius: 0,
296
+ step: (p) => {
297
+ const ent = p.entity;
298
+ const v = ent.velocity;
299
+ const gx = goal.x - ent.position.x;
300
+ const gz = goal.z - ent.position.z;
301
+ const horiz = Math.hypot(gx, gz);
302
+ const angle = Math.atan2(gz, gx);
303
+ // per tick (20/s): speed eases towards the remaining distance, y towards the goal height (blocks per tick -> per second)
304
+ const hspeed = Math.hypot(v.x, v.z) / 20;
305
+ let speed = hspeed + 0.0025 * (horiz - hspeed);
306
+ let vy = v.y / 20;
307
+ if (horiz < 1) {
308
+ speed *= 0.8;
309
+ vy *= 0.8;
310
+ }
311
+ const dir = ent.position.y < goal.y ? 1 : -1;
312
+ vy += (dir - vy) * 0.015;
313
+ v.set(Math.cos(angle) * speed * 20, vy * 20, Math.sin(angle) * speed * 20);
314
+ void ent.sendPosition(ent.position.plus(v.scaled(0.05)), false);
315
+ if (p.ticks > 80) {
316
+ if (survives)
317
+ serv.dropItem(ent.world, ent.position, 'ender_eye', 1, new vec3_1.Vec3(0, 2, 0));
318
+ return false;
319
+ }
320
+ return true;
321
+ }
322
+ });
323
+ }
324
+ finally {
325
+ eyeBusy.delete(player);
326
+ }
327
+ }
328
+ };
329
+ exports.server = server;
330
+ const player = function (player, serv) {
331
+ player._client.on('block_dig', (packet) => { if (packet.status === 5)
332
+ serv.releaseBow(player); });
333
+ };
334
+ exports.player = player;
@@ -18,13 +18,16 @@ declare global {
18
18
  * * maxVelocity: maxVelocity from consecutive hits
19
19
  * * animation: Play death/hit animation
20
20
  */
21
- 'takeDamage': ({ sound, damage, velocity, maxVelocity, animation }: {
21
+ 'takeDamage': ({ sound, damage, velocity, maxVelocity, animation, source }: {
22
22
  sound?: string | undefined;
23
23
  damage?: number | undefined;
24
24
  velocity?: any;
25
25
  maxVelocity?: any;
26
26
  animation?: boolean | undefined;
27
+ source?: Entity;
27
28
  }) => void;
29
+ /** mobs: called when a player hits it, before the damage is applied */
30
+ attackedBy?: (attacker: Player, damage: number) => void;
28
31
  }
29
32
  interface PlayerBehaviorInputMap {
30
33
  'attack': {
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.server = exports.entity = exports.player = void 0;
7
7
  const vec3_1 = require("vec3");
8
8
  const chalk_1 = __importDefault(require("chalk"));
9
+ const mobs_1 = require("./mobs");
9
10
  const user_error_1 = __importDefault(require("../user_error"));
10
11
  const MAX_ATTACK_DISTANCE = 4; // Maximum reach in blocks
11
12
  const ATTACK_COOLDOWN_MS = 250; // Minimum time between attacks
@@ -18,12 +19,16 @@ const player = function (player, serv) {
18
19
  if (!attackedEntity)
19
20
  return;
20
21
  const attackedPlayer = attackedEntity.type === 'player' ? attackedEntity : undefined;
21
- if (!attackedPlayer)
22
+ // mobs (zombies, blazes, the ender dragon, end crystals, ...) can be hit too
23
+ const attackedMob = attackedEntity.type === 'mob' || attackedEntity.name === 'end_crystal' ? attackedEntity : undefined;
24
+ if (!attackedPlayer && !attackedMob)
22
25
  return;
23
- if (attackedPlayer.gameMode === 1 || attackedPlayer.gameMode === 3 || attackedPlayer.invincible)
26
+ if (attackedMob && (attackedMob.dead || attackedMob.health === undefined))
24
27
  return;
25
- // Anti-cheat: Distance check
26
- const distance = player.position.distanceTo(attackedEntity.position);
28
+ if (attackedPlayer && (attackedPlayer.gameMode === 1 || attackedPlayer.gameMode === 3 || attackedPlayer.invincible))
29
+ return;
30
+ // Anti-cheat: Distance check (big entities like the dragon are measured from their box, not their centre)
31
+ const distance = player.position.distanceTo(attackedEntity.position) - (attackedMob ? Math.max(attackedMob.size?.x ?? 0, attackedMob.size?.y ?? 0) / 2 : 0);
27
32
  if (distance > MAX_ATTACK_DISTANCE) {
28
33
  return; // Silently fail suspicious attacks
29
34
  }
@@ -35,6 +40,16 @@ const player = function (player, serv) {
35
40
  // Calculate knockback direction and strength
36
41
  const knockbackDir = attackedEntity.position.minus(player.position).normalize();
37
42
  const velocity = DEFAULT_KNOCKBACK.plus(knockbackDir.scaled(KNOCKBACK_MULTIPLIER));
43
+ if (attackedMob) {
44
+ // damage of the item in hand, a falling player hits critically
45
+ const critical = !player.onGround && player.gameMode !== 1;
46
+ const damage = (0, mobs_1.weaponDamage)(player.inventory.slots[36 + player.heldItemSlot]?.name) * (critical ? 1.5 : 1);
47
+ player.behavior('attack', { attackedEntity, velocity, damage }, (o) => {
48
+ attackedMob.attackedBy?.(player, o.damage ?? damage);
49
+ serv.hurt(attackedMob, o.damage ?? damage, { source: player, from: player.position, knockback: 5 });
50
+ });
51
+ return;
52
+ }
38
53
  player.behavior('attack', {
39
54
  attackedEntity,
40
55
  velocity
@@ -58,7 +73,7 @@ const player = function (player, serv) {
58
73
  exports.player = player;
59
74
  const entity = function (entity, serv) {
60
75
  entity.invincible = false;
61
- entity.takeDamage = ({ sound = 'game.player.hurt', damage = 1, velocity = new vec3_1.Vec3(0, 0, 0), maxVelocity = new vec3_1.Vec3(4, 4, 4), animation = true }) => {
76
+ entity.takeDamage = ({ sound = 'game.player.hurt', damage = 1, velocity = new vec3_1.Vec3(0, 0, 0), maxVelocity = new vec3_1.Vec3(4, 4, 4), animation = true, source }) => {
62
77
  if (entity.invincible)
63
78
  return;
64
79
  entity.updateHealth(entity.health - damage);
@@ -75,8 +90,12 @@ const entity = function (entity, serv) {
75
90
  entityStatus: 3
76
91
  });
77
92
  }
93
+ // mobs play their death animation, drop their loot and are removed a moment later (`die` in mobs.ts)
78
94
  if (entity.type !== 'player') {
79
- delete serv.entities[entity.id];
95
+ if (entity.die)
96
+ entity.die(source);
97
+ else
98
+ delete serv.entities[entity.id];
80
99
  }
81
100
  }
82
101
  else if (animation) {
@@ -0,0 +1,9 @@
1
+ /** entity id of a spawner block entity (1.21 `SpawnData.entity.id`, 1.18 `SpawnData.id`, 1.8 `EntityId`, `SpawnPotentials`) */
2
+ export declare function spawnerEntityOf(be: any): string | undefined;
3
+ export declare const server: (serv: Server, options: Options) => void;
4
+ declare global {
5
+ interface Entity {
6
+ /** key of the spawner block that made this mob */
7
+ spawnerKey?: string;
8
+ }
9
+ }
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.server = void 0;
4
+ exports.spawnerEntityOf = spawnerEntityOf;
5
+ const vec3_1 = require("vec3");
6
+ const entityPhysics_1 = require("../entityPhysics");
7
+ /**
8
+ * Mob spawner blocks (nether fortress blazes, dungeons, mineshaft cave spiders, stronghold silverfish, spawners of vanilla saves).
9
+ *
10
+ * Like `BaseSpawner`: while a survival player is within `RequiredPlayerRange` (16) blocks the delay counts down; at zero up to `SpawnCount` mobs appear at random spots within
11
+ * `SpawnRange` blocks (x, z) and +-1 block (y), unless `MaxNearbyEntities` mobs of that type are around already; then a new delay of `MinSpawnDelay`..`MaxSpawnDelay` ticks starts.
12
+ * Light levels and the spawn rules of the individual mobs are ignored. Blazes (and every other flying mob) can spawn in the air.
13
+ *
14
+ * The state lives in the block entity of the chunk (`Delay` is written back every few seconds), so it survives saving.
15
+ */
16
+ const num = (tag, fallback) => (typeof tag?.value === 'number' ? tag.value : fallback);
17
+ /** entity id of a spawner block entity (1.21 `SpawnData.entity.id`, 1.18 `SpawnData.id`, 1.8 `EntityId`, `SpawnPotentials`) */
18
+ function spawnerEntityOf(be) {
19
+ const sd = be?.SpawnData?.value;
20
+ const id = sd?.entity?.value?.id?.value ?? sd?.id?.value ?? be?.EntityId?.value;
21
+ if (typeof id === 'string')
22
+ return id;
23
+ const pot = be?.SpawnPotentials?.value?.value?.[0];
24
+ const pid = pot?.data?.value?.entity?.value?.id?.value ?? pot?.data?.value?.id?.value ?? pot?.Entity?.value?.id?.value ?? pot?.Type?.value;
25
+ return typeof pid === 'string' ? pid : undefined;
26
+ }
27
+ const server = function (serv, options) {
28
+ const mcData = serv.mcData;
29
+ const spawnerBlocks = new Set(['spawner', 'mob_spawner']);
30
+ const delays = new Map();
31
+ const every = 2; // ticks between checks
32
+ const keyOf = (world, pos) => `${world.worldName ?? 'world'}:${pos.x},${pos.y},${pos.z}`;
33
+ const strip = (id) => id.replace(/^minecraft:/, '');
34
+ const spotFree = (world, p, size) => (0, entityPhysics_1.collisionBoxes)(world, [p.x - size.x / 2 + 1e-3, p.y + 1e-3, p.z - size.z / 2 + 1e-3, p.x + size.x / 2 - 1e-3, p.y + size.y - 1e-3, p.z + size.z / 2 - 1e-3]).length === 0;
35
+ const trySpawn = (world, pos, be, entityName) => {
36
+ const typeId = serv.entityTypeId(entityName, 'mob');
37
+ if (typeId === undefined)
38
+ return false;
39
+ const range = num(be.SpawnRange, 4);
40
+ const count = num(be.SpawnCount, 4);
41
+ const maxNearby = num(be.MaxNearbyEntities, 6);
42
+ const name = strip(entityName);
43
+ const nearby = Object.values(serv.entities).filter(e => e.world === world && e.type === 'mob' && !e.dead && (e.name ?? '').toLowerCase() === name &&
44
+ Math.abs(e.position.x - pos.x) <= range + 4 && Math.abs(e.position.z - pos.z) <= range + 4 && Math.abs(e.position.y - pos.y) <= range + 4).length;
45
+ if (nearby >= maxNearby)
46
+ return false;
47
+ const info = mcData.entitiesArray.find(e => e.id === typeId);
48
+ const size = new vec3_1.Vec3(info?.width ?? 0.6, info?.height ?? 1.8, info?.width ?? 0.6);
49
+ let spawned = 0;
50
+ for (let i = 0; i < count && nearby + spawned < maxNearby; i++) {
51
+ for (let attempt = 0; attempt < 8; attempt++) {
52
+ const p = new vec3_1.Vec3(pos.x + 0.5 + (Math.random() - Math.random()) * range, pos.y + Math.floor(Math.random() * 3) - 1, pos.z + 0.5 + (Math.random() - Math.random()) * range);
53
+ if (!spotFree(world, p, size))
54
+ continue;
55
+ serv.spawnMob(typeId, world, p, { yaw: Math.random() * 360 }).spawnerKey = keyOf(world, pos);
56
+ spawned++;
57
+ break;
58
+ }
59
+ }
60
+ if (spawned)
61
+ serv.emitParticle?.(mcData.particlesByName?.flame?.id ?? 0, world, pos.offset(0.5, 0.5, 0.5), { count: 10, size: new vec3_1.Vec3(1, 1, 1) });
62
+ return spawned > 0;
63
+ };
64
+ let tick = 0;
65
+ serv.on('tick', () => {
66
+ tick++;
67
+ if (tick % every !== 0)
68
+ return;
69
+ const done = new Set();
70
+ for (const player of serv.players) {
71
+ if (player.gameMode === 1 || player.gameMode === 3 || !player.world)
72
+ continue;
73
+ const world = player.world;
74
+ const cx = Math.floor(player.position.x / 16);
75
+ const cz = Math.floor(player.position.z / 16);
76
+ for (let dx = -2; dx <= 2; dx++) {
77
+ for (let dz = -2; dz <= 2; dz++) {
78
+ const column = world.getLoadedColumn(cx + dx, cz + dz);
79
+ if (!column || done.has(column))
80
+ continue;
81
+ done.add(column);
82
+ for (const [key, be] of Object.entries(column.blockEntities ?? {})) {
83
+ const entityName = spawnerEntityOf(be);
84
+ if (!entityName)
85
+ continue;
86
+ const [x, y, z] = key.split(',').map(Number);
87
+ const pos = new vec3_1.Vec3(x, y, z);
88
+ // a spawner whose block is gone does nothing
89
+ const block = world.sync.getBlock(pos);
90
+ if (!block || !spawnerBlocks.has(block.name))
91
+ continue;
92
+ const range = num(be.RequiredPlayerRange, 16);
93
+ const near = serv.players.some(p => p.world === world && p.gameMode !== 1 && p.gameMode !== 3 && p.position.distanceTo(pos.offset(0.5, 0.5, 0.5)) <= range);
94
+ if (!near)
95
+ continue;
96
+ const k = keyOf(world, pos);
97
+ let delay = delays.get(k) ?? num(be.Delay, 20);
98
+ delay -= every;
99
+ if (delay <= 0) {
100
+ trySpawn(world, pos, be, entityName);
101
+ const min = num(be.MinSpawnDelay, 200);
102
+ const max = num(be.MaxSpawnDelay, 800);
103
+ delay = min + Math.floor(Math.random() * (Math.max(max, min) - min + 1));
104
+ if (be.Delay)
105
+ be.Delay.value = delay;
106
+ }
107
+ delays.set(k, delay);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ });
113
+ };
114
+ exports.server = server;
@@ -25,6 +25,8 @@ declare global {
25
25
  /** Pitch of entity (rotation sideways) */
26
26
  pitch: number;
27
27
  "teleport": (pos: Vec3) => void;
28
+ /** sends the current position as an absolute position to the clients nearby (resync of clients that predict movement) */
29
+ sendAbsolute: () => void;
28
30
  }
29
31
  interface PlayerBehaviorInputMap {
30
32
  'move': {
@@ -115,6 +115,8 @@ const player = function (player) {
115
115
  };
116
116
  };
117
117
  exports.player = player;
118
+ const degreesToByte = (deg) => { let b = Math.floor(((deg % 360) + 360) % 360 * 256 / 360); if (b > 127)
119
+ b -= 256; return b; };
118
120
  const entity = function (entity, serv) {
119
121
  entity.sendPosition = async (position, onGround, teleport = false) => {
120
122
  if (typeof position === 'undefined')
@@ -153,8 +155,9 @@ const entity = function (entity, serv) {
153
155
  x: entityPosition.x,
154
156
  y: entityPosition.y,
155
157
  z: entityPosition.z,
156
- yaw: entity.yaw,
157
- pitch: entity.pitch,
158
+ // players keep their rotation as protocol bytes, other entities as degrees
159
+ yaw: entity.type === 'player' ? entity.yaw : degreesToByte(entity.yawDeg ?? entity.yaw ?? 0),
160
+ pitch: entity.type === 'player' ? entity.pitch : degreesToByte(entity.pitch ?? 0),
158
161
  onGround
159
162
  });
160
163
  entity.knownPosition = position;
@@ -186,6 +189,27 @@ const entity = function (entity, serv) {
186
189
  });
187
190
  return !cancelled;
188
191
  };
192
+ /**
193
+ * Absolute position for the clients nearby. Moves are sent as small deltas against the position the client has; a client that predicts movement itself (mineflayer's entity
194
+ * physics: gravity, water) drifts away from the server over time. An absolute position now and then (see entities.ts) puts every entity back where the server has it.
195
+ */
196
+ entity.sendAbsolute = () => {
197
+ let entityPosition;
198
+ if (serv.supportFeature('fixedPointPosition'))
199
+ entityPosition = entity.position.scaled(32).floored();
200
+ else
201
+ entityPosition = entity.position;
202
+ entity._writeOthersNearby('entity_teleport', {
203
+ entityId: entity.id,
204
+ x: entityPosition.x,
205
+ y: entityPosition.y,
206
+ z: entityPosition.z,
207
+ yaw: entity.type === 'player' ? entity.yaw : degreesToByte(entity.yawDeg ?? entity.yaw ?? 0),
208
+ pitch: entity.type === 'player' ? entity.pitch : degreesToByte(entity.pitch ?? 0),
209
+ onGround: !!entity.onGround
210
+ });
211
+ entity.knownPosition = entity.position.clone();
212
+ };
189
213
  entity.teleport = (pos) => {
190
214
  entity.sendPosition(pos, false, true);
191
215
  };