Fluid data
This commit is contained in:
+14
-7
@@ -8,8 +8,9 @@ import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/e
|
||||
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
|
||||
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
||||
import { display_name, get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import { get_state_value, set_state_value, shared_items_api } from "$/common/utils.ts";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import { FluidRules } from "$/common/fluids.ts";
|
||||
import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "$/common/block_shapes.ts";
|
||||
import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
@@ -90,6 +91,8 @@ const rules_world: SharedWorld = {
|
||||
|
||||
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
|
||||
export let block_rules = new BlockRules(run_mod, rules_world.get_block);
|
||||
// the fluids' rules from shared scripts, the same as the server's, see common/fluids.ts
|
||||
export let fluid_rules = new FluidRules(run_mod);
|
||||
// whether shared scripts are being set up, the only time they can register rules
|
||||
let rules_setup = false;
|
||||
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
|
||||
@@ -163,6 +166,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
||||
|
||||
// every mod's shared rules first, so client scripts can count on any mod's being there
|
||||
block_rules = new BlockRules(run_mod, rules_world.get_block);
|
||||
fluid_rules = new FluidRules(run_mod);
|
||||
rules_setup = true;
|
||||
for (const [i, bmod] of bmods.entries()) {
|
||||
const code = bmod.scripts.shared;
|
||||
@@ -221,6 +225,13 @@ function shared_context(listing: ModListing): SharedContext {
|
||||
side: "client",
|
||||
tags: tag_api(),
|
||||
blocks: blocks_api(mod),
|
||||
items: shared_items_api(mod),
|
||||
fluids: {
|
||||
register(id, rules) {
|
||||
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
||||
fluid_rules.register(mod, id, rules);
|
||||
},
|
||||
},
|
||||
world: rules_world,
|
||||
components: {
|
||||
register_block(id, rules) {
|
||||
@@ -329,20 +340,16 @@ function client_context(listing: ModListing): ClientContext {
|
||||
},
|
||||
},
|
||||
items: {
|
||||
...shared_items_api(mod),
|
||||
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
|
||||
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
|
||||
name: (id) => (known_item(id), display_name(id)),
|
||||
mod(id) {
|
||||
known_item(id);
|
||||
const namespace = id.split(":")[0];
|
||||
return mod_names.get(namespace) ?? namespace;
|
||||
},
|
||||
components: (id) => (known_item(id),
|
||||
structuredClone(
|
||||
EverythingRegistry.get<ItemRegistry>("items", id)?.components ?? {},
|
||||
)),
|
||||
},
|
||||
blocks: blocks_api(mod),
|
||||
fluids: fluid_rules.api(),
|
||||
loot: {
|
||||
table: (id) => structuredClone(EverythingRegistry.get<LootTableJson>("loot_tables", id)),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// 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 and
|
||||
// color 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";
|
||||
import { EverythingRegistry } from "./everything_registry.ts";
|
||||
import type { FluidJson } from "./mod_data.ts";
|
||||
import { color as color_schema } from "./schema.ts";
|
||||
import { name_from_id, same_data } from "./utils.ts";
|
||||
|
||||
export class FluidRules {
|
||||
#rules = new Map<string, { mod: string; rules: Rules }>();
|
||||
|
||||
// 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) {}
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
name(fluid: FluidVariant): string {
|
||||
const json = known_fluid(fluid.id);
|
||||
const name = this.#ask(fluid, "name", "a name", (value) => typeof value === "string" && value.length > 0);
|
||||
return name ?? json.name ?? name_from_id(fluid.id);
|
||||
}
|
||||
|
||||
color(fluid: FluidVariant): string {
|
||||
const json = known_fluid(fluid.id);
|
||||
const valid = (value: unknown) => color_schema.safeParse(value).success;
|
||||
return this.#ask(fluid, "color", 'a color like "#c42d39"', valid) ?? json.color;
|
||||
}
|
||||
|
||||
// ctx.fluids for server and client scripts
|
||||
api(): FluidApi {
|
||||
return {
|
||||
exists: (id) => EverythingRegistry.get("fluids", id) !== undefined,
|
||||
name: (fluid) => this.name(fluid),
|
||||
color: (fluid) => this.color(fluid),
|
||||
same: (a, b) => a.id === b.id && same_data(a.data, b.data),
|
||||
};
|
||||
}
|
||||
|
||||
// what the fluid's rule says, or undefined when it has none, says nothing, or says something that isn't one
|
||||
#ask(fluid: FluidVariant, rule: "name" | "color", wanted: string, valid: (value: unknown) => boolean) {
|
||||
const entry = this.#rules.get(fluid.id);
|
||||
const fn = entry?.rules[rule];
|
||||
if (!entry || !fn) return undefined;
|
||||
return this.run(entry.mod, `the ${rule} rule of ${fluid.id}`, () => {
|
||||
const value = fn.call(entry.rules, fluid.data);
|
||||
if (value !== undefined && !valid(value)) throw new Error(`gave ${JSON.stringify(value)}, not ${wanted}`);
|
||||
return value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function known_fluid(id: string): FluidJson {
|
||||
const json = EverythingRegistry.get<FluidJson>("fluids", id);
|
||||
if (!json) throw new Error(`unknown fluid ${id}`);
|
||||
return json;
|
||||
}
|
||||
@@ -2,10 +2,21 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what client scripts get, see docs/modding/gui/index.md
|
||||
import type { Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi } from "./shared.ts";
|
||||
import type { FluidApi, Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi } from "./shared.ts";
|
||||
import type { LootTableJson } from "../loot.ts";
|
||||
|
||||
export type { Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi, TagRegistry } from "./shared.ts";
|
||||
export type {
|
||||
FluidApi,
|
||||
FluidVariant,
|
||||
Id,
|
||||
ItemStack,
|
||||
KeyCode,
|
||||
ModInfo,
|
||||
Position,
|
||||
Season,
|
||||
TagApi,
|
||||
TagRegistry,
|
||||
} from "./shared.ts";
|
||||
|
||||
export interface ClientContext {
|
||||
mod: ModInfo;
|
||||
@@ -59,6 +70,8 @@ export interface ClientContext {
|
||||
// whether it's solid like stone, like the server's ctx.blocks.solid
|
||||
solid(id: Id): boolean;
|
||||
};
|
||||
// every fluid, named and colored by its rules, see docs/modding/resources/fluids.md
|
||||
fluids: FluidApi;
|
||||
// the mods' loot table files (see docs/modding/resources/loot_tables.md), to show what they give. tables server
|
||||
// scripts make with ctx.loot.register_table aren't here
|
||||
loot: {
|
||||
|
||||
@@ -2,13 +2,25 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what server scripts get, see docs/modding/
|
||||
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position, Season, TagApi } from "./shared.ts";
|
||||
import type { EventSignal, Face, FluidApi, Id, ItemStack, ModInfo, Position, Season, TagApi } from "./shared.ts";
|
||||
import type { ArgumentType, CommandNode } from "../commands.ts";
|
||||
import type { LootTableJson } from "../loot.ts";
|
||||
|
||||
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
|
||||
|
||||
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position, Season, TagApi, TagRegistry } from "./shared.ts";
|
||||
export type {
|
||||
EventSignal,
|
||||
Face,
|
||||
FluidApi,
|
||||
FluidVariant,
|
||||
Id,
|
||||
ItemStack,
|
||||
ModInfo,
|
||||
Position,
|
||||
Season,
|
||||
TagApi,
|
||||
TagRegistry,
|
||||
} from "./shared.ts";
|
||||
|
||||
export interface ServerContext {
|
||||
mod: ModInfo;
|
||||
@@ -25,6 +37,8 @@ export interface ServerContext {
|
||||
containers: ContainerApi;
|
||||
items: ItemApi;
|
||||
blocks: BlockApi;
|
||||
// every fluid, named and colored by its rules, see docs/modding/resources/fluids.md
|
||||
fluids: FluidApi;
|
||||
recipes: RecipeApi;
|
||||
tags: TagApi;
|
||||
loot: LootApi;
|
||||
|
||||
@@ -16,6 +16,35 @@ export interface ItemStack {
|
||||
data?: unknown;
|
||||
}
|
||||
|
||||
// a fluid with its data, like the juice in a bottle, see docs/modding/resources/fluids.md. it has no amount: whatever
|
||||
// holds fluid keeps that beside it, like a tank's { fluid, amount }
|
||||
export interface FluidVariant {
|
||||
readonly id: Id;
|
||||
// any json value, which tells fluids of one id apart, like which fruit a juice is from
|
||||
readonly data?: unknown;
|
||||
}
|
||||
|
||||
// ctx.fluids in server and client scripts: every fluid any mod defines, the same on the server and every client
|
||||
export interface FluidApi {
|
||||
exists(id: Id): boolean;
|
||||
// what players see, from the fluid's rules for its data, or else its json
|
||||
name(fluid: FluidVariant): string;
|
||||
// a color like "#c42d39", from the fluid's rules for its data, or else its json
|
||||
color(fluid: FluidVariant): string;
|
||||
// whether they're one fluid: the same id, and the same data whatever order its keys are in. no data is the same as
|
||||
// {}, so a fluid whose data was emptied is the plain fluid again
|
||||
same(a: FluidVariant, b: FluidVariant): boolean;
|
||||
}
|
||||
|
||||
// what a fluid's data makes it, registered by a shared script, 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 {
|
||||
name?(data: unknown): string | undefined;
|
||||
// a color like "#c42d39"
|
||||
color?(data: unknown): string | undefined;
|
||||
}
|
||||
|
||||
// the registries tags are for, see docs/modding/resources/tags.md
|
||||
export type TagRegistry = "blocks" | "items" | "entities" | "biomes";
|
||||
|
||||
@@ -75,6 +104,19 @@ export interface SharedContext {
|
||||
// whether it's solid like stone, like the server's ctx.blocks.solid
|
||||
solid(id: Id): boolean;
|
||||
};
|
||||
// every item any mod registered, like the client's ctx.items, for rules that read one, like a juice named after the
|
||||
// fruit it's from
|
||||
readonly items: {
|
||||
exists(id: Id): boolean;
|
||||
// what players see, like "Cooked Rice"
|
||||
name(id: Id): string;
|
||||
// the components its json lists and their params, a copy
|
||||
components(id: Id): Record<Id, unknown>;
|
||||
};
|
||||
readonly fluids: {
|
||||
// the rules of one of the mod's fluids, which the server and every client name and color it by
|
||||
register(id: Id, rules: FluidRules): void;
|
||||
};
|
||||
readonly components: {
|
||||
// the rules of a block component, the same id the server script registers the rest of it under
|
||||
// deno-lint-ignore no-explicit-any
|
||||
|
||||
+48
-4
@@ -6,8 +6,10 @@ import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from ".
|
||||
import { block_item_texture, cube_face_texture } from "./block_models.ts";
|
||||
import { FULL_SHAPE, type Shape } from "./block_shapes.ts";
|
||||
import type { ItemStack } from "./inventory.ts";
|
||||
import type { SharedContext } from "./mod_api/shared.ts";
|
||||
import type { FluidInCell } from "./physics.ts";
|
||||
import { list_matches } from "./tags.ts";
|
||||
import { is_object } from "./schema.ts";
|
||||
|
||||
export function point_inside_rec(
|
||||
point_x: number,
|
||||
@@ -80,14 +82,56 @@ export function item_texture(
|
||||
return typeof info.texture_id === "function" ? info.texture_id(item) : info.texture_id;
|
||||
}
|
||||
|
||||
// what players see an item called: its name, or one made from its id, so bworld:iron_ingot is "Iron Ingot"
|
||||
// what players see an item called: its name, or one made from its id
|
||||
export function display_name(item_id: string): string {
|
||||
const name = EverythingRegistry.get<ItemRegistry>("items", item_id)?.name;
|
||||
if (name) return name;
|
||||
const words = (item_id.split(":")[1] ?? item_id).split("_").filter((word) => word.length > 0);
|
||||
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
|
||||
export function shared_items_api(mod: string): SharedContext["items"] {
|
||||
const known = (id: string) => {
|
||||
const item = EverythingRegistry.get<ItemRegistry>("items", id);
|
||||
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
|
||||
return item;
|
||||
};
|
||||
return {
|
||||
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
|
||||
name: (id) => (known(id), display_name(id)),
|
||||
components: (id) => structuredClone(known(id).components ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
// a name for what didn't give one, so bworld:iron_ingot is "Iron Ingot"
|
||||
export function name_from_id(id: string): string {
|
||||
const words = (id.split(":")[1] ?? id).split("_").filter((word) => word.length > 0);
|
||||
return words.map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
|
||||
}
|
||||
|
||||
// whether two stacks' or fluids' data are the same, whatever order their keys are in. no data is the same as {}, and a
|
||||
// key set to undefined as one that isn't there, the way they'd be once saved or sent
|
||||
export function same_data(a: unknown, b: unknown): boolean {
|
||||
return (is_empty_data(a) && is_empty_data(b)) || same_json(a, b);
|
||||
}
|
||||
|
||||
function is_empty_data(value: unknown) {
|
||||
return value === undefined || (is_object(value) && defined_keys(value).length === 0);
|
||||
}
|
||||
|
||||
function same_json(a: unknown, b: unknown): boolean {
|
||||
if (a === b) return true;
|
||||
if (Array.isArray(a) || Array.isArray(b)) {
|
||||
return Array.isArray(a) && Array.isArray(b) && a.length === b.length &&
|
||||
a.every((value, i) => same_json(value, b[i]));
|
||||
}
|
||||
if (!is_object(a) || !is_object(b)) return false;
|
||||
const keys = defined_keys(a);
|
||||
return keys.length === defined_keys(b).length && keys.every((key) => same_json(a[key], b[key]));
|
||||
}
|
||||
|
||||
function defined_keys(value: Record<string, unknown>) {
|
||||
return Object.keys(value).filter((key) => value[key] !== undefined);
|
||||
}
|
||||
|
||||
export function get_state_value(value: number, block_info: BlockRegistry, name: string) {
|
||||
if (!block_info.states) {
|
||||
return undefined;
|
||||
|
||||
@@ -96,7 +96,7 @@ Shared scripts hold a block component's rules, the code Minecraft runs on both s
|
||||
(`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it
|
||||
changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server
|
||||
script registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the
|
||||
same id.
|
||||
same id. They also hold [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data.
|
||||
|
||||
On the server they run on the real world. On a client they run on what that client shows, when its player places, breaks
|
||||
or right clicks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and
|
||||
|
||||
@@ -165,6 +165,7 @@ ctx.items.mod(id); // the name of the mod that added it
|
||||
ctx.items.components(id); // its components and their params, like the server's, to show what they mean
|
||||
ctx.blocks.exists(id);
|
||||
ctx.blocks.components(id); // the same for a block, like what a crab pot catches with each bait
|
||||
ctx.fluids.name(fluid); // and color, exists and same, see ../resources/fluids.md#using-fluids
|
||||
ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server scripts make aren't here
|
||||
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
|
||||
ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings
|
||||
|
||||
@@ -26,3 +26,65 @@ here has no block, so it can't be placed.
|
||||
| `id` | yes | The fluid's id, in the mod's [namespace](../concepts/registries.md#identifiers). |
|
||||
| `name` | no | What players see. `copper_tools:maple_syrup` is "Maple Syrup" when not set, like an item's. |
|
||||
| `color` | yes | Its color, like `"#a0522d"`, for whatever shows it. |
|
||||
|
||||
## Fluids With Data
|
||||
|
||||
A fluid with data is a `FluidVariant`, `{ id, data? }`, like Fabric's. The data is any JSON value, and tells fluids of
|
||||
one id apart: `copper_tools:syrup` can be maple syrup or birch syrup,
|
||||
`{ "id": "copper_tools:syrup", "data": { "tree": "bworld:birch_log" } }`. A variant has no amount. Whatever holds fluid
|
||||
keeps the amount next to it, like a tank's `{ fluid, amount }`.
|
||||
|
||||
Two variants are the same fluid when their ids are the same and so is their data, whatever order its keys are in. No
|
||||
data is the same as `{}`, so a fluid whose data was emptied is the plain fluid again. Maple and birch syrup never share
|
||||
a tank.
|
||||
|
||||
## Rules
|
||||
|
||||
A fluid's name and color can depend on its data. The mod's [shared script](../concepts/sides.md#shared-scripts) gives
|
||||
one of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`:
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
|
||||
interface SyrupData {
|
||||
tree?: string;
|
||||
}
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.fluids.register("copper_tools:syrup", {
|
||||
name(data) {
|
||||
const { tree } = (data ?? {}) as SyrupData;
|
||||
return tree ? `${ctx.items.name(tree)} Syrup` : undefined;
|
||||
},
|
||||
color(data) {
|
||||
const { tree } = (data ?? {}) as SyrupData;
|
||||
return tree === "bworld:birch_log" ? "#d9a441" : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
| Rule | Returns |
|
||||
| ------------- | -------------------------------------------------------- |
|
||||
| `name(data)` | What players see, or `undefined` for the JSON's name. |
|
||||
| `color(data)` | A color like `"#d9a441"`, or `undefined` for the JSON's. |
|
||||
|
||||
`data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something
|
||||
that isn't a name or a color, is logged and the JSON's is used. A fluid has one set of rules, from its own mod, and they
|
||||
can only be registered during `setup`.
|
||||
|
||||
The rules are in the shared script because both sides need them: the server for tooltips, and clients to draw the fluid.
|
||||
Shared scripts have `ctx.items.exists(id)`, `ctx.items.name(id)` and `ctx.items.components(id)` for rules that read an
|
||||
item, like syrup named after its tree.
|
||||
|
||||
## Using Fluids
|
||||
|
||||
Server and client scripts have `ctx.fluids`, which goes through the rules:
|
||||
|
||||
```ts
|
||||
const birch = { id: "copper_tools:syrup", data: { tree: "bworld:birch_log" } };
|
||||
ctx.fluids.exists("copper_tools:syrup"); // true
|
||||
ctx.fluids.name(birch); // "Birch Log Syrup"
|
||||
ctx.fluids.color(birch); // "#d9a441"
|
||||
ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is different
|
||||
```
|
||||
|
||||
@@ -5,13 +5,21 @@
|
||||
// see docs/modding/. parts not built yet throw when used, saying so
|
||||
import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
|
||||
import { block_states, fluid_block, get_state_value, is_waterlogged, set_state_value } from "$/common/utils.ts";
|
||||
import {
|
||||
block_states,
|
||||
fluid_block,
|
||||
get_state_value,
|
||||
is_waterlogged,
|
||||
set_state_value,
|
||||
shared_items_api,
|
||||
} from "$/common/utils.ts";
|
||||
import { LootTables } from "./loot.ts";
|
||||
import { collision_shape_at, covers_face, is_solid, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
|
||||
import { AIR, CHUNK_SIZE, faces, ID_MASK } from "$/common/constants.ts";
|
||||
import { physics } from "$/common/physics.ts";
|
||||
import { clock } from "$/common/time.ts";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import { FluidRules } from "$/common/fluids.ts";
|
||||
import type { SharedContext } from "$/common/mod_api/shared.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
import { loading_mod } from "$/common/hooks.ts";
|
||||
@@ -151,6 +159,8 @@ export class ModRuntime {
|
||||
(x, y, z) => this.game.world.get_block_id(x, y, z),
|
||||
(x, y, z, from) => this.#neighbor_changed(x, y, z, from),
|
||||
);
|
||||
// the fluids' rules from shared scripts, see common/fluids.ts
|
||||
fluid_rules = new FluidRules(run_guarded);
|
||||
item_components = new Map<string, { mod: string; component: ItemComponent }>();
|
||||
effect_components = new Map<string, { mod: string; component: EffectComponent }>();
|
||||
// every command, the engine's and mods', see common/commands.ts
|
||||
@@ -268,6 +278,13 @@ export class ModRuntime {
|
||||
side: "server",
|
||||
tags: tag_api(),
|
||||
blocks,
|
||||
items: shared_items_api(mod),
|
||||
fluids: {
|
||||
register: (id, rules) => {
|
||||
if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup");
|
||||
this.fluid_rules.register(mod, id, rules);
|
||||
},
|
||||
},
|
||||
world: {
|
||||
get_block: world.get_block,
|
||||
get_state: world.get_state,
|
||||
@@ -926,6 +943,7 @@ export class ModRuntime {
|
||||
return is_solid(block);
|
||||
},
|
||||
},
|
||||
fluids: this.fluid_rules.api(),
|
||||
recipes: {
|
||||
furnace_result: (input) => {
|
||||
const recipe = game().recipes.furnace.get(input);
|
||||
|
||||
+100
-13
@@ -4,28 +4,43 @@
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import type { FluidJson } from "$/common/mod_data.ts";
|
||||
import type { ModListing } from "$/common/mod_loader.ts";
|
||||
import type { FluidApi } from "$/common/mod_api/shared.ts";
|
||||
import { read_bmod } from "$/common/bmod.ts";
|
||||
import { register_mod_data } from "$/common/mod_loader.ts";
|
||||
import { fluid_rules, load_client_mods } from "$/client/mods.ts";
|
||||
import { load_and_check } from "$/tools/check_mods.ts";
|
||||
import { pack_mod } from "$/tools/pack_mod.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
|
||||
// a mod with only a manifest and the given fluids/ files, by file name
|
||||
function fluid_mod(fluids: Record<string, unknown>) {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
|
||||
Deno.mkdirSync(`${dir}/testfluids/fluids`, { recursive: true });
|
||||
Deno.writeTextFileSync(
|
||||
`${dir}/testfluids/manifest.json`,
|
||||
JSON.stringify({ format_version: 1, id: "testfluids", name: "Test Fluids", version: "1.0.0" }),
|
||||
);
|
||||
for (const [file, fluid] of Object.entries(fluids)) {
|
||||
Deno.writeTextFileSync(`${dir}/testfluids/fluids/${file}`, JSON.stringify({ format_version: 1, fluid }));
|
||||
// testfluids: a manifest, the given fluids/ files by file name, and maybe a shared script and an item for it to read
|
||||
function fluid_mod(dir: string, fluids: Record<string, unknown>, shared_script?: string) {
|
||||
const mod = `${dir}/testfluids`;
|
||||
const write = (path: string, json: unknown) => {
|
||||
Deno.mkdirSync(`${mod}/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
|
||||
Deno.writeTextFileSync(`${mod}/${path}`, typeof json === "string" ? json : JSON.stringify(json));
|
||||
};
|
||||
write("manifest.json", {
|
||||
format_version: 1,
|
||||
id: "testfluids",
|
||||
name: "Test Fluids",
|
||||
version: "1.0.0",
|
||||
...(shared_script && { scripts: { shared: "scripts/shared.ts" } }),
|
||||
});
|
||||
for (const [file, fluid] of Object.entries(fluids)) write(`fluids/${file}`, { format_version: 1, fluid });
|
||||
if (shared_script) {
|
||||
write("scripts/shared.ts", shared_script);
|
||||
write("items/maple.json", {
|
||||
format_version: 1,
|
||||
item: { id: "testfluids:maple", texture: "engine:missing", name: "Sugar Maple" },
|
||||
});
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
Deno.test("a mod's fluids/ file registers a fluid, packed into its .bmod", async () => {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
|
||||
const syrup = { id: "testfluids:syrup", name: "Maple Syrup", color: "#a0522d" };
|
||||
const dir = fluid_mod({ "syrup.json": syrup });
|
||||
fluid_mod(dir, { "syrup.json": syrup });
|
||||
const mods = load_and_check(dir);
|
||||
assertEquals(mods[0].report.errors, []);
|
||||
const bmod = read_bmod(await pack_mod(mods[0]), "testfluids.bmod");
|
||||
@@ -36,8 +51,80 @@ Deno.test("a mod's fluids/ file registers a fluid, packed into its .bmod", async
|
||||
});
|
||||
|
||||
Deno.test("a fluid with a bad color fails loading", () => {
|
||||
const dir = fluid_mod({ "syrup.json": { id: "testfluids:syrup", color: "brown" } });
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
|
||||
fluid_mod(dir, { "syrup.json": { id: "testfluids:syrup", color: "brown" } });
|
||||
const errors = load_and_check(dir)[0].report.errors;
|
||||
assert(errors.some((e) => e.startsWith("fluids/syrup.json:") && e.includes("color")), errors.join("\n"));
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
// syrup is named after the tree in its data and has the color its data says, sap has no rules
|
||||
const RULES = `
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.fluids.register("testfluids:syrup", {
|
||||
name: (data: any) => data?.tree && ctx.items.name(data.tree) + " Syrup",
|
||||
color: (data: any) => data?.color,
|
||||
});
|
||||
}
|
||||
`;
|
||||
const FLUIDS = {
|
||||
"syrup.json": { id: "testfluids:syrup", name: "Syrup", color: "#a0522d" },
|
||||
"sap.json": { id: "testfluids:tree_sap", color: "#e8d9a0" },
|
||||
};
|
||||
|
||||
// what the server's and a client's ctx.fluids say about the fluids above
|
||||
async function both_sides(ask: (fluids: FluidApi) => unknown) {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
fluid_mod(dir, FLUIDS, RULES);
|
||||
const { game } = await test_game(dir);
|
||||
const server = ask(game.mods.fluid_rules.api());
|
||||
|
||||
const mod = load_and_check(dir).find((m) => m.id === "testfluids")!;
|
||||
const bmod = read_bmod(await pack_mod(mod), "testfluids.bmod");
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const listing: ModListing = { id: "testfluids", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
|
||||
EverythingRegistry.clear();
|
||||
await load_client_mods([listing], [bmod]);
|
||||
return { server, client: ask(fluid_rules.api()) };
|
||||
}
|
||||
|
||||
Deno.test("a fluid's rules name and color it by its data, the same on the server and clients", async () => {
|
||||
const { server, client } = await both_sides((fluids) => [
|
||||
[
|
||||
fluids.name({ id: "testfluids:syrup", data: { tree: "testfluids:maple" } }),
|
||||
fluids.color({
|
||||
id: "testfluids:syrup",
|
||||
data: { color: "#c87533" },
|
||||
}),
|
||||
],
|
||||
// the rules say nothing, or something that isn't a color, so the json's are used
|
||||
[fluids.name({ id: "testfluids:syrup" }), fluids.color({ id: "testfluids:syrup", data: { color: "brown" } })],
|
||||
// no rules, and no name in its json
|
||||
[
|
||||
fluids.name({ id: "testfluids:tree_sap" }),
|
||||
fluids.color({ id: "testfluids:tree_sap", data: { color: "#000000" } }),
|
||||
],
|
||||
]);
|
||||
assertEquals(server, [["Sugar Maple Syrup", "#c87533"], ["Syrup", "#a0522d"], ["Tree Sap", "#e8d9a0"]]);
|
||||
assertEquals(client, server);
|
||||
});
|
||||
|
||||
Deno.test("fluids are the same when their ids and data are, whatever order the data's keys are in", async () => {
|
||||
const { server, client } = await both_sides((fluids) => {
|
||||
const syrup = (data?: unknown) => ({ id: "testfluids:syrup", data });
|
||||
return [
|
||||
fluids.same(
|
||||
syrup({ tree: "testfluids:maple", grade: "a" }),
|
||||
syrup({ grade: "a", tree: "testfluids:maple" }),
|
||||
),
|
||||
fluids.same(syrup({}), syrup()),
|
||||
fluids.same(syrup({ tree: "testfluids:maple" }), syrup({ tree: "testfluids:birch" })),
|
||||
fluids.same(syrup({ tree: "testfluids:maple" }), syrup()),
|
||||
fluids.same(syrup(), { id: "testfluids:tree_sap" }),
|
||||
];
|
||||
});
|
||||
assertEquals(server, [true, true, false, false, false]);
|
||||
assertEquals(client, server);
|
||||
});
|
||||
|
||||
+4
-1
@@ -16,7 +16,7 @@ import type { SavedChunk, SavedChunks, WorldSave } from "$/server/game/saves.ts"
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import { collision_shape_at, covers_face, is_solid } from "$/common/block_shapes.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
import { get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import { get_state_value, set_state_value, shared_items_api } from "$/common/utils.ts";
|
||||
import type { Face, SharedWorld } from "$/common/mod_api/shared.ts";
|
||||
import { setup as setup_shared } from "$/mods/bworld/scripts/shared.ts";
|
||||
|
||||
@@ -259,6 +259,9 @@ export function client_of(game: GameServer, area: Area) {
|
||||
components: (id) => structuredClone(info(id)!.components ?? {}),
|
||||
solid: (id) => id !== AIR_ID && is_solid(info(id)!),
|
||||
},
|
||||
items: shared_items_api("bworld"),
|
||||
// only its blocks are looked at here
|
||||
fluids: { register() {} },
|
||||
world,
|
||||
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user