Animated textures !

This commit is contained in:
2026-10-07 19:11:44 -03:00
parent b6b10e35e2
commit fbc9266936
20 changed files with 555 additions and 25 deletions
+36 -5
View File
@@ -2,6 +2,8 @@
// from the textures in the server's .bmod files
import { TEXTURE_SIZE } from "$/common/constants.ts";
import type { SpriteRegion } from "$/common/constants.ts";
import { type Animation, texture_animation, type TextureJson } from "$/common/texture_animation.ts";
import { AnimatedTexture } from "./texture_animations.ts";
export interface AtlasLayout {
// in pixels, a power of two
@@ -51,8 +53,10 @@ function pack_shelves(entries: [string, TextureSize][], size: number) {
return y + shelf <= size ? regions : undefined;
}
// textures are png bytes by id. ones that don't decode show as missing
export async function build_atlas(textures: Map<string, Uint8Array>) {
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
// texture_animations.ts)
export async function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
const images = new Map<string, ImageBitmap>();
await Promise.all([...textures].map(async ([id, png]) => {
try {
@@ -64,7 +68,18 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
images.get("engine:missing")?.close();
images.delete("engine:missing");
const { size, regions } = atlas_layout(new Map([...images].map(([id, image]) => [id, image])));
const animations = new Map<string, Animation>();
for (const [id, image] of images) {
const json = texture_json.get(id);
const animation = json && texture_animation(json, image);
if (animation) animations.set(id, animation);
}
const sizes = new Map([...images].map(([id, image]) => {
const animation = animations.get(id);
return [id, animation ? { width: animation.frame_width, height: animation.frame_height } : image];
}));
const { size, regions } = atlas_layout(sizes);
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext("2d")!;
@@ -78,8 +93,17 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
ctx.fillRect(missing.x + half, missing.y, half, half);
ctx.fillRect(missing.x, missing.y + half, half, half);
const animated: AnimatedTexture[] = [];
for (const [id, image] of images) {
ctx.drawImage(image, regions[id].x, regions[id].y);
const animation = animations.get(id);
const { x, y, width, height } = regions[id];
if (animation) {
const first = animation.frames[0];
ctx.drawImage(image, first.x, first.y, width, height, x, y, width, height);
animated.push(new AnimatedTexture(regions[id], animation, image_pixels(image), image.width));
} else {
ctx.drawImage(image, x, y);
}
image.close();
}
for (const id of textures.keys()) {
@@ -100,7 +124,14 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
opaque.set(id, { width: region.width, height: region.height, mask });
}
return { image: canvas.transferToImageBitmap(), regions };
return { image: canvas.transferToImageBitmap(), regions, animated };
}
// every frame of an animated texture stays in memory, to copy into the atlas when it's that frame's turn
function image_pixels(image: ImageBitmap) {
const ctx = new OffscreenCanvas(image.width, image.height).getContext("2d")!;
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height).data;
}
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
+2
View File
@@ -24,6 +24,7 @@ import { Container } from "$/common/inventory.ts";
import { PLAYER_MENU } from "$/common/protocol.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityJson } from "$/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
// how far from the eyes entities can be hit, like minecraft
const ENTITY_REACH = 3;
@@ -194,6 +195,7 @@ export class Client {
this.connection.send({ type: "view_distance", distance: view_distance });
}
this.level.tick();
tick_texture_animations();
}
// closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a
+9 -2
View File
@@ -6,11 +6,14 @@ import { Options } from "./options.ts";
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts";
import { build_atlas, engine_textures } from "./atlas.ts";
import { confirm_mods } from "./confirm_mods.ts";
import { set_texture_animations } from "./texture_animations.ts";
import type { TextureJson } from "$/common/texture_animation.ts";
import { ModLoadError } from "$/common/mod_loader.ts";
import {
begin_drawing,
canvas,
clear_background,
device,
end_drawing,
init_font,
init_window,
@@ -136,12 +139,16 @@ async function join_server(address: ServerAddress, name: string, status: (text:
status("Downloading the server's mods...");
const bmods = await download_mods(welcome.mods, address.base);
const textures = await engine_textures();
const texture_json = new Map<string, TextureJson>();
for (const bmod of bmods) {
for (const [id, png] of bmod.textures) textures.set(id, png);
for (const [id, json] of bmod.texture_json ?? []) texture_json.set(id, json);
}
const atlas = await build_atlas(textures);
const atlas = await build_atlas(textures, texture_json);
loaded_mods = true;
AssetManager.instance.assets["bworld:textures"] = load_texture(atlas.image);
const atlas_texture = load_texture(atlas.image);
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
AssetManager.instance.assets["bworld:textures"] = atlas_texture;
AssetManager.instance.assets["bworld:textures_info"] = atlas.regions;
await load_client_mods(welcome.mods, bmods);
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
+101
View File
@@ -0,0 +1,101 @@
// animated textures play like minecraft's: the atlas holds one frame of each, and every tick the ones whose frame
// changed copy the new frame's pixels over it. models never change, only the atlas does
import type { SpriteRegion } from "$/common/constants.ts";
import type { Animation } from "$/common/texture_animation.ts";
// pixels to copy into a texture's place in the atlas: frame_width × frame_height of them, starting at offset bytes
// into data, rows bytes_per_row apart
export interface FrameUpload {
data: Uint8ClampedArray<ArrayBuffer>;
offset: number;
bytes_per_row: number;
}
export class AnimatedTexture {
// which of animation.frames shows, and how many ticks it has shown for
#frame = 0;
#ticks = 0;
// the frame blended into the next one, for animations that interpolate
readonly #blended: Uint8ClampedArray<ArrayBuffer>;
// pixels is the whole png, rgba row by row, image_width pixels wide
constructor(
readonly region: SpriteRegion,
readonly animation: Animation,
readonly pixels: Uint8ClampedArray<ArrayBuffer>,
readonly image_width: number,
) {
this.#blended = new Uint8ClampedArray(animation.frame_width * animation.frame_height * 4);
}
// one tick on, and what to copy into the atlas if the texture looks different now
tick(): FrameUpload | undefined {
const frames = this.animation.frames;
const current = frames[this.#frame];
this.#ticks += 1;
if (this.#ticks >= current.time) {
this.#ticks = 0;
this.#frame = (this.#frame + 1) % frames.length;
const next = frames[this.#frame];
if (next.x !== current.x || next.y !== current.y) return this.#frame_upload(next);
} else if (this.animation.interpolate) {
const next = frames[(this.#frame + 1) % frames.length];
if (next.x !== current.x || next.y !== current.y) {
return this.#blend(current, next, this.#ticks / current.time);
}
}
return undefined;
}
#frame_upload(frame: { x: number; y: number }): FrameUpload {
return {
data: this.pixels,
offset: (frame.y * this.image_width + frame.x) * 4,
bytes_per_row: this.image_width * 4,
};
}
// the colour moves from one frame to the next, the see-through-ness stays the current frame's, like minecraft
#blend(from: { x: number; y: number }, to: { x: number; y: number }, amount: number): FrameUpload {
const { frame_width, frame_height } = this.animation;
for (let y = 0; y < frame_height; y++) {
for (let x = 0; x < frame_width; x++) {
const a = ((from.y + y) * this.image_width + from.x + x) * 4;
const b = ((to.y + y) * this.image_width + to.x + x) * 4;
const out = (y * frame_width + x) * 4;
for (let c = 0; c < 3; c++) {
this.#blended[out + c] = this.pixels[a + c] + (this.pixels[b + c] - this.pixels[a + c]) * amount;
}
this.#blended[out + 3] = this.pixels[a + 3];
}
}
return { data: this.#blended, offset: 0, bytes_per_row: frame_width * 4 };
}
}
let atlas: GPUTexture | undefined;
let queue: GPUQueue | undefined;
let animated: AnimatedTexture[] = [];
// the atlas just made and its animated textures, replacing the last server's
export function set_texture_animations(texture: GPUTexture, gpu_queue: GPUQueue, textures: AnimatedTexture[]) {
atlas = texture;
queue = gpu_queue;
animated = textures;
}
// once a tick, like minecraft's TextureAtlas.cycleAnimationFrames
export function tick_texture_animations() {
if (!atlas || !queue) return;
for (const texture of animated) {
const upload = texture.tick();
if (!upload) continue;
const { region, animation } = texture;
queue.writeTexture(
{ texture: atlas, origin: [region.x, region.y] },
upload.data,
{ offset: upload.offset, bytesPerRow: upload.bytes_per_row },
[animation.frame_width, animation.frame_height],
);
}
}