Spaces:
Running

hugging-space / src /logo.ts
Chunte's picture
Chunte HF Staff
Hugging Partnership: v9 press arc test build
0a0ec90 verified
Raw History Blame Contribute Delete
14.9 kB
// Partner logo: loading, sanitising, and one-off raster analysis.
//
// Analysis happens once per logo in the logo's own space (a grid covering its viewBox). At
// runtime, scene points are mapped into that grid through the current placement
// (position / scale / rotation), so dragging is cheap.
import { convexHull, edt, type Pt } from './field';
export const CLS_OUTSIDE = 0; // transparent, outside the logo's convex hull
export const CLS_OPAQUE = 1; // painted logo
export const CLS_POCKET = 2; // transparent but inside the hull: holes, gaps between bars
export interface GripCandidate {
// Position on the logo boundary and outward normal, in viewBox units.
x: number;
y: number;
nx: number;
ny: number;
// Stroke thickness measured inward along -n, in viewBox units.
thick: number;
// True when the edge faces open space (the logo's outer silhouette), false for hole edges.
outer: boolean;
comp: number; // connected component id
}
export interface LogoAsset {
name: string;
markup: string; // sanitised <svg> element, ids prefixed
vbX: number;
vbY: number;
vbW: number;
vbH: number;
// Analysis grid (PAD px border on every side).
gs: number; // grid px per viewBox unit
W: number;
H: number;
cls: Uint8Array;
comp: Int32Array; // connected component per pixel (-1 = transparent)
dOut: Float32Array; // grid px to nearest opaque pixel
sdf: Float32Array; // signed distance in grid px: >0 outside the logo, <0 inside
candidates: GripCandidate[];
pocketOverlay: string; // data URL, for the debug view
}
export interface Placement {
cx: number; // scene position of the logo's centre
cy: number;
scale: number; // scene px per viewBox unit
rot: number; // radians
}
const PAD = 4;
const GRID_MAX = 480;
let idCounter = 0;
// ---------------------------------------------------------------------------------------------
// Loading & sanitising
const DANGEROUS = ['script', 'foreignObject', 'iframe', 'object', 'embed', 'audio', 'video'];
function scopeCss(css: string, scope: string): string {
// Minimal scoper for typical design-tool exports (".cls-1{fill:#f00}"): prefix every selector.
return css.replace(/(^|})\s*([^{}@]+)\{/g, (_m, brace: string, sel: string) => {
const scoped = sel
.split(',')
.map((s) => `#${scope} ${s.trim()}`)
.join(', ');
return `${brace} ${scoped} {`;
});
}
export function sanitizeSvg(text: string): { root: SVGSVGElement; vb: [number, number, number, number] } {
const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
const root = doc.documentElement as unknown as SVGSVGElement;
if (!root || root.nodeName.toLowerCase() !== 'svg' || doc.querySelector('parsererror')) {
throw new Error('That file is not a valid SVG.');
}
for (const tag of DANGEROUS) doc.querySelectorAll(tag).forEach((n) => n.remove());
const prefix = `L${++idCounter}_`;
const idMap = new Map<string, string>();
doc.querySelectorAll('[id]').forEach((el) => {
const old = el.getAttribute('id')!;
const neu = prefix + old.replace(/[^\w-]/g, '_');
idMap.set(old, neu);
el.setAttribute('id', neu);
});
const all = [root as Element, ...Array.from(doc.querySelectorAll('*'))];
for (const el of all) {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase();
let val = attr.value;
if (name.startsWith('on')) {
el.removeAttribute(attr.name);
continue;
}
if ((name === 'href' || name === 'xlink:href') && /^\s*javascript:/i.test(val)) {
el.removeAttribute(attr.name);
continue;
}
if (val.includes('url(#') || ((name === 'href' || name === 'xlink:href') && val.startsWith('#'))) {
val = val.replace(/url\(#([^)]+)\)/g, (_m, id: string) => `url(#${idMap.get(id) ?? id})`);
if (val.startsWith('#')) val = '#' + (idMap.get(val.slice(1)) ?? val.slice(1));
el.setAttribute(attr.name, val);
}
}
}
const scope = `${prefix}root`;
root.setAttribute('id', scope);
doc.querySelectorAll('style').forEach((s) => {
let css = s.textContent ?? '';
css = css.replace(/url\(#([^)]+)\)/g, (_m, id: string) => `url(#${idMap.get(id) ?? id})`);
s.textContent = scopeCss(css, scope);
});
let vb: [number, number, number, number];
const vbAttr = root.getAttribute('viewBox');
if (vbAttr) {
const p = vbAttr.split(/[\s,]+/).map(Number);
vb = [p[0], p[1], p[2], p[3]];
} else {
const w = parseFloat(root.getAttribute('width') ?? '') || 300;
const h = parseFloat(root.getAttribute('height') ?? '') || 300;
vb = [0, 0, w, h];
}
if (!(vb[2] > 0 && vb[3] > 0)) throw new Error('The SVG has no usable size (viewBox/width/height).');
root.setAttribute('viewBox', vb.join(' '));
root.removeAttribute('style');
root.removeAttribute('overflow');
root.setAttribute('preserveAspectRatio', 'none');
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
return { root, vb };
}
function loadImage(svgText: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }));
img.onload = () => {
URL.revokeObjectURL(url);
resolve(img);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Could not render that SVG.'));
};
img.src = url;
});
}
// ---------------------------------------------------------------------------------------------
// Analysis
export async function loadLogo(text: string, name: string): Promise<LogoAsset> {
const { root, vb } = sanitizeSvg(text);
const [vbX, vbY, vbW, vbH] = vb;
const gs = GRID_MAX / Math.max(vbW, vbH);
const gw = Math.max(8, Math.round(vbW * gs));
const gh = Math.max(8, Math.round(vbH * gs));
const W = gw + PAD * 2;
const H = gh + PAD * 2;
// Rasterise at grid size.
root.setAttribute('width', String(vbW));
root.setAttribute('height', String(vbH));
const markup = new XMLSerializer().serializeToString(root);
const rasterRoot = root.cloneNode(true) as SVGSVGElement;
rasterRoot.setAttribute('width', String(gw));
rasterRoot.setAttribute('height', String(gh));
const img = await loadImage(new XMLSerializer().serializeToString(rasterRoot));
const canvas = document.createElement('canvas');
canvas.width = W;
canvas.height = H;
const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
ctx.drawImage(img, PAD, PAD, gw, gh);
const alpha = ctx.getImageData(0, 0, W, H).data;
const N = W * H;
const opaque = new Uint8Array(N);
const transparent = new Uint8Array(N);
let count = 0;
for (let i = 0; i < N; i++) {
if (alpha[i * 4 + 3] > 110) {
opaque[i] = 1;
count++;
} else transparent[i] = 1;
}
if (count < 20) throw new Error('The SVG looks empty (nothing opaque to hug).');
// Convex hull of the opaque pixels (row extremes are enough).
const pts: Pt[] = [];
for (let y = 0; y < H; y++) {
let minX = -1;
let maxX = -1;
for (let x = 0; x < W; x++) {
if (opaque[y * W + x]) {
if (minX < 0) minX = x;
maxX = x;
}
}
if (minX >= 0) {
pts.push({ x: minX, y }, { x: maxX + 1, y }, { x: minX, y: y + 1 }, { x: maxX + 1, y: y + 1 });
}
}
const hull = convexHull(pts);
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = '#000';
ctx.beginPath();
hull.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
ctx.fill();
const hullData = ctx.getImageData(0, 0, W, H).data;
// Pockets: transparent pixels inside the hull and deep enough inside it. Shallow notches
// along the outline (gear teeth, rounded corners) stay "outside" so the body doesn't bulge
// into them; holes and the gaps between bars are deep and qualify.
const outsideHull = new Uint8Array(N);
for (let i = 0; i < N; i++) outsideHull[i] = hullData[i * 4 + 3] > 127 ? 0 : 1;
const hullDepth = edt(outsideHull, W, H);
const minDepth = 0.075 * Math.max(gw, gh);
const cls = new Uint8Array(N);
for (let i = 0; i < N; i++) {
if (opaque[i]) cls[i] = CLS_OPAQUE;
else if (!outsideHull[i] && hullDepth[i] > minDepth) cls[i] = CLS_POCKET;
else cls[i] = CLS_OUTSIDE;
}
// Connected components of the logo, so the hand prefers the piece Huggy is touching.
const comp = new Int32Array(N).fill(-1);
let compCount = 0;
const stack: number[] = [];
for (let i = 0; i < N; i++) {
if (!opaque[i] || comp[i] >= 0) continue;
comp[i] = compCount;
stack.push(i);
while (stack.length) {
const j = stack.pop()!;
const x = j % W;
const nb = [x > 0 ? j - 1 : -1, x < W - 1 ? j + 1 : -1, j - W, j + W];
for (const k of nb) {
if (k >= 0 && k < N && opaque[k] && comp[k] < 0) {
comp[k] = compCount;
stack.push(k);
}
}
}
compCount++;
}
const dOut = edt(opaque, W, H); // distance to nearest opaque
const dIn = edt(transparent, W, H); // distance to nearest transparent
const sdfGrid = new Float32Array(N);
for (let i = 0; i < N; i++) sdfGrid[i] = dOut[i] - dIn[i];
const sdf = (x: number, y: number) => {
x = Math.min(W - 1, Math.max(0, x));
y = Math.min(H - 1, Math.max(0, y));
return sdfGrid[y * W + x];
};
// Grip candidates: one boundary pixel per 4x4 cell.
const candidates: GripCandidate[] = [];
const CELL = 4;
const seen = new Set<number>();
for (let y = 1; y < H - 1; y++) {
for (let x = 1; x < W - 1; x++) {
const i = y * W + x;
if (!opaque[i]) continue;
if (opaque[i - 1] && opaque[i + 1] && opaque[i - W] && opaque[i + W]) continue;
const cell = ((y / CELL) | 0) * 10000 + ((x / CELL) | 0);
if (seen.has(cell)) continue;
seen.add(cell);
let nx = sdf(x + 2, y) - sdf(x - 2, y);
let ny = sdf(x, y + 2) - sdf(x, y - 2);
const len = Math.hypot(nx, ny);
if (len < 1e-6) continue;
nx /= len;
ny /= len;
// March inward to measure stroke thickness.
let t = 0;
const maxT = Math.max(W, H);
while (t < maxT) {
const sx = Math.round(x - nx * t);
const sy = Math.round(y - ny * t);
if (sx < 0 || sy < 0 || sx >= W || sy >= H || !opaque[sy * W + sx]) break;
t += 1;
}
const ox = Math.round(x + nx * 3);
const oy = Math.round(y + ny * 3);
const outer = ox < 0 || oy < 0 || ox >= W || oy >= H || cls[oy * W + ox] === CLS_OUTSIDE;
candidates.push({
x: (x + 0.5 - PAD) / gs,
y: (y + 0.5 - PAD) / gs,
nx,
ny,
thick: t / gs,
outer,
comp: comp[i],
});
}
}
// Debug overlay: pockets in teal.
const overlay = ctx.createImageData(W, H);
for (let i = 0; i < N; i++) {
if (cls[i] === CLS_POCKET) {
overlay.data[i * 4] = 0;
overlay.data[i * 4 + 1] = 190;
overlay.data[i * 4 + 2] = 170;
overlay.data[i * 4 + 3] = 110;
}
}
ctx.putImageData(overlay, 0, 0);
const pocketOverlay = canvas.toDataURL();
return { name, markup, vbX, vbY, vbW, vbH, gs, W, H, cls, comp, dOut, sdf: sdfGrid, candidates, pocketOverlay };
}
// ---------------------------------------------------------------------------------------------
// Runtime mapping
export class LogoSampler {
private cos: number;
private sin: number;
private k: number;
private ox: number;
private oy: number;
constructor(
readonly asset: LogoAsset,
readonly pl: Placement,
) {
this.cos = Math.cos(-pl.rot);
this.sin = Math.sin(-pl.rot);
this.k = asset.gs / pl.scale;
this.ox = (asset.vbW * asset.gs) / 2 + PAD;
this.oy = (asset.vbH * asset.gs) / 2 + PAD;
}
private index(x: number, y: number): number {
const dx = x - this.pl.cx;
const dy = y - this.pl.cy;
const gx = Math.floor((this.cos * dx - this.sin * dy) * this.k + this.ox);
const gy = Math.floor((this.sin * dx + this.cos * dy) * this.k + this.oy);
if (gx < 0 || gy < 0 || gx >= this.asset.W || gy >= this.asset.H) return -1;
return gy * this.asset.W + gx;
}
/** Classify a scene point: outside / opaque / pocket. */
cls(x: number, y: number): number {
const i = this.index(x, y);
return i < 0 ? CLS_OUTSIDE : this.asset.cls[i];
}
/** Signed distance (scene px) to the logo edge: >0 outside, <0 inside. */
sdf(x: number, y: number): number {
const i = this.index(x, y);
if (i < 0) return this.distToLogo(x, y);
return this.asset.sdf[i] / this.k;
}
/** Outward edge normal at a scene point, from the signed distance gradient. */
normal(x: number, y: number): Pt {
const h = 2.5;
const nx = this.sdf(x + h, y) - this.sdf(x - h, y);
const ny = this.sdf(x, y + h) - this.sdf(x, y - h);
const len = Math.hypot(nx, ny) || 1;
return { x: nx / len, y: ny / len };
}
/** Connected component id at a scene point (-1 if transparent). */
comp(x: number, y: number): number {
const i = this.index(x, y);
return i < 0 ? -1 : this.asset.comp[i];
}
/** Approximate scene-space distance to the nearest opaque logo pixel. */
distToLogo(x: number, y: number): number {
const i = this.index(x, y);
if (i >= 0) return this.asset.dOut[i] / this.k;
// Outside the grid: distance to the grid box plus nothing better known.
const dx = x - this.pl.cx;
const dy = y - this.pl.cy;
const lx = Math.abs(this.cos * dx - this.sin * dy) - (this.asset.vbW * this.pl.scale) / 2;
const ly = Math.abs(this.sin * dx + this.cos * dy) - (this.asset.vbH * this.pl.scale) / 2;
return Math.hypot(Math.max(lx, 0), Math.max(ly, 0));
}
/** Map a point in viewBox units (relative to the viewBox origin) to scene space. */
toScene(x: number, y: number): Pt {
const lx = (x - this.asset.vbW / 2) * this.pl.scale;
const ly = (y - this.asset.vbH / 2) * this.pl.scale;
const c = Math.cos(this.pl.rot);
const s = Math.sin(this.pl.rot);
return { x: this.pl.cx + c * lx - s * ly, y: this.pl.cy + s * lx + c * ly };
}
/** Rotate a direction from logo space to scene space. */
dirToScene(nx: number, ny: number): Pt {
const c = Math.cos(this.pl.rot);
const s = Math.sin(this.pl.rot);
return { x: c * nx - s * ny, y: s * nx + c * ny };
}
}
/** SVG transform attribute that places the logo's viewBox in the scene. */
export function placementTransform(asset: LogoAsset, pl: Placement): string {
const deg = (pl.rot * 180) / Math.PI;
return `translate(${pl.cx} ${pl.cy}) rotate(${deg}) scale(${pl.scale}) translate(${-asset.vbW / 2} ${-asset.vbH / 2})`;
}
export function overlayGeometry(asset: LogoAsset): { x: number; y: number; w: number; h: number } {
return { x: -PAD / asset.gs, y: -PAD / asset.gs, w: asset.W / asset.gs, h: asset.H / asset.gs };
}