Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c955d8d143 | ||
|
|
a28e0b9abb | ||
|
|
233c518def | ||
|
|
08df7f1b6b | ||
|
|
feb1ddd1f7 | ||
|
|
583cce88c1 | ||
|
|
436f68ce33 | ||
|
|
26b59a1899 | ||
|
|
fc27771a92 | ||
|
|
17d83acfc8 | ||
|
|
0cfa4d9b4a | ||
|
|
bcca8fa4a5 | ||
|
|
4fad43d9cc |
@@ -4,10 +4,10 @@ A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics
|
||||
redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as
|
||||
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||
|
||||
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5,
|
||||
R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a hand crank),
|
||||
Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come from reading
|
||||
`ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed`, `rotating`, `fluid` and
|
||||
items), R4, R5, R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a
|
||||
hand crank), Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come
|
||||
from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -248,9 +248,9 @@ draws `rotating` and `transformed` instances of its block's model or of any mode
|
||||
variant. A visual that has to move on the CPU (a crank easing in, a press head) gets `on_frame`, like `DynamicVisual`.
|
||||
Visuals are kept per chunk, and only the ones in chunks in view get `on_frame`.
|
||||
|
||||
**R3. Instanced drawing** (P1, `transformed` and `rotating` built). A WebGPU pipeline that draws one model many times
|
||||
from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The instance types,
|
||||
matching Create's:
|
||||
**R3. Instanced drawing** (P1, `transformed`, `rotating`, `fluid` and items built). A WebGPU pipeline that draws one
|
||||
model many times from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The
|
||||
instance types, matching Create's:
|
||||
|
||||
| Type | Per instance | Shader |
|
||||
| ------------- | ------------------------------------------ | ----------------------------------------------------------------------- |
|
||||
@@ -269,8 +269,14 @@ instances are grouped by model alone. Each group keeps its instances on the CPU
|
||||
range from the first changed instance to the last once a frame. A deleted instance's place is taken by the last one, so
|
||||
a group's instances are always its first ones. Light comes with each chunk mesh. Every instance is drawn each frame,
|
||||
with no culling by chunk, since a draw call per model is cheaper than one per model per chunk until there are far more
|
||||
instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts (P4)
|
||||
and `fluid` with tanks (P5).
|
||||
instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts
|
||||
(P4).
|
||||
|
||||
`fluid` is built apart from the table: each box is a model of its own, built on the CPU when its box is set, cut into a
|
||||
piece per block it crosses so the texture is never stretched, like Create's `renderTiledFace`, and tinted in its fluid's
|
||||
color. It's one draw call per box, drawn blended after the other instances and back to front. Items are transformed
|
||||
instances too, of a model built once from what an item draws, one per way an item looks (its id, texture and layer
|
||||
colors), so a belt of one item is one draw call.
|
||||
|
||||
**R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU
|
||||
buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and
|
||||
@@ -327,8 +333,8 @@ pressing.
|
||||
slots, and simulate. Chests and furnaces get them in `mods/bworld`. Funnels, chutes, arms, deployers, belts and vaults
|
||||
all move items only through this.
|
||||
|
||||
**S2. Fluids** (P5). A fluid registry (bworld's liquids are fluids, plus mods' own like Create's honey and chocolate),
|
||||
fluid stacks with amounts in millibuckets, a `"fluids"` capability, and fluid containers in items (buckets, bottles).
|
||||
**S2. Fluids** (P5). A fluid registry (bworld's water and lava, plus mods' own like Create's honey and chocolate), fluid
|
||||
stacks with amounts in millibuckets, a `"fluids"` capability, and fluid containers in items (buckets, bottles).
|
||||
|
||||
**S3. Redstone** (P6, or earlier for clutches). A signal API in the engine (each block side has a power level 0 to 15,
|
||||
`get_signal`, `has_neighbor_signal`, updates to neighbours) and the basic blocks in `mods/bworld`: lever, button, dust,
|
||||
@@ -337,13 +343,13 @@ today.
|
||||
|
||||
**S4. Machines acting on the world** (P3, built).
|
||||
|
||||
- `liquid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans.
|
||||
- `fluid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans.
|
||||
- Item entities in a box, which can be changed and removed, for the press, fans and belts picking items up.
|
||||
- Pushing entities, for fans.
|
||||
- Breaking a block over time with progress shown, and its drops, for drills and saws.
|
||||
- A fake player using an item on a block, for the deployer (`DeployerFakePlayer`).
|
||||
|
||||
As built, all in `ctx.world` (see the modding docs for each): `liquid_flow`, `entities_in(from, to, type?)` with
|
||||
As built, all in `ctx.world` (see the modding docs for each): `fluid_flow`, `entities_in(from, to, type?)` with
|
||||
`EntityRef.get_item`, `set_item`, `velocity` and `push`, `spawn_item` for an item lying still where it's put (the
|
||||
press's extra results), and `player.push`, which is sent to their client since it moves them. `set_break_progress` shows
|
||||
cracks to the players who have the chunk, sending only a change of stage, and `ctx.blocks.toughness` gives what breaking
|
||||
|
||||
@@ -38,7 +38,8 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script
|
||||
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
|
||||
show items
|
||||
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns
|
||||
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
|
||||
machine
|
||||
- [Crops](docs/modding/blocks/crops.md): farming without writing code
|
||||
- [Verdigris](docs/modding/blocks/verdigris.md): blocks that make and use signals, like levers, torches and doors
|
||||
|
||||
@@ -65,6 +66,7 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
|
||||
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
|
||||
- [Loot Tables](docs/modding/resources/loot_tables.md): what blocks, mobs, fishing and chests give
|
||||
- [Fluids](docs/modding/resources/fluids.md): fluids that can be held, apart from blocks that flow
|
||||
|
||||
**Everything else**
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ export class Client {
|
||||
player.yaw,
|
||||
player.pitch,
|
||||
picked?.distance ?? player.block_interaction_range,
|
||||
this.game_mode.held_item()?.targets_liquids,
|
||||
this.game_mode.held_item()?.targets_fluids,
|
||||
);
|
||||
this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
|
||||
}
|
||||
|
||||
@@ -64,12 +64,12 @@ export abstract class Entity {
|
||||
|
||||
// in water, like the server's Entity.in_water
|
||||
get in_water() {
|
||||
return physics.in_water(this, (x, y, z) => this.level.is_liquid(x, y, z));
|
||||
return physics.in_water(this, (x, y, z) => this.level.is_fluid(x, y, z));
|
||||
}
|
||||
|
||||
// its eyes are in water
|
||||
get eyes_in_water() {
|
||||
return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z));
|
||||
return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_fluid(x, y, z));
|
||||
}
|
||||
|
||||
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
|
||||
|
||||
@@ -159,9 +159,9 @@ export class LocalPlayer extends Player {
|
||||
this.drag = this.flying ? FLY_VERTICAL_DRAG : this.#in_water ? WATER_DRAG : LAND_DRAG;
|
||||
if (this.swimming && this.#in_water) this.#steer(input);
|
||||
if (!this.flying) {
|
||||
physics.push_by_liquid(
|
||||
physics.push_by_fluid(
|
||||
this,
|
||||
(x, y, z) => this.level.liquid_at(x, y, z),
|
||||
(x, y, z) => this.level.fluid_at(x, y, z),
|
||||
(x, y, z) => this.level.collision_shape(x, y, z),
|
||||
true,
|
||||
);
|
||||
@@ -229,7 +229,7 @@ export class LocalPlayer extends Player {
|
||||
// of leaping out of the water, unless it's holding jump
|
||||
#steer(input: MoveInput) {
|
||||
const look_y = Math.sin(this.pitch);
|
||||
const head_in_water = this.level.is_liquid(
|
||||
const head_in_water = this.level.is_fluid(
|
||||
Math.floor(this.x),
|
||||
Math.floor(this.y + this.height),
|
||||
Math.floor(this.z),
|
||||
@@ -259,7 +259,7 @@ export class LocalPlayer extends Player {
|
||||
#hop_out_of_water(from_y: number) {
|
||||
if (!this.colliding_x && !this.colliding_z) return;
|
||||
const blocked = (x: number, y: number, z: number) =>
|
||||
this.level.is_liquid(x, y, z) || this.level.collision_shape(x, y, z);
|
||||
this.level.is_fluid(x, y, z) || this.level.collision_shape(x, y, z);
|
||||
const dy = from_y - this.y + this.vy * TICK_DELTA + WATER_HOP_HEIGHT;
|
||||
if (physics.box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the fluids' rules from the mods' shared scripts on this client, the same as the server's (see common/fluids.ts), for
|
||||
// drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods
|
||||
// and makes it again for each server's
|
||||
import { FluidRules } from "$/common/fluids.ts";
|
||||
|
||||
export let fluid_rules = new FluidRules(() => undefined);
|
||||
|
||||
export function set_fluid_rules(rules: FluidRules) {
|
||||
fluid_rules = rules;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import type { Client } from "./client.ts";
|
||||
import type { BlockHitResult } from "./level/client_level.ts";
|
||||
import type { Container } from "$/common/inventory.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { box_overlaps_block, can_place, liquid_block, placement_target, waterlog_placement } from "$/common/utils.ts";
|
||||
import { box_overlaps_block, can_place, fluid_block, placement_target, waterlog_placement } from "$/common/utils.ts";
|
||||
import { block_rules, predict_neighbors } from "./mods.ts";
|
||||
import { collision_shape_at } from "$/common/block_shapes.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
@@ -83,11 +83,11 @@ export class MultiPlayerGameMode {
|
||||
|
||||
// the shared rules' on_interact, like a trapdoor opening, shows right away. the server runs them too and corrects
|
||||
// this if it disagrees. when they do something nothing is placed, like on the server
|
||||
// an item aimed at liquids, like a bucket, uses the liquid in a waterlogged block instead, like on the server
|
||||
// an item aimed at fluids, like a bucket, uses the fluid in a waterlogged block instead, like on the server
|
||||
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
|
||||
const held = this.held_item();
|
||||
const value = level.get_block_value(hit.x, hit.y, hit.z);
|
||||
const used = (held?.targets_liquids && liquid_block(value, block_info)) || block_info;
|
||||
const used = (held?.targets_fluids && fluid_block(value, block_info)) || block_info;
|
||||
// sneaking with an item skips the block, like on the server
|
||||
const sneaking = this.client.player.holding_sneak;
|
||||
const skips_block = sneaking && held !== undefined;
|
||||
@@ -107,7 +107,7 @@ export class MultiPlayerGameMode {
|
||||
const place_block = place_id !== undefined
|
||||
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
|
||||
: undefined;
|
||||
// with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into.
|
||||
// with the states the server will give it, see BlockRules.placement_value, and holding the fluid it goes into.
|
||||
// undefined when its rules say it can't go there
|
||||
const ruled_value = place_block &&
|
||||
block_rules.placement_value(place_block, this.client.player.yaw, this.client.player.pitch, {
|
||||
|
||||
@@ -161,8 +161,7 @@ export class ModGraphics implements Graphics {
|
||||
if (!EverythingRegistry.get<ItemRegistry>("items", id)) throw new Error(`unknown item ${id}`);
|
||||
const stack = new ItemStack(id, count);
|
||||
// the count only shows when it's more than one
|
||||
if (count === 1) stack.max_amount = 1;
|
||||
draw_item(stack, this.#x(x), this.#y(y));
|
||||
draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1);
|
||||
}
|
||||
|
||||
clip(x: number, y: number, w: number, h: number, draw: () => void) {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the box next to the mouse saying what an item is, like minecraft's: its name, what it's worth, then its lore
|
||||
// the box next to the mouse saying what an item is, like minecraft's: its name, the fluid in it, what it's worth, then
|
||||
// its lore
|
||||
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import type { ItemStack } from "$/common/inventory.ts";
|
||||
import { contained_fluid, type ItemStack } from "$/common/inventory.ts";
|
||||
import { display_name } from "$/common/utils.ts";
|
||||
import { fluid_rules } from "$/client/fluid_rules.ts";
|
||||
import { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "$/client/renderer/mod.ts";
|
||||
import { AssetManager } from "$/client/assets.ts";
|
||||
import { get_sprite_region } from "$/client/sprites.ts";
|
||||
@@ -16,6 +18,7 @@ type Color = [number, number, number, number];
|
||||
const NAME_COLOR: Color = [1, 1, 1, 1];
|
||||
const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1];
|
||||
const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1];
|
||||
const FLUID_COLOR: Color = [0.55, 0.75, 0.95, 1];
|
||||
const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1];
|
||||
// from the edge of the tooltip sprite to the text
|
||||
const PADDING = 4 * GUI_SCALE;
|
||||
@@ -34,10 +37,15 @@ export interface TooltipLine {
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
// its name, the item's lore from its json, then what the server's scripts said about this stack
|
||||
// its name, the fluid a full container holds, the item's lore from its json, then what the server's scripts said about
|
||||
// this stack
|
||||
export function item_tooltip(item: ItemStack): TooltipLine[] {
|
||||
const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }];
|
||||
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||
const fluid = contained_fluid(item.type_id, item.data);
|
||||
if (fluid) {
|
||||
lines.push({ text: `${fluid_rules.name(fluid)}, ${info!.fluid_container!.capacity} mB`, color: FLUID_COLOR });
|
||||
}
|
||||
if (info?.food) {
|
||||
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@ import {
|
||||
block_value,
|
||||
chunk_key,
|
||||
default_block_value,
|
||||
fluid_block,
|
||||
fluid_in_cell,
|
||||
is_waterlogged,
|
||||
liquid_block,
|
||||
liquid_in_cell,
|
||||
} from "$/common/utils.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
block_light_opacity,
|
||||
BlockRegistry,
|
||||
EverythingRegistry,
|
||||
is_liquid_block,
|
||||
is_fluid_block,
|
||||
RENDER_LAYERS,
|
||||
RenderLayer,
|
||||
} from "$/common/everything_registry.ts";
|
||||
@@ -376,18 +376,18 @@ export class ClientLevel {
|
||||
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
||||
}
|
||||
|
||||
// the liquid there and how high it is, for liquids pushing things along. unloaded chunks have none
|
||||
liquid_at(x: number, y: number, z: number) {
|
||||
// the fluid there and how high it is, for fluids pushing things along. unloaded chunks have none
|
||||
fluid_at(x: number, y: number, z: number) {
|
||||
const value = this.get_block_value(x, y, z);
|
||||
const nid = value & ID_MASK;
|
||||
return nid === VOID || nid === AIR ? undefined : liquid_in_cell(value, this.#blocks[nid]);
|
||||
return nid === VOID || nid === AIR ? undefined : fluid_in_cell(value, this.#blocks[nid]);
|
||||
}
|
||||
|
||||
// water, or a block waterlogged with it, see liquid_block. unloaded chunks aren't
|
||||
is_liquid(x: number, y: number, z: number) {
|
||||
// water, or a block waterlogged with it, see fluid_block. unloaded chunks aren't
|
||||
is_fluid(x: number, y: number, z: number) {
|
||||
const value = this.get_block_value(x, y, z);
|
||||
const block = value & ID_MASK;
|
||||
return block !== VOID && block !== AIR && liquid_block(value, this.#blocks[block]) !== undefined;
|
||||
return block !== VOID && block !== AIR && fluid_block(value, this.#blocks[block]) !== undefined;
|
||||
}
|
||||
|
||||
// only changes what this client shows, drops and everything else happen on the server
|
||||
@@ -409,13 +409,13 @@ export class ClientLevel {
|
||||
const old_value = chunk.blocks[index];
|
||||
const old_nid = old_value & ID_MASK;
|
||||
const old_block = this.#blocks[old_nid];
|
||||
// a waterlogged block leaves its liquid, like the server's destroy_block
|
||||
const liquid = is_waterlogged(old_value, old_block)
|
||||
// a waterlogged block leaves its fluid, like the server's destroy_block
|
||||
const fluid = is_waterlogged(old_value, old_block)
|
||||
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
|
||||
: AIR;
|
||||
chunk.blocks[index] = liquid;
|
||||
chunk.blocks[index] = fluid;
|
||||
this.#mark_dirty(chunk);
|
||||
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, liquid);
|
||||
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid);
|
||||
}
|
||||
|
||||
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks
|
||||
@@ -774,7 +774,7 @@ export class ClientLevel {
|
||||
|
||||
// the first block along the view of something at x/y/z looking at yaw/pitch, like minecraft's pick. it has to go
|
||||
// into one of the block's boxes (see common/block_shapes.ts), so it looks past the empty half of a slab. it looks
|
||||
// through liquids unless liquids is set, see ItemRegistry.targets_liquids
|
||||
// through fluids unless fluids is set, see ItemRegistry.targets_fluids
|
||||
pick(
|
||||
x: number,
|
||||
y: number,
|
||||
@@ -782,7 +782,7 @@ export class ClientLevel {
|
||||
yaw: number,
|
||||
pitch: number,
|
||||
max_distance = 6,
|
||||
liquids = false,
|
||||
fluids = false,
|
||||
step = 0.05,
|
||||
): BlockHitResult | undefined {
|
||||
const cos_pitch = Math.cos(pitch);
|
||||
@@ -812,11 +812,11 @@ export class ClientLevel {
|
||||
continue;
|
||||
}
|
||||
const info = this.#blocks[block];
|
||||
if (!liquids && is_liquid_block(info)) {
|
||||
if (!fluids && is_fluid_block(info)) {
|
||||
continue;
|
||||
}
|
||||
// aimed at liquids, the source in a waterlogged block covers it, like the server's raycast_shape
|
||||
const covered = liquids && is_waterlogged(value, info);
|
||||
// aimed at fluids, the source in a waterlogged block covers it, like the server's raycast_shape
|
||||
const covered = fluids && is_waterlogged(value, info);
|
||||
const hit = clip_shape(
|
||||
!info || covered ? FULL_SHAPE : shape_at(info, value),
|
||||
bx,
|
||||
|
||||
@@ -8,8 +8,10 @@ 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 { fluid_rules, set_fluid_rules } from "./fluid_rules.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";
|
||||
@@ -163,6 +165,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);
|
||||
set_fluid_rules(new FluidRules(run_mod));
|
||||
rules_setup = true;
|
||||
for (const [i, bmod] of bmods.entries()) {
|
||||
const code = bmod.scripts.shared;
|
||||
@@ -221,6 +224,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 +339,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)),
|
||||
},
|
||||
|
||||
@@ -43,7 +43,7 @@ let canvas_format: GPUTextureFormat;
|
||||
let pipeline_2d: GPURenderPipeline;
|
||||
let pipeline_3d: GPURenderPipeline;
|
||||
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
|
||||
let instance_pipeline: GPURenderPipeline;
|
||||
let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline };
|
||||
// 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes
|
||||
let quad_index_buffer: GPUBuffer | undefined;
|
||||
let quad_index_capacity = 0;
|
||||
@@ -576,16 +576,24 @@ export function draw_terrain(
|
||||
}
|
||||
|
||||
// draws a model's quads (4 vertices each, see MODEL_VERTEX_BYTES) once for each of the first instance_count instances
|
||||
// in instances (see INSTANCE_FLOATS), in one draw call
|
||||
export function draw_instances(model: GPUBuffer, quad_count: number, instances: GPUBuffer, instance_count: number) {
|
||||
// in instances (see INSTANCE_FLOATS), in one draw call. cut out like cutout terrain, or blended like translucent
|
||||
// terrain, which needs drawing back to front
|
||||
export function draw_instances(
|
||||
model: GPUBuffer,
|
||||
quad_count: number,
|
||||
instances: GPUBuffer,
|
||||
instance_count: number,
|
||||
translucent = false,
|
||||
) {
|
||||
if (!current_texture || quad_count === 0 || instance_count === 0) {
|
||||
return;
|
||||
}
|
||||
ensure_quad_indices(quad_count);
|
||||
const render_pass = ensure_pass();
|
||||
if (current_pipeline !== instance_pipeline) {
|
||||
render_pass.setPipeline(instance_pipeline);
|
||||
current_pipeline = instance_pipeline;
|
||||
const pipeline = translucent ? instance_pipelines.translucent : instance_pipelines.cutout;
|
||||
if (current_pipeline !== pipeline) {
|
||||
render_pass.setPipeline(pipeline);
|
||||
current_pipeline = pipeline;
|
||||
terrain_binds = undefined;
|
||||
}
|
||||
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
|
||||
@@ -1010,26 +1018,30 @@ function create_pipelines() {
|
||||
primitive: primitive_3d,
|
||||
depthStencil: depth_3d,
|
||||
});
|
||||
const blend: GPUBlendState = {
|
||||
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
};
|
||||
terrain_pipelines = {
|
||||
solid: terrain_pipeline("fs_solid"),
|
||||
// alpha to coverage needs msaa
|
||||
cutout: sample_count > 1
|
||||
? terrain_pipeline("fs_cutout", undefined, true)
|
||||
: terrain_pipeline("fs_cutout_discard"),
|
||||
translucent: terrain_pipeline("fs_translucent", {
|
||||
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
}),
|
||||
translucent: terrain_pipeline("fs_translucent", blend),
|
||||
};
|
||||
// instances are cut out like cutout terrain
|
||||
// instances are cut out like cutout terrain, or blended like translucent terrain, like a fluid's box
|
||||
const instance_vertex: GPUVertexState = {
|
||||
module: terrain_module,
|
||||
entryPoint: "vs_instance",
|
||||
buffers: INSTANCED_BUFFERS,
|
||||
};
|
||||
instance_pipeline = sample_count > 1
|
||||
? terrain_pipeline("fs_cutout", undefined, true, instance_vertex)
|
||||
: terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex);
|
||||
instance_pipelines = {
|
||||
cutout: sample_count > 1
|
||||
? terrain_pipeline("fs_cutout", undefined, true, instance_vertex)
|
||||
: terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex),
|
||||
translucent: terrain_pipeline("fs_translucent", blend, false, instance_vertex),
|
||||
};
|
||||
}
|
||||
|
||||
// how vs_instance reads a model's vertices and its instances
|
||||
|
||||
@@ -53,7 +53,7 @@ export class GameRenderer {
|
||||
#render_underwater(client: Client) {
|
||||
const { x, y, z } = client.camera;
|
||||
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
|
||||
if (!client.level.is_liquid(bx, by, bz)) return;
|
||||
if (!client.level.is_fluid(bx, by, bz)) return;
|
||||
const color = client.level.water_color(bx, bz);
|
||||
draw_rect(0, 0, canvas.width, canvas.height, [
|
||||
(color >> 16) / 255,
|
||||
@@ -78,7 +78,7 @@ export class GameRenderer {
|
||||
level.render_block_outline(client.level, client.hit_result, camera);
|
||||
level.render_entities(client.level, camera, client.player, partial_tick);
|
||||
});
|
||||
profiler.section("visuals", () => level.render_visuals(client.level, partial_tick));
|
||||
profiler.section("visuals", () => level.render_visuals(client.level, camera, partial_tick));
|
||||
profiler.section("translucent", () => level.render_translucent(client.level, camera));
|
||||
profiler.section("nameplates", () => render_nameplates(client.level, camera, client.player, partial_tick));
|
||||
end_mode_3d();
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
|
||||
import { mat4, vec3 } from "gl-matrix";
|
||||
import type { SpriteRegion } from "$/common/constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import { BlockRegistry, EverythingRegistry, type ItemLayer, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import { AssetManager } from "$/client/assets.ts";
|
||||
import { get_sprite_region } from "$/client/sprites.ts";
|
||||
import type { ItemEntity } from "$/client/entity/item_entity.ts";
|
||||
import { type ItemData, ItemStack } from "$/common/inventory.ts";
|
||||
import { contained_fluid, type ItemData, ItemStack } from "$/common/inventory.ts";
|
||||
import type { FluidVariant } from "$/common/mod_api/shared.ts";
|
||||
import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts";
|
||||
import {
|
||||
bake_model,
|
||||
@@ -23,12 +24,14 @@ import {
|
||||
type ModelDisplay,
|
||||
type ModelJson,
|
||||
} from "$/common/block_models.ts";
|
||||
import { item_model } from "./item_model.ts";
|
||||
import { item_model, type ItemQuad } from "./item_model.ts";
|
||||
import { get_state_value, item_texture } from "$/common/utils.ts";
|
||||
import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts";
|
||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
||||
import { entity_tint } from "./entity_light.ts";
|
||||
import type { Vec3 } from "./player_renderer.ts";
|
||||
import { fluid_rules } from "$/client/fluid_rules.ts";
|
||||
import { color_rgb, tint_without_biome, type TintColor } from "$/common/worldgen/biome_colors.ts";
|
||||
|
||||
// how big items on the ground are drawn, minecraft's ground transform
|
||||
const BLOCK_SCALE = 0.25;
|
||||
@@ -50,6 +53,9 @@ const CORNER_UVS = [[0, 1], [1, 1], [1, 0], [0, 0]] as const;
|
||||
// where the extra copies of a bigger stack sit, as fractions of the model's size
|
||||
const COPY_OFFSETS = [[0, 0, 0], [0.35, 0.2, -0.25], [-0.3, 0.4, 0.2], [0.15, 0.6, 0.35], [-0.2, 0.8, -0.3]];
|
||||
|
||||
// how far each of a flat item's layers sits out from the one under it, so it's drawn over it
|
||||
const LAYER_GAP = 0.001;
|
||||
|
||||
// minecraft draws more copies of the model the bigger the stack is
|
||||
function copies(amount: number) {
|
||||
if (amount > 48) return 5;
|
||||
@@ -71,6 +77,18 @@ const SHOWN_COPY_SPREAD = 0.075;
|
||||
// a point of an item's model to where it's drawn. models are 1 across, from y 0 to 1, centered on x and z
|
||||
export type ItemTransform = (x: number, y: number, z: number) => [number, number, number];
|
||||
|
||||
// where push_item's vertices go: the batch, or anything else that takes them the same way, like a visual's model
|
||||
export type VertexSink = typeof push_vertex;
|
||||
|
||||
// an item the size it's drawn on the ground, with its middle at the middle of the block. for a visual's item, which
|
||||
// is placed from there, like create's items in a basin
|
||||
export function ground_transform(item: ItemStack): ItemTransform {
|
||||
const ground = item_model_of(item)?.display.ground;
|
||||
if (ground) return display_transform(mat4.fromTranslation(mat4.create(), [0.5, 0.5, 0.5]), ground);
|
||||
const scale = drawn_as_model(item) ? BLOCK_SCALE : ITEM_SCALE;
|
||||
return (x, y, z) => [0.5 + x * scale, 0.5 + (y - 0.5) * scale, 0.5 + z * scale];
|
||||
}
|
||||
|
||||
// the atlas has to be the current texture
|
||||
export function render_item_entity(entity: ItemEntity, partial_tick: number) {
|
||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
||||
@@ -283,8 +301,15 @@ export function display_transform(base: mat4, display: DisplayTransform): ItemTr
|
||||
}
|
||||
|
||||
// an item's model: its own model or its block's item_model, a cube for other blocks, its sprite made 3d for everything
|
||||
// else (see item_model.ts). tint multiplies its colors, like the light it's in
|
||||
export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform, [tr, tg, tb]: Vec3 = [1, 1, 1]) {
|
||||
// else (see item_model.ts). tint multiplies its colors, like the light it's in. two triangles a quad, its corners 0 1 2
|
||||
// and 0 2 3
|
||||
export function push_item(
|
||||
atlas: Texture,
|
||||
item: ItemStack,
|
||||
transform: ItemTransform,
|
||||
[tr, tg, tb]: Vec3 = [1, 1, 1],
|
||||
vertex: VertexSink = push_vertex,
|
||||
) {
|
||||
const model = item_model_of(item);
|
||||
if (model) {
|
||||
for (const quad of model.quads) {
|
||||
@@ -294,7 +319,7 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf
|
||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||
const p = quad.positions;
|
||||
const [px, py, pz] = transform(p[i * 3] - 0.5, p[i * 3 + 1], p[i * 3 + 2] - 0.5);
|
||||
push_vertex(
|
||||
vertex(
|
||||
px,
|
||||
py,
|
||||
pz,
|
||||
@@ -315,24 +340,66 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf
|
||||
const region = get_sprite_region(cube_face_texture(block, face.texture));
|
||||
const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5));
|
||||
const [r, g, b] = cube_face_tint(block, face.texture);
|
||||
push_textured_quad(atlas, region, corners, [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb]);
|
||||
const color = [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb];
|
||||
push_textured_quad(atlas, region, corners, color, vertex);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// its sprite, then its layers over it: only their fronts and backs, the first two quads, each a little further out
|
||||
const texture_id = item_texture(item);
|
||||
push_sprite(atlas, texture_id, item_model(texture_id), [tr, tg, tb], 0, transform, vertex);
|
||||
item_layers(item).forEach(({ texture, color: [r, g, b] }, i) => {
|
||||
const color: Vec3 = [r * tr, g * tg, b * tb];
|
||||
push_sprite(atlas, texture, item_model(texture).slice(0, 2), color, (i + 1) * LAYER_GAP, transform, vertex);
|
||||
});
|
||||
}
|
||||
|
||||
// a flat item's sprite made 3d (see item_model.ts), its front and back gap further out than the item's
|
||||
function push_sprite(
|
||||
atlas: Texture,
|
||||
texture_id: string,
|
||||
quads: ItemQuad[],
|
||||
[r, g, b]: Vec3,
|
||||
gap: number,
|
||||
transform: ItemTransform,
|
||||
vertex: VertexSink,
|
||||
) {
|
||||
const region = get_sprite_region(texture_id);
|
||||
const u = (pixels: number) => (region.x + pixels) / atlas.width;
|
||||
const v = (pixels: number) => (region.y + pixels) / atlas.height;
|
||||
for (const quad of item_model(texture_id)) {
|
||||
for (const quad of quads) {
|
||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||
const [px, py, pz] = transform(...quad.corners[i]);
|
||||
const [cx, cy, cz] = quad.corners[i];
|
||||
const [px, py, pz] = transform(cx, cy, cz + Math.sign(cz) * gap);
|
||||
const [pu, pv] = quad.uvs[i];
|
||||
push_vertex(px, py, pz, u(pu), v(pv), quad.shade * tr, quad.shade * tg, quad.shade * tb, 1);
|
||||
const u = (region.x + pu) / atlas.width;
|
||||
const v = (region.y + pv) / atlas.height;
|
||||
vertex(px, py, pz, u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the layers drawn over a flat item's texture (see ItemLayer), each in its tint's color, without the ones whose tint
|
||||
// has no color for this stack
|
||||
export function item_layers(item: ItemStack): { texture: string; color: Vec3 }[] {
|
||||
const layers = EverythingRegistry.get<ItemRegistry>("items", item.type_id)?.layers ?? [];
|
||||
return layers.flatMap(({ texture, tint }) => {
|
||||
const color = layer_color(item, tint);
|
||||
return color ? [{ texture, color }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function layer_color(item: ItemStack, tint: ItemLayer["tint"]): Vec3 | undefined {
|
||||
if (tint === undefined) return [1, 1, 1];
|
||||
if (tint !== "fluid") return color_rgb(tint_without_biome(tint));
|
||||
const fluid = contained_fluid(item.type_id, item.data);
|
||||
return fluid && fluid_rgb(fluid);
|
||||
}
|
||||
|
||||
// a fluid's color by its rules, as r g b from 0 to 1
|
||||
export function fluid_rgb(fluid: FluidVariant): Vec3 {
|
||||
return color_rgb(tint_without_biome(fluid_rules.color(fluid) as TintColor));
|
||||
}
|
||||
|
||||
// where a model's uv in pixels (0-16) is in the atlas. the atlas's border around each sprite (see ATLAS_BORDER) keeps
|
||||
// lookups that round past its edge on its own pixels
|
||||
export function sprite_u(atlas: Texture, region: SpriteRegion, pixels: number) {
|
||||
@@ -343,7 +410,13 @@ export function sprite_v(atlas: Texture, region: SpriteRegion, pixels: number) {
|
||||
return (region.y + pixels / TEXTURE_SIZE * region.height) / atlas.height;
|
||||
}
|
||||
|
||||
function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: number[][], color: number[]) {
|
||||
function push_textured_quad(
|
||||
atlas: Texture,
|
||||
region: SpriteRegion,
|
||||
corners: number[][],
|
||||
color: number[],
|
||||
vertex: VertexSink,
|
||||
) {
|
||||
const u0 = region.x / atlas.width;
|
||||
const v0 = region.y / atlas.height;
|
||||
const u1 = (region.x + region.width) / atlas.width;
|
||||
@@ -352,6 +425,6 @@ function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: numbe
|
||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||
const [px, py, pz] = corners[i];
|
||||
const [cu, cv] = CORNER_UVS[i];
|
||||
push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1);
|
||||
vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,12 +149,12 @@ export class LevelRenderer {
|
||||
}
|
||||
|
||||
// blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first
|
||||
render_visuals(level: ClientLevel, partial_tick: number) {
|
||||
render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
|
||||
if (!this.draw.visuals) return;
|
||||
level.visuals.frame(this.#visible, level.ticks + partial_tick);
|
||||
flush_batch();
|
||||
set_current_texture(level.image.tex);
|
||||
draw_visuals(level.visuals, level.image);
|
||||
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
|
||||
}
|
||||
|
||||
// the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' faces like
|
||||
|
||||
@@ -15,7 +15,15 @@ import {
|
||||
ITEM_FACE_SHADE,
|
||||
item_tint,
|
||||
} from "$/common/block_models.ts";
|
||||
import { display_matrix, item_block, item_model_of, type ItemModel, sprite_u, sprite_v } from "./item_renderer.ts";
|
||||
import {
|
||||
display_matrix,
|
||||
item_block,
|
||||
item_layers,
|
||||
item_model_of,
|
||||
type ItemModel,
|
||||
sprite_u,
|
||||
sprite_v,
|
||||
} from "./item_renderer.ts";
|
||||
import {
|
||||
draw_rect,
|
||||
draw_text,
|
||||
@@ -77,7 +85,8 @@ export function draw_nine_slice(
|
||||
}
|
||||
}
|
||||
|
||||
export function draw_item(item: ItemStack, x: number, y: number) {
|
||||
// show_count is for drawing an item where its count means nothing, like one shown on a screen
|
||||
export function draw_item(item: ItemStack, x: number, y: number, show_count = item.max_amount !== 1) {
|
||||
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||
|
||||
if (!item_info) {
|
||||
@@ -95,7 +104,7 @@ export function draw_item(item: ItemStack, x: number, y: number) {
|
||||
draw_item_item(item, item_info, x, y);
|
||||
}
|
||||
|
||||
if (item.max_amount !== 1) {
|
||||
if (show_count) {
|
||||
draw_text(
|
||||
String(item.amount),
|
||||
x + SLOT_SIZE + 2 - 11 * 2,
|
||||
@@ -128,19 +137,27 @@ export function draw_item(item: ItemStack, x: number, y: number) {
|
||||
|
||||
// ey its not a bad name
|
||||
function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y: number) {
|
||||
const texture_id = item_texture(item, item_info);
|
||||
const sprite_region = get_sprite_region(texture_id);
|
||||
draw_texture_region(
|
||||
AssetManager.instance.get("bworld:textures"),
|
||||
sprite_region.x,
|
||||
sprite_region.y,
|
||||
sprite_region.width,
|
||||
sprite_region.height,
|
||||
x + 3,
|
||||
y + 3,
|
||||
SLOT_SIZE - 6,
|
||||
SLOT_SIZE - 6,
|
||||
);
|
||||
const draw = (texture_id: string, [r, g, b] = [1, 1, 1]) => {
|
||||
const sprite_region = get_sprite_region(texture_id);
|
||||
draw_texture_region(
|
||||
AssetManager.instance.get("bworld:textures"),
|
||||
sprite_region.x,
|
||||
sprite_region.y,
|
||||
sprite_region.width,
|
||||
sprite_region.height,
|
||||
x + 3,
|
||||
y + 3,
|
||||
SLOT_SIZE - 6,
|
||||
SLOT_SIZE - 6,
|
||||
false,
|
||||
false,
|
||||
r,
|
||||
g,
|
||||
b,
|
||||
);
|
||||
};
|
||||
draw(item_texture(item, item_info));
|
||||
for (const layer of item_layers(item)) draw(layer.texture, layer.color);
|
||||
}
|
||||
|
||||
// from a model's points to a slot, as screen x and y and depth toward the viewer. with a gui transform, the transform
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
// block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of
|
||||
// a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in
|
||||
// client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per
|
||||
// frame
|
||||
// frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own
|
||||
import { mat4, vec3 } from "gl-matrix";
|
||||
import type {
|
||||
FluidInstance,
|
||||
FluidVariant,
|
||||
Instances,
|
||||
ItemStack as ApiItemStack,
|
||||
ModelRef,
|
||||
RotatingInstance,
|
||||
TransformedInstance,
|
||||
@@ -22,11 +25,14 @@ import {
|
||||
type BakedQuad,
|
||||
find_model,
|
||||
item_tint,
|
||||
type ModelElementJson,
|
||||
type ModelJson,
|
||||
states_of,
|
||||
} from "$/common/block_models.ts";
|
||||
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
||||
import { chunk_key } from "$/common/utils.ts";
|
||||
import type { FluidJson, ModelFace } from "$/common/mod_data.ts";
|
||||
import { ItemStack } from "$/common/inventory.ts";
|
||||
import { chunk_key, item_texture } from "$/common/utils.ts";
|
||||
import {
|
||||
create_vertex_buffer,
|
||||
destroy_buffer,
|
||||
@@ -37,7 +43,7 @@ import {
|
||||
write_buffer,
|
||||
} from "$/client/renderer/mod.ts";
|
||||
import { get_sprite_region } from "$/client/sprites.ts";
|
||||
import { sprite_u, sprite_v } from "./item_renderer.ts";
|
||||
import { fluid_rgb, ground_transform, item_layers, push_item, sprite_u, sprite_v } from "./item_renderer.ts";
|
||||
|
||||
export interface VisualRegistration {
|
||||
mod: string;
|
||||
@@ -73,23 +79,57 @@ export interface DrawnInstance {
|
||||
light: number;
|
||||
}
|
||||
|
||||
// a quad of an instanced model: 4 corners counter clockwise seen from the front, x y z each in the model's space, their
|
||||
// uvs in atlas pixels, so they don't depend on the atlas's size, its tint, and whether the gpu shades it by the way it
|
||||
// faces
|
||||
export interface InstanceQuad {
|
||||
positions: number[];
|
||||
uvs: number[];
|
||||
tint: number[];
|
||||
shade: boolean;
|
||||
}
|
||||
|
||||
// what to give sprite_u and sprite_v for uvs in atlas pixels
|
||||
const ATLAS_PIXELS = { width: 1, height: 1 } as Texture;
|
||||
|
||||
// a model's baked quads as an instanced model's, each tinted
|
||||
export function instance_quads(quads: BakedQuad[], tint: (quad: BakedQuad) => number[]): InstanceQuad[] {
|
||||
return quads.map((quad) => {
|
||||
const region = get_sprite_region(quad.texture);
|
||||
const uvs = quad.uvs.map((pixels, i) =>
|
||||
i % 2 === 0 ? sprite_u(ATLAS_PIXELS, region, pixels) : sprite_v(ATLAS_PIXELS, region, pixels)
|
||||
);
|
||||
return { positions: quad.positions, uvs, tint: tint(quad), shade: quad.shade };
|
||||
});
|
||||
}
|
||||
|
||||
// the instances of one model, drawn in one draw call. their data is changed on the cpu and written to the gpu once a
|
||||
// frame, from the first instance that changed to the last
|
||||
export class InstanceGroup {
|
||||
readonly quads: BakedQuad[];
|
||||
// each quad's tint, white but for a block's own tinted quads, like leaves
|
||||
readonly tints: number[][];
|
||||
quads: InstanceQuad[];
|
||||
// drawn blended after the rest, back to front by center, like a fluid's box
|
||||
readonly translucent: boolean;
|
||||
// where it is in the world, for drawing translucent ones back to front
|
||||
center = vec3.create();
|
||||
readonly instances: DrawnInstance[] = [];
|
||||
data = new Float32Array(INSTANCE_FLOATS * 16);
|
||||
// the instances changed since the gpu last got them, by index
|
||||
dirty_from = Infinity;
|
||||
dirty_to = -1;
|
||||
// quads changed since the gpu last got them
|
||||
model_changed = false;
|
||||
// made the first time it's drawn
|
||||
gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number };
|
||||
|
||||
constructor(quads: BakedQuad[], tints: number[][]) {
|
||||
constructor(quads: InstanceQuad[], translucent = false) {
|
||||
this.quads = quads;
|
||||
this.tints = tints;
|
||||
this.translucent = translucent;
|
||||
}
|
||||
|
||||
// for a model that changes, like a fluid's box filling up
|
||||
set_quads(quads: InstanceQuad[]) {
|
||||
this.quads = quads;
|
||||
this.model_changed = true;
|
||||
}
|
||||
|
||||
add(instance: DrawnInstance) {
|
||||
@@ -152,9 +192,12 @@ export class Visuals {
|
||||
#level: VisualsLevel;
|
||||
// baked once per level, since a level's mods don't change
|
||||
#models?: Record<string, ModelJson>;
|
||||
// models from models/ by id and turns, and blocks' own by value
|
||||
// models from models/ by id and turns, blocks' own by value, and items by how they look
|
||||
#model_groups = new Map<string, InstanceGroup>();
|
||||
#block_groups = new Map<number, InstanceGroup>();
|
||||
#item_groups = new Map<string, InstanceGroup>();
|
||||
// a fluid box's model is its own, and goes with it
|
||||
#fluid_groups = new Set<InstanceGroup>();
|
||||
|
||||
constructor(level: VisualsLevel) {
|
||||
this.#level = level;
|
||||
@@ -167,6 +210,8 @@ export class Visuals {
|
||||
*groups(): Iterable<InstanceGroup> {
|
||||
yield* this.#model_groups.values();
|
||||
yield* this.#block_groups.values();
|
||||
yield* this.#item_groups.values();
|
||||
yield* this.#fluid_groups;
|
||||
}
|
||||
|
||||
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
|
||||
@@ -215,14 +260,10 @@ export class Visuals {
|
||||
for (const entry of this.#chunks.get(key)!.values()) this.#delete(entry);
|
||||
}
|
||||
this.#chunks.clear();
|
||||
for (const group of this.groups()) {
|
||||
if (group.gpu) {
|
||||
destroy_buffer(group.gpu.model);
|
||||
destroy_buffer(group.gpu.instances);
|
||||
}
|
||||
}
|
||||
for (const group of this.groups()) destroy_group(group);
|
||||
this.#model_groups.clear();
|
||||
this.#block_groups.clear();
|
||||
this.#item_groups.clear();
|
||||
}
|
||||
|
||||
// the visuals in these chunks get their on_frame. every instance is drawn either way, it's the gpu that skips what's
|
||||
@@ -275,10 +316,15 @@ export class Visuals {
|
||||
}
|
||||
|
||||
#remove_instances(entry: Entry) {
|
||||
for (const instance of entry.instances) instance.group.remove(instance);
|
||||
for (const instance of entry.instances) this.#remove_instance(instance);
|
||||
entry.instances.clear();
|
||||
}
|
||||
|
||||
#remove_instance(instance: DrawnInstance) {
|
||||
instance.group.remove(instance);
|
||||
if (this.#fluid_groups.delete(instance.group)) destroy_group(instance.group);
|
||||
}
|
||||
|
||||
#relight(entry: Entry) {
|
||||
const light = this.#level.get_light(entry.x, entry.y, entry.z);
|
||||
if (light === entry.light) return;
|
||||
@@ -291,8 +337,7 @@ export class Visuals {
|
||||
|
||||
#instances(entry: Entry, block: BlockRegistry): Instances {
|
||||
const corner = mat4.fromTranslation(mat4.create(), [entry.x, entry.y, entry.z]);
|
||||
const add = (model: ModelRef | undefined) => {
|
||||
const group = model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model);
|
||||
const add = (group: InstanceGroup) => {
|
||||
const instance: DrawnInstance = {
|
||||
group,
|
||||
index: -1,
|
||||
@@ -307,23 +352,44 @@ export class Visuals {
|
||||
return instance;
|
||||
};
|
||||
const remove = (instance: DrawnInstance) => () => {
|
||||
instance.group.remove(instance);
|
||||
this.#remove_instance(instance);
|
||||
entry.instances.delete(instance);
|
||||
};
|
||||
const model_group = (model: ModelRef | undefined) =>
|
||||
model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model);
|
||||
const transformed = (instance: DrawnInstance): TransformedInstance => ({
|
||||
set_transform(matrix) {
|
||||
if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix");
|
||||
mat4.multiply(instance.placement, corner, matrix as mat4);
|
||||
instance.group.write(instance);
|
||||
},
|
||||
delete: remove(instance),
|
||||
});
|
||||
return {
|
||||
transformed(model): TransformedInstance {
|
||||
const instance = add(model);
|
||||
transformed: (model) => transformed(add(model_group(model))),
|
||||
item: (stack) => transformed(add(this.#item_group(stack))),
|
||||
fluid: (fluid) => {
|
||||
const { texture, tint } = fluid_look(fluid);
|
||||
const group = new InstanceGroup([], true);
|
||||
this.#fluid_groups.add(group);
|
||||
const instance = add(group);
|
||||
return {
|
||||
set_transform(matrix) {
|
||||
if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix");
|
||||
mat4.multiply(instance.placement, corner, matrix as mat4);
|
||||
instance.group.write(instance);
|
||||
set_box(from, to) {
|
||||
const box = [from, to].map((corner) => [0, 1, 2].map((axis) => corner?.[axis]));
|
||||
if (!box.flat().every(Number.isFinite)) throw new Error("a box is from [x, y, z] to [x, y, z]");
|
||||
group.set_quads(fluid_box(texture, tint, box[0], box[1]));
|
||||
vec3.set(
|
||||
group.center,
|
||||
entry.x + (box[0][0] + box[1][0]) / 32,
|
||||
entry.y + (box[0][1] + box[1][1]) / 32,
|
||||
entry.z + (box[0][2] + box[1][2]) / 32,
|
||||
);
|
||||
},
|
||||
delete: remove(instance),
|
||||
};
|
||||
} satisfies FluidInstance;
|
||||
},
|
||||
rotating(model): RotatingInstance {
|
||||
const instance = add(model);
|
||||
const instance = add(model_group(model));
|
||||
return {
|
||||
set_rotation(axis, rpm, offset = 0) {
|
||||
if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`);
|
||||
@@ -346,8 +412,7 @@ export class Visuals {
|
||||
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
|
||||
const json = find_model(model, this.#models);
|
||||
if (!json) throw new Error(`there's no model ${model}`);
|
||||
const quads = bake_model(json, undefined, y, x);
|
||||
group = new InstanceGroup(quads, quads.map(() => [1, 1, 1]));
|
||||
group = new InstanceGroup(instance_quads(bake_model(json, undefined, y, x), () => [1, 1, 1]));
|
||||
this.#model_groups.set(key, group);
|
||||
}
|
||||
return group;
|
||||
@@ -358,11 +423,113 @@ export class Visuals {
|
||||
if (!group) {
|
||||
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
|
||||
const quads = bake_block(block, value, this.#models);
|
||||
group = new InstanceGroup(quads, quads.map((quad) => item_tint(block, quad.variables)));
|
||||
group = new InstanceGroup(instance_quads(quads, (quad) => item_tint(block, quad.variables)));
|
||||
this.#block_groups.set(value, group);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
// stacks that look the same share one: the same item, texture and layers in the same colors, like bottles of one
|
||||
// juice
|
||||
#item_group(stack: ApiItemStack): InstanceGroup {
|
||||
if (!EverythingRegistry.get("items", stack?.id)) throw new Error(`there's no item ${stack?.id}`);
|
||||
const item = new ItemStack(stack.id);
|
||||
if (stack.data !== undefined) item.data = structuredClone(stack.data);
|
||||
const key = JSON.stringify([item.type_id, item_texture(item), item_layers(item)]);
|
||||
let group = this.#item_groups.get(key);
|
||||
if (!group) {
|
||||
group = new InstanceGroup(item_quads(item));
|
||||
this.#item_groups.set(key, group);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
// an item's model the way push_item draws it, the size it's drawn on the ground. its shading is in its tints already,
|
||||
// like a dropped item's, so the gpu doesn't shade it again
|
||||
function item_quads(item: ItemStack): InstanceQuad[] {
|
||||
const vertices: number[][] = [];
|
||||
push_item(ATLAS_PIXELS, item, ground_transform(item), [1, 1, 1], (x, y, z, u, v, r = 1, g = 1, b = 1) => {
|
||||
vertices.push([x, y, z, u, v, r, g, b]);
|
||||
});
|
||||
const quads: InstanceQuad[] = [];
|
||||
// two triangles a quad, its corners 0 1 2 and 0 2 3
|
||||
for (let i = 0; i < vertices.length; i += 6) {
|
||||
const corners = [vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 5]];
|
||||
quads.push({
|
||||
positions: corners.flatMap(([x, y, z]) => [x, y, z]),
|
||||
uvs: corners.flatMap(([, , , u, v]) => [u, v]),
|
||||
tint: corners[0].slice(5, 8),
|
||||
shade: false,
|
||||
});
|
||||
}
|
||||
return quads;
|
||||
}
|
||||
|
||||
// a fluid's texture and its color by its rules, for a box of it
|
||||
function fluid_look(fluid: FluidVariant) {
|
||||
const json = EverythingRegistry.get<FluidJson>("fluids", fluid?.id);
|
||||
if (!json) throw new Error(`there's no fluid ${fluid?.id}`);
|
||||
return { texture: json.texture ?? "engine:missing", tint: fluid_rgb(structuredClone(fluid)) };
|
||||
}
|
||||
|
||||
// a box's faces, by the axis they're across and whether they're at its high end or its low one
|
||||
const BOX_FACES: { face: ModelFace; axis: number; high: boolean }[] = [
|
||||
{ face: "west", axis: 0, high: false },
|
||||
{ face: "east", axis: 0, high: true },
|
||||
{ face: "bottom", axis: 1, high: false },
|
||||
{ face: "top", axis: 1, high: true },
|
||||
{ face: "north", axis: 2, high: false },
|
||||
{ face: "south", axis: 2, high: true },
|
||||
];
|
||||
|
||||
// a box of a texture from one corner to the other, in pixels, like a fluid in a tank. it's cut where it goes from one
|
||||
// block into the next, and each piece is textured with the part of the texture it covers in its block, like a model
|
||||
// element's faces are, so the texture is never stretched and repeats once a block. only the outside faces are drawn.
|
||||
// nothing for a box that's flat or inside out
|
||||
export function fluid_box(texture: string, tint: number[], from: number[], to: number[]): InstanceQuad[] {
|
||||
if ([0, 1, 2].some((axis) => to[axis] <= from[axis])) return [];
|
||||
// where each axis's pieces start and end
|
||||
const cuts = [0, 1, 2].map((axis) => {
|
||||
const points = [from[axis]];
|
||||
for (let at = (Math.floor(from[axis] / 16) + 1) * 16; at < to[axis]; at += 16) points.push(at);
|
||||
return [...points, to[axis]];
|
||||
});
|
||||
const model: ModelJson = { id: "engine:fluid_box", textures: { fluid: texture }, elements: [] };
|
||||
const quads: InstanceQuad[] = [];
|
||||
for (let i = 0; i < cuts[0].length - 1; i++) {
|
||||
for (let j = 0; j < cuts[1].length - 1; j++) {
|
||||
for (let k = 0; k < cuts[2].length - 1; k++) {
|
||||
const low = [cuts[0][i], cuts[1][j], cuts[2][k]];
|
||||
const high = [cuts[0][i + 1], cuts[1][j + 1], cuts[2][k + 1]];
|
||||
const block = low.map((at) => Math.floor(at / 16));
|
||||
const element: ModelElementJson = {
|
||||
from: low.map((at, axis) => at - block[axis] * 16) as [number, number, number],
|
||||
to: high.map((at, axis) => at - block[axis] * 16) as [number, number, number],
|
||||
faces: {},
|
||||
};
|
||||
for (const { face, axis, high: side } of BOX_FACES) {
|
||||
if (side ? high[axis] === to[axis] : low[axis] === from[axis]) {
|
||||
element.faces[face] = { texture: "#fluid" };
|
||||
}
|
||||
}
|
||||
const baked = bake_model({ ...model, elements: [element] }, undefined);
|
||||
for (const quad of baked) {
|
||||
quad.positions = quad.positions.map((at, n) => at + block[n % 3]);
|
||||
}
|
||||
quads.push(...instance_quads(baked, () => tint));
|
||||
}
|
||||
}
|
||||
}
|
||||
return quads;
|
||||
}
|
||||
|
||||
// a group's gpu buffers go, for a group that won't be drawn again
|
||||
function destroy_group(group: InstanceGroup) {
|
||||
if (!group.gpu) return;
|
||||
destroy_buffer(group.gpu.model);
|
||||
destroy_buffer(group.gpu.instances);
|
||||
group.gpu = undefined;
|
||||
}
|
||||
|
||||
// false when it threw, which is logged with the mod and block
|
||||
@@ -376,39 +543,54 @@ function run_visual(entry: Entry, what: string, fn: () => void) {
|
||||
}
|
||||
}
|
||||
|
||||
// every instance, a draw call per model. a group's model goes to the gpu the first time it's drawn, and its instances
|
||||
// whenever they changed. the atlas has to be the current texture
|
||||
export function draw_visuals(visuals: Visuals, atlas: Texture) {
|
||||
// every instance, a draw call per model, and the translucent ones after the rest, back to front from the camera so each
|
||||
// shows what's behind it. a group's model goes to the gpu the first time it's drawn and again when it changed, and its
|
||||
// instances whenever they changed. the atlas has to be the current texture
|
||||
export function draw_visuals(visuals: Visuals, atlas: Texture, camera: Readonly<vec3>) {
|
||||
const translucent: InstanceGroup[] = [];
|
||||
for (const group of visuals.groups()) {
|
||||
const count = group.instances.length;
|
||||
if (count === 0) continue;
|
||||
const capacity = group.data.length / INSTANCE_FLOATS;
|
||||
if (!group.gpu || group.gpu.capacity !== capacity) {
|
||||
// the whole buffer again, when it's new or the cpu copy grew
|
||||
if (group.gpu) destroy_buffer(group.gpu.instances);
|
||||
group.gpu = {
|
||||
model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, group.tints, atlas)),
|
||||
instances: create_vertex_buffer(group.data),
|
||||
capacity,
|
||||
};
|
||||
} else if (group.dirty_to >= 0) {
|
||||
const from = group.dirty_from * INSTANCE_FLOATS;
|
||||
write_buffer(
|
||||
group.gpu.instances,
|
||||
from * 4,
|
||||
group.data,
|
||||
from,
|
||||
(group.dirty_to + 1) * INSTANCE_FLOATS - from,
|
||||
);
|
||||
}
|
||||
group.dirty_from = Infinity;
|
||||
group.dirty_to = -1;
|
||||
draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count);
|
||||
if (group.translucent) translucent.push(group);
|
||||
else draw_group(group, atlas);
|
||||
}
|
||||
const distance = (group: InstanceGroup) => vec3.squaredDistance(group.center, camera);
|
||||
translucent.sort((a, b) => distance(b) - distance(a));
|
||||
for (const group of translucent) draw_group(group, atlas);
|
||||
}
|
||||
|
||||
function draw_group(group: InstanceGroup, atlas: Texture) {
|
||||
const count = group.instances.length;
|
||||
if (count === 0 || group.quads.length === 0) return;
|
||||
const capacity = group.data.length / INSTANCE_FLOATS;
|
||||
if (group.gpu && group.model_changed) {
|
||||
destroy_buffer(group.gpu.model);
|
||||
group.gpu.model = create_vertex_buffer(pack_model(group.quads, atlas));
|
||||
}
|
||||
group.model_changed = false;
|
||||
if (!group.gpu || group.gpu.capacity !== capacity) {
|
||||
// the whole buffer again, when it's new or the cpu copy grew
|
||||
if (group.gpu) destroy_buffer(group.gpu.instances);
|
||||
group.gpu = {
|
||||
model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, atlas)),
|
||||
instances: create_vertex_buffer(group.data),
|
||||
capacity,
|
||||
};
|
||||
} else if (group.dirty_to >= 0) {
|
||||
const from = group.dirty_from * INSTANCE_FLOATS;
|
||||
write_buffer(
|
||||
group.gpu.instances,
|
||||
from * 4,
|
||||
group.data,
|
||||
from,
|
||||
(group.dirty_to + 1) * INSTANCE_FLOATS - from,
|
||||
);
|
||||
}
|
||||
group.dirty_from = Infinity;
|
||||
group.dirty_to = -1;
|
||||
draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count, group.translucent);
|
||||
}
|
||||
|
||||
// a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES
|
||||
export function pack_model(quads: BakedQuad[], tints: number[][], atlas: Texture): Uint8Array<ArrayBuffer> {
|
||||
export function pack_model(quads: InstanceQuad[], atlas: Texture): Uint8Array<ArrayBuffer> {
|
||||
const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES);
|
||||
const view = new DataView(bytes.buffer);
|
||||
const normal = vec3.create();
|
||||
@@ -418,13 +600,12 @@ export function pack_model(quads: BakedQuad[], tints: number[][], atlas: Texture
|
||||
// counterclockwise seen from the front, so it points out of the front
|
||||
const [a, b, d] = [corner(0), corner(1), corner(3)];
|
||||
vec3.normalize(normal, vec3.cross(normal, vec3.sub(b, b, a), vec3.sub(d, d, a)));
|
||||
const region = get_sprite_region(quad.texture);
|
||||
const tint = tints[q];
|
||||
const tint = quad.tint;
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const at = (q * 4 + k) * MODEL_VERTEX_BYTES;
|
||||
for (let axis = 0; axis < 3; axis++) view.setFloat32(at + axis * 4, p[k * 3 + axis], true);
|
||||
view.setUint16(at + 12, Math.round(sprite_u(atlas, region, quad.uvs[k * 2]) * 65535), true);
|
||||
view.setUint16(at + 14, Math.round(sprite_v(atlas, region, quad.uvs[k * 2 + 1]) * 65535), true);
|
||||
view.setUint16(at + 12, Math.round(quad.uvs[k * 2] / atlas.width * 65535), true);
|
||||
view.setUint16(at + 14, Math.round(quad.uvs[k * 2 + 1] / atlas.height * 65535), true);
|
||||
for (let c = 0; c < 3; c++) bytes[at + 16 + c] = Math.round(tint[c] * 255);
|
||||
bytes[at + 19] = quad.shade ? 255 : 0;
|
||||
for (let axis = 0; axis < 3; axis++) view.setInt8(at + 20 + axis, Math.round(normal[axis] * 127));
|
||||
|
||||
@@ -55,8 +55,8 @@ import {
|
||||
region_sky,
|
||||
REGION_VOID,
|
||||
} from "./lighting.ts";
|
||||
import { cell_index, liquid_quads, type LiquidCell } from "./liquid_mesh.ts";
|
||||
import { liquid_height, liquid_textures } from "$/common/everything_registry.ts";
|
||||
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
|
||||
import { fluid_height, fluid_textures } from "$/common/everything_registry.ts";
|
||||
|
||||
type TexturesInfo = Record<string, SpriteRegion>;
|
||||
|
||||
@@ -94,11 +94,11 @@ const block_occludes = new Uint8Array(TABLE_SIZE);
|
||||
// light can come around a corner past it
|
||||
const block_lets_light_by = new Uint8Array(TABLE_SIZE);
|
||||
const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) };
|
||||
// liquids: their range, 0 for blocks that aren't one, and where their level state is in the state bits
|
||||
const liquid_range = new Uint8Array(TABLE_SIZE);
|
||||
const liquid_level_shift = new Uint8Array(TABLE_SIZE);
|
||||
// waterloggable blocks: the numeric id of the liquid they hold, 0 for other blocks, and where their waterlogged state is
|
||||
const waterlog_liquid = new Uint16Array(TABLE_SIZE);
|
||||
// fluids: their range, 0 for blocks that aren't one, and where their level state is in the state bits
|
||||
const fluid_range = new Uint8Array(TABLE_SIZE);
|
||||
const fluid_level_shift = new Uint8Array(TABLE_SIZE);
|
||||
// waterloggable blocks: the numeric id of the fluid they hold, 0 for other blocks, and where their waterlogged state is
|
||||
const waterlog_fluid = new Uint16Array(TABLE_SIZE);
|
||||
const waterlogged_shift = new Uint8Array(TABLE_SIZE);
|
||||
// blocks with visuals: HAS_VISUAL, or REPLACED_MODEL when the visual draws all of it, see ctx.render.register_visual
|
||||
const block_visual = new Uint8Array(TABLE_SIZE);
|
||||
@@ -275,7 +275,7 @@ function build_block_tables() {
|
||||
// the registry has gaps, which forEach skips
|
||||
const nids = new Map<string, number>();
|
||||
blocks_registry.forEach((block, nid) => block && nids.set(block.id, nid));
|
||||
waterlog_liquid.fill(0);
|
||||
waterlog_fluid.fill(0);
|
||||
blocks_registry.forEach((block, nid) => {
|
||||
if (!block || nid === AIR) return;
|
||||
const layer = LAYER_IDS[block.render_layer ?? "solid"];
|
||||
@@ -286,13 +286,13 @@ function build_block_tables() {
|
||||
block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0;
|
||||
light_tables.opacity[nid] = opacity;
|
||||
light_tables.emission[nid] = block_light_emission(block);
|
||||
liquid_range[nid] = block.liquid?.range ?? 0;
|
||||
if (block.liquid) {
|
||||
fluid_range[nid] = block.fluid?.range ?? 0;
|
||||
if (block.fluid) {
|
||||
// the level state is the last one, see block_from_json
|
||||
liquid_level_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0);
|
||||
fluid_level_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0);
|
||||
}
|
||||
if (block.waterloggable) {
|
||||
waterlog_liquid[nid] = nids.get(block.waterloggable) ?? 0;
|
||||
waterlog_fluid[nid] = nids.get(block.waterloggable) ?? 0;
|
||||
// the waterlogged state is the last one, see block_from_json
|
||||
waterlogged_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0);
|
||||
}
|
||||
@@ -538,8 +538,8 @@ function light_quad(quad: MeshQuad, index: number, y: number, face_offsets: numb
|
||||
corner_ao.fill(1);
|
||||
}
|
||||
|
||||
// whether a block hides the face of a liquid against it, like show_face. air's layer isn't set, so it's checked first
|
||||
function hides_liquid(nid: number) {
|
||||
// whether a block hides the face of a fluid against it, like show_face. air's layer isn't set, so it's checked first
|
||||
function hides_fluid(nid: number) {
|
||||
return nid !== AIR && block_layers[nid] === SOLID;
|
||||
}
|
||||
|
||||
@@ -553,62 +553,62 @@ function region_value(chunks: (Uint32Array | null)[], index: number, y: number)
|
||||
return chunk ? chunk[y * CHUNK_AREA + (z % CHUNK_SIZE) * CHUNK_SIZE + (x % CHUNK_SIZE)] : AIR;
|
||||
}
|
||||
|
||||
// the surface of the liquid with this numeric id in a cell, if the cell is that liquid
|
||||
function liquid_cell_height(nid: number, value: number) {
|
||||
const level = ((value >>> 16) >>> liquid_level_shift[nid]) & 7;
|
||||
return liquid_height(level, liquid_range[nid]);
|
||||
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
|
||||
function fluid_cell_height(nid: number, value: number) {
|
||||
const level = ((value >>> 16) >>> fluid_level_shift[nid]) & 7;
|
||||
return fluid_height(level, fluid_range[nid]);
|
||||
}
|
||||
|
||||
const liquid_cells: LiquidCell[] = Array.from(
|
||||
const fluid_cells: FluidCell[] = Array.from(
|
||||
{ length: 9 },
|
||||
() => ({ same: false, height: 0, air: false, solid: false, top_same: false }),
|
||||
);
|
||||
|
||||
// the numeric id of the liquid in a cell: the block, or what it's waterlogged with. 0 for none
|
||||
function cell_liquid(chunks: (Uint32Array | null)[], index: number, y: number) {
|
||||
// the numeric id of the fluid in a cell: the block, or what it's waterlogged with. 0 for none
|
||||
function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
|
||||
const id = region_block(region, index, y);
|
||||
if (liquid_range[id]) return id;
|
||||
const liquid = waterlog_liquid[id];
|
||||
if (!liquid) return 0;
|
||||
return ((region_value(chunks, index, y) >>> 16) >>> waterlogged_shift[id]) & 1 ? liquid : 0;
|
||||
if (fluid_range[id]) return id;
|
||||
const fluid = waterlog_fluid[id];
|
||||
if (!fluid) return 0;
|
||||
return ((region_value(chunks, index, y) >>> 16) >>> waterlogged_shift[id]) & 1 ? fluid : 0;
|
||||
}
|
||||
|
||||
// the 3x3 cells around the liquid at index and y, see LiquidCell. a waterlogged block is a source of its liquid
|
||||
function fill_liquid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) {
|
||||
// the 3x3 cells around the fluid at index and y, see FluidCell. a waterlogged block is a source of its fluid
|
||||
function fill_fluid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) {
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
const cell = liquid_cells[cell_index(dx, dz)];
|
||||
const cell = fluid_cells[cell_index(dx, dz)];
|
||||
const at = index + dx + dz * REGION_SIZE;
|
||||
const id = region_block(region, at, y);
|
||||
cell.same = cell_liquid(chunks, at, y) === nid;
|
||||
cell.height = !cell.same ? 0 : id === nid ? liquid_cell_height(nid, region_value(chunks, at, y)) : 1;
|
||||
cell.same = cell_fluid(chunks, at, y) === nid;
|
||||
cell.height = !cell.same ? 0 : id === nid ? fluid_cell_height(nid, region_value(chunks, at, y)) : 1;
|
||||
cell.air = id === AIR;
|
||||
cell.solid = hides_liquid(id);
|
||||
cell.top_same = cell_liquid(chunks, at + REGION_LAYER, y + 1) === nid;
|
||||
cell.solid = hides_fluid(id);
|
||||
cell.top_same = cell_fluid(chunks, at + REGION_LAYER, y + 1) === nid;
|
||||
}
|
||||
}
|
||||
return liquid_cells;
|
||||
return fluid_cells;
|
||||
}
|
||||
|
||||
// for a liquid with a flowing texture of its own, how much of it a block shows: as many pixels across as the still one,
|
||||
// so minecraft's 32×32 flowing water next to its 16×16 still water shows half. see liquid_quads
|
||||
// for a fluid with a flowing texture of its own, how much of it a block shows: as many pixels across as the still one,
|
||||
// so minecraft's 32×32 flowing water next to its 16×16 still water shows half. see fluid_quads
|
||||
function flowing_scale(block: BlockRegistry): number | undefined {
|
||||
const textures = liquid_textures(block.textures);
|
||||
const textures = fluid_textures(block.textures);
|
||||
if (textures.flowing === textures.still) return undefined;
|
||||
const still = textures_info[textures.still] ?? textures_info["engine:missing"];
|
||||
const flowing = textures_info[textures.flowing] ?? textures_info["engine:missing"];
|
||||
return Math.min(1, still.width / flowing.width);
|
||||
}
|
||||
|
||||
// a liquid's quad for the mesher, see liquid_mesh.ts. it's lit like a full block's face on that side
|
||||
function liquid_mesh_quad(
|
||||
// a fluid's quad for the mesher, see fluid_mesh.ts. it's lit like a full block's face on that side
|
||||
function fluid_mesh_quad(
|
||||
block: BlockRegistry,
|
||||
face: number,
|
||||
positions: number[],
|
||||
uvs: number[],
|
||||
still: boolean,
|
||||
): MeshQuad {
|
||||
const textures = liquid_textures(block.textures);
|
||||
const textures = fluid_textures(block.textures);
|
||||
const flat = FACE_AXIS[face] !== 1 || (positions[1] === positions[4] && positions[4] === positions[7] &&
|
||||
positions[7] === positions[10]);
|
||||
return {
|
||||
@@ -625,7 +625,7 @@ function liquid_mesh_quad(
|
||||
};
|
||||
}
|
||||
|
||||
// the liquid's surface seen from below, so it shows from under water: the top quad facing down, lit and shaded like
|
||||
// the fluid's surface seen from below, so it shows from under water: the top quad facing down, lit and shaded like
|
||||
// the top. its corners go the other way round, the lighting the mesher just worked out with them
|
||||
const UNDERSIDE_CORNERS = [0, 3, 2, 1];
|
||||
|
||||
@@ -641,7 +641,7 @@ function underside(top: MeshQuad): MeshQuad {
|
||||
|
||||
// region has to be filled and lit first
|
||||
// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the
|
||||
// ones around it for liquids, whose surface follows their neighbors'
|
||||
// ones around it for fluids, whose surface follows their neighbors'
|
||||
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array | null)[], camera: number[]) {
|
||||
const values = chunks[4]!;
|
||||
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead
|
||||
@@ -707,36 +707,36 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
const layer_id = block_layers[block_nid];
|
||||
const alpha = layer_id === TRANSLUCENT ? block_info.alpha ?? 1 : 1;
|
||||
|
||||
// the liquid here, the block's own or what it's waterlogged with, then the block in it
|
||||
const liquid_nid = cell_liquid(chunks, index, y);
|
||||
if (liquid_nid) {
|
||||
const liquid_info = blocks_registry[liquid_nid];
|
||||
const liquid_layer = block_layers[liquid_nid];
|
||||
const liquid_alpha = liquid_layer === TRANSLUCENT ? liquid_info.alpha ?? 1 : 1;
|
||||
const cells = fill_liquid_cells(chunks, liquid_nid, index, y);
|
||||
// the fluid here, the block's own or what it's waterlogged with, then the block in it
|
||||
const fluid_nid = cell_fluid(chunks, index, y);
|
||||
if (fluid_nid) {
|
||||
const fluid_info = blocks_registry[fluid_nid];
|
||||
const fluid_layer = block_layers[fluid_nid];
|
||||
const fluid_alpha = fluid_layer === TRANSLUCENT ? fluid_info.alpha ?? 1 : 1;
|
||||
const cells = fill_fluid_cells(chunks, fluid_nid, index, y);
|
||||
const above = region_block(region, index + REGION_LAYER, y + 1);
|
||||
const below = region_block(region, index - REGION_LAYER, y - 1);
|
||||
const quads = liquid_quads(
|
||||
const quads = fluid_quads(
|
||||
cells,
|
||||
{
|
||||
same: cell_liquid(chunks, index + REGION_LAYER, y + 1) === liquid_nid,
|
||||
solid: hides_liquid(above),
|
||||
same: cell_fluid(chunks, index + REGION_LAYER, y + 1) === fluid_nid,
|
||||
solid: hides_fluid(above),
|
||||
},
|
||||
{
|
||||
same: cell_liquid(chunks, index - REGION_LAYER, y - 1) === liquid_nid,
|
||||
solid: hides_liquid(below),
|
||||
same: cell_fluid(chunks, index - REGION_LAYER, y - 1) === fluid_nid,
|
||||
solid: hides_fluid(below),
|
||||
},
|
||||
flowing_scale(liquid_info),
|
||||
flowing_scale(fluid_info),
|
||||
);
|
||||
for (const { face, positions, uvs, still } of quads) {
|
||||
const quad = liquid_mesh_quad(liquid_info, face, positions, uvs, still);
|
||||
const quad = fluid_mesh_quad(fluid_info, face, positions, uvs, still);
|
||||
light_quad(quad, index, y, face_offsets);
|
||||
// like minecraft's liquids, no ambient occlusion
|
||||
// like minecraft's fluids, no ambient occlusion
|
||||
corner_ao.fill(1);
|
||||
emit(quad, liquid_layer, x, y, z, liquid_alpha);
|
||||
if (face === 0) emit(underside(quad), liquid_layer, x, y, z, liquid_alpha);
|
||||
emit(quad, fluid_layer, x, y, z, fluid_alpha);
|
||||
if (face === 0) emit(underside(quad), fluid_layer, x, y, z, fluid_alpha);
|
||||
}
|
||||
if (liquid_nid === block_nid) continue;
|
||||
if (fluid_nid === block_nid) continue;
|
||||
}
|
||||
|
||||
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// liquids drawn like luanti's flowing liquids (MapblockMeshGenerator::drawLiquidNode in its content_mapblock.cpp): each
|
||||
// corner of the surface is as high as the liquid around it, so it slopes down where it flows away from a source. the
|
||||
// fluids drawn like luanti's flowing fluids (MapblockMeshGenerator::drawLiquidNode in its content_mapblock.cpp): each
|
||||
// corner of the surface is as high as the fluid around it, so it slopes down where it flows away from a source. the
|
||||
// sides between two cells of it are left out, except where it pours down past the surface of the one beside it
|
||||
import { FACE_CORNERS } from "$/common/block_models.ts";
|
||||
|
||||
// one of the 3x3 cells around a liquid and level with it, and the cell above that one
|
||||
export interface LiquidCell {
|
||||
// the same liquid, at any level
|
||||
// one of the 3x3 cells around a fluid and level with it, and the cell above that one
|
||||
export interface FluidCell {
|
||||
// the same fluid, at any level
|
||||
same: boolean;
|
||||
// its surface, 0 to 1, when it's the same liquid. 1 is a source
|
||||
// its surface, 0 to 1, when it's the same fluid. 1 is a source
|
||||
height: number;
|
||||
air: boolean;
|
||||
// hides the side of the liquid facing it, like a full block of stone
|
||||
// hides the side of the fluid facing it, like a full block of stone
|
||||
solid: boolean;
|
||||
// the cell above it is the same liquid, so the liquid here goes right up to the top
|
||||
// the cell above it is the same fluid, so the fluid here goes right up to the top
|
||||
top_same: boolean;
|
||||
}
|
||||
|
||||
export interface LiquidQuad {
|
||||
export interface FluidQuad {
|
||||
// the mesher's face index, see FACE_CORNERS
|
||||
face: number;
|
||||
// 4 corners in FACE_CORNERS' order, x y z in block space
|
||||
@@ -36,15 +36,15 @@ const SHORE = 0.02;
|
||||
// the horizontal neighbor each side faces, as dx dz, for faces 2 to 5: south (+z), north (-z), west (-x), east (+x)
|
||||
const SIDE_DIRECTIONS = [[0, 1], [0, -1], [-1, 0], [1, 0]];
|
||||
|
||||
// cells indexed by (dz + 1) * 3 + (dx + 1), so 4 is the liquid itself
|
||||
// cells indexed by (dz + 1) * 3 + (dx + 1), so 4 is the fluid itself
|
||||
export function cell_index(dx: number, dz: number) {
|
||||
return (dz + 1) * 3 + dx + 1;
|
||||
}
|
||||
|
||||
// like luanti's getCornerLevel: the height of the surface at a corner (cx and cz are 0 or 1, which end of the cell),
|
||||
// from the 4 cells that share it. a source or liquid above any of them makes it full, two of air pull it down to the
|
||||
// floor, otherwise it's the average of the liquid among them
|
||||
export function corner_height(cells: LiquidCell[], cx: number, cz: number) {
|
||||
// from the 4 cells that share it. a source or fluid above any of them makes it full, two of air pull it down to the
|
||||
// floor, otherwise it's the average of the fluid among them
|
||||
export function corner_height(cells: FluidCell[], cx: number, cz: number) {
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
let air = 0;
|
||||
@@ -92,7 +92,7 @@ function quad(
|
||||
still: boolean,
|
||||
y_at: (x: number, top: number, z: number) => number,
|
||||
uv_scale = 1,
|
||||
): LiquidQuad {
|
||||
): FluidQuad {
|
||||
const positions: number[] = [];
|
||||
const uvs: number[] = [];
|
||||
for (const [x, top, z] of FACE_CORNERS[face]) {
|
||||
@@ -104,9 +104,9 @@ function quad(
|
||||
return { face, positions, uvs, still };
|
||||
}
|
||||
|
||||
// the top of liquid flowing towards (flow_x, flow_z), like minecraft's LiquidBlockRenderer: the flowing texture turned
|
||||
// the top of fluid flowing towards (flow_x, flow_z), like minecraft's LiquidBlockRenderer: the flowing texture turned
|
||||
// so it runs downstream, a scale-sized square from its middle
|
||||
function flowing_top(heights: number[], flow_x: number, flow_z: number, scale: number): LiquidQuad {
|
||||
function flowing_top(heights: number[], flow_x: number, flow_z: number, scale: number): FluidQuad {
|
||||
const angle = Math.atan2(flow_z, flow_x) - Math.PI / 2;
|
||||
const cos = Math.cos(angle) * 16 * scale;
|
||||
const sin = Math.sin(angle) * 16 * scale;
|
||||
@@ -121,18 +121,18 @@ function flowing_top(heights: number[], flow_x: number, flow_z: number, scale: n
|
||||
return { face: 0, positions, uvs, still: false };
|
||||
}
|
||||
|
||||
// the quads of the liquid in the middle cell. above and below are the cells over and under it: whether they're the
|
||||
// same liquid, and whether they're solid. flowing_scale is for a liquid with a flowing texture of its own, how much of
|
||||
// the quads of the fluid in the middle cell. above and below are the cells over and under it: whether they're the
|
||||
// same fluid, and whether they're solid. flowing_scale is for a fluid with a flowing texture of its own, how much of
|
||||
// it a block shows, so it's as sharp as the still one (a 32×32 one next to a 16×16 still one shows half, like
|
||||
// minecraft's water). with it, the sides show that much and a sloping top flows. without, the sides show all of the
|
||||
// texture and the top is always still
|
||||
export function liquid_quads(
|
||||
cells: LiquidCell[],
|
||||
export function fluid_quads(
|
||||
cells: FluidCell[],
|
||||
above: { same: boolean; solid: boolean },
|
||||
below: { same: boolean; solid: boolean },
|
||||
flowing_scale?: number,
|
||||
): LiquidQuad[] {
|
||||
const quads: LiquidQuad[] = [];
|
||||
): FluidQuad[] {
|
||||
const quads: FluidQuad[] = [];
|
||||
// by corner, x then z
|
||||
const heights = [
|
||||
corner_height(cells, 0, 0),
|
||||
@@ -152,7 +152,7 @@ export function liquid_quads(
|
||||
if (top) return above.same ? 1 : height(x, z);
|
||||
return neighbor.same ? height(x, z) : 0;
|
||||
}, flowing_scale);
|
||||
// a side with no height, where the liquid next to it is level with it
|
||||
// a side with no height, where the fluid next to it is level with it
|
||||
const p = side.positions;
|
||||
if (p[1] === p[4] && p[4] === p[7] && p[7] === p[10]) return;
|
||||
quads.push(side);
|
||||
@@ -4,12 +4,10 @@
|
||||
// block models, in the shape of minecraft's block model json: boxes ("elements") with a texture per face.
|
||||
// a block picks one with "model" and fills in its texture variables with "textures". baking turns a model
|
||||
// into quads in block space (0 to 1) that the chunk mesher and the item renderers draw
|
||||
import { type BlockRegistry, type BlockTextures, liquid_textures } from "./everything_registry.ts";
|
||||
import { tint_without_biome } from "./worldgen/biome_colors.ts";
|
||||
import { type BlockRegistry, type BlockTextures, fluid_textures } from "./everything_registry.ts";
|
||||
import { color_rgb, tint_without_biome } from "./worldgen/biome_colors.ts";
|
||||
import { get_state_value } from "./utils.ts";
|
||||
|
||||
export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east";
|
||||
export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"];
|
||||
import { type DisplayContext, MODEL_FACES, type ModelFace } from "./mod_data.ts";
|
||||
|
||||
export interface ModelFaceJson {
|
||||
// a texture variable like "#side", or a texture id
|
||||
@@ -47,9 +45,6 @@ export interface DisplayTransform {
|
||||
scale?: [number, number, number];
|
||||
}
|
||||
|
||||
// where items are shown: in slots, held in first person, dropped, and on blocks with item_display
|
||||
export const DISPLAY_CONTEXTS = ["gui", "firstperson_righthand", "ground", "fixed"] as const;
|
||||
export type DisplayContext = typeof DISPLAY_CONTEXTS[number];
|
||||
export type ModelDisplay = Partial<Record<DisplayContext, DisplayTransform>>;
|
||||
|
||||
// a model as a mod writes it in models/. it can start from a parent, like minecraft's: it gets the parent's elements
|
||||
@@ -370,12 +365,12 @@ export function cube_face_texture(block: BlockRegistry, face: "top" | "bottom" |
|
||||
return resolve_texture(`#${face}`, cube_textures(block), BUILTIN_MODELS[DEFAULT_MODEL]);
|
||||
}
|
||||
|
||||
// the block's textures as engine:cube's. a liquid's { still, flowing } are its top and bottom, and its sides, for its
|
||||
// item and its particles. the chunk mesher draws liquids itself
|
||||
// the block's textures as engine:cube's. a fluid's { still, flowing } are its top and bottom, and its sides, for its
|
||||
// item and its particles. the chunk mesher draws fluids itself
|
||||
export function cube_textures(block: BlockRegistry): BlockTextures {
|
||||
if (!block.liquid) return block.textures;
|
||||
if (!block.fluid) return block.textures;
|
||||
// through the variables, so a "tint" on still or flowing still finds them
|
||||
return { ...liquid_textures(block.textures), top: "#still", bottom: "#still", side: "#flowing" };
|
||||
return { ...fluid_textures(block.textures), top: "#still", bottom: "#still", side: "#flowing" };
|
||||
}
|
||||
|
||||
// the color to draw a face of a block's item in, as r g b from 0 to 1. items aren't in a biome, so a biome "tint"
|
||||
@@ -387,8 +382,7 @@ export function cube_face_tint(block: BlockRegistry, face: "top" | "bottom" | "f
|
||||
// the color to draw a part of a block's item in that got its texture through these variables, see cube_face_tint
|
||||
export function item_tint(block: BlockRegistry, variables: string[]): number[] {
|
||||
if (!is_tinted(block, variables)) return [1, 1, 1];
|
||||
const color = tint_without_biome(block.tint!.color);
|
||||
return [color >> 16, (color >> 8) & 0xff, color & 0xff].map((c) => c / 255);
|
||||
return color_rgb(tint_without_biome(block.tint!.color));
|
||||
}
|
||||
|
||||
// how much darker each side of an item's model is drawn, like the mesher's: top, bottom, south, north, west, east
|
||||
|
||||
@@ -11,8 +11,7 @@ import {
|
||||
type EffectJson,
|
||||
type EntityJson,
|
||||
type EntityModelJson,
|
||||
ID_PATTERN,
|
||||
is_object,
|
||||
type FluidJson,
|
||||
type ItemJson,
|
||||
type ManifestJson,
|
||||
type OreJson,
|
||||
@@ -23,6 +22,7 @@ import {
|
||||
validate_effect,
|
||||
validate_entity,
|
||||
validate_entity_model,
|
||||
validate_fluid,
|
||||
validate_item,
|
||||
validate_manifest,
|
||||
validate_model,
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
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";
|
||||
@@ -80,8 +81,8 @@ export class BmodError extends Error {
|
||||
|
||||
// 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, and the mod's config
|
||||
// data.json every block, model, item, recipe, ore, entity, entity model, effect, fluid, tag, loot
|
||||
// table and biome, and the mod's config
|
||||
// scripts/<side>.js
|
||||
// textures/<name>.png the texture <mod id>:<name>
|
||||
// textures/<name>.json its animation, if it has one
|
||||
@@ -178,6 +179,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
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[],
|
||||
@@ -207,7 +209,15 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
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];
|
||||
const registered = [
|
||||
...data.blocks,
|
||||
...data.models,
|
||||
...data.items,
|
||||
...data.entities,
|
||||
...data.entity_models,
|
||||
...data.effects,
|
||||
...data.fluids,
|
||||
];
|
||||
const worldgen = [
|
||||
...data.noises!,
|
||||
...data.density_functions!,
|
||||
@@ -215,7 +225,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
|
||||
...data.biome_sources!,
|
||||
...data.features!,
|
||||
];
|
||||
for (const { id } of [...registered, ...data.effects, ...data.loot_tables!, ...data.biomes!, ...worldgen]) {
|
||||
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`);
|
||||
}
|
||||
|
||||
|
||||
@@ -333,6 +333,20 @@ export function greedy_string(): ArgumentType<string> {
|
||||
return { greedy: true, parse: (text) => text };
|
||||
}
|
||||
|
||||
// a json value, the rest of the line so it can have spaces, like an item's data
|
||||
export function json(): ArgumentType<unknown> {
|
||||
return {
|
||||
greedy: true,
|
||||
parse(text) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new CommandError(`${text} isn't JSON`);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// one of a few words, suggested
|
||||
export function choice<T extends string>(options: readonly T[]): ArgumentType<T> {
|
||||
return {
|
||||
@@ -376,3 +390,7 @@ export function item(): ArgumentType<string> {
|
||||
export function block(): ArgumentType<string> {
|
||||
return registry_id("blocks", "block");
|
||||
}
|
||||
|
||||
export function fluid(): ArgumentType<string> {
|
||||
return registry_id("fluids", "fluid");
|
||||
}
|
||||
|
||||
@@ -160,20 +160,20 @@ export interface BlockRegistry {
|
||||
// draws the item a server script gives it (ServerWorld.set_block_item) on top of it, like farmer's delight's
|
||||
// cutting board. surface is the height in pixels it lies on. turned with the variant's y
|
||||
item_display?: { surface: number };
|
||||
// a liquid like water, drawn like luanti's: its top slopes down towards where it flows. see LiquidProperties
|
||||
liquid?: LiquidProperties;
|
||||
// the liquid it can hold, like minecraft's waterlogged fences. it gets a "waterlogged" state, see WATERLOGGED
|
||||
// a fluid like water, drawn like luanti's: its top slopes down towards where it flows. see FluidProperties
|
||||
fluid?: FluidProperties;
|
||||
// the fluid it can hold, like minecraft's waterlogged fences. it gets a "waterlogged" state, see WATERLOGGED
|
||||
waterloggable?: string;
|
||||
// it can only be placed into a source of that liquid, so it's always placed holding it, like farmer's delight's rice
|
||||
// it can only be placed into a source of that fluid, so it's always placed holding it, like farmer's delight's rice
|
||||
waterlogged_only?: boolean;
|
||||
|
||||
compiled_states?: CompiledStateDefinition[];
|
||||
}
|
||||
|
||||
// a liquid's "level" state is 0 for a source, the full block, and 1 to range as it flows away from one, each lower,
|
||||
// like minecraft's. liquids get that state without listing it. their textures are one texture, or { still, flowing }:
|
||||
// a fluid's "level" state is 0 for a source, the full block, and 1 to range as it flows away from one, each lower,
|
||||
// like minecraft's. fluids get that state without listing it. their textures are one texture, or { still, flowing }:
|
||||
// still on the top and bottom, flowing on the sides, like luanti's special tiles
|
||||
export interface LiquidProperties {
|
||||
export interface FluidProperties {
|
||||
// how many blocks it flows from a source, 1 to 7, like luanti's liquid_range
|
||||
range: number;
|
||||
// ticks between each step it flows, like minecraft's 5 for water and 30 for lava
|
||||
@@ -183,28 +183,28 @@ export interface LiquidProperties {
|
||||
renewable: boolean;
|
||||
}
|
||||
|
||||
export const LIQUID_LEVEL: BlockStateDefinition = { name: "level", bits: 3, default: 0 };
|
||||
// a waterloggable block's state, 1 while it holds a source of its liquid. blocks get it without listing it, after
|
||||
export const FLUID_LEVEL: BlockStateDefinition = { name: "level", bits: 3, default: 0 };
|
||||
// a waterloggable block's state, 1 while it holds a source of its fluid. blocks get it without listing it, after
|
||||
// their own states
|
||||
export const WATERLOGGED: BlockStateDefinition = { name: "waterlogged", bits: 1, default: 0 };
|
||||
export const MAX_LIQUID_RANGE = 7;
|
||||
// what a liquid that doesn't say has
|
||||
export const LIQUID_DEFAULTS: LiquidProperties = { range: MAX_LIQUID_RANGE, ticks: 5, renewable: true };
|
||||
export const MAX_FLUID_RANGE = 7;
|
||||
// what a fluid that doesn't say has
|
||||
export const FLUID_DEFAULTS: FluidProperties = { range: MAX_FLUID_RANGE, ticks: 5, renewable: true };
|
||||
|
||||
// what entities swim in, and where falling doesn't hurt
|
||||
export function is_liquid_block(block: BlockRegistry | undefined): boolean {
|
||||
return block?.liquid !== undefined;
|
||||
export function is_fluid_block(block: BlockRegistry | undefined): boolean {
|
||||
return block?.fluid !== undefined;
|
||||
}
|
||||
|
||||
// a liquid's textures as the top, bottom and sides of a cube, for its item and its particles
|
||||
export function liquid_textures(textures: BlockTextures): { still: string; flowing: string } {
|
||||
// a fluid's textures as the top, bottom and sides of a cube, for its item and its particles
|
||||
export function fluid_textures(textures: BlockTextures): { still: string; flowing: string } {
|
||||
if (typeof textures === "string") return { still: textures, flowing: textures };
|
||||
const still = textures.still ?? "engine:missing";
|
||||
return { still, flowing: textures.flowing ?? still };
|
||||
}
|
||||
|
||||
// how high a liquid's surface is in a block of it at this level, 0 to 1, like luanti's flowing levels
|
||||
export function liquid_height(level: number, range: number) {
|
||||
// how high a fluid's surface is in a block of it at this level, 0 to 1, like luanti's flowing levels
|
||||
export function fluid_height(level: number, range: number) {
|
||||
if (level === 0) return 1;
|
||||
return (range - Math.min(level, range) + 0.5) / range;
|
||||
}
|
||||
@@ -247,6 +247,23 @@ export interface FoodProperties {
|
||||
returns?: string;
|
||||
}
|
||||
|
||||
// an item that holds one fluid, full or empty, like a bucket. a full one's stack data is { fluid: FluidVariant }, see
|
||||
// docs/modding/resources/fluids.md. what it looks like full is a layer tinted "fluid"
|
||||
export interface FluidContainerProperties {
|
||||
// how much a full one holds, in mB
|
||||
capacity: number;
|
||||
// how many full ones fit in a slot, the item's max_stack when not set
|
||||
full_max_stack?: number;
|
||||
}
|
||||
|
||||
// a texture drawn over a flat item's own, like the fluid in a bucket, drawn in its tint's color: a block tint's color
|
||||
// outside any biome, or "fluid" for the fluid a fluid container holds. a layer whose tint has no color for a stack, like
|
||||
// "fluid" on an empty container, isn't drawn
|
||||
export interface ItemLayer {
|
||||
texture: string;
|
||||
tint?: TintColor | "fluid";
|
||||
}
|
||||
|
||||
export interface ItemRegistry<T = unknown | undefined> {
|
||||
texture_id: string | ((item: ItemStack<T>) => string);
|
||||
// shown in place of texture_id while the stack's data has that key set, like a cast fishing rod. the first wins
|
||||
@@ -264,9 +281,12 @@ export interface ItemRegistry<T = unknown | undefined> {
|
||||
lore?: string;
|
||||
food?: FoodProperties;
|
||||
worn?: WornProperties;
|
||||
// whether players holding it aim at liquids, like buckets and fishing rods. others look through them, so they can
|
||||
// whether players holding it aim at fluids, like buckets and fishing rods. others look through them, so they can
|
||||
// break and place blocks under water
|
||||
targets_liquids?: boolean;
|
||||
targets_fluids?: boolean;
|
||||
fluid_container?: FluidContainerProperties;
|
||||
// drawn over its texture in order, see ItemLayer
|
||||
layers?: ItemLayer[];
|
||||
components?: Record<string, unknown>;
|
||||
|
||||
on_create?(item: ItemStack<T>): void;
|
||||
|
||||
@@ -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,6 +2,9 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import type { FluidVariant } from "./mod_api/shared.ts";
|
||||
import { is_object } from "./schema.ts";
|
||||
import { same_data } from "./utils.ts";
|
||||
|
||||
// how item stacks are saved and sent over the network
|
||||
export interface ItemData {
|
||||
@@ -12,25 +15,53 @@ export interface ItemData {
|
||||
lore?: string;
|
||||
}
|
||||
|
||||
// whether two stacks are of one thing and can be one stack, like minecraft's isSameItemSameComponents: the same item,
|
||||
// and the same data whatever order its keys are in
|
||||
export function same_stack(a: ItemStack, b: ItemStack): boolean {
|
||||
return a.type_id === b.type_id && same_data(a.data, b.data);
|
||||
}
|
||||
|
||||
// how many fit in one slot: the item's max_stack, 1 for tools and 64 for everything else when it has none, and a full
|
||||
// fluid container's full_max_stack
|
||||
export function max_stack(id: string, data?: unknown): number {
|
||||
const item = EverythingRegistry.get<ItemRegistry>("items", id);
|
||||
const max = item?.max_stack ?? (item?.tool ? 1 : 64);
|
||||
return contained_fluid(id, data) ? item!.fluid_container!.full_max_stack ?? max : max;
|
||||
}
|
||||
|
||||
// the fluid a fluid container's stack holds, undefined for an empty one or an item that isn't a container. one of a
|
||||
// fluid no mod defines anymore is empty
|
||||
export function contained_fluid(id: string, data?: unknown): FluidVariant | undefined {
|
||||
if (!EverythingRegistry.get<ItemRegistry>("items", id)?.fluid_container || !is_object(data)) return undefined;
|
||||
const fluid = data.fluid;
|
||||
if (!is_object(fluid) || typeof fluid.id !== "string" || !EverythingRegistry.get("fluids", fluid.id)) {
|
||||
return undefined;
|
||||
}
|
||||
return fluid as unknown as FluidVariant;
|
||||
}
|
||||
|
||||
export class ItemStack<T = unknown | undefined> {
|
||||
type_id: string;
|
||||
amount: number;
|
||||
max_amount: number;
|
||||
data?: T;
|
||||
// on clients, the lore the server's scripts gave it when it was last synced
|
||||
lore?: string;
|
||||
|
||||
constructor(type_id: string | string, amount: number = 1, max_amount?: number) {
|
||||
constructor(type_id: string | string, amount: number = 1) {
|
||||
const item_info = EverythingRegistry.get<ItemRegistry>("items", type_id);
|
||||
this.type_id = type_id;
|
||||
this.amount = amount;
|
||||
this.max_amount = max_amount ?? item_info?.max_stack ?? (item_info?.tool ? 1 : 64);
|
||||
this.data = undefined;
|
||||
if (item_info?.on_create) {
|
||||
item_info.on_create(this);
|
||||
}
|
||||
}
|
||||
|
||||
// from its data each time, since scripts change that, like filling a bucket
|
||||
get max_amount(): number {
|
||||
return max_stack(this.type_id, this.data);
|
||||
}
|
||||
|
||||
// what's left of a tool's durability, its max minus the damage kept in its data. undefined for non tools
|
||||
durability(): number | undefined {
|
||||
const tool = EverythingRegistry.get<ItemRegistry>("items", this.type_id)?.tool;
|
||||
@@ -50,7 +81,7 @@ export class ItemStack<T = unknown | undefined> {
|
||||
}
|
||||
|
||||
clone(): ItemStack {
|
||||
const item = new ItemStack(this.type_id, this.amount, this.max_amount);
|
||||
const item = new ItemStack(this.type_id, this.amount);
|
||||
item.data = structuredClone(this.data);
|
||||
item.lore = this.lore;
|
||||
return item;
|
||||
@@ -143,7 +174,7 @@ export class Container {
|
||||
add_item(item_stack: ItemStack): number {
|
||||
for (const slot of this.#slots.filter((slot) => slot.has_item())) {
|
||||
const slot_item = slot.get_item()!;
|
||||
if (slot_item.type_id === item_stack.type_id) {
|
||||
if (same_stack(slot_item, item_stack)) {
|
||||
const missing = slot_item.max_amount - slot_item.amount;
|
||||
const adding = Math.min(missing, item_stack.amount);
|
||||
slot_item.amount += adding;
|
||||
@@ -240,7 +271,7 @@ function left_click(container: Container, index: number, cursor: Cursor, limit:
|
||||
|
||||
// if you are holding something and slot type equals holding type
|
||||
// try to add to stack
|
||||
if (slot_item && slot.type_id === holding.type_id) {
|
||||
if (slot_item && same_stack(slot_item, holding)) {
|
||||
const space_left = Math.min(slot.max_amount!, limit) - slot_item.amount;
|
||||
const amount_to_add = Math.max(0, Math.min(space_left, holding.amount));
|
||||
|
||||
@@ -275,7 +306,7 @@ function right_click(container: Container, index: number, cursor: Cursor, limit:
|
||||
if (holding) {
|
||||
// and slot type equals holding type
|
||||
// add 1 to matching stack
|
||||
if (slot_item && slot.type_id === holding.type_id) {
|
||||
if (slot_item && same_stack(slot_item, holding)) {
|
||||
if (slot_item.amount < Math.min(slot_item.max_amount, limit)) {
|
||||
slot_item.amount += 1;
|
||||
holding.amount -= 1;
|
||||
@@ -333,7 +364,7 @@ export function move_into(item: ItemStack, slots: SlotRef[], accepts: (slot: Slo
|
||||
for (const slot of slots) {
|
||||
const there = slot.container.get_item(slot.index);
|
||||
if (item.amount <= 0) return;
|
||||
if (there && there !== item && there.type_id === item.type_id && accepts(slot)) {
|
||||
if (there && there !== item && same_stack(there, item) && accepts(slot)) {
|
||||
const moving = Math.max(0, Math.min(slot_cap(slot, there) - there.amount, item.amount));
|
||||
there.amount += moving;
|
||||
item.amount -= moving;
|
||||
@@ -357,7 +388,7 @@ export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: Slot
|
||||
const there = slot.container.get_item(slot.index);
|
||||
if (!accepts(slot)) continue;
|
||||
if (!there) room += slot_cap(slot, item);
|
||||
else if (there.type_id === item.type_id) room += Math.max(0, slot_cap(slot, there) - there.amount);
|
||||
else if (same_stack(there, item)) room += Math.max(0, slot_cap(slot, there) - there.amount);
|
||||
}
|
||||
return room;
|
||||
}
|
||||
@@ -365,7 +396,7 @@ export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: Slot
|
||||
// whether take_output would take it
|
||||
export function can_take_output(item: ItemStack, cursor: Cursor): boolean {
|
||||
const holding = cursor.item;
|
||||
return !holding || (holding.type_id === item.type_id && holding.max_amount - holding.amount >= item.amount);
|
||||
return !holding || (same_stack(holding, item) && holding.max_amount - holding.amount >= item.amount);
|
||||
}
|
||||
|
||||
// output slots (furnace result, crafting result) can only be taken from, all at once
|
||||
@@ -376,7 +407,7 @@ export function take_output(item: ItemStack, cursor: Cursor): boolean {
|
||||
cursor.item = item.clone();
|
||||
return true;
|
||||
}
|
||||
if (holding.type_id === item.type_id && holding.max_amount - holding.amount >= item.amount) {
|
||||
if (same_stack(holding, item) && holding.max_amount - holding.amount >= item.amount) {
|
||||
holding.amount += item.amount;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,9 +6,19 @@
|
||||
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
|
||||
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace.
|
||||
// see docs/modding/resources/loot_tables.md
|
||||
import * as z from "zod";
|
||||
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
|
||||
import { list_matches, Tags } from "./tags.ts";
|
||||
import { is_object, TAG_ID_PATTERN } from "./mod_data.ts";
|
||||
import {
|
||||
by_kind,
|
||||
find_problems,
|
||||
id,
|
||||
id_or_tag,
|
||||
json_object,
|
||||
loot_table_id,
|
||||
type Problems,
|
||||
TAG_ID_PATTERN,
|
||||
} from "./schema.ts";
|
||||
|
||||
// a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's
|
||||
// constant, uniform and binomial number providers
|
||||
@@ -87,17 +97,6 @@ export interface LootEnvironment<C extends BaseLootContext> {
|
||||
random?: () => number;
|
||||
}
|
||||
|
||||
export const LOOT_CONDITIONS = [
|
||||
"random_chance",
|
||||
"match_tool",
|
||||
"block_state",
|
||||
"killed_by_player",
|
||||
"inverted",
|
||||
"any_of",
|
||||
"all_of",
|
||||
] as const;
|
||||
export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const;
|
||||
const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"];
|
||||
// tables in tables in tables: past this it's taken as a loop and gives nothing more
|
||||
const MAX_DEPTH = 16;
|
||||
|
||||
@@ -263,155 +262,105 @@ function apply<C extends BaseLootContext>(
|
||||
|
||||
// checking a table's json
|
||||
|
||||
type Problems = string[];
|
||||
const whole = z.int().min(0);
|
||||
|
||||
const number_provider: z.ZodType<NumberProvider> = z.union([
|
||||
whole,
|
||||
z.object({ min: whole, max: whole }).refine(({ min, max }) => min <= max, {
|
||||
path: ["max"],
|
||||
message: "can't be below min",
|
||||
}),
|
||||
z.object({ n: whole, p: z.number().min(0).max(1) }),
|
||||
], "must be a whole number, { min, max } or { n, p }");
|
||||
|
||||
const conditions = z.array(z.lazy(() => loot_condition));
|
||||
|
||||
// the engine's conditions, by name
|
||||
const CONDITIONS = new Map<string, z.ZodType>([
|
||||
["random_chance", z.object({ chance: z.number().min(0).max(1) })],
|
||||
[
|
||||
"match_tool",
|
||||
z.object({ items: z.array(id_or_tag).optional(), tool: z.string().optional(), min_tier: z.int().optional() }),
|
||||
],
|
||||
[
|
||||
"block_state",
|
||||
z.object({
|
||||
block: id.optional(),
|
||||
states: z.record(
|
||||
z.string(),
|
||||
z.union(
|
||||
[z.int(), z.object({ min: z.int().optional(), max: z.int().optional() })],
|
||||
'must be a number or { min, max }, like { "age": 7 }',
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
["killed_by_player", z.object({})],
|
||||
["inverted", z.object({ term: z.lazy(() => loot_condition) })],
|
||||
["any_of", z.object({ terms: conditions })],
|
||||
["all_of", z.object({ terms: conditions })],
|
||||
]);
|
||||
|
||||
// any other condition is a mod's own, by its id. the server checks a script registered it when it starts
|
||||
const loot_condition: z.ZodType<LootCondition> = by_kind(
|
||||
"condition",
|
||||
(name) => CONDITIONS.get(name) ?? (name.includes(":") ? json_object : undefined),
|
||||
`must be one of ${[...CONDITIONS.keys()].join(", ")}, or a mod's own condition's id`,
|
||||
);
|
||||
|
||||
// every function can have conditions
|
||||
const loot_function_base = z.object({ conditions: conditions.optional() });
|
||||
|
||||
// the engine's functions, by name
|
||||
const FUNCTIONS = new Map<string, z.ZodType>([
|
||||
["set_count", loot_function_base.extend({ count: number_provider, add: z.boolean().optional() })],
|
||||
["limit_count", loot_function_base.extend({ min: z.int().optional(), max: z.int().optional() })],
|
||||
["set_data", loot_function_base.extend({ data: z.unknown() })],
|
||||
]);
|
||||
|
||||
// any other function is a mod's own, like conditions
|
||||
const loot_function: z.ZodType<LootFunction> = by_kind(
|
||||
"function",
|
||||
(name) => FUNCTIONS.get(name) ?? (name.includes(":") ? loot_function_base : undefined),
|
||||
`must be one of ${[...FUNCTIONS.keys()].join(", ")}, or a mod's own function's id`,
|
||||
);
|
||||
|
||||
const functions = z.array(loot_function);
|
||||
|
||||
// every entry can have these
|
||||
const loot_entry_base = z.object({
|
||||
weight: z.number().min(0).optional(),
|
||||
conditions: conditions.optional(),
|
||||
functions: functions.optional(),
|
||||
});
|
||||
|
||||
const loot_entry: z.ZodType<LootEntry> = z.discriminatedUnion("type", [
|
||||
loot_entry_base.extend({ type: z.literal("item").optional(), item: id, count: number_provider.optional() }),
|
||||
loot_entry_base.extend({
|
||||
type: z.literal("tag"),
|
||||
tag: z.string('must be a #tag, like "#bworld:logs"').refine((tag) =>
|
||||
tag.startsWith("#") && TAG_ID_PATTERN.test(tag.slice(1))
|
||||
),
|
||||
count: number_provider.optional(),
|
||||
}),
|
||||
loot_entry_base.extend({ type: z.literal("loot_table"), table: loot_table_id }),
|
||||
loot_entry_base.extend({ type: z.literal("empty") }),
|
||||
]);
|
||||
|
||||
const loot_table_schema: z.ZodType<LootTableJson> = z.object({
|
||||
id: z.string("its file name must be a-z, 0-9 and _, in folders").regex(TAG_ID_PATTERN),
|
||||
pools: z.array(z.object({
|
||||
rolls: number_provider.optional(),
|
||||
conditions: conditions.optional(),
|
||||
entries: z.array(loot_entry).min(1),
|
||||
functions: functions.optional(),
|
||||
})),
|
||||
conditions: conditions.optional(),
|
||||
functions: functions.optional(),
|
||||
});
|
||||
|
||||
export function validate_loot_table(json: unknown): Problems {
|
||||
if (!is_object(json)) return ["loot_table must be an object"];
|
||||
const problems: Problems = [];
|
||||
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
|
||||
problems.push("its file name must be a-z, 0-9 and _, in folders");
|
||||
}
|
||||
problems.push(...validate_conditions(json.conditions, "conditions"));
|
||||
problems.push(...validate_functions(json.functions, "functions"));
|
||||
if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"];
|
||||
json.pools.forEach((pool, i) => {
|
||||
const where = `pools[${i}]`;
|
||||
if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`);
|
||||
if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`));
|
||||
problems.push(...validate_conditions(pool.conditions, `${where}.conditions`));
|
||||
problems.push(...validate_functions(pool.functions, `${where}.functions`));
|
||||
if (!Array.isArray(pool.entries) || pool.entries.length === 0) {
|
||||
return problems.push(`${where}.entries must be a list of entries`);
|
||||
}
|
||||
pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`)));
|
||||
});
|
||||
return problems;
|
||||
}
|
||||
|
||||
function validate_entry(entry: unknown, where: string): Problems {
|
||||
if (!is_object(entry)) return [`${where} must be { type, item, weight }`];
|
||||
const problems: Problems = [];
|
||||
const type = entry.type ?? "item";
|
||||
if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) {
|
||||
problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`);
|
||||
}
|
||||
const field = { item: "item", tag: "tag", loot_table: "table" }[type as string];
|
||||
if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`);
|
||||
if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) {
|
||||
problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`);
|
||||
}
|
||||
if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`));
|
||||
if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) {
|
||||
problems.push(`${where}.weight must be a number, 0 or more`);
|
||||
}
|
||||
problems.push(...validate_conditions(entry.conditions, `${where}.conditions`));
|
||||
problems.push(...validate_functions(entry.functions, `${where}.functions`));
|
||||
return problems;
|
||||
}
|
||||
|
||||
export function validate_number(value: unknown, where: string): Problems {
|
||||
const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0;
|
||||
if (whole(value)) return [];
|
||||
if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) {
|
||||
return [];
|
||||
}
|
||||
if (
|
||||
is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1
|
||||
) return [];
|
||||
return [`${where} must be a whole number, { min, max } or { n, p }`];
|
||||
}
|
||||
|
||||
function validate_conditions(list: unknown, where: string): Problems {
|
||||
if (list === undefined) return [];
|
||||
if (!Array.isArray(list)) return [`${where} must be a list`];
|
||||
return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`));
|
||||
}
|
||||
|
||||
function validate_condition(condition: unknown, where: string): Problems {
|
||||
if (!is_object(condition) || typeof condition.condition !== "string") {
|
||||
return [`${where} must be { "condition": ... }`];
|
||||
}
|
||||
const name = condition.condition;
|
||||
switch (name) {
|
||||
case "random_chance": {
|
||||
const chance = condition.chance;
|
||||
return typeof chance === "number" && chance >= 0 && chance <= 1
|
||||
? []
|
||||
: [`${where}.chance must be from 0 to 1`];
|
||||
}
|
||||
case "match_tool": {
|
||||
const problems: Problems = [];
|
||||
const items = condition.items;
|
||||
if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) {
|
||||
problems.push(`${where}.items must be a list of item ids and #tags`);
|
||||
}
|
||||
if (condition.tool !== undefined && typeof condition.tool !== "string") {
|
||||
problems.push(`${where}.tool must be a tool type, like "axe"`);
|
||||
}
|
||||
if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) {
|
||||
problems.push(`${where}.min_tier must be a whole number`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
case "block_state": {
|
||||
const states = condition.states;
|
||||
const ok = is_object(states) && Object.values(states).every((match) =>
|
||||
Number.isInteger(match) ||
|
||||
(is_object(match) && (match.min === undefined || Number.isInteger(match.min)) &&
|
||||
(match.max === undefined || Number.isInteger(match.max)))
|
||||
);
|
||||
return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`];
|
||||
}
|
||||
case "killed_by_player":
|
||||
return [];
|
||||
case "inverted":
|
||||
return validate_condition(condition.term, `${where}.term`);
|
||||
case "any_of":
|
||||
case "all_of":
|
||||
return Array.isArray(condition.terms)
|
||||
? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`))
|
||||
: [`${where}.terms must be a list of conditions`];
|
||||
}
|
||||
return name.includes(":") ? [] : [
|
||||
`${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`,
|
||||
];
|
||||
}
|
||||
|
||||
function validate_functions(list: unknown, where: string): Problems {
|
||||
if (list === undefined) return [];
|
||||
if (!Array.isArray(list)) return [`${where} must be a list`];
|
||||
return list.flatMap((fn, i) => {
|
||||
const at = `${where}[${i}]`;
|
||||
if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`];
|
||||
const problems = validate_conditions(fn.conditions, `${at}.conditions`);
|
||||
switch (fn.function) {
|
||||
case "set_count":
|
||||
problems.push(...validate_number(fn.count, `${at}.count`));
|
||||
if (fn.add !== undefined && typeof fn.add !== "boolean") {
|
||||
problems.push(`${at}.add must be true or false`);
|
||||
}
|
||||
break;
|
||||
case "limit_count":
|
||||
for (const key of ["min", "max"]) {
|
||||
if (fn[key] !== undefined && !Number.isInteger(fn[key])) {
|
||||
problems.push(`${at}.${key} must be a whole number`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "set_data":
|
||||
if (fn.data === undefined) problems.push(`${at}.data is needed`);
|
||||
break;
|
||||
default:
|
||||
if (!fn.function.includes(":")) {
|
||||
problems.push(
|
||||
`${at}: ${fn.function} isn't a loot function. the engine's are ${
|
||||
LOOT_FUNCTIONS.join(", ")
|
||||
}, a mod's has its id`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
});
|
||||
return find_problems(loot_table_schema, json);
|
||||
}
|
||||
|
||||
// what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions
|
||||
|
||||
@@ -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, FluidVariant, 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: {
|
||||
@@ -119,6 +132,11 @@ export interface Instances {
|
||||
transformed(model?: ModelRef): TransformedInstance;
|
||||
// turning at a steady speed worked out from the time, so it never needs anything per frame
|
||||
rotating(model?: ModelRef): RotatingInstance;
|
||||
// one of an item, whatever the stack's count: the size it's drawn on the ground, with its middle at the middle of
|
||||
// the block, placed by a matrix like a transformed model. like a block entity renderer drawing an item
|
||||
item(stack: ItemStack): TransformedInstance;
|
||||
// a box of a fluid, its texture tinted in its color, see FluidInstance. it shows what's behind it
|
||||
fluid(fluid: FluidVariant): FluidInstance;
|
||||
}
|
||||
|
||||
export interface Instance {
|
||||
@@ -132,6 +150,13 @@ export interface TransformedInstance extends Instance {
|
||||
set_transform(matrix: ArrayLike<number>): void;
|
||||
}
|
||||
|
||||
// nothing is drawn until set_box is called
|
||||
export interface FluidInstance extends Instance {
|
||||
// from one corner to the other, in pixels like a model's elements: 0 to 16 across the block, past it for a box that
|
||||
// reaches into the blocks around, like a tank's. the texture is cut to fit, never stretched
|
||||
set_box(from: [number, number, number], to: [number, number, number]): void;
|
||||
}
|
||||
|
||||
export interface RotatingInstance extends Instance {
|
||||
// turns around axis through the middle of the block, counterclockwise seen from the axis's positive end when rpm
|
||||
// is positive, at time * rpm * 0.3 + offset degrees. still when not set
|
||||
|
||||
@@ -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;
|
||||
@@ -162,10 +176,13 @@ export interface CommandRegistry {
|
||||
boolean(): ArgumentType<boolean, CommandSource>;
|
||||
word(): ArgumentType<string, CommandSource>;
|
||||
greedy_string(): ArgumentType<string, CommandSource>;
|
||||
// a json value, the rest of the line like greedy_string
|
||||
json(): ArgumentType<unknown, CommandSource>;
|
||||
choice<T extends string>(options: readonly T[]): ArgumentType<T, CommandSource>;
|
||||
// an item or block id. without a namespace, whichever has that name
|
||||
// an item, block or fluid id. without a namespace, whichever has that name
|
||||
item(): ArgumentType<Id, CommandSource>;
|
||||
block(): ArgumentType<Id, CommandSource>;
|
||||
fluid(): ArgumentType<Id, CommandSource>;
|
||||
// an online player's name
|
||||
player(): ArgumentType<Player, CommandSource>;
|
||||
};
|
||||
@@ -301,9 +318,9 @@ export interface ServerWorld {
|
||||
// the first block on the line from one point to another, like minecraft's Level.clip. it hits what entities bump
|
||||
// into, so it goes through plants and other blocks without collision. undefined when nothing is in the way
|
||||
raycast(from: Position, to: Position, options?: RaycastOptions): RaycastHit | undefined;
|
||||
// which way the liquid at x y z flows, a vector 1 long, or 0 0 0 where it's still or there's none, like minecraft's
|
||||
// which way the fluid at x y z flows, a vector 1 long, or 0 0 0 where it's still or there's none, like minecraft's
|
||||
// FluidState.getFlow: toward lower cells of it beside it, and down where it falls. for what it pushes, like a wheel
|
||||
liquid_flow(x: number, y: number, z: number): Position;
|
||||
fluid_flow(x: number, y: number, z: number): Position;
|
||||
// whether the chunk the column is in was ever generated, so reading its blocks generates nothing. for code that
|
||||
// reaches far, like a walk along something long, which can stop at the rest: nobody has built anything there
|
||||
is_loaded(x: number, z: number): boolean;
|
||||
@@ -350,9 +367,9 @@ export interface BreakOptions {
|
||||
}
|
||||
|
||||
export interface RaycastOptions {
|
||||
// like minecraft's ClipContext.Fluid: "none" (the default) goes through liquids, "source_only" hits their sources
|
||||
// and goes through where they flow, "any" hits all of them. a liquid is hit at its surface
|
||||
liquids?: "none" | "source_only" | "any";
|
||||
// like minecraft's ClipContext.Fluid: "none" (the default) goes through fluids, "source_only" hits their sources
|
||||
// and goes through where they flow, "any" hits all of them. a fluid is hit at its surface
|
||||
fluids?: "none" | "source_only" | "any";
|
||||
}
|
||||
|
||||
export interface RaycastHit {
|
||||
@@ -407,6 +424,9 @@ export interface Player {
|
||||
readonly held_item: ItemStack | undefined;
|
||||
// what doesn't fit in the inventory drops at their feet
|
||||
give_item(id: Id, count?: number, data?: unknown): void;
|
||||
// one of the held item becomes result, like an empty bucket filling: straight into the hand when it was the last
|
||||
// one, into the inventory (or at their feet) when there are more
|
||||
exchange_held(result: ItemStack): void;
|
||||
send_message(text: string, options?: MessageOptions): void;
|
||||
// items drawn on them, under a key so each mod keeps its own list, like "bworld:curios". replaces what that key
|
||||
// had, [] clears it. only items whose json has worn show. not saved: set it again when they join
|
||||
@@ -511,8 +531,11 @@ export interface ItemApi {
|
||||
exists(id: Id): boolean;
|
||||
// every item, in load order
|
||||
ids(): Id[];
|
||||
// how many fit in one slot
|
||||
max_stack(id: Id): number;
|
||||
// how many fit in one slot, with this data: a full fluid container's can be fewer
|
||||
max_stack(id: Id, data?: unknown): number;
|
||||
// how much a fluid container holds when full, in mB, or undefined for an item that isn't one. see
|
||||
// docs/modding/resources/fluids.md
|
||||
fluid_capacity(id: Id): number | undefined;
|
||||
// the tool type it is, like "pickaxe" or "shovel", from the item's "tool"
|
||||
tool(id: Id): string | undefined;
|
||||
// what one of it sells for, from the item's "base_sell_value", or undefined if it can't be sold
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type EffectJson,
|
||||
type EntityJson,
|
||||
type EntityModelJson,
|
||||
type FluidJson,
|
||||
type ItemJson,
|
||||
type OreJson,
|
||||
type RecipeJson,
|
||||
@@ -58,6 +59,7 @@ export interface LoadedMod {
|
||||
entities: { file: string; json: EntityJson }[];
|
||||
entity_models: { file: string; json: EntityModelJson }[];
|
||||
effects: { file: string; json: EffectJson }[];
|
||||
fluids: { file: string; json: FluidJson }[];
|
||||
tags: { file: string; json: TagJson }[];
|
||||
loot_tables: { file: string; json: LootTableJson }[];
|
||||
biomes: { file: string; json: BiomeJson }[];
|
||||
@@ -88,6 +90,7 @@ export function mod_data(mod: LoadedMod): ModData {
|
||||
entities: mod.entities.map((e) => e.json),
|
||||
entity_models: mod.entity_models.map((m) => m.json),
|
||||
effects: mod.effects.map((e) => e.json),
|
||||
fluids: mod.fluids.map((f) => f.json),
|
||||
tags: mod.tags.map((t) => t.json),
|
||||
loot_tables: mod.loot_tables.map((t) => t.json),
|
||||
biomes: mod.biomes.map((b) => b.json),
|
||||
@@ -159,8 +162,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
const entity_model_owners = new Map<string, string[]>();
|
||||
const entity_model_jsons = new Map<string, EntityModelJson>();
|
||||
const effect_owners = new Map<string, string[]>();
|
||||
const fluid_owners = new Map<string, string[]>();
|
||||
const tag_owners = new Map<TagRegistry, Set<string>>();
|
||||
const liquids = new Set<string>();
|
||||
// blocks that flow, which waterloggable blocks can hold
|
||||
const fluid_blocks = new Set<string>();
|
||||
const loot_tables = new Set<string>();
|
||||
const biome_owners = new Map<string, string[]>();
|
||||
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
|
||||
@@ -181,7 +186,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
for (const { json } of mod.blocks) {
|
||||
add(block_owners, json.id, mod.id);
|
||||
if (json.item !== false) add(item_owners, json.id, mod.id);
|
||||
if (json.liquid) liquids.add(json.id);
|
||||
if (json.fluid) fluid_blocks.add(json.id);
|
||||
}
|
||||
// one without a texture is the item of the mod's block, which is already counted
|
||||
for (const { json } of mod.items) if (json.texture !== undefined) add(item_owners, json.id, mod.id);
|
||||
@@ -198,6 +203,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
entity_model_jsons.set(json.id, json);
|
||||
}
|
||||
for (const { json } of mod.effects) add(effect_owners, json.id, mod.id);
|
||||
for (const { json } of mod.fluids) add(fluid_owners, json.id, mod.id);
|
||||
for (const { json } of mod.loot_tables ?? []) loot_tables.add(json.id);
|
||||
for (const { json } of mod.biomes ?? []) add(biome_owners, json.id, mod.id);
|
||||
for (const { json } of mod.noises ?? []) add(worldgen_owners.noise, json.id, mod.id);
|
||||
@@ -279,8 +285,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
if (json.loot_table) uses(file, json.loot_table, "loot table");
|
||||
if (json.waterloggable) {
|
||||
uses(file, json.waterloggable, "block");
|
||||
if (block_owners.has(json.waterloggable) && !liquids.has(json.waterloggable)) {
|
||||
errors.push(`${file}: waterloggable ${json.waterloggable} isn't a liquid`);
|
||||
if (block_owners.has(json.waterloggable) && !fluid_blocks.has(json.waterloggable)) {
|
||||
errors.push(`${file}: waterloggable ${json.waterloggable} isn't a fluid`);
|
||||
}
|
||||
}
|
||||
for (const id of [...(json.place_on ?? []), ...(json.place_in ?? [])]) {
|
||||
@@ -317,6 +323,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
if (json.model) uses(file, json.model, "model");
|
||||
if (json.places) uses(file, json.places, "block");
|
||||
if (json.food?.returns) uses(file, json.food.returns, "item");
|
||||
for (const layer of json.layers ?? []) uses(file, layer.texture, "texture");
|
||||
if (json.layers && json.model) {
|
||||
errors.push(
|
||||
`${file}: item ${json.id} has a model, so it isn't drawn flat and its layers wouldn't show`,
|
||||
);
|
||||
}
|
||||
if (json.worn) {
|
||||
const { model, texture, slim_model, slim_texture } = json.worn;
|
||||
for (const id of [model, slim_model]) {
|
||||
@@ -406,12 +418,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
}
|
||||
for (const { file, json } of mod.noise_settings ?? []) {
|
||||
const refs = new_refs();
|
||||
noise_settings_refs(json as unknown as Record<string, unknown>, refs);
|
||||
noise_settings_refs(json, refs);
|
||||
check_worldgen("noise settings", file, json.id, refs);
|
||||
}
|
||||
for (const { file, json } of mod.biome_sources ?? []) {
|
||||
const refs = new_refs();
|
||||
biome_source_refs(json as unknown as Record<string, unknown>, refs);
|
||||
biome_source_refs(json, refs);
|
||||
check_worldgen("biome source", file, json.id, refs);
|
||||
// what its rules look at, in every generator that uses it
|
||||
const users = all_noise_settings.filter((settings) => settings.biome_source === (json.extends ?? json.id));
|
||||
@@ -474,6 +486,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
}
|
||||
if (json.icon !== undefined) uses(file, json.icon, "texture");
|
||||
}
|
||||
for (const { file, json } of mod.fluids) {
|
||||
if ((fluid_owners.get(json.id)?.length ?? 0) > 1) {
|
||||
errors.push(`${file}: fluid ${json.id} is also defined by ${fluid_owners.get(json.id)!.join(", ")}`);
|
||||
}
|
||||
if (json.texture !== undefined) uses(file, json.texture, "texture");
|
||||
}
|
||||
for (const { file, json } of mod.spawns) {
|
||||
check_namespace(file, json.entity);
|
||||
const entity = entity_jsons.get(json.entity);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
EffectJson,
|
||||
EntityJson,
|
||||
EntityModelJson,
|
||||
FluidJson,
|
||||
grid_recipe_from_json,
|
||||
GridRecipe,
|
||||
is_mod_recipe,
|
||||
@@ -45,6 +46,8 @@ export interface ModData {
|
||||
entity_models: EntityModelJson[];
|
||||
// status effects, see EffectJson
|
||||
effects: EffectJson[];
|
||||
// kinds of fluid, see FluidJson
|
||||
fluids: FluidJson[];
|
||||
// tag files, see common/tags.ts
|
||||
tags: TagJson[];
|
||||
// see common/loot.ts. missing from mods packed before there were loot tables
|
||||
@@ -103,8 +106,9 @@ export function is_registered(registry: TagRegistry, id: string): boolean {
|
||||
return (registry === "blocks" && id === "bworld:air") || EverythingRegistry.get(registry, id) !== undefined;
|
||||
}
|
||||
|
||||
// registers every mod's blocks, items, entities, effects, tags and recipes, in the order given (dependencies first). tags load
|
||||
// once every mod's content has, since a tag can hold anything, and recipes after them, since they can use tags
|
||||
// registers every mod's blocks, items, entities, effects, fluids, tags and recipes, in the order given (dependencies
|
||||
// first). tags load once every mod's content has, since a tag can hold anything, and recipes after them, since they can
|
||||
// use tags
|
||||
export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook {
|
||||
const recipes = new RecipeBook();
|
||||
|
||||
@@ -147,6 +151,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
|
||||
for (const json of data.effects) {
|
||||
EverythingRegistry.register<EffectJson>("effects", json.id, json);
|
||||
}
|
||||
for (const json of data.fluids) {
|
||||
EverythingRegistry.register<FluidJson>("fluids", json.id, json);
|
||||
}
|
||||
for (const json of data.loot_tables ?? []) {
|
||||
EverythingRegistry.register<LootTableJson>("loot_tables", json.id, json);
|
||||
}
|
||||
|
||||
@@ -231,39 +231,39 @@ function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision)
|
||||
return false;
|
||||
}
|
||||
|
||||
// in water like minecraft's wasTouchingWater, close enough: its feet or the middle of its box are in liquid
|
||||
export function in_water(body: Body, is_liquid: (x: number, y: number, z: number) => boolean): boolean {
|
||||
// in water like minecraft's wasTouchingWater, close enough: its feet or the middle of its box are in fluid
|
||||
export function in_water(body: Body, is_fluid: (x: number, y: number, z: number) => boolean): boolean {
|
||||
const x = Math.floor(body.x);
|
||||
const z = Math.floor(body.z);
|
||||
return is_liquid(x, Math.floor(body.y), z) || is_liquid(x, Math.floor(body.y + body.height / 2), z);
|
||||
return is_fluid(x, Math.floor(body.y), z) || is_fluid(x, Math.floor(body.y + body.height / 2), z);
|
||||
}
|
||||
|
||||
// its eyes are in liquid, so it can't breathe
|
||||
// its eyes are in fluid, so it can't breathe
|
||||
export function eyes_in_water(
|
||||
body: Body,
|
||||
eye_height: number,
|
||||
is_liquid: (x: number, y: number, z: number) => boolean,
|
||||
is_fluid: (x: number, y: number, z: number) => boolean,
|
||||
): boolean {
|
||||
return is_liquid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z));
|
||||
return is_fluid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z));
|
||||
}
|
||||
|
||||
// a liquid in a cell, for liquids pushing things along
|
||||
export interface LiquidInCell {
|
||||
// which liquid, its block's id. a liquid's flow only goes by cells of the same one
|
||||
// a fluid in a cell, for fluids pushing things along
|
||||
export interface FluidInCell {
|
||||
// which fluid, its block's id. a fluid's flow only goes by cells of the same one
|
||||
id: string;
|
||||
// its surface, 0 to 1 (see liquid_height), not counting more of it above
|
||||
// its surface, 0 to 1 (see fluid_height), not counting more of it above
|
||||
height: number;
|
||||
}
|
||||
|
||||
// the liquid in a cell, undefined for none
|
||||
export type LiquidAt = (x: number, y: number, z: number) => LiquidInCell | undefined;
|
||||
// the fluid in a cell, undefined for none
|
||||
export type FluidAt = (x: number, y: number, z: number) => FluidInCell | undefined;
|
||||
|
||||
const HORIZONTAL = [[1, 0], [-1, 0], [0, 1], [0, -1]];
|
||||
// blocks per second added each tick, minecraft's water 0.014 blocks per tick per tick
|
||||
const LIQUID_PUSH = 0.014 * 20;
|
||||
// moving slower than this sideways, a push is at least LIQUID_MIN_PUSH, so things still drift off flat-ish water
|
||||
const LIQUID_STILL_SPEED = 0.003 * 20;
|
||||
const LIQUID_MIN_PUSH = 0.0045 * 20;
|
||||
const FLUID_PUSH = 0.014 * 20;
|
||||
// moving slower than this sideways, a push is at least FLUID_MIN_PUSH, so things still drift off flat-ish water
|
||||
const FLUID_STILL_SPEED = 0.003 * 20;
|
||||
const FLUID_MIN_PUSH = 0.0045 * 20;
|
||||
|
||||
function blocks_motion(collision: boolean | Shape) {
|
||||
return shape_of(collision).length > 0;
|
||||
@@ -274,29 +274,29 @@ function normalized(x: number, y: number, z: number): [number, number, number] {
|
||||
return length < 1e-5 ? [0, 0, 0] : [x / length, y / length, z / length];
|
||||
}
|
||||
|
||||
// which way the liquid at x y z flows, a length 1 vector or nothing, like minecraft's FlowingFluid.getFlow: towards
|
||||
// which way the fluid at x y z flows, a length 1 vector or nothing, like minecraft's FlowingFluid.getFlow: towards
|
||||
// lower cells of it beside it, and towards drops where it pours over an edge. falling down a wall it goes down too
|
||||
export function liquid_flow(
|
||||
export function fluid_flow(
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
liquid_at: LiquidAt,
|
||||
fluid_at: FluidAt,
|
||||
is_solid: BlockCollision,
|
||||
): [number, number, number] {
|
||||
const here = liquid_at(x, y, z);
|
||||
const here = fluid_at(x, y, z);
|
||||
if (!here) return [0, 0, 0];
|
||||
let fx = 0;
|
||||
let fz = 0;
|
||||
for (const [dx, dz] of HORIZONTAL) {
|
||||
const neighbor = liquid_at(x + dx, y, z + dz);
|
||||
// another liquid doesn't change this one's flow
|
||||
const neighbor = fluid_at(x + dx, y, z + dz);
|
||||
// another fluid doesn't change this one's flow
|
||||
if (neighbor && neighbor.id !== here.id) continue;
|
||||
let drop = 0;
|
||||
if (neighbor) {
|
||||
drop = here.height - neighbor.height;
|
||||
} else if (!blocks_motion(is_solid(x + dx, y, z + dz))) {
|
||||
// an edge it pours over, onto more of itself
|
||||
const below = liquid_at(x + dx, y - 1, z + dz);
|
||||
const below = fluid_at(x + dx, y - 1, z + dz);
|
||||
if (below?.id === here.id) drop = here.height - (below.height - 1);
|
||||
}
|
||||
fx += dx * drop;
|
||||
@@ -306,7 +306,7 @@ export function liquid_flow(
|
||||
|
||||
// falling: flowing, not a source, with more of it above. a deep pool of sources isn't
|
||||
let fy = 0;
|
||||
if (here.height < 1 && liquid_at(x, y + 1, z)?.id === here.id) {
|
||||
if (here.height < 1 && fluid_at(x, y + 1, z)?.id === here.id) {
|
||||
const against_wall = HORIZONTAL.some(([dx, dz]) =>
|
||||
blocks_motion(is_solid(x + dx, y, z + dz)) || blocks_motion(is_solid(x + dx, y + 1, z + dz))
|
||||
);
|
||||
@@ -315,10 +315,10 @@ export function liquid_flow(
|
||||
return normalized(fx, fy, fz);
|
||||
}
|
||||
|
||||
// liquid the body is in pushes it the way it flows, like minecraft's Entity.updateFluidHeightAndDoFluidPushing: the
|
||||
// fluid the body is in pushes it the way it flows, like minecraft's Entity.updateFluidHeightAndDoFluidPushing: the
|
||||
// flow of every cell of it the box reaches, averaged, weaker where it's shallow. players get that average as it is,
|
||||
// other things are pushed at full strength whichever way it points. changes the body's velocity
|
||||
export function push_by_liquid(body: Body, liquid_at: LiquidAt, is_solid: BlockCollision, is_player: boolean) {
|
||||
export function push_by_fluid(body: Body, fluid_at: FluidAt, is_solid: BlockCollision, is_player: boolean) {
|
||||
const half = body.width / 2 - 0.001;
|
||||
const min_y = body.y + 0.001;
|
||||
const max_y = body.y + body.height - 0.001;
|
||||
@@ -330,12 +330,12 @@ export function push_by_liquid(body: Body, liquid_at: LiquidAt, is_solid: BlockC
|
||||
for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) {
|
||||
for (let y = Math.floor(min_y); y <= Math.floor(max_y); y++) {
|
||||
for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) {
|
||||
const liquid = liquid_at(x, y, z);
|
||||
if (!liquid) continue;
|
||||
const surface = y + (liquid_at(x, y + 1, z)?.id === liquid.id ? 1 : liquid.height);
|
||||
const fluid = fluid_at(x, y, z);
|
||||
if (!fluid) continue;
|
||||
const surface = y + (fluid_at(x, y + 1, z)?.id === fluid.id ? 1 : fluid.height);
|
||||
if (surface < min_y) continue;
|
||||
depth = Math.max(depth, surface - min_y);
|
||||
let [fx, fy, fz] = liquid_flow(x, y, z, liquid_at, is_solid);
|
||||
let [fx, fy, fz] = fluid_flow(x, y, z, fluid_at, is_solid);
|
||||
// minecraft's, which goes by the deepest cell so far
|
||||
if (depth < 0.4) {
|
||||
fx *= depth;
|
||||
@@ -352,31 +352,31 @@ export function push_by_liquid(body: Body, liquid_at: LiquidAt, is_solid: BlockC
|
||||
if (Math.hypot(px, py, pz) === 0) return;
|
||||
|
||||
[px, py, pz] = is_player ? [px / count, py / count, pz / count] : normalized(px, py, pz);
|
||||
px *= LIQUID_PUSH;
|
||||
py *= LIQUID_PUSH;
|
||||
pz *= LIQUID_PUSH;
|
||||
px *= FLUID_PUSH;
|
||||
py *= FLUID_PUSH;
|
||||
pz *= FLUID_PUSH;
|
||||
if (
|
||||
Math.abs(body.vx) < LIQUID_STILL_SPEED && Math.abs(body.vz) < LIQUID_STILL_SPEED &&
|
||||
Math.hypot(px, py, pz) < LIQUID_MIN_PUSH
|
||||
Math.abs(body.vx) < FLUID_STILL_SPEED && Math.abs(body.vz) < FLUID_STILL_SPEED &&
|
||||
Math.hypot(px, py, pz) < FLUID_MIN_PUSH
|
||||
) {
|
||||
[px, py, pz] = normalized(px, py, pz).map((n) => n * LIQUID_MIN_PUSH);
|
||||
[px, py, pz] = normalized(px, py, pz).map((n) => n * FLUID_MIN_PUSH);
|
||||
}
|
||||
body.vx += px;
|
||||
body.vy += py;
|
||||
body.vz += pz;
|
||||
}
|
||||
|
||||
// how far the body's feet are under the surface of liquid it's in, 0 for none, like minecraft's getFluidHeight
|
||||
export function liquid_depth(body: Body, liquid_at: LiquidAt): number {
|
||||
// how far the body's feet are under the surface of fluid it's in, 0 for none, like minecraft's getFluidHeight
|
||||
export function fluid_depth(body: Body, fluid_at: FluidAt): number {
|
||||
const half = body.width / 2 - 0.001;
|
||||
const min_y = body.y + 0.001;
|
||||
let depth = 0;
|
||||
for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) {
|
||||
for (let y = Math.floor(min_y); y <= Math.floor(body.y + body.height - 0.001); y++) {
|
||||
for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) {
|
||||
const liquid = liquid_at(x, y, z);
|
||||
if (!liquid) continue;
|
||||
const surface = y + (liquid_at(x, y + 1, z)?.id === liquid.id ? 1 : liquid.height);
|
||||
const fluid = fluid_at(x, y, z);
|
||||
if (!fluid) continue;
|
||||
const surface = y + (fluid_at(x, y + 1, z)?.id === fluid.id ? 1 : fluid.height);
|
||||
depth = Math.max(depth, surface - min_y);
|
||||
}
|
||||
}
|
||||
@@ -392,7 +392,7 @@ export const physics = {
|
||||
box_is_free,
|
||||
in_water,
|
||||
eyes_in_water,
|
||||
liquid_flow,
|
||||
push_by_liquid,
|
||||
liquid_depth,
|
||||
fluid_flow,
|
||||
push_by_fluid,
|
||||
fluid_depth,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the pieces mod data's zod schemas are made of, and the problems they find, worded for mod authors. it imports
|
||||
// nothing else of the game's, so every file can make its schemas with these as it loads, whatever imports it first
|
||||
import * as z from "zod";
|
||||
|
||||
// a list of what's wrong with some json, empty when it's fine
|
||||
export type Problems = string[];
|
||||
|
||||
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
|
||||
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
|
||||
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
|
||||
|
||||
export const id = z.string('must be an id like "my_mod:thing"').regex(ID_PATTERN);
|
||||
// an id, or a #tag of them
|
||||
export const id_or_tag = z.string('must be an id like "my_mod:thing" or a tag like "#my_mod:things"').refine(
|
||||
(value) => value.startsWith("#") ? TAG_ID_PATTERN.test(value.slice(1)) : ID_PATTERN.test(value),
|
||||
);
|
||||
export const loot_table_id = z.string('must be a loot table id, like "my_mod:blocks/thing"').regex(TAG_ID_PATTERN);
|
||||
// text players see
|
||||
export const text = z.string().min(1);
|
||||
export const vec3 = z.tuple([z.number(), z.number(), z.number()], "must be [x, y, z]");
|
||||
export const color = z.string('must be a color like "#79c05a"').regex(/^#[0-9a-fA-F]{6}$/);
|
||||
// any json object, for what's only stored, like components
|
||||
export const json_object = z.record(z.string(), z.unknown());
|
||||
|
||||
// json that says what kind of thing it is in one field, like a loot condition's "condition", checked by the schema
|
||||
// schema_for gives for its kind: the engine's kinds, and mods' own for the rest. no schema is a kind there isn't, which
|
||||
// unknown says what's wrong with
|
||||
export function by_kind<T extends Record<string, unknown>>(
|
||||
field: string,
|
||||
schema_for: (kind: string) => z.ZodType | undefined,
|
||||
unknown: string,
|
||||
): z.ZodType<T> {
|
||||
const kinded: z.ZodType = z.looseObject({ [field]: z.string() }).superRefine((json, ctx) => {
|
||||
const schema = schema_for(json[field]);
|
||||
if (schema) add_problems(ctx, schema, json);
|
||||
else ctx.addIssue({ code: "custom", path: [field], message: unknown });
|
||||
});
|
||||
// the kind's schema checked the rest of T
|
||||
return kinded as z.ZodType<T>;
|
||||
}
|
||||
|
||||
// checks json with schema as part of a bigger check, like a feature's config by its type. the problems go to ctx, under
|
||||
// path from where it is
|
||||
export function add_problems(ctx: z.RefinementCtx, schema: z.ZodType, json: unknown, path: PropertyKey[] = []) {
|
||||
for (const issue of schema.safeParse(json, { error: describe }).error?.issues ?? []) {
|
||||
ctx.addIssue({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodRawIssue);
|
||||
}
|
||||
}
|
||||
|
||||
// what's wrong with json for a schema, each as where it is and what it should be, like "tool.durability must be 1 or
|
||||
// more". a schema's own message wins over the ones from describe
|
||||
export function find_problems(schema: z.ZodType, json: unknown): Problems {
|
||||
const result = schema.safeParse(json, { error: describe });
|
||||
return result.success ? [] : result.error.issues.flatMap((issue) => issue_problems(issue, []));
|
||||
}
|
||||
|
||||
function issue_problems(issue: z.core.$ZodIssue, outer: PropertyKey[]): Problems {
|
||||
const path = [...outer, ...issue.path];
|
||||
if (issue.code === "unrecognized_keys") {
|
||||
const where = field_name(path);
|
||||
return issue.keys.map((key) => `${where ? `${where} ` : ""}can't have ${JSON.stringify(key)}`);
|
||||
}
|
||||
// a union's options are the kinds of thing the json can be, like a texture id or { variable: texture id }. when
|
||||
// it's only one of them, that one's problems say more than the union's message
|
||||
if (issue.code === "invalid_union") {
|
||||
const fitting = issue.errors.filter((issues) => !issues.every(wrong_kind));
|
||||
if (fitting.length === 1) return fitting[0].flatMap((inner) => issue_problems(inner, path));
|
||||
}
|
||||
const where = field_name(path);
|
||||
return [where ? `${where} ${issue.message}` : issue.message];
|
||||
}
|
||||
|
||||
// a problem saying json isn't the kind of thing at all: it's the wrong type, none of a union's kinds, or not the
|
||||
// value a literal like "open_sky" is
|
||||
function wrong_kind(issue: z.core.$ZodIssue): boolean {
|
||||
return issue.path.length === 0 &&
|
||||
(issue.code === "invalid_type" || issue.code === "invalid_union" || issue.code === "invalid_value");
|
||||
}
|
||||
|
||||
// a path into the json as it's written in js, like tool.durability, parts[0].when or variants["age=3"]
|
||||
function field_name(path: PropertyKey[]): string {
|
||||
return path.map((key, i) => {
|
||||
if (typeof key === "number") return `[${key}]`;
|
||||
const name = String(key);
|
||||
return /^\w+$/.test(name) ? (i === 0 ? name : `.${name}`) : `[${JSON.stringify(name)}]`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
const TYPE_NAMES: Record<string, string> = {
|
||||
number: "a number",
|
||||
int: "a whole number",
|
||||
string: "text",
|
||||
boolean: "true or false",
|
||||
array: "a list",
|
||||
tuple: "a list",
|
||||
object: "an object",
|
||||
record: "an object",
|
||||
};
|
||||
|
||||
// zod's messages, in words for mod authors. what isn't here keeps zod's own
|
||||
const describe: z.core.$ZodErrorMap = (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type":
|
||||
return issue.input === undefined
|
||||
? "is required"
|
||||
: `must be ${TYPE_NAMES[issue.expected] ?? issue.expected}`;
|
||||
case "too_small":
|
||||
if (issue.origin === "array" || issue.origin === "string") {
|
||||
if (issue.minimum === 1) return "can't be empty";
|
||||
return `must have at least ${issue.minimum} ${issue.origin === "string" ? "characters" : "entries"}`;
|
||||
}
|
||||
return issue.inclusive ? `must be ${issue.minimum} or more` : `must be above ${issue.minimum}`;
|
||||
case "too_big":
|
||||
if (issue.origin === "array" || issue.origin === "string") {
|
||||
return `must have at most ${issue.maximum} ${issue.origin === "string" ? "characters" : "entries"}`;
|
||||
}
|
||||
return issue.inclusive ? `must be at most ${issue.maximum}` : `must be below ${issue.maximum}`;
|
||||
case "invalid_value":
|
||||
return `must be ${or_list(issue.values.map((value) => JSON.stringify(value)))}`;
|
||||
// a record's key, its schema says what's wrong with it
|
||||
case "invalid_key":
|
||||
return issue.issues[0]?.message;
|
||||
// a discriminated union's field that isn't one of its kinds
|
||||
case "invalid_union":
|
||||
if (Array.isArray(issue.options)) {
|
||||
return `must be ${or_list(issue.options.map((kind) => JSON.stringify(kind)))}`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// "a", "b" or "c"
|
||||
function or_list(values: string[]): string {
|
||||
return values.length < 2 ? values.join("") : `${values.slice(0, -1).join(", ")} or ${values.at(-1)}`;
|
||||
}
|
||||
|
||||
// a json object, not null or an array
|
||||
export function is_object(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -3,23 +3,27 @@
|
||||
|
||||
// animated textures, like minecraft's .png.mcmeta and in the same format: textures/<name>.json next to
|
||||
// textures/<name>.png says how to cut the png into frames and how long each one shows. see docs/modding/resources/textures.md
|
||||
import { is_object } from "./mod_data.ts";
|
||||
import * as z from "zod";
|
||||
import { find_problems, type Problems } from "./schema.ts";
|
||||
|
||||
export interface TextureJson {
|
||||
animation?: AnimationJson;
|
||||
}
|
||||
|
||||
export interface AnimationJson {
|
||||
const animation_schema = z.object({
|
||||
// ticks each frame shows unless the frame says otherwise, 1 if not given
|
||||
frametime?: number;
|
||||
frametime: z.int().min(1).optional(),
|
||||
// blend each frame into the next a tick at a time instead of switching
|
||||
interpolate?: boolean;
|
||||
interpolate: z.boolean().optional(),
|
||||
// the order to show frames in, by index or { index, time }. every frame in order if not given
|
||||
frames?: (number | { index: number; time: number })[];
|
||||
frames: z.array(z.union([z.int().min(0), z.object({ index: z.int().min(0), time: z.int().min(1) })])).min(1)
|
||||
.optional(),
|
||||
// a frame's size in pixels. frames are square, as wide as the png is or as tall if that's less, if not given
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
width: z.int().min(1).optional(),
|
||||
height: z.int().min(1).optional(),
|
||||
});
|
||||
|
||||
export type AnimationJson = z.infer<typeof animation_schema>;
|
||||
|
||||
const texture_schema = z.object({ animation: animation_schema.optional() }, 'must be { "animation": { ... } }');
|
||||
|
||||
export type TextureJson = z.infer<typeof texture_schema>;
|
||||
|
||||
// an animation ready to play
|
||||
export interface Animation {
|
||||
@@ -29,52 +33,28 @@ export interface Animation {
|
||||
frames: { x: number; y: number; time: number }[];
|
||||
}
|
||||
|
||||
// what's wrong with a texture's .json, for the png it goes with
|
||||
export function validate_texture_json(json: unknown, size: { width: number; height: number }): string[] {
|
||||
if (!is_object(json)) return [`must be { "animation": { ... } }`];
|
||||
if (json.animation === undefined) return [];
|
||||
const animation = json.animation;
|
||||
if (!is_object(animation)) return ["animation must be an object"];
|
||||
|
||||
const problems: string[] = [];
|
||||
const ticks = (value: unknown) => Number.isInteger(value) && (value as number) >= 1;
|
||||
if (animation.frametime !== undefined && !ticks(animation.frametime)) {
|
||||
problems.push("animation.frametime must be a whole number of ticks, at least 1");
|
||||
}
|
||||
if (animation.interpolate !== undefined && typeof animation.interpolate !== "boolean") {
|
||||
problems.push("animation.interpolate must be true or false");
|
||||
}
|
||||
for (const key of ["width", "height"] as const) {
|
||||
if (animation[key] !== undefined && !ticks(animation[key])) {
|
||||
problems.push(`animation.${key} must be a whole number of pixels, at least 1`);
|
||||
}
|
||||
}
|
||||
if (problems.length > 0) return problems;
|
||||
|
||||
const { frame_width, frame_height } = frame_size(animation as AnimationJson, size);
|
||||
if (size.width % frame_width !== 0 || size.height % frame_height !== 0) {
|
||||
return [
|
||||
`the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`,
|
||||
];
|
||||
}
|
||||
const count = (size.width / frame_width) * (size.height / frame_height);
|
||||
|
||||
if (animation.frames !== undefined) {
|
||||
if (!Array.isArray(animation.frames) || animation.frames.length === 0) {
|
||||
problems.push("animation.frames must be a list of frames");
|
||||
} else {
|
||||
animation.frames.forEach((frame, i) => {
|
||||
const index = is_object(frame) ? frame.index : frame;
|
||||
if (!Number.isInteger(index) || index < 0 || index >= count) {
|
||||
problems.push(`animation.frames[${i}]: the png has frames 0 to ${count - 1}`);
|
||||
}
|
||||
if (is_object(frame) && !ticks(frame.time)) {
|
||||
problems.push(`animation.frames[${i}]: time must be a whole number of ticks, at least 1`);
|
||||
}
|
||||
// what's wrong with a texture's .json, for the png it goes with: its frames have to be in it
|
||||
export function validate_texture_json(json: unknown, size: { width: number; height: number }): Problems {
|
||||
const fits_png = texture_schema.superRefine(({ animation }, ctx) => {
|
||||
if (!animation) return;
|
||||
const { frame_width, frame_height } = frame_size(animation, size);
|
||||
if (size.width % frame_width !== 0 || size.height % frame_height !== 0) {
|
||||
return ctx.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
`the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
const count = (size.width / frame_width) * (size.height / frame_height);
|
||||
animation.frames?.forEach((frame, i) => {
|
||||
const index = typeof frame === "number" ? frame : frame.index;
|
||||
if (index >= count) {
|
||||
const path = ["animation", "frames", i, ...(typeof frame === "number" ? [] : ["index"])];
|
||||
ctx.addIssue({ code: "custom", path, message: `isn't one of the png's frames, 0 to ${count - 1}` });
|
||||
}
|
||||
});
|
||||
});
|
||||
return find_problems(fits_png, json);
|
||||
}
|
||||
|
||||
// the animation in a texture's .json, which validate_texture_json passed. undefined if it isn't animated
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { ID_MASK, STATE_SHIFT } from "./constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "./everything_registry.ts";
|
||||
import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "./everything_registry.ts";
|
||||
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 { LiquidInCell } from "./physics.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;
|
||||
@@ -191,7 +235,7 @@ export function can_place(
|
||||
const into = current?.id ?? "bworld:air";
|
||||
const replaceable = !current || current.replaceable === true;
|
||||
const in_ok = block.place_in ? list_matches("blocks", block.place_in, into) : replaceable;
|
||||
// one that's only ever waterlogged goes into a source of its liquid and nothing else
|
||||
// one that's only ever waterlogged goes into a source of its fluid and nothing else
|
||||
const source_ok = !block.waterlogged_only ||
|
||||
(current !== undefined && current.id === block.waterloggable &&
|
||||
(get_state_value(current_value, current, "level") ?? 0) === 0);
|
||||
@@ -220,31 +264,31 @@ export function chunk_key(x: number, z: number) {
|
||||
return (x + 32768) * 65536 + (z + 32768);
|
||||
}
|
||||
|
||||
// whether a block value is a waterloggable block holding its liquid
|
||||
// whether a block value is a waterloggable block holding its fluid
|
||||
export function is_waterlogged(value: number, block: BlockRegistry | undefined): boolean {
|
||||
return block?.waterloggable !== undefined && get_state_value(value, block, "waterlogged") === 1;
|
||||
}
|
||||
|
||||
// the liquid in a cell with this block value: the block itself, or the liquid it's waterlogged with. undefined for
|
||||
// the fluid in a cell with this block value: the block itself, or the fluid it's waterlogged with. undefined for
|
||||
// none. what entities swim in, see in_water in physics.ts
|
||||
export function liquid_block(value: number, block: BlockRegistry | undefined): BlockRegistry | undefined {
|
||||
if (block?.liquid) return block;
|
||||
export function fluid_block(value: number, block: BlockRegistry | undefined): BlockRegistry | undefined {
|
||||
if (block?.fluid) return block;
|
||||
if (!is_waterlogged(value, block)) return undefined;
|
||||
return EverythingRegistry.get<BlockRegistry>("blocks", block!.waterloggable!);
|
||||
}
|
||||
|
||||
// the liquid in a cell and how high it is, for liquids pushing things (see push_by_liquid in physics.ts). a waterlogged
|
||||
// the fluid in a cell and how high it is, for fluids pushing things (see push_by_fluid in physics.ts). a waterlogged
|
||||
// block holds a source
|
||||
export function liquid_in_cell(value: number, block: BlockRegistry | undefined): LiquidInCell | undefined {
|
||||
if (block?.liquid) {
|
||||
export function fluid_in_cell(value: number, block: BlockRegistry | undefined): FluidInCell | undefined {
|
||||
if (block?.fluid) {
|
||||
const level = get_state_value(value, block, "level") ?? 0;
|
||||
return { id: block.id, height: liquid_height(level, block.liquid.range) };
|
||||
return { id: block.id, height: fluid_height(level, block.fluid.range) };
|
||||
}
|
||||
const liquid = liquid_block(value, block);
|
||||
return liquid && { id: liquid.id, height: 1 };
|
||||
const fluid = fluid_block(value, block);
|
||||
return fluid && { id: fluid.id, height: 1 };
|
||||
}
|
||||
|
||||
// a waterloggable block placed where a source of its liquid is holds it, like minecraft's getStateForPlacement.
|
||||
// a waterloggable block placed where a source of its fluid is holds it, like minecraft's getStateForPlacement.
|
||||
// value is what it's placed as, current_value and current what's there now
|
||||
export function waterlog_placement(
|
||||
value: number,
|
||||
|
||||
@@ -30,6 +30,11 @@ export function is_tint_color(value: unknown): value is TintColor {
|
||||
(typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value));
|
||||
}
|
||||
|
||||
// a color like 0x80a755 as red, green and blue from 0 to 1, for drawing
|
||||
export function color_rgb(color: number): [number, number, number] {
|
||||
return [(color >> 16) / 255, ((color >> 8) & 0xff) / 255, (color & 0xff) / 255];
|
||||
}
|
||||
|
||||
// the color outside any biome, for items: the default grass, foliage or water color, or the fixed one
|
||||
export function tint_without_biome(color: TintColor) {
|
||||
if (color === "grass") return DEFAULT_GRASS_COLOR;
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
|
||||
// biomes as data: worldgen/biomes/<name>.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column
|
||||
// gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked
|
||||
import * as z from "zod";
|
||||
import { EverythingRegistry } from "../everything_registry.ts";
|
||||
import { ID_PATTERN, is_object } from "../mod_data.ts";
|
||||
import { color, find_problems, id, type Problems } from "../schema.ts";
|
||||
import { farming_day } from "../time.ts";
|
||||
|
||||
export const SEASONS = ["spring", "summer", "autumn", "winter"] as const;
|
||||
@@ -12,31 +13,39 @@ export type Season = typeof SEASONS[number];
|
||||
// how long each season lasts. day 1 to 49 is spring, 50 to 98 summer and so on, a year is 196 days
|
||||
export const SEASON_DAYS = 49;
|
||||
|
||||
// how a biome covers its ground, like minecraft's surface rules. blocks are ids
|
||||
export interface SurfaceJson {
|
||||
top: string;
|
||||
filler: string;
|
||||
filler_depth: number;
|
||||
// how a biome covers its ground, like minecraft's surface rules
|
||||
const surface_schema = z.object({
|
||||
top: id,
|
||||
filler: id,
|
||||
filler_depth: z.int().min(0).max(32),
|
||||
// the ground's cover under water, filler when not set
|
||||
underwater_top?: string;
|
||||
underwater_filler?: string;
|
||||
underwater_top: id.optional(),
|
||||
underwater_filler: id.optional(),
|
||||
// cliffs show bare stone instead of top
|
||||
bare_cliffs?: boolean;
|
||||
}
|
||||
bare_cliffs: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export interface BiomeJson {
|
||||
id: string;
|
||||
export type SurfaceJson = z.infer<typeof surface_schema>;
|
||||
|
||||
const biome_schema = z.object({
|
||||
id,
|
||||
// a season it's always in, like winter for snowy biomes. when not set it follows the calendar, see calendar_season
|
||||
season?: Season;
|
||||
surface: SurfaceJson;
|
||||
// "#rrggbb", minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
|
||||
colors?: { grass?: string; foliage?: string; water?: string };
|
||||
season: z.enum(SEASONS).optional(),
|
||||
surface: surface_schema,
|
||||
// minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
|
||||
colors: z.strictObject({ grass: color.optional(), foliage: color.optional(), water: color.optional() }).optional(),
|
||||
// how likely each tree cell is to have a tree, and which kinds grow, picked evenly (list one twice to make it
|
||||
// twice as likely). wood is the logs and leaves a kind grows here when it isn't its own, like big oaks being dark
|
||||
// oak in the dark forest. the trees feature reads it (bworld's, in its worldgen script), which says what kinds
|
||||
// and woods there are
|
||||
trees?: { chance: number; kinds: string[]; wood?: Record<string, string> };
|
||||
}
|
||||
// and woods there are, and checks them when it loads
|
||||
trees: z.object({
|
||||
chance: z.number().min(0).max(1),
|
||||
kinds: z.array(z.string()).min(1),
|
||||
wood: z.record(z.string(), z.string()).optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export type BiomeJson = z.infer<typeof biome_schema>;
|
||||
|
||||
// what's registered in "biomes", with the defaults filled in
|
||||
export interface Biome {
|
||||
@@ -97,70 +106,6 @@ export function biome_blocks(json: BiomeJson): string[] {
|
||||
return [top, filler, underwater_top, underwater_filler].filter((id) => id !== undefined);
|
||||
}
|
||||
|
||||
export function validate_biome(json: unknown): string[] {
|
||||
if (!is_object(json)) return ["biome must be an object"];
|
||||
const problems: string[] = [];
|
||||
const id = (value: unknown, field: string) => {
|
||||
if (!(typeof value === "string" && ID_PATTERN.test(value))) {
|
||||
problems.push(`${field} must be an id like "my_mod:thing"`);
|
||||
}
|
||||
};
|
||||
id(json.id, "id");
|
||||
if (json.season !== undefined && !SEASONS.includes(json.season as Season)) {
|
||||
problems.push(`season must be one of ${SEASONS.join(", ")}`);
|
||||
}
|
||||
|
||||
const surface = json.surface;
|
||||
if (!is_object(surface)) {
|
||||
problems.push("surface must be { top, filler, filler_depth }");
|
||||
} else {
|
||||
id(surface.top, "surface.top");
|
||||
id(surface.filler, "surface.filler");
|
||||
if (surface.underwater_top !== undefined) id(surface.underwater_top, "surface.underwater_top");
|
||||
if (surface.underwater_filler !== undefined) id(surface.underwater_filler, "surface.underwater_filler");
|
||||
const depth = surface.filler_depth;
|
||||
if (!Number.isInteger(depth) || (depth as number) < 0 || (depth as number) > 32) {
|
||||
problems.push("surface.filler_depth must be a whole number from 0 to 32");
|
||||
}
|
||||
if (surface.bare_cliffs !== undefined && typeof surface.bare_cliffs !== "boolean") {
|
||||
problems.push("surface.bare_cliffs must be true or false");
|
||||
}
|
||||
}
|
||||
|
||||
if (json.colors !== undefined) {
|
||||
if (!is_object(json.colors)) {
|
||||
problems.push("colors must be { grass, foliage, water }");
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(json.colors)) {
|
||||
if (!["grass", "foliage", "water"].includes(key)) problems.push(`colors.${key} isn't a biome color`);
|
||||
else if (!(typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value))) {
|
||||
problems.push(`colors.${key} must be a color like "#79c05a"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const trees = json.trees;
|
||||
if (trees !== undefined) {
|
||||
if (!is_object(trees)) {
|
||||
problems.push("trees must be { chance, kinds }");
|
||||
} else {
|
||||
if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) {
|
||||
problems.push("trees.chance must be a number from 0 to 1");
|
||||
}
|
||||
// which kinds and woods there are is up to the trees feature, bworld's checks them when it loads
|
||||
if (
|
||||
!Array.isArray(trees.kinds) || trees.kinds.length === 0 ||
|
||||
!trees.kinds.every((kind) => typeof kind === "string")
|
||||
) {
|
||||
problems.push("trees.kinds must list at least one kind of tree");
|
||||
}
|
||||
if (trees.wood !== undefined) {
|
||||
if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) {
|
||||
problems.push("trees.wood must be { <kind>: <wood> }");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
export function validate_biome(json: unknown): Problems {
|
||||
return find_problems(biome_schema, json);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
// world generation as data: noises, density functions, noise settings (a generator) and biome sources, see
|
||||
// docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow
|
||||
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
|
||||
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
|
||||
import * as z from "zod";
|
||||
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
|
||||
|
||||
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
|
||||
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
|
||||
@@ -142,376 +143,256 @@ export function new_refs(): WorldgenRefs {
|
||||
return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() };
|
||||
}
|
||||
|
||||
const ARITHMETIC = ["add", "sub", "mul", "div", "min", "max"];
|
||||
export const DENSITY_TYPES = [
|
||||
"constant",
|
||||
"x",
|
||||
"y",
|
||||
"z",
|
||||
"noise",
|
||||
...ARITHMETIC,
|
||||
"abs",
|
||||
"clamp",
|
||||
"smoothstep",
|
||||
"spline",
|
||||
"range_choice",
|
||||
"cache_2d",
|
||||
];
|
||||
// checking
|
||||
|
||||
const worldgen_id = z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(WORLDGEN_ID_PATTERN);
|
||||
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
|
||||
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
|
||||
|
||||
const noise_schema: z.ZodType<NoiseJson> = z.object({
|
||||
id: worldgen_id,
|
||||
seed_name: z.string().optional(),
|
||||
wavelength: z.number().positive(),
|
||||
amplitudes: z.array(z.number()).min(1).refine((amplitudes) => amplitudes.some((a) => a !== 0), "can't all be 0"),
|
||||
dimensions: z.literal([2, 3]).optional(),
|
||||
vertical_stretch: z.number().positive().optional(),
|
||||
quantiles: z.union([
|
||||
worldgen_id,
|
||||
z.array(z.number()).min(2).refine((q) => q.every((value, i) => i === 0 || value > q[i - 1]), "must go up"),
|
||||
], "must be at least 2 numbers going up, or a noise's id").optional(),
|
||||
}).refine((noise) => noise.vertical_stretch === undefined || noise.dimensions === 3, {
|
||||
path: ["vertical_stretch"],
|
||||
message: "is only for 3d noises",
|
||||
});
|
||||
|
||||
const RANGE_KEYS = ["min_inclusive", "min_exclusive", "max_inclusive", "max_exclusive"] as const;
|
||||
|
||||
export function validate_noise(json: unknown): string[] {
|
||||
const problems: string[] = [];
|
||||
if (!is_object(json)) return ["noise must be an object"];
|
||||
worldgen_id(json.id, "id", problems);
|
||||
if (json.seed_name !== undefined && typeof json.seed_name !== "string") problems.push("seed_name must be text");
|
||||
if (!(typeof json.wavelength === "number" && json.wavelength > 0)) problems.push("wavelength must be above 0");
|
||||
if (
|
||||
!Array.isArray(json.amplitudes) || json.amplitudes.length === 0 ||
|
||||
!json.amplitudes.every((a) => typeof a === "number" && Number.isFinite(a)) ||
|
||||
json.amplitudes.every((a) => a === 0)
|
||||
) {
|
||||
problems.push("amplitudes must be a list of numbers, not all 0");
|
||||
}
|
||||
if (json.dimensions !== undefined && json.dimensions !== 2 && json.dimensions !== 3) {
|
||||
problems.push("dimensions must be 2 or 3");
|
||||
}
|
||||
if (json.vertical_stretch !== undefined) {
|
||||
if (json.dimensions !== 3) problems.push("vertical_stretch is only for 3d noises");
|
||||
if (!(typeof json.vertical_stretch === "number" && json.vertical_stretch > 0)) {
|
||||
problems.push("vertical_stretch must be above 0");
|
||||
// a range's bounds, numbers or (in range_choice) density functions. a range needs at least one
|
||||
function bounds<T extends z.ZodType>(bound: T) {
|
||||
return {
|
||||
min_inclusive: bound.optional(),
|
||||
min_exclusive: bound.optional(),
|
||||
max_inclusive: bound.optional(),
|
||||
max_exclusive: bound.optional(),
|
||||
};
|
||||
}
|
||||
const has_bound = (range: Partial<Record<typeof RANGE_KEYS[number], unknown>>) =>
|
||||
RANGE_KEYS.some((key) => range[key] !== undefined);
|
||||
const NEEDS_BOUND = `needs at least one of ${RANGE_KEYS.join(", ")}`;
|
||||
|
||||
const range = z.object(bounds(z.number())).refine(has_bound, NEEDS_BOUND);
|
||||
|
||||
// a density function, by itself or by its id
|
||||
const density: z.ZodType<DensityJson> = z.lazy(() =>
|
||||
z.union(
|
||||
[z.number(), z.string("must be a density function's id").regex(WORLDGEN_ID_PATTERN), density_object],
|
||||
'must be a number, a density function\'s id or { "type": ... }',
|
||||
)
|
||||
);
|
||||
|
||||
const spline: z.ZodType<SplineJson> = z.object({
|
||||
coordinate: density,
|
||||
points: z.array(z.object({
|
||||
location: z.number(),
|
||||
value: z.union([z.number(), z.lazy(() => spline)], "must be a number or a spline"),
|
||||
derivative: z.number().optional(),
|
||||
})).min(1).superRefine((points, ctx) => {
|
||||
points.forEach((point, i) => {
|
||||
if (i > 0 && point.location < points[i - 1].location) {
|
||||
ctx.addIssue({ code: "custom", path: [i, "location"], message: "can't be below the point before's" });
|
||||
}
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const density_object = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("constant"), argument: z.number() }),
|
||||
z.object({ type: z.literal(["x", "y", "z"]) }),
|
||||
z.object({
|
||||
type: z.literal("noise"),
|
||||
noise: z.string("must be a noise's id").regex(WORLDGEN_ID_PATTERN),
|
||||
even: z.boolean().optional(),
|
||||
x: density.optional(),
|
||||
y: density.optional(),
|
||||
z: density.optional(),
|
||||
}),
|
||||
z.object({ type: z.literal(["add", "sub", "mul", "div", "min", "max"]), argument1: density, argument2: density }),
|
||||
z.object({ type: z.literal(["abs", "cache_2d"]), argument: density }),
|
||||
z.object({ type: z.literal("clamp"), input: density, min: z.number(), max: z.number() })
|
||||
.refine(({ min, max }) => min <= max, { path: ["min"], message: "can't be above max" }),
|
||||
z.object({ type: z.literal("smoothstep"), input: density, from: z.number(), to: z.number() })
|
||||
.refine(({ from, to }) => from !== to, { path: ["to"], message: "must be different from from" }),
|
||||
z.object({ type: z.literal("spline"), spline }),
|
||||
z.object({
|
||||
type: z.literal("range_choice"),
|
||||
input: density,
|
||||
...bounds(density),
|
||||
when_in_range: density,
|
||||
when_out_of_range: density,
|
||||
}).refine(has_bound, NEEDS_BOUND),
|
||||
]);
|
||||
|
||||
const density_function_schema: z.ZodType<DensityFunctionJson> = z.intersection(
|
||||
z.object({ id: worldgen_id }),
|
||||
density_object,
|
||||
);
|
||||
|
||||
const surface_rule: z.ZodType<SurfaceRuleJson> = z.lazy(() =>
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("sequence"), sequence: z.array(surface_rule) }),
|
||||
z.object({ type: z.literal("condition"), if_true: surface_condition, then_run: surface_rule }),
|
||||
z.object({ type: z.literal("block"), result_state: z.object({ Name: block_id }) }),
|
||||
z.object({ type: z.literal("biome_surface"), part: z.enum(BIOME_SURFACE_PARTS) }),
|
||||
])
|
||||
);
|
||||
|
||||
const surface_condition: z.ZodType<SurfaceConditionJson> = z.lazy(() =>
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("stone_depth"), offset: z.int() }),
|
||||
z.object({ type: z.literal(["filler_depth", "surface_underwater", "steep", "bare_cliffs"]) }),
|
||||
z.object({ type: z.literal("above_preliminary_surface"), offset: z.number().optional() }),
|
||||
z.object({ type: z.literal("y_at_least"), function: density }),
|
||||
z.object({ type: z.literal("biome"), biome_is: z.array(biome_id) }),
|
||||
z.object({ type: z.literal("not"), invert: surface_condition }),
|
||||
])
|
||||
);
|
||||
|
||||
const cell_height = z.literal([1, 2, 4, 8, 16, 32]);
|
||||
|
||||
const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
|
||||
id: worldgen_id,
|
||||
sea_level: z.int().min(0).max(256),
|
||||
default_block: block_id,
|
||||
cell_width: z.literal([1, 2, 4, 8, 16]),
|
||||
terrain: z.object({ density, cell_height }),
|
||||
caves: z.object({ density, cell_height }),
|
||||
preliminary_surface: density,
|
||||
climate: z.record(
|
||||
z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep")
|
||||
.regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"),
|
||||
density,
|
||||
),
|
||||
steep: z.number().min(0),
|
||||
biome_source: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN),
|
||||
fluids: z.array(z.object({
|
||||
block: block_id,
|
||||
below: z.int(),
|
||||
where: z.union([
|
||||
z.literal("open_sky"),
|
||||
z.object({ function: density, ...bounds(z.number()) }).refine(has_bound, NEEDS_BOUND),
|
||||
], 'must be "open_sky" or { "function", <range> }'),
|
||||
})),
|
||||
surface_rule,
|
||||
});
|
||||
|
||||
const biome_source_schema: z.ZodType<BiomeSourceJson> = z.object({
|
||||
id: worldgen_id,
|
||||
extends: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN).optional(),
|
||||
rules: z.array(z.object({
|
||||
id: worldgen_id,
|
||||
before: worldgen_id.optional(),
|
||||
after: worldgen_id.optional(),
|
||||
// steep is true or false, any other name is a range of that climate value
|
||||
when: z.object({ steep: z.boolean().optional() }).catchall(range).optional(),
|
||||
biome: biome_id,
|
||||
})),
|
||||
}).superRefine((source, ctx) => {
|
||||
// a rule added to another biome source goes before or after one of its rules
|
||||
source.rules.forEach((rule, i) => {
|
||||
const placed = [rule.before, rule.after].filter((id) => id !== undefined).length;
|
||||
if (source.extends !== undefined && placed !== 1) {
|
||||
ctx.addIssue({ code: "custom", path: ["rules", i], message: "needs before or after, one of them" });
|
||||
}
|
||||
}
|
||||
const quantiles = json.quantiles;
|
||||
if (quantiles !== undefined && typeof quantiles !== "string") {
|
||||
if (
|
||||
!Array.isArray(quantiles) || quantiles.length < 2 ||
|
||||
!quantiles.every((q, i) => typeof q === "number" && (i === 0 || q > quantiles[i - 1]))
|
||||
) {
|
||||
problems.push("quantiles must be at least 2 numbers going up, or a noise's id");
|
||||
if (source.extends === undefined && placed > 0) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["rules", i],
|
||||
message: "can't have before or after, they're for rules added to another biome source with extends",
|
||||
});
|
||||
}
|
||||
} else if (typeof quantiles === "string") {
|
||||
worldgen_id(quantiles, "quantiles", problems);
|
||||
}
|
||||
return problems;
|
||||
});
|
||||
});
|
||||
|
||||
export function validate_noise(json: unknown): Problems {
|
||||
return find_problems(noise_schema, json);
|
||||
}
|
||||
|
||||
// the noises a noise file refers to: the one it takes its quantiles from
|
||||
export function validate_density_function(json: unknown): Problems {
|
||||
return find_problems(density_function_schema, json);
|
||||
}
|
||||
|
||||
export function validate_noise_settings(json: unknown): Problems {
|
||||
return find_problems(noise_settings_schema, json);
|
||||
}
|
||||
|
||||
export function validate_biome_source(json: unknown): Problems {
|
||||
return find_problems(biome_source_schema, json);
|
||||
}
|
||||
|
||||
// what worldgen data that passed its checks refers to
|
||||
|
||||
export function noise_refs(json: NoiseJson, refs: WorldgenRefs) {
|
||||
if (typeof json.quantiles === "string") refs.noises.add(json.quantiles);
|
||||
}
|
||||
|
||||
export function validate_density_function(json: unknown): string[] {
|
||||
if (!is_object(json)) return ["density_function must be an object"];
|
||||
const problems: string[] = [];
|
||||
worldgen_id(json.id, "id", problems);
|
||||
const { id: _, ...fn } = json;
|
||||
check_density(fn, "", new_refs(), problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
export function density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) {
|
||||
const { id: _, ...fn } = json;
|
||||
check_density(fn, "", refs, []);
|
||||
density_refs(fn, refs);
|
||||
}
|
||||
|
||||
// checks a density function, adding what it refers to to refs. at is where it is, for messages
|
||||
export function check_density(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
|
||||
const where = at ? `${at}: ` : "";
|
||||
if (typeof json === "number") {
|
||||
if (!Number.isFinite(json)) problems.push(`${where}must be a finite number`);
|
||||
return;
|
||||
}
|
||||
function density_refs(json: DensityJson, refs: WorldgenRefs) {
|
||||
if (typeof json === "number") return;
|
||||
if (typeof json === "string") {
|
||||
if (WORLDGEN_ID_PATTERN.test(json)) refs.functions.add(json);
|
||||
else problems.push(`${where}"${json}" isn't a density function's id`);
|
||||
refs.functions.add(json);
|
||||
return;
|
||||
}
|
||||
if (!is_object(json) || typeof json.type !== "string") {
|
||||
problems.push(`${where}must be a number, a density function's id or { "type": ... }`);
|
||||
return;
|
||||
}
|
||||
const field = (name: string) => check_density(json[name], at ? `${at}.${name}` : name, refs, problems);
|
||||
const number = (name: string) => {
|
||||
if (typeof json[name] !== "number" || !Number.isFinite(json[name])) {
|
||||
problems.push(`${where}${name} must be a number`);
|
||||
for (const [key, value] of Object.entries(json)) {
|
||||
if (key === "noise") refs.noises.add(value as string);
|
||||
else if (key === "spline") spline_refs(value as SplineJson, refs);
|
||||
// the other fields that are text or objects are density functions, the rest numbers and true or false
|
||||
else if (key !== "type" && (typeof value === "string" || is_object(value))) {
|
||||
density_refs(value as DensityJson, refs);
|
||||
}
|
||||
};
|
||||
switch (json.type) {
|
||||
case "constant":
|
||||
number("argument");
|
||||
break;
|
||||
case "x":
|
||||
case "y":
|
||||
case "z":
|
||||
break;
|
||||
case "noise":
|
||||
if (typeof json.noise === "string" && WORLDGEN_ID_PATTERN.test(json.noise)) refs.noises.add(json.noise);
|
||||
else problems.push(`${where}noise must be a noise's id`);
|
||||
if (json.even !== undefined && typeof json.even !== "boolean") {
|
||||
problems.push(`${where}even must be true or false`);
|
||||
}
|
||||
for (const axis of ["x", "y", "z"]) if (json[axis] !== undefined) field(axis);
|
||||
break;
|
||||
case "abs":
|
||||
case "cache_2d":
|
||||
field("argument");
|
||||
break;
|
||||
case "clamp":
|
||||
field("input");
|
||||
number("min");
|
||||
number("max");
|
||||
if ((json.min as number) > (json.max as number)) problems.push(`${where}min is above max`);
|
||||
break;
|
||||
case "smoothstep":
|
||||
field("input");
|
||||
number("from");
|
||||
number("to");
|
||||
if (json.from === json.to) problems.push(`${where}from and to must be different`);
|
||||
break;
|
||||
case "spline":
|
||||
check_spline(json.spline, at ? `${at}.spline` : "spline", refs, problems);
|
||||
break;
|
||||
case "range_choice":
|
||||
field("input");
|
||||
if (!RANGE_KEYS.some((key) => json[key] !== undefined)) problems.push(`${where}needs at least one bound`);
|
||||
for (const key of RANGE_KEYS) if (json[key] !== undefined) field(key);
|
||||
field("when_in_range");
|
||||
field("when_out_of_range");
|
||||
break;
|
||||
default:
|
||||
if (ARITHMETIC.includes(json.type)) {
|
||||
field("argument1");
|
||||
field("argument2");
|
||||
} else {
|
||||
problems.push(`${where}type ${json.type} isn't one of ${DENSITY_TYPES.join(", ")}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function check_spline(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
|
||||
if (!is_object(json) || !Array.isArray(json.points) || json.points.length === 0) {
|
||||
problems.push(`${at}: must be { "coordinate": ..., "points": [ ... ] }`);
|
||||
return;
|
||||
}
|
||||
check_density(json.coordinate, `${at}.coordinate`, refs, problems);
|
||||
let last = -Infinity;
|
||||
json.points.forEach((point: unknown, i: number) => {
|
||||
const here = `${at}.points[${i}]`;
|
||||
if (!is_object(point) || typeof point.location !== "number") {
|
||||
problems.push(`${here}: must be { "location", "value", "derivative" }`);
|
||||
return;
|
||||
}
|
||||
if (point.location < last) problems.push(`${here}: locations must go up`);
|
||||
last = point.location;
|
||||
if (typeof point.value !== "number") check_spline(point.value, `${here}.value`, refs, problems);
|
||||
if (point.derivative !== undefined && typeof point.derivative !== "number") {
|
||||
problems.push(`${here}: derivative must be a number`);
|
||||
}
|
||||
});
|
||||
function spline_refs(spline: SplineJson, refs: WorldgenRefs) {
|
||||
density_refs(spline.coordinate, refs);
|
||||
for (const point of spline.points) if (typeof point.value !== "number") spline_refs(point.value, refs);
|
||||
}
|
||||
|
||||
export function validate_noise_settings(json: unknown): string[] {
|
||||
if (!is_object(json)) return ["noise_settings must be an object"];
|
||||
const problems: string[] = [];
|
||||
noise_settings_refs(json, new_refs(), problems);
|
||||
return problems;
|
||||
export function noise_settings_refs(json: NoiseSettingsJson, refs: WorldgenRefs) {
|
||||
refs.blocks.add(json.default_block);
|
||||
const { terrain, caves, preliminary_surface, climate } = json;
|
||||
for (const fn of [terrain.density, caves.density, preliminary_surface, ...Object.values(climate)]) {
|
||||
density_refs(fn, refs);
|
||||
}
|
||||
refs.biome_sources.add(json.biome_source);
|
||||
for (const fluid of json.fluids) {
|
||||
refs.blocks.add(fluid.block);
|
||||
if (fluid.where !== "open_sky") density_refs(fluid.where.function, refs);
|
||||
}
|
||||
surface_rule_refs(json.surface_rule, refs);
|
||||
}
|
||||
|
||||
export function noise_settings_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
|
||||
worldgen_id(json.id, "id", problems);
|
||||
const whole = (name: string, min: number, max: number) => {
|
||||
const value = json[name];
|
||||
if (!(Number.isInteger(value) && (value as number) >= min && (value as number) <= max)) {
|
||||
problems.push(`${name} must be a whole number from ${min} to ${max}`);
|
||||
}
|
||||
};
|
||||
whole("sea_level", 0, 256);
|
||||
block_id(json.default_block, "default_block", refs, problems);
|
||||
if (![1, 2, 4, 8, 16].includes(json.cell_width as number)) problems.push("cell_width must be 1, 2, 4, 8 or 16");
|
||||
for (const part of ["terrain", "caves"]) {
|
||||
const value = json[part];
|
||||
if (!is_object(value)) {
|
||||
problems.push(`${part} must be { "density", "cell_height" }`);
|
||||
continue;
|
||||
}
|
||||
check_density(value.density, `${part}.density`, refs, problems);
|
||||
if (![1, 2, 4, 8, 16, 32].includes(value.cell_height as number)) {
|
||||
problems.push(`${part}.cell_height must be 1, 2, 4, 8, 16 or 32`);
|
||||
}
|
||||
function surface_rule_refs(rule: SurfaceRuleJson, refs: WorldgenRefs) {
|
||||
if (rule.type === "sequence") { for (const inner of rule.sequence) surface_rule_refs(inner, refs); }
|
||||
if (rule.type === "condition") {
|
||||
surface_condition_refs(rule.if_true, refs);
|
||||
surface_rule_refs(rule.then_run, refs);
|
||||
}
|
||||
check_density(json.preliminary_surface, "preliminary_surface", refs, problems);
|
||||
if (!is_object(json.climate)) {
|
||||
problems.push("climate must be { <name>: <density function> }");
|
||||
} else {
|
||||
for (const [name, value] of Object.entries(json.climate)) {
|
||||
if (!/^[a-z_]+$/.test(name) || name === "surface" || name === "steep") {
|
||||
problems.push(`climate.${name}: names are lowercase letters and _, and not surface or steep`);
|
||||
}
|
||||
check_density(value, `climate.${name}`, refs, problems);
|
||||
}
|
||||
}
|
||||
if (!(typeof json.steep === "number" && json.steep >= 0)) problems.push("steep must be a number, 0 or more");
|
||||
if (typeof json.biome_source === "string" && WORLDGEN_ID_PATTERN.test(json.biome_source)) {
|
||||
refs.biome_sources.add(json.biome_source);
|
||||
} else {
|
||||
problems.push("biome_source must be a biome source's id");
|
||||
}
|
||||
if (!Array.isArray(json.fluids)) {
|
||||
problems.push("fluids must be a list");
|
||||
} else {
|
||||
json.fluids.forEach((fluid: unknown, i: number) => {
|
||||
const at = `fluids[${i}]`;
|
||||
if (!is_object(fluid)) {
|
||||
problems.push(`${at}: must be { "block", "below", "where" }`);
|
||||
return;
|
||||
}
|
||||
block_id(fluid.block, `${at}.block`, refs, problems);
|
||||
if (!Number.isInteger(fluid.below)) problems.push(`${at}.below must be a whole number`);
|
||||
if (fluid.where !== "open_sky") {
|
||||
if (!is_object(fluid.where)) {
|
||||
problems.push(`${at}.where must be "open_sky" or { "function", <range> }`);
|
||||
} else {
|
||||
check_density(fluid.where.function, `${at}.where.function`, refs, problems);
|
||||
check_range(fluid.where, `${at}.where`, problems);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
check_surface_rule(json.surface_rule, "surface_rule", refs, problems);
|
||||
if (rule.type === "block") refs.blocks.add(rule.result_state.Name);
|
||||
}
|
||||
|
||||
function check_surface_rule(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
|
||||
if (!is_object(json)) {
|
||||
problems.push(`${at}: must be a rule`);
|
||||
return;
|
||||
}
|
||||
switch (json.type) {
|
||||
case "sequence":
|
||||
if (!Array.isArray(json.sequence)) problems.push(`${at}.sequence must be a list of rules`);
|
||||
else json.sequence.forEach((rule, i) => check_surface_rule(rule, `${at}.sequence[${i}]`, refs, problems));
|
||||
break;
|
||||
case "condition":
|
||||
check_surface_condition(json.if_true, `${at}.if_true`, refs, problems);
|
||||
check_surface_rule(json.then_run, `${at}.then_run`, refs, problems);
|
||||
break;
|
||||
case "block":
|
||||
if (!is_object(json.result_state)) problems.push(`${at}.result_state must be { "Name": <block> }`);
|
||||
else block_id(json.result_state.Name, `${at}.result_state.Name`, refs, problems);
|
||||
break;
|
||||
case "biome_surface":
|
||||
if (!BIOME_SURFACE_PARTS.includes(json.part as BiomeSurfacePart)) {
|
||||
problems.push(`${at}.part must be one of ${BIOME_SURFACE_PARTS.join(", ")}`);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
problems.push(`${at}: type must be sequence, condition, block or biome_surface`);
|
||||
}
|
||||
function surface_condition_refs(condition: SurfaceConditionJson, refs: WorldgenRefs) {
|
||||
if (condition.type === "y_at_least") density_refs(condition.function, refs);
|
||||
if (condition.type === "biome") { for (const biome of condition.biome_is) refs.biomes.add(biome); }
|
||||
if (condition.type === "not") surface_condition_refs(condition.invert, refs);
|
||||
}
|
||||
|
||||
function check_surface_condition(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
|
||||
if (!is_object(json)) {
|
||||
problems.push(`${at}: must be a condition`);
|
||||
return;
|
||||
}
|
||||
switch (json.type) {
|
||||
case "stone_depth":
|
||||
if (!Number.isInteger(json.offset)) problems.push(`${at}.offset must be a whole number`);
|
||||
break;
|
||||
case "above_preliminary_surface":
|
||||
if (json.offset !== undefined && typeof json.offset !== "number") {
|
||||
problems.push(`${at}.offset must be a number`);
|
||||
}
|
||||
break;
|
||||
case "filler_depth":
|
||||
case "surface_underwater":
|
||||
case "steep":
|
||||
case "bare_cliffs":
|
||||
break;
|
||||
case "y_at_least":
|
||||
check_density(json.function, `${at}.function`, refs, problems);
|
||||
break;
|
||||
case "biome":
|
||||
if (!Array.isArray(json.biome_is) || !json.biome_is.every((b) => typeof b === "string")) {
|
||||
problems.push(`${at}.biome_is must be a list of biome ids`);
|
||||
} else {
|
||||
for (const biome of json.biome_is) refs.biomes.add(biome);
|
||||
}
|
||||
break;
|
||||
case "not":
|
||||
check_surface_condition(json.invert, `${at}.invert`, refs, problems);
|
||||
break;
|
||||
default:
|
||||
problems.push(
|
||||
`${at}: type must be stone_depth, filler_depth, above_preliminary_surface, surface_underwater, steep, ` +
|
||||
`bare_cliffs, y_at_least, biome or not`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function validate_biome_source(json: unknown): string[] {
|
||||
if (!is_object(json)) return ["biome_source must be an object"];
|
||||
const problems: string[] = [];
|
||||
biome_source_refs(json, new_refs(), problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
export function biome_source_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
|
||||
worldgen_id(json.id, "id", problems);
|
||||
if (json.extends !== undefined) {
|
||||
if (typeof json.extends === "string" && WORLDGEN_ID_PATTERN.test(json.extends)) {
|
||||
refs.biome_sources.add(json.extends);
|
||||
} else problems.push("extends must be a biome source's id");
|
||||
}
|
||||
if (!Array.isArray(json.rules)) {
|
||||
problems.push("rules must be a list");
|
||||
return;
|
||||
}
|
||||
json.rules.forEach((rule: unknown, i: number) => {
|
||||
const at = `rules[${i}]`;
|
||||
if (!is_object(rule)) {
|
||||
problems.push(`${at}: must be { "id", "when", "biome" }`);
|
||||
return;
|
||||
}
|
||||
worldgen_id(rule.id, `${at}.id`, problems);
|
||||
const placed = [rule.before, rule.after].filter((id) => id !== undefined);
|
||||
if (json.extends !== undefined && placed.length !== 1) {
|
||||
problems.push(`${at}: a rule added to another biome source needs before or after, one of them`);
|
||||
}
|
||||
if (json.extends === undefined && placed.length > 0) {
|
||||
problems.push(`${at}: before and after are for rules added to another biome source, with extends`);
|
||||
}
|
||||
for (const id of placed) worldgen_id(id, `${at}.before/after`, problems);
|
||||
if (typeof rule.biome === "string" && ID_PATTERN.test(rule.biome)) refs.biomes.add(rule.biome);
|
||||
else problems.push(`${at}.biome must be a biome's id`);
|
||||
if (rule.when !== undefined) {
|
||||
if (!is_object(rule.when)) {
|
||||
problems.push(`${at}.when must be { <climate value>: <range>, "steep": true or false }`);
|
||||
} else {
|
||||
for (const [name, condition] of Object.entries(rule.when)) {
|
||||
if (name === "steep") {
|
||||
if (typeof condition !== "boolean") problems.push(`${at}.when.steep must be true or false`);
|
||||
} else {
|
||||
check_range(condition, `${at}.when.${name}`, problems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// a range of numbers, with at least one bound
|
||||
function check_range(json: unknown, at: string, problems: string[]) {
|
||||
if (!is_object(json)) {
|
||||
problems.push(`${at} must be a range like { "min_inclusive": 0 }`);
|
||||
return;
|
||||
}
|
||||
let bounds = 0;
|
||||
for (const key of RANGE_KEYS) {
|
||||
if (json[key] === undefined) continue;
|
||||
bounds++;
|
||||
if (typeof json[key] !== "number") problems.push(`${at}.${key} must be a number`);
|
||||
}
|
||||
if (bounds === 0) problems.push(`${at} needs at least one of ${RANGE_KEYS.join(", ")}`);
|
||||
export function biome_source_refs(json: BiomeSourceJson, refs: WorldgenRefs) {
|
||||
if (json.extends !== undefined) refs.biome_sources.add(json.extends);
|
||||
for (const rule of json.rules) refs.biomes.add(rule.biome);
|
||||
}
|
||||
|
||||
// a test of whether a value is in the range, with only the bounds it has: value >= min, value < max
|
||||
@@ -529,14 +410,3 @@ export function range_test(range: RangeJson): (value: number) => boolean {
|
||||
}
|
||||
return (value) => tests.every((test) => test(value));
|
||||
}
|
||||
|
||||
function worldgen_id(value: unknown, field: string, problems: string[]) {
|
||||
if (!(typeof value === "string" && WORLDGEN_ID_PATTERN.test(value))) {
|
||||
problems.push(`${field} must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
|
||||
}
|
||||
}
|
||||
|
||||
function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: string[]) {
|
||||
if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value);
|
||||
else problems.push(`${field} must be a block's id`);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,18 @@
|
||||
import { EverythingRegistry } from "../everything_registry.ts";
|
||||
import type { BlockRegistry } from "../everything_registry.ts";
|
||||
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
|
||||
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
|
||||
import * as z from "zod";
|
||||
import {
|
||||
add_problems,
|
||||
by_kind,
|
||||
find_problems,
|
||||
id_or_tag,
|
||||
ID_PATTERN,
|
||||
is_object,
|
||||
json_object,
|
||||
type Problems,
|
||||
TAG_ID_PATTERN,
|
||||
} from "../schema.ts";
|
||||
import { list_matches } from "../tags.ts";
|
||||
import { can_stand_on } from "../utils.ts";
|
||||
import { AIR_ID } from "../protocol.ts";
|
||||
@@ -66,56 +77,108 @@ export interface FeatureRefs {
|
||||
custom: Set<string>;
|
||||
}
|
||||
|
||||
export function validate_feature(json: unknown): string[] {
|
||||
const problems: string[] = [];
|
||||
feature_refs(json, { blocks: new Set(), biomes: new Set(), custom: new Set() }, problems);
|
||||
return problems;
|
||||
// a built in name, with its namespace or without, see builtin_name
|
||||
const builtin = (...names: string[]) => z.literal(names.flatMap((name) => [name, `minecraft:${name}`]));
|
||||
|
||||
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
|
||||
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
|
||||
|
||||
// a block, see state_id
|
||||
const block_state_schema = z.union(
|
||||
[block_id, z.object({ state: z.object({ Name: block_id }) }), z.object({ Name: block_id })],
|
||||
'must be a block\'s id or { "type": "simple_state_provider", "state": { "Name": ... } }',
|
||||
);
|
||||
|
||||
// a whole number, see int_provider
|
||||
const int_provider_schema: z.ZodType = z.lazy(() =>
|
||||
z.union([
|
||||
z.int(),
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({ type: builtin("constant"), value: z.int() }),
|
||||
z.object({ type: builtin("uniform"), min_inclusive: z.int(), max_inclusive: z.int() }).refine(
|
||||
({ min_inclusive, max_inclusive }) => min_inclusive <= max_inclusive,
|
||||
{ path: ["min_inclusive"], message: "can't be above max_inclusive" },
|
||||
),
|
||||
z.object({
|
||||
type: builtin("weighted_list"),
|
||||
distribution: z.array(z.object({ data: int_provider_schema, weight: z.int().min(1) })).min(1),
|
||||
}),
|
||||
], "must be constant, uniform or weighted_list"),
|
||||
], 'must be a whole number or { "type": "uniform", ... }')
|
||||
);
|
||||
|
||||
// a y, see anchor
|
||||
const anchor_schema = z.union([
|
||||
z.strictObject({ absolute: z.int() }),
|
||||
z.strictObject({ above_bottom: z.int() }),
|
||||
z.strictObject({ below_top: z.int() }),
|
||||
], 'must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }');
|
||||
|
||||
// see height_provider
|
||||
const height_schema = z.union([
|
||||
anchor_schema,
|
||||
z.discriminatedUnion("type", [
|
||||
z.object({ type: builtin("constant"), value: anchor_schema }),
|
||||
z.object({ type: builtin("uniform"), min_inclusive: anchor_schema, max_inclusive: anchor_schema }),
|
||||
], "must be constant or uniform"),
|
||||
], 'must be a height, like { "absolute": 10 } or { "type": "uniform", ... }');
|
||||
|
||||
// see block_predicate. offset moves where it looks
|
||||
const predicate_base = z.object({
|
||||
offset: z.tuple([z.int(), z.int(), z.int()], "must be [x, y, z], whole numbers").optional(),
|
||||
});
|
||||
|
||||
const block_predicate_schema: z.ZodType = z.lazy(() =>
|
||||
z.discriminatedUnion("type", [
|
||||
predicate_base.extend({
|
||||
type: builtin("matching_blocks"),
|
||||
blocks: z.union([id_or_tag, z.array(id_or_tag)], "must be a block, a #tag, or a list of them"),
|
||||
}),
|
||||
predicate_base.extend({ type: builtin("solid", "replaceable", "true") }),
|
||||
predicate_base.extend({ type: builtin("would_survive"), state: block_state_schema }),
|
||||
predicate_base.extend({ type: builtin("not"), predicate: block_predicate_schema }),
|
||||
predicate_base.extend({ type: builtin("all_of", "any_of"), predicates: z.array(block_predicate_schema) }),
|
||||
], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true")
|
||||
);
|
||||
|
||||
// a mod's own modifier is checked by the worldgen script that registers it
|
||||
const placement_modifier = by_kind<PlacementJson>("type", (type) => {
|
||||
const name = builtin_name(type);
|
||||
if (name === undefined) return json_object;
|
||||
return Object.hasOwn(MODIFIERS, name) ? MODIFIERS[name].schema : undefined;
|
||||
}, "isn't a built in placement modifier");
|
||||
|
||||
const feature_schema: z.ZodType<FeatureJson> = z.object({
|
||||
id: z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(TAG_ID_PATTERN),
|
||||
type: z.string(),
|
||||
config: json_object.optional(),
|
||||
placement: z.array(placement_modifier).optional(),
|
||||
biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(),
|
||||
step: z.enum(FEATURE_STEPS).optional(),
|
||||
}).superRefine((feature, ctx) => {
|
||||
// a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers
|
||||
const name = builtin_name(feature.type);
|
||||
if (name === undefined) return;
|
||||
if (!Object.hasOwn(FEATURE_TYPES, name)) {
|
||||
return ctx.addIssue({ code: "custom", path: ["type"], message: `${feature.type} isn't built in` });
|
||||
}
|
||||
add_problems(ctx, FEATURE_TYPES[name].schema, feature.config ?? {}, ["config"]);
|
||||
});
|
||||
|
||||
export function validate_feature(json: unknown): Problems {
|
||||
return find_problems(feature_schema, json);
|
||||
}
|
||||
|
||||
export function feature_refs(json: unknown, refs: FeatureRefs, problems: string[] = []) {
|
||||
if (!is_object(json)) {
|
||||
problems.push("feature must be an object");
|
||||
return;
|
||||
}
|
||||
if (!(typeof json.id === "string" && TAG_ID_PATTERN.test(json.id))) {
|
||||
problems.push(`id must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
|
||||
}
|
||||
if (json.step !== undefined && !FEATURE_STEPS.includes(json.step as FeatureStep)) {
|
||||
problems.push(`step must be one of ${FEATURE_STEPS.join(", ")}`);
|
||||
}
|
||||
if (json.biomes !== undefined) {
|
||||
const biomes = typeof json.biomes === "string" ? [json.biomes] : json.biomes;
|
||||
if (!Array.isArray(biomes) || !biomes.every((b) => typeof b === "string" && ID_PATTERN.test(b))) {
|
||||
problems.push("biomes must be a biome's id or a list of them");
|
||||
} else {
|
||||
for (const biome of biomes) refs.biomes.add(biome);
|
||||
}
|
||||
}
|
||||
if (json.config !== undefined && !is_object(json.config)) problems.push("config must be an object");
|
||||
if (typeof json.type !== "string") {
|
||||
problems.push("type must be a feature type");
|
||||
} else {
|
||||
const name = builtin_name(json.type);
|
||||
if (name === undefined) refs.custom.add(json.type);
|
||||
else if (!(name in FEATURE_TYPES)) problems.push(`type ${json.type} isn't built in`);
|
||||
else FEATURE_TYPES[name].check((json.config ?? {}) as Record<string, unknown>, "config", refs, problems);
|
||||
}
|
||||
if (json.placement !== undefined) {
|
||||
if (!Array.isArray(json.placement)) {
|
||||
problems.push("placement must be a list of placement modifiers");
|
||||
return;
|
||||
}
|
||||
json.placement.forEach((modifier: unknown, i: number) => {
|
||||
const at = `placement[${i}]`;
|
||||
if (!is_object(modifier) || typeof modifier.type !== "string") {
|
||||
problems.push(`${at}: must be { "type": ... }`);
|
||||
return;
|
||||
}
|
||||
const name = builtin_name(modifier.type);
|
||||
if (name === undefined) refs.custom.add(modifier.type);
|
||||
else if (!(name in MODIFIERS)) problems.push(`${at}: ${modifier.type} isn't a built in placement modifier`);
|
||||
else MODIFIERS[name].check(modifier, at, refs, problems);
|
||||
});
|
||||
// what a feature that passed its checks uses
|
||||
export function feature_refs(json: FeatureJson, refs: FeatureRefs) {
|
||||
for (const biome of [json.biomes ?? []].flat()) refs.biomes.add(biome);
|
||||
const type = builtin_name(json.type);
|
||||
if (type === undefined) refs.custom.add(json.type);
|
||||
else FEATURE_TYPES[type].refs?.(json.config ?? {}, refs);
|
||||
for (const modifier of json.placement ?? []) {
|
||||
const name = builtin_name(modifier.type);
|
||||
if (name === undefined) refs.custom.add(modifier.type);
|
||||
else MODIFIERS[name].refs?.(modifier, refs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,15 +246,19 @@ export function compile_feature(
|
||||
// built in feature types
|
||||
|
||||
interface Builtin<T> {
|
||||
check(json: Record<string, unknown>, at: string, refs: FeatureRefs, problems: string[]): void;
|
||||
// its json: a feature type's config, or the placement modifier
|
||||
schema: z.ZodType;
|
||||
// what it uses, when it uses something
|
||||
refs?(json: Record<string, unknown>, refs: FeatureRefs): void;
|
||||
compile(json: Record<string, unknown>): T;
|
||||
}
|
||||
|
||||
const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Position) => boolean>> = {
|
||||
// one block, where it can stand
|
||||
simple_block: {
|
||||
check(json, at, refs, problems) {
|
||||
check_state(json.to_place, `${at}.to_place`, refs, problems);
|
||||
schema: z.object({ to_place: block_state_schema }),
|
||||
refs(json, refs) {
|
||||
refs.blocks.add(state_id(json.to_place));
|
||||
},
|
||||
compile(json) {
|
||||
const id = state_id(json.to_place);
|
||||
@@ -204,29 +271,15 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
|
||||
},
|
||||
// layers of blocks stacked up (or down) from the origin, cut short where allowed_placement doesn't hold
|
||||
block_column: {
|
||||
check(json, at, refs, problems) {
|
||||
if (!Array.isArray(json.layers) || json.layers.length === 0) {
|
||||
problems.push(`${at}.layers must be a list of { "height", "provider" }`);
|
||||
} else {
|
||||
json.layers.forEach((layer: unknown, i: number) => {
|
||||
const here = `${at}.layers[${i}]`;
|
||||
if (!is_object(layer)) {
|
||||
problems.push(`${here} must be { "height", "provider" }`);
|
||||
return;
|
||||
}
|
||||
check_int(layer.height, `${here}.height`, problems);
|
||||
check_state(layer.provider, `${here}.provider`, refs, problems);
|
||||
});
|
||||
}
|
||||
if (json.direction !== undefined && json.direction !== "up" && json.direction !== "down") {
|
||||
problems.push(`${at}.direction must be "up" or "down"`);
|
||||
}
|
||||
if (json.allowed_placement !== undefined) {
|
||||
check_predicate(json.allowed_placement, `${at}.allowed_placement`, refs, problems);
|
||||
}
|
||||
if (json.prioritize_tip !== undefined && typeof json.prioritize_tip !== "boolean") {
|
||||
problems.push(`${at}.prioritize_tip must be true or false`);
|
||||
}
|
||||
schema: z.object({
|
||||
layers: z.array(z.object({ height: int_provider_schema, provider: block_state_schema })).min(1),
|
||||
direction: z.enum(["up", "down"]).optional(),
|
||||
allowed_placement: block_predicate_schema.optional(),
|
||||
prioritize_tip: z.boolean().optional(),
|
||||
}),
|
||||
refs(json, refs) {
|
||||
for (const layer of json.layers as { provider: unknown }[]) refs.blocks.add(state_id(layer.provider));
|
||||
if (json.allowed_placement !== undefined) predicate_refs(json.allowed_placement, refs);
|
||||
},
|
||||
compile(json) {
|
||||
const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({
|
||||
@@ -259,14 +312,12 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
|
||||
|
||||
type Modifier = (chunk: FeatureChunk, positions: Position[]) => Position[];
|
||||
|
||||
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"];
|
||||
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"] as const;
|
||||
|
||||
const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
// each position becomes count of them
|
||||
count: {
|
||||
check(json, at, _refs, problems) {
|
||||
check_int(json.count, `${at}.count`, problems);
|
||||
},
|
||||
schema: z.object({ count: int_provider_schema }),
|
||||
compile(json) {
|
||||
const count = int_provider(json.count);
|
||||
return (chunk, positions) =>
|
||||
@@ -275,11 +326,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
},
|
||||
// one in chance positions are kept
|
||||
rarity_filter: {
|
||||
check(json, at, _refs, problems) {
|
||||
if (!(Number.isInteger(json.chance) && (json.chance as number) >= 1)) {
|
||||
problems.push(`${at}.chance must be a whole number, 1 or more`);
|
||||
}
|
||||
},
|
||||
schema: z.object({ chance: z.int().min(1) }),
|
||||
compile(json) {
|
||||
const chance = json.chance as number;
|
||||
return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance);
|
||||
@@ -287,7 +334,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
},
|
||||
// somewhere random in the chunk, across
|
||||
in_square: {
|
||||
check() {},
|
||||
schema: z.object({}),
|
||||
compile() {
|
||||
return (chunk, positions) =>
|
||||
positions.map((p) => {
|
||||
@@ -299,10 +346,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
},
|
||||
// moved by up to xz_spread across and y_spread up or down
|
||||
random_offset: {
|
||||
check(json, at, _refs, problems) {
|
||||
check_int(json.xz_spread ?? 0, `${at}.xz_spread`, problems);
|
||||
check_int(json.y_spread ?? 0, `${at}.y_spread`, problems);
|
||||
},
|
||||
schema: z.object({ xz_spread: int_provider_schema.optional(), y_spread: int_provider_schema.optional() }),
|
||||
compile(json) {
|
||||
const xz = int_provider(json.xz_spread ?? 0);
|
||||
const y = int_provider(json.y_spread ?? 0);
|
||||
@@ -312,22 +356,16 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
},
|
||||
// at a height
|
||||
height_range: {
|
||||
check(json, at, _refs, problems) {
|
||||
check_height(json.height, `${at}.height`, problems);
|
||||
},
|
||||
schema: z.object({ height: height_schema }),
|
||||
compile(json) {
|
||||
const height = height_provider(json.height);
|
||||
return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z }));
|
||||
},
|
||||
},
|
||||
// on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a liquid.
|
||||
// on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a fluid.
|
||||
// positions outside the chunk are dropped
|
||||
heightmap: {
|
||||
check(json, at, _refs, problems) {
|
||||
if (!HEIGHTMAPS.includes(json.heightmap as string)) {
|
||||
problems.push(`${at}.heightmap must be one of ${HEIGHTMAPS.join(", ")}`);
|
||||
}
|
||||
},
|
||||
schema: z.object({ heightmap: z.enum(HEIGHTMAPS) }),
|
||||
compile(json) {
|
||||
const floor = String(json.heightmap).startsWith("OCEAN_FLOOR");
|
||||
return (chunk, positions) =>
|
||||
@@ -341,8 +379,9 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
},
|
||||
// where a block predicate holds
|
||||
block_predicate_filter: {
|
||||
check(json, at, refs, problems) {
|
||||
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
|
||||
schema: z.object({ predicate: block_predicate_schema }),
|
||||
refs(json, refs) {
|
||||
predicate_refs(json.predicate, refs);
|
||||
},
|
||||
compile(json) {
|
||||
const predicate = block_predicate(json.predicate);
|
||||
@@ -353,50 +392,28 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
|
||||
|
||||
function counts_for_heightmap(id: string | undefined, floor: boolean) {
|
||||
if (id === undefined || id === AIR_ID) return false;
|
||||
return !floor || !EverythingRegistry.get<BlockRegistry>("blocks", id)?.liquid;
|
||||
return !floor || !EverythingRegistry.get<BlockRegistry>("blocks", id)?.fluid;
|
||||
}
|
||||
|
||||
// block predicates, like minecraft's
|
||||
|
||||
type Predicate = (chunk: FeatureChunk, x: number, y: number, z: number) => boolean;
|
||||
const PREDICATES = ["matching_blocks", "solid", "replaceable", "would_survive", "not", "all_of", "any_of", "true"];
|
||||
|
||||
function check_predicate(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
|
||||
if (!is_object(json) || typeof json.type !== "string") {
|
||||
problems.push(`${at} must be a block predicate, { "type": ... }`);
|
||||
return;
|
||||
}
|
||||
const name = builtin_name(json.type);
|
||||
if (name === undefined || !PREDICATES.includes(name)) {
|
||||
problems.push(`${at}: ${json.type} isn't one of ${PREDICATES.join(", ")}`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
json.offset !== undefined &&
|
||||
!(Array.isArray(json.offset) && json.offset.length === 3 && json.offset.every(Number.isInteger))
|
||||
) {
|
||||
problems.push(`${at}.offset must be [x, y, z], whole numbers`);
|
||||
}
|
||||
switch (name) {
|
||||
case "matching_blocks": {
|
||||
const blocks = typeof json.blocks === "string" ? [json.blocks] : json.blocks;
|
||||
if (!Array.isArray(blocks) || !blocks.every((b) => typeof b === "string")) {
|
||||
problems.push(`${at}.blocks must be a block, a #tag, or a list of them`);
|
||||
} else {
|
||||
for (const block of blocks) refs.blocks.add(block);
|
||||
}
|
||||
// the blocks a predicate tests for
|
||||
function predicate_refs(json: unknown, refs: FeatureRefs) {
|
||||
const predicate = json as Record<string, unknown>;
|
||||
switch (builtin_name(predicate.type as string)) {
|
||||
case "matching_blocks":
|
||||
for (const block of [predicate.blocks].flat()) refs.blocks.add(block as string);
|
||||
break;
|
||||
}
|
||||
case "would_survive":
|
||||
check_state(json.state, `${at}.state`, refs, problems);
|
||||
refs.blocks.add(state_id(predicate.state));
|
||||
break;
|
||||
case "not":
|
||||
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
|
||||
predicate_refs(predicate.predicate, refs);
|
||||
break;
|
||||
case "all_of":
|
||||
case "any_of":
|
||||
if (!Array.isArray(json.predicates)) problems.push(`${at}.predicates must be a list`);
|
||||
else json.predicates.forEach((p, i) => check_predicate(p, `${at}.predicates[${i}]`, refs, problems));
|
||||
for (const inner of predicate.predicates as unknown[]) predicate_refs(inner, refs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,18 +473,6 @@ function inside(chunk: FeatureChunk, x: number, z: number) {
|
||||
|
||||
// block states: a block's id, or minecraft's { "type": "simple_state_provider", "state": { "Name": id } }
|
||||
|
||||
function check_state(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
|
||||
const id = typeof json === "string"
|
||||
? json
|
||||
: is_object(json) && is_object(json.state)
|
||||
? json.state.Name
|
||||
: is_object(json)
|
||||
? json.Name
|
||||
: undefined;
|
||||
if (typeof id === "string" && ID_PATTERN.test(id)) refs.blocks.add(id);
|
||||
else problems.push(`${at} must be a block's id or { "type": "simple_state_provider", "state": { "Name": ... } }`);
|
||||
}
|
||||
|
||||
function state_id(json: unknown): string {
|
||||
if (typeof json === "string") return json;
|
||||
const object = json as Record<string, unknown>;
|
||||
@@ -479,41 +484,6 @@ function state_id(json: unknown): string {
|
||||
|
||||
type IntProvider = (chunk: FeatureChunk) => number;
|
||||
|
||||
function check_int(json: unknown, at: string, problems: string[]) {
|
||||
if (Number.isInteger(json)) return;
|
||||
if (!is_object(json)) {
|
||||
problems.push(`${at} must be a whole number or { "type": "uniform", ... }`);
|
||||
return;
|
||||
}
|
||||
switch (builtin_name(String(json.type))) {
|
||||
case "constant":
|
||||
if (!Number.isInteger(json.value)) problems.push(`${at}.value must be a whole number`);
|
||||
break;
|
||||
case "uniform":
|
||||
if (!Number.isInteger(json.min_inclusive) || !Number.isInteger(json.max_inclusive)) {
|
||||
problems.push(`${at} needs whole numbers min_inclusive and max_inclusive`);
|
||||
} else if ((json.min_inclusive as number) > (json.max_inclusive as number)) {
|
||||
problems.push(`${at}: min_inclusive is above max_inclusive`);
|
||||
}
|
||||
break;
|
||||
case "weighted_list":
|
||||
if (!Array.isArray(json.distribution) || json.distribution.length === 0) {
|
||||
problems.push(`${at}.distribution must be a list of { "data", "weight" }`);
|
||||
} else {
|
||||
json.distribution.forEach((entry: unknown, i: number) => {
|
||||
if (!is_object(entry) || !(Number.isInteger(entry.weight) && (entry.weight as number) > 0)) {
|
||||
problems.push(`${at}.distribution[${i}] needs a whole number weight above 0`);
|
||||
} else {
|
||||
check_int(entry.data, `${at}.distribution[${i}].data`, problems);
|
||||
}
|
||||
});
|
||||
}
|
||||
break;
|
||||
default:
|
||||
problems.push(`${at}.type must be constant, uniform or weighted_list`);
|
||||
}
|
||||
}
|
||||
|
||||
function int_provider(json: unknown): IntProvider {
|
||||
if (typeof json === "number") return () => json;
|
||||
const object = json as Record<string, unknown>;
|
||||
@@ -548,35 +518,6 @@ function int_provider(json: unknown): IntProvider {
|
||||
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
|
||||
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
|
||||
|
||||
function check_height(json: unknown, at: string, problems: string[]) {
|
||||
if (!is_object(json)) {
|
||||
problems.push(`${at} must be a height, like { "absolute": 10 } or { "type": "uniform", ... }`);
|
||||
return;
|
||||
}
|
||||
if (json.type === undefined) return check_anchor(json, at, problems);
|
||||
switch (builtin_name(String(json.type))) {
|
||||
case "constant":
|
||||
check_anchor(json.value, `${at}.value`, problems);
|
||||
break;
|
||||
case "uniform":
|
||||
check_anchor(json.min_inclusive, `${at}.min_inclusive`, problems);
|
||||
check_anchor(json.max_inclusive, `${at}.max_inclusive`, problems);
|
||||
break;
|
||||
default:
|
||||
problems.push(`${at}.type must be constant or uniform`);
|
||||
}
|
||||
}
|
||||
|
||||
function check_anchor(json: unknown, at: string, problems: string[]) {
|
||||
const keys = ["absolute", "above_bottom", "below_top"];
|
||||
if (
|
||||
!is_object(json) || Object.keys(json).length !== 1 || !keys.includes(Object.keys(json)[0]) ||
|
||||
!Number.isInteger(Object.values(json)[0])
|
||||
) {
|
||||
problems.push(`${at} must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }`);
|
||||
}
|
||||
}
|
||||
|
||||
function anchor(json: unknown): number {
|
||||
const object = json as Record<string, number>;
|
||||
if (object.absolute !== undefined) return object.absolute;
|
||||
|
||||
@@ -93,6 +93,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
|
||||
entities: [],
|
||||
entity_models: [],
|
||||
effects: [],
|
||||
fluids: [],
|
||||
loot_tables: [],
|
||||
},
|
||||
})));
|
||||
|
||||
@@ -38,7 +38,8 @@
|
||||
"@std/path": "jsr:@std/path@^1.0.0",
|
||||
"fflate": "npm:fflate@^0.8.2",
|
||||
"gl-matrix": "npm:gl-matrix@^3.4.4",
|
||||
"marked": "npm:marked@^17.0.3"
|
||||
"marked": "npm:marked@^17.0.3",
|
||||
"zod": "jsr:@zod/zod@^4.6.7"
|
||||
},
|
||||
"desktop": {
|
||||
"app": { "name": "bworld", "identifier": "com.bworld.game" },
|
||||
|
||||
@@ -15,11 +15,13 @@
|
||||
"jsr:@std/http@^1.0.23": "1.0.24",
|
||||
"jsr:@std/internal@^1.0.10": "1.0.12",
|
||||
"jsr:@std/internal@^1.0.12": "1.0.12",
|
||||
"jsr:@std/internal@^1.0.14": "1.0.14",
|
||||
"jsr:@std/media-types@^1.1.0": "1.1.0",
|
||||
"jsr:@std/net@^1.0.6": "1.0.6",
|
||||
"jsr:@std/path@1": "1.1.4",
|
||||
"jsr:@std/path@1": "1.1.6",
|
||||
"jsr:@std/path@^1.1.4": "1.1.4",
|
||||
"jsr:@std/streams@^1.0.17": "1.1.2",
|
||||
"jsr:@zod/zod@^4.6.7": "4.6.7",
|
||||
"npm:fflate@~0.8.2": "0.8.3",
|
||||
"npm:gl-matrix@^3.4.4": "3.4.4",
|
||||
"npm:marked@^17.0.3": "17.0.3"
|
||||
@@ -79,6 +81,9 @@
|
||||
"@std/internal@1.0.12": {
|
||||
"integrity": "972a634fd5bc34b242024402972cd5143eac68d8dffaca5eaa4dba30ce17b027"
|
||||
},
|
||||
"@std/internal@1.0.14": {
|
||||
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
|
||||
},
|
||||
"@std/media-types@1.1.0": {
|
||||
"integrity": "c9d093f0c05c3512932b330e3cc1fe1d627b301db33a4c2c2185c02471d6eaa4"
|
||||
},
|
||||
@@ -91,8 +96,17 @@
|
||||
"jsr:@std/internal@^1.0.12"
|
||||
]
|
||||
},
|
||||
"@std/path@1.1.6": {
|
||||
"integrity": "c68485c2a4dfbb5ae3cc74fae4e8c4e5d874cf8a8ed12927917235c758b46cbe",
|
||||
"dependencies": [
|
||||
"jsr:@std/internal@^1.0.14"
|
||||
]
|
||||
},
|
||||
"@std/streams@1.1.2": {
|
||||
"integrity": "0249bf9b78a999f57032ca4d8e7ccaa57579090242640b35ddc948fbb745d3af"
|
||||
},
|
||||
"@zod/zod@4.6.7": {
|
||||
"integrity": "6706868ce1e1907362e1bf008e298e482723345f0ba4125c43e5b9fd7960b186"
|
||||
}
|
||||
},
|
||||
"npm": {
|
||||
@@ -119,6 +133,7 @@
|
||||
"jsr:@std/fs@^1.0.23",
|
||||
"jsr:@std/http@^1.0.23",
|
||||
"jsr:@std/path@1",
|
||||
"jsr:@zod/zod@^4.6.7",
|
||||
"npm:fflate@~0.8.2",
|
||||
"npm:gl-matrix@^3.4.4",
|
||||
"npm:marked@^17.0.3"
|
||||
|
||||
@@ -87,7 +87,7 @@ when what it hangs from is gone. A block whose states follow from its neighbors,
|
||||
clients see it change right away.
|
||||
|
||||
`on_state_change` runs when the block's states change and it stays the same block: a script's `ctx.world.set_state`, a
|
||||
rule, a liquid's level. `before` is every state as it was, by name, and `ctx.world.get_state` gives what they are now.
|
||||
rule, a fluid's level. `before` is every state as it was, by name, and `ctx.world.get_state` gives what they are now.
|
||||
It's how a block reacts to a state something else sets on it, like a machine another mod's script turns off. It runs
|
||||
right away, before the blocks beside it are told, like `on_create`. Replacing the block with `set_block` runs `on_break`
|
||||
and `on_create` instead, and setting a state to what it already is runs nothing.
|
||||
@@ -296,20 +296,20 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
|
||||
|
||||
`mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them:
|
||||
|
||||
| Component | Params | What it does |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
|
||||
| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it with a `base_sell_value` for coins. |
|
||||
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
|
||||
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
|
||||
| `bworld:stonecutter` | none | Cuts one item into another with `bworld:stonecutting` recipes, picked from a list. |
|
||||
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
|
||||
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
|
||||
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
|
||||
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
|
||||
| `bworld:water_source` | none | Refills the watering can. |
|
||||
| `bworld:fishable` | `loot_table`? | The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is `loot_table`, `bworld:gameplay/fishing` when not given, built from the fish whose `liquid` is this block. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
|
||||
| Component | Params | What it does |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
|
||||
| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it with a `base_sell_value` for coins. |
|
||||
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
|
||||
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
|
||||
| `bworld:stonecutter` | none | Cuts one item into another with `bworld:stonecutting` recipes, picked from a list. |
|
||||
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
|
||||
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
|
||||
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
|
||||
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
|
||||
| `bworld:water_source` | none | Refills the watering can. |
|
||||
| `bworld:fishable` | `loot_table`? | The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is `loot_table`, `bworld:gameplay/fishing` when not given, built from the fish whose `fluid` is this block. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
|
||||
|
||||
Item components work the same way, see [Items](../items/index.md#item-components).
|
||||
|
||||
@@ -53,7 +53,7 @@ there will be holes in the world behind them.
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `collision` | `true` | Whether entities bump into it. Plants set `false`, and liquids default to it. |
|
||||
| `collision` | `true` | Whether entities bump into it. Plants set `false`, and fluids default to it. |
|
||||
| `shape` | its model | The boxes players point at and entities bump into, in pixels. See [Shapes](../resources/models.md#shapes). |
|
||||
| `collision_shape` | `shape` | What entities bump into when it's different, up to 24 pixels high. See [Collision Shapes](../resources/models.md#collision-shapes). |
|
||||
| `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. |
|
||||
@@ -65,13 +65,13 @@ there will be holes in the world behind them.
|
||||
| `item` | `true` | Also register an item that places it, with the same id. To give that item more, see [Block Items](../items/index.md#block-items). |
|
||||
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
|
||||
| `scrollable` | `false` | The mouse wheel turned while looking at it goes to its components' `on_scroll` instead of the hotbar, see [Scrolling](components.md#scrolling). |
|
||||
| `replaceable` | `false` | Placing a block into it replaces it, like water. Liquids default to `true`. |
|
||||
| `replaceable` | `false` | Placing a block into it replaces it, like water. Fluids default to `true`. |
|
||||
| `place_in` | see meaning | Block ids or [tags](../resources/tags.md) it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
|
||||
| `place_on` | anywhere | Block ids or [tags](../resources/tags.md) it can stand on, like `["bworld:hoed_dirt"]` for crops or `["#bworld:logs"]`. See [below](#placement). |
|
||||
| `states` | none | Named [state](states.md) bits, like a crop's age. |
|
||||
| `components` | none | [Components](components.md) and their parameters. |
|
||||
| `item_display` | none | Shows an item on top of it, see [Tile Data](tiledata.md#showing-an-item). |
|
||||
| `liquid` | none | Makes it a liquid, like water. See [Liquids](#liquids). |
|
||||
| `fluid` | none | Makes it a fluid, like water. See [Fluids](#fluids). |
|
||||
|
||||
A block's definition goes to every player, since clients need it to draw the block, time breaking and collide with it.
|
||||
It can't hold functions.
|
||||
@@ -129,11 +129,10 @@ crop when its farmland is dug up.
|
||||
|
||||
Food that places a block, like potatoes, is planted when clicked somewhere it can go and eaten otherwise.
|
||||
|
||||
## Liquids
|
||||
## Fluids
|
||||
|
||||
A block with `liquid` is a liquid, like water. The engine draws it like Luanti's liquids: each corner of its surface is
|
||||
as high as the liquid around it, so it slopes down from a source to where it flows, and it thins out to a film at the
|
||||
shore.
|
||||
A block with `fluid` is a fluid, like water. The engine draws it like Luanti's fluids: each corner of its surface is as
|
||||
high as the fluid around it, so it slopes down from a source to where it flows, and it thins out to a film at the shore.
|
||||
|
||||
`mods/oily/blocks/oil.json`:
|
||||
|
||||
@@ -145,7 +144,7 @@ shore.
|
||||
"textures": { "still": "oily:oil_still", "flowing": "oily:oil_flowing" },
|
||||
"render_layer": "translucent",
|
||||
"alpha": 0.9,
|
||||
"liquid": { "range": 4 }
|
||||
"fluid": { "range": 4 }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -154,9 +153,9 @@ shore.
|
||||
top. `flowing` is on its sides and on a sloping top, turned to run downhill. A block shows as many of `flowing`'s
|
||||
pixels across as `still` has, so a 32×32 `flowing` next to a 16×16 `still` spreads over two blocks. With one texture,
|
||||
it's all of that texture on every side. Either can be [animated](../resources/textures.md#animated-textures).
|
||||
- `liquid.range` is how many blocks it flows from a source, 1 to 7, and `7` when not set.
|
||||
- `liquid.ticks` is how many ticks each step of its flow takes, `5` when not set, like Minecraft's water. Lava's is 30.
|
||||
- `liquid.renewable`, `true` when not set: a spot with two sources beside it and something solid or a source under it
|
||||
- `fluid.range` is how many blocks it flows from a source, 1 to 7, and `7` when not set.
|
||||
- `fluid.ticks` is how many ticks each step of its flow takes, `5` when not set, like Minecraft's water. Lava's is 30.
|
||||
- `fluid.renewable`, `true` when not set: a spot with two sources beside it and something solid or a source under it
|
||||
becomes a source too, like Minecraft's infinite water.
|
||||
- It gets a `level` [state](states.md) of its own, after any it lists: `0` is a source, a full block, and `1` up to
|
||||
`range` as it flows away from one, each lower.
|
||||
@@ -168,43 +167,43 @@ shore.
|
||||
|
||||
### Flowing
|
||||
|
||||
Liquids flow on the server like Minecraft's water. When a block next to a liquid changes, the cells around it are looked
|
||||
Fluids flow on the server like Minecraft's water. When a block next to a fluid changes, the cells around it are looked
|
||||
at again after its `ticks`, and each works out what it should be:
|
||||
|
||||
- A source stays a source.
|
||||
- With the same liquid above, it's falling, and drawn full.
|
||||
- Otherwise it's one level more than the lowest of the liquid beside it that spreads sideways, and gone once that's past
|
||||
`range`. Sources spread sideways, and flowing liquid only does when it's on something solid: over air or more of
|
||||
- With the same fluid above, it's falling, and drawn full.
|
||||
- Otherwise it's one level more than the lowest of the fluid beside it that spreads sideways, and gone once that's past
|
||||
`range`. Sources spread sideways, and flowing fluid only does when it's on something solid: over air or more of
|
||||
itself, it falls instead.
|
||||
|
||||
So it spreads one block a step, falls off edges and spreads again where it lands, and drains away a step at a time once
|
||||
its source is gone. It only flows into air, and stops at chunks that aren't loaded. Buckets only pick up sources. Flows
|
||||
still going when the server stops don't carry on after it starts again until something next to them changes.
|
||||
|
||||
`ctx.world.liquid_flow(x, y, z)` says which way the liquid in a block flows, like Minecraft's `FluidState.getFlow`: a
|
||||
vector 1 long toward the lower liquid beside it, and down where it falls against a wall, or `{ x: 0, y: 0, z: 0 }` where
|
||||
`ctx.world.fluid_flow(x, y, z)` says which way the fluid in a block flows, like Minecraft's `FluidState.getFlow`: a
|
||||
vector 1 long toward the lower fluid beside it, and down where it falls against a wall, or `{ x: 0, y: 0, z: 0 }` where
|
||||
it's still or there's none. It's the same flow that pushes players and items along, for machines it turns, like a water
|
||||
wheel.
|
||||
|
||||
### Waterlogging
|
||||
|
||||
A block that isn't a liquid can hold one, like Minecraft's waterlogged fences. `waterloggable` names the liquid:
|
||||
A block that isn't a fluid can hold one, like Minecraft's waterlogged fences. `waterloggable` names the fluid:
|
||||
|
||||
```json
|
||||
"waterloggable": "bworld:water"
|
||||
```
|
||||
|
||||
- It gets a `waterlogged` [state](states.md) of its own, after any it lists: `1` while it holds a source of the liquid.
|
||||
- It gets a `waterlogged` [state](states.md) of its own, after any it lists: `1` while it holds a source of the fluid.
|
||||
It uses one of the block's 16 bits.
|
||||
- Placed into a source of the liquid, it holds it. Placed into flowing liquid or anything else, it doesn't. With
|
||||
- Placed into a source of the fluid, it holds it. Placed into flowing fluid or anything else, it doesn't. With
|
||||
`"waterlogged_only": true` it can only be placed into a source, so it's always placed holding it, like Farmer's
|
||||
Delight's rice.
|
||||
- Using the liquid's item on it, like a water bucket, fills it. An item that aims at liquids, like a bucket, uses the
|
||||
liquid in it instead of the block, so a bucket takes the water back out and the block stays.
|
||||
- It's a source of the liquid that never drains: the liquid flows out of it, and entities swim and are pushed in it.
|
||||
Flowing liquid doesn't flow into it.
|
||||
- Broken, it leaves a source of the liquid behind.
|
||||
- Raycasts with `liquids` other than `"none"` hit the liquid in it, filling the block, and say the liquid's id.
|
||||
- Using the fluid's item on it, like a water bucket, fills it. An item that aims at fluids, like a bucket, uses the
|
||||
fluid in it instead of the block, so a bucket takes the water back out and the block stays.
|
||||
- It's a source of the fluid that never drains: the fluid flows out of it, and entities swim and are pushed in it.
|
||||
Flowing fluid doesn't flow into it.
|
||||
- Broken, it leaves a source of the fluid behind.
|
||||
- Raycasts with `fluids` other than `"none"` hit the fluid in it, filling the block, and say the fluid's id.
|
||||
|
||||
The base game's wooden fences are waterloggable, and Farmer's Delight's rice is `waterlogged_only`.
|
||||
|
||||
@@ -228,22 +227,22 @@ hook uses it to see where it lands, and with a player's
|
||||
[`eye_position` and `look_direction`](../entities/players.md#the-player-api) it finds what they're looking at:
|
||||
|
||||
```ts
|
||||
const hit = ctx.world.raycast(from, to, { liquids: "any" });
|
||||
const hit = ctx.world.raycast(from, to, { fluids: "any" });
|
||||
if (hit && "bworld:fishable" in ctx.blocks.components(hit.id)) {
|
||||
// hit.x, hit.y, hit.z is the block, hit.face the side it went in by, hit.position the exact point
|
||||
}
|
||||
```
|
||||
|
||||
It hits what entities bump into, so it goes through plants and other blocks with `"collision": false`. `liquids` is like
|
||||
It hits what entities bump into, so it goes through plants and other blocks with `"collision": false`. `fluids` is like
|
||||
Minecraft's `ClipContext.Fluid`:
|
||||
|
||||
| `liquids` | Hits |
|
||||
| ------------------ | ------------------------------------------- |
|
||||
| `"none"` (default) | No liquids, it goes through them. |
|
||||
| `"source_only"` | Liquid sources, going through flowing ones. |
|
||||
| `"any"` | Every liquid. |
|
||||
| `fluids` | Hits |
|
||||
| ------------------ | ------------------------------------------ |
|
||||
| `"none"` (default) | No fluids, it goes through them. |
|
||||
| `"source_only"` | Fluid sources, going through flowing ones. |
|
||||
| `"any"` | Every fluid. |
|
||||
|
||||
A liquid is hit at its surface, which is lower where it flows. It returns `undefined` when nothing is in the way.
|
||||
A fluid is hit at its surface, which is lower where it flows. It returns `undefined` when nothing is in the way.
|
||||
|
||||
`ctx.blocks.components(id)` gives the components a block's json lists and their params, like `ctx.items.components`, and
|
||||
`ctx.blocks.exists(id)` whether a block exists.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# Visuals
|
||||
|
||||
A visual draws a block with code, for blocks that move: a shaft that turns, a crank's handle, a press coming down. A
|
||||
client script registers one for a block, and every block of that kind in a shown chunk gets its own. It's bworld's
|
||||
version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create draws its machines with.
|
||||
A visual draws a block with code, for blocks that move or show what's in them: a shaft that turns, a press coming down,
|
||||
the items and fluid in a machine. A client script registers one for a block, and every block of that kind in a shown
|
||||
chunk gets its own. It's bworld's version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create
|
||||
draws its machines with.
|
||||
|
||||
## Registering
|
||||
|
||||
@@ -73,6 +74,52 @@ head.set_transform([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -0.5, 0, 1]); // half
|
||||
|
||||
`delete()` stops drawing an instance for good.
|
||||
|
||||
### Items
|
||||
|
||||
An **item** instance draws one of an item, whatever the stack's count, the way it looks in a slot: its model, its block,
|
||||
or its sprite with its [layers](../items/index.md#layers) in their colors, like a bottle with its juice. It's the size
|
||||
it's drawn on the ground (half a block across, a block's item a quarter), with its middle at the middle of the block,
|
||||
and it's placed by a matrix like a transformed model:
|
||||
|
||||
```ts
|
||||
import { mat4 } from "gl-matrix";
|
||||
|
||||
const stack = block.get_client_data<ItemStack>("stack");
|
||||
if (stack) {
|
||||
const item = instances.item(stack);
|
||||
const lying = mat4.fromTranslation(mat4.create(), [0.5, 0.2, 0.5]);
|
||||
mat4.rotateX(lying, lying, Math.PI / 2);
|
||||
mat4.translate(lying, lying, [-0.5, -0.5, -0.5]);
|
||||
item.set_transform(lying); // flat, a bit above the bottom of the block
|
||||
}
|
||||
```
|
||||
|
||||
The server tells the visual what to draw through [client data](tiledata.md#client-data), like the stack above. To draw a
|
||||
stack as more than one, like a basin with a copy for every 8 items, make an instance per copy. To change what an
|
||||
instance draws, delete it and make another.
|
||||
|
||||
### Fluids
|
||||
|
||||
A **fluid** instance draws a box of a [fluid](../resources/fluids.md), its `texture` tinted in its color for its data,
|
||||
like what's in a tank:
|
||||
|
||||
```ts
|
||||
const tank = block.get_client_data<{ fluid: FluidVariant; amount: number }>("tank");
|
||||
if (tank) {
|
||||
const juice = instances.fluid(tank.fluid);
|
||||
juice.set_box([2, 2, 2], [14, 2 + 12 * tank.amount / 1000, 14]); // filling the 12 pixels inside its walls
|
||||
}
|
||||
```
|
||||
|
||||
`set_box(from, to)` is in pixels, like a model's elements: 0 to 16 across the block, or past it for a box that reaches
|
||||
into the blocks around, like a tank's. The texture is cut to fit, never stretched, and repeats once a block. Nothing is
|
||||
drawn until a box is set, and it can be set again whenever the fluid goes up or down. Only the box's outside is drawn,
|
||||
so it can't be seen from inside it.
|
||||
|
||||
A fluid's box shows what's behind it, as much as its texture's alpha lets through. Boxes are drawn after the rest of the
|
||||
visuals, the farthest first. Translucent terrain like water is drawn after them, so water behind a box isn't seen
|
||||
through it.
|
||||
|
||||
## Moving Every Frame
|
||||
|
||||
A visual whose instances move in a way the time can't say, like a crank's handle slowing to a stop, moves them in
|
||||
@@ -105,3 +152,7 @@ Only visuals in chunks in view get `on_frame`, so keep anything that has to happ
|
||||
Every instance of a model is drawn in one draw call, and the GPU turns rotating instances by the time, so a block that
|
||||
keeps turning costs nothing per frame. Setting an instance's rotation or transform sends just that instance to the GPU
|
||||
again. What costs CPU time is `on_frame`, so use a rotating instance wherever the movement is steady.
|
||||
|
||||
Items that look the same are one model: every bottle of strawberry juice in every visual is one draw call, and one of
|
||||
melon juice another. A fluid's box is a model of its own, so each is a draw call, and setting its box sends its few
|
||||
faces to the GPU again.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Registries
|
||||
|
||||
Every block, item, block model, entity, entity model, status effect and texture has an id, and is registered under it
|
||||
once, while mods load. After that the game refers to things only by their id.
|
||||
Every block, item, block model, entity, entity model, status effect, fluid and texture has an id, and is registered
|
||||
under it once, while mods load. After that the game refers to things only by their id.
|
||||
|
||||
## Identifiers
|
||||
|
||||
@@ -32,9 +32,9 @@ The server and every client load mods the same way, in the same order:
|
||||
|
||||
1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend
|
||||
on each other in a circle are an error. The server sends its order to clients, and they follow it.
|
||||
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models, entities and effects.
|
||||
Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which can use
|
||||
tags.
|
||||
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models, entities, effects and
|
||||
fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which
|
||||
can use tags.
|
||||
3. **Scripts.** Server scripts' `setup` runs on the server, and client scripts' on each client. Worldgen scripts'
|
||||
`setup` runs on the server before it makes chunks.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -29,6 +29,7 @@ interface Player {
|
||||
readonly held_item: ItemStack | undefined;
|
||||
|
||||
give_item(id: string, count?: number, data?: unknown): void; // what doesn't fit drops at their feet
|
||||
exchange_held(result: ItemStack): void; // one of the held item becomes result, see below
|
||||
send_message(text: string, options?: { overlay?: boolean }): void; // in chat, or above the hotbar with overlay
|
||||
set_worn(key: string, items: ItemStack[]): void; // what's drawn on them, see Worn Items
|
||||
teleport(x: number, y: number, z: number): void;
|
||||
@@ -63,6 +64,10 @@ interface Player {
|
||||
`inventory` is a live [container](../inventories/containers.md), and `held_item` a live stack: changing them changes
|
||||
what the player has.
|
||||
|
||||
`exchange_held(result)` is for an item that turns into another when used, like an empty bucket filling: one of the held
|
||||
stack goes, and `result` goes straight into their hand when that was the last one, or into their inventory (at their
|
||||
feet when it's full) when there are more.
|
||||
|
||||
`eye_position` and `look_direction` are for aiming. With [`ctx.world.raycast`](../blocks/index.md#raycasts) they find
|
||||
what a player is looking at, like Minecraft's `getPlayerPOVHitResult`:
|
||||
|
||||
@@ -71,7 +76,7 @@ const eye = player.eye_position;
|
||||
const look = player.look_direction;
|
||||
const reach = player.attribute("bworld:block_interaction_range");
|
||||
const to = { x: eye.x + look.x * reach, y: eye.y + look.y * reach, z: eye.z + look.z * reach };
|
||||
const hit = ctx.world.raycast(eye, to, { liquids: "source_only" });
|
||||
const hit = ctx.world.raycast(eye, to, { fluids: "source_only" });
|
||||
```
|
||||
|
||||
## Health and Hunger
|
||||
|
||||
@@ -62,13 +62,13 @@ server reloads the page, so no old mod code stays loaded.
|
||||
|
||||
### Useful Commands In Game
|
||||
|
||||
| Command | What it does |
|
||||
| ---------------------- | ------------------------------------------------------- |
|
||||
| `/give <item> [count]` | Gives you an item |
|
||||
| `/summon <entity>` | Spawns an entity where you stand |
|
||||
| `/time set <when>` | Jumps to `day`, `noon`, `sunset`, `night` or `midnight` |
|
||||
| `/time add <ticks>` | Moves time forward, running every morning it passes |
|
||||
| `/help` | Lists every command |
|
||||
| Command | What it does |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `/give <item> [count]` | Gives you an item, see [Commands](../misc/commands.md#the-engines-commands) for data |
|
||||
| `/summon <entity>` | Spawns an entity where you stand |
|
||||
| `/time set <when>` | Jumps to `day`, `noon`, `sunset`, `night` or `midnight` |
|
||||
| `/time add <ticks>` | Moves time forward, running every morning it passes |
|
||||
| `/help` | Lists every command |
|
||||
|
||||
See [Commands](../misc/commands.md) for the rest, and for adding your own.
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ mods/
|
||||
models/*.geo.json # entity models
|
||||
entities/*.json
|
||||
effects/*.json # status effects, see entities/effects.md
|
||||
fluids/*.json # fluids that can be held, see resources/fluids.md
|
||||
recipes/*.json
|
||||
tags/<registry>/<namespace>/*.json # tags, see resources/tags.md
|
||||
loot_tables/**/*.json # loot tables, see resources/loot_tables.md
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -23,6 +23,28 @@ An item with a `food` property can be eaten. Players eat by right clicking while
|
||||
|
||||
Food that places a block, like potatoes with `places`, is planted when clicked somewhere it can go and eaten otherwise.
|
||||
|
||||
## Juice
|
||||
|
||||
Items that can be juiced, like fruit, have the base game's `bworld:juiceable` component:
|
||||
|
||||
```json
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 100, "color": "#c42d39" }
|
||||
}
|
||||
```
|
||||
|
||||
| Param | What it does |
|
||||
| ------- | ------------------------------------------------- |
|
||||
| `juice` | How much juice one makes, in mB. A bottle is 250. |
|
||||
| `color` | The juice's color, like `"#c42d39"`. |
|
||||
|
||||
All juice is one [fluid](../resources/fluids.md), `bworld:juice`, and the item it's made from is in its data:
|
||||
`{ "id": "bworld:juice", "data": { "item": "bworld:strawberry" } }`. The base game's rules name it after that item,
|
||||
"Strawberry Juice", in the color its component says, so juice from another mod's item needs nothing but the component.
|
||||
Juices from different items are different fluids, so they never share a bottle or a tank. Glass bottles
|
||||
(`bworld:glass_bottle`, 250 mB) and buckets (`bworld:bucket`, 1000 mB) hold it, and whatever makes juice reads the
|
||||
component.
|
||||
|
||||
## Hunger and Health
|
||||
|
||||
Hunger and health work like Minecraft's:
|
||||
|
||||
@@ -19,6 +19,9 @@ interface ItemStack {
|
||||
`data` is how one stack differs from another of the same item, like the water left in a watering can or the damage on a
|
||||
tool. It's saved, and synced to clients as part of the container the stack is in, so client code can read it.
|
||||
|
||||
Two stacks of one item only merge into one when their `data` is the same, whatever order its keys are in, in an
|
||||
inventory or on the ground. No data is the same as `{}`.
|
||||
|
||||
Stacks handed to server scripts are live: setting `count` or `data` on one changes the real stack, and a stack counted
|
||||
down to 0 is gone.
|
||||
|
||||
@@ -39,22 +42,24 @@ down to 0 is gone.
|
||||
|
||||
## Properties
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| ----------------- | ------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `id` | required | The item's id. |
|
||||
| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). |
|
||||
| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. |
|
||||
| `lore` | none | Tooltip text under the name. `\n` starts a new line. |
|
||||
| `max_stack` | `64`, `1` for tools | How many fit in one slot. |
|
||||
| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. |
|
||||
| `places` | none | A block it places when used on a block, like seeds. |
|
||||
| `tool` | none | Makes it a [tool](tools.md). |
|
||||
| `food` | none | Makes it [edible](food.md). |
|
||||
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
|
||||
| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture. |
|
||||
| `worn` | none | How it looks worn on a player, see [below](#worn-models). |
|
||||
| `targets_liquids` | `false` | Players holding it aim at liquids, like buckets and fishing rods. Others aim through. |
|
||||
| `components` | none | [Item components](#item-components) and their parameters. |
|
||||
| Field | Default | Meaning |
|
||||
| ----------------- | ------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `id` | required | The item's id. |
|
||||
| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). |
|
||||
| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. |
|
||||
| `lore` | none | Tooltip text under the name. `\n` starts a new line. |
|
||||
| `max_stack` | `64`, `1` for tools | How many fit in one slot. |
|
||||
| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. |
|
||||
| `places` | none | A block it places when used on a block, like seeds. |
|
||||
| `tool` | none | Makes it a [tool](tools.md). |
|
||||
| `food` | none | Makes it [edible](food.md). |
|
||||
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
|
||||
| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture. |
|
||||
| `worn` | none | How it looks worn on a player, see [below](#worn-models). |
|
||||
| `targets_fluids` | `false` | Players holding it aim at fluids, like buckets and fishing rods. Others aim through. |
|
||||
| `fluid_container` | none | Makes it hold a fluid, like a bucket, see [Fluids](../resources/fluids.md#containers). |
|
||||
| `layers` | none | Textures drawn over its own, each in a color, see [below](#layers). |
|
||||
| `components` | none | [Item components](#item-components) and their parameters. |
|
||||
|
||||
### Textures From Data
|
||||
|
||||
@@ -67,6 +72,29 @@ is out:
|
||||
|
||||
A stack whose `data.cast` is truthy uses `bworld:fishing_rod_cast`. When several keys are, the first listed wins.
|
||||
|
||||
### Layers
|
||||
|
||||
`layers` are textures drawn over the item's own, in order, like the fluid in a bucket or the trim on armor. Each can be
|
||||
drawn in a color, with `tint`:
|
||||
|
||||
```json
|
||||
"layers": [
|
||||
{ "texture": "copper_tools:jar_fluid", "tint": "fluid" },
|
||||
{ "texture": "copper_tools:jar_label", "tint": "#c42d39" }
|
||||
]
|
||||
```
|
||||
|
||||
| `tint` | The layer's drawn in |
|
||||
| --------------------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| none | Its own colors. |
|
||||
| a color, like `"#c42d39"` | That color. |
|
||||
| `"grass"`, `"foliage"`, `"water"` | That color outside any biome, like a block's [tint](../blocks/index.md#tinting) in its item. |
|
||||
| `"fluid"` | The color of the fluid a [fluid container](../resources/fluids.md#containers) holds. Not when empty. |
|
||||
|
||||
A tint multiplies the texture's colors, so a tinted layer is painted in light grays. A layer whose tint has no color for
|
||||
a stack, like `"fluid"` on an empty container, isn't drawn. Layers are drawn on the front and back of a flat item, so
|
||||
they should stay inside the item's own shape, and an item drawn with a `model` can't have them.
|
||||
|
||||
### Worn Models
|
||||
|
||||
`worn` says how an item looks on a player who wears it, like Bedrock's attachables. A server script says what a player
|
||||
@@ -218,8 +246,11 @@ const { item, given } = ctx.world.use_item_on({ id: "bworld:cobblestone", count:
|
||||
ctx.items.exists("bworld:carrot"); // true
|
||||
ctx.items.ids(); // every item, in load order
|
||||
ctx.items.max_stack("bworld:wood_pickaxe"); // 1
|
||||
ctx.items.max_stack(id, data); // the same for a stack with this data, fewer for a full fluid container
|
||||
ctx.items.fluid_capacity("bworld:bucket"); // how much a fluid container holds full, or undefined
|
||||
ctx.items.tool("bworld:wood_pickaxe"); // "pickaxe", or undefined for items that aren't tools
|
||||
ctx.items.sell_value("bworld:copper_coin"); // 1, or undefined for items without a base_sell_value
|
||||
|
||||
player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet
|
||||
player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this
|
||||
```
|
||||
|
||||
@@ -50,16 +50,17 @@ That's `/heal`, `/heal 5` and `/heal 5 alice`.
|
||||
|
||||
## Argument Types
|
||||
|
||||
| `types.` | Reads | Suggests |
|
||||
| --------------------- | --------------------------------------------------------------- | -------------- |
|
||||
| `integer(min?, max?)` | a whole number | |
|
||||
| `number(min?, max?)` | any number | |
|
||||
| `boolean()` | `true` or `false` | both |
|
||||
| `word()` | one word | |
|
||||
| `greedy_string()` | the rest of the line, spaces and all. Nothing can come after it | |
|
||||
| `choice([...])` | one of the given words | them |
|
||||
| `item()`, `block()` | an id. `carrot` works too, while only one mod has a `carrot` | ids |
|
||||
| `player()` | an online player's name, as a `Player` | online players |
|
||||
| `types.` | Reads | Suggests |
|
||||
| ------------------------------ | --------------------------------------------------------------- | -------------- |
|
||||
| `integer(min?, max?)` | a whole number | |
|
||||
| `number(min?, max?)` | any number | |
|
||||
| `boolean()` | `true` or `false` | both |
|
||||
| `word()` | one word | |
|
||||
| `greedy_string()` | the rest of the line, spaces and all. Nothing can come after it | |
|
||||
| `json()` | a JSON value, the rest of the line like `greedy_string()` | |
|
||||
| `choice([...])` | one of the given words | them |
|
||||
| `item()`, `block()`, `fluid()` | an id. `carrot` works too, while only one mod has a `carrot` | ids |
|
||||
| `player()` | an online player's name, as a `Player` | online players |
|
||||
|
||||
## Errors
|
||||
|
||||
@@ -107,7 +108,8 @@ Commands can only be registered during `setup`.
|
||||
|
||||
| Command | What it does |
|
||||
| ------------------------------------------------------- | -------------------------------------------------------------------- |
|
||||
| `/give <item> [count]` | Gives you an item |
|
||||
| `/give <item> [count] [data]` | Gives you an item, with `data` as JSON |
|
||||
| `/give <item> <count> fluid <fluid> [data]` | Gives you a fluid container full of the fluid, with the fluid's data |
|
||||
| `/effect <effect> [seconds]` | Gives you a status effect, for 30 seconds by default |
|
||||
| `/summon <entity>` | Spawns an entity where you are |
|
||||
| `/time` | Shows the time |
|
||||
@@ -120,3 +122,11 @@ Commands can only be registered during `setup`.
|
||||
| `/viewdistance [chunks]` | Shows or changes how far the server sends chunks, until it restarts |
|
||||
| `/skin [url] [slim\|normal]` | Changes your skin to a 64×64 PNG, or back to the default |
|
||||
| `/help [command]` | Every command's usage, or one's |
|
||||
|
||||
`/give`'s data is the stack's `data`, and with `fluid` it's the fluid's (see
|
||||
[Fluids](../resources/fluids.md#containers)):
|
||||
|
||||
```
|
||||
/give bworld:wood_pickaxe 1 {"damage": 5}
|
||||
/give bworld:glass_bottle 3 fluid bworld:juice {"item": "bworld:strawberry"}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# Fluids
|
||||
|
||||
Fluids are what bottles and tanks hold, like juice or oil. They work like NeoForge's `FluidType`s: a fluid is defined
|
||||
once, apart from any block, container or amount.
|
||||
|
||||
This isn't the same as a [block with `fluid`](../blocks/index.md#fluids), like water, which flows in the world. A fluid
|
||||
here has no block, so it can't be placed.
|
||||
|
||||
## Defining a Fluid
|
||||
|
||||
`fluids/maple_syrup.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"fluid": {
|
||||
"id": "copper_tools:maple_syrup",
|
||||
"name": "Maple Syrup",
|
||||
"color": "#a0522d",
|
||||
"texture": "bworld:water_still"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | What it does |
|
||||
| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `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. |
|
||||
| `texture` | no | What a [box of it](../blocks/visuals.md#fluids) is drawn with, tinted by its color, like NeoForge's still texture. See below. |
|
||||
|
||||
Like a fluid container's layer, the texture is multiplied by the fluid's color, so a light gray one comes out in the
|
||||
fluid's own color, and its alpha is how much shows through. The base game's `bworld:water_still` is such a texture,
|
||||
animated, and any fluid can use it. Without one, a box of the fluid is drawn with the missing texture.
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
## Containers
|
||||
|
||||
An item with `fluid_container` holds one fluid, full or empty, like a bucket or a bottle:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "copper_tools:jar",
|
||||
"texture": "copper_tools:jar",
|
||||
"max_stack": 16,
|
||||
"fluid_container": { "capacity": 250, "full_max_stack": 4 },
|
||||
"layers": [{ "texture": "copper_tools:jar_fluid", "tint": "fluid" }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | What it does |
|
||||
| ---------------- | -------- | ---------------------------------------------------------------------- |
|
||||
| `capacity` | yes | How much a full one holds, in mB. A bucket is 1000. |
|
||||
| `full_max_stack` | no | How many full ones fit in a slot. The item's `max_stack` when not set. |
|
||||
|
||||
A full one's stack data is `{ "fluid": <variant> }`, like
|
||||
`{ "fluid": { "id": "copper_tools:syrup", "data": { ... } } }`, and one without a `fluid` is empty. It's only ever full
|
||||
or empty, so there's no amount: a full one holds `capacity`. Stacks only merge when their data is the same, so jars of
|
||||
maple and birch syrup don't stack, and an empty jar doesn't stack with a full one.
|
||||
|
||||
What's in it is drawn with a [layer](../items/index.md#layers) tinted `"fluid"`, which is drawn in the fluid's
|
||||
[color](#rules) while it's full and not at all while it's empty. Its texture is the size of the item's, opaque only
|
||||
where the fluid shows, and light gray, since the color multiplies it: white comes out as the fluid's own color. Its
|
||||
tooltip says what's in it and how much, like "Birch Log Syrup, 250 mB".
|
||||
|
||||
A server script fills one with [`player.exchange_held`](../entities/players.md#the-player-api), which turns one of the
|
||||
held stack into the full one, and `ctx.items.fluid_capacity(id)` says how much it takes:
|
||||
|
||||
```ts
|
||||
const held = player.held_item;
|
||||
const capacity = held && ctx.items.fluid_capacity(held.id);
|
||||
if (capacity !== undefined && !held!.data) {
|
||||
player.exchange_held({ id: held!.id, count: 1, data: { fluid: { id: "copper_tools:syrup" } } });
|
||||
}
|
||||
```
|
||||
@@ -134,9 +134,9 @@ does nothing unless they hold.
|
||||
## Fishing
|
||||
|
||||
The fishing tables aren't files: the base game builds them from every item with the `bworld:fish` component, so a mod
|
||||
adds a fish by giving its item the component. A fish lives in one liquid, water unless its `liquid` says otherwise, and
|
||||
is in that liquid's table: the `loot_table` of its `bworld:fishable` component, `bworld:gameplay/fishing` when it
|
||||
doesn't name one. Water's is `bworld:gameplay/fishing` and lava's is `bworld:gameplay/lava_fishing`:
|
||||
adds a fish by giving its item the component. A fish lives in one fluid, water unless its `fluid` says otherwise, and is
|
||||
in that fluid's table: the `loot_table` of its `bworld:fishable` component, `bworld:gameplay/fishing` when it doesn't
|
||||
name one. Water's is `bworld:gameplay/fishing` and lava's is `bworld:gameplay/lava_fishing`:
|
||||
|
||||
```json
|
||||
"components": {
|
||||
@@ -153,7 +153,7 @@ doesn't name one. Water's is `bworld:gameplay/fishing` and lava's is `bworld:gam
|
||||
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `weight` | How often it's caught against the other fish, 1 when not given. |
|
||||
| `seasons` | The [seasons](../worldgen/biomes.md#seasons) it's caught in where the hook is, every one when not given. |
|
||||
| `liquid` | The `bworld:fishable` block it's caught in, `bworld:water` when not given, like `"bworld:lava"`. |
|
||||
| `fluid` | The `bworld:fishable` block it's caught in, `bworld:water` when not given, like `"bworld:lava"`. |
|
||||
| `biomes` | The [biomes](../worldgen/biomes.md#biome-ids) and [biome tags](../worldgen/biomes.md#biome-tags) it's caught in where the hook is, every one when not given. |
|
||||
| `time` | The hours it's caught at on a 24 hour clock, from `from` up to `to`, like `6.5` for 06:30. When `from` is past `to` it wraps around midnight. All day when not given. |
|
||||
| `minigame` | What the player does to land it once it's reeled in, in a screen that holds the fish until they win. Closing it lets the fish get away. Caught right away when not given. The base game's are `"test"`, a Catch button, `"hold"`, a bar that fills while the mouse is held and empties while it isn't: full lands the fish, empty loses it, `"valley"`, Stardew Valley's, where holding the mouse lifts a bar to keep the fish in it, `"ring"`, where a green ring grows out toward gray ones and clicking while it's inside each lands the fish, `"maze"`, where the mouse goes from the start to the end of a maze without touching its walls, in 8 seconds, and `"chess"`, a mate in one from Lichess's puzzles to find in 8 seconds. |
|
||||
|
||||
@@ -161,15 +161,15 @@ Built in names work with or without `minecraft:`.
|
||||
| `simple_block` | `to_place` | One block, where it can stand (its `place_on`). |
|
||||
| `block_column` | `layers` (`height`, `provider`), `direction`, `allowed_placement`, `prioritize_tip` | Layers stacked `up` (or `down`), cut short where `allowed_placement` doesn't hold (air when not set). |
|
||||
|
||||
| Placement modifier | Fields | Does |
|
||||
| ------------------------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `count` | `count` | Each position becomes `count` of them. |
|
||||
| `rarity_filter` | `chance` | Keeps one in `chance`. |
|
||||
| `in_square` | | Moves each to a random spot in the chunk, across. |
|
||||
| `random_offset` | `xz_spread`, `y_spread` | Moves each by those amounts. |
|
||||
| `height_range` | `height` | Sets the height: an anchor or `constant`/`uniform` of anchors. |
|
||||
| `heightmap` | `heightmap` | On top of the column: `WORLD_SURFACE_WG`, `WORLD_SURFACE` and `MOTION_BLOCKING` on its highest block, `OCEAN_FLOOR_WG` and `OCEAN_FLOOR` on its highest that isn't a liquid. |
|
||||
| `block_predicate_filter` | `predicate` | Keeps the positions where a block predicate holds. |
|
||||
| Placement modifier | Fields | Does |
|
||||
| ------------------------ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `count` | `count` | Each position becomes `count` of them. |
|
||||
| `rarity_filter` | `chance` | Keeps one in `chance`. |
|
||||
| `in_square` | | Moves each to a random spot in the chunk, across. |
|
||||
| `random_offset` | `xz_spread`, `y_spread` | Moves each by those amounts. |
|
||||
| `height_range` | `height` | Sets the height: an anchor or `constant`/`uniform` of anchors. |
|
||||
| `heightmap` | `heightmap` | On top of the column: `WORLD_SURFACE_WG`, `WORLD_SURFACE` and `MOTION_BLOCKING` on its highest block, `OCEAN_FLOOR_WG` and `OCEAN_FLOOR` on its highest that isn't a fluid. |
|
||||
| `block_predicate_filter` | `predicate` | Keeps the positions where a block predicate holds. |
|
||||
|
||||
- **Block predicates:** `matching_blocks` (`blocks`: ids and #tags), `solid`, `replaceable`, `would_survive` (`state`),
|
||||
`not`, `all_of`, `any_of` and `true`. Each takes an `offset`.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"block": {
|
||||
"id": "bworld:juicer",
|
||||
"name": "Juicer",
|
||||
"textures": {},
|
||||
"model": "bworld:juicer",
|
||||
"item_model": "bworld:juicer_item",
|
||||
"render_layer": "cutout",
|
||||
"shape": [
|
||||
[0, 0, 0, 16, 2, 16],
|
||||
[0, 2, 0, 2, 14, 2],
|
||||
[14, 2, 0, 16, 14, 2],
|
||||
[14, 2, 14, 16, 14, 16],
|
||||
[0, 2, 14, 2, 14, 16],
|
||||
[0, 14, 0, 16, 16, 16],
|
||||
[5, 8, 5, 11, 10, 11],
|
||||
[7, 10, 7, 9, 14, 9]
|
||||
],
|
||||
"mining": {
|
||||
"toughness": 2,
|
||||
"tool": "pickaxe"
|
||||
},
|
||||
"drops": "bworld:juicer",
|
||||
"interactive": true,
|
||||
"components": {
|
||||
"bworld:juicer": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
"render_layer": "cutout",
|
||||
"light_emission": 15,
|
||||
"item": false,
|
||||
"liquid": { "range": 3, "ticks": 30, "renewable": false },
|
||||
"fluid": { "range": 3, "ticks": 30, "renewable": false },
|
||||
"components": {
|
||||
"bworld:bucketable": {
|
||||
"into": "bworld:lava_bucket"
|
||||
|
||||
@@ -11,6 +11,6 @@
|
||||
"toughness": 1.5,
|
||||
"tool": "axe"
|
||||
},
|
||||
"loot_table": "bworld:blocks/melon"
|
||||
"drops": "bworld:melon"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"light_opacity": 1,
|
||||
"alpha": 0.8,
|
||||
"item": false,
|
||||
"liquid": {},
|
||||
"fluid": {},
|
||||
"components": {
|
||||
"bworld:water_source": {},
|
||||
"bworld:fishable": {},
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"fluid": {
|
||||
"id": "bworld:juice",
|
||||
"name": "Juice",
|
||||
"color": "#e8a33d",
|
||||
"texture": "bworld:water_still"
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
"saturation_modifier": 0.6
|
||||
},
|
||||
"places": "bworld:beetroots",
|
||||
"base_sell_value": 25
|
||||
"base_sell_value": 25,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 200, "color": "#e84c6e" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
"item": {
|
||||
"id": "bworld:bucket",
|
||||
"texture": "bworld:bucket",
|
||||
"targets_liquids": true,
|
||||
"max_stack": 16,
|
||||
"base_sell_value": 180
|
||||
"targets_fluids": true,
|
||||
"base_sell_value": 180,
|
||||
"fluid_container": { "capacity": 1000, "full_max_stack": 1 },
|
||||
"layers": [{ "texture": "bworld:bucket_fluid", "tint": "fluid" }]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"saturation_modifier": 0.6
|
||||
},
|
||||
"places": "bworld:carrots",
|
||||
"base_sell_value": 12
|
||||
"base_sell_value": 12,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 200, "color": "#c87f4b" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"item": {
|
||||
"id": "bworld:copper_watering_can",
|
||||
"texture": "bworld:copper_watering_can",
|
||||
"targets_liquids": true,
|
||||
"targets_fluids": true,
|
||||
"tool": {
|
||||
"type": "watering_can",
|
||||
"tier": 1,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "bworld:glass_bottle",
|
||||
"texture": "bworld:glass_bottle",
|
||||
"fluid_container": { "capacity": 250 },
|
||||
"layers": [{ "texture": "bworld:bottle_fluid", "tint": "fluid" }]
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"item": {
|
||||
"id": "bworld:gold_watering_can",
|
||||
"texture": "bworld:gold_watering_can",
|
||||
"targets_liquids": true,
|
||||
"targets_fluids": true,
|
||||
"tool": {
|
||||
"type": "watering_can",
|
||||
"tier": 0,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"item": {
|
||||
"id": "bworld:iron_watering_can",
|
||||
"texture": "bworld:iron_watering_can",
|
||||
"targets_liquids": true,
|
||||
"targets_fluids": true,
|
||||
"tool": {
|
||||
"type": "watering_can",
|
||||
"tier": 2,
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 2,
|
||||
"minigame": "valley",
|
||||
"difficulty": 90
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 8,
|
||||
"minigame": "ring",
|
||||
"difficulty": 61
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "bworld:melon",
|
||||
"base_sell_value": 60
|
||||
"base_sell_value": 60,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 1000, "color": "#aa3d33" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 10,
|
||||
"minigame": "valley",
|
||||
"difficulty": 50
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"saturation_modifier": 0.3
|
||||
},
|
||||
"places": "bworld:potatoes",
|
||||
"base_sell_value": 20
|
||||
"base_sell_value": 20,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 200, "color": "#c48a3f" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 1,
|
||||
"minigame": "maze",
|
||||
"difficulty": 110
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "bworld:pumpkin",
|
||||
"base_sell_value": 80
|
||||
"base_sell_value": 80,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 1000, "color": "#ea8734" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"item": {
|
||||
"id": "bworld:stone_watering_can",
|
||||
"texture": "bworld:stone_watering_can",
|
||||
"targets_liquids": true,
|
||||
"targets_fluids": true,
|
||||
"tool": {
|
||||
"type": "watering_can",
|
||||
"tier": 1,
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
"nutrition": 2,
|
||||
"saturation_modifier": 0.3
|
||||
},
|
||||
"base_sell_value": 30
|
||||
"base_sell_value": 30,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 200, "color": "#ff2840" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 4,
|
||||
"minigame": "ring",
|
||||
"difficulty": 81
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 0.1,
|
||||
"minigame": "hold",
|
||||
"difficulty": 50
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"components": {
|
||||
"bworld:fish": {
|
||||
"liquid": "bworld:lava",
|
||||
"fluid": "bworld:lava",
|
||||
"weight": 10,
|
||||
"minigame": "chess",
|
||||
"difficulty": 70
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"item": {
|
||||
"id": "bworld:wood_watering_can",
|
||||
"texture": "bworld:wood_watering_can",
|
||||
"targets_liquids": true,
|
||||
"targets_fluids": true,
|
||||
"tool": {
|
||||
"type": "watering_can",
|
||||
"tier": 0,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"model": {
|
||||
"id": "bworld:juicer",
|
||||
"textures": {
|
||||
"0": "bworld:juicer_side",
|
||||
"1": "bworld:juicer_bottom",
|
||||
"2": "bworld:juicer_top",
|
||||
"particle": "bworld:juicer_side"
|
||||
},
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [16, 2, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"top": { "texture": "#1", "uv": [0, 0, 16, 16] },
|
||||
"bottom": { "texture": "#1", "uv": [0, 0, 16, 16] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [0, 2, 0],
|
||||
"to": [2, 14, 2],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [14, 2, 0],
|
||||
"to": [16, 14, 2],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [14, 2, 14],
|
||||
"to": [16, 14, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [0, 2, 14],
|
||||
"to": [2, 14, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"model": {
|
||||
"id": "bworld:juicer_item",
|
||||
"textures": {
|
||||
"0": "bworld:juicer_side",
|
||||
"1": "bworld:juicer_bottom",
|
||||
"2": "bworld:juicer_top",
|
||||
"particle": "bworld:juicer_side"
|
||||
},
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [16, 2, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"top": { "texture": "#1", "uv": [0, 0, 16, 16] },
|
||||
"bottom": { "texture": "#1", "uv": [0, 0, 16, 16] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [0, 2, 0],
|
||||
"to": [2, 14, 2],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [14, 2, 0],
|
||||
"to": [16, 14, 2],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [14, 2, 14],
|
||||
"to": [16, 14, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [0, 2, 14],
|
||||
"to": [2, 14, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 12] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [0, 14, 0],
|
||||
"to": [16, 16, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"top": { "texture": "#2", "uv": [0, 0, 16, 16] },
|
||||
"bottom": { "texture": "#1", "uv": [0, 0, 16, 16] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [5, 8, 5],
|
||||
"to": [11, 10, 11],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"east": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"south": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"west": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"top": { "texture": "#2", "uv": [5, 5, 11, 11] },
|
||||
"bottom": { "texture": "#1", "uv": [5, 5, 11, 11] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [7, 10, 7],
|
||||
"to": [9, 14, 9],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"model": {
|
||||
"id": "bworld:juicer_press",
|
||||
"textures": {
|
||||
"0": "bworld:juicer_side",
|
||||
"1": "bworld:juicer_bottom",
|
||||
"2": "bworld:juicer_top",
|
||||
"particle": "bworld:juicer_side"
|
||||
},
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 14, 0],
|
||||
"to": [16, 16, 16],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 16, 2] },
|
||||
"top": { "texture": "#2", "uv": [0, 0, 16, 16] },
|
||||
"bottom": { "texture": "#1", "uv": [0, 0, 16, 16] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [5, 8, 5],
|
||||
"to": [11, 10, 11],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"east": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"south": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"west": { "texture": "#0", "uv": [5, 0, 11, 2] },
|
||||
"top": { "texture": "#2", "uv": [5, 5, 11, 11] },
|
||||
"bottom": { "texture": "#1", "uv": [5, 5, 11, 11] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"from": [7, 10, 7],
|
||||
"to": [9, 14, 9],
|
||||
"faces": {
|
||||
"north": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"east": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"south": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"west": { "texture": "#0", "uv": [0, 0, 2, 4] },
|
||||
"top": { "texture": "#0", "uv": [0, 0, 2, 2] },
|
||||
"bottom": { "texture": "#0", "uv": [0, 0, 2, 2] }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"recipe": {
|
||||
"type": "shaped",
|
||||
"pattern": [
|
||||
"G G",
|
||||
" G "
|
||||
],
|
||||
"key": {
|
||||
"G": "bworld:glass"
|
||||
},
|
||||
"result": {
|
||||
"id": "bworld:glass_bottle",
|
||||
"count": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,23 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the screens of the base game's menus, see scripts/server.ts for their slots. in gui pixels, like minecraft's
|
||||
import type { ClientContext, ClientMenu, Color, Graphics, ItemStack, MenuScreen } from "bworld/client";
|
||||
// the screens of the base game's menus, see scripts/server.ts for their slots. in gui pixels, like minecraft's. and the
|
||||
// juicer's visual
|
||||
import { mat4 } from "gl-matrix";
|
||||
import type {
|
||||
ClientContext,
|
||||
ClientMenu,
|
||||
Color,
|
||||
Graphics,
|
||||
Instance,
|
||||
Instances,
|
||||
ItemStack,
|
||||
MenuScreen,
|
||||
Visual,
|
||||
VisualBlock,
|
||||
} from "bworld/client";
|
||||
import { MINIGAMES } from "./minigames/mod.ts";
|
||||
import { JUICER_CAPACITY, JUICER_PRESSES, type JuicerTank } from "./shared.ts";
|
||||
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
|
||||
|
||||
const WIDTH = 176;
|
||||
@@ -18,6 +32,71 @@ export function setup(ctx: ClientContext) {
|
||||
ctx.ui.register_menu_screen("bworld:smithing_table", smithing_screen);
|
||||
ctx.ui.register_menu_screen("bworld:stonecutter", (menu) => stonecutter_screen(ctx, menu));
|
||||
ctx.ui.register_menu_screen("bworld:fishing_minigame", fishing_minigame_screen);
|
||||
ctx.render.register_visual("bworld:juicer", juicer_visual);
|
||||
}
|
||||
|
||||
// the middle of the bottom copy of what's in the juicer, just over its floor, and how much higher each next one is
|
||||
const JUICER_ITEM_Y = 4 / 16;
|
||||
const JUICER_COPY_RISE = 1 / 48;
|
||||
// how many more copies a stack this much bigger shows
|
||||
const JUICER_ITEMS_A_COPY = 16;
|
||||
// the juice fills the 12 by 12 pixels inside its walls from its floor up, a pixel deep while there's any and 12 when
|
||||
// it's full
|
||||
const JUICER_INSIDE = [2, 14];
|
||||
const JUICER_DEPTH = 12;
|
||||
// how far its press goes down, from where it rests to the floor, where the press that makes the juice would take it. it
|
||||
// goes a share of the way for each press toward the next juice, and back up once that's made
|
||||
const JUICER_PRESS_TRAVEL = 6 / 16;
|
||||
|
||||
// the juicer's press, what's in it and its juice, by its "presses", "stack" and "tank" client data (see register_juicer
|
||||
// in scripts/server.ts). the press is its own model, not part of the block's, so it can go down as it's pressed. the
|
||||
// items are drawn like create's basin draws its ingredients: tipped over and turned, with a copy more for every
|
||||
// JUICER_ITEMS_A_COPY. each copy is turned further and a bit higher than the one under it, so they pile up
|
||||
function juicer_visual(block: VisualBlock, instances: Instances): Visual {
|
||||
const press = instances.transformed("bworld:juicer_press");
|
||||
const press_target = () => JUICER_PRESS_TRAVEL * (block.get_client_data<number>("presses") ?? 0) / JUICER_PRESSES;
|
||||
// how far down the press is, and where the presses say it goes, which it catches up with a quarter of the way each
|
||||
// tick. one made mid way starts there
|
||||
let target = press_target();
|
||||
let down: number | undefined;
|
||||
let last: number | undefined;
|
||||
let shown: Instance[] = [];
|
||||
const update = () => {
|
||||
target = press_target();
|
||||
for (const instance of shown) instance.delete();
|
||||
shown = [];
|
||||
const tank = block.get_client_data<JuicerTank>("tank");
|
||||
if (tank) {
|
||||
const juice = instances.fluid(tank.fluid);
|
||||
const [low, high] = JUICER_INSIDE;
|
||||
const depth = Math.min(JUICER_DEPTH, Math.max(1, JUICER_DEPTH * tank.amount / JUICER_CAPACITY));
|
||||
juice.set_box([low, low, low], [high, low + depth, high]);
|
||||
shown.push(juice);
|
||||
}
|
||||
const stack = block.get_client_data<ItemStack>("stack");
|
||||
const copies = stack ? 1 + Math.floor(stack.count / JUICER_ITEMS_A_COPY) : 0;
|
||||
shown.push(...Array.from({ length: copies }, (_, i) => {
|
||||
const copy = instances.item(stack!);
|
||||
const matrix = mat4.fromTranslation(mat4.create(), [0.5, JUICER_ITEM_Y + i * JUICER_COPY_RISE, 0.5]);
|
||||
mat4.rotateY(matrix, matrix, (35 + i * 72) * Math.PI / 180);
|
||||
mat4.rotateX(matrix, matrix, 65 * Math.PI / 180);
|
||||
mat4.translate(matrix, matrix, [-0.5, -0.5, -0.5]);
|
||||
copy.set_transform(matrix);
|
||||
return copy;
|
||||
}));
|
||||
};
|
||||
update();
|
||||
return {
|
||||
update,
|
||||
on_frame(time) {
|
||||
const ticks = last === undefined ? 0 : time - last;
|
||||
last = time;
|
||||
if (down === target) return;
|
||||
down = down === undefined ? target : down + (target - down) * Math.min(1, ticks / 4);
|
||||
if (Math.abs(target - down) < 1 / 256) down = target;
|
||||
press.set_transform([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -down, 0, 1]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// a panel with the menu's title and the inventory's label over its rows, drawing anything else over it
|
||||
|
||||
@@ -15,9 +15,9 @@ const FISH = "bworld:fish";
|
||||
// the menu a fish's minigame is played in. client.ts gives it the minigame's screen, see minigames/mod.ts
|
||||
const MINIGAME_MENU = "bworld:fishing_minigame";
|
||||
// what's caught in a fishable block whose bworld:fishable doesn't name a table, like water. each table is built from
|
||||
// the items with bworld:fish that live in its liquid, see register_fishing
|
||||
// the items with bworld:fish that live in its fluid, see register_fishing
|
||||
const FISHING_TABLE = "bworld:gameplay/fishing";
|
||||
// the liquid a fish lives in when it doesn't say
|
||||
// the fluid a fish lives in when it doesn't say
|
||||
const WATER = "bworld:water";
|
||||
// further than this from the hook, the line snaps
|
||||
const LINE_LENGTH = 16;
|
||||
@@ -65,7 +65,7 @@ interface FishParams {
|
||||
// how hard its minigame is, 10 when not given. what it changes is up to the minigame
|
||||
difficulty?: number;
|
||||
// the fishable block it's caught in, bworld:water when not given. it's in that block's loot table
|
||||
liquid?: string;
|
||||
fluid?: string;
|
||||
}
|
||||
|
||||
interface Cast {
|
||||
@@ -111,7 +111,7 @@ export function register_fishing(ctx: ServerContext) {
|
||||
const fly = (cast: Cast, velocity: Position, now: number) => {
|
||||
const from = cast.position;
|
||||
const to = { x: from.x + velocity.x, y: from.y + velocity.y, z: from.z + velocity.z };
|
||||
const hit = ctx.world.raycast(from, to, { liquids: "any" });
|
||||
const hit = ctx.world.raycast(from, to, { fluids: "any" });
|
||||
if (!hit) {
|
||||
cast.position = to;
|
||||
velocity.x *= DRAG;
|
||||
@@ -167,7 +167,7 @@ export function register_fishing(ctx: ServerContext) {
|
||||
return from <= to ? hour >= from && hour < to : hour >= from || hour < to;
|
||||
});
|
||||
|
||||
// every item with bworld:fish is in its liquid's fishing table, caught in its seasons, at its hours and in its
|
||||
// every item with bworld:fish is in its fluid's fishing table, caught in its seasons, at its hours and in its
|
||||
// biomes
|
||||
ctx.components.register_item<FishParams>(FISH, {});
|
||||
const tables = new Map<string, { item: string; weight: number; conditions: { condition: string }[] }[]>([
|
||||
@@ -186,12 +186,12 @@ export function register_fishing(ctx: ServerContext) {
|
||||
if (fish.seasons) conditions.push({ condition: "bworld:season", seasons: fish.seasons });
|
||||
if (fish.time) conditions.push({ condition: "bworld:time", ...fish.time });
|
||||
if (fish.biomes) conditions.push({ condition: "bworld:biome", biomes: fish.biomes });
|
||||
const liquid = fish.liquid ?? WATER;
|
||||
if (!ctx.blocks.exists(liquid) || !(FISHABLE in ctx.blocks.components(liquid))) {
|
||||
throw new Error(`${id} is caught in ${liquid}, which isn't a block with ${FISHABLE}`);
|
||||
const fluid = fish.fluid ?? WATER;
|
||||
if (!ctx.blocks.exists(fluid) || !(FISHABLE in ctx.blocks.components(fluid))) {
|
||||
throw new Error(`${id} is caught in ${fluid}, which isn't a block with ${FISHABLE}`);
|
||||
}
|
||||
const entry = { item: id, weight: fish.weight ?? 1, conditions };
|
||||
const table = table_of(liquid);
|
||||
const table = table_of(fluid);
|
||||
tables.set(table, [...tables.get(table) ?? [], entry]);
|
||||
return [entry];
|
||||
});
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the base game's block and item behavior, written against the same api as any other mod
|
||||
import type { BlockRef, Container, Player, Season, ServerContext } from "bworld/server";
|
||||
import type { BlockRef, Container, FluidVariant, Player, Season, ServerContext } from "bworld/server";
|
||||
import { register_curios } from "./curios.ts";
|
||||
import { register_effects } from "./effects.ts";
|
||||
import { register_fishing } from "./fishing.ts";
|
||||
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
|
||||
import { register_verdigris } from "./verdigris/server.ts";
|
||||
import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES, type JuicerTank } from "./shared.ts";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
register_hoeable(ctx);
|
||||
@@ -24,6 +25,7 @@ export function setup(ctx: ServerContext) {
|
||||
register_door(ctx);
|
||||
register_trapdoor(ctx);
|
||||
register_buckets(ctx);
|
||||
register_juicer(ctx);
|
||||
register_curios(ctx);
|
||||
register_effects(ctx);
|
||||
register_growable_block(ctx);
|
||||
@@ -793,8 +795,8 @@ function register_farming(ctx: ServerContext) {
|
||||
});
|
||||
}
|
||||
|
||||
// buckets, like minecraft's: right clicking water with a bucket picks it up into a water bucket, which places it back
|
||||
// and is a bucket again
|
||||
// buckets, like minecraft's: right clicking water with an empty bucket picks it up into a water bucket, which places it
|
||||
// back and is a bucket again. a bucket is also a fluid container, so it can be full of juice, which it can't place
|
||||
|
||||
// right clicking it with a bucket takes it away, giving the filled bucket
|
||||
interface BucketableParams {
|
||||
@@ -812,20 +814,19 @@ function register_buckets(ctx: ServerContext) {
|
||||
ctx.components.register_block<BucketableParams>("bworld:bucketable", {
|
||||
on_interact(block, params, player) {
|
||||
const bucket = player.held_item;
|
||||
if (bucket?.id !== BUCKET) return false;
|
||||
if (bucket?.id !== BUCKET || (bucket.data as { fluid?: unknown } | undefined)?.fluid !== undefined) {
|
||||
return false;
|
||||
}
|
||||
const { x, y, z } = block;
|
||||
if (ctx.world.get_block(x, y, z) === block.id) {
|
||||
// only a liquid's source fills it, not where it's flowing
|
||||
// only a fluid's source fills it, not where it's flowing
|
||||
if ((ctx.world.get_state(x, y, z, "level") ?? 0) !== 0) return false;
|
||||
ctx.world.set_block(x, y, z, "bworld:air");
|
||||
} else {
|
||||
// the liquid in a waterlogged block, like a fence in water, which stays
|
||||
// the fluid in a waterlogged block, like a fence in water, which stays
|
||||
ctx.world.set_state(x, y, z, "waterlogged", 0);
|
||||
}
|
||||
bucket.count -= 1;
|
||||
// the last one becomes the filled bucket in the hand, from a stack it goes in the inventory
|
||||
if (bucket.count <= 0) player.inventory.set(player.selected_slot, { id: params.into, count: 1 });
|
||||
else player.give_item(params.into);
|
||||
player.exchange_held({ id: params.into, count: 1 });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -847,6 +848,84 @@ function register_buckets(ctx: ServerContext) {
|
||||
});
|
||||
}
|
||||
|
||||
// the juicer has no screen. right clicking it with something juiceable puts that in, one kind at a time, and
|
||||
// pressing it (sneaking with an empty hand) JUICER_PRESSES times turns one of it into its juice, while that fits in the
|
||||
// tank. right clicking it with an empty fluid container fills it from the tank. breaking it drops what's in it, and the
|
||||
// juice is lost. clients see what's in it, its juice and how many times it's been pressed toward the next as its
|
||||
// "stack", "tank" and "presses" client data, which its visual draws (see scripts/client.ts)
|
||||
const JUICE = "bworld:juice";
|
||||
|
||||
interface JuicerData {
|
||||
container?: string;
|
||||
// how many times it's been pressed toward the next juice
|
||||
presses?: number;
|
||||
tank?: JuicerTank;
|
||||
}
|
||||
|
||||
function register_juicer(ctx: ServerContext) {
|
||||
// what juice is made from, read by whatever makes it, like the juicer. the juice's name and color are in shared.ts
|
||||
ctx.components.register_item<JuiceableParams>("bworld:juiceable", {});
|
||||
const juiceable = (id: string) => ctx.items.components(id)["bworld:juiceable"] as JuiceableParams | undefined;
|
||||
const show = (block: BlockRef, container: Container) => {
|
||||
const item = container.get(0);
|
||||
const data = item?.data !== undefined && { data: item.data };
|
||||
block.set_client_data("stack", item && { id: item.id, count: item.count, ...data });
|
||||
};
|
||||
|
||||
ctx.components.register_block("bworld:juicer", {
|
||||
on_interact(block, _params, player) {
|
||||
const held = player.held_item;
|
||||
const container = block_container(ctx, block, 1);
|
||||
const data = block.data as JuicerData;
|
||||
if (held && juiceable(held.id)) {
|
||||
held.count = container.add(held)?.count ?? 0;
|
||||
show(block, container);
|
||||
// true even when none fit, so the fruit isn't eaten instead
|
||||
return true;
|
||||
}
|
||||
|
||||
const capacity = held && ctx.items.fluid_capacity(held.id);
|
||||
if (held && capacity !== undefined) {
|
||||
if ((held.data as { fluid?: unknown } | undefined)?.fluid !== undefined) return false;
|
||||
const tank = data.tank;
|
||||
if (!tank || tank.amount < capacity) return false;
|
||||
const amount = tank.amount - capacity;
|
||||
const left = amount > 0 ? { ...tank, amount } : undefined;
|
||||
block.data = { ...data, tank: left } satisfies JuicerData;
|
||||
block.set_client_data("tank", left);
|
||||
player.exchange_held({ id: held.id, count: 1, data: { fluid: tank.fluid } });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (held || !player.is_sneaking()) return false;
|
||||
const item = container.get(0);
|
||||
const params = item && juiceable(item.id);
|
||||
if (!item || !params) return false;
|
||||
const juice: FluidVariant = { id: JUICE, data: { item: item.id } };
|
||||
const tank = data.tank;
|
||||
const fits = (tank ? tank.amount : 0) + params.juice <= JUICER_CAPACITY &&
|
||||
(!tank || ctx.fluids.same(tank.fluid, juice));
|
||||
if (!fits) return false;
|
||||
const presses = (data.presses ?? 0) + 1;
|
||||
if (presses < JUICER_PRESSES) {
|
||||
block.data = { ...data, presses } satisfies JuicerData;
|
||||
block.set_client_data("presses", presses);
|
||||
return true;
|
||||
}
|
||||
item.count -= 1;
|
||||
show(block, container);
|
||||
const filled = { fluid: juice, amount: (tank?.amount ?? 0) + params.juice };
|
||||
block.data = { ...data, presses: 0, tank: filled } satisfies JuicerData;
|
||||
block.set_client_data("tank", filled);
|
||||
block.set_client_data("presses", undefined);
|
||||
return true;
|
||||
},
|
||||
on_break(block) {
|
||||
drop_contents(ctx, block);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
interface GrowableBlockParams {
|
||||
// what grows on top of it
|
||||
block_id: string;
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
|
||||
// the base game's block rules: how blocks are placed and how they change with the blocks beside them. they run on the
|
||||
// server and on every client, so players see a fence join or a trapdoor turn the moment they place it, and a trapdoor
|
||||
// or a door open the moment they click it
|
||||
import type { SharedBlock, SharedContext } from "bworld/shared";
|
||||
// or a door open the moment they click it. and the juice's rules, which name and color it by the item it's from
|
||||
import type { FluidVariant, SharedBlock, SharedContext } from "bworld/shared";
|
||||
import { register_verdigris_rules } from "./verdigris/shared.ts";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
@@ -12,6 +12,7 @@ export function setup(ctx: SharedContext) {
|
||||
register_trapdoor(ctx);
|
||||
register_door(ctx);
|
||||
register_verdigris_rules(ctx);
|
||||
register_juice(ctx);
|
||||
}
|
||||
|
||||
// the sides a fence connects on, and the face of the block there it connects to
|
||||
@@ -136,3 +137,38 @@ function register_door(ctx: SharedContext) {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// a juiceable item's component, like a strawberry's: juice is the mB one of it makes
|
||||
export interface JuiceableParams {
|
||||
juice: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
// how much juice the juicer holds, in mB, and the juice in it: in its tile data, and in its "tank" client data for its
|
||||
// visual to draw (see register_juicer in server.ts and juicer_visual in client.ts)
|
||||
export const JUICER_CAPACITY = 1000;
|
||||
// how many presses make one of what's in it into juice. its visual lowers its press for each one toward the next
|
||||
export const JUICER_PRESSES = 4;
|
||||
export interface JuicerTank {
|
||||
fluid: FluidVariant;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
// juice is one fluid for every fruit, like create's potion fluid: which fruit sits in its data, { item }. it's named
|
||||
// after that item, "Strawberry Juice", in the color its bworld:juiceable says
|
||||
function register_juice(ctx: SharedContext) {
|
||||
const item_of = (data: unknown) => {
|
||||
const item = (data as { item?: unknown } | undefined)?.item;
|
||||
return typeof item === "string" && ctx.items.exists(item) ? item : undefined;
|
||||
};
|
||||
ctx.fluids.register("bworld:juice", {
|
||||
name(data) {
|
||||
const item = item_of(data);
|
||||
return item && `${ctx.items.name(item)} Juice`;
|
||||
},
|
||||
color(data) {
|
||||
const item = item_of(data);
|
||||
return item && (ctx.items.components(item)["bworld:juiceable"] as JuiceableParams | undefined)?.color;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 5.6 KiB |
|
After Width: | Height: | Size: 304 B |
|
After Width: | Height: | Size: 217 B |
|
After Width: | Height: | Size: 344 B |
|
Before Width: | Height: | Size: 5.9 KiB |
@@ -7,6 +7,9 @@
|
||||
"nutrition": 2,
|
||||
"saturation_modifier": 0.4
|
||||
},
|
||||
"base_sell_value": 35
|
||||
"base_sell_value": 35,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 500, "color": "#7ab244" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
"nutrition": 1,
|
||||
"saturation_modifier": 0.3
|
||||
},
|
||||
"base_sell_value": 15
|
||||
"base_sell_value": 15,
|
||||
"components": {
|
||||
"bworld:juiceable": { "juice": 250, "color": "#c0341f" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||