feat: 100% self-hosted Habbo fonts via sprite sheets + client-side compositor

This commit is contained in:
openhands committed 2026-07-03 18:22:30 +02:00
1 parent 8a58bcb252
commit 77ae4838c0
353 files changed
+227 -143

No files matched your search

-93
View File
@@ -1,93 +0,0 @@
import { NextResponse } from "next/server";
import { mkdir, writeFile, readFile } from "fs/promises";
import { existsSync } from "fs";
import path from "path";
export const dynamic = "force-dynamic";
const CACHE_DIR = "public/assets/fonts/cache";
const VALID_STYLES = new Set([
"habbo_new","habbo_big","habbo_new_big","habbo_old_big","habbo",
"habbo_tiny","habbo_oldschool","habbo_blocky","habjoy","habjoy_light",
"paradise","paradise_rounded","habbnew","habbo_clicker","reception",
"accessoires","africa","alhambra","arctic","asian","asian_small",
"basic","base","bathroom","battlebanzai","bensalem","bensalem_sea",
"bling","bling_gold","bones","books","bots","bubble","bubble_blue",
"bubble_orange","bunny_run","bunny_run_blue","buttons","candy",
"collectibles","crystal","cubie","disco","dreams","dreams_flat",
"duckets","emo","exchange","executive","explore","explore_big",
"explore_small","faq","fbomb","festival","flags","fx","freehand",
"gaming","gallery","goldentemple","gravity","hma","gold_big",
"habbo_news","habbo_runway","habbid_red","habbid_blue","habbolife",
"habbowood","habbowood_big","hands","hello","horse","ice","iced",
"iron","japan","love","marketplace_red","monkey","mushroom",
"mushroom_green","neon_blue","neon_green","neon_pink","occasional",
"palooza","palooza_blue","pets","pillow_orange","pillow_pink","pipes",
"plants","plastic","recycle","retropixel","rugs","sale","shalimar",
"shalimar_big","shalimar_small","soccer","soccer_red","soccer_yellow",
"space","spaces","special_offers","straypixels","steampunk","scifi",
"summer","teleport","theater_lights","tribe","trophies","usva",
"unknown_blue","unknown_blue_2","unknown_metal","unknown_white",
"unknown_pillow_1","unknown_pillow_2","valentine","western","wood",
"yellow_text","jurrasic","halloween","halloween_2","halloween_3",
"plastic_playful","dinner_blue","dinner_green","dinner_red",
"battleball","lido","soccer_big","hc","hc_big","hc_small",
"hc_compact","hc_gold","habboclub","habboclub_banner","habbovip",
"habbovip_banner","agenda","mini_white","volter","volter_shadow",
"volter_modern","volter_modern_small","black","windows",
"windows_lowercase","windows_jungle","windows_blue","windows_green",
"windows_pink","windows_red","windows_red_dark","windows_yellow",
"windows_purple","beta_big","beta_small","beta_small_old","beta",
"habboclub_complete","gift","habboclub_silver","love_full",
"marketplace_full","relax","habbo_ribbon",
]);
export async function GET(
_request: Request,
{ params }: { params: Promise<{ style: string; text: string }> },
) {
const { style, text } = await params;
if (!VALID_STYLES.has(style)) {
return new NextResponse("Invalid font style", { status: 400 });
}
const sanitized = text.replace(/[^a-z0-9+]/g, "");
if (!sanitized) {
return new NextResponse("Invalid text", { status: 400 });
}
const cacheFile = `${style}-${sanitized}.gif`;
const cachePath = path.join(process.cwd(), CACHE_DIR, cacheFile);
// Serve from cache if already fetched
if (existsSync(cachePath)) {
const bytes = await readFile(cachePath);
return new NextResponse(bytes, {
headers: {
"Content-Type": "image/gif",
"Cache-Control": "public, max-age=86400",
},
});
}
// Fetch from habbofont.net and cache
const upstream = `https://habbofont.net/font/${style}/${sanitized}.gif`;
const res = await fetch(upstream);
if (!res.ok) {
return new NextResponse("Font render error", { status: 502 });
}
const buffer = Buffer.from(await res.arrayBuffer());
await mkdir(path.dirname(cachePath), { recursive: true });
await writeFile(cachePath, buffer);
return new NextResponse(buffer, {
headers: {
"Content-Type": "image/gif",
"Cache-Control": "public, max-age=86400",
},
});
}
+81 -50
View File
@@ -1,20 +1,22 @@
"use client";
import { useCallback, useMemo, useState, useTransition } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from "react";
import { ContentCard } from "@/components/public/ui";
import { saveLogoFromUrl } from "@/actions/save-logo";
import { HABBO_FONT_GROUPS, buildFontUrl } from "@/components/public/habbo-fonts";
import { saveLogo } from "@/actions/save-logo";
import { HABBO_FONT_GROUPS } from "@/components/public/habbo-fonts";
import { getFontInfo, measureText, renderToCanvas } from "@/components/public/sprite-font";
export default function LogoGenerator() {
const [text, setText] = useState("Atom");
const [styleName, setStyleName] = useState("habbo");
const [search, setSearch] = useState("");
const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "done" | "error">("idle");
const [imgError, setImgError] = useState(false);
const [fontLoaded, setFontLoaded] = useState(false);
const [fontError, setFontError] = useState(false);
const [, startTransition] = useTransition();
const canvasRef = useRef<HTMLCanvasElement>(null);
const safeText = text.trim() || "Your hotel";
const gifUrl = useMemo(() => buildFontUrl(styleName, safeText), [styleName, safeText]);
const currentFont = useMemo(
() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts).find((f) => f.styleName === styleName),
@@ -36,26 +38,63 @@ export default function LogoGenerator() {
[search],
);
// Load font and render preview
useEffect(() => {
let cancelled = false;
setFontLoaded(false);
setFontError(false);
getFontInfo(styleName)
.then((info) => {
if (cancelled) return;
const canvas = renderToCanvas(info.chars, info.h, info.sheet, safeText, 12);
if (canvas && canvasRef.current) {
canvasRef.current.width = canvas.width;
canvasRef.current.height = canvas.height;
const ctx = canvasRef.current.getContext("2d");
ctx?.drawImage(canvas, 0, 0);
}
setFontLoaded(true);
})
.catch(() => {
if (!cancelled) setFontError(true);
});
return () => { cancelled = true; };
}, [styleName, safeText]);
const handleDownload = useCallback(() => {
window.open(gifUrl, "_blank");
}, [gifUrl]);
const canvas = canvasRef.current;
if (!canvas) return;
canvas.toBlob((blob) => {
if (!blob) return;
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `${safeText.replace(/[^a-z0-9]+/gi, "_") || "logo"}.png`;
a.click();
URL.revokeObjectURL(a.href);
}, "image/png");
}, [safeText]);
const handleSave = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas) return;
setSaveStatus("saving");
startTransition(async () => {
const result = await saveLogoFromUrl(
`${window.location.origin}${gifUrl}`,
);
setSaveStatus(result.success ? "done" : "error");
setTimeout(() => setSaveStatus("idle"), 3000);
});
}, [gifUrl, startTransition]);
canvas.toBlob((blob) => {
if (!blob) { setSaveStatus("error"); return; }
const file = new File([blob], "logo.png", { type: "image/png" });
const fd = new FormData();
fd.append("file", file);
startTransition(async () => {
const result = await saveLogo(fd);
setSaveStatus(result.success ? "done" : "error");
setTimeout(() => setSaveStatus("idle"), 3000);
});
}, "image/png");
}, [startTransition]);
const [zipping, setZipping] = useState(false);
const allFonts = useMemo(
() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts),
[],
);
const allFonts = useMemo(() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts), []);
const handleDownloadAll = useCallback(async () => {
if (zipping) return;
@@ -64,26 +103,26 @@ export default function LogoGenerator() {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const folder = zip.folder(safeText.replace(/[^a-z0-9]+/gi, "_") || "logo")!;
const results = await Promise.allSettled(
allFonts.map(async (font) => {
const url = buildFontUrl(font.styleName, safeText);
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const blob = await res.blob();
folder.file(`${font.styleName}.gif`, blob);
}),
);
let fail = 0;
for (const font of allFonts) {
try {
const info = await getFontInfo(font.styleName);
const canvas = renderToCanvas(info.chars, info.h, info.sheet, safeText, 12);
if (!canvas) { fail++; continue; }
const blob = await new Promise<Blob | null>((r) => canvas.toBlob((b) => r(b), "image/png"));
if (blob) folder.file(`${font.styleName}.png`, blob);
else fail++;
} catch { fail++; }
}
const failed = results.filter((r) => r.status === "rejected").length;
const content = await zip.generateAsync({ type: "blob" });
const a = document.createElement("a");
a.href = URL.createObjectURL(content);
a.download = `${safeText.replace(/[^a-z0-9]+/gi, "_") || "logo"}-all-fonts.zip`;
a.click();
URL.revokeObjectURL(a.href);
if (failed > 0) {
alert(`${allFonts.length - failed}/${allFonts.length} fonts downloaded. ${failed} failed.`);
}
if (fail > 0) alert(`${allFonts.length - fail}/${allFonts.length} fonts (${fail} failed)`);
} catch {
alert("Failed to create ZIP.");
} finally {
@@ -125,10 +164,7 @@ export default function LogoGenerator() {
</span>
<select
value={styleName}
onChange={(e) => {
setStyleName(e.target.value);
setImgError(false);
}}
onChange={(e) => setStyleName(e.target.value)}
style={{ maxHeight: 320 }}
size={Math.min(filteredGroups.flatMap((g) => g.fonts).length + filteredGroups.length, 12)}
>
@@ -144,14 +180,14 @@ export default function LogoGenerator() {
</select>
</label>
<button type="button" className="btn btn-primary" onClick={handleDownload}>
⬇️ Download GIF
<button type="button" className="btn btn-primary" onClick={handleDownload} disabled={!fontLoaded}>
⬇️ Download PNG
</button>
<button
type="button"
className="btn btn-primary"
onClick={handleSave}
disabled={saveStatus === "saving"}
disabled={saveStatus === "saving" || !fontLoaded}
>
{saveStatus === "saving"
? "⏳ Saving..."
@@ -172,7 +208,7 @@ export default function LogoGenerator() {
</div>
</ContentCard>
<ContentCard icon="👁️" title="Preview" subtitle="Rendered word via local proxy (cached on first load).">
<ContentCard icon="👁️" title="Preview" subtitle="Rendered locally from sprite sheets.">
<div
style={{
display: "grid",
@@ -185,17 +221,12 @@ export default function LogoGenerator() {
background: "repeating-conic-gradient(color-mix(in srgb, var(--color-text-muted) 14%, transparent) 0% 25%, transparent 0% 50%) 50% / 22px 22px",
}}
>
{imgError ? (
<p className="muted">Failed to load preview.</p>
{fontError ? (
<p className="muted">Failed to load font sprite.</p>
) : fontLoaded ? (
<canvas ref={canvasRef} style={{ maxWidth: "100%", height: "auto" }} />
) : (
// eslint-disable-next-line @next/next/no-img-element
<img
src={gifUrl}
alt={`Logo preview: ${safeText} in ${currentFont?.name ?? styleName} font`}
style={{ maxWidth: "100%", height: "auto" }}
onError={() => setImgError(true)}
onLoad={() => setImgError(false)}
/>
<p className="muted">Loading font…</p>
)}
</div>
</ContentCard>
+146
View File
@@ -0,0 +1,146 @@
const CHAR_ORDER = "abcdefghijklmnopqrstuvwxyz0123456789";
interface CharInfo {
char: string;
x: number;
w: number;
}
const fontCache = new Map<string, { chars: CharInfo[]; h: number; sheet: HTMLImageElement }>();
function hexPixel(data: Uint8ClampedArray, x: number, y: number, w: number): number {
const i = (y * w + x) * 4;
return (data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3];
}
function isTransparent(data: Uint8ClampedArray, x: number, y: number, w: number): boolean {
return data[(y * w + x) * 4 + 3] === 0;
}
function colEmpty(data: Uint8ClampedArray, x: number, w: number, h: number): boolean {
for (let y = 0; y < h; y++) {
if (!isTransparent(data, x, y, w)) return false;
}
return true;
}
function scanCharWidths(data: Uint8ClampedArray, sw: number, sh: number): CharInfo[] {
const chars: CharInfo[] = [];
let ci = 0;
let x = 0;
while (x < sw && ci < CHAR_ORDER.length) {
// skip transparent columns
while (x < sw && colEmpty(data, x, sw, sh)) x++;
if (x >= sw) break;
const start = x;
// find end of character
while (x < sw && !colEmpty(data, x, sw, sh)) x++;
const end = x;
const w = end - start;
if (w > 0) {
chars.push({ char: CHAR_ORDER[ci], x: start, w });
ci++;
}
}
return chars;
}
export async function getFontInfo(font: string): Promise<{ chars: CharInfo[]; h: number; sheet: HTMLImageElement }> {
const cached = fontCache.get(font);
if (cached) return cached;
const img = new Image();
img.crossOrigin = "anonymous";
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error(`Failed to load sprite for ${font}`));
img.src = `/assets/fonts/sheets/${font}.gif`;
});
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const chars = scanCharWidths(imageData.data, canvas.width, canvas.height);
// measure total height by finding first/last non-empty row
let top = canvas.height, bottom = 0;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
if (!isTransparent(imageData.data, x, y, canvas.width)) {
top = Math.min(top, y);
bottom = Math.max(bottom, y);
break;
}
}
}
const h = bottom - top + 1;
const result = { chars, h, sheet: img };
fontCache.set(font, result);
return result;
}
export function measureText(chars: CharInfo[], h: number, text: string, spaceW: number): { totalW: number } {
const map = new Map(chars.map((c) => [c.char, c]));
let totalW = 0;
for (const ch of text.toLowerCase()) {
if (ch === " ") {
totalW += spaceW;
} else {
const info = map.get(ch);
totalW += info?.w ?? spaceW;
}
}
return { totalW };
}
export function renderToCanvas(
chars: CharInfo[],
h: number,
sheet: HTMLImageElement,
text: string,
spaceW: number,
dpr = 1,
): HTMLCanvasElement | null {
const map = new Map(chars.map((c) => [c.char, c]));
const safeText = text.toLowerCase();
let totalW = 0;
for (const ch of safeText) {
totalW += ch === " " ? spaceW : (map.get(ch)?.w ?? spaceW);
}
if (totalW === 0) return null;
const canvas = document.createElement("canvas");
canvas.width = Math.round(totalW * dpr);
canvas.height = Math.round(h * dpr);
const ctx = canvas.getContext("2d");
if (!ctx) return null;
ctx.scale(dpr, dpr);
let x = 0;
for (const ch of safeText) {
if (ch === " ") {
x += spaceW;
} else {
const info = map.get(ch);
if (info) {
ctx.drawImage(sheet, info.x, 0, info.w, sheet.naturalHeight, x, 0, info.w, h);
x += info.w;
} else {
x += spaceW;
}
}
}
return canvas;
}