Block visuals
This commit is contained in:
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user