Player skins !

This commit is contained in:
2026-09-27 12:01:52 -03:00
parent edf4b72dc4
commit 60188ff735
14 changed files with 325 additions and 8 deletions
+18
View File
@@ -1,9 +1,14 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import type { ClientLevel } from "../level/client_level.ts";
import type { Texture } from "../renderer/mod.ts";
import { decode_skin } from "../skins.ts";
import { Entity } from "./entity.ts";
export abstract class Player extends Entity {
name: string;
// undefined draws the default skin
skin: Texture | undefined;
#skin_version = 0;
// how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState
walk_position = 0;
@@ -15,6 +20,19 @@ export abstract class Player extends Entity {
this.name = name;
}
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
async set_skin(skin: string | undefined) {
const version = ++this.#skin_version;
const texture = skin ? await decode_skin(skin) : undefined;
if (version !== this.#skin_version) {
// a newer skin came while this one was decoding
texture?.tex.destroy();
return;
}
this.skin?.tex.destroy();
this.skin = texture;
}
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
update_walk_animation() {
const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
+3
View File
@@ -20,6 +20,9 @@ export class RemotePlayer extends Player {
this.target_z = info.z;
this.yaw = info.yaw;
this.pitch = info.pitch;
if (info.skin) {
this.set_skin(info.skin);
}
}
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) {
+8
View File
@@ -5,6 +5,7 @@ import { GuiContainer } from "./gui/gui_container.ts";
import { GuiChat } from "./gui/gui_chat.ts";
import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
import { Player } from "./entity/player.ts";
// applies what the server sends, like minecraft's ClientPacketListener. messages queue up on the connection and
// get handled here once per frame, inside the game loop
@@ -50,6 +51,13 @@ export class ClientPacketListener {
}
break;
}
case "player_skin": {
const player = level.entities.get(message.id);
if (player instanceof Player) {
player.set_skin(message.skin);
}
break;
}
case "add_entity":
level.add_entity(new ItemEntity(level, message.entity));
break;
+7 -3
View File
@@ -12,6 +12,7 @@ import { render_player } from "./player_renderer.ts";
import {
draw_terrain,
flush_batch,
get_current_texture,
push_back_face,
push_bottom_face,
push_front_face,
@@ -94,11 +95,14 @@ export class LevelRenderer {
// every entity but the one the camera is in
render_entities(level: ClientLevel, camera_entity: Entity, partial_tick: number) {
flush_batch();
const skin = AssetManager.instance.get<Texture>("bworld:skin");
set_current_texture(skin.tex);
const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
for (const entity of level.entities.values()) {
if (entity !== camera_entity && entity instanceof RemotePlayer) {
const skin = entity.skin ?? default_skin;
if (get_current_texture() !== skin.tex) {
flush_batch();
set_current_texture(skin.tex);
}
render_player(entity, skin, partial_tick);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { load_texture, type Texture } from "./renderer/mod.ts";
// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded
export async function decode_skin(skin: string): Promise<Texture | undefined> {
try {
const bytes = Uint8Array.from(atob(skin), (char) => char.charCodeAt(0));
// as stored, so pngs with a color profile look the same as in an editor that ignores it, like minecraft
const image = await createImageBitmap(new Blob([bytes], { type: "image/png" }), {
colorSpaceConversion: "none",
premultiplyAlpha: "none",
});
const texture = image.width === 64 && image.height === 64 ? load_texture(image) : undefined;
image.close();
return texture;
} catch {
return undefined;
}
}
+5 -1
View File
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 6;
export const PROTOCOL_VERSION = 7;
export interface PlayerInfo {
id: string;
@@ -17,6 +17,8 @@ export interface PlayerInfo {
z: number;
yaw: number;
pitch: number;
// a 64x64 png as base64, see /skin. the default skin when there isn't one
skin?: string;
}
// an entity that isn't a player, as the server first sends it. players have their own messages
@@ -108,6 +110,8 @@ export type ServerMessage =
| { type: "player_join"; player: PlayerInfo }
| { type: "player_leave"; id: string }
| { type: "player_move"; id: string; x: number; y: number; z: number; yaw: number; pitch: number }
// a player changed their skin, including the one receiving it. without skin it's back to the default
| { type: "player_skin"; id: string; skin?: string }
| { type: "add_entity"; entity: EntityInfo }
| { type: "move_entity"; id: string; x: number; y: number; z: number }
// a dropped item's stack changed, like when two stacks merge
+53
View File
@@ -43,6 +43,7 @@ import {
import type { GameLoop } from "./game_loop.ts";
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { ServerWorld, Tile } from "./world.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
@@ -86,6 +87,8 @@ const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND;
export interface GameHost {
send(conn: number, data: string): void;
close(conn: number): void;
// fetches a url, failing with a message for players when it can't or it's more than max_bytes
download(url: string, max_bytes: number): Promise<Uint8Array>;
}
export interface SavedWorld {
@@ -1017,6 +1020,21 @@ export class GameServer {
}),
);
register(
literal<ServerCommandSource>("skin")
.describe("Changes your skin to a 64x64 png from the web, or back to the default without a url")
.executes((context) => {
this.set_skin(context.source.server_player, undefined);
context.source.send_message("Your skin is back to the default");
})
.then(
argument<string, ServerCommandSource>("url", word())
.executes((context) =>
this.#download_skin(context.source.server_player, context.get<string>("url"))
),
),
);
// every command's usage, or one's. aliases like /mod:name aren't listed twice
const commands = this.mods.commands;
const help = (context: CommandContext<ServerCommandSource>, only?: string) => {
@@ -1045,6 +1063,41 @@ export class GameServer {
);
}
// a base64 png, or undefined for the default skin. everyone is told, the player too
set_skin(player: ServerPlayer, skin: string | undefined) {
player.skin = skin;
this.world.dirty = true;
this.#broadcast({ type: "player_skin", id: player.id, skin });
}
// the host downloads it, which takes a while, so the player hears back later
#download_skin(player: ServerPlayer, url: string) {
if (player.downloading_skin) {
throw new CommandError("Your last skin is still downloading");
}
player.downloading_skin = true;
this.send_chat(player, "Downloading your skin...");
const online = () => this.#players.get(player.conn) === player;
this.#host.download(url, MAX_SKIN_BYTES)
.then((bytes) => {
const problem = skin_problem(bytes);
if (problem) {
throw new Error(problem);
}
if (online()) {
this.set_skin(player, encode_skin(bytes));
this.send_chat(player, "Skin changed");
}
})
.catch((e) => {
if (online()) {
this.send_chat(player, `Couldn't change your skin: ${e instanceof Error ? e.message : e}`);
}
})
.finally(() => player.downloading_skin = false);
}
#close_screen(player: ServerPlayer) {
const screen = player.screen;
player.screen = undefined;
+6 -2
View File
@@ -14,11 +14,15 @@ export type HostToGame =
| { type: "message"; conn: number; data: string }
| { type: "disconnect"; conn: number }
// save now and say when it's done, for shutting down
| { type: "shutdown" };
| { type: "shutdown" }
// answers download, with the bytes or why it failed
| { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string };
export type GameToHost =
| { type: "ready"; seed: string }
| { type: "failed"; error: string }
| { type: "send"; conn: number; data: string }
| { type: "close"; conn: number }
| { type: "save"; data: string; final: boolean };
| { type: "save"; data: string; final: boolean }
// the worker can't use the network, so the host fetches urls for it, like skins
| { type: "download"; id: number; url: string; max_bytes: number };
+18 -1
View File
@@ -29,6 +29,8 @@ export interface SavedPlayer {
inventory: (ItemData | null)[];
// players saved before health and hunger start full
vitals?: SavedVitals;
// base64 png, see /skin
skin?: string;
}
export class ServerPlayer {
@@ -52,6 +54,10 @@ export class ServerPlayer {
cursor: Cursor = { item: undefined };
selected_slot = 0;
screen: OpenScreen | undefined;
// base64 png, see /skin. undefined is the default skin
skin: string | undefined;
// a /skin download is on its way, one at a time
downloading_skin = false;
// last json sent for each synced thing, so only changes get sent
sent = new Map<string, string>();
@@ -66,7 +72,16 @@ export class ServerPlayer {
}
info(): PlayerInfo {
return { id: this.id, name: this.name, x: this.x, y: this.y, z: this.z, yaw: this.yaw, pitch: this.pitch };
return {
id: this.id,
name: this.name,
x: this.x,
y: this.y,
z: this.z,
yaw: this.yaw,
pitch: this.pitch,
skin: this.skin,
};
}
save(): SavedPlayer {
@@ -79,6 +94,7 @@ export class ServerPlayer {
selected_slot: this.selected_slot,
inventory: this.inventory.to_data(),
vitals: this.vitals.save(),
skin: this.skin,
};
}
@@ -91,5 +107,6 @@ export class ServerPlayer {
this.selected_slot = saved.selected_slot;
this.inventory.load(saved.inventory);
this.vitals.load(saved.vitals);
this.skin = saved.skin;
}
}
+32
View File
@@ -0,0 +1,32 @@
// player skins set with /skin: 64x64 pngs in minecraft 1.8's layout, see client/rendering/player_renderer.ts
// minecraft skins are a few KB, this leaves room for ones with extra metadata
export const MAX_SKIN_BYTES = 64 * 1024;
export const SKIN_SIZE = 64;
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
// why the bytes can't be a skin, for the player. only the header is checked, clients decode the rest and fall back
// to the default skin if they can't
export function skin_problem(bytes: Uint8Array): string | undefined {
const is_png = bytes.length >= 24 && PNG_SIGNATURE.every((byte, i) => bytes[i] === byte) &&
String.fromCharCode(...bytes.subarray(12, 16)) === "IHDR";
if (!is_png) {
return "That isn't a png";
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const width = view.getUint32(16);
const height = view.getUint32(20);
if (width !== SKIN_SIZE || height !== SKIN_SIZE) {
return `Skins have to be ${SKIN_SIZE}x${SKIN_SIZE} (it's ${width}x${height})`;
}
return undefined;
}
export function encode_skin(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
+19
View File
@@ -10,6 +10,9 @@ const SAVE_INTERVAL_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// downloads waiting for the host, by id
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject: (error: Error) => void }>();
let next_download = 1;
function post(message: GameToHost) {
self.postMessage(message);
@@ -22,6 +25,16 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
starting = init(message);
return;
}
if (message.type === "downloaded") {
const pending = downloads.get(message.id);
downloads.delete(message.id);
if (message.bytes) {
pending?.resolve(message.bytes);
} else {
pending?.reject(new Error(message.error ?? "Couldn't download it"));
}
return;
}
// players can connect while mods are still loading
await starting;
@@ -51,6 +64,12 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
{
send: (conn, data) => post({ type: "send", conn, data }),
close: (conn) => post({ type: "close", conn }),
download: (url, max_bytes) =>
new Promise((resolve, reject) => {
const id = next_download++;
downloads.set(id, { resolve, reject });
post({ type: "download", id, url, max_bytes });
}),
},
message.save,
message.default_seed,
+62
View File
@@ -9,6 +9,7 @@ const MAX_MESSAGE_SIZE = 4096;
// in build/, see build.ts
export const ENGINE_TEXTURES_INDEX = "assets/textures/index.json";
const SHUTDOWN_TIMEOUT_MS = 5000;
const DOWNLOAD_TIMEOUT_MS = 10_000;
export interface HostOptions {
// what deno task build made: the client and the engine's assets
@@ -70,6 +71,13 @@ export async function start_host(options: HostOptions): Promise<Host> {
on_final_save?.();
}
break;
case "download":
download(message.url, message.max_bytes).then(
(bytes) => post({ type: "downloaded", id: message.id, bytes }),
(e) =>
post({ type: "downloaded", id: message.id, error: e instanceof Error ? e.message : String(e) }),
);
break;
}
};
game.onerror = (event) => {
@@ -157,6 +165,60 @@ export async function start_host(options: HostOptions): Promise<Host> {
};
}
// for the game worker, which has no network access. errors are told to players, so they say what went wrong simply
async function download(url: string, max_bytes: number): Promise<Uint8Array> {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error("That isn't a url");
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("Only http and https urls work");
}
let response: Response;
try {
response = await fetch(parsed, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
} catch {
throw new Error("Couldn't download it");
}
if (!response.ok || !response.body) {
await response.body?.cancel();
throw new Error(`Couldn't download it (${response.status})`);
}
// read up to the limit instead of trusting content-length
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
while (true) {
let chunk: ReadableStreamReadResult<Uint8Array>;
try {
chunk = await reader.read();
} catch {
throw new Error("Couldn't download it");
}
if (chunk.done) {
break;
}
size += chunk.value.length;
if (size > max_bytes) {
await reader.cancel();
throw new Error(`It's bigger than ${Math.floor(max_bytes / 1024)} KB`);
}
chunks.push(chunk.value);
}
const bytes = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
return bytes;
}
function read_world(file: string): string | undefined {
try {
return Deno.readTextFileSync(file);
+7 -1
View File
@@ -41,6 +41,8 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se
EverythingRegistry.clear();
const outbox = new Map<number, unknown[]>();
const closed = new Set<number>();
// what host.download gives back, by url. other urls fail
const downloads = new Map<string, Uint8Array>();
const host = {
send: (conn: number, data: string) => {
if (!outbox.has(conn)) outbox.set(conn, []);
@@ -49,6 +51,10 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se
close(conn: number) {
closed.add(conn);
},
download(url: string) {
const bytes = downloads.get(url);
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it"));
},
};
const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir));
// deno-lint-ignore no-explicit-any
@@ -65,7 +71,7 @@ export async function test_game(mods_dir: string, save?: string, seed = "test-se
send(conn, { type: "ready" });
return take(conn).find((m) => m.type === "join");
};
return { game, take, send, join, closed };
return { game, take, send, join, closed, downloads };
}
export function copy_dir(from: string, to: string) {
+69
View File
@@ -0,0 +1,69 @@
import { assertEquals } from "@std/assert";
import { encode_skin } from "$/server/game/skins.ts";
import { test_game } from "./helpers.ts";
const SKIN = Deno.readFileSync("assets/sprites/skin_template.png");
// the downloads resolve on a later turn of the event loop
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
// deno-lint-ignore no-explicit-any
const chat = (messages: any[]) => messages.filter((m) => m.type === "chat").map((m) => m.text);
Deno.test("/skin downloads a png, tells everyone and is saved with the player", async () => {
const t = await test_game("mods");
t.downloads.set("https://example.com/skin.png", SKIN);
t.join(1, "alice");
t.join(2, "bob");
t.take(1);
t.take(2);
t.send(1, { type: "chat", text: "/skin https://example.com/skin.png" });
await settle();
const skin = encode_skin(SKIN);
const alice_id = t.game.players().find((p) => p.name === "alice")!.id;
const to_alice = t.take(1);
assertEquals(chat(to_alice), ["Downloading your skin...", "Skin changed"]);
assertEquals(to_alice.find((m) => m.type === "player_skin"), { type: "player_skin", id: alice_id, skin });
assertEquals(t.take(2).find((m) => m.type === "player_skin"), { type: "player_skin", id: alice_id, skin });
// players joining later get it with the rest of alice's info, and it's still there after a restart
const loaded = await test_game("mods", t.game.save());
loaded.join(1, "alice");
const join = loaded.join(2, "bob");
assertEquals(join.players.find((p: { name: string }) => p.name === "alice").skin, skin);
});
Deno.test("/skin says why a download can't be a skin, and /skin alone goes back to the default", async () => {
const t = await test_game("mods");
const wide = SKIN.slice();
new DataView(wide.buffer).setUint32(20, 32);
t.downloads.set("https://example.com/old.png", wide);
t.downloads.set("https://example.com/page.html", new TextEncoder().encode("<html></html>"));
t.join(1, "alice");
t.take(1);
const skin_messages = async (text: string) => {
t.send(1, { type: "chat", text });
await settle();
const messages = t.take(1);
return { chat: chat(messages), skins: messages.filter((m) => m.type === "player_skin") };
};
assertEquals((await skin_messages("/skin https://example.com/old.png")).chat, [
"Downloading your skin...",
"Couldn't change your skin: Skins have to be 64x64 (it's 64x32)",
]);
assertEquals(
(await skin_messages("/skin https://example.com/page.html")).chat.at(-1),
"Couldn't change your skin: That isn't a png",
);
const missing = await skin_messages("/skin https://example.com/nothing.png");
assertEquals(missing.chat.at(-1), "Couldn't change your skin: Couldn't download it");
assertEquals(missing.skins, []);
const reset = await skin_messages("/skin");
assertEquals(reset.chat, ["Your skin is back to the default"]);
assertEquals(reset.skins.length, 1);
assertEquals(reset.skins[0].skin, undefined);
});