sharing contexts
This commit is contained in:
@@ -70,8 +70,8 @@ export class BlockRules {
|
||||
readonly told?: (x: number, y: number, z: number, from: Position) => void,
|
||||
) {}
|
||||
|
||||
// checked by the shared context, see common/shared_context.ts
|
||||
register(mod: string, id: string, rules: Rules) {
|
||||
if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`);
|
||||
this.#rules.set(id, { mod, rules });
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// 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 { ModLoadError, registrar, run_phase } from "./mod_loader.ts";
|
||||
import { expose_engine } from "./hooks.ts";
|
||||
import { common_engine } from "./engine_modules.ts";
|
||||
|
||||
@@ -38,20 +38,19 @@ export async function run_content_script(
|
||||
// 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;
|
||||
let running = true;
|
||||
const register = registrar(mod, "content", () => running);
|
||||
const ctx: ContentContext = {
|
||||
mod: { id: mod, version },
|
||||
blocks: {
|
||||
register(block) {
|
||||
if (!setting_up) throw new Error("blocks can only be registered during setup");
|
||||
register.running("block");
|
||||
// what a file could hold, so the server, its players and its worldgen workers all get the same thing
|
||||
const json = JSON.parse(JSON.stringify(block ?? null));
|
||||
const id = typeof json?.id === "string" ? json.id : "without an id";
|
||||
const problems = validate_block(json);
|
||||
if (problems.length > 0) throw new Error(`block ${id}: ${problems.join("; ")}`);
|
||||
if (json.id.split(":")[0] !== mod) {
|
||||
throw new Error(`block ${json.id} isn't in this mod's namespace "${mod}"`);
|
||||
}
|
||||
if (problems.length > 0) register.fail(`block ${id}: ${problems.join("; ")}`);
|
||||
register.own("block", json.id);
|
||||
blocks.push(json);
|
||||
},
|
||||
},
|
||||
@@ -63,6 +62,6 @@ export async function run_content_script(
|
||||
const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e);
|
||||
return { blocks, problems: [problem] };
|
||||
} finally {
|
||||
setting_up = false;
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
|
||||
+5
-3
@@ -16,13 +16,15 @@ export class FluidRules {
|
||||
// run runs a mod's code, reporting what it throws instead of letting it take the game down
|
||||
constructor(readonly run: <T>(mod: string, what: string, fn: () => T) => T | undefined) {}
|
||||
|
||||
// checked by the shared context, see common/shared_context.ts
|
||||
register(mod: string, id: string, rules: Rules) {
|
||||
if (!id.startsWith(`${mod}:`)) throw new Error(`[${mod}] fluid ${id} must be in the namespace "${mod}"`);
|
||||
if (!EverythingRegistry.get("fluids", id)) throw new Error(`[${mod}] unknown fluid ${id}`);
|
||||
if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of fluid ${id} are registered twice`);
|
||||
this.#rules.set(id, { mod, rules });
|
||||
}
|
||||
|
||||
has(id: string) {
|
||||
return this.#rules.has(id);
|
||||
}
|
||||
|
||||
name(fluid: FluidVariant): string {
|
||||
const json = known_fluid(fluid.id);
|
||||
const valid = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
||||
|
||||
+35
-8
@@ -128,6 +128,35 @@ export class ModLoadError extends Error {
|
||||
export const PHASES = ["content", "shared", "server", "client", "worldgen"] as const;
|
||||
export type Phase = typeof PHASES[number];
|
||||
|
||||
// the checks everything a mod registers from code goes through, the same on every side: only while the phase that
|
||||
// registers it runs, in the mod's own namespace, and once. running says whether that phase is running. what names the
|
||||
// kind of thing, like "component"
|
||||
export function registrar(mod: string, phase: Phase, running: () => boolean) {
|
||||
const fail = (message: string): never => {
|
||||
throw new ModLoadError(mod, message);
|
||||
};
|
||||
const checks = {
|
||||
fail,
|
||||
running(what: string) {
|
||||
if (!running()) fail(`${what} can only be registered while the ${phase} phase runs`);
|
||||
},
|
||||
own(what: string, id: string) {
|
||||
if (typeof id !== "string" || !id.startsWith(`${mod}:`)) {
|
||||
fail(`${what} ${id} must be in the namespace "${mod}"`);
|
||||
}
|
||||
},
|
||||
// all three, taken saying whether id is registered already
|
||||
new_id(what: string, id: string, taken: boolean) {
|
||||
checks.running(what);
|
||||
checks.own(what, id);
|
||||
if (taken) fail(`${what} ${id} is registered twice`);
|
||||
},
|
||||
};
|
||||
return checks;
|
||||
}
|
||||
|
||||
export type Registrar = ReturnType<typeof registrar>;
|
||||
|
||||
// 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(
|
||||
@@ -329,18 +358,18 @@ export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup {
|
||||
}
|
||||
|
||||
// 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
|
||||
// on every side without being sent, like one from the mod's recipes/. checked like a data file's. list reads the book
|
||||
// as it is, so a script sees the recipes of the ones before it
|
||||
export function shared_recipes_api(
|
||||
mod: string,
|
||||
recipes: () => RecipeBook,
|
||||
setting_up: () => boolean,
|
||||
fail: (message: string) => never,
|
||||
register: Registrar,
|
||||
): SharedContext["recipes"] {
|
||||
const fail = register.fail;
|
||||
return {
|
||||
...recipe_lookup(recipes),
|
||||
register(type, json) {
|
||||
if (!setting_up()) fail("recipes can only be registered during setup");
|
||||
register.running("recipe");
|
||||
const recipe = { ...structuredClone(json), type };
|
||||
const problems = validate_recipe(recipe);
|
||||
if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`);
|
||||
@@ -353,10 +382,8 @@ export function shared_recipes_api(
|
||||
list: (type) => structuredClone(type ? recipes().all.filter((recipe) => recipe.type === type) : recipes().all),
|
||||
// the recipes of the type there are so far are parsed now, and the ones registered after as they come
|
||||
register_type(type, rules) {
|
||||
if (!setting_up()) fail("recipe types can only be registered during setup");
|
||||
if (!type.startsWith(`${mod}:`)) fail(`recipe type ${type} must be in the namespace "${mod}"`);
|
||||
const book = recipes();
|
||||
if (book.types.has(type)) fail(`recipe type ${type} is already registered`);
|
||||
register.new_id("recipe type", type, book.types.has(type));
|
||||
const type_rules = rules as RecipeType<unknown, unknown>;
|
||||
try {
|
||||
book.parsed.set(
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what mods' shared phases get, built the same way on the server and every client so they register the same rules and
|
||||
// recipes. each side gives it its own world, rules and recipe book
|
||||
import type { ModInfo, SharedContext, SharedWorld } from "./mod_api/shared.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
|
||||
import { AIR_ID } from "./protocol.ts";
|
||||
import { is_solid } from "./block_shapes.ts";
|
||||
import type { BlockRules } from "./block_rules.ts";
|
||||
import { fluid_exists, type FluidRules, same_fluid } from "./fluids.ts";
|
||||
import { type RecipeBook, registrar, shared_recipes_api } from "./mod_loader.ts";
|
||||
import { tag_api } from "./tags.ts";
|
||||
import { shared_items_api } from "./utils.ts";
|
||||
|
||||
export interface SharedSide {
|
||||
side: "server" | "client";
|
||||
// what the rules read and change: the real world on the server, what a client shows on a client
|
||||
world: SharedWorld;
|
||||
block_rules: BlockRules;
|
||||
fluid_rules: FluidRules;
|
||||
recipes: () => RecipeBook;
|
||||
// whether the shared phases are running, the only time they can register
|
||||
running: () => boolean;
|
||||
}
|
||||
|
||||
export function shared_context(mod: ModInfo, side: SharedSide): SharedContext {
|
||||
const register = registrar(mod.id, "shared", side.running);
|
||||
return {
|
||||
mod,
|
||||
side: side.side,
|
||||
tags: tag_api(),
|
||||
blocks: blocks_api(),
|
||||
items: shared_items_api(mod.id, side.fluid_rules),
|
||||
fluids: {
|
||||
exists: fluid_exists,
|
||||
same: same_fluid,
|
||||
register(id, rules) {
|
||||
register.new_id("fluid rules", id, side.fluid_rules.has(id));
|
||||
if (!fluid_exists(id)) register.fail(`unknown fluid ${id}`);
|
||||
side.fluid_rules.register(mod.id, id, rules);
|
||||
},
|
||||
},
|
||||
recipes: shared_recipes_api(mod.id, side.recipes, register),
|
||||
world: side.world,
|
||||
components: {
|
||||
register_block(id, rules) {
|
||||
register.new_id("component", id, side.block_rules.has(id));
|
||||
side.block_rules.register(mod.id, id, rules);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ctx.blocks, the part every side has
|
||||
export function blocks_api(): SharedContext["blocks"] {
|
||||
const known = (id: string) => {
|
||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
if (!block) throw new Error(`unknown block ${id}`);
|
||||
return block;
|
||||
};
|
||||
return {
|
||||
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
||||
components: (id) => structuredClone(known(id).components ?? {}),
|
||||
solid: (id) => id !== AIR_ID && is_solid(known(id)),
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_ap
|
||||
import type { OreJson } from "@/common/mod_data.ts";
|
||||
import type { SetupFeature, WorldgenSetup } from "./generation.ts";
|
||||
import { EverythingRegistry } from "./everything_registry.ts";
|
||||
import { ModLoadError, run_phase } from "./mod_loader.ts";
|
||||
import { ModLoadError, registrar, run_phase } from "./mod_loader.ts";
|
||||
import { compile_generator } from "./worldgen/generator.ts";
|
||||
import type { WorldShape } from "./world_shape.ts";
|
||||
import {
|
||||
@@ -54,17 +54,12 @@ export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenS
|
||||
const data_features = (EverythingRegistry.get_registry<FeatureJson>("features") ?? []).filter((f) => f);
|
||||
|
||||
for (const { mod, url, engine_access } of sources.scripts) {
|
||||
const own = (id: string, what: string) => {
|
||||
if (!id.startsWith(`${mod}:`)) {
|
||||
throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`);
|
||||
}
|
||||
};
|
||||
let running = true;
|
||||
const register = registrar(mod, "worldgen", () => running);
|
||||
const ctx: WorldgenContext = {
|
||||
register_feature(id, generate, options = {}) {
|
||||
own(id, "feature");
|
||||
if (pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id)) {
|
||||
throw new ModLoadError(mod, `feature ${id} is registered twice, as code or data`);
|
||||
}
|
||||
const taken = pending.some((p) => p.feature.id === id) || data_features.some((f) => f.id === id);
|
||||
register.new_id("feature", id, taken);
|
||||
const step = options.step ?? DEFAULT_STEP;
|
||||
if (!FEATURE_STEPS.includes(step)) {
|
||||
throw new ModLoadError(mod, `feature ${id}: step must be one of ${FEATURE_STEPS.join(", ")}`);
|
||||
@@ -79,13 +74,11 @@ export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenS
|
||||
});
|
||||
},
|
||||
register_feature_type(id, place) {
|
||||
own(id, "feature type");
|
||||
if (types.has(id)) throw new ModLoadError(mod, `feature type ${id} is registered twice`);
|
||||
register.new_id("feature type", id, types.has(id));
|
||||
types.set(id, place as FeatureType);
|
||||
},
|
||||
register_placement_modifier(id, modify) {
|
||||
own(id, "placement modifier");
|
||||
if (modifiers.has(id)) throw new ModLoadError(mod, `placement modifier ${id} is registered twice`);
|
||||
register.new_id("placement modifier", id, modifiers.has(id));
|
||||
modifiers.set(id, modify as PlacementModifier);
|
||||
},
|
||||
register_terrain(id) {
|
||||
@@ -97,6 +90,7 @@ export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenS
|
||||
};
|
||||
|
||||
await run_phase({ id: mod, engine_access }, url, "worldgen", () => ctx);
|
||||
running = false;
|
||||
}
|
||||
|
||||
// data features last, so they can use the types and modifiers every script registered
|
||||
|
||||
Reference in New Issue
Block a user