From 69ad4b80d0d5c719471a466f5c93b3c6be4dea2c Mon Sep 17 00:00:00 2001 From: Paula Date: Sat, 21 Nov 2026 20:07:10 -0300 Subject: [PATCH] Animation clips --- client/rendering/animation.ts | 72 ++++++++++++ client/rendering/model_math.ts | 35 +++++- common/mod.ts | 4 + common/mod_check.ts | 4 + common/mod_data.ts | 184 ++++++++++++++++++++++++++++++ common/mod_loader.ts | 6 + common/worldgen_bundle.ts | 1 + server/load_mods.ts | 1 + tests/animation_test.ts | 197 +++++++++++++++++++++++++++++++++ tools/check_mods.ts | 16 +++ 10 files changed, 514 insertions(+), 6 deletions(-) create mode 100644 client/rendering/animation.ts create mode 100644 tests/animation_test.ts diff --git a/client/rendering/animation.ts b/client/rendering/animation.ts new file mode 100644 index 0000000..896310f --- /dev/null +++ b/client/rendering/animation.ts @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// playing clips (see ANIMATION.md): what one does to the bones it moves at a time into it, sampled the way +// blockbench's timeline does a bedrock animation. no drawing here, so tests can use it +import type { ClipJson, ClipKeyframe } from "@/common/mod_data.ts"; +import { lerp } from "@/common/worldgen/noise.ts"; +import type { BoneOffsets, Vec3 } from "./model_math.ts"; + +// a keyframe this close to the time is the one it's on, in seconds +const ON_KEYFRAME = 1 / 1200; + +// adds what clip does seconds into it to each bone's offsets, scaled by weight: rotation and position times weight, +// scale weight of the way from 1. a clip that loops wraps around its length, one that doesn't stays on its last frame +export function sample_clip(clip: ClipJson, seconds: number, offsets: Map, weight = 1) { + const time = clip.loop && clip.length > 0 ? ((seconds % clip.length) + clip.length) % clip.length : seconds; + for (const [bone, channels] of Object.entries(clip.bones)) { + let offset = offsets.get(bone); + if (!offset) { + offset = { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1] }; + offsets.set(bone, offset); + } + for (const channel of ["rotation", "position"] as const) { + const keyframes = channels[channel]; + if (!keyframes) continue; + const value = sample_channel(keyframes, time, clip.loop); + for (let i = 0; i < 3; i++) offset[channel][i] += value[i] * weight; + } + if (channels.scale) { + const value = sample_channel(channels.scale, time, clip.loop); + for (let i = 0; i < 3; i++) offset.scale[i] *= 1 + (value[i] - 1) * weight; + } + } +} + +// a channel's value at time, from the keyframes around it. on a keyframe it's what it comes in at, and before the +// first or after the last it's that keyframe's +export function sample_channel(keyframes: ClipKeyframe[], time: number, loop: boolean): Vec3 { + let after = keyframes.findIndex((keyframe) => keyframe.time >= time); + if (after === -1) after = keyframes.length; + const from = keyframes[after - 1]; + const to = keyframes[after]; + if (from && time - from.time < ON_KEYFRAME) return from.pre; + if (to && to.time - time < ON_KEYFRAME) return to.pre; + if (!to) return from.post; + if (!from) return to.pre; + + const t = (time - from.time) / (to.time - from.time); + if (!from.smooth && !to.smooth) return [0, 1, 2].map((i) => lerp(t, from.post[i], to.pre[i])) as Vec3; + // through the keyframes either side too, wrapping around a loop of three or more, whose first and last are the same + // moment. where there's none, or the one next to it jumps, the curve starts or ends at the next one's value again + let before: ClipKeyframe | undefined = keyframes[after - 2]; + let beyond: ClipKeyframe | undefined = keyframes[after + 1]; + if (loop && keyframes.length >= 3) { + before ??= keyframes.at(-2); + beyond ??= keyframes[1]; + } + const p0 = before && same(from.pre, from.post) ? before.post : from.post; + const p3 = beyond && same(to.pre, to.post) ? beyond.pre : to.pre; + return [0, 1, 2].map((i) => catmullrom(t, p0[i], from.post[i], to.pre[i], p3[i])) as Vec3; +} + +function same(a: Vec3, b: Vec3) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} + +// a uniform catmull-rom spline from p1 at t 0 to p2 at t 1 +function catmullrom(t: number, p0: number, p1: number, p2: number, p3: number) { + const v0 = (p2 - p0) / 2; + const v1 = (p3 - p1) / 2; + return (2 * p1 - 2 * p2 + v0 + v1) * t ** 3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t ** 2 + v0 * t + p1; +} diff --git a/client/rendering/model_math.ts b/client/rendering/model_math.ts index 8854ec9..fc27037 100644 --- a/client/rendering/model_math.ts +++ b/client/rendering/model_math.ts @@ -17,20 +17,43 @@ export function model_pivot(bone: EntityBoneJson): Vec3 { return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]]; } +// what animation does to a bone, in the model's bedrock space like its own pivot and rotation: degrees added to its +// rotation, pixels it moves and how much it's scaled, around its pivot +export type BoneOffsets = { rotation: Vec3; position: Vec3; scale: Vec3 }; + // 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 turn_around(part.pivot ?? [0, 0, 0], part.rotation); +} + +function turn_around([px, py, pz]: Vec3, degrees: Vec3): Matrix { + const [rx, ry, rz] = degrees.map((n) => n * Math.PI / 180); 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 { +// a bone's own rotation with what animation does to it: moved, then turned and scaled around its pivot +function animated_matrix(bone: EntityBoneJson, { rotation, position, scale }: BoneOffsets): Matrix { + const [rx, ry, rz] = bone.rotation ?? [0, 0, 0]; + const turned = turn_around(bone.pivot, [rx + rotation[0], ry + rotation[1], rz + rotation[2]]); + const [px, py, pz] = model_pivot(bone); + const [sx, sy, sz] = scale; + const scaled = [sx, 0, 0, px - px * sx, 0, sy, 0, py - py * sy, 0, 0, sz, pz - pz * sz]; + const moved = [1, 0, 0, -position[0], 0, 1, 0, position[1], 0, 0, 1, position[2]]; + return multiply(moved, multiply(turned, scaled)); +} + +// every bone's matrix: its own rotation (with offsets' for it, from animation), 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, + offsets?: Map, +): Map { const bones = new Map(); for (const bone of model.bones) { - let matrix = multiply(pose(bone), own_matrix(bone)); + const offset = offsets?.get(bone.name); + let matrix = multiply(pose(bone), offset ? animated_matrix(bone, offset) : own_matrix(bone)); if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix); bones.set(bone.name, matrix); } diff --git a/common/mod.ts b/common/mod.ts index be03856..2b38d4a 100644 --- a/common/mod.ts +++ b/common/mod.ts @@ -8,6 +8,7 @@ import type { ModelFileJson } from "./block_models.ts"; import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts"; import { type BlockJson, + type ClipJson, type EffectJson, type EntityJson, type EntityModelJson, @@ -19,6 +20,7 @@ import { type SpawnJson, type TagJson, validate_block, + validate_clip, validate_effect, validate_entity, validate_entity_model, @@ -189,6 +191,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod { validate_entity_model, problems, ) as EntityModelJson[], + animations: checked(raw_data.animations, "animations", validate_clip, problems) as ClipJson[], effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[], fluids: checked(raw_data.fluids, "fluids", validate_fluid, problems) as FluidJson[], tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[], @@ -228,6 +231,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod { ...data.items, ...data.entities, ...data.entity_models, + ...data.animations!, ...data.effects, ...data.fluids, ]; diff --git a/common/mod_check.ts b/common/mod_check.ts index 9e83750..6176614 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -6,6 +6,7 @@ import { type BlockJson, choice_list, + type ClipJson, type EffectJson, entity_category, type EntityJson, @@ -64,6 +65,8 @@ export interface LoadedMod { spawns: { file: string; json: SpawnJson }[]; entities: { file: string; json: EntityJson }[]; entity_models: { file: string; json: EntityModelJson }[]; + // clips, see ANIMATION.md + animations: { file: string; json: ClipJson }[]; effects: { file: string; json: EffectJson }[]; fluids: { file: string; json: FluidJson }[]; tags: { file: string; json: TagJson }[]; @@ -98,6 +101,7 @@ export function mod_data(mod: LoadedMod): ModData { spawns: mod.spawns.map((s) => s.json), entities: mod.entities.map((e) => e.json), entity_models: mod.entity_models.map((m) => m.json), + animations: mod.animations.map((a) => a.json), effects: mod.effects.map((e) => e.json), fluids: mod.fluids.map((f) => f.json), tags: mod.tags.map((t) => t.json), diff --git a/common/mod_data.ts b/common/mod_data.ts index 74e4d74..1bec20b 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -574,6 +574,37 @@ const entity_model_schema = z.object({ export type EntityModelJson = z.infer; +// a channel's value at a time in seconds. pre is what it comes into the keyframe at and post what it leaves at, the +// same unless it jumps there. smooth is catmullrom to and from it, linear otherwise +const clip_keyframe = z.object({ time: z.number().min(0), pre: vec3, post: vec3, smooth: z.boolean() }); + +export type ClipKeyframe = z.infer; + +const clip_channel = z.array(clip_keyframe).min(1).refine( + (keyframes) => keyframes.every((keyframe, i) => i === 0 || keyframes[i - 1].time <= keyframe.time), + "keyframes must be in time order", +); + +// an entity model animation (one of those in animations/.animation.json) with only what the engine uses, see +// ANIMATION.md. values are as bedrock has them, mirrored on x from the engine's like models: rotation in degrees, +// added to a bone's own, position in pixels, and scale multiplying +const clip_schema = z.object({ + id: z.string('must be a clip id like "my_mod:thing/walk"').regex(TAG_ID_PATTERN), + // seconds + length: z.number().min(0), + loop: z.boolean(), + bones: z.record( + z.string(), + z.object({ + rotation: clip_channel.optional(), + position: clip_channel.optional(), + scale: clip_channel.optional(), + }), + ), +}); + +export type ClipJson = z.infer; + // something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must const tag_entry = z.union( [id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })], @@ -982,6 +1013,159 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems }; } +export function validate_clip(json: unknown): Problems { + return find_problems(clip_schema, json); +} + +// what a bedrock animation can have that clips leave to an animator's code +const ANIMATOR_FIELDS = [ + "anim_time_update", + "blend_weight", + "start_delay", + "loop_delay", + "override_previous_animation", + "sound_effects", + "particle_effects", + "timeline", +]; + +// an animations/.animation.json, as blockbench exports it for bedrock, to its clips. each is / and the +// last part of its name, so animation.jester.walk in dangerous_business:jester is dangerous_business:jester/walk. +// warnings are what it has that clips don't use +export function clips_from_bedrock( + json: unknown, + file_id: string, +): { clips: ClipJson[]; problems: Problems; warnings: Problems } { + const problems: Problems = []; + const warnings: Problems = []; + if (!is_object(json) || !is_object(json.animations)) { + problems.push('must be a bedrock animation file: { "animations": { "animation.thing.walk": { ... } } }'); + return { clips: [], problems, warnings }; + } + const clips: ClipJson[] = []; + for (const [name, animation] of Object.entries(json.animations)) { + const problem = (message: string) => problems.push(`${name}: ${message}`); + const id = `${file_id}/${name.split(".").at(-1)!.toLowerCase()}`; + if (clips.some((clip) => clip.id === id)) { + problem(`its id ${id} is another animation's too`); + continue; + } + if (!is_object(animation)) { + problem("must be an object"); + continue; + } + for (const field of ANIMATOR_FIELDS) { + if (field in animation) warnings.push(`${name}: ${field} isn't used, an animator does that in code`); + } + if (![undefined, true, false, "hold_on_last_frame"].includes(animation.loop as string)) { + problem('loop must be true, false or "hold_on_last_frame"'); + } + const length = animation.animation_length; + if (length !== undefined && (typeof length !== "number" || length < 0)) { + problem("animation_length must be a number of seconds"); + } + const bones: ClipJson["bones"] = {}; + let last = 0; + for (const [bone, channels] of Object.entries(is_object(animation.bones) ? animation.bones : {})) { + if (!is_object(channels)) { + problem(`${bone} must be an object of channels`); + continue; + } + const read: ClipJson["bones"][string] = {}; + for (const [channel, value] of Object.entries(channels)) { + if (channel !== "rotation" && channel !== "position" && channel !== "scale") { + warnings.push(`${name}: ${bone}'s ${channel} isn't used`); + continue; + } + const keyframes = read_channel(value, (message) => problem(`${bone} ${channel}: ${message}`)); + if (!keyframes) continue; + read[channel] = keyframes; + last = Math.max(last, keyframes.at(-1)!.time); + } + bones[bone] = read; + } + const clip = { id, length: typeof length === "number" ? length : last, loop: animation.loop === true, bones }; + for (const message of validate_clip(clip)) problem(message); + clips.push(clip); + } + return { clips: problems.length === 0 ? clips : [], problems, warnings }; +} + +// a channel: one value for the whole clip, or keyframes by time in seconds +function read_channel(value: unknown, problem: (message: string) => void): ClipKeyframe[] | undefined { + const single = !is_object(value) || "pre" in value || "post" in value || "vector" in value; + if (single) { + const keyframe = read_keyframe(0, value, problem); + return keyframe && [keyframe]; + } + const keyframes: ClipKeyframe[] = []; + for (const [time, keyframe_value] of Object.entries(value)) { + const seconds = Number(time); + if (time.trim() === "" || !(seconds >= 0)) { + problem(`${time} isn't a time in seconds`); + return undefined; + } + const keyframe = read_keyframe(seconds, keyframe_value, (message) => problem(`at ${time}: ${message}`)); + if (!keyframe) return undefined; + keyframes.push(keyframe); + } + if (keyframes.length === 0) { + problem("has no keyframes"); + return undefined; + } + return keyframes.sort((a, b) => a.time - b.time); +} + +// a value, { "pre": value, "post": value, "lerp_mode": ... } with either of pre and post, or geckolib's older +// { "vector": value, "easing": ... } +function read_keyframe(time: number, value: unknown, problem: (message: string) => void): ClipKeyframe | undefined { + if (!is_object(value)) { + const vector = read_vector(value, problem); + return vector && { time, pre: vector, post: vector, smooth: false }; + } + const lerp = "vector" in value ? value.easing : value.lerp_mode; + if (lerp !== undefined && lerp !== "linear" && lerp !== "catmullrom") { + problem(`${"vector" in value ? "easing" : "lerp_mode"} ${JSON.stringify(lerp)} isn't supported`); + return undefined; + } + if ("vector" in value) { + const vector = read_vector(value.vector, problem); + return vector && { time, pre: vector, post: vector, smooth: lerp === "catmullrom" }; + } + if (value.pre === undefined && value.post === undefined) { + problem("needs pre or post"); + return undefined; + } + const pre = read_vector(value.pre ?? value.post, problem); + const post = read_vector(value.post ?? value.pre, problem); + return pre && post && { time, pre, post, smooth: lerp === "catmullrom" }; +} + +// [x, y, z], or one number for all three. numbers can be written as text, but not expressions, which are code +function read_vector(value: unknown, problem: (message: string) => void): [number, number, number] | undefined { + if (!Array.isArray(value)) { + const number = read_number(value, problem); + return number === undefined ? undefined : [number, number, number]; + } + if (value.length !== 3) { + problem("must be [x, y, z] or a number"); + return undefined; + } + const numbers = value.map((part) => read_number(part, problem)); + return numbers.every((number) => number !== undefined) ? numbers as [number, number, number] : undefined; +} + +function read_number(value: unknown, problem: (message: string) => void): number | undefined { + const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value; + if (typeof number === "number" && Number.isFinite(number)) return number; + problem( + typeof value === "string" + ? `${JSON.stringify(value)} is an expression, which clips can't run: an animator does that in code` + : "must be [x, y, z] or a number", + ); + return undefined; +} + // a tag file's contents, with the registry and id its path gives it export function validate_tag(json: unknown): Problems { return find_problems(tag_schema, json); diff --git a/common/mod_loader.ts b/common/mod_loader.ts index fb84930..c7f066b 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -10,6 +10,7 @@ import { choice_ids, choice_list, choice_problems, + ClipJson, EffectJson, EntityJson, EntityModelJson, @@ -59,6 +60,8 @@ export interface ModData { spawns: SpawnJson[]; entities: EntityJson[]; entity_models: EntityModelJson[]; + // clips, see ANIMATION.md. missing from mods packed before there were any + animations?: ClipJson[]; // status effects, see EffectJson effects: EffectJson[]; // kinds of fluid, see FluidJson @@ -224,6 +227,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe for (const model of data.entity_models) { EverythingRegistry.register("entity_models", model.id, model); } + for (const clip of data.animations ?? []) { + EverythingRegistry.register("animations", clip.id, clip); + } for (const json of data.entities) { EverythingRegistry.register("entities", json.id, json); } diff --git a/common/worldgen_bundle.ts b/common/worldgen_bundle.ts index 6f822f6..8b488e5 100644 --- a/common/worldgen_bundle.ts +++ b/common/worldgen_bundle.ts @@ -98,6 +98,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise spawns: [], entities: [], entity_models: [], + animations: [], effects: [], fluids: [], loot_tables: [], diff --git a/server/load_mods.ts b/server/load_mods.ts index 83cdff2..344277b 100644 --- a/server/load_mods.ts +++ b/server/load_mods.ts @@ -222,6 +222,7 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod { spawns: entries(mod.data.spawns), entities: entries(mod.data.entities), entity_models: entries(mod.data.entity_models), + animations: entries(mod.data.animations ?? []), effects: entries(mod.data.effects), fluids: entries(mod.data.fluids), tags: entries(mod.data.tags), diff --git a/tests/animation_test.ts b/tests/animation_test.ts new file mode 100644 index 0000000..622805c --- /dev/null +++ b/tests/animation_test.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// clips: bedrock animation files read into them, sampled at a time, and what they do to a model's bones +import { assert, assertAlmostEquals, assertEquals, assertStringIncludes } from "@std/assert"; +import { type ClipJson, clips_from_bedrock, entity_model_from_geo, type EntityModelJson } from "@/common/mod_data.ts"; +import { sample_channel, sample_clip } from "@/client/rendering/animation.ts"; +import { apply, bone_matrices, type BoneOffsets, IDENTITY, type Vec3 } from "@/client/rendering/model_math.ts"; +import { create_mod } from "@/tools/new_mod.ts"; +import { load_and_check } from "@/tools/check_mods.ts"; + +// the one clip a file with one animation reads into +function one_clip(animation: unknown): ClipJson { + const { clips, problems } = clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test"); + assertEquals(problems, []); + return clips[0]; +} + +function problems_of(animation: unknown) { + return clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test").problems; +} + +const key = (time: number, value: Vec3, smooth = false, post = value) => ({ time, pre: value, post, smooth }); + +Deno.test("every way bedrock writes a value reads into the same keyframe", () => { + const at_zero = (value: unknown) => one_clip({ bones: { arm: { rotation: { "0.0": value } } } }).bones.arm.rotation; + const expected = [key(0, [5, 5, 5])]; + for (const value of [5, "5", [5, 5, 5], ["5", 5, 5.0], { post: [5, 5, 5] }, { pre: 5 }, { vector: [5, 5, 5] }]) { + assertEquals(at_zero(value), expected, JSON.stringify(value)); + } + // a value for the whole clip, without times + for (const value of [5, [5, 5, 5], { post: 5 }, { vector: 5 }]) { + assertEquals(one_clip({ bones: { arm: { rotation: value } } }).bones.arm.rotation, expected); + } + assertEquals(at_zero({ pre: [1, 2, 3], post: [4, 5, 6], lerp_mode: "catmullrom" }), [ + key(0, [1, 2, 3], true, [4, 5, 6]), + ]); + assertEquals(at_zero({ vector: [1, 2, 3], easing: "catmullrom" }), [key(0, [1, 2, 3], true)]); +}); + +Deno.test("a clip's keyframes are in time order, its length is the last one's without animation_length", () => { + const clip = one_clip({ bones: { arm: { position: { "1.5": [1, 0, 0], "0.25": [2, 0, 0] }, scale: 0 } } }); + assertEquals(clip.bones.arm.position!.map((keyframe) => keyframe.time), [0.25, 1.5]); + assertEquals(clip.length, 1.5); + assertEquals(clip.loop, false); + assertEquals(one_clip({ animation_length: 4, loop: true, bones: {} }).length, 4); + assertEquals(one_clip({ loop: true, bones: {} }).loop, true); + assertEquals(one_clip({ loop: "hold_on_last_frame", bones: {} }).loop, false); +}); + +Deno.test("a file's animations are clips named after their last part", () => { + const file = { animations: { "animation.Walker.WALK": { bones: {} }, "animation.walker.idle": { bones: {} } } }; + const { clips } = clips_from_bedrock(file, "a:walker"); + assertEquals(clips.map((clip) => clip.id), ["a:walker/walk", "a:walker/idle"]); + + const twice = { animations: { "animation.one.walk": { bones: {} }, "animation.two.walk": { bones: {} } } }; + const { problems } = clips_from_bedrock(twice, "a:walker"); + assertStringIncludes(problems.join(), "a:walker/walk is another animation's too"); + assertStringIncludes(clips_from_bedrock({ format_version: "1.8.0" }, "a:b").problems.join(), "animation file"); +}); + +Deno.test("expressions are problems, and what an animator does instead is a warning", () => { + const expression = problems_of({ bones: { box: { rotation: ["math.cos(query.life_time * 180) * 2.5", 0, 0] } } }); + assertEquals(expression.length, 1); + assertStringIncludes(expression[0], "box rotation"); + assertStringIncludes(expression[0], "an animator does that in code"); + assertStringIncludes( + problems_of({ bones: { box: { scale: { "0": { post: 1, lerp_mode: "bezier" } } } } }).join(), + "bezier", + ); + assertStringIncludes(problems_of({ loop: "sometimes", bones: {} }).join(), "loop"); + assertStringIncludes(problems_of({ bones: { box: { rotation: { soon: 0 } } } }).join(), "soon isn't a time"); + + const file = { + animations: { + "animation.box.crank": { + sound_effects: { "0.5": { effect: "turn" } }, + bones: { box: { rotation: 0, relative_to: { rotation: "entity" } } }, + }, + }, + }; + const { clips, warnings } = clips_from_bedrock(file, "a:box"); + assertEquals(clips.length, 1); + assertEquals(warnings.length, 2); + assertStringIncludes(warnings.join(), "sound_effects"); + assertStringIncludes(warnings.join(), "relative_to"); +}); + +Deno.test("check-mods reads a mod's animation files into its clips", async () => { + const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" }); + create_mod("walkers", "Walkers", dir); + Deno.mkdirSync(`${dir}/walkers/animations/monsters`, { recursive: true }); + const animation = { animations: { "animation.walker.walk": { loop: true, bones: { leg: { rotation: 5 } } } } }; + Deno.writeTextFileSync(`${dir}/walkers/animations/monsters/walker.animation.json`, JSON.stringify(animation)); + const broken = { animations: { "animation.broken.walk": { bones: { leg: { rotation: "q.anim_time" } } } } }; + Deno.writeTextFileSync(`${dir}/walkers/animations/broken.animation.json`, JSON.stringify(broken)); + + const mod = (await load_and_check(dir)).find((mod) => mod.id === "walkers")!; + assertEquals(mod.animations.map((clip) => clip.json.id), ["walkers:monsters/walker/walk"]); + const clip_errors = mod.report.errors.filter((error) => error.startsWith("animations/")); + assertEquals(clip_errors.length, 1); + assertStringIncludes(clip_errors[0], "animations/broken.animation.json"); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("between keyframes it's linear, and on or past them it's theirs", () => { + const keyframes = [key(1, [0, 0, 0]), key(2, [10, 20, 30], false, [100, 100, 100]), key(3, [0, 0, 0])]; + assertEquals(sample_channel(keyframes, 1.5, false), [5, 10, 15]); + assertEquals(sample_channel(keyframes, 0, false), [0, 0, 0]); + // on a keyframe that jumps it's what it comes in at, and after it what it leaves at + assertEquals(sample_channel(keyframes, 2, false), [10, 20, 30]); + assertEquals(sample_channel(keyframes, 2.5, false), [50, 50, 50]); + assertEquals(sample_channel(keyframes, 9, false), [0, 0, 0]); +}); + +Deno.test("catmullrom passes through its keyframes, and wraps around for its neighbours in a loop", () => { + const keyframes = [key(0, [0, 0, 0], true), key(1, [10, 10, 10], true), key(2, [0, 0, 0], true)]; + for (const keyframe of keyframes) assertEquals(sample_channel(keyframes, keyframe.time, false), keyframe.pre); + const curve = sample_channel(keyframes, 0.5, false)[0]; + assert(curve > 5, `${curve} curves up toward the peak, past the straight line`); + // in a loop the keyframe before the first is the one before the last, so the trough at the seam is flatter + assert(sample_channel(keyframes, 0.25, true)[0] < sample_channel(keyframes, 0.25, false)[0]); +}); + +Deno.test("a clip that loops wraps around its length, and one that doesn't stays on its last frame", () => { + const bones = { arm: { rotation: [key(0, [0, 0, 0]), key(1, [10, 0, 0])] } }; + const rotation = (clip: ClipJson, seconds: number) => { + const offsets = new Map(); + sample_clip(clip, seconds, offsets); + return offsets.get("arm")!.rotation[0]; + }; + const looping: ClipJson = { id: "a:b/c", length: 2, loop: true, bones }; + const once: ClipJson = { ...looping, loop: false }; + assertAlmostEquals(rotation(looping, 2.5), rotation(looping, 0.5)); + assertAlmostEquals(rotation(looping, -1.5), rotation(looping, 0.5)); + assertEquals(rotation(once, 2.5), 10); + assertEquals(rotation(once, 50), 10); +}); + +Deno.test("clips add up, scaled by their weight", () => { + const clip = (rotation: Vec3, scale: Vec3): ClipJson => ({ + id: "a:b/c", + length: 1, + loop: false, + bones: { arm: { rotation: [key(0, rotation)], scale: [key(0, scale)] } }, + }); + const offsets = new Map(); + sample_clip(clip([10, 0, 0], [3, 1, 1]), 0, offsets, 0.5); + assertEquals(offsets.get("arm"), { rotation: [5, 0, 0], position: [0, 0, 0], scale: [2, 1, 1] }); + sample_clip(clip([0, 20, 0], [1, 1, 0]), 0, offsets); + assertEquals(offsets.get("arm"), { rotation: [5, 20, 0], position: [0, 0, 0], scale: [2, 1, 0] }); +}); + +// a model with an arm and a hand on it, the arm turned by rotation +function arm_model(rotation?: Vec3): EntityModelJson { + const cubes = [{ origin: [0, 0, 0], size: [1, 1, 1], uv: [0, 0] }]; + const arm = { name: "arm", pivot: [2, 3, 4], cubes, ...(rotation ? { rotation } : {}) }; + const geometry = { + description: { texture_width: 16, texture_height: 16 }, + bones: [arm, { name: "hand", parent: "arm", pivot: [2, 0, 4], cubes }], + }; + return entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:arm").model!; +} + +function offsets_for(bone: string, offsets: Partial) { + const full = { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1], ...offsets } as BoneOffsets; + return new Map([[bone, full]]); +} + +function assert_matrices_equal(actual: Map, expected: Map) { + for (const [bone, matrix] of expected) { + matrix.forEach((n, i) => assertAlmostEquals(actual.get(bone)![i], n, 1e-9, `${bone}[${i}]`)); + } +} + +Deno.test("a clip turning a bone turns it like the same rotation in the model, its children with it", () => { + const turned = bone_matrices(arm_model([30, -45, 60]), () => IDENTITY); + const animated = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { rotation: [30, -45, 60] })); + assert_matrices_equal(animated, turned); + // added to the model's own rotation + const added = bone_matrices(arm_model([10, -45, 0]), () => IDENTITY, offsets_for("arm", { rotation: [20, 0, 60] })); + assert_matrices_equal(added, turned); +}); + +Deno.test("a clip moves bones in the model's pixels, and scales them around their pivot", () => { + const point: Vec3 = [5, 7, 9]; + const still = bone_matrices(arm_model(), () => IDENTITY); + const moved = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { position: [1, 2, 3] })); + // bedrock's +x is the engine's -x, like the pivots + for (const bone of ["arm", "hand"]) { + const [x, y, z] = apply(still.get(bone)!, ...point); + assertEquals(apply(moved.get(bone)!, ...point), [x - 1, y + 2, z + 3]); + } + const scaled = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { scale: [2, 3, 0.5] })); + const pivot = [-2, 3, 4]; + assertEquals(apply(scaled.get("arm")!, ...point), point.map((n, i) => pivot[i] + (n - pivot[i]) * [2, 3, 0.5][i])); +}); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 1e56e44..2ca2b16 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -5,6 +5,7 @@ // validates every mod in mods/: manifests, data files, textures, references between them, and typechecks their scripts import * as z from "zod"; import { + clips_from_bedrock, data_file, entity_model_from_geo, FORMAT_VERSION, @@ -131,6 +132,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod { spawns: [], entities: [], entity_models: [], + animations: [], effects: [], fluids: [], tags: [], @@ -229,6 +231,20 @@ function load_mod(mods_dir: string, id: string): LoadedMod { if (model) mod.entity_models.push({ file: path, json: model }); } + // animations/.animation.json, as blockbench exports them for bedrock. each animation in one is a clip + for (const file of walk(`${dir}/animations`, ".animation.json")) { + const path = `animations/${file}`; + const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); + if (json === undefined) continue; + const { clips, problems, warnings } = clips_from_bedrock( + json, + `${id}:${file.replace(/\.animation\.json$/, "")}`, + ); + for (const problem of problems) error(`${path}: ${problem}`); + for (const warning of warnings) mod.report.warnings.push(`${path}: ${warning}`); + for (const clip of clips) mod.animations.push({ file: path, json: clip }); + } + // tags///.json is the tag :, in any namespace: tags are shared for (const file of walk(`${dir}/tags`, ".json")) { const path = `tags/${file}`;