Pipeline to draw models !
This commit is contained in:
@@ -145,7 +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));
|
||||
visuals = new Visuals(this);
|
||||
|
||||
// server_blocks is the server's block id for each of its numeric ids
|
||||
constructor(server_blocks: string[], view_distance: number) {
|
||||
@@ -259,8 +259,8 @@ 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.visuals.dispose();
|
||||
this.chunks.clear();
|
||||
this.#dirty.clear();
|
||||
}
|
||||
|
||||
+139
-14
@@ -24,6 +24,18 @@ const DEPTH_FORMAT: GPUTextureFormat = "depth24plus";
|
||||
|
||||
// dynamic uniform offsets have to be 256 aligned
|
||||
const UNIFORM_SLOT_SIZE = 256;
|
||||
// the matrix, then the render time and padding to 16 bytes
|
||||
const UNIFORM_FLOATS = 20;
|
||||
// the render time wraps around after this many ticks, so a 32 bit float keeps it precise however long the game runs.
|
||||
// a whole number of turns for every speed in steps of 0.05 rpm, so those don't jump when it wraps
|
||||
const RENDER_TIME_PERIOD = 24000;
|
||||
|
||||
// a vertex of an instanced model, 24 bytes: position as float32x3, atlas uv as unorm16x2, tint as unorm8x3 with alpha 1
|
||||
// when the face is shaded by the way it faces, and the face's normal as snorm8x3 and a padding byte
|
||||
export const MODEL_VERTEX_BYTES = 24;
|
||||
// an instance, 24 floats: the matrix placing its model in the world (4 columns), the axis it spins around and its rpm,
|
||||
// then its offset in degrees, its block light and sky light as lightmap coordinates and a padding float
|
||||
export const INSTANCE_FLOATS = 24;
|
||||
|
||||
let context: GPUCanvasContext;
|
||||
let canvas_format: GPUTextureFormat;
|
||||
@@ -31,6 +43,7 @@ let canvas_format: GPUTextureFormat;
|
||||
let pipeline_2d: GPURenderPipeline;
|
||||
let pipeline_3d: GPURenderPipeline;
|
||||
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
|
||||
let instance_pipeline: 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;
|
||||
@@ -53,6 +66,9 @@ let stream_offset = 0;
|
||||
let uniform_buffer: GPUBuffer;
|
||||
let uniform_bind_group: GPUBindGroup;
|
||||
let uniform_slot = -1;
|
||||
const uniform_data = new Float32Array(UNIFORM_FLOATS);
|
||||
// in ticks, see set_render_time
|
||||
let render_time = 0;
|
||||
|
||||
const texture_bind_groups = new WeakMap<GPUTexture, GPUBindGroup>();
|
||||
|
||||
@@ -139,9 +155,11 @@ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
|
||||
}
|
||||
`;
|
||||
|
||||
const terrain_shader_src = /* wgsl */ `
|
||||
export const terrain_shader_src = /* wgsl */ `
|
||||
struct Uniforms {
|
||||
mvp: mat4x4<f32>,
|
||||
// ticks, see set_render_time
|
||||
time: f32,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
|
||||
@@ -174,6 +192,43 @@ fn vs_terrain(
|
||||
return out;
|
||||
}
|
||||
|
||||
// v turned angle radians around axis, counterclockwise seen from the axis's end
|
||||
fn spun(v: vec3<f32>, axis: vec3<f32>, angle: f32) -> vec3<f32> {
|
||||
return v * cos(angle) + cross(axis, v) * sin(angle) + axis * dot(axis, v) * (1.0 - cos(angle));
|
||||
}
|
||||
|
||||
// a model drawn many times, once per instance, see client/rendering/visuals.ts. it's turned around its block's middle
|
||||
// by spin (rpm times a minute, plus the offset) before placement puts it in the world. its faces are shaded by the
|
||||
// way they face after that, like the chunk mesher's, and lit by the light the instance has
|
||||
@vertex
|
||||
fn vs_instance(
|
||||
@location(0) position: vec3<f32>,
|
||||
@location(1) tex_coord: vec2<f32>,
|
||||
@location(2) color: vec4<f32>,
|
||||
@location(3) normal: vec4<f32>,
|
||||
@location(4) placement0: vec4<f32>,
|
||||
@location(5) placement1: vec4<f32>,
|
||||
@location(6) placement2: vec4<f32>,
|
||||
@location(7) placement3: vec4<f32>,
|
||||
// the axis, then rpm
|
||||
@location(8) spin: vec4<f32>,
|
||||
// the offset in degrees, then block light and sky light as lightmap coordinates
|
||||
@location(9) offset_light: vec4<f32>,
|
||||
) -> VertexOut {
|
||||
let placement = mat4x4<f32>(placement0, placement1, placement2, placement3);
|
||||
// in turns first, which fract keeps small. a minute is 1200 ticks
|
||||
let angle = fract(uniforms.time * spin.w / 1200.0 + offset_light.x / 360.0) * 6.2831853;
|
||||
let local = spun(position - vec3<f32>(0.5), spin.xyz, angle) + vec3<f32>(0.5);
|
||||
let n = normalize((placement * vec4<f32>(spun(normal.xyz, spin.xyz, angle), 0.0)).xyz);
|
||||
let shade = n.x * n.x * 0.6 + n.z * n.z * 0.8 + n.y * n.y * select(0.5, 1.0, n.y > 0.0);
|
||||
var out: VertexOut;
|
||||
out.position = uniforms.mvp * placement * vec4<f32>(local, 1.0);
|
||||
out.tex_coord = tex_coord;
|
||||
out.color = vec4<f32>(color.rgb * select(1.0, shade, color.a > 0.5), 1.0);
|
||||
out.light = offset_light.yz;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn lit(in: VertexOut) -> vec4<f32> {
|
||||
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
||||
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), texel.a * in.color.a);
|
||||
@@ -423,6 +478,12 @@ export function light_color(packed: number): [number, number, number] {
|
||||
return [lightmap_colors[i], lightmap_colors[i + 1], lightmap_colors[i + 2]];
|
||||
}
|
||||
|
||||
// the time rotating instances turn by, in ticks with the part of the next one (see ClientLevel.ticks). the frame's 3d
|
||||
// drawing uses the time set before begin_mode_3d
|
||||
export function set_render_time(ticks: number) {
|
||||
render_time = ticks % RENDER_TIME_PERIOD;
|
||||
}
|
||||
|
||||
export function end_mode_3d() {
|
||||
if (!mode3d) {
|
||||
return;
|
||||
@@ -514,6 +575,34 @@ export function draw_terrain(
|
||||
frame_stats.quads[layer] += quad_count;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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;
|
||||
terrain_binds = undefined;
|
||||
}
|
||||
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
|
||||
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
||||
render_pass.setBindGroup(2, lightmap_bind_group);
|
||||
render_pass.setIndexBuffer(quad_index_buffer!, "uint32");
|
||||
render_pass.setVertexBuffer(0, model);
|
||||
render_pass.setVertexBuffer(1, instances);
|
||||
render_pass.drawIndexed(quad_count * 6, instance_count);
|
||||
frame_stats.draw_calls += 1;
|
||||
}
|
||||
|
||||
// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element
|
||||
export function write_buffer(buffer: GPUBuffer, byte_offset: number, data: Float32Array, first: number, count: number) {
|
||||
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
|
||||
}
|
||||
|
||||
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
|
||||
export function view_projection(): Readonly<Float32Array> {
|
||||
return mvp as Float32Array;
|
||||
@@ -788,8 +877,9 @@ function write_mvp() {
|
||||
uniform_slot = 0;
|
||||
}
|
||||
|
||||
const matrix = mode3d ? mvp : ortho;
|
||||
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, matrix as Float32Array);
|
||||
uniform_data.set(mode3d ? mvp : ortho);
|
||||
uniform_data[16] = render_time;
|
||||
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, uniform_data);
|
||||
}
|
||||
|
||||
function update_camera() {
|
||||
@@ -824,7 +914,7 @@ function create_pipelines() {
|
||||
entries: [{
|
||||
binding: 0,
|
||||
visibility: GPUShaderStage.VERTEX,
|
||||
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 64 },
|
||||
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: UNIFORM_FLOATS * 4 },
|
||||
}],
|
||||
});
|
||||
texture_layout ??= device.createBindGroupLayout({
|
||||
@@ -907,15 +997,19 @@ function create_pipelines() {
|
||||
};
|
||||
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
|
||||
// since it's drawn sorted back to front
|
||||
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState, alphaToCoverageEnabled = false) =>
|
||||
device.createRenderPipeline({
|
||||
layout: terrain_layout,
|
||||
vertex: terrain_vertex,
|
||||
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
|
||||
multisample: { ...multisample, alphaToCoverageEnabled },
|
||||
primitive: primitive_3d,
|
||||
depthStencil: depth_3d,
|
||||
});
|
||||
const terrain_pipeline = (
|
||||
entryPoint: string,
|
||||
blend?: GPUBlendState,
|
||||
alphaToCoverageEnabled = false,
|
||||
vertex = terrain_vertex,
|
||||
) => device.createRenderPipeline({
|
||||
layout: terrain_layout,
|
||||
vertex,
|
||||
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
|
||||
multisample: { ...multisample, alphaToCoverageEnabled },
|
||||
primitive: primitive_3d,
|
||||
depthStencil: depth_3d,
|
||||
});
|
||||
terrain_pipelines = {
|
||||
solid: terrain_pipeline("fs_solid"),
|
||||
// alpha to coverage needs msaa
|
||||
@@ -927,8 +1021,39 @@ function create_pipelines() {
|
||||
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||
}),
|
||||
};
|
||||
// instances are cut out like cutout terrain
|
||||
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);
|
||||
}
|
||||
|
||||
// how vs_instance reads a model's vertices and its instances
|
||||
export const INSTANCED_BUFFERS: GPUVertexBufferLayout[] = [
|
||||
{
|
||||
arrayStride: MODEL_VERTEX_BYTES,
|
||||
attributes: [
|
||||
{ shaderLocation: 0, offset: 0, format: "float32x3" },
|
||||
{ shaderLocation: 1, offset: 12, format: "unorm16x2" },
|
||||
{ shaderLocation: 2, offset: 16, format: "unorm8x4" },
|
||||
{ shaderLocation: 3, offset: 20, format: "snorm8x4" },
|
||||
],
|
||||
},
|
||||
{
|
||||
arrayStride: INSTANCE_FLOATS * 4,
|
||||
stepMode: "instance",
|
||||
attributes: [4, 5, 6, 7, 8, 9].map((location, i) => ({
|
||||
shaderLocation: location,
|
||||
offset: i * 16,
|
||||
format: "float32x4" as const,
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
function create_stream_buffer(size: number) {
|
||||
return device.createBuffer({ size, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
||||
}
|
||||
@@ -940,7 +1065,7 @@ function create_uniform_buffer(slots: number) {
|
||||
});
|
||||
uniform_bind_group = device.createBindGroup({
|
||||
layout: uniform_layout,
|
||||
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: 64 } }],
|
||||
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: UNIFORM_FLOATS * 4 } }],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
clear_background,
|
||||
draw_rect,
|
||||
end_mode_3d,
|
||||
set_render_time,
|
||||
update_lightmap,
|
||||
} from "$/client/renderer/mod.ts";
|
||||
import { daylight } from "$/common/time.ts";
|
||||
@@ -68,6 +69,7 @@ export class GameRenderer {
|
||||
camera.setup(client.player, partial_tick);
|
||||
this.#setup_sky(client, partial_tick);
|
||||
|
||||
set_render_time(client.level.ticks + partial_tick);
|
||||
begin_mode_3d(camera);
|
||||
const level = this.level_renderer;
|
||||
level.render_opaque(client.level, camera);
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
draw_terrain,
|
||||
flush_batch,
|
||||
get_current_texture,
|
||||
light_color,
|
||||
push_vertex,
|
||||
set_current_texture,
|
||||
Texture,
|
||||
@@ -38,7 +37,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";
|
||||
import { draw_visuals } from "./visuals.ts";
|
||||
|
||||
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
||||
export class LevelRenderer {
|
||||
@@ -149,16 +148,13 @@ export class LevelRenderer {
|
||||
flush_batch();
|
||||
}
|
||||
|
||||
// blocks drawn with code, in the chunks in view, see client/rendering/visuals.ts
|
||||
// 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) {
|
||||
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)));
|
||||
});
|
||||
level.visuals.frame(this.#visible, level.ticks + partial_tick);
|
||||
flush_batch();
|
||||
set_current_texture(level.image.tex);
|
||||
draw_visuals(level.visuals, level.image);
|
||||
}
|
||||
|
||||
// the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab
|
||||
|
||||
+238
-111
@@ -2,8 +2,10 @@
|
||||
// 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
|
||||
// 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
|
||||
import { mat4, vec3 } from "gl-matrix";
|
||||
import type {
|
||||
Instances,
|
||||
@@ -25,10 +27,17 @@ import {
|
||||
} 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 {
|
||||
create_vertex_buffer,
|
||||
destroy_buffer,
|
||||
draw_instances,
|
||||
INSTANCE_FLOATS,
|
||||
MODEL_VERTEX_BYTES,
|
||||
type Texture,
|
||||
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 type { Vec3 } from "./model_math.ts";
|
||||
|
||||
export interface VisualRegistration {
|
||||
mod: string;
|
||||
@@ -41,20 +50,85 @@ export interface VisualRegistration {
|
||||
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[][];
|
||||
// what visuals read from their level
|
||||
export interface VisualsLevel {
|
||||
get_block_data(x: number, y: number, z: number): Readonly<Record<string, unknown>> | undefined;
|
||||
// block light << 4 | sky light
|
||||
get_light(x: number, y: number, z: number): 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 };
|
||||
// an instance as the engine keeps it, see INSTANCE_FLOATS
|
||||
export interface DrawnInstance {
|
||||
group: InstanceGroup;
|
||||
// where it is in its group, -1 once it's deleted
|
||||
index: number;
|
||||
// takes its model to the world, after it spins around its block's middle
|
||||
placement: mat4;
|
||||
axis: vec3;
|
||||
rpm: number;
|
||||
// degrees
|
||||
offset: number;
|
||||
// packed like ClientLevel.get_light
|
||||
light: number;
|
||||
}
|
||||
|
||||
// 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[][];
|
||||
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;
|
||||
// made the first time it's drawn
|
||||
gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number };
|
||||
|
||||
constructor(quads: BakedQuad[], tints: number[][]) {
|
||||
this.quads = quads;
|
||||
this.tints = tints;
|
||||
}
|
||||
|
||||
add(instance: DrawnInstance) {
|
||||
instance.index = this.instances.length;
|
||||
this.instances.push(instance);
|
||||
if (this.data.length < this.instances.length * INSTANCE_FLOATS) {
|
||||
const data = new Float32Array(this.data.length * 2);
|
||||
data.set(this.data);
|
||||
this.data = data;
|
||||
}
|
||||
this.write(instance);
|
||||
}
|
||||
|
||||
// the last instance moves into its place, so the ones drawn are always the first ones
|
||||
remove(instance: DrawnInstance) {
|
||||
if (instance.index < 0) return;
|
||||
const last = this.instances.pop()!;
|
||||
if (last !== instance) {
|
||||
last.index = instance.index;
|
||||
this.instances[last.index] = last;
|
||||
this.write(last);
|
||||
}
|
||||
instance.index = -1;
|
||||
}
|
||||
|
||||
// after any of its fields changed
|
||||
write(instance: DrawnInstance) {
|
||||
const index = instance.index;
|
||||
if (index < 0) return;
|
||||
const at = index * INSTANCE_FLOATS;
|
||||
this.data.set(instance.placement, at);
|
||||
this.data.set(instance.axis, at + 16);
|
||||
this.data[at + 19] = instance.rpm;
|
||||
this.data[at + 20] = instance.offset;
|
||||
this.data[at + 21] = ((instance.light >> 4) + 0.5) / 16;
|
||||
this.data[at + 22] = ((instance.light & 15) + 0.5) / 16;
|
||||
this.dirty_from = Math.min(this.dirty_from, index);
|
||||
this.dirty_to = Math.max(this.dirty_to, index);
|
||||
}
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
@@ -63,6 +137,7 @@ interface Entry {
|
||||
z: number;
|
||||
value: number;
|
||||
mod: string;
|
||||
light: number;
|
||||
// undefined when making it threw, until the block changes
|
||||
visual?: Visual;
|
||||
instances: Set<DrawnInstance>;
|
||||
@@ -74,22 +149,29 @@ interface Entry {
|
||||
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;
|
||||
#level: VisualsLevel;
|
||||
// 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>();
|
||||
// models from models/ by id and turns, and blocks' own by value
|
||||
#model_groups = new Map<string, InstanceGroup>();
|
||||
#block_groups = new Map<number, InstanceGroup>();
|
||||
|
||||
constructor(client_data: (x: number, y: number, z: number) => Readonly<Record<string, unknown>> | undefined) {
|
||||
this.#client_data = client_data;
|
||||
constructor(level: VisualsLevel) {
|
||||
this.#level = level;
|
||||
}
|
||||
|
||||
has(chunk_x: number, chunk_z: number) {
|
||||
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
|
||||
}
|
||||
|
||||
*groups(): Iterable<InstanceGroup> {
|
||||
yield* this.#model_groups.values();
|
||||
yield* this.#block_groups.values();
|
||||
}
|
||||
|
||||
// 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
|
||||
// for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones
|
||||
// that stay take it
|
||||
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>();
|
||||
@@ -100,6 +182,7 @@ export class Visuals {
|
||||
const entry = old.get(index);
|
||||
old.delete(index);
|
||||
if (entry?.value === value) {
|
||||
this.#relight(entry);
|
||||
kept.set(index, entry);
|
||||
continue;
|
||||
}
|
||||
@@ -126,21 +209,31 @@ export class Visuals {
|
||||
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,
|
||||
) {
|
||||
// every visual goes, and the gpu buffers with them
|
||||
dispose() {
|
||||
for (const key of this.#chunks.keys()) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
this.#model_groups.clear();
|
||||
this.#block_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
|
||||
// out of view
|
||||
frame(chunks: Iterable<{ x: number; z: number }>, time: number) {
|
||||
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()) {
|
||||
for (const entry of this.#chunks.get(chunk_key(chunk.x, chunk.z))?.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,85 +249,119 @@ export class Visuals {
|
||||
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 light = this.#level.get_light(x, y, z);
|
||||
const entry: Entry = { x, y, z, value, mod: registration.mod, light, instances: new Set() };
|
||||
const level = this.#level;
|
||||
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,
|
||||
get_client_data: (field) => structuredClone(level.get_block_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();
|
||||
if (!made) this.#remove_instances(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
#delete(entry: Entry) {
|
||||
const visual = entry.visual;
|
||||
if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!());
|
||||
this.#remove_instances(entry);
|
||||
}
|
||||
|
||||
#remove_instances(entry: Entry) {
|
||||
for (const instance of entry.instances) instance.group.remove(instance);
|
||||
entry.instances.clear();
|
||||
}
|
||||
|
||||
#relight(entry: Entry) {
|
||||
const light = this.#level.get_light(entry.x, entry.y, entry.z);
|
||||
if (light === entry.light) return;
|
||||
entry.light = light;
|
||||
for (const instance of entry.instances) {
|
||||
instance.light = light;
|
||||
instance.group.write(instance);
|
||||
}
|
||||
}
|
||||
|
||||
#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;
|
||||
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 instance: DrawnInstance = {
|
||||
group,
|
||||
index: -1,
|
||||
placement: mat4.clone(corner),
|
||||
axis: AXES.y,
|
||||
rpm: 0,
|
||||
offset: 0,
|
||||
light: entry.light,
|
||||
};
|
||||
group.add(instance);
|
||||
entry.instances.add(instance);
|
||||
return instance;
|
||||
};
|
||||
const remove = (instance: DrawnInstance) => () => {
|
||||
instance.group.remove(instance);
|
||||
entry.instances.delete(instance);
|
||||
};
|
||||
return {
|
||||
transformed(model): TransformedInstance {
|
||||
const instance = add(model, { matrix: mat4.create() });
|
||||
const instance = add(model);
|
||||
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);
|
||||
mat4.multiply(instance.placement, corner, matrix as mat4);
|
||||
instance.group.write(instance);
|
||||
},
|
||||
delete: () => void entry.instances.delete(instance),
|
||||
delete: remove(instance),
|
||||
};
|
||||
},
|
||||
rotating(model): RotatingInstance {
|
||||
const instance = add(model, { rotation: { axis: AXES.y, rpm: 0, offset: 0 } });
|
||||
const instance = add(model);
|
||||
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 };
|
||||
instance.axis = AXES[axis];
|
||||
instance.rpm = rpm;
|
||||
instance.offset = offset;
|
||||
instance.group.write(instance);
|
||||
},
|
||||
delete: () => void entry.instances.delete(instance),
|
||||
delete: remove(instance),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
#quads_of(ref: ModelRef): ModelQuads {
|
||||
#model_group(ref: ModelRef): InstanceGroup {
|
||||
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) {
|
||||
let group = this.#model_groups.get(key);
|
||||
if (!group) {
|
||||
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);
|
||||
const quads = bake_model(json, undefined, y, x);
|
||||
group = new InstanceGroup(quads, quads.map(() => [1, 1, 1]));
|
||||
this.#model_groups.set(key, group);
|
||||
}
|
||||
return quads;
|
||||
return group;
|
||||
}
|
||||
|
||||
#quads_of_block(block: BlockRegistry, value: number): ModelQuads {
|
||||
let quads = this.#block_quads.get(value);
|
||||
if (!quads) {
|
||||
#block_group(block: BlockRegistry, value: number): InstanceGroup {
|
||||
let group = this.#block_groups.get(value);
|
||||
if (!group) {
|
||||
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);
|
||||
const quads = bake_block(block, value, this.#models);
|
||||
group = new InstanceGroup(quads, quads.map((quad) => item_tint(block, quad.variables)));
|
||||
this.#block_groups.set(value, group);
|
||||
}
|
||||
return quads;
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,59 +376,59 @@ function run_visual(entry: Entry, what: string, fn: () => void) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
// 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
// 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> {
|
||||
const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES);
|
||||
const view = new DataView(bytes.buffer);
|
||||
const normal = vec3.create();
|
||||
quads.forEach((quad, q) => {
|
||||
const p = quad.positions;
|
||||
const corner = (k: number) => vec3.fromValues(p[k * 3], p[k * 3 + 1], p[k * 3 + 2]);
|
||||
// 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];
|
||||
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);
|
||||
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));
|
||||
}
|
||||
});
|
||||
return bytes;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user