Cache ticking blocks
This commit is contained in:
@@ -4,8 +4,8 @@ A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics
|
||||
redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as
|
||||
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||
|
||||
Nothing here is built yet. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts
|
||||
about bworld from its source.
|
||||
Built so far: the importer and Create's imported blocks and items, model `parent` and `x` turns, and S0. Facts about
|
||||
Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -275,11 +275,11 @@ categories (a press pressing over its recipe, like `compat/jei`), goggles and po
|
||||
|
||||
### Server and Gameplay
|
||||
|
||||
**S0. Ticking only what ticks** (P1). `GameServer.tick` walks every tile in the world to find the ones that tick
|
||||
([game_server.ts:376](server/game/game_server.ts#L376)). With thousands of Create blocks with tile data, that's the
|
||||
first thing to fix. Keep a set of ticking tiles per chunk, updated when tiles are added or removed, and let a component
|
||||
turn ticking off and on for one block (`block.set_ticking(false)`, like returning no ticker in NeoForge). A shaft has
|
||||
tile data and never ticks. A press only ticks while pressing.
|
||||
**S0. Ticking only what ticks** (P1, built). `ServerWorld` keeps the tiles that tick per chunk, so `GameServer.tick`
|
||||
only looks at the chunks near players instead of every tile in the world. A component turns ticking off and on for one
|
||||
block with `block.set_ticking(false)`, or `ctx.world.set_block_ticking(x, y, z, true)` from elsewhere, like returning no
|
||||
ticker in NeoForge, and it stays off through saving. A shaft has tile data and never ticks. A press only ticks while
|
||||
pressing.
|
||||
|
||||
**S1. Block capabilities** (P3). `ctx.capabilities.register_block("items", block_id, (block, side) => handler)` and
|
||||
`ctx.world.capability("items", x, y, z, side)`, like NeoForge's `BlockCapability`. Handlers insert, extract, report
|
||||
|
||||
@@ -44,6 +44,9 @@ export interface BlockRef {
|
||||
// tile data, any json value. saved with the world, never sent to clients
|
||||
// deno-lint-ignore no-explicit-any
|
||||
data: any;
|
||||
// turns on_tick and on_second off for this block, or back on, like a machine with nothing to do. it stays off until
|
||||
// it's turned on again, saved with the world, and goes with the block
|
||||
set_ticking(ticking: boolean): void;
|
||||
}
|
||||
|
||||
// P is the component's params from the block json
|
||||
@@ -215,6 +218,8 @@ export interface ServerWorld {
|
||||
// shape covers the whole face. false for air, plants, water and the sides of a slab
|
||||
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
|
||||
get_block_data<T>(x: number, y: number, z: number): T | undefined;
|
||||
// BlockRef.set_ticking for a block, for waking one from somewhere else, like a machine getting something to work on
|
||||
set_block_ticking(x: number, y: number, z: number, ticking: boolean): void;
|
||||
// the item a block with item_display shows on top of it, like a block entity renderer: saved with the block's data
|
||||
// and synced to players. undefined shows nothing. it goes away with the block, without dropping
|
||||
set_block_item(x: number, y: number, z: number, item: ItemStack | undefined): void;
|
||||
|
||||
@@ -69,9 +69,9 @@ component.
|
||||
| `on_second(block, params, dt)` | Every second, near a player. | |
|
||||
| `on_new_day(block, params, day)` | Every morning at 06:00. See [Ticking](#ticking) for where. | |
|
||||
|
||||
`block` is `{ id, x, y, z, biome, season, data }`, where `data` is the block's [tile data](tiledata.md) and `biome` and
|
||||
`season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)). `params` is what the block's JSON lists for
|
||||
this component, and `dt` is in seconds.
|
||||
`block` is `{ id, x, y, z, biome, season, data, set_ticking }`, where `data` is the block's [tile data](tiledata.md),
|
||||
`biome` and `season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)) and `set_ticking` turns its
|
||||
[ticking](#ticking) off and on. `params` is what the block's JSON lists for this component, and `dt` is in seconds.
|
||||
|
||||
## Rules
|
||||
|
||||
@@ -160,6 +160,22 @@ clients guess that the click places the held block and show it for a moment befo
|
||||
`on_tick` and `on_second` only run for blocks that **have tile data**, within 6 chunks of a player. So a component that
|
||||
ticks from the start sets `block.data` in `on_create`, like `copper_tools:oxidizes` above.
|
||||
|
||||
A block that only has work some of the time turns its ticking off with `block.set_ticking(false)`, like a machine with
|
||||
nothing to make, so the server doesn't spend time on it every tick. It stays off, even when the world is saved and
|
||||
loaded, until something turns it back on: its own `on_interact`, or any other script with
|
||||
`ctx.world.set_block_ticking(x, y, z, true)`, like a pipe bringing it something to work on. Breaking or replacing the
|
||||
block forgets it.
|
||||
|
||||
```ts
|
||||
on_tick(block) {
|
||||
if (!has_work(block)) {
|
||||
block.set_ticking(false);
|
||||
return;
|
||||
}
|
||||
// ...
|
||||
},
|
||||
```
|
||||
|
||||
`on_new_day` runs for every block with tile data in the whole world, near a player or not, so crops keep growing while
|
||||
nobody's around. Blocks without tile data, like the cacti world generation makes, run it too, but only within 6 chunks
|
||||
of a player, like the blocks Minecraft random ticks. Blocks one of them places that morning, like a cactus growing a
|
||||
|
||||
@@ -27,8 +27,8 @@ Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
|
||||
- Tile data is saved with the world, and goes away when the block is broken or replaced.
|
||||
- It's **never sent to clients**. To show it to a player, open a [menu](../inventories/menus.md), or change a block
|
||||
state that the block's `variants` show.
|
||||
- Only blocks with tile data run `on_tick` and `on_second`. `on_new_day` runs for blocks without it too, but only near
|
||||
players, see [Ticking](components.md#ticking).
|
||||
- Only blocks with tile data run `on_tick` and `on_second`, unless they turned it off. `on_new_day` runs for blocks
|
||||
without it too, but only near players, see [Ticking](components.md#ticking).
|
||||
|
||||
## Blocks With Containers
|
||||
|
||||
|
||||
+52
-24
@@ -45,14 +45,7 @@ import {
|
||||
import { collision_shape_at, type Shape } from "$/common/block_shapes.ts";
|
||||
import { physics } from "$/common/physics.ts";
|
||||
import { EXHAUSTION } from "./vitals.ts";
|
||||
import {
|
||||
type BlockComponentOf,
|
||||
entity_ref,
|
||||
ModRuntime,
|
||||
new_stack,
|
||||
run_guarded,
|
||||
type ServerCommandSource,
|
||||
} from "./mod_runtime.ts";
|
||||
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
|
||||
import type { LootContext } from "$/common/mod_api/server.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
import {
|
||||
@@ -160,6 +153,8 @@ interface SavedTile {
|
||||
mod_data?: unknown;
|
||||
// what it shows, see ServerWorld.set_block_item in the mod api
|
||||
item?: ItemData;
|
||||
// false when its components turned ticking off for it
|
||||
ticking?: false;
|
||||
}
|
||||
|
||||
// the loaded mods, see load_mods.ts
|
||||
@@ -283,6 +278,7 @@ export class GameServer {
|
||||
z: tile.z,
|
||||
mod_data: tile.mod_data,
|
||||
item: tile.item,
|
||||
ticking: tile.ticking,
|
||||
});
|
||||
}
|
||||
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
|
||||
@@ -371,25 +367,20 @@ export class GameServer {
|
||||
this.#broadcast({ type: "time", time: this.world.time });
|
||||
}
|
||||
|
||||
// the tiles that tick, picked before any runs so one that a handler adds waits for the next tick
|
||||
const ticking: [Tile, readonly BlockComponentOf[]][] = [];
|
||||
let near: Map<number, [number, number]> | undefined;
|
||||
for (const tile of this.world.tiles.values()) {
|
||||
if (tile.mod_data === undefined) {
|
||||
continue;
|
||||
}
|
||||
const components = this.mods.ticking_components_of(tile.id);
|
||||
if (components.length === 0) {
|
||||
continue;
|
||||
}
|
||||
near ??= this.#chunks_near_players();
|
||||
if (near.has(chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE)))) {
|
||||
ticking.push([tile, components]);
|
||||
// the tiles near players that tick, picked before any runs so one that a handler adds waits for the next tick
|
||||
const ticking: Tile[] = [];
|
||||
if (this.world.has_ticking_tiles) {
|
||||
for (const [chunk_x, chunk_z] of this.#chunks_near_players().values()) {
|
||||
for (const tile of this.world.ticking_tiles(chunk_x, chunk_z)) ticking.push(tile);
|
||||
}
|
||||
}
|
||||
for (const [tile, components] of ticking) {
|
||||
for (const tile of ticking) {
|
||||
// a handler that ran before it broke it or turned its ticking off
|
||||
if (!this.world.ticks(tile)) {
|
||||
continue;
|
||||
}
|
||||
const block = this.mods.block_ref(tile.x, tile.y, tile.z, tile.id);
|
||||
for (const { mod, id, component, params } of components) {
|
||||
for (const { mod, id, component, params } of this.mods.ticking_components_of(tile.id)) {
|
||||
if (component.on_tick) {
|
||||
run_guarded(mod, `${id} on_tick`, () => component.on_tick!(block, params, TICK_DELTA));
|
||||
}
|
||||
@@ -446,6 +437,7 @@ export class GameServer {
|
||||
z: tile.z,
|
||||
mod_data: tile.mod_data,
|
||||
item: tile.item,
|
||||
ticking: tile.ticking,
|
||||
})),
|
||||
containers: Object.fromEntries(
|
||||
[...this.containers].map(([id, container]) => [id, container.to_data()]),
|
||||
@@ -717,6 +709,42 @@ export class GameServer {
|
||||
return tile;
|
||||
}
|
||||
|
||||
// BlockRef.data's setter
|
||||
set_tile_data(x: number, y: number, z: number, data: unknown) {
|
||||
const tile = this.get_or_create_tile(x, y, z);
|
||||
tile.mod_data = data;
|
||||
this.#update_ticking(tile);
|
||||
this.world.dirty = true;
|
||||
}
|
||||
|
||||
// a component turning ticking off for one block, or back on, see BlockRef.set_ticking. it stays off when saved
|
||||
set_tile_ticking(x: number, y: number, z: number, ticking: boolean) {
|
||||
if (this.world.get_block_id(x, y, z) === AIR_ID) {
|
||||
return;
|
||||
}
|
||||
// ticking is on unless a tile says it's off
|
||||
const tile = ticking ? this.world.get_tile(x, y, z) : this.get_or_create_tile(x, y, z);
|
||||
if (!tile) {
|
||||
return;
|
||||
}
|
||||
if (ticking) delete tile.ticking;
|
||||
else tile.ticking = false;
|
||||
this.#update_ticking(tile);
|
||||
this.world.dirty = true;
|
||||
}
|
||||
|
||||
// which of the tiles loaded with the world tick, which needs every mod's components registered first
|
||||
find_ticking_tiles() {
|
||||
for (const tile of this.world.tiles.values()) this.#update_ticking(tile);
|
||||
}
|
||||
|
||||
// a tile ticks while it has data, its block has components with on_tick or on_second, and they haven't turned it off
|
||||
#update_ticking(tile: Tile) {
|
||||
const ticks = tile.mod_data !== undefined && tile.ticking !== false &&
|
||||
this.mods.ticking_components_of(tile.id).length > 0;
|
||||
this.world.set_ticks(tile, ticks);
|
||||
}
|
||||
|
||||
// containers
|
||||
|
||||
create_container(size: number): { id: string; container: Container } {
|
||||
|
||||
@@ -77,6 +77,7 @@ export async function start_game(
|
||||
mods.flatMap((mod) => mod.server_url ? [{ ...script_of(mod), url: mod.server_url }] : []),
|
||||
);
|
||||
runtime.finish_setup();
|
||||
game.find_ticking_tiles();
|
||||
// what a worldgen worker needs to generate the same chunks, see worldgen_pool.ts
|
||||
game.worldgen_bundle = worldgen_bundle(
|
||||
game.world.seed,
|
||||
|
||||
@@ -547,8 +547,10 @@ export class ModRuntime {
|
||||
return game.world.get_tile(x, y, z)?.mod_data;
|
||||
},
|
||||
set data(value) {
|
||||
game.get_or_create_tile(x, y, z).mod_data = value;
|
||||
game.world.dirty = true;
|
||||
game.set_tile_data(x, y, z, value);
|
||||
},
|
||||
set_ticking(ticking) {
|
||||
game.set_tile_ticking(x, y, z, ticking);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -687,6 +689,7 @@ export class ModRuntime {
|
||||
},
|
||||
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
|
||||
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
|
||||
set_block_ticking: (x, y, z, ticking) => game().set_tile_ticking(x, y, z, ticking),
|
||||
set_block_item: (x, y, z, item) => {
|
||||
if (game().world.get_block_id(x, y, z) === AIR_ID) return;
|
||||
if (!item || item.count <= 0) {
|
||||
|
||||
+67
-18
@@ -46,6 +46,44 @@ export interface Tile {
|
||||
mod_data?: unknown;
|
||||
// the item it shows, sent to clients, see BlockRegistry.item_display. only set through set_tile_item
|
||||
item?: ItemData;
|
||||
// false when its components turned ticking off for it, see GameServer.set_tile_ticking
|
||||
ticking?: false;
|
||||
}
|
||||
|
||||
// some of the tiles, kept by chunk so a chunk's are found without going through every tile in the world
|
||||
class ChunkTiles {
|
||||
#chunks = new Map<number, Set<Tile>>();
|
||||
|
||||
get empty() {
|
||||
return this.#chunks.size === 0;
|
||||
}
|
||||
|
||||
// adds or removes it
|
||||
set(tile: Tile, has: boolean) {
|
||||
const key = tile_chunk_key(tile);
|
||||
let tiles = this.#chunks.get(key);
|
||||
if (has) {
|
||||
if (!tiles) {
|
||||
tiles = new Set();
|
||||
this.#chunks.set(key, tiles);
|
||||
}
|
||||
tiles.add(tile);
|
||||
} else if (tiles?.delete(tile) && tiles.size === 0) {
|
||||
this.#chunks.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
has(tile: Tile) {
|
||||
return this.#chunks.get(tile_chunk_key(tile))?.has(tile) ?? false;
|
||||
}
|
||||
|
||||
in_chunk(chunk_x: number, chunk_z: number): Iterable<Tile> {
|
||||
return this.#chunks.get(chunk_key(chunk_x, chunk_z)) ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
function tile_chunk_key(tile: Tile) {
|
||||
return chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE));
|
||||
}
|
||||
|
||||
// a chunk as it is now, loaded from the save or generated
|
||||
@@ -94,8 +132,10 @@ export class ServerWorld {
|
||||
// unsaved chunks #chunks forgot, ready to save, by chunk_key
|
||||
#evicted = new Map<number, SavedChunk>();
|
||||
tiles = new Map<string, Tile>();
|
||||
// the tiles showing an item, by chunk_key, to send with their chunk
|
||||
#item_tiles = new Map<number, Set<Tile>>();
|
||||
// the tiles showing an item, to send with their chunk
|
||||
#item_tiles = new ChunkTiles();
|
||||
// the tiles that tick, which the game decides, see GameServer.set_tile_ticking
|
||||
#ticking_tiles = new ChunkTiles();
|
||||
|
||||
// ticks since 06:00 of day 1, see common/time.ts
|
||||
time = 0;
|
||||
@@ -480,33 +520,42 @@ export class ServerWorld {
|
||||
|
||||
remove_tile(x: number, y: number, z: number) {
|
||||
const tile = this.get_tile(x, y, z);
|
||||
if (tile?.item) this.set_tile_item(tile, undefined);
|
||||
if (!tile) return;
|
||||
if (tile.item) this.set_tile_item(tile, undefined);
|
||||
this.#ticking_tiles.set(tile, false);
|
||||
this.tiles.delete(position_key(x, y, z));
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
set_tile_item(tile: Tile, item: ItemData | undefined) {
|
||||
const key = chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE));
|
||||
let tiles = this.#item_tiles.get(key);
|
||||
if (item) {
|
||||
tile.item = item;
|
||||
if (!tiles) {
|
||||
tiles = new Set();
|
||||
this.#item_tiles.set(key, tiles);
|
||||
}
|
||||
tiles.add(tile);
|
||||
} else {
|
||||
delete tile.item;
|
||||
tiles?.delete(tile);
|
||||
if (tiles?.size === 0) this.#item_tiles.delete(key);
|
||||
}
|
||||
if (item) tile.item = item;
|
||||
else delete tile.item;
|
||||
this.#item_tiles.set(tile, item !== undefined);
|
||||
this.dirty = true;
|
||||
this.on_tile_item_change?.(tile.x, tile.y, tile.z, item);
|
||||
}
|
||||
|
||||
// the tiles in a chunk that show an item
|
||||
item_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
|
||||
return this.#item_tiles.get(chunk_key(chunk_x, chunk_z)) ?? [];
|
||||
return this.#item_tiles.in_chunk(chunk_x, chunk_z);
|
||||
}
|
||||
|
||||
// whether it runs its components' on_tick and on_second near players
|
||||
set_ticks(tile: Tile, ticks: boolean) {
|
||||
this.#ticking_tiles.set(tile, ticks);
|
||||
}
|
||||
|
||||
ticks(tile: Tile) {
|
||||
return this.#ticking_tiles.has(tile);
|
||||
}
|
||||
|
||||
// the tiles in a chunk that tick
|
||||
ticking_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
|
||||
return this.#ticking_tiles.in_chunk(chunk_x, chunk_z);
|
||||
}
|
||||
|
||||
get has_ticking_tiles() {
|
||||
return !this.#ticking_tiles.empty;
|
||||
}
|
||||
|
||||
#mark_unsaved(chunk_x: number, chunk_z: number) {
|
||||
|
||||
@@ -23,6 +23,19 @@ export function setup(ctx: ServerContext) {
|
||||
ctx.components.register_block("testmod:lazy", {
|
||||
on_tick() { log("lazy_tick"); },
|
||||
});
|
||||
// a machine that works for 5 ticks at a time, then waits to be woken
|
||||
ctx.components.register_block("testmod:sleeper", {
|
||||
on_create(block) { block.data = { ticks: 0 }; },
|
||||
on_tick(block) {
|
||||
block.data.ticks += 1;
|
||||
log("sleeper_tick");
|
||||
if (block.data.ticks % 5 === 0) block.set_ticking(false);
|
||||
},
|
||||
on_interact(block) {
|
||||
ctx.world.set_block_ticking(block.x, block.y, block.z, true);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
ctx.components.register_block("testmod:broken", {
|
||||
on_create(block) { block.data = {}; },
|
||||
on_tick() { throw new Error("broken on purpose"); },
|
||||
@@ -133,6 +146,10 @@ function test_mods() {
|
||||
block("testmod:ticker", { components: { "testmod:ticker": {} } }),
|
||||
);
|
||||
Deno.writeTextFileSync(`${mod}/blocks/lazy.json`, block("testmod:lazy", { components: { "testmod:lazy": {} } }));
|
||||
Deno.writeTextFileSync(
|
||||
`${mod}/blocks/sleeper.json`,
|
||||
block("testmod:sleeper", { interactive: true, components: { "testmod:sleeper": {} } }),
|
||||
);
|
||||
Deno.writeTextFileSync(
|
||||
`${mod}/blocks/broken.json`,
|
||||
block("testmod:broken", { components: { "testmod:broken": {} } }),
|
||||
@@ -195,6 +212,26 @@ Deno.test("components tick 20 times a second and on_second once, only with block
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("a block can turn its ticking off and be woken, and both last through saving", async () => {
|
||||
const { game, log, dir } = await setup();
|
||||
game.set_block(2, 100, 2, "testmod:ticker");
|
||||
game.set_block(3, 100, 2, "testmod:sleeper");
|
||||
for (let i = 0; i < 20; i++) game.tick();
|
||||
assertEquals(log()["sleeper_tick"]?.length, 5);
|
||||
|
||||
const saved = game.save();
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const again = await setup(saved);
|
||||
for (let i = 0; i < 20; i++) again.game.tick();
|
||||
assertEquals(again.log()["tick_2"]?.length, 40, "blocks loaded with the world tick");
|
||||
assertEquals(again.log()["sleeper_tick"]?.length, 5, "and one that turned it off stays off");
|
||||
|
||||
again.send(1, { type: "use_block", x: 3, y: 100, z: 2, face: "top" });
|
||||
for (let i = 0; i < 20; i++) again.game.tick();
|
||||
assertEquals(again.log()["sleeper_tick"]?.length, 10);
|
||||
Deno.removeSync(again.dir, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("timers and the tick event run on the game loop's ticks", async () => {
|
||||
const { game, log, dir } = await setup();
|
||||
for (let i = 0; i < 50; i++) game.tick();
|
||||
|
||||
Reference in New Issue
Block a user