Engine api
This commit is contained in:
@@ -28,6 +28,7 @@ import {
|
||||
validate_tag,
|
||||
} from "./mod_data.ts";
|
||||
import type { ModData } from "./mod_loader.ts";
|
||||
import { ENGINE_GLOBAL } from "./hooks.ts";
|
||||
|
||||
export const BMOD_EXTENSION = ".bmod";
|
||||
|
||||
@@ -169,6 +170,10 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
scripts[side as ScriptSide] = code;
|
||||
}
|
||||
}
|
||||
// what the bworld/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 bworld/engine, which needs "engine_access": true in manifest.json`);
|
||||
}
|
||||
const credits = manifest.credits === undefined ? undefined : text(manifest.credits);
|
||||
if (manifest.credits !== undefined && credits === undefined) {
|
||||
problems.push(`manifest.json: credits ${manifest.credits} isn't in the file`);
|
||||
|
||||
@@ -4,6 +4,9 @@ export const TEXTURE_SIZE = 16;
|
||||
// the most a texture can be on either side, entity sprites are bigger than blocks'
|
||||
export const MAX_TEXTURE_SIZE = 256;
|
||||
|
||||
// the game's version, what mods' game_version is checked against. mods with engine_access are tied to its minor version
|
||||
export const GAME_VERSION = "0.1.0";
|
||||
|
||||
export const TICKS_PER_SECOND = 20;
|
||||
export const TICK_DELTA = 1 / TICKS_PER_SECOND;
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// what engine access mods get as engine.common, on every side. see docs/modding/misc/engine.md
|
||||
import { EverythingRegistry } from "./everything_registry.ts";
|
||||
import { Container, ContainerSlot, ItemStack } from "./inventory.ts";
|
||||
import { BlockRules } from "./block_rules.ts";
|
||||
import { Tags } from "./tags.ts";
|
||||
import { CommandDispatcher } from "./commands.ts";
|
||||
import { OverworldTerrain } from "./worldgen/terrain.ts";
|
||||
import { BIOMES } from "./worldgen/overworld.ts";
|
||||
import { physics } from "./physics.ts";
|
||||
|
||||
// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined
|
||||
export function common_engine() {
|
||||
return {
|
||||
EverythingRegistry,
|
||||
ItemStack,
|
||||
Container,
|
||||
ContainerSlot,
|
||||
BlockRules,
|
||||
Tags,
|
||||
CommandDispatcher,
|
||||
OverworldTerrain,
|
||||
BIOMES,
|
||||
physics,
|
||||
};
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
// engine access: hooks on the engine's own methods, like neoforge's mixins, and the global the bworld/engine shim reads.
|
||||
// see docs/modding/misc/engine.md and docs/modding_plan.md
|
||||
import { GAME_VERSION } from "./constants.ts";
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type Method = (...args: any[]) => any;
|
||||
type MethodOf<T, K extends keyof T> = T[K] extends Method ? T[K] : never;
|
||||
|
||||
export interface HookHandlers<T, K extends keyof T> {
|
||||
// runs first. change args in place, or return { result } to skip the method and everything after
|
||||
before?(self: T, args: Parameters<MethodOf<T, K>>): { result: ReturnType<MethodOf<T, K>> } | void;
|
||||
// wraps the method, calling original (or not)
|
||||
replace?(
|
||||
self: T,
|
||||
args: Parameters<MethodOf<T, K>>,
|
||||
original: (...args: Parameters<MethodOf<T, K>>) => ReturnType<MethodOf<T, K>>,
|
||||
): ReturnType<MethodOf<T, K>>;
|
||||
// runs last, and returns the result the caller gets. returning undefined keeps the result it was given
|
||||
after?(
|
||||
self: T,
|
||||
args: Parameters<MethodOf<T, K>>,
|
||||
result: ReturnType<MethodOf<T, K>>,
|
||||
): ReturnType<MethodOf<T, K>> | void;
|
||||
// lower runs earlier, the default is 1000. ties go in load order
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
export type Hook = <T extends object, K extends keyof T>(
|
||||
target: T,
|
||||
method: K,
|
||||
handlers: HookHandlers<T, K>,
|
||||
) => () => void;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type AnyHandlers = HookHandlers<any, any>;
|
||||
|
||||
interface Entry {
|
||||
mod: string;
|
||||
handlers: AnyHandlers;
|
||||
priority: number;
|
||||
// when it was hooked, for ties
|
||||
order: number;
|
||||
}
|
||||
|
||||
// one hooked method. the original goes back once its last hook is gone, so a method nobody hooks costs nothing
|
||||
interface Hooked {
|
||||
target: object;
|
||||
key: PropertyKey;
|
||||
name: string;
|
||||
// how it was before the first hook: its own property on target, or inherited when undefined
|
||||
descriptor: PropertyDescriptor | undefined;
|
||||
original: Method;
|
||||
entries: Entry[];
|
||||
}
|
||||
|
||||
const hooked = new Map<object, Map<PropertyKey, Hooked>>();
|
||||
let next_order = 0;
|
||||
|
||||
// the mod whose script is loading or running setup. hooks are made then, so each one knows its mod
|
||||
let loading: { mod: string; engine_access: boolean } | undefined;
|
||||
|
||||
function log(mod: string, what: string, e: unknown) {
|
||||
console.error(`[${mod}] ${what} threw:`, e);
|
||||
}
|
||||
|
||||
// the wrapper that replaces the method. it's made again whenever the hooks change, with only the steps they need, so
|
||||
// a method with only after hooks doesn't walk empty before and replace lists every call
|
||||
function wrapper(state: Hooked): Method {
|
||||
const { original, name } = state;
|
||||
const before = state.entries.filter((e) => e.handlers.before);
|
||||
const replace = state.entries.filter((e) => e.handlers.replace);
|
||||
const after = state.entries.filter((e) => e.handlers.after);
|
||||
|
||||
// the replace hooks, the first outermost, around the original
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const call = (self: any, args: any[], i: number): any => {
|
||||
if (i === replace.length) return original.apply(self, args);
|
||||
const { mod, handlers } = replace[i];
|
||||
let called = false;
|
||||
let inner: unknown;
|
||||
const next = (...next_args: unknown[]) => {
|
||||
called = true;
|
||||
inner = call(self, next_args, i + 1);
|
||||
return inner;
|
||||
};
|
||||
try {
|
||||
return handlers.replace!(self, args, next);
|
||||
} catch (e) {
|
||||
log(mod, `a replace hook on ${name}`, e);
|
||||
// skipped: what it got from the method if it called it, so the method doesn't run twice
|
||||
return called ? inner : call(self, args, i + 1);
|
||||
}
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return function (this: any, ...args: any[]) {
|
||||
for (const { mod, handlers } of before) {
|
||||
try {
|
||||
const skip = handlers.before!(this, args);
|
||||
if (skip) return skip.result;
|
||||
} catch (e) {
|
||||
log(mod, `a before hook on ${name}`, e);
|
||||
}
|
||||
}
|
||||
let result = call(this, args, 0);
|
||||
for (const { mod, handlers } of after) {
|
||||
try {
|
||||
const changed = handlers.after!(this, args, result);
|
||||
if (changed !== undefined) result = changed;
|
||||
} catch (e) {
|
||||
log(mod, `an after hook on ${name}`, e);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function install(state: Hooked) {
|
||||
if (state.entries.length > 0) {
|
||||
Object.defineProperty(state.target, state.key, {
|
||||
value: wrapper(state),
|
||||
writable: true,
|
||||
configurable: true,
|
||||
enumerable: state.descriptor?.enumerable ?? false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.descriptor) {
|
||||
Object.defineProperty(state.target, state.key, state.descriptor);
|
||||
} else {
|
||||
delete (state.target as Record<PropertyKey, unknown>)[state.key];
|
||||
}
|
||||
hooked.get(state.target)?.delete(state.key);
|
||||
}
|
||||
|
||||
function method_name(target: object, key: PropertyKey) {
|
||||
const owner = typeof target === "function" ? target.name : target.constructor?.name;
|
||||
return owner && owner !== "Object" ? `${owner}.${String(key)}` : String(key);
|
||||
}
|
||||
|
||||
// hooks target's method for the mod that's loading. see HookHandlers
|
||||
export const hook: Hook = (target, method, handlers) => {
|
||||
if (!loading) throw new Error("hook can only be called while a mod's script loads or runs its setup");
|
||||
if (!loading.engine_access) {
|
||||
throw new Error(`${loading.mod} hooks the engine without "engine_access" in its manifest`);
|
||||
}
|
||||
const key = method as PropertyKey;
|
||||
let by_key = hooked.get(target);
|
||||
let state = by_key?.get(key);
|
||||
if (!state) {
|
||||
const original = (target as Record<PropertyKey, unknown>)[key];
|
||||
if (typeof original !== "function") throw new Error(`${method_name(target, key)} isn't a method`);
|
||||
if (!Object.isExtensible(target)) throw new Error(`${method_name(target, key)} can't be hooked`);
|
||||
state = {
|
||||
target,
|
||||
key,
|
||||
name: method_name(target, key),
|
||||
descriptor: Object.getOwnPropertyDescriptor(target, key),
|
||||
original: original as Method,
|
||||
entries: [],
|
||||
};
|
||||
if (state.descriptor && !state.descriptor.configurable) {
|
||||
throw new Error(`${state.name} can't be hooked`);
|
||||
}
|
||||
if (!by_key) hooked.set(target, by_key = new Map());
|
||||
by_key.set(key, state);
|
||||
}
|
||||
const entry: Entry = {
|
||||
mod: loading.mod,
|
||||
handlers: handlers as AnyHandlers,
|
||||
priority: handlers.priority ?? 1000,
|
||||
order: next_order++,
|
||||
};
|
||||
state.entries.push(entry);
|
||||
state.entries.sort((a, b) => a.priority - b.priority || a.order - b.order);
|
||||
install(state);
|
||||
|
||||
const hooked_state = state;
|
||||
return () => {
|
||||
const i = hooked_state.entries.indexOf(entry);
|
||||
if (i === -1) return;
|
||||
hooked_state.entries.splice(i, 1);
|
||||
install(hooked_state);
|
||||
};
|
||||
};
|
||||
|
||||
// puts every hooked method back, before a game loads its mods. tests start many games in one realm, and a client
|
||||
// joining another server leaves the last one's mods behind
|
||||
export function clear_hooks() {
|
||||
for (const by_key of [...hooked.values()]) {
|
||||
for (const state of [...by_key.values()]) {
|
||||
state.entries = [];
|
||||
install(state);
|
||||
}
|
||||
}
|
||||
hooked.clear();
|
||||
}
|
||||
|
||||
// runs fn as the mod: hook knows whose hooks it makes, and bworld/engine refuses mods without engine_access
|
||||
export async function loading_mod<T>(mod: string, engine_access: boolean, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = loading;
|
||||
loading = { mod, engine_access };
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
loading = previous;
|
||||
}
|
||||
}
|
||||
|
||||
// the engine's modules on each side, what mods get as engine
|
||||
export interface EngineModules {
|
||||
common?: Record<string, unknown>;
|
||||
server?: Record<string, unknown>;
|
||||
client?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// what bworld/engine reads, see common/mod_api/engine.ts
|
||||
export interface EngineGlobal {
|
||||
version: string;
|
||||
engine: EngineModules;
|
||||
hook: Hook;
|
||||
// throws unless the mod that's loading has engine_access
|
||||
check_access(): void;
|
||||
}
|
||||
|
||||
export const ENGINE_GLOBAL = "__bworld_engine";
|
||||
|
||||
// puts a side's modules where bworld/engine finds them. a realm with the server and a client in it, like tests, gets
|
||||
// both
|
||||
export function expose_engine(modules: EngineModules) {
|
||||
const global = globalThis as unknown as Record<string, EngineGlobal | undefined>;
|
||||
const existing = global[ENGINE_GLOBAL];
|
||||
if (existing) {
|
||||
Object.assign(existing.engine, modules);
|
||||
return;
|
||||
}
|
||||
global[ENGINE_GLOBAL] = {
|
||||
version: GAME_VERSION,
|
||||
engine: { ...modules },
|
||||
hook,
|
||||
check_access() {
|
||||
if (!loading) throw new Error("bworld/engine can only be imported by a mod's script");
|
||||
if (!loading.engine_access) {
|
||||
throw new Error(`${loading.mod} imports bworld/engine without "engine_access" in its manifest`);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// bworld/engine: engine access, for what the game api doesn't cover yet. a mod needs "engine_access": true and a
|
||||
// game_version within one minor version in its manifest. see docs/modding/misc/engine.md
|
||||
//
|
||||
// this is bundled into each mod that imports it, so it only imports types: the engine and hook are the game's own,
|
||||
// read from the global the game sets up before it loads mods
|
||||
import type { EngineGlobal, Hook } from "../hooks.ts";
|
||||
import type { common_engine } from "../engine_modules.ts";
|
||||
import type { server_engine } from "../../server/game/engine_modules.ts";
|
||||
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
|
||||
export interface Engine {
|
||||
common: ReturnType<typeof common_engine>;
|
||||
server: ReturnType<typeof server_engine>;
|
||||
client: ReturnType<typeof client_engine>;
|
||||
}
|
||||
|
||||
const api = (globalThis as unknown as Record<string, EngineGlobal | undefined>)["__bworld_engine"];
|
||||
if (!api) throw new Error("bworld/engine only works in a mod's script, loaded by the game");
|
||||
api.check_access();
|
||||
|
||||
export const engine = api.engine as Engine;
|
||||
// the version of the game that's running, like "0.4.2"
|
||||
export const game_version: string = api.version;
|
||||
// hooks a method of target, usually a class's prototype, so every instance already made changes too. returns a
|
||||
// function that unhooks it
|
||||
export const hook: Hook = api.hook;
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "./everything_registry.ts";
|
||||
import { type BlockPart, type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts";
|
||||
import { expand_items, list_matches } from "./tags.ts";
|
||||
import { GAME_VERSION } from "./constants.ts";
|
||||
|
||||
export const FORMAT_VERSION = 1;
|
||||
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
|
||||
@@ -35,6 +36,8 @@ export interface ManifestJson {
|
||||
version: string;
|
||||
authors?: string[];
|
||||
game_version?: string;
|
||||
// imports bworld/engine to reach into the engine and hook its methods. needs game_version within one minor version
|
||||
engine_access?: boolean;
|
||||
dependencies?: { id: string; version: string }[];
|
||||
scripts?: { server?: string; client?: string; worldgen?: string; shared?: string };
|
||||
credits?: string;
|
||||
@@ -448,6 +451,13 @@ export function validate_manifest(json: unknown, folder_name: string): Problems
|
||||
if (typeof json.version !== "string" || !/^\d+\.\d+\.\d+/.test(json.version)) {
|
||||
problems.push("version must be semver, like 1.0.0");
|
||||
}
|
||||
if (json.engine_access !== undefined && typeof json.engine_access !== "boolean") {
|
||||
problems.push("engine_access must be true or false");
|
||||
}
|
||||
if (json.engine_access === true) {
|
||||
const problem = engine_version_problem(json.game_version);
|
||||
if (problem) problems.push(problem);
|
||||
}
|
||||
if (json.dependencies !== undefined) {
|
||||
if (!Array.isArray(json.dependencies)) {
|
||||
problems.push("dependencies must be a list");
|
||||
@@ -474,6 +484,20 @@ export function validate_manifest(json: unknown, folder_name: string): Problems
|
||||
return problems;
|
||||
}
|
||||
|
||||
// engine access isn't a stable api: a mod using it names one minor version of the game, like "~0.4.0" or "0.4.2", and
|
||||
// loading it on another is an error. game is the version it's loading on
|
||||
export function engine_version_problem(range: unknown, game = GAME_VERSION): string | undefined {
|
||||
const [major, minor, patch] = game.split(".").map(Number);
|
||||
const match = typeof range === "string" ? range.match(/^(~?)(\d+)\.(\d+)\.(\d+)$/) : null;
|
||||
if (!match) {
|
||||
return `engine_access needs game_version to be one minor version, like "~${major}.${minor}.0"`;
|
||||
}
|
||||
const [, tilde, m, n, p] = match;
|
||||
const fits = Number(m) === major && Number(n) === minor &&
|
||||
(tilde ? Number(p) <= patch : Number(p) === patch);
|
||||
if (!fits) return `uses engine_access for game_version ${range}, this is the game's ${game}`;
|
||||
}
|
||||
|
||||
export function validate_block(json: unknown): Problems {
|
||||
if (!is_object(json)) return ["block must be an object"];
|
||||
const problems = validate_id(json.id, "id");
|
||||
|
||||
@@ -52,6 +52,8 @@ export interface ModListing {
|
||||
// where it's served from, relative to the server's root. named by its hash, so it never changes
|
||||
file: string;
|
||||
size: number;
|
||||
// it imports bworld/engine, see docs/modding/misc/engine.md. the confirm screen for other sites says so
|
||||
engine_access?: boolean;
|
||||
}
|
||||
|
||||
export class RecipeBook {
|
||||
|
||||
@@ -243,3 +243,7 @@ export function eyes_in_water(
|
||||
): boolean {
|
||||
return is_liquid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z));
|
||||
}
|
||||
|
||||
// what the engine calls through, so engine access mods can hook these like methods (module exports can't be
|
||||
// reassigned). see docs/modding/misc/engine.md
|
||||
export const physics = { move_body, back_off_from_edge, box_is_free, in_water, eyes_in_water };
|
||||
|
||||
@@ -3,11 +3,15 @@ import type { WorldgenContext } from "$/common/mod_api/worldgen.ts";
|
||||
import type { OreJson } from "$/common/mod_data.ts";
|
||||
import type { WorldgenSetup } from "./generation.ts";
|
||||
import { ModLoadError } from "./mod_loader.ts";
|
||||
import { loading_mod } from "./hooks.ts";
|
||||
|
||||
export async function load_worldgen(scripts: { mod: string; url: string }[], ores: OreJson[]): Promise<WorldgenSetup> {
|
||||
export async function load_worldgen(
|
||||
scripts: { mod: string; url: string; engine_access?: boolean }[],
|
||||
ores: OreJson[],
|
||||
): Promise<WorldgenSetup> {
|
||||
const setup: WorldgenSetup = { ores, features: [] };
|
||||
|
||||
for (const { mod, url } of scripts) {
|
||||
for (const { mod, url, engine_access } of scripts) {
|
||||
const ctx: WorldgenContext = {
|
||||
register_feature(id, generate) {
|
||||
if (!id.startsWith(`${mod}:`)) {
|
||||
@@ -26,11 +30,13 @@ export async function load_worldgen(scripts: { mod: string; url: string }[], ore
|
||||
},
|
||||
};
|
||||
|
||||
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 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);
|
||||
});
|
||||
}
|
||||
|
||||
return setup;
|
||||
|
||||
Reference in New Issue
Block a user