Better block models !

This commit is contained in:
2026-10-03 15:57:47 -03:00
parent ecc0295f6d
commit 24fe7cdede
23 changed files with 678 additions and 122 deletions
+17 -4
View File
@@ -48,6 +48,9 @@ export interface BlockVariant {
textures?: BlockTextures;
// turns the model around the vertical axis, clockwise seen from above: 0, 90, 180 or 270
y?: number;
// what the player points at and bumps into, as boxes in pixels: [x1, y1, z1, x2, y2, z2]. the model's boxes when
// not set, see common/block_shapes.ts
shape?: number[][];
}
export const DEFAULT_MODEL = "engine:cube";
@@ -142,21 +145,31 @@ export function texture_variables(reference: string, textures: BlockTextures | u
return variables;
}
// the block's model, textures and turn for a value with state bits. each comes from the first variant whose conditions
// the block's model, textures, turn and shape for a value with state bits. each comes from the first variant whose conditions
// match that sets it, so "lit=1" can change the textures and "facing=1" the turn of the same block
export function block_variant(block: BlockRegistry, states?: Record<string, number>): Required<BlockVariant> {
export function block_variant(
block: BlockRegistry,
states?: Record<string, number>,
): Required<Omit<BlockVariant, "shape">> & Pick<BlockVariant, "shape"> {
let model: string | undefined;
let textures: BlockTextures | undefined;
let y: number | undefined;
let shape: number[][] | undefined;
if (block.variants && states) {
for (const [condition, override] of Object.entries(block.variants)) {
if (!variant_matches(condition, states)) continue;
model ??= override.model;
textures ??= override.textures;
y ??= override.y;
shape ??= override.shape;
}
}
return { model: model ?? block.model ?? DEFAULT_MODEL, textures: textures ?? block.textures, y: y ?? 0 };
return {
model: model ?? block.model ?? DEFAULT_MODEL,
textures: textures ?? block.textures,
y: y ?? 0,
shape: shape ?? block.shape,
};
}
// "age=7" or "age=7,facing=2", "" matches everything
@@ -300,7 +313,7 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
}
// turns a point (in block space) by the element's rotation
function element_rotation(element: ModelElementJson): (point: number[]) => number[] {
export function element_rotation(element: ModelElementJson): (point: number[]) => number[] {
const rotation = element.rotation;
if (!rotation || rotation.angle === 0) return (point) => point;
+136
View File
@@ -0,0 +1,136 @@
// a block's shape, like minecraft's VoxelShape: the boxes it's made of. it's what the player points at and what the
// cracks are drawn on when it breaks (minecraft's getShape), and what entities bump into when it has collision
// (getCollisionShape). blocks get theirs from the boxes of their model, or set "shape" like minecraft's Block.box
import { block_variant, element_rotation, find_model, type ModelJson } from "./block_models.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
import { get_state_value } from "./utils.ts";
// min x y z then max x y z, in block space (0 to 1)
export type Box = readonly [number, number, number, number, number, number];
export type Shape = readonly Box[];
export const FULL_SHAPE: Shape = [[0, 0, 0, 1, 1, 1]];
export const EMPTY_SHAPE: Shape = [];
// thinner than this on some axis is a flat plane, like the cross model's, not a box
const FLAT = 1e-4;
// the boxes of a model's elements, turned like the model is. elements turned by their own rotation take the box
// around them. flat planes (plants) aren't boxes, so a model made only of planes gets one box around all of them
export function model_shape(model: ModelJson, y_rotation = 0): Shape {
const boxes: Box[] = [];
let bounds: Box | undefined;
for (const element of model.elements) {
const rotate = element_rotation(element);
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
for (let corner = 0; corner < 8; corner++) {
const point = rotate(
[0, 1, 2].map((axis) => ((corner >> axis) & 1 ? element.to[axis] : element.from[axis]) / 16),
);
for (let axis = 0; axis < 3; axis++) {
min[axis] = Math.min(min[axis], point[axis]);
max[axis] = Math.max(max[axis], point[axis]);
}
}
const box = clamp([...min, ...max]);
bounds = bounds ? clamp(bounds.map((v, i) => (i < 3 ? Math.min : Math.max)(v, box[i]))) : box;
if ([0, 1, 2].every((axis) => box[axis + 3] - box[axis] > FLAT)) boxes.push(box);
}
if (boxes.length === 0 && bounds) boxes.push(bounds);
return boxes.map((box) => turn(box, y_rotation));
}
// boxes in pixels, like a block's "shape" ([x1, y1, z1, x2, y2, z2], 0 to 16), turned like the model is
export function pixel_shape(boxes: number[][], y_rotation = 0): Shape {
return boxes.map((box) => turn(clamp(box.map((v) => v / 16)), y_rotation));
}
// what the block is at a value with state bits: its "shape" when it (or a variant) sets one, otherwise its model's
export function block_shape(block: BlockRegistry, states?: Record<string, number>): Shape {
const variant = block_variant(block, states);
if (variant.shape) return pixel_shape(variant.shape, variant.y);
const model = find_model(variant.model, Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")));
return model ? model_shape(model, variant.y) : FULL_SHAPE;
}
// shapes by block, then by value with state bits, worked out the first time they're asked for
const cache = new WeakMap<BlockRegistry, Map<number, Shape>>();
// the block's shape at a value from the world, see block_shape
export function shape_at(block: BlockRegistry, value: number): Shape {
let shapes = cache.get(block);
if (!shapes) cache.set(block, shapes = new Map());
const key = block.variants ? value : 0;
let shape = shapes.get(key);
if (!shape) {
let states: Record<string, number> | undefined;
if (block.variants && block.states) {
states = {};
for (const state of block.states) states[state.name] = get_state_value(value, block, state.name)!;
}
shape = block_shape(block, states);
shapes.set(key, shape);
}
return shape;
}
// what entities bump into, like getCollisionShape: the shape, or nothing for blocks with "collision": false
export function collision_shape_at(block: BlockRegistry, value: number): Shape {
return block.has_collision ? shape_at(block, value) : EMPTY_SHAPE;
}
// how far along the ray (origin plus direction times distance) it first goes into one of the boxes of a block at
// x, y, z, and the side it went in by as the axis and which way along it the ray was going. undefined if it misses
export function clip_shape(
shape: Shape,
x: number,
y: number,
z: number,
origin: number[],
direction: number[],
max_distance: number,
): { distance: number; axis: number; sign: number } | undefined {
const offset = [x, y, z];
let closest: { distance: number; axis: number; sign: number } | undefined;
for (const box of shape) {
let enter = 0;
let enter_axis = -1;
let leave = closest?.distance ?? max_distance;
for (let axis = 0; axis < 3 && enter <= leave; axis++) {
const min = offset[axis] + box[axis];
const max = offset[axis] + box[axis + 3];
if (Math.abs(direction[axis]) < 1e-9) {
if (origin[axis] < min || origin[axis] > max) enter = Infinity;
continue;
}
const a = (min - origin[axis]) / direction[axis];
const b = (max - origin[axis]) / direction[axis];
if (Math.min(a, b) >= enter) {
enter = Math.min(a, b);
enter_axis = axis;
}
leave = Math.min(leave, Math.max(a, b));
}
if (enter <= leave && enter_axis >= 0) {
closest = { distance: enter, axis: enter_axis, sign: Math.sign(direction[enter_axis]) };
}
}
return closest;
}
function clamp(box: number[]): Box {
const c = box.map((v) => Math.min(Math.max(v, 0), 1));
return [c[0], c[1], c[2], c[3], c[4], c[5]];
}
// clockwise seen from above by 0, 90, 180 or 270 degrees, the same as bake_model turns quads
function turn(box: Box, y_rotation: number): Box {
const turns = ((Math.round(y_rotation / 90) % 4) + 4) % 4;
let [x1, y1, z1, x2, y2, z2] = box;
for (let t = 0; t < turns; t++) {
// a point (x, z) goes to (1 - z, x)
[x1, z1, x2, z2] = [1 - z2, x1, 1 - z1, x2];
}
return [x1, y1, z1, x2, y2, z2];
}
+2
View File
@@ -119,6 +119,8 @@ export interface BlockRegistry {
alpha?: number;
has_collision: boolean;
// boxes in pixels, see BlockVariant.shape
shape?: number[][];
toughness?: number;
requires_tool?: boolean;
tool_to_break?: string;
+18 -1
View File
@@ -55,6 +55,7 @@ export interface BlockJson {
transparent?: boolean;
alpha?: number;
collision?: boolean;
shape?: number[][];
mining?: { toughness: number; tool?: string; requires_tool?: boolean; tier?: number };
drops?: string;
item?: boolean;
@@ -267,6 +268,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (block.light_opacity !== undefined) json.light_opacity = block.light_opacity;
if (block.alpha !== undefined) json.alpha = block.alpha;
if (!block.has_collision) json.collision = false;
if (block.shape !== undefined) json.shape = block.shape;
if (block.toughness !== undefined) {
json.mining = { toughness: block.toughness };
if (block.tool_to_break !== undefined) json.mining.tool = block.tool_to_break;
@@ -294,6 +296,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.name !== undefined) block.name = json.name;
if (json.model !== undefined) block.model = json.model;
if (json.variants !== undefined) block.variants = json.variants;
if (json.shape !== undefined) block.shape = json.shape;
const render_layer = json.render_layer ?? (json.transparent ? "translucent" : undefined);
if (render_layer && render_layer !== "solid") block.render_layer = render_layer;
if (json.cull_same !== undefined) block.cull_same = json.cull_same;
@@ -474,7 +477,7 @@ export function validate_block(json: unknown): Problems {
}
}
if (!is_object(variant)) {
problems.push(`${where} must be { model, textures, y }`);
problems.push(`${where} must be { model, textures, y, shape }`);
continue;
}
if (variant.model !== undefined) problems.push(...validate_id(variant.model, `${where}.model`));
@@ -484,9 +487,11 @@ export function validate_block(json: unknown): Problems {
if (variant.y !== undefined && ![0, 90, 180, 270].includes(variant.y as number)) {
problems.push(`${where}.y must be 0, 90, 180 or 270`);
}
if (variant.shape !== undefined) problems.push(...validate_shape(variant.shape, `${where}.shape`));
}
}
}
if (json.shape !== undefined) problems.push(...validate_shape(json.shape, "shape"));
if (json.render_layer !== undefined && !RENDER_LAYERS.includes(json.render_layer as RenderLayer)) {
problems.push(`render_layer must be one of ${RENDER_LAYERS.join(", ")}`);
}
@@ -549,6 +554,18 @@ export function validate_block(json: unknown): Problems {
return problems;
}
// boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 and the second past the first
function validate_shape(shape: unknown, where: string): Problems {
const is_box = (box: unknown) =>
Array.isArray(box) && box.length === 6 &&
box.every((v) => typeof v === "number" && v >= 0 && v <= 16) &&
box[0] <= box[3] && box[1] <= box[4] && box[2] <= box[5];
if (!Array.isArray(shape) || shape.length === 0 || !shape.every(is_box)) {
return [`${where} must be a list of boxes in pixels, like [[0, 0, 0, 16, 8, 16]]`];
}
return [];
}
export function validate_model(json: unknown): Problems {
if (!is_object(json)) return ["model must be an object"];
const problems = validate_id(json.id, "id");
+41 -16
View File
@@ -1,11 +1,20 @@
// collision against blocks, shared by the client's entities and the server's, so both move things the same way
import { TICK_DELTA } from "./constants.ts";
import { EMPTY_SHAPE, FULL_SHAPE, type Shape } from "./block_shapes.ts";
// how far inside a block face still counts as touching it, so boxes resting exactly on a face don't snag
const EPSILON = 1e-7;
// the two axes that aren't the one being moved along
const OTHER_AXES = [[1, 2], [0, 2], [0, 1]] as const;
// what a body bumps into at a block: its collision shape (see common/block_shapes.ts), or true for a full block and
// false for nothing
export type BlockCollision = (x: number, y: number, z: number) => boolean | Shape;
function shape_of(collision: boolean | Shape): Shape {
return collision === true ? FULL_SHAPE : collision === false ? EMPTY_SHAPE : collision;
}
// something with a box that moves. position is the middle of its feet, velocity is in blocks per second
export interface Body {
x: number;
@@ -36,7 +45,7 @@ export interface Collisions {
export function move_body(
body: Body,
gravity: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
step_height = 0,
on_ground = false,
) {
@@ -82,7 +91,7 @@ function sweep(
max: number[],
wanted: number[],
axes: number[],
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
const moved = [0, 0, 0];
for (const axis of axes) {
@@ -101,7 +110,7 @@ function step_up(
max: number[],
wanted: number[],
step_height: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
const up = sweep(min, max, [0, step_height, 0], [1], is_solid)[1];
const across = sweep(min, max, wanted, horizontal_order(wanted), is_solid);
@@ -109,13 +118,13 @@ function step_up(
return [across[0], up + down, across[2]];
}
// how far the box can go along an axis before it runs into a block
// how far the box can go along an axis before it runs into a block's shape
function clip(
min: number[],
max: number[],
axis: number,
distance: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
if (distance === 0) {
return 0;
@@ -132,13 +141,21 @@ function clip(
position[axis] = i;
position[a] = j;
position[b] = k;
if (!is_solid(position[0], position[1], position[2])) {
continue;
}
if (distance > 0 && i >= max[axis] - EPSILON) {
distance = Math.min(distance, i - max[axis]);
} else if (distance < 0 && i + 1 <= min[axis] + EPSILON) {
distance = Math.max(distance, i + 1 - min[axis]);
for (const box of shape_of(is_solid(position[0], position[1], position[2]))) {
// only boxes beside the body on the other two axes are in the way
if (
position[a] + box[a] >= max[a] - EPSILON || position[a] + box[a + 3] <= min[a] + EPSILON ||
position[b] + box[b] >= max[b] - EPSILON || position[b] + box[b + 3] <= min[b] + EPSILON
) {
continue;
}
const box_min = i + box[axis];
const box_max = i + box[axis + 3];
if (distance > 0 && box_min >= max[axis] - EPSILON) {
distance = Math.min(distance, box_min - max[axis]);
} else if (distance < 0 && box_max <= min[axis] + EPSILON) {
distance = Math.max(distance, box_max - min[axis]);
}
}
}
}
@@ -153,7 +170,7 @@ export function back_off_from_edge(
dx: number,
dz: number,
drop: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
): [number, number] {
const step = 0.05;
const toward_zero = (d: number) => Math.abs(d) <= step ? 0 : d - Math.sign(d) * step;
@@ -178,7 +195,7 @@ export function box_is_free(
dx: number,
dy: number,
dz: number,
is_blocked: (x: number, y: number, z: number) => boolean,
is_blocked: BlockCollision,
): boolean {
const half = body.width / 2;
const min = [body.x - half + dx, body.y + dy, body.z - half + dz];
@@ -186,11 +203,19 @@ export function box_is_free(
return !overlaps_solid(min, max, is_blocked);
}
function overlaps_solid(min: number[], max: number[], is_solid: (x: number, y: number, z: number) => boolean) {
function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) {
for (let x = Math.floor(min[0] + EPSILON); x <= Math.floor(max[0] - EPSILON); x++) {
for (let y = Math.floor(min[1] + EPSILON); y <= Math.floor(max[1] - EPSILON); y++) {
for (let z = Math.floor(min[2] + EPSILON); z <= Math.floor(max[2] - EPSILON); z++) {
if (is_solid(x, y, z)) return true;
for (const box of shape_of(is_solid(x, y, z))) {
if (
x + box[0] < max[0] - EPSILON && x + box[3] > min[0] + EPSILON &&
y + box[1] < max[1] - EPSILON && y + box[4] > min[1] + EPSILON &&
z + box[2] < max[2] - EPSILON && z + box[5] > min[2] + EPSILON
) {
return true;
}
}
}
}
}
+9 -4
View File
@@ -1,6 +1,7 @@
import { ID_MASK, STATE_SHIFT } from "./constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import { block_item_texture, cube_face_texture } from "./block_models.ts";
import { FULL_SHAPE, type Shape } from "./block_shapes.ts";
import type { ItemStack } from "./inventory.ts";
import { list_matches } from "./tags.ts";
@@ -163,17 +164,21 @@ export function can_place(
return in_ok && can_stand_on(block, below);
}
// whether an entity's collision box, centered on x and z with its feet at y, overlaps the block at bx, by, bz
// whether an entity's collision box, centered on x and z with its feet at y, overlaps the block at bx, by, bz. only
// the block's boxes count when given its shape, so a slab's empty half doesn't
export function box_overlaps_block(
entity: { x: number; y: number; z: number; width: number; height: number },
bx: number,
by: number,
bz: number,
shape: Shape = FULL_SHAPE,
): boolean {
const half = entity.width / 2;
return entity.x + half > bx && entity.x - half < bx + 1 &&
entity.y + entity.height > by && entity.y < by + 1 &&
entity.z + half > bz && entity.z - half < bz + 1;
return shape.some((box) =>
entity.x + half > bx + box[0] && entity.x - half < bx + box[3] &&
entity.y + entity.height > by + box[1] && entity.y < by + box[4] &&
entity.z + half > bz + box[2] && entity.z - half < bz + box[5]
);
}
// numeric so looking chunks up doesnt allocate a string every time, fine for |x|, |z| < 32768