Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(portal): turn any website into a walkable 3D world from its own URL

nirholasd7a8a9087b94
diff --git a/api/_lib/portal/fetch-site.js b/api/_lib/portal/fetch-site.js
new file mode 100644
index 000000000..ab09cc68a
--- /dev/null
+++ b/api/_lib/portal/fetch-site.js
@@ -0,0 +1,162 @@
+// @ts-check
+// Fetching the page a Portal is built from.
+//
+// Portal is a crawler that runs on a visitor's request, so it is held to
+// crawler manners rather than browser manners:
+//
+// identifies itself a real product token with a URL a webmaster can read.
+// asks first robots.txt is fetched (and cached) before the page, and
+// a Disallow for our token is honoured with a clean 403,
+// not a silent fetch.
+// takes one copy a built world is cached fleet-wide, so a link shared to
+// a thousand people is one request to the origin site.
+// stays inside limits SSRF-guarded, IP-pinned, size-capped, time-boxed.
+//
+// The SSRF guard is not optional decoration here: the URL is caller-supplied by
+// definition, so every fetch goes through fetchSafePublicUrlPinned, which
+// re-resolves the host, refuses private ranges, pins the socket to the address
+// it validated, re-validates every redirect hop, and enforces the byte ceiling
+// while streaming.
+
+import { fetchSafePublicUrlPinned, SsrfBlockedError, MaxBytesExceededError } from '../ssrf-guard.js';
+import { cacheWrapLastGood } from '../cache.js';
+import { isAllowed } from './robots.js';
+import { outlineFromHtml } from './outline.js';
+
+/** The token webmasters will see, and the page that explains it. */
+export const USER_AGENT = 'ThreeWSPortalBot/1.0 (+https://three.ws/portal)';
+export const ROBOTS_TOKEN = 'threewsportalbot';
+
+export const MAX_HTML_BYTES = 3 * 1024 * 1024;
+export const MAX_ROBOTS_BYTES = 512 * 1024;
+const PAGE_TIMEOUT_MS = 12_000;
+const ROBOTS_TIMEOUT_MS = 6_000;
+/** A world is stable for an hour; the last good copy outlives an origin outage. */
+export const WORLD_TTL_SECONDS = 3600;
+
+/** Thrown for every reason a URL cannot become a world. `code` is the wire code. */
+export class PortalFetchError extends Error {
+ /** @param {string} code @param {string} message @param {number} [status] */
+ constructor(code, message, status = 400) {
+ super(message);
+ this.name = 'PortalFetchError';
+ this.code = code;
+ this.status = status;
+ }
+}
+
+/**
+ * Normalize what a human typed into a URL we are willing to fetch.
+ * Accepts `example.com`, rejects anything that is not http(s).
+ * @param {string} input
+ * @returns {URL}
+ */
+export function normalizeTarget(input) {
+ const raw = String(input || '').trim();
+ if (!raw) throw new PortalFetchError('invalid_url', 'Pass a website address to explore.');
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
+ let u;
+ try {
+ u = new URL(withScheme);
+ } catch {
+ throw new PortalFetchError('invalid_url', `${raw} is not a web address.`);
+ }
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') {
+ throw new PortalFetchError('invalid_url', 'Only http and https addresses can be explored.');
+ }
+ if (!u.hostname.includes('.')) {
+ throw new PortalFetchError('invalid_url', `${u.hostname} is not a public host name.`);
+ }
+ u.hash = '';
+ return u;
+}
+
+async function readText(url, { timeoutMs, maxBytes }) {
+ const res = await fetchSafePublicUrlPinned(
+ url,
+ {
+ headers: {
+ 'user-agent': USER_AGENT,
+ accept: 'text/html,application/xhtml+xml,text/plain;q=0.8,*/*;q=0.5',
+ 'accept-language': 'en',
+ },
+ signal: AbortSignal.timeout(timeoutMs),
+ },
+ { allowHttp: true, maxBytes },
+ );
+ return { status: res.status, contentType: res.headers.get('content-type') || '', body: await res.text() };
+}
+
+/**
+ * robots.txt for an origin, cached for an hour and shared across every page of
+ * that host. A robots.txt that cannot be read allows everything, which is what
+ * RFC 9309 says an unavailable file means.
+ * @param {URL} target
+ * @returns {Promise<string|null>}
+ */
+export async function robotsFor(target) {
+ const origin = target.origin;
+ const { value } = await cacheWrapLastGood(
+ `portal:robots:${origin}`,
+ WORLD_TTL_SECONDS,
+ async () => {
+ try {
+ const { status, body } = await readText(`${origin}/robots.txt`, {
+ timeoutMs: ROBOTS_TIMEOUT_MS,
+ maxBytes: MAX_ROBOTS_BYTES,
+ });
+ // 4xx means "no rules" per the RFC; 5xx means the site is unwell, and
+ // treating that as a blanket Disallow would make Portal unusable
+ // every time an origin has a bad minute.
+ return status >= 200 && status < 300 ? body : '';
+ } catch {
+ return '';
+ }
+ },
+ { withMeta: true },
+ );
+ return value || null;
+}
+
+/**
+ * Fetch one page and read it into a SiteOutline. Every failure is a
+ * PortalFetchError carrying a code the UI can explain to a human.
+ * @param {URL} target
+ * @returns {Promise<import('./types.js').SiteOutline>}
+ */
+export async function outlineForUrl(target) {
+ const robots = await robotsFor(target);
+ if (!isAllowed(robots, `${target.pathname}${target.search}`, ROBOTS_TOKEN)) {
+ throw new PortalFetchError(
+ 'robots_disallowed',
+ `${target.host} asks crawlers not to read this page, so Portal will not build it.`,
+ 403,
+ );
+ }
+
+ let page;
+ try {
+ page = await readText(target.toString(), { timeoutMs: PAGE_TIMEOUT_MS, maxBytes: MAX_HTML_BYTES });
+ } catch (err) {
+ if (err instanceof SsrfBlockedError) {
+ throw new PortalFetchError('blocked_host', 'That address does not resolve to a public website.', 400);
+ }
+ if (err instanceof MaxBytesExceededError) {
+ throw new PortalFetchError('too_large', `${target.host} sent more than ${Math.round(MAX_HTML_BYTES / 1e6)} MB of HTML.`, 413);
+ }
+ const reason = err?.name === 'TimeoutError' ? 'did not answer in time' : err?.message || 'could not be reached';
+ throw new PortalFetchError('unreachable', `${target.host} ${reason}.`, 502);
+ }
+
+ if (page.status >= 400) {
+ throw new PortalFetchError('upstream_status', `${target.host} answered ${page.status}.`, page.status === 404 ? 404 : 502);
+ }
+ if (page.contentType && !/html|xml|text\/plain/i.test(page.contentType)) {
+ throw new PortalFetchError('not_html', `${target.host} served ${page.contentType.split(';')[0]}, which has no page structure to walk.`, 415);
+ }
+ const outline = outlineFromHtml(page.body, target.toString());
+ if (!outline.sections.length) {
+ throw new PortalFetchError('no_structure', `${target.host} has no headings or text to build a world from.`, 422);
+ }
+ return outline;
+}
diff --git a/api/_lib/portal/outline.js b/api/_lib/portal/outline.js
new file mode 100644
index 000000000..8143a600c
--- /dev/null
+++ b/api/_lib/portal/outline.js
@@ -0,0 +1,231 @@
+// @ts-check
+// HTML to SiteOutline: the reading half of Portal.
+//
+// Portal turns a web page into a walkable place, and a place needs structure
+// rather than prose. This module reads a page the way a reader skims it (the
+// heading spine, what sits under each heading, where each section points) and
+// emits a small, stable description of that structure. Everything downstream
+// (the world layout, the GLB export, the SDK) consumes this shape and never
+// touches HTML again, which is what keeps the layout a pure function.
+//
+// Two properties are load-bearing and covered by tests:
+//
+// deterministic the same bytes always produce the same outline, so the same
+// URL always builds the same world and a share link is stable.
+// bounded every list is capped and every string is trimmed, so one
+// pathological page cannot produce a 40 MB world document.
+
+import { parse } from 'node-html-parser';
+
+/** Caps. A page with more than this is summarized, never truncated silently. */
+export const LIMITS = Object.freeze({
+ sections: 24,
+ linksPerSection: 8,
+ imagesPerSection: 4,
+ summaryChars: 220,
+ headingChars: 90,
+ titleChars: 120,
+ descriptionChars: 300,
+});
+
+/** Elements that carry no reader-facing text. */
+const DROP = 'script,style,noscript,template,svg,iframe,form,nav,footer,header';
+
+const collapse = (s) => String(s || '').replace(/\s+/g, ' ').trim();
+const clamp = (s, n) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
+
+/** Stable slug for a section id, so a world keeps its ids across rebuilds. */
+export function slugify(text, fallback) {
+ const base = collapse(text)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+ return base || fallback;
+}
+
+function metaContent(root, names) {
+ for (const name of names) {
+ const el =
+ root.querySelector(`meta[property="${name}"]`) || root.querySelector(`meta[name="${name}"]`);
+ const value = collapse(el?.getAttribute('content') || '');
+ if (value) return value;
+ }
+ return '';
+}
+
+/** Absolute URL, or null when the href is unusable (mailto:, javascript:, junk). */
+export function absolutize(href, base) {
+ const raw = String(href || '').trim();
+ if (!raw || raw.startsWith('#')) return null;
+ try {
+ const u = new URL(raw, base);
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
+ u.hash = '';
+ return u.toString();
+ } catch {
+ return null;
+ }
+}
+
+/** A six-digit hex colour from a CSS colour value, or null. */
+export function normalizeColor(value) {
+ const raw = collapse(value).toLowerCase();
+ let m = /^#([0-9a-f]{3})$/.exec(raw);
+ if (m) return `#${m[1][0]}${m[1][0]}${m[1][1]}${m[1][1]}${m[1][2]}${m[1][2]}`;
+ m = /^#([0-9a-f]{6})$/.exec(raw);
+ if (m) return `#${m[1]}`;
+ m = /^rgba?\(\s*(\d{1,3})\D+(\d{1,3})\D+(\d{1,3})/.exec(raw);
+ if (m) {
+ const hex = [1, 2, 3]
+ .map((i) => Math.min(255, Number(m[i])).toString(16).padStart(2, '0'))
+ .join('');
+ return `#${hex}`;
+ }
+ return null;
+}
+
+/**
+ * Read one page into a SiteOutline.
+ * @param {string} html raw document
+ * @param {string} pageUrl the URL it was fetched from (used to resolve links)
+ * @returns {import('./types.js').SiteOutline}
+ */
+export function outlineFromHtml(html, pageUrl) {
+ const root = parse(String(html || ''), { blockTextElements: { script: false, style: false } });
+ for (const el of root.querySelectorAll(DROP)) el.remove();
+
+ const base = (() => {
+ const href = root.querySelector('base[href]')?.getAttribute('href');
+ return absolutize(href, pageUrl) || pageUrl;
+ })();
+ const canonical = absolutize(root.querySelector('link[rel="canonical"]')?.getAttribute('href'), base) || pageUrl;
+ const host = new URL(pageUrl).host;
+
+ const title = clamp(
+ collapse(metaContent(root, ['og:title', 'twitter:title']) || root.querySelector('title')?.text || host),
+ LIMITS.titleChars,
+ );
+ const description = clamp(
+ collapse(metaContent(root, ['og:description', 'description', 'twitter:description'])),
+ LIMITS.descriptionChars,
+ );
+ const siteName = clamp(collapse(metaContent(root, ['og:site_name'])), LIMITS.titleChars) || null;
+ const themeColor = normalizeColor(
+ root.querySelector('meta[name="theme-color"]')?.getAttribute('content') || '',
+ );
+ const image = absolutize(metaContent(root, ['og:image', 'twitter:image']), base);
+ const icon =
+ absolutize(root.querySelector('link[rel~="icon"]')?.getAttribute('href'), base) ||
+ absolutize('/favicon.ico', base);
+ const lang = collapse(root.querySelector('html')?.getAttribute('lang') || '').slice(0, 12) || 'en';
+
+ const sections = readSections(root, base, host);
+ const linkCounts = sections.reduce(
+ (acc, s) => {
+ for (const l of s.links) acc[l.internal ? 'internal' : 'external'] += 1;
+ return acc;
+ },
+ { internal: 0, external: 0 },
+ );
+
+ return {
+ version: 1,
+ url: pageUrl,
+ canonical,
+ host,
+ title,
+ description,
+ siteName,
+ themeColor,
+ image,
+ icon,
+ lang,
+ sections,
+ linkCounts,
+ words: sections.reduce((n, s) => n + s.words, 0),
+ };
+}
+
+/**
+ * Walk the document in order, opening a new section at every h1..h3 and
+ * attributing the content that follows to it. Content before the first heading
+ * becomes the intro section, so a page with no headings still has a place.
+ */
+function readSections(root, base, host) {
+ const body = root.querySelector('body') || root;
+ /** @type {any[]} */
+ const sections = [];
+ let current = null;
+ const open = (level, heading) => {
+ if (sections.length >= LIMITS.sections) return null;
+ const id = slugify(heading, `section-${sections.length + 1}`);
+ const unique = sections.some((s) => s.id === id) ? `${id}-${sections.length + 1}` : id;
+ current = {
+ id: unique,
+ level,
+ heading: clamp(collapse(heading), LIMITS.headingChars),
+ summary: '',
+ words: 0,
+ paragraphs: 0,
+ codeBlocks: 0,
+ links: [],
+ images: [],
+ };
+ sections.push(current);
+ return current;
+ };
+
+ // One ordered pass. `inText` marks that an ancestor already counted this
+ // prose, so a <p> nested in a <blockquote> is not counted twice while its
+ // links and images are still collected.
+ const walk = (node, inText, inPre) => {
+ for (const child of node.childNodes || []) {
+ if (child.nodeType !== 1) continue;
+ const tag = String(child.rawTagName || '').toLowerCase();
+ if (/^h[1-3]$/.test(tag)) {
+ const text = collapse(child.text);
+ if (text) open(Number(tag[1]), text);
+ continue;
+ }
+ if (!current) open(1, clamp(collapse(root.querySelector('title')?.text || host) || host, LIMITS.headingChars));
+ if (!current) return;
+ const isText = tag === 'p' || tag === 'li' || tag === 'blockquote' || tag === 'td';
+ if (isText && !inText) countText(current, collapse(child.text));
+ // <pre><code> is one block, not two: only the outermost counts.
+ if (tag === 'pre' || (tag === 'code' && !inPre)) current.codeBlocks += 1;
+ if (tag === 'a') collectLink(current, child, base, host);
+ if (tag === 'img') collectImage(current, child, base);
+ if (child.childNodes?.length && tag !== 'a') walk(child, inText || isText, inPre || tag === 'pre' || tag === 'code');
+ }
+ };
+ walk(body, false, false);
+
+ return sections.filter((s) => s.heading);
+}
+
+function countText(section, text) {
+ if (!text) return;
+ section.paragraphs += 1;
+ section.words += text.split(' ').length;
+ if (section.summary.length < LIMITS.summaryChars) {
+ section.summary = clamp(collapse(`${section.summary} ${text}`), LIMITS.summaryChars);
+ }
+}
+
+function collectLink(section, el, base, host) {
+ if (section.links.length >= LIMITS.linksPerSection) return;
+ const href = absolutize(el.getAttribute('href'), base);
+ if (!href) return;
+ if (section.links.some((l) => l.href === href)) return;
+ const text = clamp(collapse(el.text) || new URL(href).pathname, 60);
+ section.links.push({ href, text, internal: new URL(href).host === host });
+}
+
+function collectImage(section, el, base) {
+ if (section.images.length >= LIMITS.imagesPerSection) return;
+ const src = absolutize(el.getAttribute('src') || el.getAttribute('data-src'), base);
+ if (!src) return;
+ if (section.images.some((i) => i.src === src)) return;
+ section.images.push({ src, alt: clamp(collapse(el.getAttribute('alt') || ''), 80) });
+}
diff --git a/api/_lib/portal/robots.js b/api/_lib/portal/robots.js
new file mode 100644
index 000000000..66271f50e
--- /dev/null
+++ b/api/_lib/portal/robots.js
@@ -0,0 +1,150 @@
+// @ts-check
+// A minimal, correct robots.txt matcher for the Portal crawler.
+//
+// Portal fetches a page the visitor asked for, on their behalf, once, and
+// caches the result. That is polite by construction, but "polite by
+// construction" is not the same as "asked permission", and a crawler that
+// ignores robots.txt is the kind of detail that turns a good product into a
+// complaint. There is no robots parser in this repo's dependency tree, and the
+// format is small enough that a correct implementation is shorter than the
+// argument for adding one.
+//
+// Implements the parts of the Robots Exclusion Protocol (RFC 9309) that decide
+// an allow/deny for one path:
+//
+// - Groups are selected by the MOST SPECIFIC matching User-agent token, with
+// `*` as the fallback group. Consecutive `User-agent` lines share one group.
+// - Within the winning group, the LONGEST matching rule wins, and Allow beats
+// Disallow on an exact tie (RFC 9309 section 2.2.2).
+// - `*` matches any run of characters, `$` anchors the end of the path.
+// - An empty `Disallow:` value allows everything; a group with no rules allows
+// everything. A missing or unreachable robots.txt allows everything, which is
+// what every major crawler does and what the RFC's "unavailable" status says.
+// - Comments (`#`) are stripped, values are trimmed, keys are case-insensitive.
+
+/** @typedef {{ agents: string[], rules: { allow: boolean, path: string }[] }} RobotsGroup */
+
+/**
+ * Parse a robots.txt body into its groups. Never throws: a malformed file is a
+ * file that grants everything, not a crash in the caller's request path.
+ * @param {string} body
+ * @returns {RobotsGroup[]}
+ */
+export function parseRobots(body) {
+ /** @type {RobotsGroup[]} */
+ const groups = [];
+ /** @type {RobotsGroup | null} */
+ let current = null;
+ // True while we are reading a run of User-agent lines, which all belong to
+ // the same group. The first rule line closes the run, so the NEXT
+ // User-agent line starts a new group rather than joining this one.
+ let collectingAgents = false;
+
+ for (const rawLine of String(body || '').split(/\r?\n/)) {
+ const line = rawLine.split('#')[0].trim();
+ if (!line) continue;
+ const idx = line.indexOf(':');
+ if (idx < 0) continue;
+ const key = line.slice(0, idx).trim().toLowerCase();
+ const value = line.slice(idx + 1).trim();
+
+ if (key === 'user-agent') {
+ if (!current || !collectingAgents) {
+ current = { agents: [], rules: [] };
+ groups.push(current);
+ collectingAgents = true;
+ }
+ if (value) current.agents.push(value.toLowerCase());
+ continue;
+ }
+ if (key !== 'allow' && key !== 'disallow') continue;
+ if (!current) continue;
+ collectingAgents = false;
+ // `Disallow:` with an empty value is the documented "allow everything"
+ // form, so it is recorded as nothing rather than as a rule matching "".
+ if (key === 'disallow' && value === '') continue;
+ current.rules.push({ allow: key === 'allow', path: value });
+ }
+ return groups;
+}
+
+/**
+ * The group that governs `userAgent`: the longest matching agent token, or the
+ * `*` group, or null when neither exists.
+ * @param {RobotsGroup[]} groups
+ * @param {string} userAgent
+ */
+function groupFor(groups, userAgent) {
+ const ua = String(userAgent || '').toLowerCase();
+ /** @type {RobotsGroup | null} */
+ let best = null;
+ let bestLen = -1;
+ /** @type {RobotsGroup | null} */
+ let wildcard = null;
+ for (const group of groups) {
+ for (const agent of group.agents) {
+ if (agent === '*') {
+ if (!wildcard) wildcard = group;
+ continue;
+ }
+ if (ua.includes(agent) && agent.length > bestLen) {
+ best = group;
+ bestLen = agent.length;
+ }
+ }
+ }
+ return best || wildcard;
+}
+
+/**
+ * Does a robots path pattern match this path? `*` is any run of characters and
+ * a trailing `$` anchors the end. Everything else is a literal prefix match.
+ * @param {string} pattern
+ * @param {string} path
+ * @returns {number} length of the matched pattern, or -1 when it does not match
+ */
+export function matchRule(pattern, path) {
+ if (pattern === '') return -1;
+ const anchored = pattern.endsWith('$');
+ const body = anchored ? pattern.slice(0, -1) : pattern;
+ const parts = body.split('*');
+ let cursor = 0;
+ for (let i = 0; i < parts.length; i++) {
+ const part = parts[i];
+ if (part === '') continue;
+ const at = i === 0 ? (path.startsWith(part) ? 0 : -1) : path.indexOf(part, cursor);
+ if (at < 0) return -1;
+ cursor = at + part.length;
+ }
+ if (anchored && cursor !== path.length) {
+ // A trailing wildcard before the anchor may still consume the remainder.
+ if (!body.endsWith('*')) return -1;
+ }
+ return pattern.length;
+}
+
+/**
+ * Is `path` fetchable by `userAgent` under this robots.txt body?
+ * @param {string|null|undefined} body robots.txt contents, or null when unreachable
+ * @param {string} path URL path (with query, as sent on the wire)
+ * @param {string} userAgent our product token
+ * @returns {boolean}
+ */
+export function isAllowed(body, path, userAgent) {
+ if (!body) return true;
+ const group = groupFor(parseRobots(body), userAgent);
+ if (!group || !group.rules.length) return true;
+ const target = path || '/';
+ let verdict = true;
+ let bestLen = -1;
+ for (const rule of group.rules) {
+ const len = matchRule(rule.path, target);
+ if (len < 0) continue;
+ // Longest match wins; Allow wins an exact-length tie (RFC 9309 2.2.2).
+ if (len > bestLen || (len === bestLen && rule.allow)) {
+ bestLen = len;
+ verdict = rule.allow;
+ }
+ }
+ return verdict;
+}
diff --git a/api/_lib/portal/types.js b/api/_lib/portal/types.js
new file mode 100644
index 000000000..2f334f9f5
--- /dev/null
+++ b/api/_lib/portal/types.js
@@ -0,0 +1,50 @@
+// @ts-check
+// The two wire shapes Portal is built on. They are contracts: the renderer, the
+// GLB exporter, the MCP tool and the published SDK all read them, so a change
+// here is a change to every one of those. The prose spec is specs/portal-world.md.
+
+/**
+ * @typedef {object} SiteLink
+ * @property {string} href absolute http(s) URL
+ * @property {string} text the anchor's visible text, trimmed
+ * @property {boolean} internal same host as the page it was found on
+ */
+
+/**
+ * @typedef {object} SiteImage
+ * @property {string} src absolute http(s) URL
+ * @property {string} alt alternative text, trimmed (may be empty)
+ */
+
+/**
+ * @typedef {object} SiteSection
+ * @property {string} id stable slug, unique within the outline
+ * @property {1|2|3} level heading level it was opened by
+ * @property {string} heading
+ * @property {string} summary first prose of the section, clamped
+ * @property {number} words
+ * @property {number} paragraphs
+ * @property {number} codeBlocks
+ * @property {SiteLink[]} links
+ * @property {SiteImage[]} images
+ */
+
+/**
+ * @typedef {object} SiteOutline
+ * @property {1} version
+ * @property {string} url the URL that was fetched
+ * @property {string} canonical the page's own canonical URL, or `url`
+ * @property {string} host
+ * @property {string} title
+ * @property {string} description
+ * @property {string|null} siteName
+ * @property {string|null} themeColor `#rrggbb`
+ * @property {string|null} image og:image
+ * @property {string|null} icon
+ * @property {string} lang
+ * @property {SiteSection[]} sections
+ * @property {{internal:number,external:number}} linkCounts
+ * @property {number} words
+ */
+
+export {};
diff --git a/api/_lib/portal/world-glb.js b/api/_lib/portal/world-glb.js
new file mode 100644
index 000000000..c0031af7e
--- /dev/null
+++ b/api/_lib/portal/world-glb.js
@@ -0,0 +1,209 @@
+// @ts-check
+// A Portal world as a real glTF 2.0 binary.
+//
+// The browser renders the world from JSON, which is the right shape for a live,
+// navigable page. This is the other half of the promise: the same world as a
+// file you can open in Blender, drop into Unity, view in AR on a phone, or hand
+// to any glTF tool on earth. It reads the SAME world document the renderer
+// reads (src/portal/layout.js), so what downloads is what was walked.
+//
+// Built with @gltf-transform, the library already used for avatar baking and
+// diorama scene export, so the output travels the same validated path as every
+// other GLB the platform emits. Two geometries (a unit box and a unit cylinder)
+// are authored once and instanced by every node, and materials are deduplicated
+// by colour, which keeps a 24-district city in the tens of kilobytes rather
+// than the tens of megabytes a naive per-node mesh would produce.
+
+import { Document, NodeIO } from '@gltf-transform/core';
+import { KHRLightsPunctual, KHRMaterialsEmissiveStrength } from '@gltf-transform/extensions';
+
+/** Cube vertices, one face at a time so each face keeps its own normal. */
+function boxPrimitive(doc, buffer) {
+ const p = [];
+ const n = [];
+ const idx = [];
+ /** @type {[number[], number[]][]} */
+ const faces = [
+ [[0, 0, 1], [-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5]],
+ [[0, 0, -1], [0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5]],
+ [[1, 0, 0], [0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5]],
+ [[-1, 0, 0], [-0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5]],
+ [[0, 1, 0], [-0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5]],
+ [[0, -1, 0], [-0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5]],
+ ];
+ faces.forEach(([normal, verts], f) => {
+ for (let v = 0; v < 4; v++) {
+ p.push(verts[v * 3], verts[v * 3 + 1], verts[v * 3 + 2]);
+ n.push(normal[0], normal[1], normal[2]);
+ }
+ const base = f * 4;
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
+ });
+ return doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(new Float32Array(p)).setBuffer(buffer))
+ .setAttribute('NORMAL', doc.createAccessor().setType('VEC3').setArray(new Float32Array(n)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint16Array(idx)).setBuffer(buffer));
+}
+
+/** A unit-radius, unit-height cylinder: the plaza disc and the ground plate. */
+function cylinderPrimitive(doc, buffer, segments = 48) {
+ const p = [];
+ const n = [];
+ const idx = [];
+ p.push(0, 0.5, 0);
+ n.push(0, 1, 0);
+ for (let i = 0; i <= segments; i++) {
+ const a = (i / segments) * Math.PI * 2;
+ p.push(Math.cos(a), 0.5, Math.sin(a));
+ n.push(0, 1, 0);
+ }
+ for (let i = 1; i <= segments; i++) idx.push(0, i + 1, i);
+ const sideStart = p.length / 3;
+ for (let i = 0; i <= segments; i++) {
+ const a = (i / segments) * Math.PI * 2;
+ const cx = Math.cos(a);
+ const cz = Math.sin(a);
+ p.push(cx, 0.5, cz, cx, -0.5, cz);
+ n.push(cx, 0, cz, cx, 0, cz);
+ }
+ for (let i = 0; i < segments; i++) {
+ const a = sideStart + i * 2;
+ idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
+ }
+ return doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(new Float32Array(p)).setBuffer(buffer))
+ .setAttribute('NORMAL', doc.createAccessor().setType('VEC3').setArray(new Float32Array(n)).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint16Array(idx)).setBuffer(buffer));
+}
+
+function srgbToLinear(c) {
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+}
+
+/** '#rrggbb' to the linear float RGBA glTF base colours are authored in. */
+export function hexToLinear(hex, alpha = 1) {
+ const m = /^#?([0-9a-f]{6})$/i.exec(String(hex || '')) || [null, '888888'];
+ const int = parseInt(m[1], 16);
+ return [
+ srgbToLinear(((int >> 16) & 255) / 255),
+ srgbToLinear(((int >> 8) & 255) / 255),
+ srgbToLinear((int & 255) / 255),
+ alpha,
+ ];
+}
+
+/**
+ * Compose a world document into a single GLB.
+ * @param {object} world a PortalWorld from src/portal/layout.js
+ * @returns {Promise<Uint8Array>}
+ */
+export async function worldToGlb(world) {
+ const doc = new Document();
+ doc.createBuffer();
+ const buffer = doc.getRoot().listBuffers()[0];
+ const lightsExt = doc.createExtension(KHRLightsPunctual);
+ doc.createExtension(KHRMaterialsEmissiveStrength);
+
+ const scene = doc.createScene(`portal:${world.meta.host}`);
+ doc.getRoot().setDefaultScene(scene);
+ // The asset block travels with the file, so anyone who opens it later can see
+ // what made it and which page its structure came from.
+ Object.assign(doc.getRoot().getAsset(), {
+ generator: 'three.ws Portal',
+ copyright: `Structure derived from ${world.meta.canonical || world.meta.url}`,
+ });
+
+ const box = boxPrimitive(doc, buffer);
+ const cyl = cylinderPrimitive(doc, buffer);
+ /** @type {Map<string, any>} */
+ const materials = new Map();
+ /** @type {Map<string, any>} */
+ const meshes = new Map();
+
+ const materialFor = (hex, { metallic = 0.1, rough = 0.72, emissive = 0 } = {}) => {
+ const key = `${hex}|${metallic}|${rough}|${emissive}`;
+ if (materials.has(key)) return materials.get(key);
+ const mat = doc
+ .createMaterial(`m${materials.size}`)
+ .setBaseColorFactor(hexToLinear(hex))
+ .setMetallicFactor(metallic)
+ .setRoughnessFactor(rough);
+ if (emissive > 0) mat.setEmissiveFactor(hexToLinear(hex).slice(0, 3).map((c) => c * emissive));
+ materials.set(key, mat);
+ return mat;
+ };
+
+ // One mesh per (shape, material) pair, instanced by every node that needs it.
+ const meshFor = (shape, hex, opts) => {
+ const mat = materialFor(hex, opts);
+ const key = `${shape}|${mat.getName()}`;
+ if (meshes.has(key)) return meshes.get(key);
+ const prim = (shape === 'box' ? box : cyl).clone().setMaterial(mat);
+ const mesh = doc.createMesh(key).addPrimitive(prim);
+ meshes.set(key, mesh);
+ return mesh;
+ };
+
+ const place = (name, mesh, { x, y, z, sx, sy, sz, yaw = 0 }) => {
+ const node = doc
+ .createNode(name)
+ .setMesh(mesh)
+ .setTranslation([x, y, z])
+ .setScale([sx, sy, sz])
+ .setRotation([0, Math.sin(-yaw / 2), 0, Math.cos(-yaw / 2)]);
+ scene.addChild(node);
+ return node;
+ };
+
+ // Ground and plaza.
+ place('ground', meshFor('cyl', world.ground.color, { rough: 0.95 }), {
+ x: 0, y: -0.25, z: 0, sx: world.ground.radius, sy: 0.5, sz: world.ground.radius,
+ });
+ place('plaza', meshFor('cyl', world.palette.accent, { rough: 0.5, metallic: 0.2 }), {
+ x: 0, y: 0.02, z: 0, sx: world.plaza.radius, sy: 0.08, sz: world.plaza.radius,
+ });
+ place('monument', meshFor('box', world.palette.primary, { metallic: 0.35, rough: 0.35, emissive: 0.25 }), {
+ x: 0, y: world.plaza.monument.h / 2, z: 0, sx: 1.6, sy: world.plaza.monument.h, sz: 1.6,
+ });
+
+ for (const b of world.buildings) {
+ place(`building:${b.sectionId}`, meshFor('box', b.color, { metallic: 0.15, rough: 0.6 }), {
+ x: b.x, y: b.h / 2, z: b.z, sx: b.w, sy: b.h, sz: b.d, yaw: b.rot,
+ });
+ }
+ for (const d of world.doors) {
+ place(`door:${d.id}`, meshFor('box', d.color, { emissive: 0.9, rough: 0.3 }), {
+ x: d.x, y: d.h / 2, z: d.z, sx: d.w, sy: d.h, sz: 0.22, yaw: d.yaw,
+ });
+ }
+ for (const p of world.props) {
+ if (p.kind === 'billboard') {
+ place(`billboard:${p.id}`, meshFor('box', p.color, { emissive: 0.35, rough: 0.4 }), {
+ x: p.x, y: p.h / 2 + 1.2, z: p.z, sx: p.w, sy: p.h, sz: 0.16, yaw: p.yaw,
+ });
+ place(`billboard-post:${p.id}`, meshFor('box', world.palette.monolith, {}), {
+ x: p.x, y: 0.6, z: p.z, sx: 0.18, sy: 1.2, sz: 0.18, yaw: p.yaw,
+ });
+ } else if (p.kind === 'monolith') {
+ place(`monolith:${p.id}`, meshFor('box', p.color, { metallic: 0.55, rough: 0.25, emissive: 0.12 }), {
+ x: p.x, y: p.h / 2, z: p.z, sx: p.w, sy: p.h, sz: p.w, yaw: p.yaw,
+ });
+ }
+ }
+
+ // A sun aimed down the world's diagonal, and a soft fill, so the file looks
+ // like the page rather than like a flat viewer default.
+ const sun = lightsExt.createLight('sun').setType('directional').setIntensity(3.2).setColor([1, 0.97, 0.9]);
+ const sunNode = doc.createNode('sun').setRotation([-0.36, 0.24, 0.1, 0.9]);
+ sunNode.setExtension('KHR_lights_punctual', sun);
+ scene.addChild(sunNode);
+ const fill = lightsExt.createLight('fill').setType('directional').setIntensity(0.8).setColor(hexToLinear(world.palette.accent).slice(0, 3));
+ const fillNode = doc.createNode('fill').setRotation([0.3, -0.5, 0, 0.81]);
+ fillNode.setExtension('KHR_lights_punctual', fill);
+ scene.addChild(fillNode);
+
+ const io = new NodeIO().registerExtensions([KHRLightsPunctual, KHRMaterialsEmissiveStrength]);
+ return io.writeBinary(doc);
+}
diff --git a/api/portal.js b/api/portal.js
new file mode 100644
index 000000000..66d702386
--- /dev/null
+++ b/api/portal.js
@@ -0,0 +1,120 @@
+/**
+ * Portal: any website, as a walkable 3D world.
+ * ---------------------------------------------
+ * GET /api/portal?url=<address> → { outline, world, cached }
+ * GET /api/portal?url=<address>&format=glb → the world as a binary glTF
+ * GET /api/portal?url=<address>&include=world|outline|both
+ *
+ * The world is a JSON document (specs/portal-world.md) that the page renderer,
+ * the published SDK (@three-ws/portal) and the GLB exporter all read. Building
+ * one costs exactly one request to the target site plus a cached robots.txt
+ * read, and the result is cached fleet-wide for an hour, so a link shared to a
+ * thousand people is still one visit to the origin.
+ *
+ * Open CORS on purpose: the SDK runs in other people's pages, and this endpoint
+ * returns nothing that is not already public on the site it read.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { cacheWrapLastGood } from './_lib/cache.js';
+import { normalizeTarget, outlineForUrl, PortalFetchError, WORLD_TTL_SECONDS, USER_AGENT } from './_lib/portal/fetch-site.js';
+import { buildWorld } from '../src/portal/layout.js';
+
+export const maxDuration = 30;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const raw = url.searchParams.get('url') || '';
+ const format = (url.searchParams.get('format') || 'json').toLowerCase();
+ const include = (url.searchParams.get('include') || 'both').toLowerCase();
+
+ let target;
+ try {
+ target = normalizeTarget(raw);
+ } catch (err) {
+ return error(res, 400, err.code || 'invalid_url', err.message);
+ }
+
+ const ip = clientIp(req);
+ const cacheKey = `portal:world:${target.toString()}`;
+
+ // A cached world is free to serve and costs the origin site nothing, so the
+ // rate limiter only guards a real build. Checking the cache first is what
+ // makes a viral share link cheap for everyone involved.
+ let cached = true;
+ let built;
+ try {
+ const { value, stale } = await cacheWrapLastGood(
+ cacheKey,
+ WORLD_TTL_SECONDS,
+ async () => {
+ cached = false;
+ const gate = await gateBuild(ip);
+ if (gate) throw gate;
+ const outline = await outlineForUrl(target);
+ return { outline, world: buildWorld(outline), builtAt: new Date().toISOString() };
+ },
+ { withMeta: true },
+ );
+ built = { ...value, stale: !!stale };
+ } catch (err) {
+ if (err instanceof RateLimited) return rateLimited(res, err.result, err.message);
+ if (err instanceof PortalFetchError) return error(res, err.status, err.code, err.message);
+ console.error('[portal] build failed', target.host, err?.message || err);
+ return error(res, 502, 'build_failed', `Could not build a world from ${target.host}.`);
+ }
+
+ if (format === 'glb') {
+ const exportGate = await limits.portalExportIp(ip);
+ if (!exportGate.success) {
+ return rateLimited(res, exportGate, 'Too many world exports from this address. Try again shortly.');
+ }
+ const { worldToGlb } = await import('./_lib/portal/world-glb.js');
+ const glb = await worldToGlb(built.world);
+ res.statusCode = 200;
+ res.setHeader('content-type', 'model/gltf-binary');
+ res.setHeader('content-length', String(glb.byteLength));
+ res.setHeader('content-disposition', `attachment; filename="portal-${safeName(built.world.meta.host)}.glb"`);
+ res.setHeader('cache-control', 'public, max-age=3600');
+ return res.end(Buffer.from(glb));
+ }
+
+ const body = { ok: true, cached, stale: built.stale, built_at: built.builtAt, user_agent: USER_AGENT };
+ if (include === 'outline' || include === 'both') body.outline = built.outline;
+ if (include === 'world' || include === 'both') body.world = built.world;
+ return json(res, 200, body, {
+ 'cache-control': 'public, max-age=300, stale-while-revalidate=3600',
+ });
+});
+
+/**
+ * Rate-limit rejection carried out of the cache loader without losing the
+ * limiter result, which is what carries the real reset time and the reason a
+ * degraded limiter reports (see rateLimited in api/_lib/http.js).
+ */
+class RateLimited extends Error {
+ constructor(message, result) {
+ super(message);
+ this.name = 'RateLimited';
+ this.result = result;
+ }
+}
+
+async function gateBuild(ip) {
+ const [perIp, fleet] = await Promise.all([limits.portalBuildIp(ip), limits.portalBuildGlobal()]);
+ if (!perIp.success) {
+ return new RateLimited('Too many new worlds from this address. Open a world someone already built, or try again shortly.', perIp);
+ }
+ if (!fleet.success) {
+ return new RateLimited('Portal is building at capacity right now. Try again in a few minutes.', fleet);
+ }
+ return null;
+}
+
+function safeName(host) {
+ return String(host || 'world').replace(/[^a-z0-9.-]+/gi, '-').slice(0, 48);
+}
diff --git a/src/portal/layout.js b/src/portal/layout.js
new file mode 100644
index 000000000..ecf1d1325
--- /dev/null
+++ b/src/portal/layout.js
@@ -0,0 +1,299 @@
+// Outline to world: the pure half of Portal.
+//
+// Given a SiteOutline (api/_lib/portal/outline.js) this returns a PortalWorld:
+// a small, JSON-safe description of a walkable place. It is deliberately pure
+// and dependency-free so the SAME function runs in three places and cannot
+// drift between them: the browser renderer (src/portal/render.js), the server
+// GLB exporter (api/_lib/portal/world-glb.js), and the published SDK
+// (packages/portal). No three.js here, no DOM, no randomness that is not seeded.
+//
+// The mapping, so a reader can predict what a page will look like before
+// loading it:
+//
+// site one plaza at the origin with the title monument, and one
+// district per section arranged on a phyllotaxis spiral, so
+// districts never collide and the walk between them is short.
+// section one building. Height comes from its word count (log scale,
+// so a 10,000 word essay is taller than a 500 word one but
+// not twenty times taller). Footprint comes from how many
+// blocks it holds. Heading level picks the silhouette.
+// link one door on the building's perimeter, facing out. Internal
+// links are portals (walk in, the world rebuilds there);
+// external links are gates (walk in, the page opens).
+// image one billboard beside the building, showing the real image.
+// code block one monolith: a tall, dark slab with an emissive edge.
+//
+// Determinism: every position derives from the section index and a seed hashed
+// from the page URL, so the same URL always builds the same city, and a share
+// link always leads to the place the sharer saw.
+
+export const WORLD_VERSION = 1;
+
+/** Spacing constants, in metres. The avatar is ~1.8 m for scale. */
+export const METRICS = Object.freeze({
+ plazaRadius: 11,
+ districtStep: 7.6,
+ districtBase: 17,
+ minBuilding: 4.5,
+ maxBuilding: 13,
+ minHeight: 3.5,
+ maxHeight: 26,
+ doorWidth: 1.6,
+ doorHeight: 2.6,
+ billboard: 3.2,
+ groundPad: 26,
+});
+
+/** FNV-1a over a string: a stable 32-bit seed with no dependency. */
+export function hashSeed(text) {
+ let h = 0x811c9dc5;
+ const s = String(text || '');
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ return h >>> 0;
+}
+
+/** mulberry32: tiny, fast, well-distributed seeded PRNG. */
+export function seededRandom(seed) {
+ let a = seed >>> 0;
+ return function next() {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Clamp helper. Inline maths stays readable when the bounds are named. */
+const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
+const round = (n) => Math.round(n * 1000) / 1000;
+
+/**
+ * Hue for a host, so a site looks like itself everywhere without stored art.
+ * Mirrors the crew-colour idea already used elsewhere in the platform.
+ */
+export function paletteFor(outline) {
+ const themed = hexToHsl(outline.themeColor);
+ const hue = themed ? themed.h : hashSeed(outline.host) % 360;
+ const sat = themed ? clamp(themed.s, 45, 85) : 62;
+ return {
+ primary: hslToHex(hue, sat, 56),
+ secondary: hslToHex((hue + 28) % 360, sat, 44),
+ accent: hslToHex((hue + 186) % 360, Math.min(92, sat + 18), 62),
+ ground: hslToHex(hue, 18, 16),
+ sky: hslToHex(hue, 30, 9),
+ fog: hslToHex(hue, 26, 12),
+ monolith: hslToHex((hue + 210) % 360, 24, 22),
+ };
+}
+
+export function hexToHsl(hex) {
+ const m = /^#([0-9a-f]{6})$/i.exec(String(hex || ''));
+ if (!m) return null;
+ const int = parseInt(m[1], 16);
+ const r = ((int >> 16) & 255) / 255;
+ const g = ((int >> 8) & 255) / 255;
+ const b = (int & 255) / 255;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const l = (max + min) / 2;
+ if (max === min) return { h: 0, s: 0, l: l * 100 };
+ const d = max - min;
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ let h;
+ if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
+ else if (max === g) h = ((b - r) / d + 2) / 6;
+ else h = ((r - g) / d + 4) / 6;
+ return { h: h * 360, s: s * 100, l: l * 100 };
+}
+
+export function hslToHex(h, s, l) {
+ const sat = clamp(s, 0, 100) / 100;
+ const lum = clamp(l, 0, 100) / 100;
+ const c = (1 - Math.abs(2 * lum - 1)) * sat;
+ const hp = (((h % 360) + 360) % 360) / 60;
+ const x = c * (1 - Math.abs((hp % 2) - 1));
+ const [r1, g1, b1] =
+ hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x];
+ const m = lum - c / 2;
+ const to = (v) => Math.round(clamp((v + m) * 255, 0, 255)).toString(16).padStart(2, '0');
+ return `#${to(r1)}${to(g1)}${to(b1)}`;
+}
+
+/** Where district `i` of `n` sits: a phyllotaxis spiral, so nothing collides. */
+export function districtPosition(index) {
+ const golden = Math.PI * (3 - Math.sqrt(5));
+ const angle = index * golden;
+ const radius = METRICS.districtBase + METRICS.districtStep * Math.sqrt(index);
+ return { x: round(Math.cos(angle) * radius), z: round(Math.sin(angle) * radius), angle };
+}
+
+/**
+ * Build the world.
+ * @param {object} outline SiteOutline
+ * @param {{ seed?: number }} [opts]
+ * @returns {object} PortalWorld
+ */
+export function buildWorld(outline, opts = {}) {
+ if (!outline || !Array.isArray(outline.sections)) {
+ throw new TypeError('buildWorld: an outline with sections is required');
+ }
+ const seed = Number.isFinite(opts.seed) ? opts.seed >>> 0 : hashSeed(outline.canonical || outline.url);
+ const rand = seededRandom(seed);
+ const palette = paletteFor(outline);
+
+ const buildings = [];
+ const doors = [];
+ const props = [];
+ const districts = [];
+
+ outline.sections.forEach((section, i) => {
+ const pos = districtPosition(i);
+ const facing = Math.atan2(-pos.z, -pos.x); // every building faces the plaza
+ const weight = Math.log10(Math.max(10, section.words)) - 1; // 0 at 10 words, 1 at 100, 2 at 1000
+ const height = round(clamp(METRICS.minHeight + weight * 7 + section.paragraphs * 0.35, METRICS.minHeight, METRICS.maxHeight));
+ const width = round(clamp(METRICS.minBuilding + section.paragraphs * 0.5 + rand() * 1.5, METRICS.minBuilding, METRICS.maxBuilding));
+ const depth = round(clamp(width * (0.72 + rand() * 0.4), METRICS.minBuilding * 0.8, METRICS.maxBuilding));
+ const kind = section.level === 1 ? 'tower' : section.level === 2 ? 'hall' : 'kiosk';
+ const building = {
+ id: `b-${section.id}`,
+ sectionId: section.id,
+ kind,
+ label: section.heading,
+ summary: section.summary,
+ words: section.words,
+ x: pos.x,
+ z: pos.z,
+ w: width,
+ d: depth,
+ h: kind === 'kiosk' ? round(Math.min(height, 6)) : height,
+ rot: round(facing),
+ color: i === 0 ? palette.primary : palette.secondary,
+ floors: Math.max(1, Math.round(height / 3.2)),
+ };
+ buildings.push(building);
+ districts.push({ id: `d-${section.id}`, sectionId: section.id, x: pos.x, z: pos.z, radius: round(Math.max(width, depth) * 0.9 + 3) });
+
+ // Doors along the face that looks at the plaza, then wrapping the sides.
+ section.links.forEach((link, li) => {
+ const slot = doorSlot(building, li, section.links.length);
+ doors.push({
+ id: `door-${section.id}-${li}`,
+ buildingId: building.id,
+ href: link.href,
+ label: link.text,
+ internal: !!link.internal,
+ x: round(slot.x),
+ z: round(slot.z),
+ yaw: round(slot.yaw),
+ w: METRICS.doorWidth,
+ h: METRICS.doorHeight,
+ color: link.internal ? palette.accent : palette.primary,
+ });
+ });
+
+ // Billboards fan out behind the building, angled back toward the plaza.
+ section.images.forEach((img, ii) => {
+ const spread = (ii - (section.images.length - 1) / 2) * 4.4;
+ const back = Math.max(width, depth) * 0.5 + 3.2;
+ const bx = pos.x + Math.cos(facing + Math.PI) * back + Math.cos(facing + Math.PI / 2) * spread;
+ const bz = pos.z + Math.sin(facing + Math.PI) * back + Math.sin(facing + Math.PI / 2) * spread;
+ props.push({
+ id: `img-${section.id}-${ii}`,
+ kind: 'billboard',
+ x: round(bx),
+ z: round(bz),
+ yaw: round(facing),
+ w: METRICS.billboard,
+ h: round(METRICS.billboard * 0.62),
+ src: img.src,
+ label: img.alt,
+ color: palette.accent,
+ });
+ });
+
+ // One monolith per code block, capped, standing in a short row.
+ const monoliths = Math.min(section.codeBlocks, 4);
+ for (let ci = 0; ci < monoliths; ci++) {
+ const spread = (ci - (monoliths - 1) / 2) * 2.4;
+ const side = Math.max(width, depth) * 0.5 + 2.4;
+ props.push({
+ id: `code-${section.id}-${ci}`,
+ kind: 'monolith',
+ x: round(pos.x + Math.cos(facing + Math.PI / 2) * side + Math.cos(facing) * spread),
+ z: round(pos.z + Math.sin(facing + Math.PI / 2) * side + Math.sin(facing) * spread),
+ yaw: round(facing),
+ w: 0.9,
+ h: round(2.6 + rand() * 1.8),
+ color: palette.monolith,
+ label: 'code',
+ });
+ }
+ });
+
+ const groundRadius = round(
+ Math.max(
+ METRICS.plazaRadius + METRICS.groundPad,
+ ...buildings.map((b) => Math.hypot(b.x, b.z) + Math.max(b.w, b.d) + 12),
+ ),
+ );
+
+ return {
+ version: WORLD_VERSION,
+ meta: {
+ url: outline.url,
+ canonical: outline.canonical,
+ host: outline.host,
+ title: outline.title,
+ description: outline.description,
+ siteName: outline.siteName,
+ lang: outline.lang,
+ seed,
+ words: outline.words,
+ sections: outline.sections.length,
+ links: outline.linkCounts,
+ },
+ palette,
+ ground: { radius: groundRadius, color: palette.ground, sky: palette.sky, fog: palette.fog },
+ plaza: { radius: METRICS.plazaRadius, monument: { label: outline.title, sub: outline.description || outline.host, h: 5.4 } },
+ spawn: { x: 0, z: METRICS.plazaRadius * 0.55, yaw: Math.PI },
+ districts,
+ buildings,
+ doors,
+ props,
+ };
+}
+
+/**
+ * Place door `index` of `count` on a building's perimeter, starting at the
+ * plaza-facing wall and wrapping around, always flush to the wall and never
+ * inside it.
+ */
+export function doorSlot(building, index, count) {
+ const perFace = 2;
+ const face = Math.floor(index / perFace) % 4;
+ const withinFace = index % perFace;
+ const spread = count <= 1 ? 0 : (withinFace - (Math.min(perFace, count) - 1) / 2) * (building.w * 0.42);
+ const yaw = building.rot + (face * Math.PI) / 2;
+ const half = (face % 2 === 0 ? building.d : building.w) / 2;
+ const along = face % 2 === 0 ? building.w : building.d;
+ const offset = count <= 1 ? 0 : clamp(spread, -along * 0.35, along * 0.35);
+ return {
+ x: building.x + Math.cos(yaw) * half + Math.cos(yaw + Math.PI / 2) * offset,
+ z: building.z + Math.sin(yaw) * half + Math.sin(yaw + Math.PI / 2) * offset,
+ yaw,
+ };
+}
+
+/** Every solid the player collides with, as circles. Renderer and SDK share it. */
+export function collidersFor(world) {
+ const out = world.buildings.map((b) => ({ x: b.x, z: b.z, r: Math.max(b.w, b.d) * 0.5 + 0.35 }));
+ for (const p of world.props) {
+ if (p.kind === 'monolith') out.push({ x: p.x, z: p.z, r: p.w * 0.7 });
+ }
+ out.push({ x: 0, z: 0, r: 2.2 });
+ return out;
+}
diff --git a/src/portal/main.js b/src/portal/main.js
new file mode 100644
index 000000000..6dff4a764
--- /dev/null
+++ b/src/portal/main.js
@@ -0,0 +1,410 @@
+// Portal: the page controller.
+//
+// Owns the state machine (intro → building → walking → error), the HUD, the
+// minimap, the touch stick, and the three ways a world leaves this page: a
+// share link, an embed snippet, and a GLB download. The world itself is built
+// by the API (api/portal.js) and rendered by ./render.js; this module never
+// parses HTML and never touches WebGL.
+//
+// A world is addressed by the page's own query string (`/portal?url=…`), so the
+// browser's back button walks back through the sites you visited, and any link
+// you copy reopens exactly the world you were standing in.
+
+import { createPortalWorld } from './render.js';
+
+const $ = (id) => document.getElementById(id);
+const els = {
+ canvas: $('pt-canvas'),
+ intro: $('pt-intro'),
+ introForm: $('pt-intro-form'),
+ introInput: $('pt-intro-input'),
+ examples: $('pt-examples'),
+ loading: $('pt-loading'),
+ loadingHost: $('pt-loading-host'),
+ steps: $('pt-steps'),
+ error: $('pt-error'),
+ errorCode: $('pt-error-code'),
+ errorMessage: $('pt-error-message'),
+ errorForm: $('pt-error-form'),
+ errorInput: $('pt-error-input'),
+ site: $('pt-site'),
+ siteIcon: $('pt-site-icon'),
+ siteTitle: $('pt-site-title'),
+ siteMeta: $('pt-site-meta'),
+ actions: $('pt-actions'),
+ copy: $('pt-copy'),
+ embed: $('pt-embed'),
+ glb: $('pt-glb'),
+ newAddress: $('pt-new'),
+ address: $('pt-address'),
+ addressInput: $('pt-address-input'),
+ door: $('pt-door'),
+ doorLabel: $('pt-door-label'),
+ doorKind: $('pt-door-kind'),
+ map: $('pt-map'),
+ mapCanvas: $('pt-map-canvas'),
+ stick: $('pt-stick'),
+ stickKnob: $('pt-stick-knob'),
+ toast: $('pt-toast'),
+ keys: $('pt-keys'),
+};
+
+let active = null; // the running world, if any
+let current = null; // { url, world, outline }
+
+// ── small helpers ──────────────────────────────────────────────────────────
+function show(el, on) {
+ if (el) el.hidden = !on;
+}
+
+let toastTimer = 0;
+function toast(message) {
+ els.toast.textContent = message;
+ els.toast.dataset.open = '1';
+ clearTimeout(toastTimer);
+ toastTimer = window.setTimeout(() => {
+ els.toast.dataset.open = '0';
+ }, 2400);
+}
+
+function setStep(name, state) {
+ for (const li of els.steps.querySelectorAll('.pt-step')) {
+ if (li.dataset.step === name) li.dataset.state = state;
+ }
+}
+
+function markStepsUpTo(name) {
+ const order = ['fetch', 'read', 'layout', 'render'];
+ const at = order.indexOf(name);
+ order.forEach((step, i) => setStep(step, i < at ? 'done' : i === at ? 'active' : ''));
+}
+
+function formatCount(n) {
+ return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
+}
+
+// ── loading and error surfaces ─────────────────────────────────────────────
+function showLoading(host) {
+ els.loadingHost.textContent = host;
+ markStepsUpTo('fetch');
+ show(els.intro, false);
+ show(els.error, false);
+ show(els.loading, true);
+}
+
+function showError(code, message) {
+ els.errorCode.textContent = String(code || 'error').replace(/_/g, ' ');
+ els.errorMessage.textContent = message || 'Something went wrong building that world.';
+ show(els.loading, false);
+ show(els.intro, false);
+ show(els.error, true);
+ els.errorInput.value = '';
+ els.errorInput.focus();
+}
+
+// ── the main flow ──────────────────────────────────────────────────────────
+async function openWorld(rawUrl, { push = true } = {}) {
+ const target = String(rawUrl || '').trim();
+ if (!target) return;
+ const host = target.replace(/^https?:\/\//, '').split('/')[0];
+ showLoading(host);
+
+ let payload;
+ try {
+ const res = await fetch(`/api/portal?url=${encodeURIComponent(target)}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(25_000),
+ });
+ markStepsUpTo('read');
+ payload = await res.json().catch(() => null);
+ if (!res.ok || !payload?.world) {
+ return showError(payload?.error || `http_${res.status}`, payload?.error_description || payload?.message || `${host} could not be read.`);
+ }
+ } catch (err) {
+ return showError(
+ err?.name === 'TimeoutError' ? 'timeout' : 'unreachable',
+ err?.name === 'TimeoutError'
+ ? `${host} took too long to answer. It may be slow rather than gone: try again.`
+ : `Could not reach three.ws to build ${host}. Check your connection and try again.`,
+ );
+ }
+
+ markStepsUpTo('layout');
+ current = { url: target, world: payload.world, outline: payload.outline };
+ if (push) {
+ const next = `/portal?url=${encodeURIComponent(target)}`;
+ if (location.pathname + location.search !== next) history.pushState({ url: target }, '', next);
+ }
+ document.title = `${payload.world.meta.title} as a walkable world · Portal · three.ws`;
+
+ markStepsUpTo('render');
+ mountWorld(payload.world);
+ paintHud(payload.world, payload.outline, payload.cached);
+ show(els.loading, false);
+}
+
+function mountWorld(world) {
+ active?.dispose();
+ active = createPortalWorld({
+ canvas: els.canvas,
+ world,
+ onDoor: handleDoor,
+ onReady: () => {
+ show(els.keys, !matchMedia('(pointer: coarse)').matches);
+ },
+ });
+ resize();
+ startMinimap(world);
+}
+
+function paintHud(world, outline, cached) {
+ els.siteTitle.textContent = world.meta.title || world.meta.host;
+ els.siteMeta.textContent = '';
+ const bits = [
+ world.meta.host,
+ `${world.meta.sections} ${world.meta.sections === 1 ? 'section' : 'sections'}`,
+ `${formatCount(world.meta.words)} words`,
+ `${world.doors.length} ${world.doors.length === 1 ? 'door' : 'doors'}`,
+ ];
+ if (cached) bits.push('cached');
+ for (const bit of bits) {
+ const span = document.createElement('span');
+ span.textContent = bit;
+ els.siteMeta.append(span);
+ }
+ if (outline?.icon) {
+ els.siteIcon.src = `/api/img?url=${encodeURIComponent(outline.icon)}`;
+ els.siteIcon.alt = '';
+ } else {
+ els.siteIcon.removeAttribute('src');
+ }
+ show(els.site, true);
+ show(els.actions, true);
+ show(els.address, true);
+ show(els.map, true);
+ show(els.stick, matchMedia('(pointer: coarse)').matches);
+ els.addressInput.value = '';
+ els.addressInput.placeholder = world.meta.host;
+}
+
+function handleDoor(door, phase) {
+ if (!door) {
+ els.door.dataset.open = '0';
+ return;
+ }
+ if (phase === 'near') {
+ els.doorLabel.textContent = door.label || door.href;
+ els.doorKind.textContent = door.internal ? 'same site' : new URL(door.href).host;
+ els.door.dataset.open = '1';
+ return;
+ }
+ // Activated: an internal link rebuilds the world in place, an external one
+ // opens the page it points at, which is what a door on the edge of a site is.
+ if (door.internal) {
+ openWorld(door.href);
+ } else {
+ window.open(door.href, '_blank', 'noopener,noreferrer');
+ toast(`Opened ${new URL(door.href).host}`);
+ }
+}
+
+// ── minimap ────────────────────────────────────────────────────────────────
+let mapRaf = 0;
+function startMinimap(world) {
+ cancelAnimationFrame(mapRaf);
+ const ctx = els.mapCanvas.getContext('2d');
+ const size = els.mapCanvas.width;
+ const scale = size / (world.ground.radius * 2.1);
+ const toMap = (x, z) => [size / 2 + x * scale, size / 2 + z * scale];
+
+ const draw = () => {
+ mapRaf = requestAnimationFrame(draw);
+ ctx.clearRect(0, 0, size, size);
+ ctx.fillStyle = 'rgba(255,255,255,0.03)';
+ ctx.beginPath();
+ ctx.arc(size / 2, size / 2, (world.ground.radius * scale), 0, Math.PI * 2);
+ ctx.fill();
+
+ ctx.strokeStyle = 'rgba(255,255,255,0.10)';
+ ctx.lineWidth = 1;
+ for (const d of world.districts) {
+ const [x, y] = toMap(d.x, d.z);
+ ctx.beginPath();
+ ctx.moveTo(size / 2, size / 2);
+ ctx.lineTo(x, y);
+ ctx.stroke();
+ }
+ for (const b of world.buildings) {
+ const [x, y] = toMap(b.x, b.z);
+ ctx.fillStyle = b.color;
+ ctx.fillRect(x - Math.max(2, b.w * scale) / 2, y - Math.max(2, b.d * scale) / 2, Math.max(2, b.w * scale), Math.max(2, b.d * scale));
+ }
+ for (const door of world.doors) {
+ const [x, y] = toMap(door.x, door.z);
+ ctx.fillStyle = door.color;
+ ctx.fillRect(x - 1.5, y - 1.5, 3, 3);
+ }
+ const p = active?.player;
+ if (p) {
+ const [x, y] = toMap(p.x, p.z);
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.rotate(-p.yaw);
+ ctx.fillStyle = '#ffffff';
+ ctx.beginPath();
+ ctx.moveTo(0, -6);
+ ctx.lineTo(4.5, 5);
+ ctx.lineTo(-4.5, 5);
+ ctx.closePath();
+ ctx.fill();
+ ctx.restore();
+ }
+ };
+ draw();
+}
+
+// ── touch stick ────────────────────────────────────────────────────────────
+function wireStick() {
+ let id = null;
+ let origin = { x: 0, y: 0 };
+ const radius = 44;
+ const set = (dx, dy) => {
+ const len = Math.hypot(dx, dy);
+ const k = len > radius ? radius / len : 1;
+ els.stickKnob.style.transform = `translate(${dx * k}px, ${dy * k}px)`;
+ active?.steer((dx * k) / radius, (dy * k) / radius);
+ };
+ els.stick.addEventListener('pointerdown', (e) => {
+ id = e.pointerId;
+ origin = { x: e.clientX, y: e.clientY };
+ els.stick.setPointerCapture(id);
+ });
+ els.stick.addEventListener('pointermove', (e) => {
+ if (e.pointerId !== id) return;
+ set(e.clientX - origin.x, e.clientY - origin.y);
+ });
+ const end = (e) => {
+ if (e.pointerId !== id) return;
+ id = null;
+ els.stickKnob.style.transform = 'translate(0,0)';
+ active?.steer(0, 0);
+ };
+ els.stick.addEventListener('pointerup', end);
+ els.stick.addEventListener('pointercancel', end);
+}
+
+// ── sharing ────────────────────────────────────────────────────────────────
+async function copyText(text, message) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(message);
+ } catch {
+ // Clipboard permission can be refused (an iframe, a locked-down browser).
+ // Selecting the text is the honest fallback: the user can still copy it.
+ const box = document.createElement('textarea');
+ box.value = text;
+ box.setAttribute('readonly', '');
+ box.style.position = 'fixed';
+ box.style.opacity = '0';
+ document.body.append(box);
+ box.select();
+ const ok = document.execCommand?.('copy');
+ box.remove();
+ toast(ok ? message : 'Copy blocked by the browser. The link is in the address bar.');
+ }
+}
+
+function embedSnippet(url) {
+ return `<iframe src="https://three.ws/portal?url=${encodeURIComponent(url)}&embed=1" width="100%" height="520" style="border:0;border-radius:14px" loading="lazy" title="Walk ${url} in 3D"></iframe>`;
+}
+
+async function downloadGlb() {
+ if (!current) return;
+ els.glb.disabled = true;
+ els.glb.textContent = 'Building GLB';
+ try {
+ const res = await fetch(`/api/portal?url=${encodeURIComponent(current.url)}&format=glb`, { signal: AbortSignal.timeout(30_000) });
+ if (!res.ok) {
+ const body = await res.json().catch(() => null);
+ throw new Error(body?.error_description || `export failed (${res.status})`);
+ }
+ const blob = await res.blob();
+ const href = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = href;
+ a.download = `portal-${current.world.meta.host}.glb`;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(href), 4000);
+ toast('Downloaded. Open it in any glTF viewer.');
+ } catch (err) {
+ toast(err?.message || 'Could not export this world.');
+ } finally {
+ els.glb.disabled = false;
+ els.glb.textContent = 'Download GLB';
+ }
+}
+
+// ── wiring ─────────────────────────────────────────────────────────────────
+function resize() {
+ active?.setSize(window.innerWidth, window.innerHeight);
+}
+
+function urlFromLocation() {
+ return new URLSearchParams(location.search).get('url') || '';
+}
+
+function boot() {
+ wireStick();
+ window.addEventListener('resize', resize);
+ window.addEventListener('popstate', () => {
+ const url = urlFromLocation();
+ if (url) openWorld(url, { push: false });
+ });
+
+ els.introForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ openWorld(els.introInput.value);
+ });
+ els.errorForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ openWorld(els.errorInput.value);
+ });
+ els.address.addEventListener('submit', (e) => {
+ e.preventDefault();
+ if (els.addressInput.value.trim()) openWorld(els.addressInput.value);
+ });
+ for (const root of [els.examples, els.error]) {
+ root.addEventListener('click', (e) => {
+ const chip = e.target.closest('[data-url]');
+ if (chip) openWorld(chip.dataset.url);
+ });
+ }
+ els.copy.addEventListener('click', () => {
+ copyText(`https://three.ws/portal?url=${encodeURIComponent(current?.url || '')}`, 'Link copied.');
+ });
+ els.embed.addEventListener('click', () => {
+ copyText(embedSnippet(current?.url || ''), 'Embed snippet copied.');
+ });
+ els.glb.addEventListener('click', downloadGlb);
+ els.newAddress.addEventListener('click', () => {
+ els.introInput.value = current?.url || '';
+ show(els.intro, true);
+ els.introInput.focus();
+ els.introInput.select();
+ });
+ els.door.addEventListener('click', () => active?.activate());
+
+ // An embedded portal hides the chrome that only makes sense on our own page.
+ if (new URLSearchParams(location.search).get('embed') === '1') {
+ document.body.classList.add('pt-embedded');
+ show(els.keys, false);
+ }
+
+ const initial = urlFromLocation();
+ if (initial) openWorld(initial, { push: false });
+ else els.introInput.focus();
+}
+
+boot();
diff --git a/src/portal/portal.css b/src/portal/portal.css
new file mode 100644
index 000000000..10c764a3c
--- /dev/null
+++ b/src/portal/portal.css
@@ -0,0 +1,310 @@
+/* Portal: the walkable-web surface.
+ The world fills the viewport and every control floats over it as glass, so
+ the page reads as a place rather than as a form with a canvas in it. Tokens
+ come from public/tokens.css; nothing here invents a colour the rest of the
+ site does not already use. */
+
+.pt-root {
+ position: fixed;
+ inset: 0;
+ overflow: hidden;
+ background: #05060a;
+ color: var(--ink);
+ font-family: var(--font-body);
+}
+
+.pt-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: block;
+ touch-action: none;
+}
+
+/* ── shared glass ────────────────────────────────────────────────────────── */
+.pt-glass {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ backdrop-filter: blur(18px) saturate(140%);
+ -webkit-backdrop-filter: blur(18px) saturate(140%);
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);
+}
+
+.pt-hud {
+ position: absolute;
+ z-index: 3;
+ pointer-events: auto;
+}
+
+/* ── top bar ─────────────────────────────────────────────────────────────── */
+.pt-top {
+ top: max(var(--space-md), env(safe-area-inset-top));
+ left: var(--space-md);
+ right: var(--space-md);
+ display: flex;
+ gap: var(--space-sm);
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ pointer-events: none;
+}
+.pt-top > * { pointer-events: auto; }
+
+.pt-site {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ min-width: 0;
+}
+.pt-site__icon {
+ width: 22px;
+ height: 22px;
+ border-radius: 6px;
+ background: var(--surface-3);
+ object-fit: cover;
+ flex: none;
+}
+.pt-site__text { min-width: 0; }
+.pt-site__title {
+ font-size: var(--text-ui);
+ font-weight: var(--weight-semibold);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 46vw;
+}
+.pt-site__meta {
+ font-size: var(--text-2xs);
+ color: var(--ink-dim);
+ display: flex;
+ gap: var(--space-sm);
+ white-space: nowrap;
+}
+
+.pt-actions { display: flex; gap: var(--space-xs); flex-wrap: wrap; }
+.pt-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ padding: var(--space-sm) var(--space-md);
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-medium);
+ cursor: pointer;
+ transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
+}
+.pt-btn:hover { background: var(--surface-3); border-color: var(--accent); }
+.pt-btn:active { transform: translateY(1px); }
+.pt-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.pt-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
+.pt-btn--primary { background: var(--accent); color: #0a0a0a; border-color: transparent; }
+.pt-btn--primary:hover { background: rgba(255, 255, 255, 0.88); }
+
+/* ── address bar ─────────────────────────────────────────────────────────── */
+.pt-address {
+ bottom: max(var(--space-md), env(safe-area-inset-bottom));
+ left: var(--space-md);
+ display: flex;
+ gap: var(--space-xs);
+ padding: var(--space-xs);
+ align-items: center;
+ width: min(520px, calc(100vw - 2 * var(--space-md)));
+}
+.pt-address__input {
+ flex: 1;
+ min-width: 0;
+ background: transparent;
+ border: 0;
+ color: var(--ink);
+ font-family: var(--font-mono);
+ font-size: var(--text-md);
+ padding: var(--space-sm) var(--space-md);
+}
+.pt-address__input::placeholder { color: var(--ink-dim); }
+.pt-address__input:focus { outline: none; }
+
+/* ── minimap ─────────────────────────────────────────────────────────────── */
+.pt-map {
+ bottom: max(var(--space-md), env(safe-area-inset-bottom));
+ right: var(--space-md);
+ width: 168px;
+ height: 168px;
+ padding: 6px;
+ display: grid;
+ place-items: center;
+}
+.pt-map canvas { width: 100%; height: 100%; border-radius: var(--radius-md); }
+
+/* ── door prompt ─────────────────────────────────────────────────────────── */
+.pt-door {
+ left: 50%;
+ bottom: calc(max(var(--space-md), env(safe-area-inset-bottom)) + 4.6rem);
+ transform: translateX(-50%) translateY(8px);
+ padding: var(--space-sm) var(--space-lg);
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ opacity: 0;
+ transition: opacity 160ms ease, transform 160ms ease;
+ pointer-events: none;
+ max-width: min(560px, 92vw);
+}
+.pt-door[data-open='1'] { opacity: 1; transform: translateX(-50%) translateY(0); pointer-events: auto; }
+.pt-door__key {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ padding: 2px 8px;
+ border-radius: 6px;
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-3);
+}
+.pt-door__label {
+ font-size: var(--text-ui);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.pt-door__kind { font-size: var(--text-2xs); color: var(--ink-dim); }
+
+/* ── joystick (touch) ────────────────────────────────────────────────────── */
+.pt-stick {
+ display: none;
+ left: var(--space-md);
+ bottom: calc(max(var(--space-md), env(safe-area-inset-bottom)) + 4.6rem);
+ width: 128px;
+ height: 128px;
+ border-radius: 50%;
+ touch-action: none;
+ place-items: center;
+}
+.pt-stick__knob {
+ width: 52px;
+ height: 52px;
+ border-radius: 50%;
+ background: var(--accent);
+ opacity: 0.85;
+ transition: transform 60ms linear;
+}
+@media (pointer: coarse) {
+ .pt-stick { display: grid; }
+ .pt-map { width: 116px; height: 116px; }
+}
+
+/* ── overlays: intro, loading, error ─────────────────────────────────────── */
+.pt-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 4;
+ display: grid;
+ place-items: center;
+ padding: var(--space-lg);
+ background: radial-gradient(120% 80% at 50% 10%, rgba(12, 14, 22, 0.72), rgba(4, 5, 9, 0.94));
+ backdrop-filter: blur(6px);
+}
+.pt-overlay[hidden] { display: none; }
+.pt-panel {
+ width: min(680px, 100%);
+ padding: var(--space-xl);
+ text-align: center;
+}
+.pt-eyebrow {
+ font-size: var(--text-2xs);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-sm);
+}
+.pt-h1 {
+ font-family: var(--font-display);
+ font-size: clamp(1.8rem, 5vw, var(--text-2xl));
+ line-height: var(--leading-tight);
+ margin: 0 0 var(--space-md);
+}
+.pt-lede {
+ color: var(--ink-dim);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ margin: 0 auto var(--space-lg);
+ max-width: 46ch;
+}
+.pt-form { display: flex; gap: var(--space-xs); margin-bottom: var(--space-md); }
+.pt-form input {
+ flex: 1;
+ padding: var(--space-md);
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-1);
+ color: var(--ink);
+ font-family: var(--font-mono);
+ font-size: var(--text-ui);
+}
+.pt-form input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
+.pt-examples { display: flex; flex-wrap: wrap; gap: var(--space-xs); justify-content: center; }
+.pt-chip {
+ padding: var(--space-2xs) var(--space-sm);
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ cursor: pointer;
+}
+.pt-chip:hover { color: var(--ink); border-color: var(--accent); }
+
+.pt-steps { list-style: none; margin: var(--space-lg) 0 0; padding: 0; display: grid; gap: var(--space-sm); text-align: left; }
+.pt-step { display: flex; gap: var(--space-sm); align-items: center; font-size: var(--text-sm); color: var(--ink-dim); }
+.pt-step__dot {
+ width: 8px; height: 8px; border-radius: 50%;
+ background: var(--stroke-strong);
+ flex: none;
+ transition: background 200ms ease, box-shadow 200ms ease;
+}
+.pt-step[data-state='active'] { color: var(--ink); }
+.pt-step[data-state='active'] .pt-step__dot { background: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft); animation: pt-pulse 1.2s ease-in-out infinite; }
+.pt-step[data-state='done'] .pt-step__dot { background: var(--success); }
+@keyframes pt-pulse { 50% { box-shadow: 0 0 0 9px transparent; } }
+
+.pt-error__code {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--warn);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.pt-toast {
+ position: absolute;
+ left: 50%;
+ top: 5.2rem;
+ transform: translateX(-50%) translateY(-6px);
+ z-index: 5;
+ padding: var(--space-sm) var(--space-md);
+ font-size: var(--text-sm);
+ opacity: 0;
+ transition: opacity 160ms ease, transform 160ms ease;
+ pointer-events: none;
+}
+.pt-toast[data-open='1'] { opacity: 1; transform: translateX(-50%) translateY(0); }
+
+.pt-keys {
+ position: absolute;
+ right: var(--space-md);
+ top: 5.6rem;
+ z-index: 3;
+ padding: var(--space-sm) var(--space-md);
+ font-size: var(--text-2xs);
+ color: var(--ink-dim);
+ display: grid;
+ gap: 3px;
+ text-align: right;
+}
+@media (max-width: 720px), (pointer: coarse) { .pt-keys { display: none; } }
+@media (prefers-reduced-motion: reduce) {
+ .pt-door, .pt-toast, .pt-step__dot { transition: none; animation: none; }
+}
diff --git a/src/portal/render.js b/src/portal/render.js
new file mode 100644
index 000000000..c084543a0
--- /dev/null
+++ b/src/portal/render.js
@@ -0,0 +1,505 @@
+// Portal: the walkable renderer.
+//
+// Takes a PortalWorld (src/portal/layout.js) and builds a real place you can
+// walk through: districts you can see from the plaza, buildings sized by how
+// much a section says, doors you step into, billboards showing the page's own
+// images, and your avatar animated by the platform's universal clip library, so
+// any rig walks correctly rather than sliding around in a T-pose.
+//
+// The module owns WebGL and input and nothing else: it never fetches a site,
+// never parses HTML, and never decides what a world contains. It renders the
+// document it is handed and reports two things back, `door` (what you are
+// standing in front of) and `ready`, which is all the page needs to drive its
+// HUD.
+
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { AnimationManager } from '../animation-manager.js';
+import { collidersFor } from './layout.js';
+import { log } from '../shared/log.js';
+
+const AVATAR_URL = '/avatars/default.glb';
+const MANIFEST_URL = '/animations/manifest.json';
+const WALK_SPEED = 4.4;
+const RUN_SPEED = 8.2;
+const TURN_RATE = 9;
+const DOOR_REACH = 3.2;
+const EYE_HEIGHT = 1.55;
+
+const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
+const lerp = (a, b, t) => a + (b - a) * t;
+
+/** A label drawn to a canvas and hung in the world as a sprite. */
+function makeLabel(text, { color = '#ffffff', background = 'rgba(6,8,14,0.72)', size = 44, maxWidth = 640 } = {}) {
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
+ const font = `600 ${size}px "Inter", system-ui, sans-serif`;
+ ctx.font = font;
+ const text1 = String(text || '').slice(0, 64);
+ const width = Math.min(maxWidth, Math.ceil(ctx.measureText(text1).width) + size * 1.2);
+ canvas.width = width;
+ canvas.height = Math.ceil(size * 1.8);
+ const c = canvas.getContext('2d');
+ c.font = font;
+ c.textBaseline = 'middle';
+ c.fillStyle = background;
+ const r = canvas.height / 2;
+ c.beginPath();
+ c.roundRect(0, 0, canvas.width, canvas.height, r);
+ c.fill();
+ c.fillStyle = color;
+ c.fillText(text1, size * 0.6, canvas.height / 2, canvas.width - size * 1.2);
+ const texture = new THREE.CanvasTexture(canvas);
+ texture.colorSpace = THREE.SRGBColorSpace;
+ texture.anisotropy = 4;
+ const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: texture, transparent: true, depthWrite: false }));
+ sprite.scale.set((canvas.width / canvas.height) * 1.1, 1.1, 1);
+ sprite.userData.dispose = () => {
+ texture.dispose();
+ sprite.material.dispose();
+ };
+ return sprite;
+}
+
+/**
+ * Build and run a portal world.
+ * @param {{ canvas: HTMLCanvasElement, world: object, onDoor?: (door:object|null)=>void, onReady?: ()=>void }} opts
+ */
+export function createPortalWorld({ canvas, world, onDoor, onReady }) {
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(world.ground.sky);
+ scene.fog = new THREE.Fog(world.ground.fog, 34, world.ground.radius * 1.5);
+
+ const camera = new THREE.PerspectiveCamera(58, 1, 0.1, world.ground.radius * 4);
+ const disposables = [];
+ const track = (obj) => {
+ disposables.push(obj);
+ return obj;
+ };
+
+ // ── lighting ──────────────────────────────────────────────────────────────
+ const hemi = new THREE.HemisphereLight(world.palette.accent, world.ground.color, 1.15);
+ scene.add(hemi);
+ const sun = new THREE.DirectionalLight(0xfff3e0, 2.2);
+ sun.position.set(28, 46, 18);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ const shadowSpan = Math.min(70, world.ground.radius);
+ Object.assign(sun.shadow.camera, { left: -shadowSpan, right: shadowSpan, top: shadowSpan, bottom: -shadowSpan, near: 1, far: 160 });
+ sun.shadow.bias = -0.0008;
+ scene.add(sun);
+ scene.add(new THREE.AmbientLight(world.palette.secondary, 0.25));
+
+ // ── ground, plaza, roads ──────────────────────────────────────────────────
+ const groundGeo = track(new THREE.CircleGeometry(world.ground.radius, 96));
+ const groundMat = track(new THREE.MeshStandardMaterial({ color: world.ground.color, roughness: 0.96, metalness: 0.02 }));
+ const ground = new THREE.Mesh(groundGeo, groundMat);
+ ground.rotation.x = -Math.PI / 2;
+ ground.receiveShadow = true;
+ scene.add(ground);
+
+ const plazaGeo = track(new THREE.CircleGeometry(world.plaza.radius, 64));
+ const plazaMat = track(new THREE.MeshStandardMaterial({ color: world.palette.accent, roughness: 0.45, metalness: 0.25, transparent: true, opacity: 0.35 }));
+ const plaza = new THREE.Mesh(plazaGeo, plazaMat);
+ plaza.rotation.x = -Math.PI / 2;
+ plaza.position.y = 0.02;
+ plaza.receiveShadow = true;
+ scene.add(plaza);
+
+ // A road out to every district, so the city reads as connected from the air.
+ const roadMat = track(new THREE.MeshBasicMaterial({ color: world.palette.accent, transparent: true, opacity: 0.16 }));
+ for (const d of world.districts) {
+ const length = Math.hypot(d.x, d.z);
+ const geo = track(new THREE.PlaneGeometry(2.4, length));
+ const road = new THREE.Mesh(geo, roadMat);
+ road.rotation.x = -Math.PI / 2;
+ road.rotation.z = -Math.atan2(d.z, d.x) + Math.PI / 2;
+ road.position.set(d.x / 2, 0.015, d.z / 2);
+ scene.add(road);
+ }
+
+ // ── the monument: the page's own title, standing at the centre ────────────
+ const monumentGeo = track(new THREE.BoxGeometry(1.6, world.plaza.monument.h, 1.6));
+ const monumentMat = track(new THREE.MeshStandardMaterial({
+ color: world.palette.primary,
+ emissive: new THREE.Color(world.palette.primary).multiplyScalar(0.35),
+ roughness: 0.3,
+ metalness: 0.4,
+ }));
+ const monument = new THREE.Mesh(monumentGeo, monumentMat);
+ monument.position.y = world.plaza.monument.h / 2;
+ monument.castShadow = true;
+ scene.add(monument);
+ const titleLabel = makeLabel(world.plaza.monument.label, { size: 52 });
+ titleLabel.position.set(0, world.plaza.monument.h + 1.4, 0);
+ titleLabel.scale.multiplyScalar(2.1);
+ scene.add(titleLabel);
+ disposables.push({ dispose: () => titleLabel.userData.dispose() });
+
+ // ── buildings ─────────────────────────────────────────────────────────────
+ const edgeMat = track(new THREE.LineBasicMaterial({ color: world.palette.accent, transparent: true, opacity: 0.55 }));
+ for (const b of world.buildings) {
+ const geo = track(new THREE.BoxGeometry(b.w, b.h, b.d));
+ const mat = track(new THREE.MeshStandardMaterial({ color: b.color, roughness: 0.55, metalness: 0.2 }));
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.set(b.x, b.h / 2, b.z);
+ mesh.rotation.y = -b.rot;
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ mesh.userData.portal = { kind: 'building', id: b.id, label: b.label };
+ scene.add(mesh);
+
+ const edges = new THREE.LineSegments(track(new THREE.EdgesGeometry(geo)), edgeMat);
+ edges.position.copy(mesh.position);
+ edges.rotation.copy(mesh.rotation);
+ scene.add(edges);
+
+ // Floor bands read as storeys, so height means something at a glance.
+ for (let f = 1; f < b.floors; f++) {
+ const bandGeo = track(new THREE.BoxGeometry(b.w * 1.01, 0.06, b.d * 1.01));
+ const band = new THREE.Mesh(bandGeo, track(new THREE.MeshBasicMaterial({ color: world.palette.accent, transparent: true, opacity: 0.3 })));
+ band.position.set(b.x, (b.h / b.floors) * f, b.z);
+ band.rotation.y = -b.rot;
+ scene.add(band);
+ }
+
+ const label = makeLabel(b.label, { size: 40 });
+ label.position.set(b.x, b.h + 1.1, b.z);
+ label.scale.multiplyScalar(1.35);
+ scene.add(label);
+ disposables.push({ dispose: () => label.userData.dispose() });
+ }
+
+ // ── doors ─────────────────────────────────────────────────────────────────
+ const doorMeshes = [];
+ for (const d of world.doors) {
+ const geo = track(new THREE.PlaneGeometry(d.w, d.h));
+ const mat = track(new THREE.MeshStandardMaterial({
+ color: d.color,
+ emissive: new THREE.Color(d.color),
+ emissiveIntensity: 0.7,
+ roughness: 0.25,
+ side: THREE.DoubleSide,
+ transparent: true,
+ opacity: 0.92,
+ }));
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.set(d.x + Math.cos(d.yaw) * 0.06, d.h / 2, d.z + Math.sin(d.yaw) * 0.06);
+ mesh.rotation.y = -d.yaw + Math.PI / 2;
+ mesh.userData.door = d;
+ scene.add(mesh);
+ doorMeshes.push({ mesh, door: d, material: mat });
+
+ const label = makeLabel(d.label || new URL(d.href).host, { size: 34, color: d.internal ? '#eaf6ff' : '#ffeede' });
+ label.position.set(d.x, d.h + 0.75, d.z);
+ scene.add(label);
+ disposables.push({ dispose: () => label.userData.dispose() });
+ }
+
+ // ── billboards and monoliths ──────────────────────────────────────────────
+ const loaderTexture = new THREE.TextureLoader();
+ loaderTexture.setCrossOrigin('anonymous');
+ for (const p of world.props) {
+ if (p.kind === 'billboard') {
+ const geo = track(new THREE.PlaneGeometry(p.w, p.h));
+ const mat = track(new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide }));
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.set(p.x, p.h / 2 + 1.2, p.z);
+ mesh.rotation.y = -p.yaw + Math.PI / 2;
+ scene.add(mesh);
+ // The image is fetched through our own proxy: a foreign host that sends
+ // no CORS header would otherwise taint the texture and render black.
+ loaderTexture.load(
+ `/api/img?url=${encodeURIComponent(p.src)}`,
+ (tex) => {
+ tex.colorSpace = THREE.SRGBColorSpace;
+ mat.map = tex;
+ mat.needsUpdate = true;
+ disposables.push(tex);
+ },
+ undefined,
+ () => {
+ // An image we cannot read becomes its own alt text, which is more
+ // useful than a blank panel and is exactly what the page meant.
+ mat.color.set(p.color);
+ if (p.label) {
+ const alt = makeLabel(p.label, { size: 30 });
+ alt.position.set(p.x, p.h + 1.6, p.z);
+ scene.add(alt);
+ disposables.push({ dispose: () => alt.userData.dispose() });
+ }
+ },
+ );
+ const postGeo = track(new THREE.CylinderGeometry(0.09, 0.09, 1.2, 8));
+ const post = new THREE.Mesh(postGeo, track(new THREE.MeshStandardMaterial({ color: world.palette.monolith, roughness: 0.8 })));
+ post.position.set(p.x, 0.6, p.z);
+ post.castShadow = true;
+ scene.add(post);
+ } else if (p.kind === 'monolith') {
+ const geo = track(new THREE.BoxGeometry(p.w, p.h, p.w));
+ const mat = track(new THREE.MeshStandardMaterial({
+ color: p.color,
+ emissive: new THREE.Color(world.palette.accent).multiplyScalar(0.22),
+ roughness: 0.2,
+ metalness: 0.7,
+ }));
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.set(p.x, p.h / 2, p.z);
+ mesh.rotation.y = -p.yaw;
+ mesh.castShadow = true;
+ scene.add(mesh);
+ }
+ }
+
+ // ── the player ────────────────────────────────────────────────────────────
+ const player = new THREE.Group();
+ player.position.set(world.spawn.x, 0, world.spawn.z);
+ player.rotation.y = world.spawn.yaw;
+ scene.add(player);
+
+ // A designed stand-in that is visible from frame one, replaced the moment the
+ // rigged avatar loads. It is never the final state on a working connection,
+ // and it is a real body rather than an empty camera when the GLB cannot load.
+ const standInGeo = track(new THREE.CapsuleGeometry(0.32, 1.05, 6, 14));
+ const standInMat = track(new THREE.MeshStandardMaterial({
+ color: world.palette.accent,
+ emissive: new THREE.Color(world.palette.accent).multiplyScalar(0.4),
+ roughness: 0.35,
+ }));
+ const standIn = new THREE.Mesh(standInGeo, standInMat);
+ standIn.position.y = 0.85;
+ standIn.castShadow = true;
+ player.add(standIn);
+
+ const anim = new AnimationManager();
+ let avatarModel = null;
+ let moving = false;
+
+ (async () => {
+ try {
+ const [gltf, defs] = await Promise.all([
+ new GLTFLoader().loadAsync(AVATAR_URL),
+ fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])),
+ ]);
+ avatarModel = gltf.scene;
+ avatarModel.traverse((o) => {
+ if (o.isMesh) {
+ o.castShadow = true;
+ o.frustumCulled = false;
+ }
+ });
+ anim.setAvatarContext({ avatarUrl: AVATAR_URL });
+ anim.attach(avatarModel);
+ if (Array.isArray(defs) && defs.length) {
+ anim.setAnimationDefs(defs.filter((d) => d.name === 'idle' || d.name === 'walk'));
+ await anim.ensureLoaded('idle').catch(() => {});
+ await anim.ensureLoaded('walk').catch(() => {});
+ await anim.play('idle').catch(() => {});
+ }
+ player.remove(standIn);
+ player.add(avatarModel);
+ } catch (err) {
+ log.warn('[portal] avatar unavailable, keeping the stand-in:', err?.message || err);
+ } finally {
+ onReady?.();
+ }
+ })();
+
+ // ── input ─────────────────────────────────────────────────────────────────
+ const keys = new Set();
+ const onKeyDown = (e) => {
+ if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;
+ keys.add(e.code);
+ if (e.code === 'Enter' && nearDoor) activate();
+ if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(e.code)) e.preventDefault();
+ };
+ const onKeyUp = (e) => keys.delete(e.code);
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('keyup', onKeyUp);
+
+ let orbit = { yaw: world.spawn.yaw + Math.PI, pitch: 0.34, distance: 9.5 };
+ let dragging = false;
+ let lastPointer = { x: 0, y: 0 };
+ const onPointerDown = (e) => {
+ dragging = true;
+ lastPointer = { x: e.clientX, y: e.clientY };
+ canvas.setPointerCapture?.(e.pointerId);
+ };
+ const onPointerMove = (e) => {
+ if (!dragging) return;
+ orbit.yaw -= (e.clientX - lastPointer.x) * 0.006;
+ orbit.pitch = clamp(orbit.pitch + (e.clientY - lastPointer.y) * 0.004, -0.15, 1.05);
+ lastPointer = { x: e.clientX, y: e.clientY };
+ };
+ const onPointerUp = (e) => {
+ dragging = false;
+ canvas.releasePointerCapture?.(e.pointerId);
+ };
+ const onWheel = (e) => {
+ orbit.distance = clamp(orbit.distance + e.deltaY * 0.01, 4.2, 26);
+ e.preventDefault();
+ };
+ canvas.addEventListener('pointerdown', onPointerDown);
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ canvas.addEventListener('wheel', onWheel, { passive: false });
+
+ /** Touch and on-screen steering: set by the page's joystick, read by the loop. */
+ const stick = { x: 0, y: 0 };
+
+ // ── movement ──────────────────────────────────────────────────────────────
+ const colliders = collidersFor(world);
+ let nearDoor = null;
+ const velocity = new THREE.Vector3();
+
+ function inputVector() {
+ let x = stick.x;
+ let y = stick.y;
+ if (keys.has('KeyW') || keys.has('ArrowUp')) y -= 1;
+ if (keys.has('KeyS') || keys.has('ArrowDown')) y += 1;
+ if (keys.has('KeyA') || keys.has('ArrowLeft')) x -= 1;
+ if (keys.has('KeyD') || keys.has('ArrowRight')) x += 1;
+ const len = Math.hypot(x, y);
+ return len > 1 ? { x: x / len, y: y / len } : { x, y };
+ }
+
+ function resolveCollisions(next) {
+ for (const c of colliders) {
+ const dx = next.x - c.x;
+ const dz = next.z - c.z;
+ const dist = Math.hypot(dx, dz);
+ const min = c.r + 0.45;
+ if (dist < min && dist > 0.0001) {
+ next.x = c.x + (dx / dist) * min;
+ next.z = c.z + (dz / dist) * min;
+ }
+ }
+ const edge = world.ground.radius - 1.5;
+ const out = Math.hypot(next.x, next.z);
+ if (out > edge) {
+ next.x = (next.x / out) * edge;
+ next.z = (next.z / out) * edge;
+ }
+ return next;
+ }
+
+ function activate() {
+ if (nearDoor && onDoor) onDoor(nearDoor, 'activate');
+ }
+
+ const clock = new THREE.Clock();
+ let raf = 0;
+ let disposed = false;
+
+ function frame() {
+ if (disposed) return;
+ raf = requestAnimationFrame(frame);
+ const dt = Math.min(0.05, clock.getDelta());
+ const input = inputVector();
+ const running = keys.has('ShiftLeft') || keys.has('ShiftRight');
+ const speed = running ? RUN_SPEED : WALK_SPEED;
+
+ // Move relative to where the camera looks, which is what every player
+ // expects and what makes a third-person world feel like a place.
+ const forward = new THREE.Vector3(Math.sin(orbit.yaw), 0, Math.cos(orbit.yaw));
+ const right = new THREE.Vector3(forward.z, 0, -forward.x);
+ const wish = new THREE.Vector3()
+ .addScaledVector(forward, -input.y)
+ .addScaledVector(right, input.x);
+ const wishLen = wish.length();
+ if (wishLen > 0.001) wish.normalize();
+ velocity.lerp(wish.multiplyScalar(wishLen > 0.001 ? speed : 0), 1 - Math.exp(-12 * dt));
+
+ const next = resolveCollisions({
+ x: player.position.x + velocity.x * dt,
+ z: player.position.z + velocity.z * dt,
+ });
+ player.position.x = next.x;
+ player.position.z = next.z;
+
+ const wasMoving = moving;
+ moving = velocity.lengthSq() > 0.35;
+ if (moving) {
+ const target = Math.atan2(velocity.x, velocity.z);
+ let delta = target - player.rotation.y;
+ delta = Math.atan2(Math.sin(delta), Math.cos(delta));
+ player.rotation.y += delta * Math.min(1, TURN_RATE * dt);
+ }
+ if (moving !== wasMoving && avatarModel) {
+ anim.crossfadeTo(moving ? 'walk' : 'idle', 0.22).catch(() => {});
+ }
+ if (avatarModel) anim.setSpeed(running && moving ? 1.55 : 1);
+ anim.update?.(dt);
+
+ // Camera: behind the player, easing, never inside a wall it can avoid.
+ const camTarget = new THREE.Vector3(
+ player.position.x - Math.sin(orbit.yaw) * orbit.distance * Math.cos(orbit.pitch),
+ EYE_HEIGHT + orbit.distance * Math.sin(orbit.pitch) + 0.9,
+ player.position.z - Math.cos(orbit.yaw) * orbit.distance * Math.cos(orbit.pitch),
+ );
+ camera.position.lerp(camTarget, 1 - Math.exp(-9 * dt));
+ camera.lookAt(player.position.x, EYE_HEIGHT, player.position.z);
+
+ // Nearest door in reach, reported once per change.
+ let best = null;
+ let bestDist = DOOR_REACH;
+ for (const { door, material } of doorMeshes) {
+ const dist = Math.hypot(door.x - player.position.x, door.z - player.position.z);
+ material.emissiveIntensity = lerp(material.emissiveIntensity, dist < DOOR_REACH ? 1.9 : 0.7, 0.15);
+ if (dist < bestDist) {
+ best = door;
+ bestDist = dist;
+ }
+ }
+ if (best?.id !== nearDoor?.id) {
+ nearDoor = best;
+ onDoor?.(best, 'near');
+ }
+
+ titleLabel.position.y = world.plaza.monument.h + 1.4 + Math.sin(clock.elapsedTime * 1.4) * 0.08;
+ renderer.render(scene, camera);
+ }
+ frame();
+
+ function setSize(width, height) {
+ renderer.setSize(width, height, false);
+ camera.aspect = width / Math.max(1, height);
+ camera.updateProjectionMatrix();
+ }
+
+ return {
+ setSize,
+ activate,
+ get player() {
+ return { x: player.position.x, z: player.position.z, yaw: player.rotation.y };
+ },
+ get nearDoor() {
+ return nearDoor;
+ },
+ steer(x, y) {
+ stick.x = clamp(x, -1, 1);
+ stick.y = clamp(y, -1, 1);
+ },
+ dispose() {
+ disposed = true;
+ cancelAnimationFrame(raf);
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('keyup', onKeyUp);
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ canvas.removeEventListener('pointerdown', onPointerDown);
+ canvas.removeEventListener('wheel', onWheel);
+ anim.detach?.();
+ for (const d of disposables) d.dispose?.();
+ renderer.dispose();
+ },
+ };
+}