Compare commits
3
Commits
8b549162c4
...
86d5c39eab
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86d5c39eab | ||
|
|
b68fe3a19f | ||
|
|
58afaac821 |
@@ -2,3 +2,4 @@ build/
|
||||
world.json
|
||||
world.json.tmp
|
||||
server_mods/
|
||||
dist/
|
||||
|
||||
@@ -1,51 +1,65 @@
|
||||
# bworld mods specification
|
||||
|
||||
Status: **draft, format_version 1**. Nothing here is implemented yet, see [Implementation plan](#implementation-plan).
|
||||
Status: **draft, format_version 1**, partly built. The [Implementation plan](#implementation-plan) lists what works
|
||||
today and what's planned, and sections about planned features say so.
|
||||
|
||||
Mods add blocks, items, textures, recipes, world generation, game logic and GUIs to bworld. A mod is installed **on the
|
||||
server**. Players who join download its client code, data and textures from the server automatically, so they don't
|
||||
install anything themselves. bworld is always played on a server; there is no single player mode.
|
||||
Mods add blocks, items, textures, recipes, world generation, game logic and GUIs to bworld, and can change how the game
|
||||
itself works. A mod is installed **on the server**. Players who join download its client code, data and textures from
|
||||
the server automatically, so they don't install anything themselves. bworld is always played on a server; there is no
|
||||
single player mode.
|
||||
|
||||
This borrows from Minecraft Bedrock add-ons: data lives in JSON, blocks get behavior from named custom components, and
|
||||
scripts use before/after events. Bedrock servers also push resource packs to joining players, and their server scripts
|
||||
can show forms that the client draws (`@minecraft/server-ui`). bworld goes one step further and pushes client _scripts_
|
||||
too, since the client is already a web page.
|
||||
bworld's modding takes from three places:
|
||||
|
||||
- **Minetest: the game is mods.** The engine is small, and everything that makes bworld _bworld_ (its blocks, items,
|
||||
crafting, inventory screen, HUD, commands and terrain) lives in `mods/bworld`, written against the same API as any
|
||||
other mod. Mods can change each other's content, including the base game's.
|
||||
- **Minecraft Bedrock add-ons: easy to start.** Most content is JSON, blocks and items get behavior from named
|
||||
components, scripts use before/after events and server-driven forms, and players get everything from the server.
|
||||
- **Minecraft Java with Fabric: no ceiling.** A mod that needs to can reach into the engine itself and hook any of its
|
||||
methods, on the server and on the client, like Fabric's mixins.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Loading](#loading)
|
||||
- [Creating a mod](#creating-a-mod)
|
||||
- [Mod layout](#mod-layout)
|
||||
- [manifest.json](#manifestjson)
|
||||
- [Identifiers](#identifiers)
|
||||
- [Textures](#textures)
|
||||
- [Blocks](#blocks)
|
||||
- [Block models](#block-models)
|
||||
- [Items](#items)
|
||||
- [Recipes](#recipes)
|
||||
- [Server scripts](#server-scripts)
|
||||
- [Client scripts](#client-scripts)
|
||||
- [GUIs](#guis)
|
||||
- [Mod channels](#mod-channels)
|
||||
- [World generation](#world-generation)
|
||||
- Data: [Textures](#textures), [Blocks](#blocks), [Block models](#block-models), [Items](#items),
|
||||
[Recipes](#recipes), [Overrides](#overrides)
|
||||
- Game API: [Common scripts](#common-scripts), [Server scripts](#server-scripts), [Client scripts](#client-scripts),
|
||||
[GUIs](#guis), [Mod channels](#mod-channels), [World generation](#world-generation)
|
||||
- [Engine access](#engine-access)
|
||||
- [Delivery to clients](#delivery-to-clients)
|
||||
- [Security](#security)
|
||||
- [Example mod](#example-mod)
|
||||
- [The base game as a mod](#the-base-game-as-a-mod)
|
||||
- [The engine and the base game](#the-engine-and-the-base-game)
|
||||
- [Implementation plan](#implementation-plan)
|
||||
- [Open questions](#open-questions)
|
||||
|
||||
## Overview
|
||||
|
||||
A mod can have up to three scripts, each running in a different place:
|
||||
A mod is built from up to three layers. Most mods only need the first one or two.
|
||||
|
||||
| Script | Runs on | Sent to clients | Owns |
|
||||
| ---------- | ------------------------------- | --------------- | ------------------------------------------------------------------------------ |
|
||||
| `server` | the server, in a worker | **never** | game logic: block components, ticking, tile data, containers, commands, events |
|
||||
| `client` | every client, main thread | yes | presentation: custom screens, HUD, keybinds |
|
||||
| `worldgen` | server and client chunk workers | yes | terrain features, must be deterministic |
|
||||
| Layer | Like | What a mod writes | Stability |
|
||||
| --------------------------------- | --------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------- |
|
||||
| **Data** | Bedrock behavior packs | JSON in `blocks/`, `items/`, `models/`, `recipes/`, `overrides/`, `worldgen/`, and textures | Versioned by `format_version` |
|
||||
| **Game API** | Minetest's Lua API, Bedrock's Script API | TypeScript against `bworld/common`, `bworld/server`, `bworld/client` and `bworld/worldgen` | Stable, only breaks with the game's major version |
|
||||
| **[Engine access](#engine-access)** | Fabric's mixins | `import { engine, hook } from "bworld/engine"`, opted into in the manifest | None, tied to one game version |
|
||||
|
||||
The mod's JSON data and textures go to both sides.
|
||||
Data is shorthand for the Game API: loading `blocks/copper_block.json` does exactly what `ctx.blocks.register(...)` with
|
||||
the same object does in a common script. So anything a JSON file can do, code can do too, for content that's easier to
|
||||
generate (every color of wool) or that depends on other mods.
|
||||
|
||||
A mod can have up to four scripts, each running in a different place:
|
||||
|
||||
| Script | Runs on | Sent to clients | Owns |
|
||||
| ---------- | ---------------------------------------------- | --------------- | ------------------------------------------------------------------------------------ |
|
||||
| `common` | the server and every client, before the others | yes | content: registering blocks, items, models and recipes, and changing other mods' content |
|
||||
| `server` | the server, in a worker | **never** | game logic: block components, ticking, tile data, containers, commands, events |
|
||||
| `client` | every client, main thread | yes | presentation: custom screens, HUD, keybinds |
|
||||
| `worldgen` | server and client chunk workers | yes | terrain and features, must be deterministic |
|
||||
|
||||
**The server is the authority.** Clients send what the player is trying to do ("break the block at x, y, z", "click slot
|
||||
3"). The server checks it, runs mod logic and sends back what happened. For responsiveness, clients show the expected
|
||||
@@ -55,17 +69,33 @@ result of breaking and placing immediately, and the server sends a correction if
|
||||
server process browser
|
||||
┌───────────────────────────────────────┐ ┌──────────────────────────────────┐
|
||||
│ host: http, websocket, files │ │ game client (rendering, input) │
|
||||
│ ┌───────────────────────────────────┐ │ ws │ + mod client scripts │
|
||||
│ │ game server worker │◄├──────────┤► (screens, HUD, keybinds) │
|
||||
│ ┌───────────────────────────────────┐ │ ws │ + mod common and client │
|
||||
│ │ game server worker │◄├──────────┤► scripts │
|
||||
│ │ world, inventories, tile data │ │ protocol │ │
|
||||
│ │ + mod server scripts │ │ │ chunk workers │
|
||||
│ │ + mod common and server scripts │ │ │ chunk workers │
|
||||
│ └───────────────────────────────────┘ │ │ + mod worldgen scripts │
|
||||
│ chunk workers + mod worldgen scripts │ └──────────────────────────────────┘
|
||||
└───────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Moving from the current setup to this is a big change, see the [Implementation plan](#implementation-plan). Right now
|
||||
the server only relays block changes and doesn't know about blocks, inventories or terrain.
|
||||
## Loading
|
||||
|
||||
The server and every client load mods the same way, in the same order: dependencies first, otherwise alphabetical. The
|
||||
server sends its order to clients, and they follow it.
|
||||
|
||||
1. **Content**, one mod at a time: the mod's JSON data is registered, then its `common` script's `setup` runs. So a
|
||||
common script sees its own data and everything from the mods before it, and can change it.
|
||||
2. **Freeze.** The registries close: blocks get their numeric ids, block items are created and recipes are indexed.
|
||||
Registering or changing content after this throws.
|
||||
3. **Scripts.** `server` scripts' `setup` runs on the server, `client` scripts' on each client, and `worldgen` scripts in
|
||||
every chunk worker. These can read every registry but not change them.
|
||||
4. The server starts ticking, or the client sends `ready` and joins.
|
||||
|
||||
**Content has to come out the same on every side.** Common scripts run on the server and on every client, and all of
|
||||
them must end up with exactly the same blocks, items and recipes: no `Math.random`, dates, or anything that differs
|
||||
between the server and a client. After the freeze each side hashes its registries (every id and its definition), and
|
||||
the client sends the hash with `ready`. When it doesn't match the server's, the player is turned away with a message
|
||||
naming the first thing that differs, instead of playing with mismatched blocks. _Planned, phase 1._
|
||||
|
||||
## Creating a mod
|
||||
|
||||
@@ -74,14 +104,13 @@ deno task new-mod copper_tools "Copper Tools" # copies templates/mod to mods/c
|
||||
deno task check-mods # validates every mod in mods/
|
||||
```
|
||||
|
||||
The template has one of everything: a block with a custom component, an item, a shaped recipe, textures, and all three
|
||||
scripts. `check-mods` checks manifests and data files against this spec, checks that every id, item and texture a mod
|
||||
refers to exists (and that it depends on the mods those come from), and typechecks scripts against the API types in
|
||||
`common/mod_api/`, which scripts import as `bworld/server`, `bworld/client` and `bworld/worldgen`. Folders in `mods/`
|
||||
starting with `_` or `.` are ignored.
|
||||
The template has one of everything: a block with a custom component, an item, a shaped recipe, textures, and a script
|
||||
for each side. `check-mods` checks manifests and data files against this spec, checks that every id, item and texture a
|
||||
mod refers to exists (and that it depends on the mods those come from), and typechecks scripts against the API types in
|
||||
`common/mod_api/`, which scripts import as `bworld/common`, `bworld/server`, `bworld/client`, `bworld/worldgen` and,
|
||||
with engine access, `bworld/engine`. Folders in `mods/` starting with `_` or `.` are ignored.
|
||||
|
||||
`deno task build` builds every mod in `mods/` and fails if any has errors; `deno task server` then loads them. What
|
||||
works so far is listed in the [Implementation plan](#implementation-plan).
|
||||
`deno task build` builds every mod in `mods/` and fails if any has errors; `deno task server` then loads them.
|
||||
|
||||
## Mod layout
|
||||
|
||||
@@ -93,13 +122,15 @@ mods/
|
||||
models/*.json
|
||||
items/*.json
|
||||
recipes/*.json
|
||||
overrides/*.json # changes to other mods' content
|
||||
worldgen/ores.json
|
||||
textures/*.png
|
||||
scripts/
|
||||
common.ts # content, runs on both sides
|
||||
server.ts # game logic, stays on the server
|
||||
client.ts # sent to players
|
||||
worldgen.ts # sent to players, also runs on the server
|
||||
shared/ # anything both sides import, bundled into each
|
||||
shared/ # anything several scripts import, bundled into each
|
||||
```
|
||||
|
||||
Only `manifest.json` is required. Data folders can have subfolders, with one definition per file.
|
||||
@@ -116,9 +147,11 @@ Only `manifest.json` is required. Data folders can have subfolders, with one def
|
||||
"authors": ["paula"],
|
||||
"game_version": ">=0.1.0",
|
||||
"dependencies": [
|
||||
{ "id": "bworld", "version": "*" },
|
||||
{ "id": "more_ores", "version": "^2.0.0" }
|
||||
],
|
||||
"scripts": {
|
||||
"common": "scripts/common.ts",
|
||||
"server": "scripts/server.ts",
|
||||
"client": "scripts/client.ts",
|
||||
"worldgen": "scripts/worldgen.ts"
|
||||
@@ -134,16 +167,18 @@ Only `manifest.json` is required. Data folders can have subfolders, with one def
|
||||
| `description` | no | One or two sentences. |
|
||||
| `version` | yes | Semver of the mod itself. |
|
||||
| `authors` | no | List of names. |
|
||||
| `game_version` | no | Semver range of bworld versions the mod works with. |
|
||||
| `dependencies` | no | Other mods by `id`, with a semver range. Missing or mismatched dependencies fail loading. |
|
||||
| `game_version` | no | Semver range of bworld versions the mod works with. Mods with `engine_access` need one. |
|
||||
| `dependencies` | no | Other mods by `id`, with a semver range. Missing or mismatched dependencies fail loading. A mod can only change content of mods it depends on. |
|
||||
| `scripts.common` | no | Content entry, run on the server and sent to every player. _Planned, phase 1._ |
|
||||
| `scripts.server` | no | Server entry. Never sent to clients. |
|
||||
| `scripts.client` | no | Client entry, sent to every player. |
|
||||
| `scripts.worldgen` | no | Worldgen entry, sent to every player and also run on the server. |
|
||||
| `engine_access` | no | `true` lets the mod's scripts import `bworld/engine`, see [Engine access](#engine-access). _Planned, phase 3._ |
|
||||
| `credits` | no | A markdown file in the mod, shown on the Credits screen. For asset licenses and thanks. |
|
||||
|
||||
Scripts can be `.js` or `.ts`. The build bundles each entry separately into one ES module. Code imported by both the
|
||||
server and client entries is copied into both bundles, so **don't import secrets into shared code**. Anything the client
|
||||
bundle imports is visible to players.
|
||||
Scripts can be `.js` or `.ts`. The build bundles each entry separately into one ES module. Code imported by several
|
||||
entries is copied into each bundle, so **don't import secrets into shared code**. Anything the common, client or worldgen
|
||||
bundles import is visible to players.
|
||||
|
||||
## Identifiers
|
||||
|
||||
@@ -151,13 +186,13 @@ Everything a mod registers has an id of the form `namespace:name`:
|
||||
|
||||
- `namespace` is the mod's `id`. It must match `^[a-z0-9_]+$` and be at most 32 characters.
|
||||
- Two namespaces are reserved. `bworld` belongs to the base game mod shipped in `mods/bworld` (see
|
||||
[The base game as a mod](#the-base-game-as-a-mod)). `engine` belongs to the engine itself, for things every game
|
||||
needs, like the block-breaking cracks. The one exception is `bworld:air`: it's the engine's empty block, but it keeps
|
||||
that id because every save already contains it.
|
||||
[The engine and the base game](#the-engine-and-the-base-game)). `engine` belongs to the engine itself, for things
|
||||
every game needs, like the block-breaking cracks and the built-in block models. The one exception is `bworld:air`:
|
||||
it's the engine's empty block, but it keeps that id because every save already contains it.
|
||||
- `name` must match `^[a-z0-9_]+$`.
|
||||
- A mod only registers ids in its own namespace: blocks, items, components, screens, channels and HUD elements. It can
|
||||
_refer to_ any id.
|
||||
- Registering an id that already exists is a load error.
|
||||
- A mod only registers ids in its own namespace: blocks, items, models, components, recipe types, screens, channels and
|
||||
HUD elements. It can _refer to_ any id, and [change](#overrides) other mods' content.
|
||||
- Registering an id that already exists is a load error. Changing an existing one is what overrides are for.
|
||||
|
||||
Blocks get a numeric id when they register, and chunk data stores those numbers. Numeric ids are **local to one running
|
||||
program**, so the server and each client can number blocks differently. Saves and the network always use string ids.
|
||||
@@ -213,7 +248,7 @@ program**, so the server and each client can number blocks differently. Saves an
|
||||
| `interactive` | `false` | `interactive` | Right clicking it does something (opens a screen), so clients don't guess it places a block. |
|
||||
| `replaceable` | `false` | new | Placing a block into it replaces it, like water. |
|
||||
| `states` | none | `states` | Up to 16 bits of named state, like `hoed_dirt` has now. |
|
||||
| `components` | none | the `on_*` hooks | Custom components with parameters, handled by server scripts. |
|
||||
| `components` | none | `components` | Custom components with parameters, handled by server scripts. |
|
||||
|
||||
The client needs this data too (for meshing, mining time and collision), so it's sent to every player. It can't contain
|
||||
functions.
|
||||
@@ -348,7 +383,7 @@ clients as part of the container it's in, so client screens can show it.
|
||||
|
||||
| `type` | Fields | Notes |
|
||||
| --------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
|
||||
| `shaped` | `pattern` rows (space is empty), `key` letter to item id, `result` `{ id, count }` | Fits anywhere in the 3×3 grid, like the recipes in `server/game/crafting.ts` |
|
||||
| `shaped` | `pattern` rows (space is empty), `key` letter to item id, `result` `{ id, count }` | Used by the crafting grid, fits anywhere in it |
|
||||
| `furnace` | `input` item id, `output` `{ id, count }`, `cook_time` in ticks | Used by the furnace |
|
||||
| `fuel` | `item` id, `burn_time` in ticks | Used by the furnace |
|
||||
| `smithing` | `tool` item id, `material` `{ id, count }`, optional `addition` item id, `result` item id | Used by the smithing table: upgrades the tool, keeping its data. Uses up the tool, `count` of the material and the addition |
|
||||
@@ -382,8 +417,128 @@ A shaped recipe, for the crafting grid in the player's inventory screen:
|
||||
```
|
||||
|
||||
Two furnace recipes with the same `input`, two smithing recipes with the same tool, material and addition, or two
|
||||
shaped recipes with the same pattern and key, are a load error. Server
|
||||
scripts can also register recipe types of their own through `ctx.recipes`.
|
||||
shaped recipes with the same pattern and key, are a load error. Mods can add recipe types of their own for their
|
||||
machines, see [Common scripts](#common-scripts).
|
||||
|
||||
## Overrides
|
||||
|
||||
A mod can change content other mods registered, like Minetest's `override_item`. The JSON form covers the common cases,
|
||||
and a [common script](#common-scripts) can do the same with `override` and `extend`. _Planned, phase 2._
|
||||
|
||||
`overrides/grass_weeds.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"override": {
|
||||
"block": "bworld:grass",
|
||||
"set": { "mining": { "toughness": 1, "tool": "shovel" } },
|
||||
"add_components": { "farming_plus:weeds": { "chance": 0.01 } }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| ------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| `block` or `item` | The id to change. |
|
||||
| `set` | Fields to replace, with the same names as in the block or item JSON. Each listed field is replaced whole, so `mining` above replaces all of the old `mining`. |
|
||||
| `add_components` | Components to add. One the block or item already has gets these params instead. |
|
||||
| `remove_components` | Component ids to take away. |
|
||||
|
||||
A recipe override removes recipes, so a mod can replace them with its own:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"override": { "remove_recipes": { "type": "shaped", "result": "bworld:chest" } }
|
||||
}
|
||||
```
|
||||
|
||||
`remove_recipes` matches recipes whose fields equal the ones given (`result` matches the result's id).
|
||||
|
||||
Rules:
|
||||
|
||||
- A mod can only change content of mods it lists in `dependencies`, so it always loads after them. `check-mods` makes
|
||||
this an error.
|
||||
- Changes apply in load order, so when two mods change the same field the later one wins. `check-mods` warns about it.
|
||||
- Ids never change, and blocks and items can't be removed, because saves refer to them. To make something unobtainable,
|
||||
remove its recipes and drops.
|
||||
- Overrides are content like everything else: they're applied on the server and every client, and are part of the
|
||||
registry hash.
|
||||
|
||||
## Common scripts
|
||||
|
||||
`scripts.common` exports `setup`, called on the server and on every client while content loads, right after the mod's
|
||||
own JSON is registered (see [Loading](#loading)). _Planned, phase 1._
|
||||
|
||||
```ts
|
||||
import type { CommonContext } from "bworld/common";
|
||||
|
||||
const COLORS = ["white", "red", "green", "blue", "black"];
|
||||
|
||||
export function setup(ctx: CommonContext) {
|
||||
for (const color of COLORS) {
|
||||
ctx.blocks.register({
|
||||
id: `wool:${color}_wool`,
|
||||
textures: `wool:${color}_wool`,
|
||||
mining: { toughness: 1 },
|
||||
drops: `wool:${color}_wool`,
|
||||
});
|
||||
ctx.recipes.register({
|
||||
type: "shaped",
|
||||
pattern: ["D", "W"],
|
||||
key: { D: `wool:${color}_dye`, W: "wool:white_wool" },
|
||||
result: { id: `wool:${color}_wool`, count: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
// wool burns in the base game's furnace
|
||||
for (const color of COLORS) {
|
||||
ctx.recipes.register({ type: "fuel", item: `wool:${color}_wool`, burn_time: 100 });
|
||||
}
|
||||
|
||||
// every leaf block any mod registered drops sticks sometimes
|
||||
for (const id of ctx.blocks.ids().filter((id) => id.endsWith("_leaves"))) {
|
||||
ctx.blocks.extend(id, { components: { "wool:stick_drop": { chance: 0.05 } } });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
interface CommonContext {
|
||||
mod: { id: string; version: string };
|
||||
blocks: ContentRegistry<BlockJson>;
|
||||
items: ContentRegistry<ItemJson>;
|
||||
models: ContentRegistry<ModelJson>;
|
||||
recipes: RecipeRegistry;
|
||||
log(...args: unknown[]): void;
|
||||
}
|
||||
|
||||
// T is the same shape as the JSON file's content, checked the same way
|
||||
interface ContentRegistry<T> {
|
||||
register(definition: T): void;
|
||||
get(id: string): Readonly<T> | undefined; // what's registered so far, by any mod
|
||||
ids(): string[];
|
||||
override(id: string, fields: Partial<T>): void; // like "set" in an override file
|
||||
extend(id: string, change: { components?: Record<string, unknown>; remove_components?: string[] }): void;
|
||||
}
|
||||
|
||||
interface RecipeRegistry {
|
||||
register(recipe: RecipeJson): void;
|
||||
remove(match: (recipe: RecipeJson) => boolean): number; // how many it removed
|
||||
list(type: string): readonly RecipeJson[];
|
||||
// a new recipe type: its recipes are checked with validate, and scripts read them with list
|
||||
register_type(id: string, type: { validate(recipe: unknown): string[] }): void;
|
||||
}
|
||||
```
|
||||
|
||||
- Definitions are checked exactly like JSON files, and a problem is a load error naming the mod.
|
||||
- Common scripts only run during loading. They can't keep state for later, and can't reach the world, players or
|
||||
anything else: that's what server and client scripts are for. They get the same `ctx` shape on both sides on
|
||||
purpose, so they can't accidentally register different things.
|
||||
- Recipe types are ids like everything else. `shaped`, `furnace`, `fuel` and `smithing` are short for `bworld:shaped`
|
||||
and so on, since the base game's crafting grid, furnace and smithing table use them. A mod's machine registers its own
|
||||
type (`copper_tools:alloy`) and its server script reads the recipes with `ctx.recipes.list("copper_tools:alloy")`.
|
||||
|
||||
## Server scripts
|
||||
|
||||
@@ -400,6 +555,9 @@ export function setup(ctx: ServerContext) {
|
||||
Server scripts run in the game server worker with **no Deno permissions** (see [Security](#security)). They get the mod
|
||||
API and standard JavaScript, but no file, network or subprocess access; persistent state goes through `ctx.storage`.
|
||||
|
||||
`ctx` is the Game API for the server. Content is already registered and frozen by now (see [Loading](#loading)), so
|
||||
server scripts read registries but don't change them.
|
||||
|
||||
```ts
|
||||
interface ServerContext {
|
||||
mod: { id: string; version: string };
|
||||
@@ -557,7 +715,7 @@ ctx.commands.register("heal", {
|
||||
```
|
||||
|
||||
Commands run on the server when a player types `/name` in chat. Two mods using the same name, or a mod using one of the
|
||||
engine's (`give`, `time` and `tps`), is a load error. `/copper_tools:heal` always works as the unambiguous form.
|
||||
engine's (`give`, `time` and `tps`, until phase 5 moves `give` and `time` into `mods/bworld`), is a load error. `/copper_tools:heal` always works as the unambiguous form.
|
||||
|
||||
## Client scripts
|
||||
|
||||
@@ -584,6 +742,8 @@ interface ClientContext {
|
||||
}
|
||||
```
|
||||
|
||||
Only `ctx.player`, `ctx.world` and `ctx.log` work so far, the rest is phase 4.
|
||||
|
||||
Client scripts are for presentation. They can't change the world or inventories; they ask the server over a
|
||||
[mod channel](#mod-channels). Anything they show should be treated as a view of the server's state. Everything in a
|
||||
client script is visible to players and can be changed by them, so it must not be trusted for anything that matters.
|
||||
@@ -597,6 +757,8 @@ There are three ways to show a GUI. They're listed from least code to most. Pick
|
||||
|
||||
### 1. Forms (server only)
|
||||
|
||||
_Planned, phase 4._
|
||||
|
||||
Simple dialogs defined entirely by server code, like Bedrock's `@minecraft/server-ui`. The client draws them with the
|
||||
game's UI style. No client script is needed.
|
||||
|
||||
@@ -716,6 +878,8 @@ Items handed to scripts are live: setting `count` changes the stack, and a stack
|
||||
|
||||
### 3. Custom screens (client code)
|
||||
|
||||
_Planned, phase 4._
|
||||
|
||||
For anything forms and containers can't do: maps, skill trees, minigames, custom layouts. The client script registers a
|
||||
screen class, and the server opens it with some props:
|
||||
|
||||
@@ -798,6 +962,8 @@ doesn't involve the server.
|
||||
|
||||
### HUD
|
||||
|
||||
_Planned, phase 4._
|
||||
|
||||
```ts
|
||||
ctx.hud.register("copper_tools:heat", {
|
||||
on_render(g) {
|
||||
@@ -810,7 +976,7 @@ HUD elements draw every frame after the world, under open screens. They get thei
|
||||
|
||||
## Mod channels
|
||||
|
||||
Client and server parts of a mod talk over named channels. Messages are JSON.
|
||||
_Planned, phase 4._ Client and server parts of a mod talk over named channels. Messages are JSON.
|
||||
|
||||
```ts
|
||||
// server.ts
|
||||
@@ -848,7 +1014,7 @@ Each chunk is generated in three passes:
|
||||
3. **Features.** Every mod's registered features, in load order.
|
||||
|
||||
The world is 256 blocks tall and the sea is at y 64 (`CHUNK_HEIGHT` and `SEA_LEVEL` in `common/constants.ts`). The
|
||||
base overworld lives in `common/worldgen/` until phase 3 moves it into `mods/bworld`. It works like Minecraft 1.18+ and
|
||||
base overworld lives in `common/worldgen/` until phase 6 moves it into `mods/bworld`. It works like Minecraft 1.18+ and
|
||||
the Terralith datapack: continentalness, erosion and weirdness noises feed nested splines that give every column a
|
||||
height, jaggedness and roughness, a 3D density around that height is sampled on a coarse grid and interpolated, and
|
||||
caves are cut out of it. On top of that come Terralith-style shapes: terraced plateaus, shattered hills, river valleys
|
||||
@@ -859,7 +1025,8 @@ how many grow and which kinds. `deno run -A tools/worldgen_preview.ts [seed]` re
|
||||
|
||||
### Terrain generators
|
||||
|
||||
A world uses exactly one terrain generator, registered by a worldgen script. The base game's is `bworld:overworld`.
|
||||
A world uses exactly one terrain generator, registered by a worldgen script. The base game's will be `bworld:overworld`
|
||||
(phase 6); until then `register_terrain` throws and the engine's own overworld is used.
|
||||
Which one a world uses is saved with the world. A new world uses the only one installed, or the server's `TERRAIN`
|
||||
setting when there are several. A server with no terrain generator refuses to start.
|
||||
|
||||
@@ -954,6 +1121,111 @@ interface FeatureChunk {
|
||||
- Each feature's `rng` is seeded with its own id, so adding or removing another mod's feature doesn't change what this
|
||||
one generates.
|
||||
|
||||
## Engine access
|
||||
|
||||
For what the Game API doesn't cover yet: a new kind of rendering, different player physics, a change to how lighting
|
||||
spreads, an entity type. Like Fabric's mixins, a mod can reach the engine's own classes and hook their methods, on the
|
||||
server and on the client. It's powerful and unstable at once, so a mod has to ask for it. _Planned, phase 3._
|
||||
|
||||
```json
|
||||
{ "engine_access": true, "game_version": "~0.4.0" }
|
||||
```
|
||||
|
||||
```ts
|
||||
// client.ts: an outline around every dropped item
|
||||
import type { ClientContext } from "bworld/client";
|
||||
import { engine, hook } from "bworld/engine";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
hook(engine.client.LevelRenderer.prototype, "render_entities", {
|
||||
after(renderer, [level, camera_entity, partial_tick]) {
|
||||
for (const entity of level.entities.values()) {
|
||||
if (entity instanceof engine.client.ItemEntity) draw_outline(entity, partial_tick);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// server.ts: broken blocks drop twice
|
||||
import { engine, hook } from "bworld/engine";
|
||||
|
||||
export function setup() {
|
||||
hook(engine.server.GameServer.prototype, "pop_item", {
|
||||
after(game, [x, y, z, stack], entity) {
|
||||
game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
|
||||
return entity;
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// client.ts: everything falls at half speed. physics is an object so its functions can be hooked, see below
|
||||
import { engine, hook } from "bworld/engine";
|
||||
|
||||
export function setup() {
|
||||
hook(engine.common.physics, "move_body", {
|
||||
before(_physics, args) {
|
||||
args[1] /= 2; // gravity
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### What `bworld/engine` gives
|
||||
|
||||
- `engine` holds the engine's modules as they run on that side: `engine.common` (registries, constants, inventory,
|
||||
physics, generation, the protocol types) everywhere, `engine.server` (`GameServer`, `ServerWorld`, `ModRuntime`, the
|
||||
running `game`) in server scripts, and `engine.client` (`Client`, `ClientLevel`, the renderer, GUI classes, the running
|
||||
`client`) in client scripts. Worldgen scripts get `engine.common` only.
|
||||
- They're the live classes and objects the game uses, not copies: the engine puts them on the global object at startup,
|
||||
and `bworld/engine` in a mod's bundle is a small shim that reads them. So a hook on a prototype changes every instance
|
||||
the engine already made.
|
||||
- The types are the engine's own source, so `check-mods` typechecks a mod against exactly the engine it will run on, and
|
||||
an engine change that breaks a mod shows up there first.
|
||||
|
||||
### Hooks
|
||||
|
||||
```ts
|
||||
function hook<T, K extends keyof T>(target: T, method: K, handlers: {
|
||||
// runs first. change args in place, or return { result } to skip the method and everything after
|
||||
before?(self: T, args: Parameters<T[K]>): { result: ReturnType<T[K]> } | void;
|
||||
// wraps the method, calling original (or not)
|
||||
replace?(self: T, args: Parameters<T[K]>, original: T[K]): ReturnType<T[K]>;
|
||||
// runs last, and returns the result the caller gets
|
||||
after?(self: T, args: Parameters<T[K]>, result: ReturnType<T[K]>): ReturnType<T[K]>;
|
||||
// lower runs earlier, the default is 1000. ties go in load order
|
||||
priority?: number;
|
||||
}): () => void; // unhook
|
||||
```
|
||||
|
||||
- Hooks on a prototype apply to every instance, hooks on one object only to it.
|
||||
- Several mods can hook the same method. `before` hooks run in priority order, `replace` hooks nest (the first one's
|
||||
`original` is the next one's wrapper, the last one's is the engine's method), and `after` hooks run in priority order,
|
||||
each getting the previous one's result.
|
||||
- A hook that throws is logged under its mod and skipped, like event handlers. The method still runs.
|
||||
- Functions exported from a module can't be hooked, because a module's exports can't be reassigned. The engine puts
|
||||
functions mods may want to change on plain objects (like `engine.common.physics`) and calls them through those objects
|
||||
itself, so a hook changes what the engine calls. Classes' methods are hookable on their prototype.
|
||||
- JavaScript's `#private` members can't be hooked or read. The engine keeps things that mods should be able to change
|
||||
as normal members, and `#private` for things with rules that must hold (like a container's slots). Making something
|
||||
hookable is an ordinary engine change, and asking for one is how the Game API grows.
|
||||
- Hooks reach one JavaScript realm: the game server worker for server scripts, the page for client scripts, and one
|
||||
chunk worker for worldgen scripts. Each chunk worker runs its own copy of the engine, so a hook in a client script
|
||||
doesn't change meshing; a worldgen script with engine access can.
|
||||
|
||||
### Rules
|
||||
|
||||
- **It isn't a stable API.** Any game update can rename or change what a hook targets. A mod with `engine_access` must
|
||||
set `game_version` to a range within one minor version (like `~0.4.0`). Loading it on another version is a load error
|
||||
naming the mod, instead of a crash somewhere later.
|
||||
- **Prefer the Game API.** When it can do something, it keeps working across updates. Engine access is for what it
|
||||
can't do yet, and a mod that hooks the same thing as many others is a sign it should become part of the Game API.
|
||||
- Without `engine_access`, importing `bworld/engine` is a `check-mods` error and a load error.
|
||||
- See [Security](#security) for what it means for players and servers.
|
||||
|
||||
## Delivery to clients
|
||||
|
||||
### Build
|
||||
@@ -963,7 +1235,8 @@ interface FeatureChunk {
|
||||
```
|
||||
build/mods/<id>/<hash>/ # public, served to players
|
||||
manifest.json
|
||||
data.json # all blocks, items, recipes and ores merged
|
||||
data.json # all blocks, items, models, recipes, overrides and ores merged
|
||||
common.js
|
||||
client.js
|
||||
worldgen.js
|
||||
server_mods/<id>/<hash>/ # private, outside the static root, never served
|
||||
@@ -986,11 +1259,11 @@ client server
|
||||
│ │
|
||||
│ [cross-origin: confirm screen] │
|
||||
│ download the atlas and every mod file, │
|
||||
│ check each one's sha256, register data │
|
||||
│ check each one's sha256, load content │
|
||||
│ in the listed order, run client │
|
||||
│ setup(), start chunk workers │
|
||||
│ │
|
||||
│ ready │
|
||||
│ ready { registry_hash } │ a different hash gets rejected { reason }
|
||||
├────────────────────────────────────────►│
|
||||
│ join { id, name, players, entities, │ the player is created here, player_join fires,
|
||||
│ changes, spawn, selected_slot } │ and their inventory follows as container messages
|
||||
@@ -1024,6 +1297,12 @@ where the page came from:
|
||||
headers on `build/mods/`.
|
||||
- The hash check confirms the files are the ones the server listed. It doesn't protect against a malicious server.
|
||||
|
||||
**Engine access.** A server mod with engine access controls the game server worker completely, but the worker still
|
||||
has no Deno permissions, so it can't reach files or the network any more than other server scripts. A client mod with
|
||||
engine access changes nothing about what it _can_ reach, since client scripts already run with the page's full access,
|
||||
but it can change how the game behaves for players in ways the Game API can't. The confirm screen for other servers
|
||||
lists which mods use engine access.
|
||||
|
||||
**Server scripts.** They run in a worker with **no Deno permissions** (Deno worker permissions; currently needs
|
||||
`--unstable-worker-options`). They can't read files, open connections or run programs. Everything they need goes through
|
||||
the mod API. Installing a server mod still means trusting it with the game world and everything players send.
|
||||
@@ -1044,6 +1323,7 @@ A smelter block with a container screen, a stats screen written in client code,
|
||||
"id": "copper_tools",
|
||||
"name": "Copper Tools",
|
||||
"version": "1.0.0",
|
||||
"dependencies": [{ "id": "bworld", "version": "*" }],
|
||||
"scripts": { "server": "scripts/server.ts", "client": "scripts/client.ts" }
|
||||
}
|
||||
```
|
||||
@@ -1152,182 +1432,150 @@ class SmelterStats implements ModScreen {
|
||||
}
|
||||
```
|
||||
|
||||
## The base game as a mod
|
||||
## The engine and the base game
|
||||
|
||||
Everything that makes bworld _bworld_ (its blocks, items, recipes, textures, block behavior and terrain) moves into a
|
||||
mod at `mods/bworld`, written against the same API as any other mod. The engine keeps only what every game built on it
|
||||
needs.
|
||||
Like a Minetest game, bworld is the engine plus one mod, `mods/bworld`, written against the same API as any other mod.
|
||||
This is how the API gets tested for real: if the base game can't be written as a mod, the API is missing something, and
|
||||
other mods would hit the same wall. It also means there's one way content works, so mods can do anything the base game
|
||||
does, and change any of it.
|
||||
|
||||
This is how the mod API gets tested for real: if the base game can't be written as a mod, the API is missing something,
|
||||
and other mods would hit the same wall. It also means there's one way content works instead of two, so mods can do
|
||||
anything the base game does.
|
||||
**The engine** keeps what every game built on it needs: rendering, meshing, lighting and the sky; physics, player
|
||||
movement and input; networking, saving, the game server and its loop; registries, the mod loader and the Game API;
|
||||
containers, slot click rules, screens and the GUI toolkit; item entities; chat; world time; `/tps`; `bworld:air`; and
|
||||
the engine assets in `assets/` (UI sprites, font, player sprite, and the `engine:` textures and block models).
|
||||
|
||||
### What moves
|
||||
**`mods/bworld`** has everything else:
|
||||
|
||||
| Content | Now | In `mods/bworld` |
|
||||
| ------------------------------------ | ------------------------------ | --------------------------------------------------------------- |
|
||||
| 18 blocks | `common/blocks/*.ts` | `blocks/*.json` |
|
||||
| 11 items | `common/items/*.ts` | `items/*.json` |
|
||||
| 62 textures | `assets/sprites/textures/` | `textures/` |
|
||||
| 5 crafting recipes | `server/game/crafting.ts` | `recipes/*.json`, type `shaped` |
|
||||
| 6 furnace recipes, 2 fuels | `server/game/blocks.ts` | `recipes/*.json`, types `furnace` and `fuel` |
|
||||
| Hoeing grass and dirt | `server/game/blocks.ts` | component `bworld:hoeable`, params `{ tool, into }` |
|
||||
| Chest | `server/game/blocks.ts` | component `bworld:storage`, params `{ rows }` |
|
||||
| Furnace (smelting, fuel, its screen) | `server/game/blocks.ts` | component `bworld:furnace` |
|
||||
| Watering can's starting water | `common/items/watering_can.ts` | item component `bworld:watering_can`, params `{ max_water }` |
|
||||
| Terrain and biomes | `common/worldgen/` | terrain generator `bworld:overworld` in `scripts/worldgen.ts` |
|
||||
| Ore table (`BASE_ORES`) | `common/generation.ts` | `worldgen/ores.json`, unchanged |
|
||||
| Texture credits (the Kenney packs) | `assets/ASSETS.md` | `CREDITS.md`, listed in the manifest's `credits` |
|
||||
|
||||
Not moved:
|
||||
|
||||
- **Carrots, potatoes, tomatoes and pumpkins** (`common/blocks/crops.ts`) are unfinished and mostly commented out.
|
||||
Wheat uses the `bworld:crop` component instead, and they can too once they have blocks.
|
||||
- **The watering can's lore** moved into its component's `get_lore`, but it isn't shown anywhere yet, because the game
|
||||
has no item tooltips.
|
||||
|
||||
### What stays in the engine
|
||||
|
||||
Rendering, physics and player controls; chunks, meshing and the generation passes (noise helpers, chunk assembly, ores,
|
||||
features); networking, saving and the game server; registries and the mod loader; inventories, the crafting grid, slot
|
||||
click rules and the generic container screen; chat and `/give`; `bworld:air`; and the engine assets in `assets/`: the UI
|
||||
sprites, font, player sprite and the `engine:` textures (the breaking cracks and the missing texture).
|
||||
| What | Where it is now | Status |
|
||||
| ---------------------------------------------------- | ----------------------------------- | ----------------------- |
|
||||
| Blocks, items, models, recipes, textures, credits | `mods/bworld` JSON and `textures/` | Done |
|
||||
| Hoeing, chest, furnace, smithing table, crops, watering can | `mods/bworld/scripts/server.ts` | Done |
|
||||
| Recipe types `shaped`, `furnace`, `fuel`, `smithing` | engine (`common/mod_loader.ts`, `server/game/crafting.ts`) | Phase 5 |
|
||||
| The player's inventory screen and crafting grid | engine (`client/gui/gui_player_inventory.ts`, `server/game/crafting.ts`) | Phase 5 |
|
||||
| The hotbar and crosshair | engine (`client/gui/hud.ts`) | Phase 5 |
|
||||
| `/give` and `/time` | engine (`server/game/game_server.ts`) | Phase 5 |
|
||||
| Mining: tool speed, `requires_tool`, drops | engine (`client/game_mode.ts`, `server/game/game_server.ts`) | Phase 5 |
|
||||
| Day and night lengths, sky colors | engine (`common/time.ts`, `client/rendering/game_renderer.ts`) | Phase 5 |
|
||||
| Where new players spawn | engine (`server/game/world.ts`) | Phase 5 |
|
||||
| Terrain, biomes, trees and ores | engine (`common/worldgen/`, `common/generation.ts`) | Phase 6 |
|
||||
|
||||
### Rules that keep existing worlds working
|
||||
|
||||
Worlds saved before the move must load afterwards with nothing changed:
|
||||
Worlds saved before any of this must load afterwards with nothing changed:
|
||||
|
||||
1. **Ids don't change.** Saves store blocks and items by string id, including player inventories and chest contents. The
|
||||
JSON uses exactly the ids the TypeScript files register now.
|
||||
1. **Ids don't change.** Saves store blocks and items by string id, including player inventories and chest contents.
|
||||
2. **Terrain is identical, block for block.** A save only stores what players changed _on top of_ generated terrain. If
|
||||
the generator's output changes at all, every existing world silently changes with it: trees move and blocks players
|
||||
broke reappear. The golden terrain test (phase 0) enforces this.
|
||||
3. **Tile data keeps its shape.** Chests store their items in `containers.main`, and furnaces keep `containers.main`
|
||||
plus `progress`, `progress_max`, `fuel` and `fuel_max` in `data`. The components read exactly those, so tiles saved
|
||||
by the current code load into them.
|
||||
4. **The protocol doesn't change, and old saves load.** Clients receive `mods/bworld` like any other mod. The save
|
||||
format may change when it has to, as long as older saves are upgraded when loading (phase 2 did, to version 3).
|
||||
broke reappear. The golden terrain test (phase 6) enforces this.
|
||||
3. **Old saves are upgraded when loading.** The save format can change when it has to, like version 3 did for
|
||||
containers, as long as older saves load into the new shape. `tests/fixtures/` keeps a save from each version.
|
||||
4. **The protocol can change, with `PROTOCOL_VERSION`.** Clients on another version are asked to reload before anything
|
||||
else happens.
|
||||
|
||||
### Phases
|
||||
## Implementation plan
|
||||
|
||||
Each phase ends with every test passing and the game playable.
|
||||
**Done so far:** the mod loader, build and delivery to clients (hashed downloads, the confirm screen for other servers,
|
||||
credits); the data layer (blocks, block models with variants, items, recipes, ores); server scripts with components,
|
||||
events, commands, timers, storage, recipes, containers and container screens; worldgen features and ores; the base
|
||||
game's block behavior as a mod; world time with day and night. The code is in `common/mod_loader.ts`,
|
||||
`common/mod_data.ts`, `server/game/mod_runtime.ts`, `client/mods.ts` and `common/worldgen_loader.ts`.
|
||||
|
||||
**Phase 0: safety net.** Do this first, before any other mod work. Started: `deno task test` runs `tests/`, which covers
|
||||
loading mods (the base game and the template), their scripts and worldgen, saves, and the mod tools.
|
||||
Each phase ends with every test passing and the game playable. Phases 1 to 3 are the foundation; 4 to 6 can happen in
|
||||
any order after them.
|
||||
|
||||
- Move the test scripts used while building steps 1–3 into the repo as `deno test` files under `tests/`: server logic
|
||||
(breaking, placing, crafting, chest, furnace, saves), client and server terrain agreement, click prediction, and the
|
||||
end-to-end WebSocket test.
|
||||
- Record golden fixtures from the current code: `tests/fixtures/registry.json`, every block and item with all its fields
|
||||
(functions left out), and `tests/fixtures/terrain.json`, a SHA-256 of the final blocks of 64 chunks for 3 seeds,
|
||||
including negative coordinates and chunks with trees on their borders.
|
||||
- Save a world from the current code with chests, a running furnace and some player inventories as
|
||||
`tests/fixtures/world_v2.json`, with a test that loads it and checks everything is where it was.
|
||||
**Phase 1: loading and common scripts.**
|
||||
|
||||
**Phase 1: data** (after steps 4 and 5). _Done._
|
||||
- `scripts.common`, bundled like the client script, run on the server and on clients between each mod's data and the
|
||||
next mod.
|
||||
- `CommonContext` with `ctx.blocks`, `ctx.items`, `ctx.models` and `ctx.recipes` (`register`, `get`, `ids`). The JSON
|
||||
loader goes through the same functions, so there's one path for content.
|
||||
- The freeze: registries close after content loads, and registering later throws. Numeric ids, block items and recipe
|
||||
indexes are made at the freeze, not while registering.
|
||||
- The registry hash: both sides hash their registries after the freeze, the client sends its hash with `ready`, and a
|
||||
mismatch turns the player away naming the first difference.
|
||||
- Recipe types become ids with `register_type` and `list`, with `shaped`, `furnace`, `fuel` and `smithing` as short
|
||||
names for the base game's. Server scripts get `ctx.recipes.list(type)`.
|
||||
- Check: a test mod registers blocks, items and recipes from code, and the server and a client end up with equal
|
||||
registries and hashes. A common script that registers something different on each side is caught by the hash.
|
||||
|
||||
- Create `mods/bworld` with its manifest and credits, and move the 62 textures there. Rename the breaking cracks to
|
||||
`engine:break_0`–`8` and the fallback to `engine:missing`.
|
||||
- Generate the block, item and recipe JSON with a script that reads the current registries, instead of writing it by
|
||||
hand. Hand-copying 18 blocks' fields is how typos get in. They were generated this way, checked equal to the
|
||||
TypeScript definitions, and those were then deleted.
|
||||
- The loader registers the recipes and `server/game/crafting.ts` matches against them. Behaviors stay in
|
||||
`server/game/blocks.ts`, still keyed by block id, for now.
|
||||
- Delete `common/blocks/` and `common/items/`.
|
||||
- Check: the registry built from JSON equals `registry.json`, and all tests pass.
|
||||
**Phase 2: overrides.**
|
||||
|
||||
**Phase 2: behavior** (after step 6, and container screens from step 7). _Done._
|
||||
- `override` and `extend` in common scripts, and `overrides/*.json` for the same thing as data. `recipes.remove`.
|
||||
- `check-mods`: changing content of a mod that isn't a dependency is an error, two mods changing the same field is a
|
||||
warning.
|
||||
- Check: a test mod adds a component to `bworld:grass`, changes `bworld:glass`'s toughness and replaces the chest
|
||||
recipe, and all of it works on both sides and in the registry hash.
|
||||
|
||||
- `mods/bworld/scripts/server.ts` registers `bworld:hoeable`, `bworld:storage`, `bworld:furnace`, `bworld:crop` (bone
|
||||
meal on wheat) and `bworld:watering_can`. The chest and furnace open their screens with `ctx.ui.open_container`, with
|
||||
the same layouts as before.
|
||||
- The block and item JSON lists the components. `server/game/blocks.ts` is deleted.
|
||||
- Saves went to version 3: tiles only keep `mod_data`, and containers are saved by id. Version 2 chests and furnaces are
|
||||
upgraded when loaded: their `data` fields stay and their `containers.main` becomes a container whose id is in
|
||||
`container`, which is the shape the components use.
|
||||
- Check: `tests/base_game_test.ts` (hoeing, chest, furnace smelting, breaking a chest gives its contents back, bone meal,
|
||||
the watering can) and `tests/fixtures/world_v2.json`, saved by the engine code before the move, pass.
|
||||
**Phase 3: engine access.**
|
||||
|
||||
**Phase 3: world generation** (after step 9).
|
||||
- The engine puts its modules on the global object at startup on each side (page, game server worker, chunk workers),
|
||||
and the build turns `bworld/engine` imports into a shim that reads them. Types come from the engine's source.
|
||||
- `hook` with `before`, `replace`, `after`, priorities and unhooking.
|
||||
- `engine_access` in the manifest: `check-mods` and the loader refuse `bworld/engine` imports without it, and refuse
|
||||
loading on a game version outside the mod's range. The confirm screen and the join screen say which mods use it.
|
||||
- Go through the engine for things mods will want to change and make them hookable: move module functions like
|
||||
`move_body` onto objects the engine calls through, and turn `#private` members that don't protect a rule into normal
|
||||
ones.
|
||||
- Check: test mods hook a server method, a client method and a worldgen method, several hooks on one method run in
|
||||
priority order, and a throwing hook is logged without breaking the game.
|
||||
|
||||
- Port `common/worldgen/` to `mods/bworld/scripts/worldgen.ts` as the `bworld:overworld` terrain generator. It's a
|
||||
straight port: it only uses named noises, which are exactly `noise_2d` / `noise_3d` in
|
||||
[Terrain generators](#terrain-generators).
|
||||
- Move `BASE_ORES` to `mods/bworld/worldgen/ores.json`. They already run through the same ore pass as mods' ores, in
|
||||
the same order, so the result is identical.
|
||||
- Remove the content from `common/generation.ts`, leaving the passes and noise helpers.
|
||||
- Check: `terrain.json` matches exactly, client and server terrain still agree, and `world_v2.json` loads unchanged.
|
||||
**Phase 4: the rest of the Game API.**
|
||||
|
||||
**Phase 4: engine cleanup.**
|
||||
- Mod channels (`ctx.net` on both sides, `{ type: "mod", channel, data }`, the size and rate limits).
|
||||
- Keybinds (`ctx.input.bind`), forms (`message_form`, `action_form`, `modal_form`), custom screens with `Graphics`, and
|
||||
HUD elements.
|
||||
- More events: items picked up and dropped, containers clicked, players moving between chunks, entities.
|
||||
- Check: the example mod below works end to end, and every server event has a test.
|
||||
|
||||
- Replace the hardcoded water checks in `server/game/game_server.ts` with the `replaceable` block field, like
|
||||
`client/game_mode.ts` already does.
|
||||
- `/give` stops assuming `bworld:`. It looks names up across all namespaces and asks for the full id when two mods have
|
||||
the same name.
|
||||
- Rename engine asset keys like `bworld:ui` and `bworld:m6x11` in `client/main.ts` to `engine:`, so `bworld:` only means
|
||||
content.
|
||||
- The Credits screen (title screen and pause menu) shows the engine's `assets/ASSETS.md` plus every loaded mod's credits.
|
||||
_Done._ Credits are published next to the mod's data and checked by hash like everything else.
|
||||
**Phase 5: gameplay out of the engine.**
|
||||
|
||||
- `/give` and `/time` become commands in `mods/bworld`. `/tps` stays, it's about the engine.
|
||||
- The crafting grid's matching and the `shaped` recipe type move into `mods/bworld`, and the player's inventory screen
|
||||
becomes a screen `mods/bworld` registers, opened by the engine's inventory key.
|
||||
- The hotbar and crosshair become `mods/bworld` HUD elements.
|
||||
- Mining rules (how long breaking takes, tool speed, `requires_tool`, what drops) become something `mods/bworld` sets,
|
||||
with the engine asking it on both sides so clients still predict breaking.
|
||||
- The day and night lengths and sky colors become settings `mods/bworld` makes in its common script. The engine keeps
|
||||
counting ticks.
|
||||
- Where new players spawn becomes `mods/bworld`'s choice.
|
||||
- Check: all tests pass unchanged, and `world_v2.json` and a version 3 save still load.
|
||||
|
||||
**Phase 6: world generation.**
|
||||
|
||||
- First the golden fixture: `tests/fixtures/terrain.json`, a SHA-256 of the final blocks of 64 chunks for 3 seeds,
|
||||
including negative coordinates and chunks with trees on their borders, recorded from the current code.
|
||||
- Port `common/worldgen/` to `mods/bworld/scripts/worldgen.ts` as the `bworld:overworld` terrain generator. It only uses
|
||||
named noises, which are exactly `noise_2d` / `noise_3d` in [Terrain generators](#terrain-generators).
|
||||
- Move the ore table to `mods/bworld/worldgen/ores.json`, and take the content out of `common/generation.ts`, leaving
|
||||
the passes and noise helpers.
|
||||
- The server refuses to start without a terrain generator, naming the mods that could provide one.
|
||||
- Check: `terrain.json` matches exactly, client and server terrain still agree, and old saves load unchanged.
|
||||
|
||||
### Done when
|
||||
**Done when:**
|
||||
|
||||
- Searching `client/`, `common/` and `server/` for `"bworld:` finds only `bworld:air`.
|
||||
- Removing `mods/bworld` gives an engine that starts and says it needs a terrain generator, instead of crashing
|
||||
somewhere.
|
||||
- All tests pass, the golden fixtures are unchanged, and a world saved before the move plays exactly the same after it.
|
||||
|
||||
## Implementation plan
|
||||
|
||||
Steps 1–6 are done and 9 mostly, enough that a mod made from the template loads and runs. Each step keeps the game
|
||||
working:
|
||||
|
||||
1. **Game server core.** Move `client/generation.ts` to `common/` (it already only needs constants and the rng package)
|
||||
and have the server generate terrain. Move world state, chunks, tile data and player inventories into a game server
|
||||
module that runs in a Deno worker, with `server/main.ts` handling HTTP, WebSockets and files.
|
||||
2. **Server authority.** Change the protocol from "here's the block I changed" to intents (`break_block`, `place_block`,
|
||||
`interact`, `select_slot`, `container_click`). The client keeps showing breaks and places immediately and accepts
|
||||
corrections. Move inventories, drops and `/give` to the server. Replace `GuiChest` / `GuiFurnace` with server-synced
|
||||
containers.
|
||||
3. **Server only.** Remove the offline fallback in `client/main.ts`, which currently starts a local game when it can't
|
||||
reach a server, and show a connection error instead.
|
||||
4. **Mod loader and build.** Discover mods, check manifests, sort by dependencies, turn JSON into registry entries,
|
||||
build the combined atlas (textures are currently all named `bworld:<file>`), bundle scripts per side, and write
|
||||
hashed output to `build/mods/` and `server_mods/`. _Done._
|
||||
5. **Delivery.** Split `welcome` into `welcome` / `ready` / `join`. Clients download, verify and run mods before
|
||||
joining. Add the confirm screen for cross-origin servers and CORS headers on the server. _Done._
|
||||
6. **Server scripts.** Components, events, commands, system, storage and `ctx.recipes`. Move `FURNACE_RECIPES` and
|
||||
`FUEL_VALUES` into the recipe registry. _Done_ (`server/game/mod_runtime.ts`, with the loop in
|
||||
`server/game/game_loop.ts`). `ctx.net` throws until step 8, and so do the client's `ctx.ui`, `ctx.hud`,
|
||||
`ctx.input` and `ctx.net`.
|
||||
7. **GUIs.** Forms, then container screens (rebuild chest and furnace with them), then custom screens, the `Graphics`
|
||||
API (built on the existing renderer and debug UI widgets) and the HUD. _Container screens done_ (`ctx.containers`,
|
||||
`ctx.ui.open_container`), forms and custom screens throw until they're built.
|
||||
8. **Mod channels** and keybinds.
|
||||
9. **Worldgen mods.** Worldgen URLs and mod ores go into the chunk worker `init` message. Workers must finish importing
|
||||
before generating anything. _Done for features and ores._ `register_terrain` throws until phase 3 moves the base
|
||||
terrain out of the engine.
|
||||
|
||||
Steps 1–3 are engine work every multiplayer feature needs, with or without mods. Mods could start with data only (step 4
|
||||
plus data in step 5) before scripts exist.
|
||||
|
||||
Moving the base game into `mods/bworld` happens alongside steps 4–9. See
|
||||
[The base game as a mod](#the-base-game-as-a-mod) for which phase follows which step.
|
||||
- The base game uses only the Game API, no engine access. If it needs a hook for something, that thing belongs in the
|
||||
Game API.
|
||||
- All tests pass, the golden fixtures are unchanged, and a world saved before any of this plays exactly the same.
|
||||
|
||||
## Open questions
|
||||
|
||||
- **Chunk delivery.** Clients generate terrain from the seed, which needs deterministic worldgen and trusts clients to
|
||||
run the same generator. Sending chunks from the server instead (like Minecraft) removes both problems but costs
|
||||
bandwidth, roughly 5–15 KB per chunk compressed. It could be worth it once the server generates terrain anyway.
|
||||
- **Client-only mods.** Should players be able to install their own client mods (minimaps, UI tweaks) that work on any
|
||||
server? They'd need a separate `"side": "client"` kind of mod that can't add content, and servers might want to forbid
|
||||
them.
|
||||
- **Client-only mods.** Should players be able to install their own client mods (minimaps, UI tweaks, shaders) that work
|
||||
on any server, like Fabric's client mods? They'd need a separate `"side": "client"` kind of mod that can't add content
|
||||
or change the registry hash, and servers might want to forbid them.
|
||||
- **Client-side prediction for mods.** Custom block components only run on the server, so interacting with a mod block
|
||||
always waits one round trip. Optional client-side component handlers for prediction could fix that later.
|
||||
- **Overriding base game content.** Replacing `bworld:` blocks is forbidden for now. An `"extends"` field that adds
|
||||
components to an existing block (for example to `bworld:grass`) is a possible middle ground.
|
||||
always waits one round trip. Components could get optional handlers in common scripts that clients run to predict.
|
||||
- **Engine access versions.** Tying engine access mods to one minor version is simple but strict. Fabric gets further
|
||||
with mapped names and mixin error reporting; how much of that is worth building depends on how often the engine
|
||||
changes under mods.
|
||||
- **Game API versions.** The Game API only breaking with the game's major version is a promise that needs deprecation
|
||||
warnings and a changelog to keep.
|
||||
- **Screen scaling.** The GUI currently works in raw canvas pixels (`SLOT_SIZE` is 54). `Graphics` should probably use a
|
||||
UI scale the player can change, with screens laid out in scaled units.
|
||||
- **Entities.** The only entities are players (`client/entity/`), so mob mods are out of scope until there are more
|
||||
entity types.
|
||||
- **Entities.** The only entities are players and dropped items, so mob mods need entity types in the Game API first.
|
||||
- **Hot reload.** Restarting the server and reconnecting is the version 1 answer.
|
||||
|
||||
@@ -20,8 +20,8 @@ const TITLE_SCALE = 8;
|
||||
// for the player when it fails
|
||||
export type JoinServer = (address: ServerAddress, name: string, status: (text: string) => void) => Promise<void>;
|
||||
|
||||
// the first thing players see, like minecraft's title and multiplayer screens rolled into one:
|
||||
// a name, a server, and a button to join it
|
||||
// the first thing players see, like minecraft's title and multiplayer screens rolled into one: a name, a server,
|
||||
// and a button to join it. in the desktop app there's also singleplayer, which joins the app's own server
|
||||
export class TitleScreen extends GuiScreen {
|
||||
#join_server: JoinServer;
|
||||
|
||||
@@ -33,6 +33,10 @@ export class TitleScreen extends GuiScreen {
|
||||
);
|
||||
server = new EditBox(WIDTH, ROW_HEIGHT, new TextInput(initial_server(), 256, (char) => char !== " "), "host:port");
|
||||
join_button = new Button("Join server", WIDTH, ROW_HEIGHT, () => this.#join());
|
||||
// the page was served by a game server of its own to play on alone, see desktop/main.ts
|
||||
singleplayer_button = has_singleplayer()
|
||||
? new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => this.#join_singleplayer())
|
||||
: undefined;
|
||||
credits_button = new Button("Credits", WIDTH, ROW_HEIGHT, () => this.#open_credits());
|
||||
// open over the title screen, it gets the input while it's there
|
||||
#credits: CreditsScreen | undefined;
|
||||
@@ -75,6 +79,7 @@ export class TitleScreen extends GuiScreen {
|
||||
if (InputManager.is_key_pressed("Enter")) {
|
||||
this.#join();
|
||||
}
|
||||
this.singleplayer_button?.handle_input();
|
||||
this.join_button.handle_input();
|
||||
this.credits_button.handle_input();
|
||||
}
|
||||
@@ -92,6 +97,7 @@ export class TitleScreen extends GuiScreen {
|
||||
this.#label("Name", this.name);
|
||||
this.#label("Server", this.server);
|
||||
this.name.render();
|
||||
this.singleplayer_button?.render();
|
||||
this.server.render();
|
||||
this.join_button.render();
|
||||
this.credits_button.render();
|
||||
@@ -121,12 +127,18 @@ export class TitleScreen extends GuiScreen {
|
||||
|
||||
#layout() {
|
||||
const x = (canvas.width - WIDTH) / 2;
|
||||
const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + 2 * ROW_HEIGHT + GAP;
|
||||
const singleplayer_height = this.singleplayer_button ? ROW_HEIGHT + GAP : 0;
|
||||
const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + singleplayer_height + 2 * ROW_HEIGHT + GAP;
|
||||
let y = (canvas.height - total) / 2 + 40;
|
||||
for (const field of [this.name, this.server]) {
|
||||
field.x = x;
|
||||
field.y = y + LABEL_GAP;
|
||||
y += LABEL_GAP + ROW_HEIGHT + GAP;
|
||||
if (field === this.name && this.singleplayer_button) {
|
||||
this.singleplayer_button.x = x;
|
||||
this.singleplayer_button.y = y;
|
||||
y += singleplayer_height;
|
||||
}
|
||||
}
|
||||
this.join_button.x = x;
|
||||
this.join_button.y = y;
|
||||
@@ -151,10 +163,21 @@ export class TitleScreen extends GuiScreen {
|
||||
return;
|
||||
}
|
||||
remember(LAST_SERVER_KEY, this.server.value.trim());
|
||||
remember(LAST_NAME_KEY, this.name.value);
|
||||
await this.#connect(address);
|
||||
}
|
||||
|
||||
// the server that served this page
|
||||
async #join_singleplayer() {
|
||||
if (this.#joining) {
|
||||
return;
|
||||
}
|
||||
await this.#connect(server_address(location.host), "Starting singleplayer...");
|
||||
}
|
||||
|
||||
async #connect(address: ServerAddress, status = `Connecting to ${address.base.host}...`) {
|
||||
remember(LAST_NAME_KEY, this.name.value);
|
||||
this.#set_joining(true);
|
||||
this.status = `Connecting to ${address.base.host}...`;
|
||||
this.status = status;
|
||||
this.status_is_error = false;
|
||||
try {
|
||||
await this.#join_server(address, this.name.value, (text) => this.status = text);
|
||||
@@ -167,6 +190,9 @@ export class TitleScreen extends GuiScreen {
|
||||
#set_joining(joining: boolean) {
|
||||
this.#joining = joining;
|
||||
this.name.active = this.server.active = this.join_button.active = !joining;
|
||||
if (this.singleplayer_button) {
|
||||
this.singleplayer_button.active = !joining;
|
||||
}
|
||||
}
|
||||
|
||||
#show_error(message: string) {
|
||||
@@ -202,8 +228,19 @@ function remember(key: string, value: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// a server's mods can't be unloaded, so going back to the title screen starts the page over. without ?server=
|
||||
// or ?name=, so the fields show what was used last
|
||||
export function back_to_title() {
|
||||
location.href = location.pathname;
|
||||
function has_singleplayer() {
|
||||
return new URL(location.href).searchParams.has("singleplayer");
|
||||
}
|
||||
|
||||
// a server's mods can't be unloaded, so going back to the title screen starts the page over. without ?server=
|
||||
// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, its saved
|
||||
// fields don't last between launches and the page's own address isn't a server to join
|
||||
export function back_to_title() {
|
||||
const page = new URL(location.href);
|
||||
const next = new URL(location.pathname, location.href);
|
||||
if (has_singleplayer()) {
|
||||
next.searchParams.set("server", page.searchParams.get("server") ?? "");
|
||||
next.searchParams.set("singleplayer", "");
|
||||
}
|
||||
location.href = next.href;
|
||||
}
|
||||
|
||||
+19
-3
@@ -25,12 +25,11 @@ export function default_server(page = new URL(location.href)): string {
|
||||
return page.searchParams.get("server") ?? page.host;
|
||||
}
|
||||
|
||||
// what a player typed as the server: host:port, or a full http(s) or ws(s) url
|
||||
// what a player typed as the server: host:port, or a full http(s) or ws(s) url to pick the scheme
|
||||
export function server_address(input: string, page = new URL(location.href)): ServerAddress {
|
||||
const text = input.trim();
|
||||
let host = text;
|
||||
// without a scheme it's as secure as the page, browsers block insecure sockets from secure pages anyway
|
||||
let secure = page.protocol === "https:";
|
||||
let secure: boolean;
|
||||
if (text.includes("://")) {
|
||||
let url: URL;
|
||||
try {
|
||||
@@ -40,6 +39,10 @@ export function server_address(input: string, page = new URL(location.href)): Se
|
||||
}
|
||||
host = url.host;
|
||||
secure = url.protocol === "https:" || url.protocol === "wss:";
|
||||
} else {
|
||||
// servers on this machine are plain ws and everything else is wss, whatever the page was served over. the
|
||||
// desktop app's page is plain http on localhost, but the servers it joins are real domains behind tls
|
||||
secure = !is_local_host(host);
|
||||
}
|
||||
if (!host || /[\s/?#]/.test(host)) {
|
||||
throw new HandshakeError(`${text || "An empty address"} isn't a server address`);
|
||||
@@ -52,6 +55,19 @@ export function server_address(input: string, page = new URL(location.href)): Se
|
||||
};
|
||||
}
|
||||
|
||||
const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"];
|
||||
|
||||
// host is host:port, or just a host
|
||||
function is_local_host(host: string) {
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(`http://${host}/`).hostname;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return LOCAL_HOSTS.includes(hostname);
|
||||
}
|
||||
|
||||
// a socket whose messages all land in one queue, so none get lost between the handshake and the game
|
||||
export class ServerSocket {
|
||||
socket: WebSocket;
|
||||
|
||||
@@ -12,7 +12,7 @@ import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from
|
||||
import { AssetManager } from "../assets.ts";
|
||||
import { ChunkWorkerPool } from "../chunk_workers.ts";
|
||||
import { worldgen_mods } from "../mods.ts";
|
||||
import { type FromChunkWorker, TERRAIN_VERTEX_FLOATS } from "../workers/chunk_messages.ts";
|
||||
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
|
||||
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
|
||||
import { crosses_planes } from "../workers/translucent_sort.ts";
|
||||
import { Camera } from "../camera.ts";
|
||||
@@ -37,6 +37,9 @@ export interface Chunk {
|
||||
// bumped on every mesh request so late results from older requests get ignored
|
||||
mesh_version: number;
|
||||
meshes: Partial<Record<RenderLayer, ChunkMesh>>;
|
||||
// the lowest and highest y of its meshes, for frustum culling
|
||||
min_y: number;
|
||||
max_y: number;
|
||||
// only for translucent meshes that have to be sorted again as the camera moves
|
||||
translucent_sort?: TranslucentSort;
|
||||
// blocks its generation put in neighboring chunks (leaves), as x, y, z, numeric id. kept so a neighbor that
|
||||
@@ -49,6 +52,8 @@ export interface ChunkMesh {
|
||||
quad_count: number;
|
||||
// the translucent layer's quads sorted back to front, the others are drawn in order
|
||||
index_buffer?: GPUBuffer;
|
||||
// solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts
|
||||
groups?: FaceGroup[];
|
||||
}
|
||||
|
||||
interface TranslucentSort {
|
||||
@@ -63,8 +68,6 @@ interface TranslucentSort {
|
||||
applied: number;
|
||||
}
|
||||
|
||||
const FLOATS_PER_QUAD = 4 * TERRAIN_VERTEX_FLOATS;
|
||||
|
||||
export { chunk_key };
|
||||
|
||||
// the block being looked at and which face of it
|
||||
@@ -199,6 +202,8 @@ export class ClientLevel {
|
||||
generated: false,
|
||||
mesh_version: 0,
|
||||
meshes: {},
|
||||
min_y: 0,
|
||||
max_y: 0,
|
||||
};
|
||||
this.chunks.set(chunk_key(x, z), chunk);
|
||||
return chunk;
|
||||
@@ -548,16 +553,15 @@ export class ClientLevel {
|
||||
}
|
||||
|
||||
this.delete_chunk_mesh(chunk);
|
||||
chunk.min_y = message.min_y;
|
||||
chunk.max_y = message.max_y;
|
||||
|
||||
for (const layer of RENDER_LAYERS) {
|
||||
const { vertices, quad_count } = message[layer];
|
||||
const { vertices, quad_count, groups } = message[layer];
|
||||
if (quad_count === 0) {
|
||||
continue;
|
||||
}
|
||||
chunk.meshes[layer] = {
|
||||
vertex_buffer: create_vertex_buffer(vertices.subarray(0, quad_count * FLOATS_PER_QUAD)),
|
||||
quad_count,
|
||||
};
|
||||
chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
|
||||
}
|
||||
|
||||
const translucent = message.translucent;
|
||||
|
||||
+36
-13
@@ -1,7 +1,7 @@
|
||||
import type { Camera } from "../camera.ts";
|
||||
import { mat4 } from "gl-matrix";
|
||||
import type { RenderLayer } from "$/common/everything_registry.ts";
|
||||
import { TERRAIN_VERTEX_FLOATS } from "../workers/chunk_messages.ts";
|
||||
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
|
||||
|
||||
export let device: GPUDevice;
|
||||
export let canvas: HTMLCanvasElement;
|
||||
@@ -375,10 +375,16 @@ export function flush_batch() {
|
||||
vert_index = 0;
|
||||
}
|
||||
|
||||
// draws a chunk mesh made of quads (4 vertices each). without an index buffer the quads are drawn in order
|
||||
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
|
||||
// again for each one. cleared whenever the pipeline changes
|
||||
let terrain_binds: { slot: number; texture: GPUTexture; index_buffer: GPUBuffer } | undefined;
|
||||
|
||||
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
|
||||
// drawn in order
|
||||
export function draw_terrain(
|
||||
layer: RenderLayer,
|
||||
vertex_buffer: GPUBuffer,
|
||||
first: number,
|
||||
quad_count: number,
|
||||
index_buffer?: GPUBuffer,
|
||||
) {
|
||||
@@ -386,7 +392,7 @@ export function draw_terrain(
|
||||
return;
|
||||
}
|
||||
if (!index_buffer) {
|
||||
ensure_quad_indices(quad_count);
|
||||
ensure_quad_indices(first + quad_count);
|
||||
index_buffer = quad_index_buffer!;
|
||||
}
|
||||
|
||||
@@ -395,17 +401,33 @@ export function draw_terrain(
|
||||
if (current_pipeline !== pipeline) {
|
||||
render_pass.setPipeline(pipeline);
|
||||
current_pipeline = pipeline;
|
||||
terrain_binds = undefined;
|
||||
}
|
||||
|
||||
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
|
||||
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
||||
render_pass.setBindGroup(2, lightmap_bind_group);
|
||||
if (!terrain_binds) {
|
||||
render_pass.setBindGroup(2, lightmap_bind_group);
|
||||
}
|
||||
if (terrain_binds?.slot !== uniform_slot) {
|
||||
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
|
||||
}
|
||||
if (terrain_binds?.texture !== current_texture) {
|
||||
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
||||
}
|
||||
if (terrain_binds?.index_buffer !== index_buffer) {
|
||||
render_pass.setIndexBuffer(index_buffer, "uint32");
|
||||
}
|
||||
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer };
|
||||
|
||||
render_pass.setVertexBuffer(0, vertex_buffer);
|
||||
render_pass.setIndexBuffer(index_buffer, "uint32");
|
||||
render_pass.drawIndexed(quad_count * 6);
|
||||
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
|
||||
}
|
||||
|
||||
export function create_vertex_buffer(vertices: Float32Array): GPUBuffer {
|
||||
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
|
||||
export function view_projection(): Readonly<Float32Array> {
|
||||
return mvp as Float32Array;
|
||||
}
|
||||
|
||||
export function create_vertex_buffer(vertices: Float32Array<ArrayBuffer> | Uint8Array<ArrayBuffer>): GPUBuffer {
|
||||
const buffer = device.createBuffer({
|
||||
size: Math.max(4, vertices.byteLength),
|
||||
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
|
||||
@@ -598,6 +620,7 @@ function ensure_pass(): GPURenderPassEncoder {
|
||||
pending_color_clear = false;
|
||||
pending_depth_clear = false;
|
||||
current_pipeline = undefined;
|
||||
terrain_binds = undefined;
|
||||
apply_scissor(pass);
|
||||
|
||||
return pass;
|
||||
@@ -762,12 +785,12 @@ function create_pipelines() {
|
||||
module: terrain_module,
|
||||
entryPoint: "vs_terrain",
|
||||
buffers: [{
|
||||
arrayStride: TERRAIN_VERTEX_FLOATS * 4,
|
||||
arrayStride: TERRAIN_VERTEX_BYTES,
|
||||
attributes: [
|
||||
{ shaderLocation: 0, offset: 0, format: "float32x3" },
|
||||
{ shaderLocation: 1, offset: 12, format: "float32x2" },
|
||||
{ shaderLocation: 2, offset: 20, format: "float32x4" },
|
||||
{ shaderLocation: 3, offset: 36, format: "float32x2" },
|
||||
{ shaderLocation: 1, offset: 12, format: "unorm16x2" },
|
||||
{ shaderLocation: 2, offset: 16, format: "unorm8x4" },
|
||||
{ shaderLocation: 3, offset: 20, format: "unorm8x2" },
|
||||
],
|
||||
}],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// what the camera can see: the six planes around it, taken from its view projection matrix (gl-matrix's column major
|
||||
// order, with webgpu's 0 to 1 depth). a box is out of view when it's entirely behind one of them
|
||||
export class Frustum {
|
||||
// a, b, c, d per plane, where a * x + b * y + c * z + d >= 0 is the inside
|
||||
#planes = new Float32Array(24);
|
||||
|
||||
update(m: Readonly<Float32Array>) {
|
||||
const planes = this.#planes;
|
||||
const set = (i: number, a: number, b: number, c: number, d: number) => {
|
||||
planes[i * 4] = a;
|
||||
planes[i * 4 + 1] = b;
|
||||
planes[i * 4 + 2] = c;
|
||||
planes[i * 4 + 3] = d;
|
||||
};
|
||||
// row r of the matrix is m[r], m[4 + r], m[8 + r], m[12 + r]
|
||||
set(0, m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]); // left
|
||||
set(1, m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]); // right
|
||||
set(2, m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]); // bottom
|
||||
set(3, m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]); // top
|
||||
set(4, m[2], m[6], m[10], m[14]); // near, depth 0
|
||||
set(5, m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]); // far
|
||||
}
|
||||
|
||||
// whether any of the box can be seen. may say yes for boxes just outside a corner, never no for one inside
|
||||
intersects_box(min_x: number, min_y: number, min_z: number, max_x: number, max_y: number, max_z: number) {
|
||||
const planes = this.#planes;
|
||||
for (let i = 0; i < 24; i += 4) {
|
||||
const a = planes[i];
|
||||
const b = planes[i + 1];
|
||||
const c = planes[i + 2];
|
||||
// the box's corner furthest along the plane's normal
|
||||
const x = a > 0 ? max_x : min_x;
|
||||
const y = b > 0 ? max_y : min_y;
|
||||
const z = c > 0 ? max_z : min_z;
|
||||
if (a * x + b * y + c * z + planes[i + 3] < 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TEXTURE_SIZE } from "$/common/constants.ts";
|
||||
import { CHUNK_SIZE, ClientLevel } from "$/client/level/client_level.ts";
|
||||
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts";
|
||||
import { Camera } from "$/client/camera.ts";
|
||||
import { AssetManager } from "$/client/assets.ts";
|
||||
import { get_sprite_region } from "$/client/sprites.ts";
|
||||
@@ -20,8 +20,13 @@ import {
|
||||
push_top_face,
|
||||
set_current_texture,
|
||||
Texture,
|
||||
view_projection,
|
||||
white_tex,
|
||||
} from "$/client/renderer/mod.ts";
|
||||
import type { RenderLayer } from "$/common/everything_registry.ts";
|
||||
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
|
||||
import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts";
|
||||
import { Frustum } from "./frustum.ts";
|
||||
|
||||
const BREAKING_FACES = [
|
||||
push_back_face,
|
||||
@@ -34,48 +39,59 @@ const BREAKING_FACES = [
|
||||
|
||||
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
||||
export class LevelRenderer {
|
||||
frustum = new Frustum();
|
||||
// chunks in view this frame, worked out once for all the layers
|
||||
#visible: Chunk[] = [];
|
||||
|
||||
// solid and cutout terrain, drawn before entities
|
||||
render_opaque(level: ClientLevel, camera: Camera) {
|
||||
level.request_meshes(camera);
|
||||
level.update_translucent_sorting(camera);
|
||||
|
||||
set_current_texture(level.image.tex);
|
||||
|
||||
this.frustum.update(view_projection());
|
||||
this.#visible.length = 0;
|
||||
for (const chunk of level.chunks.values()) {
|
||||
const mesh = chunk.meshes.solid;
|
||||
if (mesh) {
|
||||
draw_terrain("solid", mesh.vertex_buffer, mesh.quad_count);
|
||||
if (Object.keys(chunk.meshes).length > 0 && this.#in_view(chunk)) {
|
||||
this.#visible.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
for (const chunk of level.chunks.values()) {
|
||||
const mesh = chunk.meshes.cutout;
|
||||
if (mesh) {
|
||||
draw_terrain("cutout", mesh.vertex_buffer, mesh.quad_count);
|
||||
set_current_texture(level.image.tex);
|
||||
|
||||
for (const layer of ["solid", "cutout"] as const) {
|
||||
for (const chunk of this.#visible) {
|
||||
const mesh = chunk.meshes[layer];
|
||||
if (mesh) {
|
||||
draw_facing_camera(layer, mesh, camera);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// translucent terrain, drawn after entities so they show through water and glass.
|
||||
// chunks go back to front, and each chunk's quads are already sorted back to front
|
||||
render_translucent(level: ClientLevel, camera: Camera) {
|
||||
render_translucent(_level: ClientLevel, camera: Camera) {
|
||||
const distance_sq = (x: number, z: number) => {
|
||||
const dx = (x + 0.5) * CHUNK_SIZE - camera.x;
|
||||
const dz = (z + 0.5) * CHUNK_SIZE - camera.z;
|
||||
return dx * dx + dz * dz;
|
||||
};
|
||||
const chunks = [...level.chunks.values()]
|
||||
const chunks = this.#visible
|
||||
.filter((chunk) => chunk.meshes.translucent)
|
||||
.map((chunk) => ({ mesh: chunk.meshes.translucent!, distance: distance_sq(chunk.x, chunk.z) }))
|
||||
.sort((a, b) => b.distance - a.distance);
|
||||
|
||||
set_current_texture(level.image.tex);
|
||||
|
||||
for (const { mesh } of chunks) {
|
||||
draw_terrain("translucent", mesh.vertex_buffer, mesh.quad_count, mesh.index_buffer);
|
||||
draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
#in_view(chunk: Chunk) {
|
||||
const x = chunk.x * CHUNK_SIZE;
|
||||
const z = chunk.z * CHUNK_SIZE;
|
||||
return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE);
|
||||
}
|
||||
|
||||
// every entity but the one the camera is in
|
||||
render_entities(level: ClientLevel, camera_entity: Entity, partial_tick: number) {
|
||||
flush_batch();
|
||||
@@ -127,6 +143,44 @@ export class LevelRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
// only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any
|
||||
// of them lie on. neighboring groups that are both drawn go in one draw call
|
||||
function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera) {
|
||||
const groups = mesh.groups;
|
||||
if (!groups) {
|
||||
draw_terrain(layer, mesh.vertex_buffer, 0, mesh.quad_count);
|
||||
return;
|
||||
}
|
||||
let start = 0;
|
||||
let end = 0;
|
||||
for (let g = 0; g < FACE_GROUPS; g++) {
|
||||
const group = groups[g];
|
||||
if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) {
|
||||
continue;
|
||||
}
|
||||
if (group.first !== end) {
|
||||
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
|
||||
start = group.first;
|
||||
}
|
||||
end = group.first + group.count;
|
||||
}
|
||||
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
|
||||
}
|
||||
|
||||
export function group_faces_camera(
|
||||
group: number,
|
||||
min: number,
|
||||
max: number,
|
||||
camera: { x: number; y: number; z: number },
|
||||
) {
|
||||
if (group === UNALIGNED_GROUP) {
|
||||
return true;
|
||||
}
|
||||
const axis = FACE_AXIS[group];
|
||||
const position = axis === 0 ? camera.x : axis === 1 ? camera.y : camera.z;
|
||||
return FACE_NORMALS[group][axis] > 0 ? position > min : position < max;
|
||||
}
|
||||
|
||||
// a box body and head in the player's color
|
||||
function render_player(player: RemotePlayer, partial_tick: number) {
|
||||
const [r, g, b] = player.color;
|
||||
|
||||
@@ -6,8 +6,23 @@ import type { SortType } from "./translucent_sort.ts";
|
||||
|
||||
// messages between the main thread and the chunk workers
|
||||
|
||||
// position 3, uv 2, color 4 (directional shade and ambient occlusion, alpha), lightmap coordinates 2
|
||||
export const TERRAIN_VERTEX_FLOATS = 11;
|
||||
// a terrain vertex, 24 bytes: position as float32x3, atlas uv as unorm16x2, directional shade times ambient occlusion
|
||||
// and alpha as unorm8x4 (shade repeated in rgb), and lightmap coordinates as unorm8x2 plus two unused bytes
|
||||
export const TERRAIN_VERTEX_BYTES = 24;
|
||||
export const TERRAIN_QUAD_BYTES = 4 * TERRAIN_VERTEX_BYTES;
|
||||
|
||||
// solid and cutout quads are grouped by the way they face, so groups facing away from the camera can be skipped, like
|
||||
// sodium's block face culling. the groups follow FACE_NORMALS' order, then the quads that aren't axis aligned
|
||||
export const FACE_GROUPS = 7;
|
||||
export const UNALIGNED_GROUP = 6;
|
||||
|
||||
export interface FaceGroup {
|
||||
first: number;
|
||||
count: number;
|
||||
// the lowest and highest plane the group's quads lie on, along its axis
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export type ToChunkWorker =
|
||||
| {
|
||||
@@ -44,10 +59,12 @@ export type ToChunkWorker =
|
||||
camera: number[];
|
||||
};
|
||||
|
||||
// 4 vertices per quad
|
||||
// 4 vertices per quad, TERRAIN_VERTEX_BYTES each
|
||||
export interface LayerMesh {
|
||||
vertices: Float32Array;
|
||||
vertices: Uint8Array<ArrayBuffer>;
|
||||
quad_count: number;
|
||||
// solid and cutout only, see FACE_GROUPS. the quads are stored group after group
|
||||
groups?: FaceGroup[];
|
||||
}
|
||||
|
||||
export type FromChunkWorker =
|
||||
@@ -64,6 +81,9 @@ export type FromChunkWorker =
|
||||
chunk_x: number;
|
||||
chunk_z: number;
|
||||
version: number;
|
||||
// the lowest and highest y of the chunk's quads, for frustum culling
|
||||
min_y: number;
|
||||
max_y: number;
|
||||
solid: LayerMesh;
|
||||
cutout: LayerMesh;
|
||||
translucent: LayerMesh & {
|
||||
|
||||
@@ -16,13 +16,22 @@ import {
|
||||
TEXTURE_SIZE,
|
||||
} from "$/common/constants.ts";
|
||||
import type { Texture } from "../renderer/types.ts";
|
||||
import { type FromChunkWorker, TERRAIN_VERTEX_FLOATS, type ToChunkWorker } from "./chunk_messages.ts";
|
||||
import {
|
||||
FACE_GROUPS,
|
||||
type FaceGroup,
|
||||
type FromChunkWorker,
|
||||
TERRAIN_QUAD_BYTES,
|
||||
TERRAIN_VERTEX_BYTES,
|
||||
type ToChunkWorker,
|
||||
UNALIGNED_GROUP,
|
||||
} from "./chunk_messages.ts";
|
||||
import { generate_raw_chunk, WorldgenSetup } from "$/common/generation.ts";
|
||||
import { load_worldgen } from "$/common/worldgen_loader.ts";
|
||||
import { default_block_value, get_state_value } from "$/common/utils.ts";
|
||||
import { bake_model, block_variant, FACE_CORNERS, find_model, type ModelJson } from "$/common/block_models.ts";
|
||||
import {
|
||||
choose_sort_type,
|
||||
FACE_AXIS,
|
||||
FACE_NORMALS,
|
||||
quad_indices,
|
||||
quad_planes,
|
||||
@@ -42,7 +51,6 @@ import {
|
||||
|
||||
type TexturesInfo = Record<string, SpriteRegion>;
|
||||
|
||||
const FLOATS_PER_QUAD = 4 * TERRAIN_VERTEX_FLOATS;
|
||||
// keeps texture lookups off the sprite's edge
|
||||
const UV_PAD = 0.5;
|
||||
|
||||
@@ -91,6 +99,8 @@ interface MeshQuad {
|
||||
face: number;
|
||||
cull: number;
|
||||
flush: boolean;
|
||||
// the face group it goes in, see FACE_GROUPS
|
||||
group: number;
|
||||
shade: number;
|
||||
sprite: SpriteRegion;
|
||||
// 4 weights per corner
|
||||
@@ -132,7 +142,7 @@ self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
|
||||
case "mesh": {
|
||||
region.fill(message.chunks);
|
||||
region.compute(light_tables);
|
||||
const { solid, cutout, translucent } = make_chunk_mesh(
|
||||
const { solid, cutout, translucent, min_y, max_y } = make_chunk_mesh(
|
||||
message.chunk_x,
|
||||
message.chunk_z,
|
||||
message.chunks[4]!,
|
||||
@@ -144,6 +154,8 @@ self.onmessage = async (event: MessageEvent<ToChunkWorker>) => {
|
||||
chunk_x: message.chunk_x,
|
||||
chunk_z: message.chunk_z,
|
||||
version: message.version,
|
||||
min_y,
|
||||
max_y,
|
||||
solid,
|
||||
cutout,
|
||||
translucent,
|
||||
@@ -285,28 +297,57 @@ function should_flip() {
|
||||
return light(0) + light(2) > light(1) + light(3);
|
||||
}
|
||||
|
||||
function push_quad(vertices: Float32Array, i: number, quad: MeshQuad, x: number, y: number, z: number, alpha: number) {
|
||||
// quads being built, in the terrain vertex format
|
||||
class QuadBuffer {
|
||||
count = 0;
|
||||
bytes = new Uint8Array(TERRAIN_QUAD_BYTES * 64);
|
||||
f32 = new Float32Array(this.bytes.buffer);
|
||||
u16 = new Uint16Array(this.bytes.buffer);
|
||||
|
||||
// room for one more quad
|
||||
reserve() {
|
||||
if ((this.count + 1) * TERRAIN_QUAD_BYTES <= this.bytes.length) return;
|
||||
const bytes = new Uint8Array(this.bytes.length * 2);
|
||||
bytes.set(this.bytes);
|
||||
this.bytes = bytes;
|
||||
this.f32 = new Float32Array(bytes.buffer);
|
||||
this.u16 = new Uint16Array(bytes.buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// the lowest and highest y of any quad in the chunk being meshed
|
||||
let mesh_min_y = Infinity;
|
||||
let mesh_max_y = -Infinity;
|
||||
|
||||
function push_quad(buffer: QuadBuffer, quad: MeshQuad, x: number, y: number, z: number, alpha: number) {
|
||||
buffer.reserve();
|
||||
const { f32, u16, bytes } = buffer;
|
||||
const sprite = quad.sprite;
|
||||
// starting from the second corner moves the diagonal, the winding stays the same
|
||||
const first = should_flip() ? 1 : 0;
|
||||
const alpha_byte = Math.round(alpha * 255);
|
||||
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const corner = (first + k) & 3;
|
||||
const brightness = quad.shade * corner_ao[corner];
|
||||
vertices[i++] = x + quad.positions[corner * 3];
|
||||
vertices[i++] = y + quad.positions[corner * 3 + 1];
|
||||
vertices[i++] = z + quad.positions[corner * 3 + 2];
|
||||
vertices[i++] = atlas_u(sprite, quad.uvs[corner * 2]);
|
||||
vertices[i++] = atlas_v(sprite, quad.uvs[corner * 2 + 1]);
|
||||
vertices[i++] = brightness;
|
||||
vertices[i++] = brightness;
|
||||
vertices[i++] = brightness;
|
||||
vertices[i++] = alpha;
|
||||
const byte = (buffer.count * 4 + k) * TERRAIN_VERTEX_BYTES;
|
||||
const vy = y + quad.positions[corner * 3 + 1];
|
||||
f32[byte / 4] = x + quad.positions[corner * 3];
|
||||
f32[byte / 4 + 1] = vy;
|
||||
f32[byte / 4 + 2] = z + quad.positions[corner * 3 + 2];
|
||||
u16[byte / 2 + 6] = Math.round(atlas_u(sprite, quad.uvs[corner * 2]) * 65535);
|
||||
u16[byte / 2 + 7] = Math.round(atlas_v(sprite, quad.uvs[corner * 2 + 1]) * 65535);
|
||||
const brightness = Math.round(quad.shade * corner_ao[corner] * 255);
|
||||
bytes[byte + 16] = brightness;
|
||||
bytes[byte + 17] = brightness;
|
||||
bytes[byte + 18] = brightness;
|
||||
bytes[byte + 19] = alpha_byte;
|
||||
// where to read the lightmap, block light across and sky light down
|
||||
vertices[i++] = (corner_block[corner] + 0.5) / 16;
|
||||
vertices[i++] = (corner_sky[corner] + 0.5) / 16;
|
||||
bytes[byte + 20] = Math.round((corner_block[corner] + 0.5) / 16 * 255);
|
||||
bytes[byte + 21] = Math.round((corner_sky[corner] + 0.5) / 16 * 255);
|
||||
if (vy < mesh_min_y) mesh_min_y = vy;
|
||||
if (vy > mesh_max_y) mesh_max_y = vy;
|
||||
}
|
||||
return i;
|
||||
buffer.count += 1;
|
||||
}
|
||||
|
||||
// pixels of a sprite to atlas coordinates, kept off the sprite's edge
|
||||
@@ -340,6 +381,7 @@ function block_quads(value: number): MeshQuad[] {
|
||||
face: quad.face,
|
||||
cull: quad.cull,
|
||||
flush: quad.flush,
|
||||
group: quad.aligned ? quad.face : UNALIGNED_GROUP,
|
||||
shade: quad.shade ? FACE_SHADE[quad.face] : 1,
|
||||
sprite: textures_info[quad.texture] ?? textures_info["engine:missing"],
|
||||
light_weights: light_weights(quad.face, quad.positions),
|
||||
@@ -408,7 +450,13 @@ function light_quad(quad: MeshQuad, index: number, y: number, face_offsets: numb
|
||||
// region has to be filled and lit first
|
||||
// values is the middle chunk's blocks with their states, for models that change with them
|
||||
function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array, camera: number[]) {
|
||||
const layers = [SOLID, CUTOUT, TRANSLUCENT].map(() => ({ vertices: new Float32Array(4096), floats: 0 }));
|
||||
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead
|
||||
const opaque = [SOLID, CUTOUT].map(() =>
|
||||
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
|
||||
);
|
||||
const translucent_quads = new QuadBuffer();
|
||||
mesh_min_y = Infinity;
|
||||
mesh_max_y = -Infinity;
|
||||
// for sorting the translucent quads
|
||||
let centers = new Float32Array(256);
|
||||
let faces = new Uint8Array(256);
|
||||
@@ -426,7 +474,6 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array,
|
||||
|
||||
const block_info = blocks_registry[block_nid];
|
||||
const layer_id = block_layers[block_nid];
|
||||
const layer = layers[layer_id];
|
||||
const alpha = layer_id === TRANSLUCENT ? block_info.alpha ?? 1 : 1;
|
||||
|
||||
const wx = chunk_x * CHUNK_SIZE + x;
|
||||
@@ -443,12 +490,20 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array,
|
||||
}
|
||||
|
||||
light_quad(quad, index, y, face_offsets);
|
||||
layer.vertices = ensure_capacity(layer.vertices, layer.floats + FLOATS_PER_QUAD);
|
||||
layer.floats = push_quad(layer.vertices, layer.floats, quad, wx, y, wz, alpha);
|
||||
|
||||
if (layer_id === TRANSLUCENT) {
|
||||
if (layer_id !== TRANSLUCENT) {
|
||||
const group = opaque[layer_id][quad.group];
|
||||
push_quad(group.buffer, quad, wx, y, wz, alpha);
|
||||
if (quad.group !== UNALIGNED_GROUP) {
|
||||
const axis = FACE_AXIS[quad.face];
|
||||
const plane = (axis === 0 ? wx : axis === 1 ? y : wz) + quad.positions[axis];
|
||||
if (plane < group.min) group.min = plane;
|
||||
if (plane > group.max) group.max = plane;
|
||||
}
|
||||
} else {
|
||||
push_quad(translucent_quads, quad, wx, y, wz, alpha);
|
||||
// sorting treats every quad as facing along an axis, rotated ones too
|
||||
const q = layer.floats / FLOATS_PER_QUAD - 1;
|
||||
const q = translucent_quads.count - 1;
|
||||
centers = ensure_capacity(centers, (q + 1) * 3);
|
||||
faces = ensure_capacity(faces, q + 1);
|
||||
const p = quad.positions;
|
||||
@@ -462,16 +517,31 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, values: Uint32Array,
|
||||
}
|
||||
}
|
||||
|
||||
const [solid, cutout, translucent] = layers.map((layer) => ({
|
||||
vertices: layer.vertices,
|
||||
quad_count: layer.floats / FLOATS_PER_QUAD,
|
||||
}));
|
||||
// each layer's groups one after another, in one buffer
|
||||
const [solid, cutout] = opaque.map((groups) => {
|
||||
const quad_count = groups.reduce((sum, group) => sum + group.buffer.count, 0);
|
||||
const vertices = new Uint8Array(quad_count * TERRAIN_QUAD_BYTES);
|
||||
const ranges: FaceGroup[] = [];
|
||||
let first = 0;
|
||||
for (const { buffer, min, max } of groups) {
|
||||
vertices.set(buffer.bytes.subarray(0, buffer.count * TERRAIN_QUAD_BYTES), first * TERRAIN_QUAD_BYTES);
|
||||
ranges.push({ first, count: buffer.count, min, max });
|
||||
first += buffer.count;
|
||||
}
|
||||
return { vertices, quad_count, groups: ranges };
|
||||
});
|
||||
const translucent = {
|
||||
vertices: translucent_quads.bytes.slice(0, translucent_quads.count * TERRAIN_QUAD_BYTES),
|
||||
quad_count: translucent_quads.count,
|
||||
};
|
||||
|
||||
const quads = { centers, faces, count: translucent.quad_count };
|
||||
const sort_type = choose_sort_type(quads);
|
||||
const [camera_x, camera_y, camera_z] = camera;
|
||||
|
||||
return {
|
||||
min_y: mesh_min_y === Infinity ? 0 : mesh_min_y,
|
||||
max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y,
|
||||
solid,
|
||||
cutout,
|
||||
translucent: {
|
||||
|
||||
+10
-5
@@ -180,6 +180,9 @@ export interface BakedQuad {
|
||||
cull: number;
|
||||
// on the block's edge facing straight out, so it's lit like a full block's face
|
||||
flush: boolean;
|
||||
// flat on a plane facing straight along face's axis, so it can only be seen from that side of the plane.
|
||||
// rotated quads, like the cross model's, aren't
|
||||
aligned: boolean;
|
||||
shade: boolean;
|
||||
}
|
||||
|
||||
@@ -245,7 +248,7 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
|
||||
|
||||
let cull = face_json.cullface ? FACE_INDEX[face_json.cullface] : -1;
|
||||
for (let t = 0; t < turns && cull >= 0; t++) cull = TURN_Y[cull];
|
||||
const { face: facing, flush } = classify(positions);
|
||||
const { face: facing, flush, aligned } = classify(positions);
|
||||
quads.push({
|
||||
positions,
|
||||
uvs,
|
||||
@@ -253,6 +256,7 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
|
||||
face: facing,
|
||||
cull,
|
||||
flush,
|
||||
aligned,
|
||||
shade: element.shade ?? true,
|
||||
});
|
||||
}
|
||||
@@ -285,8 +289,8 @@ function element_rotation(element: ModelElementJson): (point: number[]) => numbe
|
||||
};
|
||||
}
|
||||
|
||||
// which way a quad faces most, and whether it's flat against the block's edge
|
||||
function classify(p: number[]): { face: number; flush: boolean } {
|
||||
// which way a quad faces most, whether it's flat against the block's edge, and whether it faces straight along an axis
|
||||
function classify(p: number[]): { face: number; flush: boolean; aligned: boolean } {
|
||||
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
|
||||
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
|
||||
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||
@@ -303,6 +307,7 @@ function classify(p: number[]): { face: number; flush: boolean } {
|
||||
|
||||
const axis = FACE_NORMALS[face].findIndex((v) => v !== 0);
|
||||
const edge = FACE_NORMALS[face][axis] > 0 ? 1 : 0;
|
||||
const flush = [0, 1, 2, 3].every((k) => Math.abs(p[k * 3 + axis] - edge) < EPSILON);
|
||||
return { face, flush };
|
||||
const aligned = [1, 2, 3].every((k) => Math.abs(p[k * 3 + axis] - p[axis]) < EPSILON);
|
||||
const flush = aligned && Math.abs(p[axis] - edge) < EPSILON;
|
||||
return { face, flush, aligned };
|
||||
}
|
||||
|
||||
@@ -5,17 +5,19 @@
|
||||
"server": "deno run --unstable-worker-options --allow-net --allow-read --allow-write --allow-env server/main.ts",
|
||||
"new-mod": "deno run --allow-read --allow-write tools/new_mod.ts",
|
||||
"check-mods": "deno run --allow-read --allow-run tools/check_mods.ts",
|
||||
"test": "deno test --allow-read --allow-write --allow-run tests/"
|
||||
"test": "deno test --allow-read --allow-write --allow-run tests/",
|
||||
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-env=BWORLD_SERVER,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld"
|
||||
},
|
||||
"compilerOptions": {
|
||||
"lib": ["dom", "dom.asynciterable", "dom.iterable", "deno.ns", "deno.unstable", "deno.webgpu"]
|
||||
},
|
||||
"unstable": ["bundle", "raw-imports"],
|
||||
"unstable": ["bundle", "raw-imports", "worker-options"],
|
||||
"fmt": {
|
||||
"useTabs": true,
|
||||
"indentWidth": 4,
|
||||
"lineWidth": 120,
|
||||
"newLineKind": "lf"
|
||||
"newLineKind": "lf",
|
||||
"exclude": ["desktop/*.md"]
|
||||
},
|
||||
"imports": {
|
||||
"$/": "./",
|
||||
@@ -30,5 +32,10 @@
|
||||
"@std/path": "jsr:@std/path@^1.0.0",
|
||||
"gl-matrix": "npm:gl-matrix@^3.4.4",
|
||||
"marked": "npm:marked@^17.0.3"
|
||||
},
|
||||
"desktop": {
|
||||
"app": { "name": "bworld", "identifier": "com.bworld.game" },
|
||||
"backend": "cef",
|
||||
"output": { "macos": "./dist/bworld.app", "windows": "./dist/bworld", "linux": "./dist/bworld" }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"server": "bworld.moder.fans"
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld
|
||||
// deno desktop has no setting for chromium's command line, but its linux launcher passes its arguments on to chromium.
|
||||
// so this moves the launcher to bworld-bin and puts a script in its place that starts it with the switches webgpu
|
||||
// needs on some linux setups. run it on the app folder after deno desktop builds it; running it again does nothing
|
||||
const SWITCHES = [
|
||||
"--enable-unsafe-webgpu",
|
||||
"--ozone-platform=x11",
|
||||
"--use-angle=vulkan",
|
||||
"--enable-features=Vulkan,VulkanFromANGLE",
|
||||
];
|
||||
|
||||
const dir = Deno.args[0];
|
||||
if (!dir) {
|
||||
console.error("usage: linux_launcher.ts <app folder>, like dist/bworld");
|
||||
Deno.exit(1);
|
||||
}
|
||||
const name = dir.replace(/\/+$/, "").split("/").pop()!;
|
||||
const launcher = `${dir}/${name}`;
|
||||
const binary = `${launcher}-bin`;
|
||||
|
||||
// already wrapped: the launcher is a script now
|
||||
const head = new Uint8Array(4);
|
||||
const file = Deno.openSync(launcher);
|
||||
file.readSync(head);
|
||||
file.close();
|
||||
const is_elf = head[0] === 0x7f && head[1] === 0x45 && head[2] === 0x4c && head[3] === 0x46;
|
||||
if (!is_elf) {
|
||||
console.log(`${launcher} is already wrapped`);
|
||||
Deno.exit(0);
|
||||
}
|
||||
|
||||
Deno.renameSync(launcher, binary);
|
||||
Deno.writeTextFileSync(
|
||||
launcher,
|
||||
`#!/bin/sh
|
||||
# starts ${name} with the chromium switches webgpu needs on some linux setups, see desktop/linux_launcher.ts.
|
||||
# BWORLD_CHROMIUM_FLAGS replaces them, set it to "" to start without any
|
||||
here="$(dirname "$(readlink -f "$0")")"
|
||||
# the binary finds its runtime by its own name, which is ${name}.so and not ${name}-bin.so
|
||||
export LAUFEY_RUNTIME_PATH="$here/${name}.so"
|
||||
exec "$here/${name}-bin" \${BWORLD_CHROMIUM_FLAGS-${SWITCHES.join(" ")}} "$@"
|
||||
`,
|
||||
);
|
||||
Deno.chmodSync(launcher, 0o755);
|
||||
console.log(`Wrapped ${launcher}: ${SWITCHES.join(" ")}`);
|
||||
@@ -0,0 +1,86 @@
|
||||
/// <reference lib="deno.desktop" />
|
||||
|
||||
// the desktop app: the web client in a bundled chromium (deno desktop's cef backend), so people whose browser has no
|
||||
// webgpu (firefox) can still play. it joins servers like the browser does, and runs its own game server for
|
||||
// singleplayer, like minecraft java. build it with deno task desktop, see the desktop/ docs for how deno desktop works
|
||||
import { fromFileUrl, join } from "@std/path";
|
||||
import { type Host, serve_static, start_host } from "../server/host.ts";
|
||||
|
||||
// where the project was built from: build/ and server_mods/ are bundled into the app with --include
|
||||
const ROOT = fromFileUrl(new URL("../", import.meta.url));
|
||||
const BUILD_DIR = join(ROOT, "build");
|
||||
|
||||
// the server the address field starts with. "" leaves it empty for the player to fill in
|
||||
const config: { server?: string } = JSON.parse(
|
||||
await Deno.readTextFile(new URL("./config.json", import.meta.url)),
|
||||
);
|
||||
const default_server = Deno.env.get("BWORLD_SERVER") ?? config.server ?? "";
|
||||
|
||||
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
|
||||
|
||||
// the singleplayer game server, started the first time singleplayer connects so players who only join other servers
|
||||
// don't get a world made for them
|
||||
let host: Host | undefined;
|
||||
|
||||
function singleplayer_host(): Host {
|
||||
if (!host) {
|
||||
const worlds = join(data_dir(), "worlds");
|
||||
Deno.mkdirSync(worlds, { recursive: true });
|
||||
host = start_host({
|
||||
build_dir: BUILD_DIR,
|
||||
server_mods_dir: join(ROOT, "server_mods"),
|
||||
root: ROOT,
|
||||
world_file: join(worlds, "world.json"),
|
||||
on_fatal(message) {
|
||||
console.error(message);
|
||||
alert(`The singleplayer world stopped: ${message}`);
|
||||
Deno.exit(1);
|
||||
},
|
||||
});
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
// the world gets saved before the app closes
|
||||
win.addEventListener("close", async (event) => {
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
try {
|
||||
await host.shutdown();
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
}
|
||||
Deno.exit(0);
|
||||
});
|
||||
|
||||
// deno desktop binds this to a private local address and opens the window on it, the port given here is ignored
|
||||
Deno.serve((req) => {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/") {
|
||||
// ?server= fills in the address field, without it the field would start with this app's own address.
|
||||
// ?singleplayer shows the singleplayer button, which joins this app's own server
|
||||
const start = new URL("/client/", url);
|
||||
start.searchParams.set("server", default_server);
|
||||
start.searchParams.set("singleplayer", "");
|
||||
return Response.redirect(start, 302);
|
||||
}
|
||||
if (url.pathname === "/ws") {
|
||||
return singleplayer_host().handle(req);
|
||||
}
|
||||
return serve_static(BUILD_DIR, req, url);
|
||||
});
|
||||
|
||||
// where the app keeps its worlds, the usual place for app data on each os
|
||||
function data_dir() {
|
||||
const home = Deno.env.get("HOME") ?? Deno.env.get("USERPROFILE") ?? ".";
|
||||
switch (Deno.build.os) {
|
||||
case "windows":
|
||||
return join(Deno.env.get("APPDATA") ?? join(home, "AppData", "Roaming"), "bworld");
|
||||
case "darwin":
|
||||
return join(home, "Library", "Application Support", "bworld");
|
||||
default:
|
||||
return join(Deno.env.get("XDG_DATA_HOME") ?? join(home, ".local", "share"), "bworld");
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
// the part of a game server that has permissions: files and networking. the game itself runs in a worker with none.
|
||||
// server/main.ts runs it as a dedicated server, and the desktop app runs it for singleplayer
|
||||
import { serveDir } from "@std/http/file-server";
|
||||
import { isAbsolute, join } from "@std/path";
|
||||
import { GameToHost, HostToGame } from "./game/host_protocol.ts";
|
||||
import type { ServerModIndex } from "../build.ts";
|
||||
|
||||
const MAX_MESSAGE_SIZE = 4096;
|
||||
const SHUTDOWN_TIMEOUT_MS = 5000;
|
||||
|
||||
export interface HostOptions {
|
||||
// what deno task build made: the client, assets and mods players download
|
||||
build_dir: string;
|
||||
// the server scripts, with index.json
|
||||
server_mods_dir: string;
|
||||
// what the paths in server_mods/index.json are relative to, the folder the build ran in
|
||||
root: string;
|
||||
world_file: string;
|
||||
seed?: string;
|
||||
// the game can't go on, like the worker crashing
|
||||
on_fatal(message: string): void;
|
||||
}
|
||||
|
||||
export interface Host {
|
||||
handle(req: Request): Response | Promise<Response>;
|
||||
// saves the world and stops the game. resolves once it's on disk
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
export function start_host(options: HostOptions): Host {
|
||||
const mods = read_mods(options);
|
||||
console.log(`Mods: ${mods.mods.map((mod) => `${mod.listing.id} ${mod.listing.version}`).join(", ") || "none"}`);
|
||||
|
||||
const game = new Worker(new URL("./game/worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
deno: { permissions: "none" },
|
||||
} as WorkerOptions);
|
||||
const post = (message: HostToGame) => game.postMessage(message);
|
||||
|
||||
const sockets = new Map<number, WebSocket>();
|
||||
let next_conn = 1;
|
||||
let on_final_save: (() => void) | undefined;
|
||||
|
||||
game.onmessage = (event: MessageEvent<GameToHost>) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "ready":
|
||||
console.log(`World ${options.world_file} ready, seed ${message.seed}`);
|
||||
break;
|
||||
case "failed":
|
||||
options.on_fatal(`Couldn't start the game: ${message.error}`);
|
||||
break;
|
||||
case "send": {
|
||||
const socket = sockets.get(message.conn);
|
||||
if (socket?.readyState === WebSocket.OPEN) {
|
||||
socket.send(message.data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "close":
|
||||
sockets.get(message.conn)?.close();
|
||||
break;
|
||||
case "save":
|
||||
write_world(options.world_file, message.data);
|
||||
if (message.final) {
|
||||
console.log("World saved");
|
||||
on_final_save?.();
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
game.onerror = (event) => {
|
||||
event.preventDefault();
|
||||
options.on_fatal(`Game server crashed: ${event.message}`);
|
||||
};
|
||||
|
||||
post({
|
||||
type: "init",
|
||||
save: read_world(options.world_file),
|
||||
default_seed: options.seed ?? crypto.randomUUID(),
|
||||
...mods,
|
||||
});
|
||||
|
||||
function handle_socket(socket: WebSocket) {
|
||||
const conn = next_conn++;
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
sockets.set(conn, socket);
|
||||
post({ type: "connect", conn });
|
||||
});
|
||||
|
||||
socket.addEventListener("message", (event) => {
|
||||
if (typeof event.data !== "string" || event.data.length > MAX_MESSAGE_SIZE) {
|
||||
return;
|
||||
}
|
||||
post({ type: "message", conn, data: event.data });
|
||||
});
|
||||
|
||||
socket.addEventListener("close", () => {
|
||||
if (sockets.delete(conn)) {
|
||||
post({ type: "disconnect", conn });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
handle(req) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/ws") {
|
||||
if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
|
||||
return new Response("Expected a websocket", { status: 426 });
|
||||
}
|
||||
const { socket, response } = Deno.upgradeWebSocket(req);
|
||||
handle_socket(socket);
|
||||
return response;
|
||||
}
|
||||
if (url.pathname === "/") {
|
||||
return Response.redirect(new URL("/client/", url), 302);
|
||||
}
|
||||
return serve_static(options.build_dir, req, url);
|
||||
},
|
||||
|
||||
shutdown() {
|
||||
console.log("Saving world...");
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(
|
||||
() => reject(new Error("Game server didn't save in time")),
|
||||
SHUTDOWN_TIMEOUT_MS,
|
||||
);
|
||||
on_final_save = () => {
|
||||
clearTimeout(timeout);
|
||||
game.terminate();
|
||||
resolve();
|
||||
};
|
||||
post({ type: "shutdown" });
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function read_world(file: string): string | undefined {
|
||||
try {
|
||||
return Deno.readTextFileSync(file);
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return undefined;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function write_world(file: string, data: string) {
|
||||
// write then rename so a crash mid write doesnt eat the world
|
||||
Deno.writeTextFileSync(`${file}.tmp`, data);
|
||||
Deno.renameSync(`${file}.tmp`, file);
|
||||
}
|
||||
|
||||
// what deno task build made. no index means the build failed or never ran, and the game never runs without its mods
|
||||
function read_mods(options: HostOptions): Pick<Extract<HostToGame, { type: "init" }>, "mods" | "atlas"> {
|
||||
let index: ServerModIndex;
|
||||
try {
|
||||
index = JSON.parse(Deno.readTextFileSync(join(options.server_mods_dir, "index.json")));
|
||||
} catch {
|
||||
throw new Error(
|
||||
`No ${options.server_mods_dir}/index.json, run deno task build first (it also reports mod errors)`,
|
||||
);
|
||||
}
|
||||
const from_root = (path: string) => isAbsolute(path) ? path : join(options.root, path);
|
||||
return {
|
||||
atlas: index.atlas,
|
||||
mods: index.mods.map(({ listing, server }) => ({
|
||||
listing,
|
||||
data: JSON.parse(Deno.readTextFileSync(join(options.build_dir, listing.data))),
|
||||
server_code: server ? Deno.readTextFileSync(from_root(server)) : undefined,
|
||||
worldgen_code: listing.worldgen
|
||||
? Deno.readTextFileSync(join(options.build_dir, listing.worldgen))
|
||||
: undefined,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// mod files and the atlas are named by their hash, so they never change and pages on other origins can load them
|
||||
export async function serve_static(build_dir: string, req: Request, url: URL) {
|
||||
const response = await serveDir(req, { fsRoot: build_dir, quiet: true });
|
||||
const shared = url.pathname.startsWith("/mods/") || url.pathname.startsWith("/assets/");
|
||||
if (shared && response.ok) {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
if (url.pathname.startsWith("/mods/") || /^\/assets\/sprites\/textures\.[0-9a-f]+\./.test(url.pathname)) {
|
||||
headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
}
|
||||
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
||||
}
|
||||
return response;
|
||||
}
|
||||
+27
-155
@@ -1,169 +1,41 @@
|
||||
import { serveDir } from "@std/http/file-server";
|
||||
import { GameToHost, HostToGame } from "./game/host_protocol.ts";
|
||||
import type { ServerModIndex } from "../build.ts";
|
||||
// a dedicated server: the host from server/host.ts on a port, saving the world when it's stopped
|
||||
import { type Host, start_host } from "./host.ts";
|
||||
|
||||
const PORT = Number(Deno.env.get("PORT") ?? 8000);
|
||||
const WORLD_FILE = Deno.env.get("WORLD_FILE") ?? "world.json";
|
||||
const STATIC_ROOT = Deno.env.get("BUILD_DIR") ?? "build";
|
||||
const SERVER_MODS_DIR = Deno.env.get("SERVER_MODS_DIR") ?? "server_mods";
|
||||
const MAX_MESSAGE_SIZE = 4096;
|
||||
const SHUTDOWN_TIMEOUT_MS = 5000;
|
||||
|
||||
// the host only does files and networking, the game runs in a worker with no permissions
|
||||
const game = new Worker(new URL("./game/worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
deno: { permissions: "none" },
|
||||
} as WorkerOptions);
|
||||
|
||||
const sockets = new Map<number, WebSocket>();
|
||||
let next_conn = 1;
|
||||
|
||||
function post(message: HostToGame) {
|
||||
game.postMessage(message);
|
||||
}
|
||||
|
||||
function read_world(): string | undefined {
|
||||
try {
|
||||
return Deno.readTextFileSync(WORLD_FILE);
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return undefined;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function write_world(data: string) {
|
||||
// write then rename so a crash mid write doesnt eat the world
|
||||
Deno.writeTextFileSync(`${WORLD_FILE}.tmp`, data);
|
||||
Deno.renameSync(`${WORLD_FILE}.tmp`, WORLD_FILE);
|
||||
}
|
||||
|
||||
game.onmessage = (event: MessageEvent<GameToHost>) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "ready":
|
||||
console.log(`World ${WORLD_FILE} ready, seed ${message.seed}`);
|
||||
break;
|
||||
case "failed":
|
||||
console.error(`Couldn't start the game: ${message.error}`);
|
||||
let host: Host;
|
||||
try {
|
||||
host = start_host({
|
||||
build_dir: Deno.env.get("BUILD_DIR") ?? "build",
|
||||
server_mods_dir: Deno.env.get("SERVER_MODS_DIR") ?? "server_mods",
|
||||
root: ".",
|
||||
world_file: Deno.env.get("WORLD_FILE") ?? "world.json",
|
||||
seed: Deno.env.get("SEED"),
|
||||
on_fatal(message) {
|
||||
console.error(message);
|
||||
Deno.exit(1);
|
||||
break;
|
||||
case "send": {
|
||||
const socket = sockets.get(message.conn);
|
||||
if (socket?.readyState === WebSocket.OPEN) {
|
||||
socket.send(message.data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "close":
|
||||
sockets.get(message.conn)?.close();
|
||||
break;
|
||||
case "save":
|
||||
write_world(message.data);
|
||||
if (message.final) {
|
||||
console.log("World saved");
|
||||
Deno.exit(0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// what deno task build made. no index means the build failed or never ran, and the game never runs without its mods
|
||||
function read_mods(): Pick<Extract<HostToGame, { type: "init" }>, "mods" | "atlas"> {
|
||||
let index: ServerModIndex;
|
||||
try {
|
||||
index = JSON.parse(Deno.readTextFileSync(`${SERVER_MODS_DIR}/index.json`));
|
||||
} catch {
|
||||
console.error(`No ${SERVER_MODS_DIR}/index.json, run deno task build first (it also reports mod errors)`);
|
||||
Deno.exit(1);
|
||||
}
|
||||
return {
|
||||
atlas: index.atlas,
|
||||
mods: index.mods.map(({ listing, server }) => ({
|
||||
listing,
|
||||
data: JSON.parse(Deno.readTextFileSync(`${STATIC_ROOT}/${listing.data}`)),
|
||||
server_code: server ? Deno.readTextFileSync(server) : undefined,
|
||||
worldgen_code: listing.worldgen ? Deno.readTextFileSync(`${STATIC_ROOT}/${listing.worldgen}`) : undefined,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
game.onerror = (event) => {
|
||||
console.error("Game server crashed:", event.message);
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
Deno.exit(1);
|
||||
};
|
||||
|
||||
const { mods, atlas } = read_mods();
|
||||
console.log(`Mods: ${mods.map((mod) => `${mod.listing.id} ${mod.listing.version}`).join(", ") || "none"}`);
|
||||
const save = read_world();
|
||||
post({ type: "init", save, default_seed: Deno.env.get("SEED") ?? crypto.randomUUID(), atlas, mods });
|
||||
|
||||
// mod files and the atlas are named by their hash, so they never change and pages on other origins can load them
|
||||
async function serve_static(req: Request, url: URL) {
|
||||
const response = await serveDir(req, { fsRoot: STATIC_ROOT, quiet: true });
|
||||
const shared = url.pathname.startsWith("/mods/") || url.pathname.startsWith("/assets/");
|
||||
if (shared && response.ok) {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
if (url.pathname.startsWith("/mods/") || /^\/assets\/sprites\/textures\.[0-9a-f]+\./.test(url.pathname)) {
|
||||
headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
}
|
||||
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
function handle_socket(socket: WebSocket) {
|
||||
const conn = next_conn++;
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
sockets.set(conn, socket);
|
||||
post({ type: "connect", conn });
|
||||
});
|
||||
|
||||
socket.addEventListener("message", (event) => {
|
||||
if (typeof event.data !== "string" || event.data.length > MAX_MESSAGE_SIZE) {
|
||||
return;
|
||||
}
|
||||
post({ type: "message", conn, data: event.data });
|
||||
});
|
||||
|
||||
socket.addEventListener("close", () => {
|
||||
if (sockets.delete(conn)) {
|
||||
post({ type: "disconnect", conn });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
console.log("Saving world...");
|
||||
post({ type: "shutdown" });
|
||||
setTimeout(() => {
|
||||
console.error("Game server didn't save in time");
|
||||
async function shutdown() {
|
||||
try {
|
||||
await host.shutdown();
|
||||
Deno.exit(0);
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
Deno.exit(1);
|
||||
}, SHUTDOWN_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
Deno.addSignalListener("SIGINT", shutdown);
|
||||
if (Deno.build.os !== "windows") {
|
||||
Deno.addSignalListener("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
Deno.serve({ port: PORT, onListen: ({ port }) => console.log(`bworld server on http://localhost:${port}/`) }, (req) => {
|
||||
const url = new URL(req.url);
|
||||
|
||||
if (url.pathname === "/ws") {
|
||||
if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
|
||||
return new Response("Expected a websocket", { status: 426 });
|
||||
}
|
||||
const { socket, response } = Deno.upgradeWebSocket(req);
|
||||
handle_socket(socket);
|
||||
return response;
|
||||
}
|
||||
|
||||
if (url.pathname === "/") {
|
||||
return Response.redirect(new URL("/client/", url), 302);
|
||||
}
|
||||
|
||||
return serve_static(req, url);
|
||||
});
|
||||
Deno.serve(
|
||||
{ port: PORT, onListen: ({ port }) => console.log(`bworld server on http://localhost:${port}/`) },
|
||||
host.handle,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { assertEquals, assertThrows } from "@std/assert";
|
||||
import { server_address } from "$/client/handshake.ts";
|
||||
|
||||
const DESKTOP_PAGE = new URL("http://127.0.0.1:33549/client/");
|
||||
const HTTPS_PAGE = new URL("https://bworld.moder.fans/client/");
|
||||
|
||||
Deno.test("servers on this machine use ws, everything else wss, whatever the page was served over", () => {
|
||||
for (const host of ["localhost:8000", "127.0.0.1:8000", "0.0.0.0:8000", "[::1]:8000", "localhost"]) {
|
||||
assertEquals(server_address(host, DESKTOP_PAGE).ws_url, `ws://${host}/ws`, host);
|
||||
assertEquals(server_address(host, HTTPS_PAGE).ws_url, `ws://${host}/ws`, host);
|
||||
}
|
||||
for (const host of ["bworld.moder.fans", "example.com:8000", "192.168.1.5:8000", "localhost.example.com"]) {
|
||||
assertEquals(server_address(host, DESKTOP_PAGE).ws_url, `wss://${host}/ws`, host);
|
||||
assertEquals(server_address(host, DESKTOP_PAGE).base.protocol, "https:", host);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("a scheme picks ws or wss itself", () => {
|
||||
assertEquals(server_address("ws://192.168.1.5:8000", DESKTOP_PAGE).ws_url, "ws://192.168.1.5:8000/ws");
|
||||
assertEquals(server_address("http://example.com", DESKTOP_PAGE).base.href, "http://example.com/");
|
||||
assertEquals(server_address("wss://localhost:8000", DESKTOP_PAGE).ws_url, "wss://localhost:8000/ws");
|
||||
assertEquals(server_address("https://bworld.moder.fans/", HTTPS_PAGE).cross_origin, false);
|
||||
assertThrows(() => server_address("", DESKTOP_PAGE));
|
||||
assertThrows(() => server_address("not a host", DESKTOP_PAGE));
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
// the renderer skips chunks outside the view and faces pointing away from the camera, but must never skip one it
|
||||
// would have shown
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { mat4 } from "gl-matrix";
|
||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
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 { test_game } from "./helpers.ts";
|
||||
|
||||
// the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts
|
||||
function camera_matrix(x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||
const proj = mat4.perspectiveZO(mat4.create(), Math.PI / 3, 16 / 9, 0.1, 1000);
|
||||
const view = mat4.create();
|
||||
mat4.rotateX(view, view, -pitch);
|
||||
mat4.rotateY(view, view, -yaw);
|
||||
mat4.translate(view, view, [-x, -y, -z]);
|
||||
return mat4.multiply(mat4.create(), proj, view) as Float32Array;
|
||||
}
|
||||
|
||||
Deno.test("the frustum keeps what's in front of the camera and drops what's behind or beside it", () => {
|
||||
const frustum = new Frustum();
|
||||
// yaw 0 looks toward -z
|
||||
frustum.update(camera_matrix(0, 70, 0, 0, 0));
|
||||
assert(frustum.intersects_box(-8, 60, -40, 8, 80, -24), "straight ahead");
|
||||
assert(frustum.intersects_box(-1, 0, -1, 1, 256, 1), "the chunk the camera is in");
|
||||
assert(!frustum.intersects_box(-8, 60, 24, 8, 80, 40), "behind");
|
||||
assert(!frustum.intersects_box(200, 60, -40, 216, 80, -24), "far off to the side");
|
||||
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
|
||||
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>();
|
||||
worker.onmessage = (e) => {
|
||||
const key = `${e.data.type} ${e.data.chunk_x} ${e.data.chunk_z}`;
|
||||
replies.get(key)?.(e.data);
|
||||
replies.delete(key);
|
||||
};
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const ask = (message: any, reply: string) =>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
new Promise<any>((resolve) => {
|
||||
replies.set(`${reply} ${message.chunk_x} ${message.chunk_z}`, resolve);
|
||||
worker.postMessage(message);
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
const meshes = [];
|
||||
for (let x = -radius; x <= radius; x++) {
|
||||
for (let z = -radius; z <= radius; z++) {
|
||||
const chunks = [];
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
for (let dx = -1; dx <= 1; dx++) chunks.push(generated.get(`${x + dx},${z + dz}`)!.slice());
|
||||
}
|
||||
meshes.push(
|
||||
await ask({ type: "mesh", chunk_x: x, chunk_z: z, version: 1, chunks, camera: [0, 0, 0] }, "meshed"),
|
||||
);
|
||||
}
|
||||
}
|
||||
worker.terminate();
|
||||
return meshes;
|
||||
}
|
||||
|
||||
// each quad's corners, read back out of the vertex format
|
||||
function quad_corners(mesh: LayerMesh, quad: number) {
|
||||
const f32 = new Float32Array(mesh.vertices.buffer, mesh.vertices.byteOffset, mesh.vertices.byteLength / 4);
|
||||
return [0, 1, 2, 3].map((k) => {
|
||||
const i = ((quad * 4 + k) * TERRAIN_VERTEX_BYTES) / 4;
|
||||
return [f32[i], f32[i + 1], f32[i + 2]];
|
||||
});
|
||||
}
|
||||
|
||||
Deno.test("face groups only skip quads that face away from the camera", async () => {
|
||||
const meshes = await mesh_chunks(1);
|
||||
const cameras = [[8, 70, 8], [-20, 120, 30], [24, 20, -5], [8, 300, 8], [0.5, 64.5, 15.5]];
|
||||
let checked = 0;
|
||||
for (const message of meshes) {
|
||||
for (const layer of ["solid", "cutout"] as const) {
|
||||
const mesh: LayerMesh = message[layer];
|
||||
if (mesh.quad_count === 0) continue;
|
||||
assertEquals(mesh.groups!.length, FACE_GROUPS);
|
||||
assertEquals(mesh.groups!.reduce((sum, g) => sum + g.count, 0), mesh.quad_count);
|
||||
for (const [cx, cy, cz] of cameras) {
|
||||
for (const [g, group] of mesh.groups!.entries()) {
|
||||
if (group_faces_camera(g, group.min, group.max, { x: cx, y: cy, z: cz })) continue;
|
||||
// a skipped group: every quad in it faces away from the camera, or is edge on
|
||||
for (let q = group.first; q < group.first + group.count; q++) {
|
||||
const [a, b, , d] = quad_corners(mesh, q);
|
||||
const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
const e2 = [d[0] - a[0], d[1] - a[1], d[2] - a[2]];
|
||||
const n = [
|
||||
e1[1] * e2[2] - e1[2] * e2[1],
|
||||
e1[2] * e2[0] - e1[0] * e2[2],
|
||||
e1[0] * e2[1] - e1[1] * e2[0],
|
||||
];
|
||||
const facing = n[0] * (cx - a[0]) + n[1] * (cy - a[1]) + n[2] * (cz - a[2]);
|
||||
assert(facing <= 1e-4, `group ${g} skipped a quad facing the camera at ${cx},${cy},${cz}`);
|
||||
checked++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// the bounds hold every quad
|
||||
for (const layer of ["solid", "cutout", "translucent"] as const) {
|
||||
const mesh: LayerMesh = message[layer];
|
||||
for (let q = 0; q < mesh.quad_count; q++) {
|
||||
for (const [, y] of quad_corners(mesh, q)) assert(y >= message.min_y && y <= message.max_y);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(checked > 1000, `only checked ${checked} quads`);
|
||||
});
|
||||
Reference in New Issue
Block a user