Files
bworld/common/mod.ts
T
2026-11-15 19:54:08 -03:00

371 lines
14 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
// .cubi 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,
type FluidJson,
type ItemJson,
type ManifestJson,
type OreJson,
type RecipeJson,
type SpawnJson,
type TagJson,
validate_block,
validate_effect,
validate_entity,
validate_entity_model,
validate_fluid,
validate_item,
validate_manifest,
validate_model,
validate_ore,
validate_recipe,
validate_spawn,
validate_tag,
} from "./mod_data.ts";
import { ID_PATTERN, is_object } from "./schema.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 DimensionJson,
type NoiseJson,
type NoiseSettingsJson,
validate_biome_source,
validate_density_function,
validate_dimension,
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";
import { type Schematic, validate_schematic } from "./schematic.ts";
export const MOD_EXTENSION = ".cubi";
// what a .cubi 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 interface Mod {
manifest: ManifestJson;
data: ModData;
// 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
texture_json?: Map<string, TextureJson>;
credits?: string;
}
export class ModError extends Error {
constructor(file: string, problems: string[]) {
super(`${file}: ${problems.join("; ")}`);
this.name = "ModError";
}
}
// the zip's layout:
// 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, biome and schematic, and the mod's config
// 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 };
delete manifest.main;
delete manifest.credits;
const files: Record<string, Uint8Array> = {};
if (mod.script !== undefined) {
files["script.js"] = text(mod.script);
manifest.main = "script.js";
}
if (mod.credits !== undefined) {
files["credits.md"] = text(mod.credits);
manifest.credits = "credits.md";
}
for (const [id, png] of mod.textures) {
files[`textures/${id.split(":")[1]}.png`] = png;
}
for (const [id, json] of mod.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(mod.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>;
}
// only a .cubi's manifest, checked, without unzipping the rest. for listing mods, read_mod checks the whole thing
export function read_manifest(bytes: Uint8Array, file: string): ManifestJson {
let manifest: ManifestJson;
try {
const files = unzipSync(bytes, { filter: (entry) => entry.name === "manifest.json" });
manifest = JSON.parse(new TextDecoder().decode(files["manifest.json"]));
} catch (e) {
throw new ModError(file, [`isn't a readable .cubi: ${(e as Error).message}`]);
}
const problems = validate_manifest(manifest, manifest?.id);
if (problems.length > 0) throw new ModError(file, problems.map((problem) => `manifest.json: ${problem}`));
return manifest;
}
// opens and checks a .cubi. file is only for error messages. throws ModError listing what's wrong
export function read_mod(bytes: Uint8Array, file: string): Mod {
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 ModError(file, [`isn't a readable .cubi: ${(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 ModError(file, problems);
for (const problem of validate_manifest(manifest, manifest.id)) problems.push(`manifest.json: ${problem}`);
if (problems.length > 0) throw new ModError(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[],
fluids: checked(raw_data.fluids, "fluids", validate_fluid, problems) as FluidJson[],
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[],
dimensions: checked(raw_data.dimensions, "dimensions", validate_dimension, problems) as DimensionJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
schematics: checked(raw_data.schematics, "schematics", validate_schematic, problems) as Schematic[],
config: raw_data.config,
};
if (raw_data.config !== undefined && !is_object(raw_data.config)) {
problems.push("data.json: config must be an object");
}
// a mod only registers ids in its own namespace
const registered = [
...data.blocks,
...data.models,
...data.items,
...data.entities,
...data.entity_models,
...data.effects,
...data.fluids,
];
const worldgen = [
...data.noises!,
...data.density_functions!,
...data.noise_settings!,
...data.biome_sources!,
...data.dimensions!,
...data.features!,
...data.schematics!,
];
for (const { id } of [...registered, ...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 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 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) {
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 ModError(file, problems);
return { manifest, data, script, textures, texture_json, credits };
}
// the same mod without the terrain's data, its schematics 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 {
noises: _n,
density_functions: _d,
noise_settings: _s,
biome_sources: _b,
dimensions: _dim,
features: _f,
schematics: _sc,
config: _c,
...data
} = mod.data;
return { ...mod, 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) };
}
// a mod's bundled script as a url import() takes, for realms without file access
export function data_url(code: string) {
const bytes = new TextEncoder().encode(code);
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return `data:application/javascript;base64,${btoa(binary)}`;
}