// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // turning and moving the parts of models: entity models' bones, the player's parts and what's worn on them. no // drawing here, so tests can use it import type { EntityBoneJson, EntityCubeJson, EntityModelJson } from "@/common/mod_data.ts"; export type Vec3 = [number, number, number]; // 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's export type Matrix = number[]; export const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; // bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right export function model_pivot(bone: EntityBoneJson): Vec3 { return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]]; } // a bone's or a cube's own rotation around its pivot. mirroring x turns x and y rotations the other way export function own_matrix(part: EntityBoneJson | EntityCubeJson): Matrix { if (!part.rotation) return IDENTITY; const [rx, ry, rz] = part.rotation.map((degrees) => degrees * Math.PI / 180); const [px, py, pz] = part.pivot ?? [0, 0, 0]; return rotation_around([-px, py, pz], -rx, -ry, rz); } // every bone's matrix: its own rotation, then pose's for it (like a head looking or a limb swinging), then its // parent's. parents come before their children in the model export function bone_matrices(model: EntityModelJson, pose: (bone: EntityBoneJson) => Matrix): Map { const bones = new Map(); for (const bone of model.bones) { let matrix = multiply(pose(bone), own_matrix(bone)); if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix); bones.set(bone.name, matrix); } return bones; } // turns around pivot by x, then y, then z (radians). y turns like the whole model does and x like the player's head // pitch export function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix { const [sx, cx] = [Math.sin(rx), Math.cos(rx)]; const [sy, cy] = [Math.sin(ry), Math.cos(ry)]; const [sz, cz] = [Math.sin(rz), Math.cos(rz)]; const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0]; const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0]; const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0]; const [px, py, pz] = pivot; const rotation = multiply(rot_z, multiply(rot_y, rot_x)); return multiply( [1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz], multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]), ); } // a after b export function multiply(a: Matrix, b: Matrix): Matrix { const out: Matrix = []; for (let row = 0; row < 3; row++) { for (let col = 0; col < 4; col++) { let sum = col === 3 ? a[row * 4 + 3] : 0; for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col]; out.push(sum); } } return out; } export function apply(m: Matrix, x: number, y: number, z: number): Vec3 { return [ m[0] * x + m[1] * y + m[2] * z + m[3], m[4] * x + m[5] * y + m[6] * z + m[7], m[8] * x + m[9] * y + m[10] * z + m[11], ]; }