Block visuals
This commit is contained in:
@@ -4,8 +4,8 @@ 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, R5, S0, S7, and stonecutting from S9. 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, R5, S0, S7, and stonecutting from S9. Facts
|
||||
about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -235,11 +235,14 @@ it's set to something else, like NeoForge's `getUpdateTag` but per field, so a f
|
||||
rest. It's saved, goes with the block, and client scripts read it with `ctx.world.get_client_data`. The display item is
|
||||
its `item` field now, so there's one way to sync block data. R2's visuals will be told when a field changes.
|
||||
|
||||
**R2. Block visuals** (P1). `ctx.render.register_visual(block_id, factory)` in client scripts. A visual is created when
|
||||
its chunk is meshed, updated when the block's client data or states change, and deleted with the block or chunk, like
|
||||
Flywheel's `Visual`. Most visuals only create instances and update them on change. A visual that has to animate on the
|
||||
CPU (a crank easing in, a press head) asks for a per-frame callback, like `DynamicVisual`. The engine keeps visuals per
|
||||
chunk and skips whole chunks outside the frustum.
|
||||
**R2. Block visuals** (P1, built). `ctx.render.register_visual(block_id, create, { replaces_model })` in client scripts,
|
||||
like Flywheel's `Visual`. The chunk mesher lists the blocks with visuals in each chunk it meshes, and leaves out the
|
||||
models of the ones whose visual replaces it, like `ENTITYBLOCK_ANIMATED`. A visual is made from that list, `update`d
|
||||
when a client data field changes, made again when the block's states change, and deleted with the block or chunk. It
|
||||
draws `rotating` and `transformed` instances of its block's model or of any model in `models/` by id, turned like a
|
||||
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 chunks in view are drawn. Until R3, instances are worked out on the CPU each frame
|
||||
and drawn in the entity batch, behind the same API, so R3 changes no mod.
|
||||
|
||||
**R3. Instanced drawing** (P1). A WebGPU pipeline that draws one model many times from an instance buffer, the thing
|
||||
bworld has none of today (`client/renderer/core.ts` only batches vertices). The instance types, matching Create's:
|
||||
@@ -256,7 +259,8 @@ light, updated when that light changes. `rotating` is the important one: thousan
|
||||
nothing per frame. See `ports/sodium` for how to keep buffer updates cheap.
|
||||
|
||||
**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.
|
||||
buffer, and turned for whatever axis it's used on. Loading by id and turning are built with R2, baked for the CPU, and
|
||||
the GPU buffers come with R3.
|
||||
|
||||
**R5. The model format** (P0, built). Everything Create's static models use: `parent`, `x` turns, `uvlock` on variants
|
||||
and parts, element `rotation` at any angle around one axis, and items drawn with models. An item's `model` draws it in
|
||||
@@ -274,7 +278,8 @@ glass can use it.
|
||||
their own, and drawn with the contraption's matrix each frame. Its moving parts (a drill on it, a bearing's shaft) are
|
||||
instances drawn relative to it. A block change on it remeshes only it.
|
||||
|
||||
**R8. Render time** (P1). World ticks plus the partial tick, as a shader uniform and for client scripts.
|
||||
**R8. Render time** (P1). World ticks plus the partial tick, as a shader uniform and for client scripts. Visuals get it
|
||||
in `on_frame` (`ClientLevel.ticks`, which doesn't jump with `/time`), and the uniform comes with R3.
|
||||
|
||||
**R9. Particles** (P3). A simple GPU particle system: sprite, velocity, gravity, lifetime. Used for rotation indicators,
|
||||
crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it can come late.
|
||||
|
||||
@@ -38,6 +38,7 @@ 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
|
||||
- [Crops](docs/modding/blocks/crops.md): farming without writing code
|
||||
|
||||
**Items**
|
||||
|
||||
@@ -32,6 +32,7 @@ import type { Entity } from "../entity/entity.ts";
|
||||
import type { ModelJson } from "$/common/block_models.ts";
|
||||
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
|
||||
import { BlockPredictions } from "./block_predictions.ts";
|
||||
import { block_visuals, Visuals } from "../rendering/visuals.ts";
|
||||
|
||||
export interface Block {
|
||||
id: string;
|
||||
@@ -126,6 +127,8 @@ export class ClientLevel {
|
||||
tick_timer = 0;
|
||||
// world time in ticks, counted here between the server's updates. see common/time.ts
|
||||
time = 0;
|
||||
// ticks since this client joined, which never jumps like time can, for what moves at a steady speed
|
||||
ticks = 0;
|
||||
// in chunks, what the server was asked to send
|
||||
view_distance: number;
|
||||
// the chunk the server says the player is in
|
||||
@@ -142,6 +145,7 @@ export class ClientLevel {
|
||||
entities = new Map<string, Entity>();
|
||||
// the client data of blocks that have some, see BlockRef.set_client_data, by chunk_key then position_key "x,y,z"
|
||||
block_data = new Map<number, Map<string, BlockData>>();
|
||||
visuals = new Visuals((x, y, z) => this.get_block_data(x, y, z));
|
||||
|
||||
// server_blocks is the server's block id for each of its numeric ids
|
||||
constructor(server_blocks: string[], view_distance: number) {
|
||||
@@ -165,6 +169,7 @@ export class ClientLevel {
|
||||
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")),
|
||||
textures_info: AssetManager.instance.get("bworld:textures_info"),
|
||||
image: { width: this.image.width, height: this.image.height },
|
||||
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -178,6 +183,7 @@ export class ClientLevel {
|
||||
|
||||
tick() {
|
||||
this.time += 1;
|
||||
this.ticks += 1;
|
||||
for (const entity of this.entities.values()) {
|
||||
entity.save_previous_position();
|
||||
entity.tick();
|
||||
@@ -253,6 +259,7 @@ export class ClientLevel {
|
||||
this.workers.terminate();
|
||||
for (const chunk of this.chunks.values()) {
|
||||
this.delete_chunk_mesh(chunk);
|
||||
this.visuals.unload(chunk.x, chunk.z);
|
||||
}
|
||||
this.chunks.clear();
|
||||
this.#dirty.clear();
|
||||
@@ -525,6 +532,7 @@ export class ClientLevel {
|
||||
this.chunks.delete(key);
|
||||
this.#dirty.delete(chunk);
|
||||
this.block_data.delete(key);
|
||||
this.visuals.unload(cx, cz);
|
||||
}
|
||||
|
||||
// see block_data in common/protocol.ts
|
||||
@@ -547,6 +555,7 @@ export class ClientLevel {
|
||||
} else if (blocks?.delete(position) && blocks.size === 0) {
|
||||
this.block_data.delete(key);
|
||||
}
|
||||
this.visuals.data_changed(x, y, z);
|
||||
}
|
||||
|
||||
get_block_data(x: number, y: number, z: number): Readonly<Record<string, unknown>> | undefined {
|
||||
@@ -643,6 +652,7 @@ export class ClientLevel {
|
||||
chunk.light = message.light;
|
||||
chunk.min_y = message.min_y;
|
||||
chunk.max_y = message.max_y;
|
||||
this.visuals.meshed(chunk.x, chunk.z, message.visuals);
|
||||
|
||||
for (const layer of RENDER_LAYERS) {
|
||||
const { vertices, quad_count, groups } = message[layer];
|
||||
|
||||
@@ -20,6 +20,7 @@ import { GuiModScreen } from "./gui/gui_mod_screens.ts";
|
||||
import { clear_hooks, expose_engine, loading_mod } from "$/common/hooks.ts";
|
||||
import { common_engine } from "$/common/engine_modules.ts";
|
||||
import { client_engine } from "./engine_modules.ts";
|
||||
import { block_visuals } from "./rendering/visuals.ts";
|
||||
import { biome_season } from "$/common/worldgen/biomes.ts";
|
||||
import type { LootTableJson } from "$/common/loot.ts";
|
||||
|
||||
@@ -53,6 +54,9 @@ export function receive_mod_message(channel: string, data: unknown) {
|
||||
export let block_rules = new BlockRules(run_mod);
|
||||
// whether shared scripts are being set up, the only time they can register rules
|
||||
let rules_setup = false;
|
||||
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
|
||||
// which blocks have them when the level starts
|
||||
let client_setup = false;
|
||||
|
||||
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
|
||||
try {
|
||||
@@ -147,6 +151,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
||||
inventory_overlays.length = 0;
|
||||
menu_screens.clear();
|
||||
net_handlers.clear();
|
||||
block_visuals.clear();
|
||||
mod_names.clear();
|
||||
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
||||
|
||||
@@ -172,6 +177,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
||||
}
|
||||
rules_setup = false;
|
||||
|
||||
client_setup = true;
|
||||
for (const [i, bmod] of bmods.entries()) {
|
||||
const code = bmod.scripts.client;
|
||||
if (!code) continue;
|
||||
@@ -183,6 +189,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
||||
await module.setup(client_context(listings[i]));
|
||||
});
|
||||
}
|
||||
client_setup = false;
|
||||
}
|
||||
|
||||
function script_url(code: string) {
|
||||
@@ -332,6 +339,17 @@ function client_context(listing: ModListing): ClientContext {
|
||||
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
|
||||
},
|
||||
tags: tag_api(),
|
||||
render: {
|
||||
register_visual(block, create, options) {
|
||||
if (!client_setup) throw new Error(`[${mod}] visuals can only be registered during setup`);
|
||||
const nid = EverythingRegistry.get_id("blocks", block);
|
||||
if (nid === undefined) throw new Error(`[${mod}] unknown block ${block}`);
|
||||
if (typeof create !== "function") throw new Error(`[${mod}] a visual needs a function that makes it`);
|
||||
const other = block_visuals.get(nid);
|
||||
if (other) throw new Error(`[${mod}] ${block} already has a visual, from ${other.mod}`);
|
||||
block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false });
|
||||
},
|
||||
},
|
||||
log: (...args) => console.log(`[${mod}]`, ...args),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -76,6 +76,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("translucent", () => level.render_translucent(client.level, camera));
|
||||
profiler.section("nameplates", () => render_nameplates(client.level, camera, client.player, partial_tick));
|
||||
end_mode_3d();
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
draw_terrain,
|
||||
flush_batch,
|
||||
get_current_texture,
|
||||
light_color,
|
||||
push_vertex,
|
||||
set_current_texture,
|
||||
Texture,
|
||||
@@ -37,6 +38,7 @@ import type { BlockHitResult } from "$/client/level/client_level.ts";
|
||||
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
|
||||
import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts";
|
||||
import { Frustum } from "./frustum.ts";
|
||||
import { draw_instance } from "./visuals.ts";
|
||||
|
||||
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
||||
export class LevelRenderer {
|
||||
@@ -44,7 +46,7 @@ export class LevelRenderer {
|
||||
// chunks in view this frame, worked out once for all the layers
|
||||
#visible: Chunk[] = [];
|
||||
// what to draw, switched off in the f3 performance window to see what each costs
|
||||
draw = { solid: true, cutout: true, translucent: true, entities: true };
|
||||
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
|
||||
|
||||
get visible_chunks() {
|
||||
return this.#visible.length;
|
||||
@@ -75,7 +77,8 @@ export class LevelRenderer {
|
||||
this.frustum.update(view_projection());
|
||||
this.#visible.length = 0;
|
||||
for (const chunk of level.chunks.values()) {
|
||||
if (Object.keys(chunk.meshes).length > 0 && this.#in_view(chunk)) {
|
||||
const drawn = Object.keys(chunk.meshes).length > 0 || level.visuals.has(chunk.x, chunk.z);
|
||||
if (drawn && this.#in_view(chunk)) {
|
||||
this.#visible.push(chunk);
|
||||
}
|
||||
}
|
||||
@@ -146,6 +149,18 @@ export class LevelRenderer {
|
||||
flush_batch();
|
||||
}
|
||||
|
||||
// blocks drawn with code, in the chunks in view, see client/rendering/visuals.ts
|
||||
render_visuals(level: ClientLevel, partial_tick: number) {
|
||||
if (!this.draw.visuals) return;
|
||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
||||
set_current_texture(level.image.tex);
|
||||
const time = level.ticks + partial_tick;
|
||||
level.visuals.render(this.#visible, time, (instance, x, y, z) => {
|
||||
draw_instance(atlas, instance, x, y, z, time, light_color(level.get_light(x, y, z)));
|
||||
});
|
||||
flush_batch();
|
||||
}
|
||||
|
||||
// the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab
|
||||
// or a plant cracks where it is and not on a whole cube around it
|
||||
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode) {
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per
|
||||
// block, made when its chunk is meshed, kept by chunk so chunks out of view are skipped, and drawn as instances of
|
||||
// models. instances are worked out on the cpu each frame and drawn in the same batch as entities
|
||||
import { mat4, vec3 } from "gl-matrix";
|
||||
import type {
|
||||
Instances,
|
||||
ModelRef,
|
||||
RotatingInstance,
|
||||
TransformedInstance,
|
||||
Visual,
|
||||
VisualBlock,
|
||||
} from "$/common/mod_api/client.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import {
|
||||
bake_block,
|
||||
bake_model,
|
||||
type BakedQuad,
|
||||
find_model,
|
||||
item_tint,
|
||||
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 { push_vertex, type Texture } from "$/client/renderer/mod.ts";
|
||||
import { get_sprite_region } from "$/client/sprites.ts";
|
||||
import { sprite_u, sprite_v } from "./item_renderer.ts";
|
||||
import type { Vec3 } from "./model_math.ts";
|
||||
|
||||
export interface VisualRegistration {
|
||||
mod: string;
|
||||
create: (block: VisualBlock, instances: Instances) => Visual;
|
||||
// the block's model isn't in the terrain, the visual draws all of it
|
||||
replaces_model: boolean;
|
||||
}
|
||||
|
||||
// each block's visual by the block's numeric id, see ctx.render.register_visual
|
||||
export const block_visuals = new Map<number, VisualRegistration>();
|
||||
|
||||
const AXES: Record<string, vec3> = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
|
||||
// a rotating instance turns this many degrees per tick at 1 rpm
|
||||
const DEGREES_PER_TICK = 360 / 60 / 20;
|
||||
|
||||
// a model's quads with the color each is tinted, white but for a block's own tinted quads, like leaves
|
||||
interface ModelQuads {
|
||||
quads: BakedQuad[];
|
||||
tints: number[][];
|
||||
}
|
||||
|
||||
// an instance as the engine keeps it, one of matrix or rotation
|
||||
export interface DrawnInstance extends ModelQuads {
|
||||
// from the model's space to the block's
|
||||
matrix?: mat4;
|
||||
rotation?: { axis: vec3; rpm: number; offset: number };
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
value: number;
|
||||
mod: string;
|
||||
// undefined when making it threw, until the block changes
|
||||
visual?: Visual;
|
||||
instances: Set<DrawnInstance>;
|
||||
// on_frame threw, so it isn't called again
|
||||
frame_failed?: boolean;
|
||||
}
|
||||
|
||||
// a level's visuals
|
||||
export class Visuals {
|
||||
// by chunk_key, then the block's index in its chunk
|
||||
#chunks = new Map<number, Map<number, Entry>>();
|
||||
#client_data: (x: number, y: number, z: number) => Readonly<Record<string, unknown>> | undefined;
|
||||
// baked once per level, since a level's mods don't change
|
||||
#models?: Record<string, ModelJson>;
|
||||
#model_quads = new Map<string, ModelQuads>();
|
||||
#block_quads = new Map<number, ModelQuads>();
|
||||
|
||||
constructor(client_data: (x: number, y: number, z: number) => Readonly<Record<string, unknown>> | undefined) {
|
||||
this.#client_data = client_data;
|
||||
}
|
||||
|
||||
has(chunk_x: number, chunk_z: number) {
|
||||
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
|
||||
}
|
||||
|
||||
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
|
||||
// for blocks that are gone or changed go, and new ones are made
|
||||
meshed(chunk_x: number, chunk_z: number, found: Uint32Array) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
const old = this.#chunks.get(key) ?? new Map<number, Entry>();
|
||||
const kept = new Map<number, Entry>();
|
||||
for (let i = 0; i < found.length; i += 2) {
|
||||
const index = found[i];
|
||||
const value = found[i + 1];
|
||||
const entry = old.get(index);
|
||||
old.delete(index);
|
||||
if (entry?.value === value) {
|
||||
kept.set(index, entry);
|
||||
continue;
|
||||
}
|
||||
if (entry) this.#delete(entry);
|
||||
const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE);
|
||||
const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE;
|
||||
const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value);
|
||||
if (made) kept.set(index, made);
|
||||
}
|
||||
for (const entry of old.values()) this.#delete(entry);
|
||||
if (kept.size > 0) this.#chunks.set(key, kept);
|
||||
else this.#chunks.delete(key);
|
||||
}
|
||||
|
||||
// a field of the block's client data changed
|
||||
data_changed(x: number, y: number, z: number) {
|
||||
const entry = this.#entry(x, y, z);
|
||||
if (entry?.visual?.update) run_visual(entry, "update", () => entry.visual!.update!());
|
||||
}
|
||||
|
||||
unload(chunk_x: number, chunk_z: number) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
for (const entry of this.#chunks.get(key)?.values() ?? []) this.#delete(entry);
|
||||
this.#chunks.delete(key);
|
||||
}
|
||||
|
||||
// the visuals in these chunks get their on_frame, then their instances are drawn
|
||||
render(
|
||||
chunks: Iterable<{ x: number; z: number }>,
|
||||
time: number,
|
||||
draw: (instance: DrawnInstance, x: number, y: number, z: number) => void,
|
||||
) {
|
||||
for (const chunk of chunks) {
|
||||
const entries = this.#chunks.get(chunk_key(chunk.x, chunk.z));
|
||||
if (!entries) continue;
|
||||
for (const entry of entries.values()) {
|
||||
const visual = entry.visual;
|
||||
if (visual?.on_frame && !entry.frame_failed) {
|
||||
entry.frame_failed = !run_visual(entry, "on_frame", () => visual.on_frame!(time));
|
||||
}
|
||||
for (const instance of entry.instances) draw(instance, entry.x, entry.y, entry.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#entry(x: number, y: number, z: number) {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const index = y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
|
||||
return this.#chunks.get(chunk_key(chunk_x, chunk_z))?.get(index);
|
||||
}
|
||||
|
||||
#create(x: number, y: number, z: number, value: number): Entry | undefined {
|
||||
const registration = block_visuals.get(value & ID_MASK);
|
||||
const block = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
|
||||
if (!registration || !block) return undefined;
|
||||
const entry: Entry = { x, y, z, value, mod: registration.mod, instances: new Set() };
|
||||
const client_data = this.#client_data;
|
||||
const view: VisualBlock = {
|
||||
id: block.id,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
states: Object.freeze(states_of(block, value)),
|
||||
get_client_data: (field) => structuredClone(client_data(x, y, z)?.[field]) as never,
|
||||
};
|
||||
const made = run_visual(entry, "create", () => {
|
||||
entry.visual = registration.create(view, this.#instances(entry, block));
|
||||
});
|
||||
// nothing it made before it threw is drawn
|
||||
if (!made) entry.instances.clear();
|
||||
return entry;
|
||||
}
|
||||
|
||||
#delete(entry: Entry) {
|
||||
const visual = entry.visual;
|
||||
if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!());
|
||||
entry.instances.clear();
|
||||
}
|
||||
|
||||
#instances(entry: Entry, block: BlockRegistry): Instances {
|
||||
const add = (model: ModelRef | undefined, instance: Omit<DrawnInstance, keyof ModelQuads>) => {
|
||||
const quads = model === undefined ? this.#quads_of_block(block, entry.value) : this.#quads_of(model);
|
||||
const added = { ...instance, ...quads };
|
||||
entry.instances.add(added);
|
||||
return added;
|
||||
};
|
||||
return {
|
||||
transformed(model): TransformedInstance {
|
||||
const instance = add(model, { matrix: mat4.create() });
|
||||
return {
|
||||
set_transform(matrix) {
|
||||
if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix");
|
||||
mat4.copy(instance.matrix!, matrix as mat4);
|
||||
},
|
||||
delete: () => void entry.instances.delete(instance),
|
||||
};
|
||||
},
|
||||
rotating(model): RotatingInstance {
|
||||
const instance = add(model, { rotation: { axis: AXES.y, rpm: 0, offset: 0 } });
|
||||
return {
|
||||
set_rotation(axis, rpm, offset = 0) {
|
||||
if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`);
|
||||
instance.rotation = { axis: AXES[axis], rpm, offset };
|
||||
},
|
||||
delete: () => void entry.instances.delete(instance),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
#quads_of(ref: ModelRef): ModelQuads {
|
||||
const { model, x = 0, y = 0 } = typeof ref === "string" ? { model: ref } : ref;
|
||||
const key = `${model} ${x} ${y}`;
|
||||
let quads = this.#model_quads.get(key);
|
||||
if (!quads) {
|
||||
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 baked = bake_model(json, undefined, y, x);
|
||||
quads = { quads: baked, tints: baked.map(() => [1, 1, 1]) };
|
||||
this.#model_quads.set(key, quads);
|
||||
}
|
||||
return quads;
|
||||
}
|
||||
|
||||
#quads_of_block(block: BlockRegistry, value: number): ModelQuads {
|
||||
let quads = this.#block_quads.get(value);
|
||||
if (!quads) {
|
||||
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
|
||||
const baked = bake_block(block, value, this.#models);
|
||||
quads = { quads: baked, tints: baked.map((quad) => item_tint(block, quad.variables)) };
|
||||
this.#block_quads.set(value, quads);
|
||||
}
|
||||
return quads;
|
||||
}
|
||||
}
|
||||
|
||||
// false when it threw, which is logged with the mod and block
|
||||
function run_visual(entry: Entry, what: string, fn: () => void) {
|
||||
try {
|
||||
fn();
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error(`[${entry.mod}] the visual at ${entry.x} ${entry.y} ${entry.z} threw in ${what}:`, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// where an instance's model goes at a time, as a matrix from its space to the world's
|
||||
export function instance_matrix(out: mat4, instance: DrawnInstance, x: number, y: number, z: number, time: number) {
|
||||
mat4.fromTranslation(out, [x, y, z]);
|
||||
if (instance.matrix) return mat4.multiply(out, out, instance.matrix);
|
||||
const { axis, rpm, offset } = instance.rotation!;
|
||||
const degrees = (time * rpm * DEGREES_PER_TICK + offset) % 360;
|
||||
mat4.translate(out, out, [0.5, 0.5, 0.5]);
|
||||
mat4.rotate(out, out, degrees * Math.PI / 180, axis);
|
||||
return mat4.translate(out, out, [-0.5, -0.5, -0.5]);
|
||||
}
|
||||
|
||||
// reused every quad of every frame
|
||||
const matrix = mat4.create();
|
||||
const corners = [vec3.create(), vec3.create(), vec3.create(), vec3.create()];
|
||||
const edge_a = vec3.create();
|
||||
const edge_b = vec3.create();
|
||||
const normal = vec3.create();
|
||||
|
||||
// an instance's quads into the batch, lit by tint. each quad is shaded by the way it faces after turning, like a
|
||||
// block's faces are by theirs. the atlas has to be the current texture
|
||||
export function draw_instance(
|
||||
atlas: Texture,
|
||||
instance: DrawnInstance,
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
time: number,
|
||||
[tr, tg, tb]: Vec3,
|
||||
) {
|
||||
instance_matrix(matrix, instance, x, y, z, time);
|
||||
for (const [q, quad] of instance.quads.entries()) {
|
||||
const p = quad.positions;
|
||||
for (let k = 0; k < 4; k++) {
|
||||
vec3.set(corners[k], p[k * 3], p[k * 3 + 1], p[k * 3 + 2]);
|
||||
vec3.transformMat4(corners[k], corners[k], matrix);
|
||||
}
|
||||
const shade = quad.shade ? facing_shade(corners) : 1;
|
||||
const [r, g, b] = instance.tints[q];
|
||||
const region = get_sprite_region(quad.texture);
|
||||
for (const k of [0, 1, 2, 0, 2, 3]) {
|
||||
const [px, py, pz] = corners[k];
|
||||
const u = sprite_u(atlas, region, quad.uvs[k * 2]);
|
||||
const v = sprite_v(atlas, region, quad.uvs[k * 2 + 1]);
|
||||
push_vertex(px, py, pz, u, v, shade * r * tr, shade * g * tg, shade * b * tb, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// how bright a quad facing this way is, blending the shades of the sides it faces between: 1 up, 0.5 down, 0.8
|
||||
// north and south, 0.6 east and west, like the chunk mesher's
|
||||
export function facing_shade([a, b, , d]: vec3[]) {
|
||||
vec3.cross(normal, vec3.sub(edge_a, b, a), vec3.sub(edge_b, d, a));
|
||||
vec3.normalize(normal, normal);
|
||||
const [nx, ny, nz] = normal;
|
||||
return nx * nx * 0.6 + nz * nz * 0.8 + ny * ny * (ny > 0 ? 1 : 0.5);
|
||||
}
|
||||
@@ -35,6 +35,9 @@ export type ToChunkWorker =
|
||||
models: Record<string, ModelJson>;
|
||||
textures_info: Record<string, SpriteRegion>;
|
||||
image: { width: number; height: number };
|
||||
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
|
||||
// ctx.render.register_visual
|
||||
visuals: [number, boolean][];
|
||||
}
|
||||
| {
|
||||
type: "mesh";
|
||||
@@ -89,6 +92,8 @@ export type FromChunkWorker =
|
||||
// the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's
|
||||
// packed light data. entities are lit from it
|
||||
light: Uint8Array<ArrayBuffer>;
|
||||
// the blocks in it with visuals, as pairs of the block's index in the chunk (like light's) and its value
|
||||
visuals: Uint32Array<ArrayBuffer>;
|
||||
}
|
||||
| {
|
||||
type: "sorted";
|
||||
|
||||
@@ -100,6 +100,10 @@ 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);
|
||||
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);
|
||||
const HAS_VISUAL = 1;
|
||||
const REPLACED_MODEL = 2;
|
||||
const region = new LightRegion();
|
||||
|
||||
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
|
||||
@@ -135,6 +139,10 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
models = message.models;
|
||||
baked.clear();
|
||||
build_block_tables();
|
||||
block_visual.fill(0);
|
||||
for (const [nid, replaces_model] of message.visuals) {
|
||||
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
|
||||
}
|
||||
textures_info = message.textures_info;
|
||||
image = message.image as Texture;
|
||||
break;
|
||||
@@ -142,7 +150,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
region.fill(message.chunks);
|
||||
region.compute(light_tables);
|
||||
blend_biome_colors(message.biome_colors);
|
||||
const { solid, cutout, translucent, min_y, max_y } = make_chunk_mesh(
|
||||
const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh(
|
||||
message.chunk_x,
|
||||
message.chunk_z,
|
||||
message.chunks,
|
||||
@@ -162,9 +170,11 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
||||
translucent,
|
||||
camera: message.camera,
|
||||
light,
|
||||
visuals,
|
||||
},
|
||||
[
|
||||
light.buffer,
|
||||
visuals.buffer,
|
||||
solid.vertices.buffer,
|
||||
cutout.vertices.buffer,
|
||||
translucent.vertices.buffer,
|
||||
@@ -644,6 +654,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
// for sorting the translucent quads
|
||||
let centers = new Float32Array(256);
|
||||
let faces = new Uint8Array(256);
|
||||
// the blocks with visuals, see "meshed"
|
||||
const visuals: number[] = [];
|
||||
|
||||
// where the neighbor on each face is, same order as FACE_NORMALS
|
||||
const face_offsets = FACE_NORMALS.map(([nx, ny, nz]) => nx + ny * REGION_LAYER + nz * REGION_SIZE);
|
||||
@@ -727,7 +739,16 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
if (liquid_nid === block_nid) continue;
|
||||
}
|
||||
|
||||
for (const quad of block_quads(values[y * CHUNK_AREA + z * CHUNK_SIZE + x])) {
|
||||
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
|
||||
if (block_visual[block_nid]) {
|
||||
visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value);
|
||||
// with the block above and below, since a visual can reach past its block, like a large cog
|
||||
if (y - 1 < mesh_min_y) mesh_min_y = y - 1;
|
||||
if (y + 2 > mesh_max_y) mesh_max_y = y + 2;
|
||||
if (block_visual[block_nid] === REPLACED_MODEL) continue;
|
||||
}
|
||||
|
||||
for (const quad of block_quads(value)) {
|
||||
if (quad.cull >= 0) {
|
||||
const neighbor = region_block(
|
||||
region,
|
||||
@@ -778,6 +799,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
||||
centers: centers.slice(0, quads.count * 3),
|
||||
planes: quad_planes(quads),
|
||||
},
|
||||
visuals: Uint32Array.from(visuals),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -70,9 +70,72 @@ export interface ClientContext {
|
||||
};
|
||||
// every mod's block, item and entity tags
|
||||
tags: TagApi;
|
||||
// blocks drawn with code, like a shaft that turns, see docs/modding/blocks/visuals.md
|
||||
render: ClientRender;
|
||||
log(...args: unknown[]): void;
|
||||
}
|
||||
|
||||
export interface ClientRender {
|
||||
// every block of this id gets a visual from create while its chunk is shown, like a block entity renderer or
|
||||
// flywheel's visuals. only during setup, and one per block. replaces_model leaves the block's model out of the
|
||||
// terrain, for a visual that draws all of it
|
||||
register_visual(
|
||||
block: Id,
|
||||
create: (block: VisualBlock, instances: Instances) => Visual,
|
||||
options?: { replaces_model?: boolean },
|
||||
): void;
|
||||
}
|
||||
|
||||
// the block a visual draws
|
||||
export interface VisualBlock {
|
||||
readonly id: Id;
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly z: number;
|
||||
// they stay the same for the visual's life, it's made again when they change
|
||||
readonly states: Readonly<Record<string, number>>;
|
||||
// a field of its client data now, a copy, see BlockRef.set_client_data in bworld/server
|
||||
get_client_data<T>(field: string): T | undefined;
|
||||
}
|
||||
|
||||
export interface Visual {
|
||||
// a field of its block's client data changed
|
||||
update?(): void;
|
||||
// before each frame its chunk is in view, for what moves on the cpu, like a crank slowing down. time is in ticks
|
||||
// with the part of the next one, the same time rotating instances turn by
|
||||
on_frame?(time: number): void;
|
||||
// it's going, with its block, with its chunk, or because its states changed. its instances go with it
|
||||
on_delete?(): void;
|
||||
}
|
||||
|
||||
// a model from models/ by id, turned like a block variant: x then y, in steps of 90 degrees
|
||||
export type ModelRef = Id | { model: Id; x?: number; y?: number };
|
||||
|
||||
// what a visual draws: models lit by the block's light. without a model, the block's own, the way its states draw it
|
||||
export interface Instances {
|
||||
// placed by a matrix, set again whenever it moves
|
||||
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;
|
||||
}
|
||||
|
||||
export interface Instance {
|
||||
// stops drawing it for good
|
||||
delete(): void;
|
||||
}
|
||||
|
||||
export interface TransformedInstance extends Instance {
|
||||
// a 4x4 matrix in column major order, like gl-matrix's mat4, from the model's space (0 to 1 across the block) to
|
||||
// the block's, where 0 0 0 is its corner. where the block is when not set
|
||||
set_transform(matrix: ArrayLike<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
|
||||
set_rotation(axis: "x" | "y" | "z", rpm: number, offset?: number): void;
|
||||
}
|
||||
|
||||
// the keys the player has bound, like the key mappings in minecraft's Options
|
||||
export interface KeyMappings {
|
||||
readonly key_forward: KeyCode;
|
||||
|
||||
@@ -76,7 +76,8 @@ ctx.components.register_block("copper_tools:shaft", {
|
||||
changes often doesn't resend the others, and setting a field to what it already is sends nothing.
|
||||
- `undefined` removes a field. All of them go when the block is broken or replaced.
|
||||
- It's saved with the world. `get_client_data` and `set_client_data` copy the value, so change it by setting it again.
|
||||
- Client scripts read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md).
|
||||
- Client scripts read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md). A block's
|
||||
[visual](visuals.md) reads it with `block.get_client_data`, and its `update` is called when a field changes.
|
||||
|
||||
Like NeoForge's `getUpdateTag`, but per field. Keep it to what clients need to draw the block: everything in it is sent
|
||||
to every player near it.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# 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.
|
||||
|
||||
## Registering
|
||||
|
||||
```ts
|
||||
import type { ClientContext } from "bworld/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.render.register_visual("copper_tools:shaft", (block, instances) => {
|
||||
const shaft = instances.rotating();
|
||||
const turn = () => shaft.set_rotation("y", block.get_client_data<number>("speed") ?? 0);
|
||||
turn();
|
||||
return { update: turn };
|
||||
}, { replaces_model: true });
|
||||
}
|
||||
```
|
||||
|
||||
- Visuals can only be registered during `setup`, and a block has at most one.
|
||||
- With `replaces_model: true`, the block's model is left out of the terrain, for a visual that draws all of the block,
|
||||
like the shaft above. Without it, the model is drawn as usual and the visual adds to it, like a press's head over its
|
||||
casing. The model is still what the block's item, its outline and the cracks on it while it's broken are drawn with.
|
||||
- `block` is `{ id, x, y, z, states, get_client_data }`. `get_client_data` reads a field of its
|
||||
[client data](tiledata.md#client-data) as it is now, which is how the server tells a visual what to draw.
|
||||
|
||||
## When Visuals Are Made
|
||||
|
||||
| Handler | Called when |
|
||||
| ---------------- | -------------------------------------------------------------------------------------- |
|
||||
| the function | The block's chunk is shown, or the block is placed or its states change. |
|
||||
| `update()` | A field of the block's client data changes. |
|
||||
| `on_frame(time)` | Before each frame its chunk is in view. See [Moving Every Frame](#moving-every-frame). |
|
||||
| `on_delete()` | The block or its chunk goes, the player leaves, or its states change. |
|
||||
|
||||
Changing a block's states makes its visual again, so `block.states` never changes. Instances go with their visual, so
|
||||
`on_delete` is only needed for something else the visual keeps.
|
||||
|
||||
A visual that throws is logged with its mod and block. One whose function threw isn't made again until the block
|
||||
changes, and an `on_frame` that throws isn't called again.
|
||||
|
||||
## Instances
|
||||
|
||||
A visual draws models as instances, lit by the block's light and shaded by the way each face points:
|
||||
|
||||
```ts
|
||||
instances.rotating(); // the block's own model, the way its states draw it
|
||||
instances.rotating("copper_tools:shaft_half"); // a model from models/
|
||||
instances.transformed({ model: "copper_tools:shaft_half", x: 90, y: 180 }); // turned like a block variant
|
||||
```
|
||||
|
||||
A **rotating** instance turns around an axis through the middle of the block at a steady speed:
|
||||
|
||||
```ts
|
||||
shaft.set_rotation("x", 32); // 32 rpm around x
|
||||
shaft.set_rotation("x", -32, 22.5); // the other way, 22.5 degrees along at time 0
|
||||
```
|
||||
|
||||
It's at `time × rpm × 0.3 + offset` degrees, counterclockwise seen from the axis's positive end when `rpm` is positive.
|
||||
It needs nothing per frame, only `set_rotation` again when the speed changes. Every instance on a client turns by the
|
||||
same time, so cogs set up to mesh stay meshed.
|
||||
|
||||
A **transformed** instance goes wherever a matrix puts it, set again whenever it moves. The matrix is 16 numbers in
|
||||
column major order, like gl-matrix's `mat4`, from the model's space (0 to 1 across the block) to the block's, where 0 0
|
||||
0 is its corner:
|
||||
|
||||
```ts
|
||||
const head = instances.transformed("copper_tools:press_head");
|
||||
head.set_transform([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -0.5, 0, 1]); // half a block down
|
||||
```
|
||||
|
||||
`delete()` stops drawing an instance for good.
|
||||
|
||||
## 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
|
||||
`on_frame`. `time` is in ticks, with the part of the next one, the same time rotating instances turn by:
|
||||
|
||||
```ts
|
||||
ctx.render.register_visual("copper_tools:crank", (block, instances) => {
|
||||
const handle = instances.rotating("copper_tools:crank_handle");
|
||||
let angle = 0;
|
||||
let speed = 0;
|
||||
let last: number | undefined;
|
||||
return {
|
||||
on_frame(time) {
|
||||
const ticks = last === undefined ? 0 : time - last;
|
||||
last = time;
|
||||
// catches up with the speed the server says, a quarter of the way each tick
|
||||
const target = block.get_client_data<number>("speed") ?? 0;
|
||||
speed += (target - speed) * Math.min(1, ticks / 4);
|
||||
angle += speed * 0.3 * ticks;
|
||||
handle.set_rotation("y", 0, angle);
|
||||
},
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
Only visuals in chunks in view get `on_frame`, so keep anything that has to happen out of view in the server script.
|
||||
|
||||
## Cost
|
||||
|
||||
Instances are worked out on the CPU each frame for now, a little for each one in view. A few hundred are fine.
|
||||
@@ -172,6 +172,9 @@ ctx.options.key_inventory; // the key the player has bound, like Minecraft's Opt
|
||||
|
||||
`ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not during `setup`.
|
||||
|
||||
To draw blocks that move, like a shaft that turns, register a [visual](../blocks/visuals.md) with
|
||||
`ctx.render.register_visual`.
|
||||
|
||||
The key mappings are `key_forward`, `key_back`, `key_left`, `key_right`, `key_jump`, `key_sprint`, `key_sneak`,
|
||||
`key_inventory`, `key_drop` and `key_chat`. A screen that should close on the inventory key, like the recipe viewer's,
|
||||
checks `g.key_pressed(ctx.options.key_inventory)` and calls `ctx.ui.close()`, the way JEI checks `keyInventory`.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// with the block
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { chunk_key, ClientLevel } from "$/client/level/client_level.ts";
|
||||
import { Visuals } from "$/client/rendering/visuals.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
|
||||
|
||||
@@ -90,6 +91,7 @@ Deno.test("the client keeps the fields it's sent for each block until they're re
|
||||
const level = Object.assign(Object.create(ClientLevel.prototype), {
|
||||
chunks: new Map([[chunk_key(0, 0), {}]]),
|
||||
block_data: new Map(),
|
||||
visuals: new Visuals(() => undefined),
|
||||
}) as ClientLevel;
|
||||
level.set_block_data(1, 99, 1, { speed: 16, axis: "x" });
|
||||
level.set_block_data(1, 99, 1, { speed: 32 });
|
||||
|
||||
@@ -19,6 +19,7 @@ async function mesh_light() {
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [],
|
||||
});
|
||||
|
||||
const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
|
||||
@@ -177,6 +177,7 @@ async function mesh(blocks: [number, number, number, string, number?][]) {
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [],
|
||||
});
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT));
|
||||
for (const [x, y, z, id, level] of blocks) {
|
||||
|
||||
@@ -58,6 +58,7 @@ async function mesh_chunks(radius: number) {
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [],
|
||||
});
|
||||
|
||||
const generated = new Map<string, Uint32Array>();
|
||||
|
||||
@@ -26,6 +26,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
|
||||
models: {},
|
||||
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [],
|
||||
});
|
||||
|
||||
const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// blocks drawn with code: the chunk mesher finds them, their visuals come and go with them and their chunks, and their
|
||||
// instances are placed and turned by the time
|
||||
import { assert, assertAlmostEquals, assertEquals, assertRejects } from "@std/assert";
|
||||
import { mat4, vec3 } from "gl-matrix";
|
||||
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
|
||||
import { block_value } from "$/common/utils.ts";
|
||||
import type { ModListing } from "$/common/mod_loader.ts";
|
||||
import { read_bmod } from "$/common/bmod.ts";
|
||||
import type { Visual } from "$/common/mod_api/client.ts";
|
||||
import {
|
||||
block_visuals,
|
||||
type DrawnInstance,
|
||||
facing_shade,
|
||||
instance_matrix,
|
||||
Visuals,
|
||||
} from "$/client/rendering/visuals.ts";
|
||||
import { load_client_mods } from "$/client/mods.ts";
|
||||
import { load_and_check } from "$/tools/check_mods.ts";
|
||||
import { pack_mod } from "$/tools/pack_mod.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
|
||||
const HALF = {
|
||||
textures: { "0": "testmod:shaft" },
|
||||
elements: [{ from: [6, 0, 6], to: [10, 8, 10], faces: { north: { texture: "#0" } } }],
|
||||
};
|
||||
|
||||
// testmod: a shaft with an axis state and a model of half of one, and maybe a client script
|
||||
function write_testmod(dir: string, client_script?: string) {
|
||||
const mod = `${dir}/testmod`;
|
||||
for (const folder of ["blocks", "models", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
|
||||
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
|
||||
write("manifest.json", {
|
||||
format_version: 1,
|
||||
id: "testmod",
|
||||
name: "Test",
|
||||
version: "1.0.0",
|
||||
...(client_script && { scripts: { client: "scripts/client.ts" } }),
|
||||
});
|
||||
write("blocks/shaft.json", {
|
||||
format_version: 1,
|
||||
block: {
|
||||
id: "testmod:shaft",
|
||||
textures: "testmod:shaft",
|
||||
render_layer: "cutout",
|
||||
states: [{ name: "axis", bits: 2, default: 1 }],
|
||||
mining: { toughness: 1 },
|
||||
},
|
||||
});
|
||||
write("models/half.json", { format_version: 1, model: { id: "testmod:half", ...HALF } });
|
||||
if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script);
|
||||
}
|
||||
|
||||
// a game's registries with mods/bworld and testmod
|
||||
async function registries() {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
write_testmod(dir);
|
||||
await test_game(dir);
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const nid = (id: string) => EverythingRegistry.get_id("blocks", id)!;
|
||||
const value = (id: string, state = 0) => block_value(nid(id), state);
|
||||
return { nid, value };
|
||||
}
|
||||
|
||||
const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
|
||||
|
||||
Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => {
|
||||
const { nid, value } = await registries();
|
||||
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
||||
worker.postMessage({
|
||||
type: "init",
|
||||
blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry<BlockRegistry>("blocks"))),
|
||||
models: Object.fromEntries(EverythingRegistry.entries("models")),
|
||||
textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
||||
image: { width: 1024, height: 1024 },
|
||||
visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]],
|
||||
});
|
||||
const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT));
|
||||
const middle = chunks[4];
|
||||
middle[index_of(1, 64, 1)] = value("bworld:stone");
|
||||
middle[index_of(4, 64, 1)] = value("bworld:cobblestone");
|
||||
middle[index_of(7, 64, 1)] = value("bworld:dirt");
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const meshed = await new Promise<any>((resolve) => {
|
||||
worker.onmessage = (e) => resolve(e.data);
|
||||
worker.postMessage({
|
||||
type: "mesh",
|
||||
chunk_x: 0,
|
||||
chunk_z: 0,
|
||||
version: 1,
|
||||
chunks,
|
||||
biome_colors: chunks.map(() => null),
|
||||
camera: [0, 0, 0],
|
||||
});
|
||||
});
|
||||
worker.terminate();
|
||||
|
||||
assertEquals([...meshed.visuals], [
|
||||
index_of(1, 64, 1),
|
||||
value("bworld:stone"),
|
||||
index_of(4, 64, 1),
|
||||
value("bworld:cobblestone"),
|
||||
]);
|
||||
// the cobblestone and the dirt, not the stone
|
||||
assertEquals(meshed.solid.quad_count, 12);
|
||||
// a visual can reach past its block, so the chunk is in view when that might be
|
||||
assert(meshed.min_y <= 63 && meshed.max_y >= 66, `${meshed.min_y} to ${meshed.max_y}`);
|
||||
});
|
||||
|
||||
Deno.test("a visual is made with its block, told when its client data changes, and goes with it", async () => {
|
||||
const { nid, value } = await registries();
|
||||
const log: string[] = [];
|
||||
const data: Record<string, unknown> = { speed: 16 };
|
||||
const visuals = new Visuals((x, y, z) => x === 1 && y === 64 && z === 1 ? data : undefined);
|
||||
block_visuals.clear();
|
||||
block_visuals.set(nid("testmod:shaft"), {
|
||||
mod: "testmod",
|
||||
replaces_model: true,
|
||||
create(block, instances): Visual {
|
||||
log.push(`create ${block.id} ${block.x} ${block.y} ${block.z} axis ${block.states.axis}`);
|
||||
instances.rotating().set_rotation("y", block.get_client_data<number>("speed")!);
|
||||
instances.transformed("testmod:half");
|
||||
return {
|
||||
update: () => log.push(`update ${block.get_client_data("speed")}`),
|
||||
on_frame: (time) => log.push(`frame ${time}`),
|
||||
on_delete: () => log.push(`delete ${block.x} ${block.y} ${block.z}`),
|
||||
};
|
||||
},
|
||||
});
|
||||
const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis));
|
||||
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
|
||||
// meshed again for something else, it stays
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
assertEquals(log.splice(0), []);
|
||||
|
||||
data.speed = 32;
|
||||
visuals.data_changed(1, 64, 1);
|
||||
visuals.data_changed(2, 64, 1);
|
||||
assertEquals(log.splice(0), ["update 32"]);
|
||||
|
||||
// only chunks in view are drawn, each instance where its block is
|
||||
const drawn: string[] = [];
|
||||
const draw = (instance: DrawnInstance, x: number, y: number, z: number) =>
|
||||
drawn.push(`${instance.rotation ? "rotating" : "transformed"} ${instance.quads.length} at ${x} ${y} ${z}`);
|
||||
visuals.render([{ x: 1, z: 0 }], 10.5, draw);
|
||||
assertEquals([log.splice(0), drawn.splice(0)], [[], []]);
|
||||
visuals.render([{ x: 0, z: 0 }], 10.5, draw);
|
||||
assertEquals(log.splice(0), ["frame 10.5"]);
|
||||
// the block's own model is a cube, the half model has one face
|
||||
assertEquals(drawn.splice(0), ["rotating 6 at 1 64 1", "transformed 1 at 1 64 1"]);
|
||||
|
||||
// its states changing makes it again
|
||||
visuals.meshed(0, 0, shaft(2));
|
||||
assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]);
|
||||
// and it goes with the block, or with the chunk
|
||||
visuals.meshed(0, 0, new Uint32Array());
|
||||
assertEquals(log.splice(0), ["delete 1 64 1"]);
|
||||
assert(!visuals.has(0, 0));
|
||||
visuals.meshed(0, 0, shaft(1));
|
||||
visuals.unload(0, 0);
|
||||
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]);
|
||||
visuals.render([{ x: 0, z: 0 }], 11, draw);
|
||||
assertEquals(drawn, []);
|
||||
block_visuals.clear();
|
||||
});
|
||||
|
||||
Deno.test("a visual that throws is logged and left out, and not made again until its block changes", async () => {
|
||||
const { nid, value } = await registries();
|
||||
let made = 0;
|
||||
block_visuals.clear();
|
||||
block_visuals.set(nid("testmod:shaft"), {
|
||||
mod: "testmod",
|
||||
replaces_model: false,
|
||||
create(block, instances) {
|
||||
made += 1;
|
||||
instances.rotating();
|
||||
if (block.states.axis === 1) throw new Error("broken");
|
||||
return {
|
||||
on_frame() {
|
||||
made += 1;
|
||||
throw new Error("broken every frame");
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
const visuals = new Visuals(() => undefined);
|
||||
const errors: unknown[] = [];
|
||||
const console_error = console.error;
|
||||
console.error = (...args) => errors.push(args);
|
||||
try {
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
|
||||
assertEquals([made, errors.length], [1, 1]);
|
||||
let drawn = 0;
|
||||
visuals.render([{ x: 0, z: 0 }], 0, () => drawn += 1);
|
||||
assertEquals(drawn, 0);
|
||||
|
||||
// an on_frame that throws isn't called again
|
||||
visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2)));
|
||||
for (let frame = 0; frame < 3; frame++) visuals.render([{ x: 0, z: 0 }], frame, () => {});
|
||||
assertEquals([made, errors.length], [3, 2]);
|
||||
} finally {
|
||||
console.error = console_error;
|
||||
block_visuals.clear();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("a rotating instance turns around its block's middle by the time, rpm and offset", () => {
|
||||
const near = (actual: ArrayLike<number>, expected: number[]) =>
|
||||
expected.forEach((v, i) => assertAlmostEquals(actual[i], v, 1e-9));
|
||||
const point = (instance: DrawnInstance, time: number, p: [number, number, number]) =>
|
||||
vec3.transformMat4(vec3.create(), p, instance_matrix(mat4.create(), instance, 10, 20, 30, time));
|
||||
const turning = (rpm: number, offset = 0): DrawnInstance => ({
|
||||
quads: [],
|
||||
tints: [],
|
||||
rotation: { axis: [0, 1, 0], rpm, offset },
|
||||
});
|
||||
// 50 rpm is 15 degrees a tick. a quarter turn counterclockwise seen from above takes east to north
|
||||
near(point(turning(50), 6, [1, 0.5, 0.5]), [10.5, 20.5, 30]);
|
||||
near(point(turning(50), 0, [1, 0.5, 0.5]), [11, 20.5, 30.5]);
|
||||
near(point(turning(-50), 6, [1, 0.5, 0.5]), [10.5, 20.5, 31]);
|
||||
near(point(turning(0, 90), 1000, [1, 0.5, 0.5]), [10.5, 20.5, 30]);
|
||||
|
||||
// a transformed one is where its matrix puts it in its block
|
||||
const moved: DrawnInstance = { quads: [], tints: [], matrix: mat4.fromTranslation(mat4.create(), [0, 0.25, 0]) };
|
||||
near(point(moved, 0, [0.5, 0, 0.5]), [10.5, 20.25, 30.5]);
|
||||
});
|
||||
|
||||
Deno.test("a turned quad is shaded between the sides it faces", () => {
|
||||
const quad = (corners: number[][]) => corners.map((c) => vec3.fromValues(c[0], c[1], c[2]));
|
||||
assertAlmostEquals(facing_shade(quad([[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]])), 1);
|
||||
assertAlmostEquals(facing_shade(quad([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]])), 0.5);
|
||||
// facing up and north at once
|
||||
assertAlmostEquals(facing_shade(quad([[0, 0, 0], [1, 0, 0], [1, 1, -1], [0, 1, -1]])), 0.9);
|
||||
});
|
||||
|
||||
Deno.test("client scripts register visuals during setup, for blocks that exist", async () => {
|
||||
const load = async (script: string) => {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
|
||||
write_testmod(dir, script);
|
||||
const mod = load_and_check(dir)[0];
|
||||
const bmod = read_bmod(await pack_mod(mod), "testmod.bmod");
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
|
||||
EverythingRegistry.clear();
|
||||
await load_client_mods([listing], [bmod]);
|
||||
};
|
||||
await load(`
|
||||
import type { ClientContext } from "bworld/client";
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.render.register_visual("testmod:shaft", (_block, instances) => {
|
||||
instances.rotating();
|
||||
return {};
|
||||
}, { replaces_model: true });
|
||||
}
|
||||
`);
|
||||
const visual = block_visuals.get(EverythingRegistry.get_id("blocks", "testmod:shaft")!);
|
||||
assertEquals([visual?.mod, visual?.replaces_model], ["testmod", true]);
|
||||
|
||||
await assertRejects(
|
||||
() =>
|
||||
load(`
|
||||
import type { ClientContext } from "bworld/client";
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.render.register_visual("testmod:gear", () => ({}));
|
||||
}
|
||||
`),
|
||||
Error,
|
||||
"unknown block testmod:gear",
|
||||
);
|
||||
block_visuals.clear();
|
||||
});
|
||||
Reference in New Issue
Block a user