@zardoy/flying-squid 0.0.132 → 0.0.134

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.
@@ -2,33 +2,26 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.server = exports.entity = void 0;
4
4
  const vec3_1 = require("vec3");
5
+ const entityPhysics_1 = require("../entityPhysics");
5
6
  const entity = function (entity, serv, { version }) {
6
- const blocks = serv.mcData.blocks;
7
7
  entity.calculatePhysics = async (delta) => {
8
- if (entity.gravity) {
9
- addGravity(entity, 'x', delta);
10
- addGravity(entity, 'y', delta);
11
- addGravity(entity, 'z', delta);
12
- }
13
- const vSign = getSign(entity.velocity);
14
- const sizeSigned = new vec3_1.Vec3(vSign.x * entity.size.x, vSign.y * entity.size.y, vSign.z * entity.size.z);
15
- const xVec = entity.position.offset(entity.velocity.x * delta + sizeSigned.x / 2, 0, 0);
16
- const yVec = entity.position.offset(0, entity.velocity.y * delta + sizeSigned.y / 2, 0);
17
- const zVec = entity.position.offset(0, 0, entity.velocity.z * delta + sizeSigned.z / 2);
18
- // Get block for each (x/y/z)Vec, check to avoid duplicate getBlockTypes
19
- const xBlock = blocks[await entity.world.getBlockType(xVec)].boundingBox === 'block';
20
- const yBlock = yVec.equals(xVec) ? xBlock : blocks[await entity.world.getBlockType(yVec)].boundingBox === 'block';
21
- const zBlock = zVec.equals(yVec) ? yBlock : (zVec.equals(xVec) ? xBlock : blocks[await entity.world.getBlockType(zVec)].boundingBox === 'block');
22
- if (xBlock || yBlock || zBlock) {
23
- entity.velocity.x = getFriction(entity.velocity.x, entity.friction.x, delta);
24
- entity.velocity.z = getFriction(entity.velocity.z, entity.friction.z, delta);
25
- }
26
- const newPos = entity.position.clone();
27
- newPos.x += getMoveAmount('x', xBlock, entity, delta, sizeSigned.x);
28
- newPos.y += getMoveAmount('y', yBlock, entity, delta, sizeSigned.y);
29
- newPos.z += getMoveAmount('z', zBlock, entity, delta, sizeSigned.z);
30
- // serv.emitParticle(30, serv.overworld, entity.position, { size: new Vec3(0, 0, 0) });
31
- return { position: newPos, onGround: yBlock };
8
+ // the box physics works on a copy: `sendPosition` compares the old and the new position
9
+ const body = {
10
+ position: entity.position.clone(),
11
+ velocity: entity.velocity,
12
+ size: entity.size,
13
+ gravity: entity.noGravity ? undefined : entity.gravity,
14
+ terminalvelocity: entity.terminalvelocity,
15
+ friction: entity.friction,
16
+ buoyant: entity.name === 'item' || entity.name === 'experience_orb',
17
+ flying: entity.isFlyer,
18
+ onGround: entity.onGround
19
+ };
20
+ const moved = (0, entityPhysics_1.stepBody)(entity.world, body, delta);
21
+ entity.inWater = body.inWater;
22
+ entity.inLava = body.inLava;
23
+ entity.hitWall = !!(body.hitX || body.hitZ);
24
+ return { position: moved ? body.position : entity.position, onGround: moved ? !!body.onGround : entity.onGround };
32
25
  };
33
26
  entity.sendVelocity = (vel, maxVel) => {
34
27
  const velocity = vel;
@@ -51,29 +44,6 @@ const entity = function (entity, serv, { version }) {
51
44
  entity.velocity.add(velocity);
52
45
  }
53
46
  };
54
- function getMoveAmount(dir, block, entity, delta, sizeSigned) {
55
- if (block) {
56
- entity.velocity[dir] = 0;
57
- return -1 * (entity.position[dir] + sizeSigned / 2 - entity.position[dir]);
58
- }
59
- else {
60
- return entity.velocity[dir] * delta;
61
- }
62
- }
63
- function getSign(vec) {
64
- return new vec3_1.Vec3(Math.sign(vec.x), Math.sign(vec.y), Math.sign(vec.z));
65
- }
66
- function addGravity(entity, dir, delta) {
67
- if (entity.velocity[dir] < entity.terminalvelocity[dir] && entity.velocity[dir] > -entity.terminalvelocity[dir]) {
68
- entity.velocity[dir] = clamp(-entity.terminalvelocity[dir], entity.velocity[dir] + entity.gravity[dir] * delta, entity.terminalvelocity[dir]);
69
- }
70
- }
71
- function getFriction(vel, fric, delta) {
72
- return vel > 0 ? Math.max(0, vel - fric * delta) : Math.min(0, vel + fric * delta);
73
- }
74
- function clamp(a, b, c) {
75
- return Math.max(a, Math.min(b, c));
76
- }
77
47
  function addVelocityWithMax(current, newVel, max) {
78
48
  let x, y, z;
79
49
  if (current.x > max.x || current.x < -max.x)
@@ -286,18 +286,13 @@ const player = async function (player, serv, settings) {
286
286
  const viewDistance = (settings['view-distance'] ??= 8);
287
287
  const dimensionCodec = (0, dimensionCodec_1.getDimensionCodec)(MAX_HEIGHT, serv.supportFeature('dimensionDataIsAvailable'), settings.version);
288
288
  // const dimensionCodec = serv.mcData.loginPacket.dimensionCodec
289
- const worldState = serv.mcData.loginPacket.worldState;
290
- if (worldState) {
291
- worldState.gamemode = {
292
- 0: 'survival',
293
- 1: 'creative',
294
- 2: 'adventure',
295
- 3: 'spectator'
296
- }[player.gameMode];
297
- worldState.previousGamemode = player.prevGameMode;
298
- }
289
+ // 1.20.2+: dimension, level name and game mode of the world the player is in (a player saved in the nether joins the nether)
290
+ const worldState = serv.mcData.loginPacket.worldState
291
+ ? serv.worldState(player.world ?? serv.overworld, player.gameMode, player.prevGameMode)
292
+ : undefined;
299
293
  player._client.write('login', {
300
294
  ...serv.mcData.loginPacket, // for new fields
295
+ ...(worldState ? { worldState } : {}),
301
296
  entityId: player.id,
302
297
  isHardcore: player.gameMode === 0,
303
298
  gameMode: player.gameMode,
@@ -359,10 +354,7 @@ const player = async function (player, serv, settings) {
359
354
  }
360
355
  };
361
356
  function updateTime() {
362
- player._client.write('update_time', {
363
- age: [0, 0],
364
- time: [0, serv.time]
365
- });
357
+ player.sendTime();
366
358
  }
367
359
  player.setGameMode = (gameMode) => {
368
360
  if (gameMode !== player.gameMode)
@@ -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) {
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.player = void 0;
4
4
  const player = function (player, serv) {
5
- player._client.on('client_command', (data) => {
5
+ player._client.on('client_command', async (data) => {
6
6
  let actionId;
7
7
  if (serv.supportFeature('respawnIsPayload')) {
8
8
  actionId = data.payload;
@@ -11,7 +11,7 @@ const player = function (player, serv) {
11
11
  actionId = data.actionId;
12
12
  }
13
13
  if (actionId === 0) {
14
- player.position = player.spawnPoint;
14
+ player.position = await player.respawnPosition();
15
15
  player.behavior('requestRespawn', {}, () => {
16
16
  // the respawn point is in the overworld: a player who died in another world (nether, end, /mv world) really changes the world, not only the client's dimension
17
17
  const switchingWorld = player.world !== serv.overworld;
@@ -19,7 +19,7 @@ const player = function (player, serv) {
19
19
  player._unloadAllChunks();
20
20
  player.world = serv.overworld;
21
21
  }
22
- player._client.write('respawn', {
22
+ player._client.write('respawn', serv.supportFeature('spawnRespawnWorldDataField') ? { worldState: serv.worldState(serv.overworld, player.gameMode, player.prevGameMode, 0), copyMetadata: 0 } : {
23
23
  previousGameMode: player.prevGameMode,
24
24
  dimension: serv.supportFeature('dimensionIsAWorld') ? {
25
25
  type: 'compound',
@@ -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
+ }