Shared state between client and server

This commit is contained in:
2026-10-03 18:45:07 -03:00
parent 63e6248f9f
commit 7417bfd5f1
24 changed files with 656 additions and 193 deletions
+55 -29
View File
@@ -59,21 +59,45 @@ component.
## Handlers
| Handler | Called when | Returns |
| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- |
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
| `on_click(block, params, player)` | A player starts hitting it. | |
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
| `on_second(block, params, dt)` | Every second, near a player. | |
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | |
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with |
| Handler | Called when | Returns |
| ------------------------------------ | ----------------------------------------------------------------- | -------------------------- |
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
| `on_click(block, params, player)` | A player starts hitting it. | |
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
| `on_second(block, params, dt)` | Every second, near a player. | |
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | |
`block` is `{ id, x, y, z, data }`, where `data` is the block's [tile data](tiledata.md). `params` is what the block's
JSON lists for this component, and `dt` is in seconds.
## Rules
A component's rules decide a block's states from where it's placed and what's around it. They're registered in the mod's
[shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients run them too: that's
how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the server
answers. A component can have rules, handlers, or both, and a block can list one that only has rules.
```ts
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
ctx.components.register_block("copper_tools:pipe", {
state_for_placement(placement, params) {/* ... */},
on_neighbor_change(block, params, neighbor) {/* ... */},
});
}
```
| Rule | Called when | Returns |
| --------------------------------------------- | ---------------------------------------------------------------------- | ----------------------- |
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with |
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has
`get_block`, `get_state`, `set_state` and `is_face_sturdy`, and only works inside rules.
### Neighbors
`on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is
@@ -87,10 +111,11 @@ a slab's sides and plants aren't.
### Placing
`state_for_placement` picks the states a block is placed with, like Minecraft's `getStateForPlacement`. `placement` is
`{ x, y, z, player, face, hit }`: where it's going, the face of the block that was clicked, and where on that block the
click was, from 0 to 1 on each axis. It returns states by name, and the rest keep their defaults, except that a 2 bit
`facing` already faces the player. It runs before the server checks that no one is in the way, so that's checked against
the shape the block will really have. A trapdoor clicked onto the upper half of a block's side hangs in the top half:
`{ x, y, z, face, hit, facing }`: where it's going, the face of the block that was clicked, where on that block the
click was (from 0 to 1 on each axis), and the way the player looks along the ground. It returns states by name, and the
rest keep their defaults, except that a 2 bit `facing` already faces the player. It runs before the server checks that
no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked onto the upper
half of a block's side hangs in the top half:
```ts
state_for_placement(placement): Record<string, number> {
@@ -101,7 +126,8 @@ state_for_placement(placement): Record<string, number> {
},
```
Clients guess blocks are placed with their defaults, and the server corrects them right after.
A fence's placement looks at its neighbors, so it's joined from the start, and its `on_neighbor_change` keeps it joined
after. Both are in `mods/bworld/scripts/shared.ts`.
### Interacting
@@ -127,18 +153,18 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
`mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them:
| Component | Params | What it does |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
| `bworld:water_source` | none | Refills the watering can. |
| `bworld:fishable` | none | Can be fished in with the fishing rod. |
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's. Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
| Component | Params | What it does |
| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
| `bworld:water_source` | none | Refills the watering can. |
| `bworld:fishable` | none | Can be fished in with the fishing rod. |
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (its rules are in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
Item components work the same way, see [Items](../items/index.md#item-components).
+38 -6
View File
@@ -9,10 +9,11 @@ Clients send what the player is _trying_ to do: "break the block at x, y, z", "u
slot 3". The server checks it (reach, the item being held, container rules), runs mod logic, and sends back what
happened.
For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away. When the
server disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is
undone. Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other
than placing.
For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away, with the
states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does. When the server
disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is undone.
Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other than
placing.
```
server process browser
@@ -21,18 +22,20 @@ than placing.
│ ┌───────────────────────────────────┐ │ ws │ + mods' client scripts │
│ │ game server worker │◄├──────────┤► │
│ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │
│ │ + mods' server scripts │ │ chunks └──────────────────────────────────┘
│ │ + mods' server scripts │ │ chunks │ + mods' shared scripts │
│ │ + mods' shared scripts │ │ └──────────────────────────────────┘
│ │ + mods' worldgen scripts │ │
│ └───────────────────────────────────┘ │
└───────────────────────────────────────┘
```
## The Three Scripts
## The Four Scripts
| Script | Runs on | Sent to players | For |
| ---------- | -------------------------------- | --------------- | ------------------------------------------------------------------- |
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and
@@ -73,6 +76,34 @@ can't change the world or inventories.
Client code is visible to players and can be changed by them. Never trust it for anything that matters. See
[Security](security.md).
### Shared Scripts
```ts
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
ctx.components.register_block("copper_tools:pipe", {
state_for_placement(placement) {/* ... */},
on_neighbor_change(block, params, neighbor) {/* ... */},
});
}
```
Shared scripts hold a block component's rules, the code Minecraft runs on both sides: what states a block is placed with
(`state_for_placement`) and how it changes with the blocks beside it (`on_neighbor_change`). See
[Block Components](../blocks/components.md#placing). The server script registers the rest of the same component, like
its `on_interact`, under the same id.
On the server they run on the real world. On a client they run on what that client shows, when its player places or
breaks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and the
server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs a
flicker. `ctx.side` says which one it's running on.
`setup` runs before the server or client script on each side, for every mod first, so their scripts can count on any
mod's rules being there. Rules can only be registered during `setup`, and `ctx.world` only works in them.
Shared code is sent to players like client code, so it's for rules anyone may read, never anti-cheat or secrets.
### Worldgen Scripts
Worldgen scripts register features that run on every chunk the server generates. They must be deterministic: the same
@@ -90,6 +121,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
| Entities | yes | near the player |
| `ctx.storage` | yes | no |
| Server script code | yes | **never** |
| Shared script code | yes | yes, and runs it |
When a client needs to see something only the server has, the server has to send it: open a
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
+8 -5
View File
@@ -1,6 +1,6 @@
# Mod Files
A mod is a folder with a `manifest.json`, some data files, textures, and up to three scripts. The build packs it into a
A mod is a folder with a `manifest.json`, some data files, textures, and up to four scripts. The build packs it into a
single `.bmod` file, which is what servers load.
## Layout
@@ -25,6 +25,7 @@ mods/
scripts/
server.ts # game logic, never sent to players
client.ts # sent to players
shared.ts # block rules, run on the server and sent to players
worldgen.ts # terrain features, never sent to players
```
@@ -55,7 +56,8 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
"scripts": {
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"worldgen": "scripts/worldgen.ts"
"worldgen": "scripts/worldgen.ts",
"shared": "scripts/shared.ts"
},
"credits": "CREDITS.md"
}
@@ -71,7 +73,7 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
| `authors` | no | A list of names. |
| `game_version` | no | The bworld versions the mod works with, as a semver range. Not checked yet. |
| `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. |
| `scripts` | no | Paths to the `server`, `client` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
| `scripts` | no | Paths to the `server`, `client`, `shared` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
| `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. |
List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It
@@ -90,8 +92,8 @@ so they can import other files and packages, but code imported by several script
When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own
imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in
this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client` and
`bworld/worldgen`:
this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client`,
`bworld/shared` and `bworld/worldgen`:
```ts
import type { ServerContext } from "bworld/server";
@@ -114,6 +116,7 @@ copper_tools.bmod
scripts/server.js # each script bundled into one module
scripts/client.js
scripts/worldgen.js
scripts/shared.js
textures/<name>.png
credits.md
```