Send chunks to players connected to server
This commit is contained in:
@@ -110,6 +110,7 @@ Deno.test("the server loads every .bmod in its folder, dependencies first, and p
|
||||
assertEquals([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), mod.listing.sha256);
|
||||
const copy = read_bmod(mod.client_bytes, mod.listing.file);
|
||||
assertEquals(copy.scripts.server, undefined, "server scripts never go to players");
|
||||
assertEquals(copy.scripts.worldgen, undefined, "players get the world from the server, not its generator");
|
||||
assertEquals(copy.data, mod.bmod.data);
|
||||
}
|
||||
assert(mods[1].bmod.scripts.server, "the server still has it");
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// the server sends the world in whole chunks, like minecraft java: nearest first, in batches the client paces, and
|
||||
// only to players who can see them
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
|
||||
import { decode_level_chunk, encode_level_chunk, is_within_view } from "$/common/chunk_streaming.ts";
|
||||
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
|
||||
import { sent_block, test_game } from "./helpers.ts";
|
||||
|
||||
Deno.test("a chunk comes back as it was encoded, whatever its sections hold", () => {
|
||||
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
const section = CHUNK_AREA * 16;
|
||||
// section 0 is all one block, 1 has 3 kinds, 2 has 16, 3 has 300 (more than a palette holds), the rest air
|
||||
blocks.fill(7, 0, section);
|
||||
for (let i = 0; i < section; i++) {
|
||||
blocks[section + i] = [1, 2 | (3 << 16), 5][i % 3];
|
||||
blocks[2 * section + i] = i % 16;
|
||||
blocks[3 * section + i] = (i % 300) | ((i % 7) << 16);
|
||||
}
|
||||
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => i < 100 ? "bworld:plains" : "bworld:desert");
|
||||
|
||||
const decoded = decode_level_chunk(encode_level_chunk({ x: -3, z: 70000, blocks, biomes }));
|
||||
assertEquals(decoded.x, -3);
|
||||
assertEquals(decoded.z, 70000);
|
||||
assertEquals(decoded.blocks, blocks);
|
||||
assertEquals(decoded.biomes, biomes);
|
||||
|
||||
// one biome, and the receiver's numbering
|
||||
const one = decode_level_chunk(
|
||||
encode_level_chunk({ x: 0, z: 0, blocks, biomes: biomes.map(() => "bworld:plains") }),
|
||||
(value) => value === 7 ? 70 : value,
|
||||
);
|
||||
assertEquals(one.biomes, biomes.map(() => "bworld:plains"));
|
||||
assertEquals(one.blocks[0], 70);
|
||||
assertEquals(one.blocks[section], 1);
|
||||
});
|
||||
|
||||
Deno.test("the view is round, with a ring of chunks past it for meshing its edge", () => {
|
||||
assert(is_within_view(0, 0, 2, 0, 0));
|
||||
assert(is_within_view(0, 0, 2, 3, 0), "the outer ring");
|
||||
assert(!is_within_view(0, 0, 2, 3, 0, false));
|
||||
assert(!is_within_view(0, 0, 2, 4, 0));
|
||||
assert(is_within_view(0, 0, 2, 2, 2));
|
||||
assert(!is_within_view(0, 0, 2, 3, 3), "corners are cut off");
|
||||
assert(is_within_view(10, -10, 2, 12, -12));
|
||||
});
|
||||
|
||||
// every chunk around cx, cz a view distance of 2 covers
|
||||
function view(cx: number, cz: number) {
|
||||
const chunks: string[] = [];
|
||||
for (let x = cx - 4; x <= cx + 4; x++) {
|
||||
for (let z = cz - 4; z <= cz + 4; z++) {
|
||||
if (is_within_view(cx, cz, 2, x, z)) chunks.push(`${x},${z}`);
|
||||
}
|
||||
}
|
||||
return chunks.sort();
|
||||
}
|
||||
|
||||
Deno.test("chunks come in batches, nearest first, as fast as the client says it can take them", async () => {
|
||||
const { game, take, send } = await test_game("mods");
|
||||
game.on_connect(1);
|
||||
send(1, { type: "hello", name: "alice", protocol: PROTOCOL_VERSION });
|
||||
send(1, { type: "ready", view_distance: 2 });
|
||||
send(1, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 });
|
||||
const joined = take(1);
|
||||
assert(joined.some((m) => m.type === "set_center_chunk" && m.x === 0 && m.z === 0));
|
||||
assert(!joined.some((m) => m.type === "level_chunk"), "chunks come with ticks");
|
||||
|
||||
// the first batch before the client has said anything: minecraft's 9 chunks
|
||||
game.tick();
|
||||
let messages = take(1).filter((m) => m.type.includes("chunk"));
|
||||
assertEquals(messages[0].type, "chunk_batch_start");
|
||||
assertEquals(messages.at(-1), { type: "chunk_batch_finished", size: 9 });
|
||||
const first = messages.filter((m) => m.type === "level_chunk");
|
||||
assertEquals(first.length, 9);
|
||||
assertEquals(`${first[0].x},${first[0].z}`, "0,0");
|
||||
for (const chunk of first) assert(Math.abs(chunk.x) <= 1 && Math.abs(chunk.z) <= 1, "nearest first");
|
||||
|
||||
// nothing more until the client has it
|
||||
game.tick();
|
||||
assertEquals(take(1).filter((m) => m.type === "level_chunk"), []);
|
||||
|
||||
// then the rest, each chunk in view once
|
||||
const sent = first.map((m) => `${m.x},${m.z}`);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
send(1, { type: "chunk_batch_received", chunks_per_tick: 4 });
|
||||
game.tick();
|
||||
messages = take(1).filter((m) => m.type === "level_chunk");
|
||||
assert(messages.length <= 4);
|
||||
sent.push(...messages.map((m) => `${m.x},${m.z}`));
|
||||
}
|
||||
assertEquals(sent.sort(), view(0, 0));
|
||||
|
||||
// walking off: a new center, the chunks out of view are forgotten and the new ones come
|
||||
send(1, { type: "move", x: 8 + 16 * 3, y: 100, z: 8, yaw: 0, pitch: 0 });
|
||||
messages = take(1);
|
||||
assertEquals(messages.find((m) => m.type === "set_center_chunk"), { type: "set_center_chunk", x: 3, z: 0 });
|
||||
const forgotten = messages.filter((m) => m.type === "forget_level_chunk").map((m) => `${m.x},${m.z}`);
|
||||
assertEquals(forgotten.sort(), view(0, 0).filter((key) => !view(3, 0).includes(key)));
|
||||
const more: string[] = [];
|
||||
for (let i = 0; i < 20; i++) {
|
||||
send(1, { type: "chunk_batch_received", chunks_per_tick: 64 });
|
||||
game.tick();
|
||||
more.push(...take(1).filter((m) => m.type === "level_chunk").map((m) => `${m.x},${m.z}`));
|
||||
}
|
||||
assertEquals(more.sort(), view(3, 0).filter((key) => !view(0, 0).includes(key)));
|
||||
});
|
||||
|
||||
Deno.test("block changes only go to players who have the chunk, the others get them with it", async () => {
|
||||
const { game, take, send, join } = await test_game("mods");
|
||||
const alice = join(1, "alice");
|
||||
send(1, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 });
|
||||
const bob = join(2, "bob");
|
||||
send(2, { type: "move", x: 8 + 16 * 100, y: 100, z: 8, yaw: 0, pitch: 0 });
|
||||
game.tick();
|
||||
take(1);
|
||||
take(2);
|
||||
|
||||
game.set_block(3, 120, 5, "bworld:stone");
|
||||
assert(take(1).some((m) => m.type === "set_block" && m.x === 3 && m.id === "bworld:stone"));
|
||||
assertEquals(take(2).filter((m) => m.type === "set_block"), [], "bob is too far away to have it");
|
||||
|
||||
// bob walks over and gets the chunk with the stone in it
|
||||
send(2, { type: "move", x: 8, y: 100, z: 8, yaw: 0, pitch: 0 });
|
||||
send(2, { type: "chunk_batch_received", chunks_per_tick: 9 });
|
||||
game.tick();
|
||||
assertEquals(sent_block(take(2), bob, 3, 120, 5), ["bworld:stone", 0]);
|
||||
|
||||
// the chunk the server sends is what it has, with the ids join listed
|
||||
assertEquals(alice.blocks[game.world.block_ids["bworld:stone"]], "bworld:stone");
|
||||
const chunk = decode_level_chunk(game.world.level_chunk(0, 0));
|
||||
assertEquals(chunk.blocks[120 * CHUNK_AREA + 5 * CHUNK_SIZE + 3], game.world.get_block_value(3, 120, 5));
|
||||
});
|
||||
+20
-2
@@ -5,6 +5,8 @@ import type { ServerModSource } from "$/server/game/load_mods.ts";
|
||||
import { GameServer } from "$/server/game/game_server.ts";
|
||||
import { start_game } from "$/server/game/load_mods.ts";
|
||||
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
|
||||
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
||||
import type { WorldSave } from "$/server/game/saves.ts";
|
||||
|
||||
// mods straight from their source folders, skipping the build: scripts are imported as typescript
|
||||
@@ -45,9 +47,12 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
|
||||
// what host.download gives back, by url. other urls fail
|
||||
const downloads = new Map<string, Uint8Array>();
|
||||
const host = {
|
||||
send: (conn: number, data: string) => {
|
||||
// chunks come out decoded, as { type: "level_chunk", x, z, blocks, biomes }
|
||||
send: (conn: number, data: string | Uint8Array) => {
|
||||
if (!outbox.has(conn)) outbox.set(conn, []);
|
||||
outbox.get(conn)!.push(JSON.parse(data));
|
||||
outbox.get(conn)!.push(
|
||||
typeof data === "string" ? JSON.parse(data) : { type: "level_chunk", ...decode_level_chunk(data) },
|
||||
);
|
||||
},
|
||||
close(conn: number) {
|
||||
closed.add(conn);
|
||||
@@ -58,6 +63,7 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
|
||||
},
|
||||
};
|
||||
const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir));
|
||||
game.chunk_send_budget_ms = Infinity;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const take = (conn: number): any[] => {
|
||||
const messages = outbox.get(conn) ?? [];
|
||||
@@ -75,6 +81,18 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
|
||||
return { game, take, send, join, closed, downloads };
|
||||
}
|
||||
|
||||
// the block id and state bits at x, y, z in the chunks among messages, read the way a client does with the table
|
||||
// join sent. undefined when no chunk there was sent
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export function sent_block(messages: any[], join: { blocks: string[] }, x: number, y: number, z: number) {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const chunk = messages.findLast((m) => m.type === "level_chunk" && m.x === chunk_x && m.z === chunk_z);
|
||||
if (!chunk) return undefined;
|
||||
const value = chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
||||
return [join.blocks[value & ID_MASK], value >>> 16];
|
||||
}
|
||||
|
||||
export function copy_dir(from: string, to: string) {
|
||||
if (Deno.statSync(from).isDirectory) {
|
||||
Deno.mkdirSync(to, { recursive: true });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
import { copy_dir, sent_block, test_game } from "./helpers.ts";
|
||||
import type { WorldSave } from "$/server/game/saves.ts";
|
||||
|
||||
// a mod that uses every part of the server api worth testing, and writes down what happened in its storage
|
||||
@@ -218,6 +218,8 @@ Deno.test("block states start at their defaults, can be changed, and are synced
|
||||
send(1, { type: "chat", text: `/state ${args}` });
|
||||
return take(1).filter((m) => m.type === "chat").map((m) => m.text).at(-1);
|
||||
};
|
||||
// alice gets the chunks around her, and from then on changes to them
|
||||
game.tick();
|
||||
game.set_block(5, 100, 5, "testmod:lamp");
|
||||
take(1);
|
||||
assertEquals(state("5 100 5 power"), "state 2");
|
||||
@@ -232,13 +234,15 @@ Deno.test("block states start at their defaults, can be changed, and are synced
|
||||
assert(state("5 100 5 power 8").startsWith('error testmod:lamp state "power" has 3 bits'));
|
||||
assert(state("5 100 5 color").startsWith('error testmod:lamp has no state "color"'));
|
||||
|
||||
// saved and loaded, and new players get it with the world's changes
|
||||
// saved and loaded, and new players get it in the chunk
|
||||
const saved = game.save();
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const again = await setup(saved);
|
||||
assertEquals(again.game.world.get_block_value(5, 100, 5) >>> 16, 5 | (1 << 3));
|
||||
const joined = again.join(2, "bob");
|
||||
assert(joined.changes.some((c: unknown[]) => c[0] === 5 && c[3] === "testmod:lamp" && c[4] === (5 | (1 << 3))));
|
||||
again.send(2, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
||||
again.game.tick();
|
||||
assertEquals(sent_block(again.take(2), joined, 5, 100, 5), ["testmod:lamp", 5 | (1 << 3)]);
|
||||
Deno.removeSync(again.dir, { recursive: true });
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.
|
||||
import { Frustum } from "$/client/rendering/frustum.ts";
|
||||
import { group_faces_camera } from "$/client/rendering/level_renderer.ts";
|
||||
import { FACE_GROUPS, type LayerMesh, TERRAIN_VERTEX_BYTES } from "$/client/workers/chunk_messages.ts";
|
||||
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
// the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts
|
||||
@@ -29,12 +30,10 @@ Deno.test("the frustum keeps what's in front of the camera and drops what's behi
|
||||
assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane");
|
||||
});
|
||||
|
||||
// real chunks from the chunk worker, meshed the way the client does it
|
||||
// real chunks as the server sends them, meshed the way the client does it
|
||||
async function mesh_chunks(radius: number) {
|
||||
const { game } = await test_game("mods", undefined, "culling-seed");
|
||||
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||
const block_ids: Record<string, number> = {};
|
||||
blocks.forEach((b, nid) => block_ids[b.id] = nid);
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const replies = new Map<string, (message: any) => void>();
|
||||
@@ -53,19 +52,15 @@ async function mesh_chunks(radius: number) {
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
blocks_registry: JSON.parse(JSON.stringify(blocks)),
|
||||
block_ids,
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
worldgen_scripts: [],
|
||||
ores: game.recipes.ores,
|
||||
});
|
||||
|
||||
const generated = new Map<string, Uint32Array>();
|
||||
for (let x = -radius - 1; x <= radius + 1; x++) {
|
||||
for (let z = -radius - 1; z <= radius + 1; z++) {
|
||||
const reply = await ask({ type: "generate", chunk_x: x, chunk_z: z, seed: "culling-seed" }, "generated");
|
||||
generated.set(`${x},${z}`, reply.blocks);
|
||||
generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).blocks);
|
||||
}
|
||||
}
|
||||
const meshes = [];
|
||||
|
||||
@@ -20,12 +20,9 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
blocks_registry: JSON.parse(JSON.stringify(blocks)),
|
||||
block_ids,
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
worldgen_scripts: [],
|
||||
ores: [],
|
||||
});
|
||||
|
||||
const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { assert, assertEquals, assertNotEquals } from "@std/assert";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { CHUNK_VOLUME, decode_chunk, encode_chunk, is_changed, SavedChunk } from "$/server/game/saves.ts";
|
||||
import { read_regions, region_file, write_chunks } from "$/server/regions.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
import { sent_block, test_game } from "./helpers.ts";
|
||||
|
||||
function chunk_data(seed: number, palette_size = 3) {
|
||||
const palette: [string, number][] = [];
|
||||
@@ -77,9 +77,11 @@ Deno.test("changed blocks are saved as whole chunks, and only chunks that change
|
||||
assertEquals(loaded.game.world.get_block_id(3, 120, 5), "bworld:stone");
|
||||
assertEquals(loaded.game.world.get_block_id(-20, 120, 40), "bworld:planks");
|
||||
assertEquals(loaded.game.world.get_block_value(-20, 121, 40) >>> 16, 1);
|
||||
// players get the changes, not the whole chunks
|
||||
// players get the whole chunks, with what was saved in them
|
||||
const join = loaded.join(1, "alice");
|
||||
assertEquals(join.changes.length, 3);
|
||||
loaded.send(1, { type: "move", x: 3.5, y: 130, z: 5.5, yaw: 0, pitch: 0 });
|
||||
loaded.game.tick();
|
||||
assertEquals(sent_block(loaded.take(1), join, 3, 120, 5), ["bworld:stone", 0]);
|
||||
// nothing to save again after loading
|
||||
assertEquals(loaded.game.save().chunks, []);
|
||||
});
|
||||
@@ -108,10 +110,9 @@ Deno.test("when world generation is the same, blocks it made come from it", asyn
|
||||
Deno.test("when world generation changed, saved chunks keep their terrain and are saved again", async () => {
|
||||
const { saved, level } = await saved_with_old_terrain();
|
||||
saved.level = JSON.stringify({ ...level, worldgen: "older" });
|
||||
const { game, join } = await test_game("mods", saved);
|
||||
const { game } = await test_game("mods", saved);
|
||||
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
|
||||
assertEquals(game.world.get_block_id(3, 120, 5), "bworld:stone");
|
||||
assertEquals(join(1, "alice").changes.length, 2);
|
||||
|
||||
const again = game.save();
|
||||
assertNotEquals(JSON.parse(again.level).worldgen, "older");
|
||||
|
||||
Reference in New Issue
Block a user