Single module modding
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
|
||||
// the block rules shared phases register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
|
||||
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
|
||||
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
|
||||
import type {
|
||||
|
||||
+18
-10
@@ -1,33 +1,42 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// runs a mod's content script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the server on
|
||||
// its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to the mod's
|
||||
// data before anything else reads it
|
||||
// runs the content phase of a mod's script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the
|
||||
// server on its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to
|
||||
// the mod's data before anything else reads it
|
||||
import { type BlockJson, validate_block } from "./mod_data.ts";
|
||||
import type { ContentContext } from "./mod_api/content.ts";
|
||||
import { ModLoadError, run_phase } from "./mod_loader.ts";
|
||||
import { expose_engine } from "./hooks.ts";
|
||||
import { common_engine } from "./engine_modules.ts";
|
||||
|
||||
export interface ContentScript {
|
||||
mod: string;
|
||||
version: string;
|
||||
engine_access?: boolean;
|
||||
// importable url of the script
|
||||
url: string;
|
||||
}
|
||||
|
||||
// a .cubi's bundled content script, what server/content_worker.ts is sent
|
||||
// a .cubi's bundled script, what server/content_worker.ts is sent
|
||||
export interface ContentScriptCode {
|
||||
mod: string;
|
||||
version: string;
|
||||
engine_access?: boolean;
|
||||
code: string;
|
||||
}
|
||||
|
||||
// what a content script registered, in order, and what was wrong. with problems the mod doesn't load
|
||||
// what a content phase registered, in order, and what was wrong. with problems the mod doesn't load
|
||||
export interface RegisteredContent {
|
||||
blocks: BlockJson[];
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
export async function run_content_script({ mod, version, url }: ContentScript): Promise<RegisteredContent> {
|
||||
export async function run_content_script(
|
||||
{ mod, version, engine_access, url }: ContentScript,
|
||||
): Promise<RegisteredContent> {
|
||||
// the whole script loads here, and one with engine access can import cubi/engine. only engine.common is here
|
||||
expose_engine({ common: common_engine() });
|
||||
const blocks: BlockJson[] = [];
|
||||
let setting_up = true;
|
||||
const ctx: ContentContext = {
|
||||
@@ -48,12 +57,11 @@ export async function run_content_script({ mod, version, url }: ContentScript):
|
||||
},
|
||||
};
|
||||
try {
|
||||
const module = await import(url);
|
||||
if (typeof module.setup !== "function") throw new Error("the content script doesn't export a setup function");
|
||||
await module.setup(ctx);
|
||||
await run_phase({ id: mod, engine_access }, url, "content", () => ctx);
|
||||
return { blocks, problems: [] };
|
||||
} catch (e) {
|
||||
return { blocks, problems: [e instanceof Error ? e.message : String(e)] };
|
||||
const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e);
|
||||
return { blocks, problems: [problem] };
|
||||
} finally {
|
||||
setting_up = false;
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ export interface BlockRegistry {
|
||||
place_in?: string[];
|
||||
// custom components from mods and their params, the server runs them
|
||||
components?: Record<string, unknown>;
|
||||
// draws the item a server script gives it (ServerWorld.set_block_item) on top of it, like the
|
||||
// draws the item a mod's server phase gives it (ServerWorld.set_block_item) on top of it, like the
|
||||
// cutting board. surface is the height in pixels it lies on. turned with the variant's y
|
||||
item_display?: { surface: number };
|
||||
// a fluid like water, drawn like luanti's: its top slopes down towards where it flows. see FluidProperties
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name,
|
||||
// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared phases give them, which name,
|
||||
// color and value a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips
|
||||
// and a client's drawing agree
|
||||
import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts";
|
||||
@@ -44,7 +44,7 @@ export class FluidRules {
|
||||
return this.#ask(fluid, "sell_value", "a number of 0 or more", valid) ?? json.base_sell_value;
|
||||
}
|
||||
|
||||
// ctx.fluids for server and client scripts
|
||||
// ctx.fluids for server and client phases
|
||||
api(): FluidApi {
|
||||
return {
|
||||
ids: () => EverythingRegistry.entries("fluids").map(([id]) => id),
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ export interface ItemData {
|
||||
id: string;
|
||||
count: number;
|
||||
data?: unknown;
|
||||
// what server scripts say about it (get_lore), only sent to players, never saved
|
||||
// what server phases say about it (get_lore), only sent to players, never saved
|
||||
lore?: string;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
// loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table
|
||||
// has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions
|
||||
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
|
||||
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace.
|
||||
// conditions and functions (ctx.loot in server phases), which are ids in their namespace.
|
||||
// see docs/modding/resources/loot_tables.md
|
||||
import * as z from "zod";
|
||||
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
|
||||
|
||||
+19
-35
@@ -59,14 +59,11 @@ const MAX_UNZIPPED_BYTES = 64 * 1024 * 1024;
|
||||
// written into every entry, so packing the same mod twice gives the same bytes and the same hash
|
||||
const FIXED_TIME = new Date(Date.UTC(2020, 0, 1));
|
||||
|
||||
export type ScriptSide = "server" | "client" | "worldgen" | "shared" | "content";
|
||||
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared", "content"];
|
||||
|
||||
export interface Mod {
|
||||
manifest: ManifestJson;
|
||||
data: ModData;
|
||||
// bundled javascript, one module per side
|
||||
scripts: Partial<Record<ScriptSide, string>>;
|
||||
// its script bundled into one javascript module, which every side runs the phases of, see run_phase
|
||||
script?: string;
|
||||
// png bytes by texture id, like copper_tools:copper_block
|
||||
textures: Map<string, Uint8Array>;
|
||||
// the .json of the textures that have one, like animated ones, by texture id
|
||||
@@ -82,27 +79,24 @@ export class ModError extends Error {
|
||||
}
|
||||
|
||||
// the zip's layout:
|
||||
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip
|
||||
// manifest.json the mod's manifest, with "main" and "credits" pointing into the zip
|
||||
// data.json every block, model, item, recipe, ore, entity, entity model, effect, fluid, tag, loot
|
||||
// table and biome, and the mod's config
|
||||
// scripts/<side>.js
|
||||
// script.js
|
||||
// textures/<name>.png the texture <mod id>:<name>
|
||||
// textures/<name>.json its animation, if it has one
|
||||
// credits.md
|
||||
export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
|
||||
const text = (value: string) => new TextEncoder().encode(value);
|
||||
const manifest: ManifestJson = { ...mod.manifest, scripts: {} };
|
||||
const manifest: ManifestJson = { ...mod.manifest };
|
||||
delete manifest.main;
|
||||
delete manifest.credits;
|
||||
|
||||
const files: Record<string, Uint8Array> = {};
|
||||
for (const side of SCRIPT_SIDES) {
|
||||
const code = mod.scripts[side];
|
||||
if (code !== undefined) {
|
||||
files[`scripts/${side}.js`] = text(code);
|
||||
manifest.scripts![side] = `scripts/${side}.js`;
|
||||
}
|
||||
if (mod.script !== undefined) {
|
||||
files["script.js"] = text(mod.script);
|
||||
manifest.main = "script.js";
|
||||
}
|
||||
if (Object.keys(manifest.scripts!).length === 0) delete manifest.scripts;
|
||||
if (mod.credits !== undefined) {
|
||||
files["credits.md"] = text(mod.credits);
|
||||
manifest.credits = "credits.md";
|
||||
@@ -233,18 +227,13 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
|
||||
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
|
||||
}
|
||||
|
||||
const scripts: Mod["scripts"] = {};
|
||||
for (const [side, path] of Object.entries(manifest.scripts ?? {})) {
|
||||
const code = text(path);
|
||||
if (!SCRIPT_SIDES.includes(side as ScriptSide) || code === undefined) {
|
||||
problems.push(`manifest.json: scripts.${side} ${path} isn't in the file`);
|
||||
} else {
|
||||
scripts[side as ScriptSide] = code;
|
||||
}
|
||||
const script = manifest.main === undefined ? undefined : text(manifest.main);
|
||||
if (manifest.main !== undefined && script === undefined) {
|
||||
problems.push(`manifest.json: main ${manifest.main} isn't in the file`);
|
||||
}
|
||||
// what the cubi/engine shim reads, so it's in the bundle of every script that imports it
|
||||
if (!manifest.engine_access && Object.values(scripts).some((code) => code.includes(ENGINE_GLOBAL))) {
|
||||
problems.push(`a script uses cubi/engine, which needs "engine_access": true in manifest.json`);
|
||||
// what the cubi/engine shim reads, so it's in the bundle of a script that imports it
|
||||
if (!manifest.engine_access && script?.includes(ENGINE_GLOBAL)) {
|
||||
problems.push(`its script uses cubi/engine, which needs "engine_access": true in manifest.json`);
|
||||
}
|
||||
const credits = manifest.credits === undefined ? undefined : text(manifest.credits);
|
||||
if (manifest.credits !== undefined && credits === undefined) {
|
||||
@@ -293,17 +282,12 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
|
||||
}
|
||||
|
||||
if (problems.length > 0) throw new ModError(file, problems);
|
||||
return { manifest, data, scripts, textures, texture_json, credits };
|
||||
return { manifest, data, script, textures, texture_json, credits };
|
||||
}
|
||||
|
||||
// the same mod without its server and worldgen scripts, the terrain's data and its config, what players get. the
|
||||
// server sends them the world
|
||||
// the same mod without the terrain's data and its config, what players get. the server sends them the world. its
|
||||
// script goes with it whole, and players only run its shared and client phases
|
||||
export function client_copy(mod: Mod): Mod {
|
||||
const scripts = { ...mod.scripts };
|
||||
delete scripts.server;
|
||||
delete scripts.worldgen;
|
||||
// players get what it registered in data, see common/mod_api/content.ts
|
||||
delete scripts.content;
|
||||
const {
|
||||
noises: _n,
|
||||
density_functions: _d,
|
||||
@@ -314,7 +298,7 @@ export function client_copy(mod: Mod): Mod {
|
||||
config: _c,
|
||||
...data
|
||||
} = mod.data;
|
||||
return { ...mod, scripts, data };
|
||||
return { ...mod, data };
|
||||
}
|
||||
|
||||
function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what client scripts get, see docs/modding/gui/index.md
|
||||
// what client phases get, see docs/modding/gui/index.md
|
||||
import type {
|
||||
FluidApi,
|
||||
FluidVariant,
|
||||
@@ -66,7 +66,7 @@ export interface ClientContext {
|
||||
// read only, what this client sees
|
||||
world: {
|
||||
get_block(x: number, y: number, z: number): Id | undefined;
|
||||
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy.
|
||||
// a field of the block's client data, what server phases set with BlockRef.set_client_data, a copy.
|
||||
// undefined when it isn't set or the chunk isn't loaded
|
||||
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
|
||||
// the biome at a block and its season, like the server's. undefined when the chunk isn't loaded
|
||||
@@ -115,7 +115,7 @@ export interface ClientContext {
|
||||
table(id: Id): LootTableJson | undefined;
|
||||
};
|
||||
// every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies.
|
||||
// find and all read the recipes of types shared scripts registered
|
||||
// find and all read the recipes of types shared phases registered
|
||||
recipes: {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
list(type?: Id): any[];
|
||||
@@ -376,7 +376,7 @@ export interface HudRegistry {
|
||||
// a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's
|
||||
// registerAboveAll. only during setup. one that throws is removed, with the error in the console
|
||||
register(id: Id, layer: HudLayer): void;
|
||||
// a server script sent an overlay message (MessageOptions.overlay), for a layer to show
|
||||
// a mod's server phase sent an overlay message (MessageOptions.overlay), for a layer to show
|
||||
on_overlay_message(fn: (text: string) => void): void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// content scripts: blocks made in code, for content that's easier to generate than to write out file by file, like
|
||||
// content phases: blocks made in code, for content that's easier to generate than to write out file by file, like
|
||||
// every block of every kind of rock. the server runs them while it loads mods, before anything else reads their data,
|
||||
// and what they register becomes part of the mod's data just like its files: checked the same way, sent to players
|
||||
// with the rest, and generated by worldgen workers. see docs/modding/gettingstarted/modfiles.md
|
||||
|
||||
@@ -13,8 +13,8 @@ import type { client_engine } from "../../client/engine_modules.ts";
|
||||
|
||||
export type { HookHandlers } from "../hooks.ts";
|
||||
|
||||
// the engine's live classes and objects. common is on every side, server only in server scripts, client only in
|
||||
// client scripts
|
||||
// the engine's live classes and objects. common is on every side, server only in server phases, client only in
|
||||
// client phases
|
||||
export interface Engine {
|
||||
common: ReturnType<typeof common_engine>;
|
||||
server: ReturnType<typeof server_engine>;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what server scripts get, see docs/modding/
|
||||
// what server phases get, see docs/modding/
|
||||
import type {
|
||||
EventSignal,
|
||||
Face,
|
||||
@@ -118,7 +118,7 @@ export interface BlockComponent<P = any> {
|
||||
// particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none
|
||||
// there. see ServerFluidApi.block_handler
|
||||
fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined;
|
||||
// placing and neighbor rules are in shared scripts, see BlockRules in cubi/shared
|
||||
// placing and neighbor rules are in shared phases, see BlockRules in cubi/shared
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -638,7 +638,7 @@ export interface TankHandlerOptions {
|
||||
set(tanks: FluidStack[]): void;
|
||||
}
|
||||
|
||||
// ctx.fluids in server scripts: FluidApi, and fluid handlers
|
||||
// ctx.fluids in server phases: FluidApi, and fluid handlers
|
||||
export interface ServerFluidApi extends FluidApi {
|
||||
// the handler of the block at x y z reached from face, from the first of its components with one, like
|
||||
// level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there
|
||||
@@ -660,7 +660,7 @@ export interface ServerFluidApi extends FluidApi {
|
||||
interact(player: Player, handler: FluidHandler): boolean;
|
||||
}
|
||||
|
||||
// find and all read the recipes of types shared scripts registered
|
||||
// find and all read the recipes of types shared phases registered
|
||||
export interface RecipeApi extends RecipeLookup {
|
||||
// every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -817,7 +817,7 @@ export interface MenuRegistry {
|
||||
// adds slots to every player's own inventory menu, always there while they play, like the curios slots next to the
|
||||
// inventory. build runs when each player joins. only during setup
|
||||
extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void;
|
||||
// like registering a MenuType. the client script gives it a screen with ctx.ui.register_menu_screen
|
||||
// like registering a MenuType. the client phase gives it a screen with ctx.ui.register_menu_screen
|
||||
register<Args = undefined>(
|
||||
id: Id,
|
||||
build: (menu: MenuBuilder, args: Args, player: Player) => void,
|
||||
|
||||
+10
-10
@@ -12,7 +12,7 @@ export type Season = "spring" | "summer" | "autumn" | "winter";
|
||||
export interface ItemStack {
|
||||
readonly id: Id;
|
||||
count: number;
|
||||
// any json value, set by server scripts
|
||||
// any json value, set by server phases
|
||||
data?: unknown;
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface FluidStack {
|
||||
amount: number;
|
||||
}
|
||||
|
||||
// ctx.fluids in server and client scripts: every fluid any mod defines, the same on the server and every client
|
||||
// ctx.fluids in server and client phases: every fluid any mod defines, the same on the server and every client
|
||||
export interface FluidApi {
|
||||
// every fluid's id, in load order, like ctx.items.ids. each without data, which a fluid like juice has many of
|
||||
ids(): Id[];
|
||||
@@ -44,7 +44,7 @@ export interface FluidApi {
|
||||
same(a: FluidVariant, b: FluidVariant): boolean;
|
||||
}
|
||||
|
||||
// what a fluid's data makes it, registered by a shared script, like neoforge's FluidType.getDescription and
|
||||
// what a fluid's data makes it, registered by a mod's shared phase, like neoforge's FluidType.getDescription and
|
||||
// FluidTintSource.colorAsStack without the amount. data is the variant's, undefined for none, and isn't to be changed.
|
||||
// returning undefined keeps what the fluid's json says
|
||||
export interface FluidRules {
|
||||
@@ -127,7 +127,7 @@ export interface EventSignal<T> {
|
||||
subscribe(handler: (event: T) => void): Unsubscribe;
|
||||
}
|
||||
|
||||
// shared scripts: block rules that run on the server and on every client, so a client places blocks the way the
|
||||
// shared phases: block rules that run on the server and on every client, so a client places blocks the way the
|
||||
// server will, like minecraft's Block code that both sides run. see docs/modding/gettingstarted/modfiles.md
|
||||
|
||||
export interface SharedContext {
|
||||
@@ -169,21 +169,21 @@ export interface SharedContext {
|
||||
readonly recipes: {
|
||||
// adds a recipe of type, like "shaped" or "bworld:cooking", as a file in the mod's recipes/ with that
|
||||
// json would, only during setup. for recipes made from other data, like one for every item with a component.
|
||||
// shared scripts run on the server and every client alike, so they all have it without it being sent. it's
|
||||
// there for server and client scripts, which set up after, and it throws when it's broken like a file would
|
||||
// shared phases run on the server and every client alike, so they all have it without it being sent. it's
|
||||
// there for server and client phases, which set up after, and it throws when it's broken like a file would
|
||||
// stop the mod loading
|
||||
register(type: string, json: Record<string, unknown>): void;
|
||||
// every recipe, or every one of type, as its json, copies, in load order: the mods' recipes/ files, and what the
|
||||
// shared scripts that set up before this one registered, which are the dependencies'. like the client's
|
||||
// shared phases that set up before this one registered, which are the dependencies'. like the client's
|
||||
// deno-lint-ignore no-explicit-any
|
||||
list(type?: string): any[];
|
||||
// a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register,
|
||||
// are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod
|
||||
// registers stops its mod loading once every shared script has set up. see RecipeType
|
||||
// registers stops its mod loading once every shared phase has set up. see RecipeType
|
||||
register_type<R, I>(type: Id, rules: RecipeType<R, I>): void;
|
||||
} & RecipeLookup;
|
||||
readonly components: {
|
||||
// the rules of a block component, the same id the server script registers the rest of it under
|
||||
// the rules of a block component, the same id the server phase registers the rest of it under
|
||||
// deno-lint-ignore no-explicit-any
|
||||
register_block<P = any>(id: Id, rules: BlockRules<P>): void;
|
||||
};
|
||||
@@ -246,6 +246,6 @@ export interface BlockRules<P = any> {
|
||||
on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void;
|
||||
// a player right clicks it, like minecraft's useWithoutItem: changes only its states and its neighbors', which
|
||||
// the clicking client shows right away instead of waiting for the server. return true if it did something, then
|
||||
// nothing is placed. the server runs the server script's on_interact too
|
||||
// nothing is placed. the server runs the server phase's on_interact too
|
||||
on_interact?(block: SharedBlock, params: P, interaction: BlockInteraction): boolean | void;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
|
||||
// what worldgen phases get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
|
||||
import type { Id, Position } from "./shared.ts";
|
||||
|
||||
export type { Id, Position } from "./shared.ts";
|
||||
|
||||
+1
-1
@@ -487,7 +487,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
// check-mods doesn't run scripts, the server checks these when it starts
|
||||
for (const custom of refs.custom) {
|
||||
check_namespace(file, custom);
|
||||
warnings.push(`${file}: ${custom} isn't built in, a worldgen script must register it`);
|
||||
warnings.push(`${file}: ${custom} isn't built in, a mod's worldgen phase must register it`);
|
||||
}
|
||||
}
|
||||
for (const { file, json } of mod.biomes ?? []) {
|
||||
|
||||
+2
-7
@@ -82,13 +82,8 @@ const manifest_schema = (folder_name: string) =>
|
||||
// imports cubi/engine to reach into the engine and hook its methods. needs game_version within one minor version
|
||||
engine_access: z.boolean().optional(),
|
||||
dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(),
|
||||
scripts: z.strictObject({
|
||||
server: z.string().optional(),
|
||||
client: z.string().optional(),
|
||||
worldgen: z.string().optional(),
|
||||
shared: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
}).optional(),
|
||||
// the mod's script, whose exports are its phases, see common/mod_loader.ts's PHASES
|
||||
main: z.string().optional(),
|
||||
credits: z.string().optional(),
|
||||
}).superRefine((manifest, ctx) => {
|
||||
const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined;
|
||||
|
||||
+37
-6
@@ -44,6 +44,7 @@ import type {
|
||||
import type { FeatureJson } from "./worldgen/features.ts";
|
||||
import { register_block_item } from "./utils.ts";
|
||||
import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts";
|
||||
import { loading_mod } from "./hooks.ts";
|
||||
|
||||
// everything a mod's json files hold, merged into one file by the build (build/mods/<id>/<hash>/data.json)
|
||||
export interface ModData {
|
||||
@@ -81,7 +82,7 @@ export interface ModData {
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// a mod as the server lists it to clients, in load order: the .cubi players download, without its server script
|
||||
// a mod as the server lists it to clients, in load order: the .cubi players download, without its terrain or config
|
||||
export interface ModListing {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -100,7 +101,7 @@ export class RecipeBook {
|
||||
// recipes of mods' own types, by type, and the mod with the first one of each, for the error when nothing registers it
|
||||
by_type = new Map<string, ModRecipeJson[]>();
|
||||
first_used_by = new Map<string, string>();
|
||||
// the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type
|
||||
// the types shared phases registered, and their recipes as parse made them, see SharedContext.recipes.register_type
|
||||
types = new Map<string, RecipeType<unknown, unknown>>();
|
||||
parsed = new Map<string, unknown[]>();
|
||||
// every recipe as its json, in load order, for recipe viewers
|
||||
@@ -111,12 +112,42 @@ export class RecipeBook {
|
||||
}
|
||||
|
||||
export class ModLoadError extends Error {
|
||||
// the message without the mod's id
|
||||
readonly problem: string;
|
||||
|
||||
constructor(mod: string, message: string) {
|
||||
super(`${mod}: ${message}`);
|
||||
this.name = "ModLoadError";
|
||||
this.problem = message;
|
||||
}
|
||||
}
|
||||
|
||||
// what a mod's script can export, each called with its context where and when it runs: content on the server while
|
||||
// it loads mods, shared on the server and every client, then server or client, and worldgen wherever chunks are
|
||||
// generated. see docs/modding/concepts/sides.md
|
||||
export const PHASES = ["content", "shared", "server", "client", "worldgen"] as const;
|
||||
export type Phase = typeof PHASES[number];
|
||||
|
||||
// imports a mod's script and calls its export for phase, if it has one, with the context context makes. a realm
|
||||
// imports the same url once, so every phase there gets the same module and what it keeps at its top level
|
||||
export async function run_phase(
|
||||
mod: { id: string; engine_access?: boolean },
|
||||
url: string,
|
||||
phase: Phase,
|
||||
context: () => unknown,
|
||||
): Promise<void> {
|
||||
await loading_mod(mod.id, mod.engine_access ?? false, async () => {
|
||||
const module = await import(url);
|
||||
if (!PHASES.some((name) => name in module)) {
|
||||
throw new ModLoadError(mod.id, `its script exports none of ${PHASES.join(", ")}`);
|
||||
}
|
||||
const run = module[phase];
|
||||
if (run === undefined) return;
|
||||
if (typeof run !== "function") throw new ModLoadError(mod.id, `its script's ${phase} export isn't a function`);
|
||||
await run(context());
|
||||
});
|
||||
}
|
||||
|
||||
// whether a block, item, entity or biome is registered, for tags. air isn't a registered block, but tags can hold it
|
||||
export function is_registered(registry: TagRegistry, id: string): boolean {
|
||||
return (registry === "blocks" && id === "cubi:air") || EverythingRegistry.get(registry, id) !== undefined;
|
||||
@@ -183,7 +214,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
|
||||
}
|
||||
for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json);
|
||||
for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json);
|
||||
// compiled with the types worldgen scripts register, see common/worldgen_loader.ts
|
||||
// compiled with the types worldgen phases register, see common/worldgen_loader.ts
|
||||
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
|
||||
} catch (e) {
|
||||
throw new ModLoadError(id, (e as Error).message);
|
||||
@@ -212,7 +243,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
|
||||
return recipes;
|
||||
}
|
||||
|
||||
// puts mod's recipe in the book, from its recipes/ or its shared script. throws when its registered type's parse throws
|
||||
// puts mod's recipe in the book, from its recipes/ or its shared phase. throws when its registered type's parse throws
|
||||
export function add_recipe(recipes: RecipeBook, recipe: RecipeJson, mod: string) {
|
||||
recipes.all.push(recipe);
|
||||
if (is_mod_recipe(recipe)) {
|
||||
@@ -276,7 +307,7 @@ function checked_item(name: string, problems: string[], id: string): string {
|
||||
return id;
|
||||
}
|
||||
|
||||
// once every shared script has set up: a recipe of a type no mod registered, which nothing would read, is an error
|
||||
// once every shared phase has set up: a recipe of a type no mod registered, which nothing would read, is an error
|
||||
// for the first mod with one, like a misspelled type
|
||||
export function check_recipe_types(recipes: RecipeBook) {
|
||||
for (const [type, mod] of recipes.first_used_by) {
|
||||
@@ -297,7 +328,7 @@ export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup {
|
||||
};
|
||||
}
|
||||
|
||||
// ctx.recipes for shared scripts, the same on the server and every client: a recipe registered there is in the book
|
||||
// ctx.recipes for shared phases, the same on the server and every client: a recipe registered there is in the book
|
||||
// on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the
|
||||
// side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it
|
||||
export function shared_recipes_api(
|
||||
|
||||
+2
-2
@@ -166,7 +166,7 @@ export type ClientMessage =
|
||||
| { type: "chat"; text: string }
|
||||
// what could come next in a command being typed, answered with suggestions. id matches them up
|
||||
| { type: "suggest"; id: number; text: string }
|
||||
// a mod's client script talking to its server script, see ctx.net
|
||||
// a mod's client phase talking to its server phase, see ctx.net
|
||||
| { type: "mod"; channel: string; data: unknown };
|
||||
|
||||
export type ServerMessage =
|
||||
@@ -304,7 +304,7 @@ export type ServerMessage =
|
||||
// the player's own effects that show an icon, when they change. duration is in ticks, -1 for forever, and the
|
||||
// client counts it down itself, so it isn't sent every tick
|
||||
| { type: "effects"; effects: { id: string; amplifier: number; duration: number }[] }
|
||||
// a mod's server script talking to its client script, see ctx.net
|
||||
// a mod's server phase talking to its client phase, see ctx.net
|
||||
| { type: "mod"; channel: string; data: unknown };
|
||||
|
||||
export const MAX_NAME_LENGTH = 16;
|
||||
|
||||
+1
-1
@@ -181,7 +181,7 @@ export function expand_items(list: readonly string[]): string[] {
|
||||
return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))];
|
||||
}
|
||||
|
||||
// ctx.tags for server and client scripts. everything it returns is a copy
|
||||
// ctx.tags for server and client phases. everything it returns is a copy
|
||||
export function tag_api(): TagApi {
|
||||
const registry = (name: string): TagRegistry => {
|
||||
if (!TAG_REGISTRIES.includes(name as TagRegistry)) {
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ export function display_name(item_id: string): string {
|
||||
return EverythingRegistry.get<ItemRegistry>("items", item_id)?.name || name_from_id(item_id);
|
||||
}
|
||||
|
||||
// ctx.items for shared scripts, and the part of the client's that's the same. fluids are this side's rules, which
|
||||
// ctx.items for shared phases, and the part of the client's that's the same. fluids are this side's rules, which
|
||||
// price full fluid containers
|
||||
export function shared_items_api(mod: string, fluids: FluidRules): SharedContext["items"] {
|
||||
const known = (id: string) => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
// data features: worldgen/features/<path>.json in a mod, a feature's type and config (what) with a list of placement
|
||||
// modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into
|
||||
// one file. the types and modifiers here are built in, worldgen scripts register more
|
||||
// one file. the types and modifiers here are built in, worldgen phases register more
|
||||
import { EverythingRegistry } from "../everything_registry.ts";
|
||||
import type { BlockRegistry } from "../everything_registry.ts";
|
||||
import { CHUNK_SIZE } from "../constants.ts";
|
||||
@@ -42,7 +42,7 @@ export const DEFAULT_STEP: FeatureStep = "top_layer_modification";
|
||||
|
||||
export interface FeatureJson {
|
||||
id: string;
|
||||
// a built in type, like "minecraft:block_column", or one a worldgen script registers
|
||||
// a built in type, like "minecraft:block_column", or one a mod's worldgen phase registers
|
||||
type: string;
|
||||
config?: Record<string, unknown>;
|
||||
placement?: PlacementJson[];
|
||||
@@ -73,7 +73,7 @@ export function builtin_name(type: string): string | undefined {
|
||||
export interface FeatureRefs {
|
||||
blocks: Set<string>;
|
||||
biomes: Set<string>;
|
||||
// types and modifiers that aren't built in, which a worldgen script has to register
|
||||
// types and modifiers that aren't built in, which a mod's worldgen phase has to register
|
||||
custom: Set<string>;
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ const block_predicate_schema: z.ZodType = z.lazy(() =>
|
||||
], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true")
|
||||
);
|
||||
|
||||
// a mod's own modifier is checked by the worldgen script that registers it
|
||||
// a mod's own modifier is checked by the worldgen phase that registers it
|
||||
const placement_modifier = by_kind<PlacementJson>("type", (type) => {
|
||||
const name = builtin_name(type);
|
||||
if (name === undefined) return json_object;
|
||||
@@ -156,7 +156,7 @@ const feature_schema: z.ZodType<FeatureJson> = z.object({
|
||||
biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(),
|
||||
step: z.enum(FEATURE_STEPS).optional(),
|
||||
}).superRefine((feature, ctx) => {
|
||||
// a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers
|
||||
// a built in type's config. a mod's own type is checked by the worldgen phase that registers it, like modifiers
|
||||
const name = builtin_name(feature.type);
|
||||
if (name === undefined) return;
|
||||
if (!Object.hasOwn(FEATURE_TYPES, name)) {
|
||||
@@ -205,7 +205,7 @@ export function compile_feature(
|
||||
const type = types.get(json.type);
|
||||
if (!type) {
|
||||
throw new Error(
|
||||
`feature ${json.id}: type ${json.type} isn't built in, and no worldgen script registered it`,
|
||||
`feature ${json.id}: type ${json.type} isn't built in, and no mod's worldgen phase registered it`,
|
||||
);
|
||||
}
|
||||
place = (chunk, origin) => type(chunk, config, origin);
|
||||
@@ -216,7 +216,7 @@ export function compile_feature(
|
||||
const custom = modifiers.get(modifier.type);
|
||||
if (!custom) {
|
||||
throw new Error(
|
||||
`feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no worldgen script registered it`,
|
||||
`feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no mod's worldgen phase registered it`,
|
||||
);
|
||||
}
|
||||
return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions);
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// everything generating a chunk reads, as one plain object a worker can be sent: the seed, the generator, and each
|
||||
// mod's data generation needs with its worldgen script's url. loading it registers the data in this realm and loads
|
||||
// the scripts, which gives the same numeric block ids and the same generator as the game, so chunks come out the same
|
||||
// block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture
|
||||
// mod's data generation needs with its script's url. loading it registers the data in this realm and runs the
|
||||
// scripts' worldgen phases, which gives the same numeric block ids and the same generator as the game, so chunks come
|
||||
// out the same block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture
|
||||
import type { ModData } from "./mod_loader.ts";
|
||||
import { register_mod_data } from "./mod_loader.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
|
||||
@@ -35,20 +35,21 @@ export interface WorldgenBundle {
|
||||
// the dimension's, see WorldShape
|
||||
shape: WorldShapeJson;
|
||||
// in load order
|
||||
mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[];
|
||||
// url is the mod's script, which worldgen workers run the worldgen phase of
|
||||
mods: { id: string; data: WorldgenModData; url?: string; engine_access?: boolean }[];
|
||||
}
|
||||
|
||||
export function worldgen_bundle(
|
||||
seed: string,
|
||||
generator: string,
|
||||
shape: WorldShapeJson,
|
||||
mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[],
|
||||
mods: { id: string; data: ModData; url?: string; engine_access?: boolean }[],
|
||||
): WorldgenBundle {
|
||||
return {
|
||||
seed,
|
||||
generator,
|
||||
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
|
||||
mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({
|
||||
mods: mods.map(({ id, data, url, engine_access }) => ({
|
||||
id,
|
||||
data: {
|
||||
blocks: data.blocks,
|
||||
@@ -62,7 +63,7 @@ export function worldgen_bundle(
|
||||
biome_sources: data.biome_sources ?? [],
|
||||
features: data.features ?? [],
|
||||
},
|
||||
...(worldgen_url ? { worldgen_url } : {}),
|
||||
...(url ? { url } : {}),
|
||||
...(engine_access ? { engine_access } : {}),
|
||||
})),
|
||||
};
|
||||
@@ -105,7 +106,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
|
||||
const setup = await load_worldgen({
|
||||
mods: bundle.mods.map((mod) => mod.id),
|
||||
scripts: bundle.mods.flatMap((mod) =>
|
||||
mod.worldgen_url ? [{ mod: mod.id, url: mod.worldgen_url, engine_access: mod.engine_access }] : []
|
||||
mod.url ? [{ mod: mod.id, url: mod.url, engine_access: mod.engine_access }] : []
|
||||
),
|
||||
ores: recipes.ores,
|
||||
generator: bundle.generator,
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// imports mods' worldgen scripts and collects what they and mods' data add to generation: the generator, ores, and
|
||||
// runs mods' worldgen phases and collects what they and mods' data add to generation: the generator, ores, and
|
||||
// features, code and data, in the order they run. used by the game server
|
||||
import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_api/worldgen.ts";
|
||||
import type { OreJson } from "@/common/mod_data.ts";
|
||||
import type { SetupFeature, WorldgenSetup } from "./generation.ts";
|
||||
import { EverythingRegistry } from "./everything_registry.ts";
|
||||
import { ModLoadError } from "./mod_loader.ts";
|
||||
import { loading_mod } from "./hooks.ts";
|
||||
import { ModLoadError, run_phase } from "./mod_loader.ts";
|
||||
import { compile_generator } from "./worldgen/generator.ts";
|
||||
import type { WorldShape } from "./world_shape.ts";
|
||||
import {
|
||||
@@ -97,13 +96,7 @@ export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenS
|
||||
},
|
||||
};
|
||||
|
||||
await loading_mod(mod, engine_access ?? false, async () => {
|
||||
const module = await import(url);
|
||||
if (typeof module.setup !== "function") {
|
||||
throw new ModLoadError(mod, "the worldgen script doesn't export a setup function");
|
||||
}
|
||||
await module.setup(ctx);
|
||||
});
|
||||
await run_phase({ id: mod, engine_access }, url, "worldgen", () => ctx);
|
||||
}
|
||||
|
||||
// data features last, so they can use the types and modifiers every script registered
|
||||
|
||||
Reference in New Issue
Block a user