Files
bworld/common/bmod.ts
T
2026-10-12 17:56:47 -03:00

330 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// .bmod files: a built mod in one zip, what servers load from server_mods/ and send to players. see
// docs/modding/gettingstarted/modfiles.md. the same code reads them on the server and in the browser, so it only works on bytes
import { unzipSync, zipSync } from "fflate";
import type { ModelFileJson } from "./block_models.ts";
import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts";
import {
type BlockJson,
type EffectJson,
type EntityJson,
type EntityModelJson,
ID_PATTERN,
type ItemJson,
type ManifestJson,
type OreJson,
type RecipeJson,
type SpawnJson,
type TagJson,
validate_block,
validate_effect,
validate_entity,
validate_entity_model,
validate_item,
validate_manifest,
validate_model,
validate_ore,
validate_recipe,
validate_spawn,
validate_tag,
} from "./mod_data.ts";
import type { ModData } from "./mod_loader.ts";
import { type LootTableJson, validate_loot_table } from "./loot.ts";
import { type BiomeJson, validate_biome } from "./worldgen/biomes.ts";
import {
type BiomeSourceJson,
type DensityFunctionJson,
type NoiseJson,
type NoiseSettingsJson,
validate_biome_source,
validate_density_function,
validate_noise,
validate_noise_settings,
} from "./worldgen/data.ts";
import { type FeatureJson, validate_feature } from "./worldgen/features.ts";
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts";
export const BMOD_EXTENSION = ".bmod";
// what a .bmod can hold at most unzipped, so a small file can't unzip into gigabytes
const MAX_FILES = 4096;
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";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared"];
export interface Bmod {
manifest: ManifestJson;
data: ModData;
// bundled javascript, one module per side
scripts: Partial<Record<ScriptSide, 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
texture_json?: Map<string, TextureJson>;
credits?: string;
}
export class BmodError extends Error {
constructor(file: string, problems: string[]) {
super(`${file}: ${problems.join("; ")}`);
this.name = "BmodError";
}
}
// the zip's layout:
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip
// data.json every block, model, item, recipe, ore, entity, entity model, effect, tag, loot table and
// biome
// scripts/<side>.js
// textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one
// credits.md
export function write_bmod(bmod: Bmod): Uint8Array<ArrayBuffer> {
const text = (value: string) => new TextEncoder().encode(value);
const manifest: ManifestJson = { ...bmod.manifest, scripts: {} };
delete manifest.credits;
const files: Record<string, Uint8Array> = {};
for (const side of SCRIPT_SIDES) {
const code = bmod.scripts[side];
if (code !== undefined) {
files[`scripts/${side}.js`] = text(code);
manifest.scripts![side] = `scripts/${side}.js`;
}
}
if (Object.keys(manifest.scripts!).length === 0) delete manifest.scripts;
if (bmod.credits !== undefined) {
files["credits.md"] = text(bmod.credits);
manifest.credits = "credits.md";
}
for (const [id, png] of bmod.textures) {
files[`textures/${id.split(":")[1]}.png`] = png;
}
for (const [id, json] of bmod.texture_json ?? []) {
files[`textures/${id.split(":")[1]}.json`] = text(JSON.stringify(json));
}
files["manifest.json"] = text(JSON.stringify(manifest, null, "\t"));
files["data.json"] = text(JSON.stringify(bmod.data));
// sorted, so the order doesn't depend on how the files were collected
const sorted: Record<string, Uint8Array> = {};
for (const name of Object.keys(files).sort()) sorted[name] = files[name];
return zipSync(sorted, { mtime: FIXED_TIME, level: 9 }) as Uint8Array<ArrayBuffer>;
}
// opens and checks a .bmod. file is only for error messages. throws BmodError listing what's wrong
export function read_bmod(bytes: Uint8Array, file: string): Bmod {
let files: Record<string, Uint8Array>;
let count = 0;
let total = 0;
try {
files = unzipSync(bytes, {
filter(entry) {
count += 1;
total += entry.originalSize;
if (count > MAX_FILES || total > MAX_UNZIPPED_BYTES) {
throw new Error(`unzips to more than ${MAX_FILES} files or ${MAX_UNZIPPED_BYTES >> 20} MB`);
}
return !entry.name.endsWith("/");
},
});
} catch (e) {
throw new BmodError(file, [`isn't a readable .bmod: ${(e as Error).message}`]);
}
const problems: string[] = [];
const parse = (name: string): unknown => {
const content = files[name];
if (!content) {
problems.push(`${name} is missing`);
return undefined;
}
try {
return JSON.parse(new TextDecoder().decode(content));
} catch (e) {
problems.push(`${name} isn't valid json: ${(e as Error).message}`);
return undefined;
}
};
const text = (name: string) => files[name] && new TextDecoder().decode(files[name]);
const manifest = parse("manifest.json") as ManifestJson | undefined;
const raw_data = parse("data.json") as Partial<ModData> | undefined;
if (!manifest || !raw_data) throw new BmodError(file, problems);
for (const problem of validate_manifest(manifest, manifest.id)) problems.push(`manifest.json: ${problem}`);
if (problems.length > 0) throw new BmodError(file, problems);
const mod = manifest.id;
const data: ModData = {
blocks: checked(raw_data.blocks, "blocks", validate_block, problems) as BlockJson[],
models: checked(raw_data.models, "models", validate_model, problems) as ModelFileJson[],
items: checked(raw_data.items, "items", validate_item, problems) as ItemJson[],
recipes: checked(raw_data.recipes, "recipes", validate_recipe, problems) as RecipeJson[],
ores: checked(raw_data.ores, "ores", validate_ore, problems) as OreJson[],
spawns: checked(raw_data.spawns, "spawns", validate_spawn, problems) as SpawnJson[],
entities: checked(raw_data.entities, "entities", validate_entity, problems) as EntityJson[],
entity_models: checked(
raw_data.entity_models,
"entity_models",
validate_entity_model,
problems,
) as EntityModelJson[],
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
loot_tables: checked(raw_data.loot_tables, "loot_tables", validate_loot_table, problems) as LootTableJson[],
biomes: checked(raw_data.biomes, "biomes", validate_biome, problems) as BiomeJson[],
noises: checked(raw_data.noises, "noises", validate_noise, problems) as NoiseJson[],
density_functions: checked(
raw_data.density_functions,
"density_functions",
validate_density_function,
problems,
) as DensityFunctionJson[],
noise_settings: checked(
raw_data.noise_settings,
"noise_settings",
validate_noise_settings,
problems,
) as NoiseSettingsJson[],
biome_sources: checked(
raw_data.biome_sources,
"biome_sources",
validate_biome_source,
problems,
) as BiomeSourceJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
};
// a mod only registers ids in its own namespace
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models];
const worldgen = [
...data.noises!,
...data.density_functions!,
...data.noise_settings!,
...data.biome_sources!,
...data.features!,
];
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!, ...worldgen]) {
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
}
const scripts: Bmod["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;
}
}
// 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`);
}
// sizes are checked once it's known which textures are animated
const pngs = new Map<string, Uint8Array>();
for (const [name, content] of Object.entries(files)) {
const match = name.match(/^textures\/(.+)\.png$/);
if (!match) continue;
const id = `${mod}:${match[1]}`;
const size = png_size(content);
if (!ID_PATTERN.test(id)) {
problems.push(`${name}: texture names must be a-z, 0-9 and _`);
} else if (!size) {
problems.push(`${name}: isn't a png`);
} else {
pngs.set(id, content);
}
}
const texture_json = new Map<string, TextureJson>();
for (const name of Object.keys(files)) {
const match = name.match(/^textures\/(.+)\.json$/);
if (!match) continue;
const id = `${mod}:${match[1]}`;
const png = pngs.get(id);
if (!png) {
problems.push(`${name}: there's no textures/${match[1]}.png for it to go with`);
continue;
}
const json = parse(name);
if (json === undefined) continue;
const json_problems = validate_texture_json(json, png_size(png)!);
for (const problem of json_problems) problems.push(`${name}: ${problem}`);
if (json_problems.length === 0) texture_json.set(id, json as TextureJson);
}
const textures = new Map<string, Uint8Array>();
for (const [id, png] of pngs) {
const problem = texture_size_problem(png_size(png)!, texture_json.get(id));
if (problem) {
problems.push(`textures/${id.split(":")[1]}.png: ${problem}`);
} else {
textures.set(id, png);
}
}
if (problems.length > 0) throw new BmodError(file, problems);
return { manifest, data, scripts, textures, texture_json, credits };
}
// the same mod without its server and worldgen scripts and the terrain's data, what players get. the server sends
// them the world
export function client_copy(bmod: Bmod): Bmod {
const scripts = { ...bmod.scripts };
delete scripts.server;
delete scripts.worldgen;
const { noises: _n, density_functions: _d, noise_settings: _s, biome_sources: _b, features: _f, ...data } =
bmod.data;
return { ...bmod, scripts, data };
}
function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] {
if (list === undefined) return [];
if (!Array.isArray(list)) {
problems.push(`data.json: ${name} must be a list`);
return [];
}
list.forEach((entry, i) => {
for (const problem of validate(entry)) problems.push(`data.json: ${name}[${i}]: ${problem}`);
});
return list;
}
// textures can be any size up to MAX_TEXTURE_SIZE, like 64×32 for an entity. blocks and items stretch theirs to fit.
// for an animated one (json is its .json) that's each frame's size
export function texture_size_problem(size: { width: number; height: number }, json?: TextureJson): string | undefined {
const { width, height } = size;
const animation = json && texture_animation(json, size);
if (animation) {
const { frame_width, frame_height } = animation;
if (width > MAX_ANIMATED_TEXTURE_SIZE || height > MAX_ANIMATED_TEXTURE_SIZE) {
return `is ${width}×${height}, animated textures can be at most ${MAX_ANIMATED_TEXTURE_SIZE}×${MAX_ANIMATED_TEXTURE_SIZE}`;
}
if (frame_width > MAX_TEXTURE_SIZE || frame_height > MAX_TEXTURE_SIZE) {
return `has ${frame_width}×${frame_height} frames, textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`;
}
return undefined;
}
if (width < 1 || height < 1 || width > MAX_TEXTURE_SIZE || height > MAX_TEXTURE_SIZE) {
return `is ${width}×${height}, textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`;
}
}
// reads the size out of the png header instead of decoding the image
export function png_size(bytes: Uint8Array): { width: number; height: number } | undefined {
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
if (bytes.length < 24 || !signature.every((b, i) => bytes[i] === b)) return undefined;
const view = new DataView(bytes.buffer, bytes.byteOffset);
return { width: view.getUint32(16), height: view.getUint32(20) };
}