Animators and coilhead animations
This commit is contained in:
@@ -52,7 +52,7 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
**Entities**
|
||||
|
||||
- [Entities](docs/modding/entities/index.md): animals, monsters, custom behaviors and their goals, how mobs get around,
|
||||
natural spawning, scripted entities and entity models
|
||||
natural spawning, scripted entities, entity models and their animations
|
||||
- [Players](docs/modding/entities/players.md): the player API, health and hunger
|
||||
|
||||
**Inventories**
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
|
||||
import type { EntityJson } from "@/common/mod_data.ts";
|
||||
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { wrap_angle } from "@/common/utils.ts";
|
||||
import { animation_for, type EntityAnimation } from "../rendering/entity_animators.ts";
|
||||
import type { ClientLevel } from "../level/client_level.ts";
|
||||
import { Entity } from "./entity.ts";
|
||||
|
||||
@@ -21,8 +22,12 @@ const SWING_TICKS = 6;
|
||||
export class RemoteEntity extends Entity {
|
||||
// the entity type, like "cubi:item"
|
||||
readonly type: string;
|
||||
// synced data, see EntityData
|
||||
// synced data, see EntityData. set_data changes it
|
||||
data: EntityData;
|
||||
// ticks since this client got it
|
||||
age = 0;
|
||||
// its type's animator from a mod, see ClientRender.register_entity_animator
|
||||
readonly animation: EntityAnimation | undefined;
|
||||
head_yaw: number;
|
||||
// counting down after a hurt event, and up after a death one
|
||||
hurt_time = 0;
|
||||
@@ -47,6 +52,13 @@ export class RemoteEntity extends Entity {
|
||||
this.pitch = info.pitch;
|
||||
this.head_yaw = info.head_yaw ?? info.yaw;
|
||||
this.#target = { x: info.x, y: info.y, z: info.z, yaw: info.yaw, pitch: info.pitch, head_yaw: this.head_yaw };
|
||||
this.animation = animation_for(this);
|
||||
}
|
||||
|
||||
set_data(data: EntityData) {
|
||||
const before = this.data;
|
||||
this.data = data;
|
||||
this.animation?.data_changed(before);
|
||||
}
|
||||
|
||||
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number, head_yaw = yaw) {
|
||||
@@ -66,6 +78,7 @@ export class RemoteEntity extends Entity {
|
||||
}
|
||||
|
||||
tick() {
|
||||
this.age += 1;
|
||||
if (this.hurt_time > 0) this.hurt_time -= 1;
|
||||
if (this.dead) this.death_time = Math.min(DEATH_TICKS, this.death_time + 1);
|
||||
|
||||
|
||||
@@ -44,9 +44,11 @@ import { clear_hooks, expose_engine } 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 { entity_animators } from "./rendering/entity_animators.ts";
|
||||
import { biome_season } from "@/common/worldgen/biomes.ts";
|
||||
import { clock, farming_day } from "@/common/time.ts";
|
||||
import type { LootTableJson } from "@/common/loot.ts";
|
||||
import type { ClipJson } from "@/common/mod_data.ts";
|
||||
|
||||
// each loaded mod's credits file, for the credits screen
|
||||
export const mod_credits: { name: string; version: string; text: string }[] = [];
|
||||
@@ -206,6 +208,7 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
|
||||
menu_screens.clear();
|
||||
net_handlers.clear();
|
||||
block_visuals.clear();
|
||||
entity_animators.clear();
|
||||
mod_names.clear();
|
||||
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
||||
|
||||
@@ -429,6 +432,21 @@ function client_context(listing: ModListing): ClientContext {
|
||||
if (other) register.fail(`${block} already has a visual, from ${other.mod}`);
|
||||
block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false });
|
||||
},
|
||||
register_entity_animator(type, create) {
|
||||
register.running("entity animator");
|
||||
if (!EverythingRegistry.get("entities", type)) throw new Error(`[${mod}] unknown entity ${type}`);
|
||||
if (typeof create !== "function") {
|
||||
throw new Error(`[${mod}] an animator needs a function that makes it`);
|
||||
}
|
||||
const other = entity_animators.get(type);
|
||||
if (other) register.fail(`${type} already has an animator, from ${other.mod}`);
|
||||
entity_animators.set(type, { mod, create });
|
||||
},
|
||||
clip(id) {
|
||||
const json = EverythingRegistry.get<ClipJson>("animations", id);
|
||||
if (!json) throw new Error(`[${mod}] unknown clip ${id}`);
|
||||
return Object.freeze({ id, length: json.length, loop: json.loop });
|
||||
},
|
||||
},
|
||||
log: (...args) => console.log(`[${mod}]`, ...args),
|
||||
};
|
||||
|
||||
@@ -145,7 +145,7 @@ export class ClientPacketListener {
|
||||
case "entity_data": {
|
||||
const entity = level.entities.get(message.id);
|
||||
if (entity instanceof RemoteEntity) {
|
||||
entity.data = message.data;
|
||||
entity.set_data(message.data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,11 @@ 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;
|
||||
|
||||
// a bone nothing has moved
|
||||
export function rest_offsets(): BoneOffsets {
|
||||
return { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1] };
|
||||
}
|
||||
|
||||
// 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<string, BoneOffsets>, weight = 1) {
|
||||
@@ -17,7 +22,7 @@ export function sample_clip(clip: ClipJson, seconds: number, offsets: Map<string
|
||||
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] };
|
||||
offset = rest_offsets();
|
||||
offsets.set(bone, offset);
|
||||
}
|
||||
for (const channel of ["rotation", "position"] as const) {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// mods' entity animators, see ClientRender.register_entity_animator and ANIMATION.md. each entity of a type with one
|
||||
// gets its own, made with the entity, which says what its model's bones do every frame it's drawn
|
||||
import type { AnimatedEntity, Clip, EntityAnimator, EntityPose } from "@/common/mod_api/client.ts";
|
||||
import type { ClipJson } from "@/common/mod_data.ts";
|
||||
import type { EntityData } from "@/common/protocol.ts";
|
||||
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import { wrap_angle } from "@/common/utils.ts";
|
||||
import { rest_offsets, sample_clip } from "./animation.ts";
|
||||
import type { BoneOffsets } from "./model_math.ts";
|
||||
|
||||
export interface AnimatorRegistration {
|
||||
mod: string;
|
||||
create: (entity: AnimatedEntity) => EntityAnimator;
|
||||
}
|
||||
|
||||
// by entity type
|
||||
export const entity_animators = new Map<string, AnimatorRegistration>();
|
||||
|
||||
// what an animator reads of its entity, a RemoteEntity's
|
||||
export interface AnimatorSource {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly data: EntityData;
|
||||
// ticks since this client got it
|
||||
readonly age: number;
|
||||
readonly yaw: number;
|
||||
readonly head_yaw: number;
|
||||
readonly pitch: number;
|
||||
walk_animation(partial_tick: number): { position: number; speed: number };
|
||||
attack_animation(partial_tick: number): number;
|
||||
}
|
||||
|
||||
const DEGREES = 180 / Math.PI;
|
||||
|
||||
// one entity's animator, undefined for a type without one
|
||||
export function animation_for(source: AnimatorSource): EntityAnimation | undefined {
|
||||
const registration = entity_animators.get(source.type);
|
||||
return registration && new EntityAnimation(source, registration);
|
||||
}
|
||||
|
||||
export class EntityAnimation {
|
||||
#source: AnimatorSource;
|
||||
#mod: string;
|
||||
#entity: AnimatedEntity;
|
||||
#animator: EntityAnimator | undefined;
|
||||
|
||||
constructor(source: AnimatorSource, { mod, create }: AnimatorRegistration) {
|
||||
this.#source = source;
|
||||
this.#mod = mod;
|
||||
this.#entity = animated_entity(source);
|
||||
this.#run("create", () => this.#animator = create(this.#entity));
|
||||
for (const field of Object.keys(client_data(source.data))) this.#on_data(field);
|
||||
}
|
||||
|
||||
// its client data was before and is now the source's
|
||||
data_changed(before: EntityData) {
|
||||
const old = client_data(before);
|
||||
const now = client_data(this.#source.data);
|
||||
for (const field of new Set([...Object.keys(old), ...Object.keys(now)])) {
|
||||
if (JSON.stringify(old[field]) !== JSON.stringify(now[field])) this.#on_data(field);
|
||||
}
|
||||
}
|
||||
|
||||
// what the animator does to the bones at time, undefined when there's no animator (anymore)
|
||||
pose(time: number): Map<string, BoneOffsets> | undefined {
|
||||
const animator = this.#animator;
|
||||
if (!animator) return undefined;
|
||||
const offsets = new Map<string, BoneOffsets>();
|
||||
const posed = this.#run("pose", () => animator.pose(entity_pose(offsets, this.#entity), time));
|
||||
return posed ? offsets : undefined;
|
||||
}
|
||||
|
||||
#on_data(field: string) {
|
||||
const animator = this.#animator;
|
||||
if (animator?.on_data) this.#run("on_data", () => animator.on_data!(field, this.#source.age));
|
||||
}
|
||||
|
||||
// false when it threw, which is logged with the mod and the entity, and the animator is gone
|
||||
#run(what: string, fn: () => void) {
|
||||
try {
|
||||
fn();
|
||||
return true;
|
||||
} catch (e) {
|
||||
const { type, id } = this.#source;
|
||||
console.error(`[${this.#mod}] the animator of ${type} ${id} threw in ${what}, it's removed:`, e);
|
||||
this.#animator = undefined;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function client_data(data: EntityData): Record<string, unknown> {
|
||||
return (data.client_data ?? {}) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function animated_entity(source: AnimatorSource): AnimatedEntity {
|
||||
// time is in ticks with the part of the next one, the source's walk and attack take that part
|
||||
const partial = (time: number) => Math.min(Math.max(time - source.age, 0), 1);
|
||||
return {
|
||||
get id() {
|
||||
return source.id;
|
||||
},
|
||||
get type() {
|
||||
return source.type;
|
||||
},
|
||||
get_client_data: (field) => structuredClone(client_data(source.data)[field]) as never,
|
||||
walk_position: (time) => source.walk_animation(partial(time)).position,
|
||||
walk_speed: (time) => source.walk_animation(partial(time)).speed,
|
||||
attack_progress: (time) => source.attack_animation(partial(time)),
|
||||
// mirrored like a model's rotations, see model_math's own_matrix
|
||||
get head_pitch() {
|
||||
return -source.pitch * DEGREES;
|
||||
},
|
||||
get head_yaw() {
|
||||
return -wrap_angle(source.head_yaw - source.yaw) * DEGREES;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// a clip by what ClientRender.clip gave
|
||||
function clip_json(clip: Clip): ClipJson {
|
||||
const json = EverythingRegistry.get<ClipJson>("animations", clip?.id);
|
||||
if (!json) throw new Error(`${clip?.id} isn't a clip, see ctx.render.clip`);
|
||||
return json;
|
||||
}
|
||||
|
||||
function entity_pose(offsets: Map<string, BoneOffsets>, entity: AnimatedEntity): EntityPose {
|
||||
const offset = (bone: string) => {
|
||||
let found = offsets.get(bone);
|
||||
if (!found) {
|
||||
found = rest_offsets();
|
||||
offsets.set(bone, found);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
const pose: EntityPose = {
|
||||
play(clip, seconds, weight = 1) {
|
||||
sample_clip(clip_json(clip), seconds, offsets, weight);
|
||||
},
|
||||
play_state(clip, state, time, weight) {
|
||||
if (state.started) pose.play(clip, state.seconds(time), weight);
|
||||
},
|
||||
play_walk(clip, walker, time, speed_scale = 1) {
|
||||
pose.play(clip, walker.walk_position(time) / 20, Math.min(walker.walk_speed(time) * speed_scale, 1));
|
||||
},
|
||||
rotate(bone, x, y, z) {
|
||||
const rotation = offset(bone).rotation;
|
||||
rotation[0] += x;
|
||||
rotation[1] += y;
|
||||
rotation[2] += z;
|
||||
},
|
||||
move(bone, x, y, z) {
|
||||
const position = offset(bone).position;
|
||||
position[0] += x;
|
||||
position[1] += y;
|
||||
position[2] += z;
|
||||
},
|
||||
scale(bone, x, y, z) {
|
||||
const scale = offset(bone).scale;
|
||||
scale[0] *= x;
|
||||
scale[1] *= y;
|
||||
scale[2] *= z;
|
||||
},
|
||||
look(bone) {
|
||||
pose.rotate(bone, entity.head_pitch, entity.head_yaw, 0);
|
||||
},
|
||||
};
|
||||
return pose;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no
|
||||
// animation files yet: the model turns to the entity's yaw, a bone named "head" to where it looks, and bones named
|
||||
// like minecraft's humanoid ones (right_arm, left_arm, right_leg, left_leg) swing as it walks, the right arm when it
|
||||
// attacks too. entities without a model are their texture facing the camera, like minecraft's fishing hook
|
||||
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. the model
|
||||
// turns to the entity's yaw, and its bones are posed by its type's animator from a mod (see entity_animators.ts). without
|
||||
// one, a bone named "head" turns to where it looks, and bones named like minecraft's humanoid ones (right_arm, left_arm,
|
||||
// right_leg, left_leg) swing as it walks, the right arm when it attacks too. entities without a model are their texture
|
||||
// facing the camera, like minecraft's fishing hook
|
||||
import { AssetManager } from "@/client/assets.ts";
|
||||
import type { Camera } from "@/client/camera.ts";
|
||||
import type { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||
@@ -14,7 +15,7 @@ import type { SpriteRegion } from "@/common/constants.ts";
|
||||
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import type { EntityBoneJson, EntityJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||
import { HURT_TINT } from "./player_renderer.ts";
|
||||
import { IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||
import { bone_matrices, IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||
import { push_model } from "./model_renderer.ts";
|
||||
import { entity_tint } from "./entity_light.ts";
|
||||
|
||||
@@ -44,8 +45,15 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
|
||||
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
|
||||
};
|
||||
|
||||
const offsets = entity.animation?.pose(entity.age + partial_tick);
|
||||
const pose = offsets ? () => IDENTITY : default_pose(entity, partial_tick);
|
||||
push_model(model, bone_matrices(model, pose, offsets), atlas, region, to_world, tint);
|
||||
}
|
||||
|
||||
// the head looking and the humanoid swing, for an entity without an animator
|
||||
function default_pose(entity: RemoteEntity, partial_tick: number) {
|
||||
const limbs = limb_angles(entity, partial_tick);
|
||||
const pose = (bone: EntityBoneJson) => {
|
||||
return (bone: EntityBoneJson) => {
|
||||
let matrix = IDENTITY;
|
||||
if (bone.name === "head") {
|
||||
matrix = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
|
||||
@@ -54,7 +62,6 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
|
||||
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
|
||||
return matrix;
|
||||
};
|
||||
push_model(model, pose, atlas, region, to_world, tint);
|
||||
}
|
||||
|
||||
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
import type { Texture } from "@/client/renderer/mod.ts";
|
||||
import type { SpriteRegion } from "@/common/constants.ts";
|
||||
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||
import { apply, bone_matrices, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
|
||||
import { apply, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
|
||||
import { push_box, type VertexSink } from "./player_renderer.ts";
|
||||
|
||||
// pose is each bone's turn before its parent's, like a head looking or a limb swinging. to_world takes the model's
|
||||
// pixels, after the bones are turned, to the world. the texture is region of the atlas, stretched to the model's
|
||||
// texture size. only picks the bones drawn, all of them when not given. emit gets the vertices, the batch by default
|
||||
// bones is each bone's matrix, see bone_matrices. to_world takes the model's pixels, after the bones are turned, to the
|
||||
// world. the texture is region of the atlas, stretched to the model's texture size. only picks the bones drawn, all of
|
||||
// them when not given. emit gets the vertices, the batch by default
|
||||
export function push_model(
|
||||
model: EntityModelJson,
|
||||
pose: (bone: EntityBoneJson) => Matrix,
|
||||
bones: Map<string, Matrix>,
|
||||
atlas: Texture,
|
||||
region: SpriteRegion,
|
||||
to_world: (x: number, y: number, z: number) => Vec3,
|
||||
@@ -25,11 +25,10 @@ export function push_model(
|
||||
(region.x + u * region.width / model.texture_width) / atlas.width,
|
||||
(region.y + v * region.height / model.texture_height) / atlas.height,
|
||||
];
|
||||
const matrices = bone_matrices(model, pose);
|
||||
for (const bone of model.bones) {
|
||||
if (only && !only(bone)) continue;
|
||||
for (const cube of bone.cubes) {
|
||||
const matrix = multiply(matrices.get(bone.name)!, own_matrix(cube));
|
||||
const matrix = multiply(bones.get(bone.name)!, own_matrix(cube));
|
||||
const transform = (px: number, py: number, pz: number) => to_world(...apply(matrix, px, py, pz));
|
||||
const inflate = cube.inflate ?? 0;
|
||||
const [ox, oy, oz] = cube.origin;
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { Texture } from "@/client/renderer/mod.ts";
|
||||
import { get_sprite_region } from "@/client/sprites.ts";
|
||||
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||
import { IDENTITY, type Vec3 } from "./model_math.ts";
|
||||
import { bone_matrices, IDENTITY, type Vec3 } from "./model_math.ts";
|
||||
import { push_model } from "./model_renderer.ts";
|
||||
import type { VertexSink } from "./player_renderer.ts";
|
||||
import { on_part, type PlayerPose, pose_to_world, right_arm, worn_bone_pose, worn_look } from "./player_model.ts";
|
||||
@@ -34,7 +34,7 @@ export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3
|
||||
if (!model) continue;
|
||||
push_model(
|
||||
model,
|
||||
worn_bone_pose(pose),
|
||||
bone_matrices(model, worn_bone_pose(pose)),
|
||||
atlas,
|
||||
get_sprite_region(look.texture),
|
||||
to_world,
|
||||
@@ -59,6 +59,7 @@ export function render_worn_arm(player: Player, transform: (x: number, y: number
|
||||
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
|
||||
if (!model) continue;
|
||||
const only = (bone: EntityBoneJson) => on_part(model, bone, "right_arm");
|
||||
push_model(model, () => IDENTITY, atlas, get_sprite_region(look.texture), to_arm, tint, only);
|
||||
const bones = bone_matrices(model, () => IDENTITY);
|
||||
push_model(model, bones, atlas, get_sprite_region(look.texture), to_arm, tint, only);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,104 @@ export interface ClientRender {
|
||||
create: (block: VisualBlock, instances: Instances) => Visual,
|
||||
options?: { replaces_model?: boolean },
|
||||
): void;
|
||||
// every entity of this type gets an animator from create while the client has it, which poses its model's bones
|
||||
// each frame instead of the engine's head look and humanoid swing, like a model's setupAnim. only during setup,
|
||||
// and one per type. see ANIMATION.md
|
||||
register_entity_animator(type: Id, create: (entity: AnimatedEntity) => EntityAnimator): void;
|
||||
// a clip, from a bedrock animation file in animations/: animation.walker.walk in animations/walker.animation.json
|
||||
// is my_mod:walker/walk. throws when there isn't one, so a typo shows up at setup
|
||||
clip(id: string): Clip;
|
||||
}
|
||||
|
||||
// what poses one entity. time is its age on this client in ticks, with the part of the next one, the same time
|
||||
// AnimationState takes. one that throws is removed, with the error in the console, and the entity posed without it
|
||||
export interface EntityAnimator {
|
||||
// before each frame the entity is drawn
|
||||
pose(pose: EntityPose, time: number): void;
|
||||
// a field of its client data changed (see MobRef.set_client_data in cubi/server), or was already set when the
|
||||
// animator was made
|
||||
on_data?(field: string, time: number): void;
|
||||
}
|
||||
|
||||
// the entity an animator poses
|
||||
export interface AnimatedEntity {
|
||||
readonly id: string;
|
||||
readonly type: Id;
|
||||
// a field of its client data now, a copy, see MobRef.set_client_data in cubi/server
|
||||
get_client_data<T>(field: string): T | undefined;
|
||||
// how far it's walked, about 1 a tick at full speed, and how fast it's walking now, 0 to 1. they ease
|
||||
// toward its movement, so a clip doesn't jump when it starts or stops
|
||||
walk_position(time: number): number;
|
||||
walk_speed(time: number): number;
|
||||
// how far through its attack swing it is, 0 to 1, 0 when it isn't swinging
|
||||
attack_progress(time: number): number;
|
||||
// how a bone facing the way its body does turns to where it looks, in degrees, as EntityPose.rotate takes them
|
||||
readonly head_pitch: number;
|
||||
readonly head_yaw: number;
|
||||
}
|
||||
|
||||
// a clip from animations/, see ClientRender.clip
|
||||
export interface Clip {
|
||||
readonly id: string;
|
||||
// seconds
|
||||
readonly length: number;
|
||||
// one that doesn't stays on its last frame after its length
|
||||
readonly loop: boolean;
|
||||
}
|
||||
|
||||
// a model's bones for one frame, all at rest until something moves them. what's played and added adds up: rotations
|
||||
// and positions add, scales multiply. bones are the model's by name, ones it doesn't have do nothing
|
||||
export interface EntityPose {
|
||||
// clip at seconds into it. weight scales what it does, 1 when not given
|
||||
play(clip: Clip, seconds: number, weight?: number): void;
|
||||
// clip from when state started, nothing while it's stopped
|
||||
play_state(clip: Clip, state: AnimationState, time: number, weight?: number): void;
|
||||
// clip as it walks, like neoforge's applyWalk: as far through as it's walked (a second of clip for 20 of
|
||||
// walk_position) and as strongly as it's walking, times speed_scale, at most 1
|
||||
play_walk(clip: Clip, entity: AnimatedEntity, time: number, speed_scale?: number): void;
|
||||
// on top of the clips, in degrees, pixels and how much it's scaled, like the clips. bedrock's +x, like the model
|
||||
rotate(bone: string, x: number, y: number, z: number): void;
|
||||
move(bone: string, x: number, y: number, z: number): void;
|
||||
scale(bone: string, x: number, y: number, z: number): void;
|
||||
// turns a bone to where the entity looks, like the engine does a bone named head without an animator
|
||||
look(bone: string): void;
|
||||
}
|
||||
|
||||
// when something an animator plays started, like neoforge's AnimationState. time is in ticks, see EntityAnimator
|
||||
export class AnimationState {
|
||||
#started: number | undefined;
|
||||
|
||||
get started() {
|
||||
return this.#started !== undefined;
|
||||
}
|
||||
|
||||
start(time: number) {
|
||||
this.#started = time;
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.#started = undefined;
|
||||
}
|
||||
|
||||
start_if_stopped(time: number) {
|
||||
if (this.#started === undefined) this.#started = time;
|
||||
}
|
||||
|
||||
// starts it when condition holds and it's stopped, and stops it when it doesn't
|
||||
animate_when(condition: boolean, time: number) {
|
||||
if (condition) this.start_if_stopped(time);
|
||||
else this.stop();
|
||||
}
|
||||
|
||||
// seconds since it started, at 20 ticks a second. 0 while it's stopped
|
||||
seconds(time: number) {
|
||||
return this.#started === undefined ? 0 : (time - this.#started) / 20;
|
||||
}
|
||||
|
||||
// whether a clip that doesn't loop has played to its end since this started. never for one that loops
|
||||
finished(clip: Clip, time: number) {
|
||||
return this.started && !clip.loop && this.seconds(time) >= clip.length;
|
||||
}
|
||||
}
|
||||
|
||||
// the block a visual draws
|
||||
|
||||
@@ -284,6 +284,11 @@ export interface MobRef extends LivingRef {
|
||||
jump(): void;
|
||||
// swings its arm and hits target with its attack_damage, wherever target is
|
||||
attack(target: Player | MobRef): void;
|
||||
// what clients see of its state, like BlockRef's: what its animator reads (see register_entity_animator in
|
||||
// cubi/client). each field is any json value, saved with it, and sent to clients when it changes. undefined
|
||||
// removes one
|
||||
get_client_data<T>(field: string): T | undefined;
|
||||
set_client_data(field: string, value: unknown): void;
|
||||
}
|
||||
|
||||
// commands, brigadier's way like neoforge's: see common/commands.ts and docs/modding/misc/commands.md
|
||||
|
||||
+2
-1
@@ -52,7 +52,8 @@ export type EntityInfo =
|
||||
};
|
||||
|
||||
// what an entity looks like that can change, like minecraft's SynchedEntityData: custom_name, custom_name_visible,
|
||||
// glowing, on_fire, silent, left_handed, equipment (slot to item). only what's set is there
|
||||
// glowing, on_fire, silent, left_handed, equipment (slot to item), and client_data (a mod's fields, see
|
||||
// MobRef.set_client_data). only what's set is there
|
||||
export type EntityData = Record<string, unknown>;
|
||||
|
||||
// what happens to an entity that clients show, see entity_event
|
||||
|
||||
@@ -327,8 +327,8 @@ where a face that's left out isn't drawn and a negative size flips it. Faces are
|
||||
`entity_alphatest` material, so a flat cube needs only one textured face. A bone's parent has to come before it. The
|
||||
model faces -z, 16 pixels to a block with its feet at 0, and shows the way Blockbench shows it.
|
||||
|
||||
There are no animation files yet. The whole model turns with the entity, and bones with Minecraft's humanoid names move
|
||||
on their own:
|
||||
The whole model turns with the entity. An entity type with an [animator](#animations) has its bones posed by that.
|
||||
Without one, bones with Minecraft's humanoid names move on their own:
|
||||
|
||||
- `head` turns to where the entity looks.
|
||||
- `right_arm`, `left_arm`, `right_leg` and `left_leg` swing as it walks, each arm with the opposite leg.
|
||||
@@ -336,3 +336,74 @@ on their own:
|
||||
|
||||
Without a model, the whole texture is drawn facing the camera, 16 pixels to a block, centered on the middle of the
|
||||
entity's box.
|
||||
|
||||
## Animations
|
||||
|
||||
Animations are keyframes made in Blockbench, played by code in the mod's client script. This is how NeoForge does it
|
||||
too: JSON keyframes, applied by the model's own `setupAnim`. Bedrock's Molang expressions and animation controllers
|
||||
aren't used, since the animator does both in TypeScript.
|
||||
|
||||
### Clips
|
||||
|
||||
`animations/<name>.animation.json` are animation files as Blockbench exports them for Bedrock. Each animation in one is
|
||||
a clip, named after the file and the last part of the animation's name: `animation.coilhead.walk` in
|
||||
`animations/coilhead.animation.json` is `<mod id>:coilhead/walk`. From each animation, bworld uses:
|
||||
|
||||
- `animation_length`, in seconds, or the last keyframe's time without it,
|
||||
- `loop`: `true` loops. `false`, no `loop` and `"hold_on_last_frame"` all stay on the last frame after the clip's end,
|
||||
- each bone's `rotation` (degrees, added to the bone's own), `position` (pixels) and `scale`, as one value for the whole
|
||||
clip or keyframes by time. A keyframe is a number for all three axes, `[x, y, z]`, `{ "pre": ..., "post": ... }`, and
|
||||
can be `"lerp_mode": "catmullrom"` for a smooth curve.
|
||||
|
||||
A value that's a Molang expression, like `"math.cos(query.life_time * 180) * 2.5"`, is an error: do it in the animator
|
||||
with `pose.rotate` or `pose.move`. `deno task check-mods` warns about what the animator does instead, like
|
||||
`sound_effects` and `anim_time_update`.
|
||||
|
||||
### Animators
|
||||
|
||||
The client phase registers an animator for an entity type. Each entity of that type the client has gets its own, and
|
||||
before each frame it's drawn, the animator plays clips and moves bones. A coilhead that bobs as it walks, looks around,
|
||||
and plays `stop` once when it freezes:
|
||||
|
||||
```ts
|
||||
import { AnimationState, type ClientContext } from "cubi/client";
|
||||
|
||||
export function client(ctx: ClientContext) {
|
||||
const walk = ctx.render.clip("my_mod:coilhead/walk");
|
||||
const stop = ctx.render.clip("my_mod:coilhead/stop");
|
||||
ctx.render.register_entity_animator("my_mod:coilhead", (coilhead) => {
|
||||
const frozen = new AnimationState();
|
||||
return {
|
||||
on_data(field, time) {
|
||||
if (field === "frozen") frozen.animate_when(coilhead.get_client_data("frozen") === true, time);
|
||||
},
|
||||
pose(pose, time) {
|
||||
if (frozen.started && !frozen.finished(stop, time)) pose.play_state(stop, frozen, time);
|
||||
else pose.play_walk(walk, coilhead, time);
|
||||
pose.look("head");
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- `time` is the entity's age on this client in ticks, with the part of the next one.
|
||||
- `pose.play(clip, seconds, weight)` plays a clip at some point in it. Clips played together add up, and `weight` scales
|
||||
one, so blending from one to another is turning one down while the other goes up.
|
||||
- `pose.play_state(clip, state, time)` plays it from when an `AnimationState` started. An animator keeps one for each
|
||||
clip it starts on its own, and starts and stops it with `start`, `stop` and `animate_when`.
|
||||
- `pose.play_walk(clip, entity, time)` plays it as far through as the entity has walked, as strongly as it's walking.
|
||||
- `pose.rotate`, `pose.move` and `pose.scale` add to a bone on top of the clips, in the clips' units.
|
||||
- `pose.look(bone)` turns a bone to where the entity looks.
|
||||
|
||||
An animator that throws is removed, with the error in the console, and its entity goes back to the humanoid pose.
|
||||
|
||||
What the animator knows of the mob's state comes from its client data, which the server side sets:
|
||||
|
||||
```ts
|
||||
mob.set_client_data("frozen", true);
|
||||
mob.set_client_data("frozen", undefined); // removes it
|
||||
```
|
||||
|
||||
Client data is saved with the mob and sent to players when it changes. The animator's `on_data` hears about each field
|
||||
as it changes, and about the ones already set when the entity first shows up.
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
{
|
||||
"format_version": "1.8.0",
|
||||
"animations": {
|
||||
"animation.CoilHead.idle": {
|
||||
"loop": true,
|
||||
"animation_length": 1,
|
||||
"bones": {
|
||||
"coilhead": {
|
||||
"rotation": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"position": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"scale": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"animation.CoilHead.stop": {
|
||||
"animation_length": 0.75,
|
||||
"bones": {
|
||||
"spring": {
|
||||
"rotation": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [-22.5, 0, 0]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [12.5, 0, 0]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"position": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"scale": {
|
||||
"0.0": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
},
|
||||
"head": {
|
||||
"rotation": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [-17.5, 0, 0]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [32.5, 0, 0]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"position": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"scale": {
|
||||
"0.0": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.5417": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.75": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"animation.CoilHead.walk": {
|
||||
"loop": true,
|
||||
"animation_length": 0.5,
|
||||
"bones": {
|
||||
"coilhead": {
|
||||
"rotation": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"position": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [0, -1.3, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [0, -1.3, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"scale": {
|
||||
"0.0": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
},
|
||||
"left_leg": {
|
||||
"rotation": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [-20, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [25, 0, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"position": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"scale": {
|
||||
"0.0": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
},
|
||||
"right_leg": {
|
||||
"rotation": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [25, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [-12.5, 0, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"position": {
|
||||
"0.0": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [0, 0, 0]
|
||||
}
|
||||
},
|
||||
"scale": {
|
||||
"0.0": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.125": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.25": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.375": {
|
||||
"vector": [1, 1, 1]
|
||||
},
|
||||
"0.5": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
},
|
||||
"spring": {
|
||||
"rotation": {
|
||||
"vector": [-22.5, 0, 0]
|
||||
},
|
||||
"position": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"scale": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
},
|
||||
"head": {
|
||||
"rotation": {
|
||||
"vector": [-17.5, 0, 0]
|
||||
},
|
||||
"position": {
|
||||
"vector": [0, 0, 0]
|
||||
},
|
||||
"scale": {
|
||||
"vector": [1, 1, 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// the coilhead: it goes after players like any monster, but can't move while one of them is looking at it
|
||||
import type { MobRef, Player, Position, ScriptGoal, ServerContext } from "cubi/server";
|
||||
import { AnimationState, type ClientContext } from "cubi/client";
|
||||
import { DOOR, type DoorParams, set_door_open } from "./shared.ts";
|
||||
|
||||
// how far away a player still freezes it
|
||||
@@ -21,11 +22,16 @@ export function register_coilhead(ctx: ServerContext) {
|
||||
const nearest_player = builtin.nearest_attackable_player();
|
||||
|
||||
ctx.entities.register_behavior("dangerous_business:coilhead", (mob, goals) => {
|
||||
// takes every control from the goals after it, so it doesn't walk, turn, jump or hit while seen
|
||||
// takes every control from the goals after it, so it doesn't walk, turn, jump or hit while seen. clients see it
|
||||
// frozen, for its animator
|
||||
goals.add(0, {
|
||||
flags: ["move", "look", "jump"],
|
||||
can_use: () => ctx.players.all().some((player) => sees(ctx, player, mob)),
|
||||
start: () => mob.stop(),
|
||||
start: () => {
|
||||
mob.stop();
|
||||
mob.set_client_data("frozen", true);
|
||||
},
|
||||
stop: () => mob.set_client_data("frozen", undefined),
|
||||
});
|
||||
goals.add(1, chase);
|
||||
goals.add(2, stroll);
|
||||
@@ -36,6 +42,31 @@ export function register_coilhead(ctx: ServerContext) {
|
||||
});
|
||||
}
|
||||
|
||||
// bobs as it walks and stands still otherwise. when it freezes its head springs back and forth once, and it looks
|
||||
// where it's looking
|
||||
export function register_coilhead_animator(ctx: ClientContext) {
|
||||
const idle = ctx.render.clip("dangerous_business:coilhead/idle");
|
||||
const walk = ctx.render.clip("dangerous_business:coilhead/walk");
|
||||
const stop = ctx.render.clip("dangerous_business:coilhead/stop");
|
||||
ctx.render.register_entity_animator("dangerous_business:coilhead", (coilhead) => {
|
||||
const frozen = new AnimationState();
|
||||
return {
|
||||
on_data(field, time) {
|
||||
if (field === "frozen") frozen.animate_when(coilhead.get_client_data("frozen") === true, time);
|
||||
},
|
||||
pose(pose, time) {
|
||||
if (frozen.started && !frozen.finished(stop, time)) {
|
||||
pose.play_state(stop, frozen, time);
|
||||
} else {
|
||||
pose.play(idle, time / 20);
|
||||
pose.play_walk(walk, coilhead, time);
|
||||
}
|
||||
pose.look("head");
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// opens a door on the mob's way after it's stood at it for ticks. without flags, so the goal going after its target
|
||||
// keeps its way and the mob stays at the door. the door's in the mobs_path_through tag, so its way goes through it
|
||||
export function opens_doors(ctx: ServerContext, mob: MobRef, ticks: number): ScriptGoal {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { ClientContext, Color } from "cubi/client";
|
||||
import type { ServerContext } from "cubi/server";
|
||||
import { DOOR, FACILITY_DOOR } from "./shared.ts";
|
||||
import { Alea } from "@paulaboks/rng";
|
||||
import { register_coilhead } from "./coilhead.ts";
|
||||
import { register_coilhead, register_coilhead_animator } from "./coilhead.ts";
|
||||
import { DOORWAY, MAIN_TILE, type Marker, type PlacedTile, plan_interior, tile_type, TILES } from "./interior.ts";
|
||||
|
||||
export { shared } from "./shared.ts";
|
||||
@@ -19,6 +19,7 @@ export function server(ctx: ServerContext) {
|
||||
|
||||
export function client(ctx: ClientContext) {
|
||||
register_hud(ctx);
|
||||
register_coilhead_animator(ctx);
|
||||
}
|
||||
|
||||
// a small 5x5 ring in the middle of the screen to aim with, its corners and middle left empty, in gui pixels
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { EntityData } from "@/common/protocol.ts";
|
||||
import type { ItemStack } from "@/common/inventory.ts";
|
||||
import { wrap_angle } from "@/common/utils.ts";
|
||||
import { TICK_DELTA } from "@/common/constants.ts";
|
||||
import { is_object } from "@/common/schema.ts";
|
||||
import { physics } from "@/common/physics.ts";
|
||||
|
||||
// minecraft's despawning distances: gone at once past the first, maybe after a while past the second
|
||||
@@ -40,6 +41,7 @@ export interface SavedMob extends SavedLivingEntity {
|
||||
home_pos?: [number, number, number];
|
||||
home_radius?: number;
|
||||
drop_chances?: Partial<Record<EquipmentSlot, number>>;
|
||||
client_data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// what natural spawning counts a mob as, like minecraft's MobCategory
|
||||
@@ -52,6 +54,9 @@ export abstract class Mob extends LivingEntity {
|
||||
persistence_required = false;
|
||||
can_pick_up_loot = false;
|
||||
left_handed = false;
|
||||
// what clients see of a mod's mob's state, see MobRef.set_client_data. replaced rather than changed, so a save never
|
||||
// shares it
|
||||
client_data: Record<string, unknown> = {};
|
||||
// where it stays around, see is_within_home. no home when the radius is -1
|
||||
home: { x: number; y: number; z: number } | undefined;
|
||||
home_radius = -1;
|
||||
@@ -265,6 +270,7 @@ export abstract class Mob extends LivingEntity {
|
||||
override synced_data(): EntityData {
|
||||
const data = super.synced_data();
|
||||
if (this.left_handed) data.left_handed = true;
|
||||
if (Object.keys(this.client_data).length) data.client_data = this.client_data;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -281,6 +287,7 @@ export abstract class Mob extends LivingEntity {
|
||||
saved.home_radius = this.home_radius;
|
||||
}
|
||||
if (Object.keys(this.drop_chances).length) saved.drop_chances = { ...this.drop_chances };
|
||||
if (Object.keys(this.client_data).length) saved.client_data = this.client_data;
|
||||
}
|
||||
|
||||
override load_additional(saved: SavedMob) {
|
||||
@@ -289,6 +296,7 @@ export abstract class Mob extends LivingEntity {
|
||||
this.persistence_required = saved.persistence_required === true;
|
||||
this.can_pick_up_loot = saved.can_pick_up_loot === true;
|
||||
this.left_handed = saved.left_handed === true;
|
||||
this.client_data = is_object(saved.client_data) ? structuredClone(saved.client_data) : {};
|
||||
if (Array.isArray(saved.home_pos) && typeof saved.home_radius === "number") {
|
||||
const [x, y, z] = saved.home_pos.map((n) => finite(n, 0));
|
||||
this.restrict_to(x, y, z, saved.home_radius);
|
||||
|
||||
@@ -750,6 +750,12 @@ export class ModRuntime {
|
||||
mob.level.entity_event(mob, "swing");
|
||||
mob.do_hurt_target(entity);
|
||||
},
|
||||
get_client_data: (field) => structuredClone(mob.client_data[field]) as never,
|
||||
set_client_data(field, value) {
|
||||
if (typeof field !== "string" || field === "") throw new Error("a client data field needs a name");
|
||||
const { [field]: _, ...rest } = mob.client_data;
|
||||
mob.client_data = value === undefined ? rest : { ...rest, [field]: structuredClone(value) };
|
||||
},
|
||||
};
|
||||
return Object.defineProperties(living_ref(mob), Object.getOwnPropertyDescriptors(extra)) as MobRef;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,11 @@ 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";
|
||||
import { type AnimatedEntity, AnimationState, type Clip, type EntityAnimator } from "@/common/mod_api/client.ts";
|
||||
import { animation_for, type AnimatorSource, entity_animators } from "@/client/rendering/entity_animators.ts";
|
||||
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import type { EntityData } from "@/common/protocol.ts";
|
||||
import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts";
|
||||
|
||||
// the one clip a file with one animation reads into
|
||||
function one_clip(animation: unknown): ClipJson {
|
||||
@@ -195,3 +200,143 @@ Deno.test("a clip moves bones in the model's pixels, and scales them around thei
|
||||
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]));
|
||||
});
|
||||
|
||||
Deno.test("an animation state counts seconds from when it started, and knows when a clip has played through", () => {
|
||||
const once: Clip = { id: "a:b/once", length: 1, loop: false };
|
||||
const state = new AnimationState();
|
||||
assertEquals([state.started, state.seconds(100), state.finished(once, 100)], [false, 0, false]);
|
||||
state.animate_when(true, 10);
|
||||
state.animate_when(true, 15);
|
||||
assertEquals(state.seconds(20), 0.5);
|
||||
assert(!state.finished(once, 29));
|
||||
assert(state.finished(once, 30));
|
||||
assert(!state.finished({ ...once, loop: true }, 300));
|
||||
state.animate_when(false, 40);
|
||||
assertEquals(state.started, false);
|
||||
state.start_if_stopped(50);
|
||||
state.start_if_stopped(60);
|
||||
assertEquals(state.seconds(70), 1);
|
||||
});
|
||||
|
||||
// an entity the way an animator sees it, standing still and looking ahead
|
||||
function animated(type: string, data: EntityData = {}): AnimatorSource & { data: EntityData } {
|
||||
return {
|
||||
id: "e1",
|
||||
type,
|
||||
data,
|
||||
age: 0,
|
||||
yaw: 0,
|
||||
head_yaw: 0,
|
||||
pitch: 0,
|
||||
walk_animation: () => ({ position: 0, speed: 0 }),
|
||||
attack_animation: () => 0,
|
||||
};
|
||||
}
|
||||
|
||||
// registers an animator for a new entity type, and a clip turning the arm up to 90 degrees over a second
|
||||
function animator_type(name: string, create: (entity: AnimatedEntity) => EntityAnimator) {
|
||||
const type = `test:${name}`;
|
||||
entity_animators.set(type, { mod: "test", create });
|
||||
const clip_id = `test:${name}/raise`;
|
||||
if (!EverythingRegistry.get("animations", clip_id)) {
|
||||
EverythingRegistry.register<ClipJson>("animations", clip_id, {
|
||||
id: clip_id,
|
||||
length: 1,
|
||||
loop: false,
|
||||
bones: { arm: { rotation: [key(0, [0, 0, 0]), key(1, [90, 0, 0])] } },
|
||||
});
|
||||
}
|
||||
return { type, raise: { id: clip_id, length: 1, loop: false } };
|
||||
}
|
||||
|
||||
Deno.test("an animator hears about each client data field as it changes, and the ones there from the start", () => {
|
||||
const heard: string[] = [];
|
||||
const { type } = animator_type("listener", () => ({ pose() {}, on_data: (field) => heard.push(field) }));
|
||||
const entity = animated(type, { client_data: { mood: 1 }, glowing: true });
|
||||
const animation = animation_for(entity)!;
|
||||
assertEquals(heard, ["mood"]);
|
||||
|
||||
const before = entity.data;
|
||||
entity.data = { client_data: { mood: 1, state: 2 } };
|
||||
animation.data_changed(before);
|
||||
assertEquals(heard, ["mood", "state"]);
|
||||
const again = entity.data;
|
||||
entity.data = { client_data: { state: 3 } };
|
||||
animation.data_changed(again);
|
||||
assertEquals(heard, ["mood", "state", "mood", "state"]);
|
||||
assertEquals(animation_for(animated("test:no_animator")), undefined);
|
||||
});
|
||||
|
||||
Deno.test("an animator's pose plays clips and moves bones", () => {
|
||||
const { type, raise } = animator_type("poser", () => ({
|
||||
pose(pose, time) {
|
||||
pose.play(raise, time / 20, 0.5);
|
||||
pose.move("arm", 1, 2, 3);
|
||||
pose.scale("leg", 2, 2, 2);
|
||||
pose.look("head");
|
||||
},
|
||||
}));
|
||||
const entity = { ...animated(type), head_yaw: Math.PI / 2, pitch: -Math.PI / 4 };
|
||||
const offsets = animation_for(entity)!.pose(10)!;
|
||||
assertEquals(offsets.get("arm"), { rotation: [22.5, 0, 0], position: [1, 2, 3], scale: [1, 1, 1] });
|
||||
assertEquals(offsets.get("leg")!.scale, [2, 2, 2]);
|
||||
// mirrored like a model's own rotations
|
||||
const head = offsets.get("head")!.rotation;
|
||||
assertAlmostEquals(head[0], 45);
|
||||
assertAlmostEquals(head[1], -90);
|
||||
});
|
||||
|
||||
Deno.test("a clip plays from when its state started, and with walking as strongly as it walks", () => {
|
||||
const state = new AnimationState();
|
||||
state.start(10);
|
||||
const { type, raise } = animator_type("stateful", (entity) => ({
|
||||
pose(pose, time) {
|
||||
pose.play_state(raise, state, time);
|
||||
pose.play_walk(raise, entity, time);
|
||||
},
|
||||
}));
|
||||
// half a second of clip walked, at half speed
|
||||
const animation = animation_for({ ...animated(type), walk_animation: () => ({ position: 10, speed: 0.5 }) })!;
|
||||
// a quarter of a second into the state is 22.5 degrees, and walking half of 45
|
||||
assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5 + 22.5);
|
||||
state.stop();
|
||||
assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5);
|
||||
});
|
||||
|
||||
Deno.test("an animator that throws is removed, and the entity is posed without it", async () => {
|
||||
const { type } = animator_type("thrower", () => ({
|
||||
pose(pose) {
|
||||
pose.play({ id: "test:nowhere/nothing", length: 1, loop: false }, 0);
|
||||
},
|
||||
}));
|
||||
const animation = animation_for(animated(type))!;
|
||||
const errors = await errors_during(() => assertEquals(animation.pose(0), undefined));
|
||||
assertEquals(errors.length, 1);
|
||||
assertStringIncludes(errors[0], "[test] the animator of test:thrower e1 threw in pose");
|
||||
assertStringIncludes(errors[0], "test:nowhere/nothing isn't a clip");
|
||||
assertEquals(animation.pose(1), undefined);
|
||||
});
|
||||
|
||||
Deno.test("a mob's client data goes to the players who see it, and is saved with it", async () => {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_client_data_" });
|
||||
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
|
||||
const t = await test_game(dir);
|
||||
t.join(1, "alice");
|
||||
const mob = test_mob(t.game, {}, 0.5, 100, 0.5);
|
||||
const ref = t.game.mods.mob(mob);
|
||||
t.game.tick();
|
||||
t.take(1);
|
||||
|
||||
ref.set_client_data("state", { mood: 3 });
|
||||
assertEquals(ref.get_client_data("state"), { mood: 3 });
|
||||
t.game.tick();
|
||||
const sent = t.take(1).find((m) => m.type === "entity_data" && m.id === mob.id);
|
||||
assertEquals(sent && "data" in sent ? sent.data.client_data : undefined, { state: { mood: 3 } });
|
||||
|
||||
const copy = test_mob(t.game, {}, 2.5, 100, 0.5);
|
||||
copy.load(mob.save());
|
||||
assertEquals(t.game.mods.mob(copy).get_client_data("state"), { mood: 3 });
|
||||
ref.set_client_data("state", undefined);
|
||||
assertEquals(mob.synced_data().client_data, undefined);
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
@@ -9,7 +9,8 @@ import { ItemStack } from "@/common/inventory.ts";
|
||||
import { get_state_value, set_state_value } from "@/common/utils.ts";
|
||||
import { create_entity } from "@/server/game/entity/entity_types.ts";
|
||||
import type { Mob } from "@/server/game/entity/mob.ts";
|
||||
import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts";
|
||||
import { copy_dir, errors_during, load_as_player, test_game, test_mob } from "./helpers.ts";
|
||||
import { animation_for } from "@/client/rendering/entity_animators.ts";
|
||||
|
||||
const HALF = "dangerous_business:concrete_wall_slab";
|
||||
const CONNECTS = "dangerous_business:floor_grate";
|
||||
@@ -138,15 +139,18 @@ function spawn_coilhead(t: Awaited<ReturnType<typeof setup>>["t"]) {
|
||||
|
||||
Deno.test("a coilhead can't move while a player looks at it, and comes for them once they look away", async () => {
|
||||
const { t } = await setup();
|
||||
const coilhead = spawn_coilhead(t);
|
||||
const coilhead = spawn_coilhead(t) as Mob;
|
||||
for (let i = 0; i < 100; i++) t.game.tick();
|
||||
assertAlmostEquals(coilhead.x, 0.5, 1e-6);
|
||||
assertAlmostEquals(coilhead.z, -2.5, 1e-6);
|
||||
// what its animator reads
|
||||
assertEquals(coilhead.client_data.frozen, true);
|
||||
|
||||
// looking south, with it behind her
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: Math.PI, pitch: 0 });
|
||||
for (let i = 0; i < 100; i++) t.game.tick();
|
||||
assert(coilhead.z > 0, `it only got to z ${coilhead.z}`);
|
||||
assertEquals(coilhead.client_data.frozen, undefined);
|
||||
});
|
||||
|
||||
Deno.test("a player can't stop a coilhead through a wall", async () => {
|
||||
@@ -251,3 +255,27 @@ Deno.test("a coilhead seen while it waits at a closed door stops waiting, and do
|
||||
assert(!open(), "it opened the door while it was seen");
|
||||
assertEquals(coilhead.navigation.blocked_by, undefined);
|
||||
});
|
||||
|
||||
// last, since it loads the mod the way a player gets it, in place of the server's
|
||||
Deno.test("a coilhead's head springs back and forth when it freezes, and stays still when it stands", async () => {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "dangerous_business_client_" });
|
||||
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
|
||||
await load_as_player(dir);
|
||||
const coilhead = (frozen: boolean) => ({
|
||||
id: "e1",
|
||||
type: COILHEAD,
|
||||
data: frozen ? { client_data: { frozen: true } } : {},
|
||||
age: 0,
|
||||
yaw: 0,
|
||||
head_yaw: 0,
|
||||
pitch: 0,
|
||||
walk_animation: () => ({ position: 0, speed: 0 }),
|
||||
attack_animation: () => 0,
|
||||
});
|
||||
const head = (frozen: boolean, time: number) => animation_for(coilhead(frozen))!.pose(time)!.get("head")?.rotation;
|
||||
assertNotEquals(head(true, 5), [0, 0, 0]);
|
||||
assertEquals(head(false, 5), [0, 0, 0]);
|
||||
// it's over in under a minute
|
||||
assertEquals(head(true, 1200), head(false, 1200));
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
validate_entity,
|
||||
} from "@/common/mod_data.ts";
|
||||
import type { Texture } from "@/client/renderer/mod.ts";
|
||||
import { IDENTITY } from "@/client/rendering/model_math.ts";
|
||||
import { bone_matrices, IDENTITY } from "@/client/rendering/model_math.ts";
|
||||
import { push_model } from "@/client/rendering/model_renderer.ts";
|
||||
import { Mob } from "@/server/game/entity/mob.ts";
|
||||
import { create_entity } from "@/server/game/entity/entity_types.ts";
|
||||
@@ -54,7 +54,13 @@ function model_vertices(model: EntityModelJson, only?: (bone: EntityBoneJson) =>
|
||||
const out: number[][] = [];
|
||||
const atlas = { width: model.texture_width, height: model.texture_height } as Texture;
|
||||
const region = { x: 0, y: 0, width: model.texture_width, height: model.texture_height };
|
||||
push_model(model, () => IDENTITY, atlas, region, (x, y, z) => [x, y, z], undefined, only, (x, y, z, u, v) => {
|
||||
push_model(model, bone_matrices(model, () => IDENTITY), atlas, region, (x, y, z) => [x, y, z], undefined, only, (
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
u,
|
||||
v,
|
||||
) => {
|
||||
out.push([x, y, z, u * model.texture_width, v * model.texture_height]);
|
||||
});
|
||||
return out;
|
||||
@@ -114,9 +120,18 @@ Deno.test("a cube's rotation turns it around its pivot like the same rotation on
|
||||
const atlas = { width: 16, height: 16 } as Texture;
|
||||
const region = { x: 0, y: 0, width: 16, height: 16 };
|
||||
const only = (bone: EntityBoneJson) => bone.name === name;
|
||||
push_model(model!, () => IDENTITY, atlas, region, (x, y, z) => [x, y, z], undefined, only, (x, y, z) => {
|
||||
out.push(x, y, z);
|
||||
});
|
||||
push_model(
|
||||
model!,
|
||||
bone_matrices(model!, () => IDENTITY),
|
||||
atlas,
|
||||
region,
|
||||
(x, y, z) => [x, y, z],
|
||||
undefined,
|
||||
only,
|
||||
(x, y, z) => {
|
||||
out.push(x, y, z);
|
||||
},
|
||||
);
|
||||
return out;
|
||||
};
|
||||
const turned = points("turned_cube");
|
||||
|
||||
Reference in New Issue
Block a user