@zardoy/flying-squid 0.0.132 → 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.
@@ -0,0 +1,48 @@
1
+ import { Vec3 } from 'vec3';
2
+ /**
3
+ * Axis aligned box physics for server side entities (items, mobs, projectiles).
4
+ *
5
+ * The old physics probed a single point per axis, so a falling item could end up inside a block and then keep sinking, and anything moving diagonally clipped corners. This
6
+ * moves the entity's box one axis at a time (y, x, z like vanilla) against the real collision shapes of the blocks it sweeps through:
7
+ * - unloaded chunks count as solid, nothing falls into the void while its chunk is not there,
8
+ * - an entity that starts inside blocks (spawned in a wall, a block was placed on it) is lifted out through the top,
9
+ * - liquids slow entities down and let light things float.
10
+ */
11
+ export type Box = [number, number, number, number, number, number];
12
+ export interface PhysicsWorld {
13
+ sync: {
14
+ getBlock(pos: Vec3): any;
15
+ };
16
+ }
17
+ export interface Body {
18
+ position: Vec3;
19
+ velocity: Vec3;
20
+ /** width (x), height (y), depth (z) */
21
+ size: Vec3;
22
+ /** m/s^2 on each axis (negative y = down) */
23
+ gravity?: Vec3;
24
+ terminalvelocity?: Vec3;
25
+ /** deceleration (m/s^2) of x / z while standing on something */
26
+ friction?: Vec3;
27
+ /** floats up in liquids (items, boats) */
28
+ buoyant?: boolean;
29
+ /** ignores liquid drag (flying mobs) */
30
+ flying?: boolean;
31
+ onGround?: boolean;
32
+ inWater?: boolean;
33
+ inLava?: boolean;
34
+ /** set by the step: velocity components that were stopped by a block */
35
+ hitX?: boolean;
36
+ hitY?: boolean;
37
+ hitZ?: boolean;
38
+ }
39
+ /** world space collision boxes of the blocks overlapping `aabb` */
40
+ export declare function collisionBoxes(world: PhysicsWorld, aabb: Box, out?: Box[]): Box[];
41
+ /** advances `body` by `dt` seconds; returns false when its chunk is not loaded (nothing moved) */
42
+ export declare function stepBody(world: PhysicsWorld, body: Body, dt: number): boolean;
43
+ /** first solid block face hit by the segment `from` -> `to` (swept point); `at` is the last free position before it */
44
+ export declare function raycastBlocks(world: PhysicsWorld, from: Vec3, to: Vec3): {
45
+ hit: boolean;
46
+ at: Vec3;
47
+ block?: Vec3;
48
+ };
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collisionBoxes = collisionBoxes;
4
+ exports.stepBody = stepBody;
5
+ exports.raycastBlocks = raycastBlocks;
6
+ const vec3_1 = require("vec3");
7
+ const EPS = 1e-7;
8
+ const FULL = [0, 0, 0, 1, 1, 1];
9
+ const boxesOfBlock = (block) => {
10
+ if (!block)
11
+ return [FULL];
12
+ const shapes = block.shapes;
13
+ if (shapes)
14
+ return shapes;
15
+ return block.boundingBox === 'block' ? [FULL] : [];
16
+ };
17
+ const tmp = new vec3_1.Vec3(0, 0, 0);
18
+ /** world space collision boxes of the blocks overlapping `aabb` */
19
+ function collisionBoxes(world, aabb, out = []) {
20
+ const x0 = Math.floor(aabb[0] + EPS);
21
+ const x1 = Math.floor(aabb[3] - EPS);
22
+ const y0 = Math.floor(aabb[1] + EPS);
23
+ const y1 = Math.floor(aabb[4] - EPS);
24
+ const z0 = Math.floor(aabb[2] + EPS);
25
+ const z1 = Math.floor(aabb[5] - EPS);
26
+ for (let y = y0; y <= y1; y++) {
27
+ for (let z = z0; z <= z1; z++) {
28
+ for (let x = x0; x <= x1; x++) {
29
+ tmp.set(x, y, z);
30
+ const block = world.sync.getBlock(tmp);
31
+ for (const s of boxesOfBlock(block))
32
+ out.push([x + s[0], y + s[1], z + s[2], x + s[3], y + s[4], z + s[5]]);
33
+ }
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ const overlapsOn = (a, b, skip) => {
39
+ for (let i = 0; i < 3; i++)
40
+ if (i !== skip && !(a[i] < b[i + 3] - EPS && a[i + 3] > b[i] + EPS))
41
+ return false;
42
+ return true;
43
+ };
44
+ const isLiquid = (block, name) => !!block && (block.name === name || (name === 'water' && (block.name === 'bubble_column' || block.name === 'seagrass' || block.name === 'tall_seagrass' || block.name === 'kelp' || block.name === 'kelp_plant')) || (block.name === 'flowing_' + name));
45
+ /** advances `body` by `dt` seconds; returns false when its chunk is not loaded (nothing moved) */
46
+ function stepBody(world, body, dt) {
47
+ dt = Math.min(dt, 0.1);
48
+ const { position: p, velocity: v, size } = body;
49
+ const hw = size.x / 2;
50
+ const hd = size.z / 2;
51
+ const h = size.y;
52
+ // the block the entity is in decides about liquids; an unloaded chunk freezes it
53
+ tmp.set(Math.floor(p.x), Math.floor(p.y + Math.min(h, 1) / 2), Math.floor(p.z));
54
+ const here = world.sync.getBlock(tmp);
55
+ if (!here)
56
+ return false;
57
+ body.inWater = isLiquid(here, 'water');
58
+ body.inLava = isLiquid(here, 'lava');
59
+ const liquid = (body.inWater || body.inLava) && !body.flying;
60
+ if (body.gravity) {
61
+ const g = liquid ? 0.15 : 1;
62
+ const t = body.terminalvelocity;
63
+ v.x += body.gravity.x * dt * g;
64
+ v.y += body.gravity.y * dt * g;
65
+ v.z += body.gravity.z * dt * g;
66
+ if (t) {
67
+ v.y = Math.max(-t.y, Math.min(t.y, v.y));
68
+ }
69
+ }
70
+ if (liquid) {
71
+ const drag = body.inLava ? 0.5 : 0.8;
72
+ v.x *= drag;
73
+ v.z *= drag;
74
+ v.y *= drag;
75
+ if (body.buoyant)
76
+ v.y = Math.min(2, v.y + 12 * dt);
77
+ }
78
+ let aabb = [p.x - hw, p.y, p.z - hd, p.x + hw, p.y + h, p.z + hd];
79
+ // started inside blocks: lift out through the top (at most a few blocks, so a wall of rock does not launch the entity into the sky)
80
+ const inside = collisionBoxes(world, [aabb[0] + 1e-3, aabb[1] + 1e-3, aabb[2] + 1e-3, aabb[3] - 1e-3, aabb[4] - 1e-3, aabb[5] - 1e-3]);
81
+ if (inside.length) {
82
+ let top = p.y;
83
+ for (let i = 0; i < 6; i++) {
84
+ const probe = [aabb[0] + 1e-3, top + 1e-3, aabb[2] + 1e-3, aabb[3] - 1e-3, top + h - 1e-3, aabb[5] - 1e-3];
85
+ const hits = collisionBoxes(world, probe);
86
+ if (!hits.length)
87
+ break;
88
+ top = Math.max(...hits.map(b => b[4]));
89
+ }
90
+ p.y = top;
91
+ if (v.y < 0)
92
+ v.y = 0;
93
+ aabb = [p.x - hw, p.y, p.z - hd, p.x + hw, p.y + h, p.z + hd];
94
+ }
95
+ body.hitX = body.hitY = body.hitZ = false;
96
+ let onGround = false;
97
+ const axes = [[1, 'y'], [0, 'x'], [2, 'z']];
98
+ for (const [i, k] of axes) {
99
+ let d = v[k] * dt;
100
+ if (d === 0)
101
+ continue;
102
+ const sweep = [...aabb];
103
+ if (d > 0)
104
+ sweep[i + 3] += d;
105
+ else
106
+ sweep[i] += d;
107
+ const boxes = collisionBoxes(world, sweep);
108
+ let clipped = false;
109
+ for (const b of boxes) {
110
+ if (!overlapsOn(aabb, b, i))
111
+ continue;
112
+ if (d > 0 && b[i] >= aabb[i + 3] - EPS) {
113
+ const gap = b[i] - aabb[i + 3];
114
+ if (gap < d) {
115
+ d = Math.max(0, gap);
116
+ clipped = true;
117
+ }
118
+ }
119
+ else if (d < 0 && b[i + 3] <= aabb[i] + EPS) {
120
+ const gap = b[i + 3] - aabb[i];
121
+ if (gap > d) {
122
+ d = Math.min(0, gap);
123
+ clipped = true;
124
+ }
125
+ }
126
+ }
127
+ p[k] += d;
128
+ aabb[i] += d;
129
+ aabb[i + 3] += d;
130
+ if (clipped) {
131
+ if (k === 'y') {
132
+ body.hitY = true;
133
+ if (v.y < 0)
134
+ onGround = true;
135
+ }
136
+ else if (k === 'x')
137
+ body.hitX = true;
138
+ else
139
+ body.hitZ = true;
140
+ v[k] = 0;
141
+ }
142
+ }
143
+ body.onGround = onGround;
144
+ if (onGround && body.friction && (v.x !== 0 || v.z !== 0)) {
145
+ const speed = Math.hypot(v.x, v.z);
146
+ const slow = Math.max(0, speed - Math.max(body.friction.x, body.friction.z) * dt);
147
+ const f = speed > 0 ? slow / speed : 0;
148
+ v.x *= f;
149
+ v.z *= f;
150
+ if (Math.abs(v.x) < 1e-3)
151
+ v.x = 0;
152
+ if (Math.abs(v.z) < 1e-3)
153
+ v.z = 0;
154
+ }
155
+ return true;
156
+ }
157
+ /** first solid block face hit by the segment `from` -> `to` (swept point); `at` is the last free position before it */
158
+ function raycastBlocks(world, from, to) {
159
+ const d = to.minus(from);
160
+ const len = d.norm();
161
+ if (len === 0)
162
+ return { hit: false, at: from.clone() };
163
+ const steps = Math.ceil(len / 0.2);
164
+ let last = from.clone();
165
+ for (let i = 1; i <= steps; i++) {
166
+ const pt = from.plus(d.scaled(i / steps));
167
+ tmp.set(Math.floor(pt.x), Math.floor(pt.y), Math.floor(pt.z));
168
+ const block = world.sync.getBlock(tmp);
169
+ if (!block)
170
+ return { hit: true, at: last, block: tmp.clone() };
171
+ for (const s of boxesOfBlock(block)) {
172
+ if (pt.x >= tmp.x + s[0] && pt.x <= tmp.x + s[3] && pt.y >= tmp.y + s[1] && pt.y <= tmp.y + s[4] && pt.z >= tmp.z + s[2] && pt.z <= tmp.z + s[5])
173
+ return { hit: true, at: last, block: tmp.clone() };
174
+ }
175
+ last = pt;
176
+ }
177
+ return { hit: false, at: to.clone() };
178
+ }
@@ -1,4 +1,5 @@
1
1
  export declare const server: (serv: Server) => void;
2
+ export declare const player: (player: Player, serv: Server) => void;
2
3
  declare global {
3
4
  interface Server {
4
5
  /** Set daylight cycle time in ticks. See `serv.time` for more info. */
@@ -9,5 +10,11 @@ declare global {
9
10
  * Resets to 0 at 24000. Use {@link setTime `serv.setTime(time)`} to set the time.
10
11
  */
11
12
  'time': number;
13
+ /** time of day the players of `world` see (the End is always night) */
14
+ worldTime: (world: any) => number;
15
+ }
16
+ interface Player {
17
+ /** sends the time of day of the player's world */
18
+ sendTime: () => void;
12
19
  }
13
20
  }
@@ -1,13 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.server = void 0;
3
+ exports.player = exports.server = void 0;
4
+ /** the End has no day: its players always see the night sky (vanilla: a fixed dark sky) */
5
+ const END_TIME = 18000;
4
6
  const server = function (serv) {
7
+ /** time of day shown to the players of `world` */
8
+ serv.worldTime = (world) => (world?.environment === 'end' ? END_TIME : serv.time);
5
9
  serv.setTime = (time) => {
6
10
  serv.time = time;
7
- serv._writeAll('update_time', {
8
- age: [0, 0], // TODO
9
- time: [0, serv.time]
10
- });
11
+ for (const player of serv.players)
12
+ player.sendTime();
11
13
  };
12
14
  serv.doDaylightCycle ??= true;
13
15
  serv.time ??= 0;
@@ -90,3 +92,12 @@ const server = function (serv) {
90
92
  });
91
93
  };
92
94
  exports.server = server;
95
+ const player = function (player, serv) {
96
+ player.sendTime = () => {
97
+ player._client.write('update_time', {
98
+ age: [0, 0], // TODO
99
+ time: [0, serv.worldTime(player.world)]
100
+ });
101
+ };
102
+ };
103
+ exports.player = player;
@@ -0,0 +1,17 @@
1
+ import { Vec3 } from 'vec3';
2
+ export declare const server: (serv: Server, options: Options) => void;
3
+ declare global {
4
+ interface Server {
5
+ endFight: {
6
+ readonly dragon?: Entity;
7
+ readonly crystals: Entity[];
8
+ readonly killed: boolean;
9
+ };
10
+ /** 5x5 obsidian platform where players arrive in the End (100, 48, 0) */
11
+ makeEndPlatform: () => Promise<void>;
12
+ /** exit portal (bedrock fountain, torches, optionally the dragon egg) on the middle island */
13
+ buildExitPortal: (world: any, egg?: boolean) => Promise<void>;
14
+ /** an entity without own physics and without item data (end crystals) */
15
+ spawnPlain: (names: string[], world: any, position: Vec3, velocity: Vec3, owner?: Entity, size?: number) => Entity | undefined;
16
+ }
17
+ }
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.server = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const vec3_1 = require("vec3");
10
+ const endSpikes_1 = require("minecraft-worldgen/dist/feature/endSpikes");
11
+ const random_1 = require("minecraft-worldgen/dist/rng/random");
12
+ const bossBars_1 = require("./bossBars");
13
+ /**
14
+ * The End: arrival platform, end crystals on the ten obsidian pillars, the ender dragon and what happens after it dies.
15
+ *
16
+ * Simplified compared to vanilla:
17
+ * - the dragon circles above the island (radius 32, about 10 blocks/s) and now and then dives at a player (10 damage on contact, knockback); it stays within 60 blocks of the centre; it does not perch, breathe or destroy blocks,
18
+ * - each crystal within 32 blocks heals it 2 hp per second; breaking a crystal blows up (power 6, capped damage) and the dragon hurts,
19
+ * - the first kill gives 12000 xp (500 later) and builds the exit portal with the dragon egg; the portal leads back to the overworld (no credits),
20
+ * - the fight starts when a player is in the End and the dragon was not killed in this world before (`flyingsquid-end.json` in the world folder).
21
+ */
22
+ const SPAWN_HEIGHT = 128;
23
+ /** flight circle around the middle island (the island is ~100 blocks wide), the furthest it may drift, and the furthest a dive may reach */
24
+ const CIRCLE_RADIUS = 32;
25
+ const LEASH_RADIUS = 60;
26
+ const ISLAND_RADIUS = 48;
27
+ const server = function (serv, options) {
28
+ const mcData = serv.mcData;
29
+ const flat = serv.supportFeature('theFlattening');
30
+ const block = (name) => mcData.blocksByName[name];
31
+ const stateFile = options.worldFolder && !options.noWorldRegion ? path_1.default.join(options.worldFolder, 'flyingsquid-end.json') : undefined;
32
+ const state = { dragonKilled: false };
33
+ try {
34
+ if (stateFile)
35
+ Object.assign(state, JSON.parse(fs_1.default.readFileSync(stateFile, 'utf8')));
36
+ }
37
+ catch { }
38
+ const save = () => { if (stateFile)
39
+ fs_1.default.promises.writeFile(stateFile, JSON.stringify(state)).catch(() => { }); };
40
+ const fight = { crystals: [], starting: false, ticksSinceHeal: 0 };
41
+ serv.endFight = {
42
+ get dragon() { return fight.dragon; },
43
+ get crystals() { return fight.crystals; },
44
+ get killed() { return state.dragonKilled; }
45
+ };
46
+ const setBlockName = async (world, x, y, z, name, props) => {
47
+ const b = block(name);
48
+ if (!b)
49
+ return;
50
+ let stateId = flat ? b.minStateId : b.id << 4;
51
+ if (props && flat) {
52
+ const Block = serv.PrismarineBlock;
53
+ try {
54
+ stateId = Block.fromProperties(name, props, 0).stateId;
55
+ }
56
+ catch { }
57
+ }
58
+ await serv.setBlock(world, new vec3_1.Vec3(x, y, z), stateId);
59
+ };
60
+ // ---------------------------------------------------------------- arrival platform (ServerLevel.makeObsidianPlatform)
61
+ serv.makeEndPlatform = async () => {
62
+ const world = serv.endworld;
63
+ await world.getColumn(6, 0);
64
+ for (let dx = -2; dx <= 2; dx++) {
65
+ for (let dz = -2; dz <= 2; dz++) {
66
+ await setBlockName(world, 100 + dx, 48, dz, 'obsidian');
67
+ for (let dy = 1; dy <= 3; dy++)
68
+ await setBlockName(world, 100 + dx, 48 + dy, dz, 'air');
69
+ }
70
+ }
71
+ };
72
+ // ---------------------------------------------------------------- starting the fight
73
+ async function startFight() {
74
+ if (fight.starting || fight.dragon || state.dragonKilled)
75
+ return;
76
+ fight.starting = true;
77
+ try {
78
+ const world = serv.endworld;
79
+ const spikes = (0, endSpikes_1.spikesFor)((0, random_1.parseWorldSeed)(world.seed ?? serv.seed ?? 0));
80
+ // the pillars (and the island) have to exist before crystals float above them
81
+ const chunks = new Set(['0,0']);
82
+ for (const s of spikes)
83
+ chunks.add(`${s.cx >> 4},${s.cz >> 4}`);
84
+ await Promise.all([...chunks].map(c => { const [x, z] = c.split(',').map(Number); return world.getColumn(x, z); }));
85
+ for (const s of spikes) {
86
+ const crystal = serv.spawnPlain(['end_crystal', 'endercrystal', 'ender_crystal'], world, new vec3_1.Vec3(s.cx + 0.5, s.height + 1, s.cz + 0.5), new vec3_1.Vec3(0, 0, 0), undefined, 2);
87
+ if (!crystal)
88
+ continue;
89
+ crystal.health = 1;
90
+ crystal.maxHealth = 1;
91
+ crystal.persistent = true;
92
+ crystal.name = 'end_crystal';
93
+ fight.crystals.push(crystal);
94
+ }
95
+ const typeId = serv.entityTypeId(['ender_dragon', 'enderdragon'], 'mob');
96
+ if (typeId === undefined)
97
+ return;
98
+ const dragon = serv.spawnMob(typeId, world, new vec3_1.Vec3(0, SPAWN_HEIGHT, 0), {});
99
+ dragon.name = 'ender_dragon';
100
+ dragon.persistent = true;
101
+ dragon.customMotion = true;
102
+ dragon.noGravity = true;
103
+ dragon.deathAnimationMs = 10_000;
104
+ dragon.ai = { kind: 'dragon', def: serv.mobDefs.ender_dragon, state: { angle: Math.random() * Math.PI * 2, phase: 'circle', nextDive: Date.now() + 12_000 } };
105
+ fight.dragon = dragon;
106
+ fight.bar = serv.createBossBar(undefined, 'Ender Dragon', 1, bossBars_1.BossBarColor.PURPLE, bossBars_1.BossBarDividers.NONE, bossBars_1.BossBarFlags.DRAGON_BAR);
107
+ }
108
+ finally {
109
+ fight.starting = false;
110
+ }
111
+ }
112
+ // ---------------------------------------------------------------- the dragon each tick
113
+ const toByte = (deg) => { let b = Math.floor(((deg % 360) + 360) % 360 * 256 / 360); if (b > 127)
114
+ b -= 256; return b; };
115
+ let tickNo = 0;
116
+ serv.on('tick', () => {
117
+ tickNo++;
118
+ const world = serv.endworld;
119
+ const inEnd = serv.players.filter(p => p.world === world);
120
+ if (inEnd.length && !fight.dragon && !state.dragonKilled && !fight.starting)
121
+ void startFight();
122
+ const dragon = fight.dragon;
123
+ if (!dragon || !serv.entities[dragon.id]) {
124
+ if (dragon && !serv.entities[dragon.id])
125
+ fight.dragon = undefined;
126
+ return;
127
+ }
128
+ if (dragon.dead)
129
+ return;
130
+ const dt = 0.05;
131
+ const ai = dragon.ai;
132
+ const s = ai.state;
133
+ const now = Date.now();
134
+ const targets = inEnd.filter(p => (p.gameMode === 0 || p.gameMode === 2) && p.health > 0);
135
+ // phases: circle the island, now and then dive at the nearest player and fly out again
136
+ let goal;
137
+ let speed = 11;
138
+ if (s.phase === 'dive' && targets.length) {
139
+ const t = s.target && targets.includes(s.target) ? s.target : targets[0];
140
+ s.target = t;
141
+ // never further out than the island: a player on the edge is attacked from above the edge
142
+ const gx = t.position.x;
143
+ const gz = t.position.z;
144
+ const out = Math.hypot(gx, gz);
145
+ const k = out > ISLAND_RADIUS ? ISLAND_RADIUS / out : 1;
146
+ goal = new vec3_1.Vec3(gx * k, Math.max(t.position.y + 1, 62), gz * k);
147
+ speed = 18;
148
+ if (dragon.position.distanceTo(goal) < 5 || now - s.diveStart > 7000) {
149
+ s.phase = 'circle';
150
+ s.nextDive = now + 15_000 + Math.random() * 10_000;
151
+ s.angle = Math.atan2(dragon.position.z, dragon.position.x);
152
+ }
153
+ }
154
+ else {
155
+ s.phase = 'circle';
156
+ // the goal on the circle moves at ~8 blocks/s; the dragon follows it with a little lag
157
+ s.angle += (8 / CIRCLE_RADIUS) * dt;
158
+ goal = new vec3_1.Vec3(Math.cos(s.angle) * CIRCLE_RADIUS, 80 + Math.sin(s.angle * 2.3) * 8, Math.sin(s.angle) * CIRCLE_RADIUS);
159
+ if (targets.length && now > s.nextDive) {
160
+ s.phase = 'dive';
161
+ s.diveStart = now;
162
+ }
163
+ }
164
+ // leash: whatever happened, it comes back when it is far from the island
165
+ if (Math.hypot(dragon.position.x, dragon.position.z) > LEASH_RADIUS) {
166
+ goal = new vec3_1.Vec3(Math.cos(s.angle) * CIRCLE_RADIUS, 80, Math.sin(s.angle) * CIRCLE_RADIUS);
167
+ speed = 16;
168
+ s.phase = 'circle';
169
+ }
170
+ const to = goal.minus(dragon.position);
171
+ const dist = to.norm();
172
+ const v = dist > 0.01 ? to.scaled(Math.min(speed, dist * 3) / dist) : new vec3_1.Vec3(0, 0, 0);
173
+ // turn smoothly: the velocity follows the wanted one
174
+ dragon.velocity.x += (v.x - dragon.velocity.x) * 0.12;
175
+ dragon.velocity.y += (v.y - dragon.velocity.y) * 0.12;
176
+ dragon.velocity.z += (v.z - dragon.velocity.z) * 0.12;
177
+ const next = dragon.position.plus(dragon.velocity.scaled(dt));
178
+ void dragon.sendPosition(next, false);
179
+ if (Math.hypot(dragon.velocity.x, dragon.velocity.z) > 1) {
180
+ // the dragon model looks the other way round
181
+ const yaw = Math.atan2(-dragon.velocity.x, dragon.velocity.z) * 180 / Math.PI + 180;
182
+ if (tickNo % 4 === 0) {
183
+ dragon.yawDeg = yaw;
184
+ dragon.yaw = yaw;
185
+ dragon._writeOthersNearby('entity_look', { entityId: dragon.id, yaw: toByte(yaw), pitch: 0, onGround: false });
186
+ dragon._writeOthersNearby('entity_head_rotation', { entityId: dragon.id, headYaw: toByte(yaw) });
187
+ }
188
+ }
189
+ // bumping into players
190
+ if (tickNo % 4 === 0) {
191
+ for (const p of targets) {
192
+ const dx = p.position.x - dragon.position.x;
193
+ const dz = p.position.z - dragon.position.z;
194
+ if (Math.hypot(dx, dz) < 8 && p.position.y + 1.8 > dragon.position.y - 2 && p.position.y < dragon.position.y + 6) {
195
+ serv.hurt(p, 10, { source: dragon, from: dragon.position, knockback: 14 });
196
+ }
197
+ }
198
+ }
199
+ // crystals heal the dragon
200
+ fight.crystals = fight.crystals.filter(c => serv.entities[c.id] && !c.dead);
201
+ if (tickNo % 10 === 0 && fight.crystals.some(c => c.position.distanceTo(dragon.position) < 40) && dragon.health < (dragon.maxHealth ?? 200)) {
202
+ dragon.health = Math.min(dragon.maxHealth ?? 200, dragon.health + 1);
203
+ }
204
+ if (fight.bar && tickNo % 10 === 0)
205
+ serv.updateBossBar(fight.bar, { health: Math.max(0, dragon.health / (dragon.maxHealth ?? 200)) });
206
+ });
207
+ // ---------------------------------------------------------------- crystals blow up, the dragon dies
208
+ serv.on('mobDied', (mob, killer) => {
209
+ if (mob.name === 'end_crystal') {
210
+ fight.crystals = fight.crystals.filter(c => c !== mob);
211
+ void serv.explode(mob.world, mob.position.offset(0, 0.5, 0), 6, { source: mob, maxDamage: 14 });
212
+ // the bedrock under it burns: the fire above it is gone with the crystal
213
+ return;
214
+ }
215
+ if (mob !== fight.dragon)
216
+ return;
217
+ const first = !state.dragonKilled;
218
+ state.dragonKilled = true;
219
+ save();
220
+ if (fight.bar) {
221
+ serv.removeBossBar(fight.bar);
222
+ fight.bar = undefined;
223
+ }
224
+ for (const c of fight.crystals)
225
+ c.destroy();
226
+ fight.crystals = [];
227
+ const players = serv.players.filter(p => p.world === mob.world);
228
+ // the dragon falls apart after its death animation; the xp goes to every player in the End
229
+ mob.setTimeout(() => {
230
+ for (const p of players)
231
+ if (serv.players.includes(p))
232
+ p.setXp(p.xp + (first ? 12000 : 500));
233
+ void buildExitPortal(mob.world, first);
234
+ serv.broadcast?.('§dThe Ender Dragon has been defeated!', { whitelist: serv.players.filter(p => p.world === mob.world) });
235
+ fight.dragon = undefined;
236
+ }, 9500);
237
+ });
238
+ // ---------------------------------------------------------------- exit portal + egg (EndPodiumFeature)
239
+ async function buildExitPortal(world, egg) {
240
+ await world.getColumn(0, 0);
241
+ // the podium sits on the island surface in the middle
242
+ let y0 = 64;
243
+ for (let y = 120; y > 30; y--) {
244
+ if ((await world.getBlockType(new vec3_1.Vec3(0, y, 0))) !== 0) {
245
+ y0 = y + 1;
246
+ break;
247
+ }
248
+ }
249
+ for (let dx = -4; dx <= 4; dx++) {
250
+ for (let dz = -4; dz <= 4; dz++) {
251
+ const d2 = dx * dx + dz * dz;
252
+ if (d2 > 3.5 * 3.5)
253
+ continue;
254
+ for (let y = y0 - 1; y <= y0 + 8; y++) {
255
+ if (y < y0)
256
+ await setBlockName(world, dx, y, dz, 'bedrock');
257
+ else if (y > y0)
258
+ await setBlockName(world, dx, y, dz, 'air');
259
+ else if (d2 > 2.5 * 2.5)
260
+ await setBlockName(world, dx, y, dz, 'bedrock');
261
+ else
262
+ await setBlockName(world, dx, y, dz, 'end_portal');
263
+ }
264
+ }
265
+ }
266
+ for (let i = 0; i < 3; i++)
267
+ await setBlockName(world, 0, y0 + i, 0, 'bedrock');
268
+ const torch = block('wall_torch') ? 'wall_torch' : 'torch';
269
+ for (const [dx, dz, facing] of [[0, -1, 'north'], [0, 1, 'south'], [-1, 0, 'west'], [1, 0, 'east']])
270
+ await setBlockName(world, dx, y0 + 2, dz, torch, { facing });
271
+ await setBlockName(world, 0, y0 + 3, 0, 'bedrock');
272
+ if (egg)
273
+ await setBlockName(world, 0, y0 + 4, 0, 'dragon_egg');
274
+ }
275
+ serv.buildExitPortal = (world, egg = false) => buildExitPortal(world, egg);
276
+ serv.commands.add({
277
+ base: 'enderfight',
278
+ info: 'Starts / resets the ender dragon fight',
279
+ usage: '/enderfight <start|reset|state>',
280
+ op: true,
281
+ parse: (str) => (['start', 'reset', 'state'].includes(str.trim()) ? str.trim() : false),
282
+ async action(what) {
283
+ if (what === 'state')
284
+ return `dragon: ${fight.dragon ? Math.round(fight.dragon.health) + ' hp' : 'none'}, crystals: ${fight.crystals.length}, killed before: ${state.dragonKilled}`;
285
+ if (what === 'reset') {
286
+ state.dragonKilled = false;
287
+ save();
288
+ return 'The dragon will come back the next time somebody is in the End (kill the current one first).';
289
+ }
290
+ state.dragonKilled = false;
291
+ if (fight.dragon)
292
+ return 'The fight is running';
293
+ await startFight();
294
+ return 'The fight started';
295
+ }
296
+ });
297
+ };
298
+ exports.server = server;
@@ -33,16 +33,15 @@ const server = function (serv) {
33
33
  // entity.friction = new Vec3(0.6, 0.6, 0.6)
34
34
  // entity.terminalvelocity = new Vec3(27, 27, 27)
35
35
  // }
36
- if (!entity.velocity || !entity.size)
36
+ // every half second (spread over the ticks by id) the clients get the absolute position of moving mobs and objects: clients that predict movement themselves drift (see sendAbsolute)
37
+ if (entity.type !== 'player' && entity.velocity && (serv.tickCount + entity.id) % 10 === 0 && (!entity.onGround || entity.velocity.norm() > 0.01))
38
+ entity.sendAbsolute();
39
+ if (!entity.velocity || !entity.size || entity.customMotion)
37
40
  return;
38
41
  const { position, onGround } = await entity.calculatePhysics(delta);
39
- if (entity.type === 'mob' ||
40
- entity.type === 'player' ||
41
- (entity.type === 'object' &&
42
- (entity.velocity.x !== 0 ||
43
- entity.velocity.y !== 0 ||
44
- entity.velocity.z !== 0)))
45
- entity.sendPosition(position, onGround);
42
+ // sendPosition does nothing when neither the position nor onGround changed; an object that just landed has no velocity left but still has to be moved
43
+ if (entity.type === 'mob' || entity.type === 'player' || entity.type === 'object')
44
+ await entity.sendPosition(position, onGround);
46
45
  }))
47
46
  .then(() => { ticking = false; })
48
47
  .catch((err) => setTimeout(() => { throw err; }, 0));
@@ -22,6 +22,7 @@ module.exports = {
22
22
  'digging': require('./digging'),
23
23
  'dimensionCodec': require('./dimensionCodec'),
24
24
  'effects': require('./effects'),
25
+ 'endFight': require('./endFight'),
25
26
  'entities': require('./entities'),
26
27
  'errorHandler': require('./errorHandler'),
27
28
  'experience': require('./experience'),
@@ -37,6 +38,7 @@ module.exports = {
37
38
  'log': require('./log'),
38
39
  'logout': require('./logout'),
39
40
  'maps': require('./maps'),
41
+ 'mobs': require('./mobs'),
40
42
  'moderation': require('./moderation'),
41
43
  'particle': require('./particle'),
42
44
  'physics': require('./physics'),
@@ -45,6 +47,7 @@ module.exports = {
45
47
  'players': require('./players'),
46
48
  'pluginsFolder': require('./pluginsFolder'),
47
49
  'portal': require('./portal'),
50
+ 'projectiles': require('./projectiles'),
48
51
  'pvp': require('./pvp'),
49
52
  'recipes': require('./recipes'),
50
53
  'redstone': require('./redstone'),
@@ -57,6 +60,7 @@ module.exports = {
57
60
  'smelting': require('./smelting'),
58
61
  'sound': require('./sound'),
59
62
  'spawn': require('./spawn'),
63
+ 'spawners': require('./spawners'),
60
64
  'stats': require('./stats'),
61
65
  'tabComplete': require('./tabComplete'),
62
66
  'tick': require('./tick'),