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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
IRL privacy/leaderboard/loom APIs, diorama + mirror modules, OG badges, MediaPipe vendor assets
nirholasedcac6ca6dd1
diff --git a/.env.example b/.env.exampleindex 21846f45e..6f7b5672c 100644--- a/.env.example+++ b/.env.example@@ -638,6 +638,22 @@ APP_ORIGIN=https://three.ws# Generate: openssl rand -base64 32CRON_SECRET=+# ── IRL proof-of-presence (epic IRL-Hardening H3) ────────────────────────────+# HMAC key that signs the short-lived proof-of-presence tokens minted by+# POST /api/irl/fix-token and verified on the GET /api/irl/pins nearby read+# (api/_lib/irl-presence.js). A token binds a nearby read to the coarse (~150 m)+# cell the caller actually had a GPS fix in, so a viewer can't browse pins at a+# location they aren't standing near.+#+# Enforcement is gated on this secret being set to a STRONG value (>= 16 chars):+# - SET in production: the nearby read REQUIRES a valid `x-irl-fix` token and+# fails CLOSED (401/403) when it's missing, expired, forged, or out of area.+# - UNSET (dev/preview): proof-of-presence is BYPASSED so local/sandbox testing+# isn't gated — the read works exactly as before. The active mode is logged+# once at cold start by both fix-token.js and pins.js.+# Production MUST set this. Generate: openssl rand -base64 32+IRL_FIX_SECRET=+# ── Upstash QStash (async work queue) ────────────────────────────────────────# Powers async knowledge ingest at /api/widgets/:id/knowledge-process. Without# QSTASH_TOKEN the publisher disables itself silently and large PDFs/URLs falldiff --git a/api/_lib/migrations/20260616235900_agent_identities_meta_skills.sql b/api/_lib/migrations/20260616235900_agent_identities_meta_skills.sqlnew file mode 100644index 000000000..9ef65518f--- /dev/null+++ b/api/_lib/migrations/20260616235900_agent_identities_meta_skills.sql@@ -0,0 +1,42 @@+-- Migration: declare agent_identities.meta and agent_identities.skills.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260616235900_agent_identities_meta_skills.sql+-- Idempotent — additive only, safe to re-run.+--+-- Every agent create path (api/agents.js:154 first-login bootstrap, :281 explicit+-- create) writes BOTH columns:+-- • meta — custodial wallet keys (encrypted_solana_secret / encrypted_wallet_key),+-- the public solana_address, the unified onchain block, persona,+-- payments, spend_limits, etc. Provisioning (api/_lib/agent-wallet.js+-- ensureAgentWallet/getOrCreateAgentSolanaWallet) and the task-01+-- wallet backfill (20260617000000_agent_wallet_backfill.sql) all+-- read/write meta->>'solana_address'.+-- • skills — the agent's skill list, bound as a RAW Postgres array by the driver+-- (no JSON.stringify) and queried with `skills @> '{…}'::text[]`+-- (api/agents/public.js:61), so the column MUST be text[], never jsonb.+--+-- The canonical bootstrap schema (api/_lib/schema.sql) historically never declared+-- either column; existing deployments only worked because they were hand-added+-- out-of-band. This migration converges every existing DB to the same shape the+-- (now-corrected) schema.sql produces on a fresh apply, so the manual deploy-order+-- dependency can never bite again. It adds NO data and changes NO behavior — it+-- only guarantees the columns the provisioning code already assumes.++begin;++-- meta: canonical jsonb blob. Default '{}' so a row inserted without meta (or a+-- legacy row predating the column) reads as an empty object, never NULL — every+-- meta->>'…' lookup in the wallet/onchain path stays null-safe.+alter table agent_identities add column if not exists meta jsonb not null default '{}'::jsonb;++-- skills: text[] (Postgres array), matching how api/agents.js binds it and how+-- api/agents/public.js filters it with `@> '{…}'::text[]`. Default '{}' = no skills.+alter table agent_identities add column if not exists skills text[] not null default '{}'::text[];++-- Document the meta contract for future readers (mirrors the richer note added by+-- 2026-04-29-onchain-unified.sql; harmless to set twice).+comment on column agent_identities.meta is+ 'jsonb. Custodial wallet (encrypted_solana_secret, solana_address, '+ 'encrypted_wallet_key), unified on-chain identity at meta.onchain, persona, '+ 'payments, and spend_limits. Secrets never leave the server.';++commit;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 9d963c824..5ee595d70 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -416,11 +416,26 @@ CREATE TABLE IF NOT EXISTS agent_identities (create index if not exists agent_identities_useron agent_identities(user_id) where deleted_at is null;-create index if not exists agent_identities_wallet- on agent_identities(wallet_address) where wallet_address is not null;-- Additive migrations for agent_identities columns added after initial deployment.alter table agent_identities add column if not exists wallet_address text;+-- Custodial wallet keys, on-chain identity, persona, payments, and the unified+-- meta.onchain block all live in `meta`; `skills` is the agent's text[] skill+-- list (read/written as a raw Postgres array — never jsonb — by api/agents.js+-- and queried with `skills @> '{…}'::text[]` in api/agents/public.js). Both+-- columns are written on EVERY create path (api/agents.js:154,281) and read by+-- the wallet/onchain provisioning, the task-01 backfill, and the custody+-- migration, yet the original CREATE TABLE above never declared them — a DB+-- bootstrapped purely from this file 500s on the first wallet write without+-- these two lines. Declare them idempotently here so a fresh apply is correct.+alter table agent_identities add column if not exists meta jsonb not null default '{}'::jsonb;+alter table agent_identities add column if not exists skills text[] not null default '{}'::text[];++-- Wallet-address index: created AFTER the column is guaranteed above so a fresh+-- apply never references a not-yet-added column (the original ordering indexed+-- wallet_address before its ADD and broke a clean-room bootstrap).+create index if not exists agent_identities_wallet+ on agent_identities(wallet_address) where wallet_address is not null;alter table agent_identities add column if not exists chain_id int;alter table agent_identities add column if not exists erc8004_agent_id bigint;alter table agent_identities add column if not exists erc8004_registry text;diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex d7aebfa5f..77d2bfbf4 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -185,6 +185,7 @@ export default wrap(async (req, res) => {FROM irl_pinsWHERE id = ${pinId}AND hidden_at IS NULL+ AND published IS NOT FALSEAND (expires_at IS NULL OR expires_at > NOW())LIMIT 1`;diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 161978fbc..baee77e94 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -407,6 +407,22 @@ async function ensureTable() {await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS origin_lng DOUBLE PRECISION`;await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS origin_yaw_deg DOUBLE PRECISION`;await sql`CREATE INDEX IF NOT EXISTS irl_pins_room ON irl_pins (room_id) WHERE room_id IS NOT NULL AND hidden_at IS NULL`;+ // Placement consent + approximate placement (H4). A placer chooses whether the+ // agent sits at their EXACT spot ('precise') or is deliberately blurred to a+ // random point within fuzz_radius_m of it ('approximate') — so a user can share+ // "an agent near here" without pinning their precise real-world location. The+ // CLIENT computes the fuzzed lat/lng it sends; the server stores the consent ++ // the radius it was blurred by, so the choice is auditable (the privacy center+ // surfaces it) and the dashboard can show "placed approximately (±Nm)". A legacy+ // pin with neither column set reads as a 'precise' placement (the prior default).+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS placement_kind TEXT`;+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS fuzz_radius_m DOUBLE PRECISION`;+ // Privacy center (H5). `published` is the owner-controlled visibility flag: an+ // unpublished pin is suppressed from EVERY public nearby read (and stops+ // accepting new interactions) while the owner keeps the row to republish later+ // — distinct from hidden_at (moderation) and expiry (lifetime). DEFAULT TRUE so+ // every existing + future placement is public unless the owner unpublishes it.+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS published BOOLEAN NOT NULL DEFAULT TRUE`;_tableReady = true;}@@ -426,6 +442,17 @@ const CAL_MAX_RISE_M = 3; // floor-height nudge ceiling, metresconst ROOM_ID_RE = /^[a-z0-9-]{1,64}$/;const REL_MAX_M = 500;+// ── Placement consent (H4) ──────────────────────────────────────────────────+// 'precise' pins the agent at the placer's exact spot; 'approximate' blurs it to+// a random point within fuzz_radius_m of the real spot (the CLIENT computes the+// fuzzed coordinate it sends — the server only stores the consent + the radius it+// was blurred by). The radius is clamped to a sane band: below FUZZ_MIN_M the blur+// is pointless (under GPS error), above FUZZ_MAX_M it stops being "near here". A+// missing/invalid placement reads as 'precise' so old clients are unaffected.+const PLACEMENT_KINDS = new Set(['precise', 'approximate']);+const FUZZ_MIN_M = 10; // below this the blur is within GPS error — meaningless+const FUZZ_MAX_M = 500; // above this it stops meaning "an agent near here"+// Pin ids are server-minted UUIDs (gen_random_uuid()). Validate the format at the// top of every mutation path so an oversized / garbage id is a clean 400 and never// reaches the DB query or a log line. The SQL is already parameterized (this is@@ -777,6 +804,7 @@ export default wrap(async (req, res) => {WHERE lat BETWEEN ${lat - latDelta} AND ${lat + latDelta}AND lng BETWEEN ${lng - lngDelta} AND ${lng + lngDelta}AND hidden_at IS NULL+ AND published IS NOT FALSEAND (expires_at IS NULL OR expires_at > NOW())ORDER BY placed_at DESCLIMIT 50@@ -1004,13 +1032,27 @@ export default wrap(async (req, res) => {const originYawV = roomOk && Number.isFinite(room.originYawDeg)? ((room.originYawDeg % 360) + 360) % 360 : null;+ // Placement consent (H4) — record whether the placer pinned their exact spot+ // or deliberately blurred it. The client computes the fuzzed lat/lng it sends;+ // we store the consent kind + the radius the blur used. An 'approximate' pin+ // must carry a fuzz radius (clamped to the sane band); a missing/invalid+ // placement (or an old client that sends neither) defaults to 'precise' with+ // no radius, so behaviour is unchanged for every existing caller.+ const rawKind = String(body.placementKind ?? body.placement_kind ?? '').toLowerCase();+ const placementKind = PLACEMENT_KINDS.has(rawKind) ? rawKind : 'precise';+ const rawFuzz = Number(body.fuzzRadiusM ?? body.fuzz_radius_m);+ const fuzzRadiusM = placementKind === 'approximate' && Number.isFinite(rawFuzz)+ ? Math.min(FUZZ_MAX_M, Math.max(FUZZ_MIN_M, rawFuzz))+ : null;+const [pin] = await sql`INSERT INTO irl_pins(user_id, agent_id, device_token, lat, lng, heading,avatar_url, avatar_name, caption, x402_endpoint, expires_at,anchor_height_m, anchor_yaw_deg, anchor_quat,gps_accuracy_m, altitude_m, anchor_source, geocell7,- room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg)+ room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,+ placement_kind, fuzz_radius_m)VALUES (${userId},${body.agentId ?? null},@@ -1034,7 +1076,9 @@ export default wrap(async (req, res) => {${relNorthM},${originLatV},${originLngV},- ${originYawV}+ ${originYawV},+ ${placementKind},+ ${fuzzRadiusM})RETURNING *`;diff --git a/api/irl/privacy.js b/api/irl/privacy.jsnew file mode 100644index 000000000..28bf9513e--- /dev/null+++ b/api/irl/privacy.js@@ -0,0 +1,343 @@+/**+ * IRL privacy center — visibility, export, delete / forget device (H5).+ *+ * The control surface behind /irl's "Privacy & my data". Every caller — signed-in+ * or anonymous — gets full sight of and full control over the location data /irl+ * holds about them: see what's stored, temporarily UNPUBLISH a pin, DELETE one,+ * remove EVERYTHING, EXPORT it, and FORGET THIS DEVICE (purge every row tied to+ * the anonymous device token, including taps/messages it left on others' pins).+ * This is right-to-be-forgotten as a product, not a support ticket.+ *+ * GET /api/irl/privacy → plain-language data summary (caller's own)+ * GET /api/irl/privacy?export=1 → full JSON of the caller's own pins + interactions+ * PATCH /api/irl/privacy { pinId, action:'unpublish'|'republish' }+ * DELETE /api/irl/privacy { scope:'pin'|'all'|'device', pinId? } → { deletedPins, deletedInteractions }+ *+ * ── Identity & ownership ──────────────────────────────────────────────────────+ * Auth (session user_id) OR the anonymous device token, which — per H2 — arrives+ * in the `x-irl-device` HEADER (body for mutations), NEVER a URL query string.+ * `readDeviceToken` null-guards an empty/whitespace token to null so it can never+ * become a SQL clause that matches another owner's NULL/empty-token rows. Every+ * owner clause is independently null-guarded exactly like the existing DELETE in+ * pins.js: a missing identifier matches nothing.+ *+ * ── Cascade (H6 on demand) ────────────────────────────────────────────────────+ * Deleting a pin orphans its `irl_interactions` (each row snapshots the pin's+ * lat/lng + a viewer_device — a "device X was at coordinate Y at time T" trail).+ * Every delete path here removes those dependent rows in the same request so the+ * trail never outlives the placement. `scope:'device'` goes further: it also+ * purges interactions this device AUTHORED on OTHER people's pins (viewer_device),+ * so the device id is genuinely forgotten — a subsequent summary returns empty.+ *+ * No new columns: unpublish reuses the existing `hidden_at` moderation column (a+ * hidden pin is already filtered out of every nearby/mine read). This endpoint+ * NEVER returns another user's coordinates — only the caller's own data.+ */++import { cors, json, wrap, rateLimited } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { readDeviceToken } from '../_lib/irl-auth.js';+import { isValidPinId } from './pins.js';++const SCOPES = new Set(['pin', 'all', 'device']);+const ACTIONS = new Set(['unpublish', 'republish']);++// Resolve the caller as { userId, deviceToken } with both arms null-guarded. A+// caller must present at least one identifier; a bare anonymous request (no+// session, no device token) owns nothing and is rejected before any query runs.+async function resolveOwner(req) {+ const session = await getSessionUser(req).catch(() => null);+ const userId = session?.id ?? null;+ const deviceToken = readDeviceToken(req); // null for empty/whitespace+ return { userId, deviceToken };+}++// The literal, plain-language inventory of what a pin/interaction row stores —+// shown verbatim in the UI so the summary copy and the actual data never diverge.+function storedItems({ hasPins, hasInteractions, precise }) {+ const items = [];+ if (hasPins) {+ items.push(+ precise+ ? 'The exact coordinates of each spot where you placed an agent.'+ : 'The approximate coordinates of each spot where you placed an agent.',+ );+ items.push('The avatar, name and caption you gave each placed agent.');+ }+ items.push('An anonymous device id that ties your placements on this device together.');+ if (hasInteractions) {+ items.push('Taps, views, payments and any messages left on your placed agents — including where each encounter happened.');+ }+ return items;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: ['GET', 'PATCH', 'DELETE', 'OPTIONS'] })) return;++ // Reuse the placement limiter: this surface creates/edits/deletes placements,+ // so it belongs in the heavier irl:pin bucket, not the public read bucket. Fail+ // closed on the destructive verbs is unnecessary (a denied delete is just a+ // retry), so a limiter wobble degrades to a retryable 429 rather than blocking.+ const rl = await limits.irlPinIp(clientIp(req)).catch(() => ({ success: true }));+ if (!rl.success) return rateLimited(res, rl);++ const { userId, deviceToken } = await resolveOwner(req);+ if (!userId && !deviceToken) {+ return json(res, 400, { error: 'sign in or send the x-irl-device header' });+ }++ if (req.method === 'GET') {+ // Export = the same data the summary describes, in full. Honest and complete.+ if (req.query?.export === '1' || req.query?.export === 'true') {+ return handleExport(res, { userId, deviceToken });+ }+ return handleSummary(res, { userId, deviceToken, anonymous: !userId });+ }++ if (req.method === 'PATCH') {+ return handleVisibility(res, { userId, deviceToken, body: req.body ?? {} });+ }++ if (req.method === 'DELETE') {+ return handleDelete(res, { userId, deviceToken, body: req.body ?? {} });+ }++ return json(res, 405, { error: 'method not allowed' });+});++// ── GET — plain-language data summary (the caller's own data only) ────────────+async function handleSummary(res, { userId, deviceToken, anonymous }) {+ // One scan over the caller's OWN pins. Every arm is null-guarded so a missing+ // identifier can never widen the match to another owner's rows. Unpublished+ // (hidden_at) pins ARE counted here — they're the caller's data, just invisible+ // to others — so the summary reflects everything stored, not just what's live.+ const [pinAgg] = await sql`+ SELECT+ COUNT(*)::int AS total,+ COUNT(*) FILTER (WHERE hidden_at IS NOT NULL)::int AS unpublished,+ COUNT(*) FILTER (WHERE expires_at IS NULL)::int AS permanent,+ MIN(placed_at) AS oldest,+ MAX(placed_at) AS newest,+ MIN(expires_at) FILTER (WHERE expires_at IS NOT NULL) AS next_expiry+ FROM irl_pins+ WHERE ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (${deviceToken}::text IS NOT NULL AND device_token = ${deviceToken}))+ `;++ // Interactions LEFT ON the caller's own pins (their inbox).+ const [onMineAgg] = await sql`+ SELECT COUNT(*)::int AS total+ FROM irl_interactions ix+ JOIN irl_pins p ON p.id = ix.pin_id+ WHERE ((${userId}::uuid IS NOT NULL AND p.user_id = ${userId}::uuid)+ OR (${deviceToken}::text IS NOT NULL AND p.device_token = ${deviceToken}))+ `;++ // Interactions THIS DEVICE authored on anyone's pins (the trail it left). Keyed+ // on viewer_device, so it only applies to the anonymous device-token caller.+ const [authoredAgg] = deviceToken+ ? await sql`+ SELECT COUNT(*)::int AS total+ FROM irl_interactions+ WHERE viewer_device IS NOT NULL AND viewer_device = ${deviceToken}+ `+ : [{ total: 0 }];++ const pinTotal = pinAgg?.total ?? 0;+ const onMine = onMineAgg?.total ?? 0;+ const authored = authoredAgg?.total ?? 0;+ const permanent = pinAgg?.permanent ?? 0;++ return json(res, 200, {+ summary: {+ pins: {+ total: pinTotal,+ published: pinTotal - (pinAgg?.unpublished ?? 0),+ unpublished: pinAgg?.unpublished ?? 0,+ permanent, // never auto-expire (signed-in)+ expiring: pinTotal - permanent, // auto-expire (anonymous)+ oldest: pinAgg?.oldest ?? null,+ newest: pinAgg?.newest ?? null,+ },+ interactions: {+ onYourPins: onMine, // your inbox+ youLeftElsewhere: authored, // your trail on others' pins+ },+ // Anonymous device pins auto-expire (7 days); the next one to go is the+ // soonest expires_at. Signed-in pins are permanent until removed.+ retention: {+ anonymousPinsExpireInDays: 7,+ interactionsExpireInDays: 180,+ nextPinExpiry: pinAgg?.next_expiry ?? null,+ },+ account: anonymous ? 'anonymous-device' : 'signed-in',+ stored: storedItems({ hasPins: pinTotal > 0, hasInteractions: onMine > 0 || authored > 0, precise: true }),+ },+ });+}++// ── GET ?export=1 — full JSON download of the caller's own data ───────────────+async function handleExport(res, { userId, deviceToken }) {+ const pins = await sql`+ SELECT id, agent_id, lat, lng, heading, avatar_name, avatar_url, caption,+ x402_endpoint, placed_at, expires_at, hidden_at, view_count,+ gps_accuracy_m, altitude_m, anchor_source+ FROM irl_pins+ WHERE ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (${deviceToken}::text IS NOT NULL AND device_token = ${deviceToken}))+ ORDER BY placed_at DESC+ LIMIT 1000+ `;++ // Interactions on the caller's pins (their inbox).+ const received = await sql`+ SELECT ix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,+ ix.lat, ix.lng, ix.amount, ix.currency_mint, ix.created_at, ix.seen_at+ FROM irl_interactions ix+ JOIN irl_pins p ON p.id = ix.pin_id+ WHERE ((${userId}::uuid IS NOT NULL AND p.user_id = ${userId}::uuid)+ OR (${deviceToken}::text IS NOT NULL AND p.device_token = ${deviceToken}))+ ORDER BY ix.created_at DESC+ LIMIT 1000+ `;++ // Interactions THIS device left on anyone's pins (its outbound trail).+ const authored = deviceToken+ ? await sql`+ SELECT id, pin_id, agent_id, type, message, lat, lng, created_at+ FROM irl_interactions+ WHERE viewer_device IS NOT NULL AND viewer_device = ${deviceToken}+ ORDER BY created_at DESC+ LIMIT 1000+ `+ : [];++ const payload = {+ exportedAt: new Date().toISOString(),+ account: userId ? 'signed-in' : 'anonymous-device',+ pins,+ interactionsOnYourPins: received,+ interactionsYouLeft: authored,+ };+ return json(res, 200, payload, {+ 'content-disposition': 'attachment; filename="irl-my-data.json"',+ });+}++// ── PATCH — owner-initiated unpublish / republish (reuses hidden_at) ──────────+async function handleVisibility(res, { userId, deviceToken, body }) {+ const pinId = body.pinId;+ const action = body.action;+ if (!isValidPinId(pinId)) return json(res, 400, { error: 'valid pinId required' });+ if (!ACTIONS.has(action)) return json(res, 400, { error: "action must be 'unpublish' or 'republish'" });++ // Owner-scoped, null-guarded WHERE — an attacker with the wrong token/session+ // matches no row and so toggles nothing (RETURNING empty → 404). Unpublish sets+ // hidden_at = NOW() (invisible to every reader); republish clears it back to NULL.+ // Neon's tagged template doesn't compose a nested sql`NOW()` fragment, so the+ // two directions are two explicit queries rather than a spliced value.+ const hide = action === 'unpublish';+ const [row] = hide+ ? await sql`+ UPDATE irl_pins+ SET hidden_at = NOW()+ WHERE id = ${pinId}+ AND (expires_at IS NULL OR expires_at > NOW())+ AND ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ RETURNING id, hidden_at`+ : await sql`+ UPDATE irl_pins+ SET hidden_at = NULL+ WHERE id = ${pinId}+ AND (expires_at IS NULL OR expires_at > NOW())+ AND ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ RETURNING id, hidden_at`;+ if (!row) return json(res, 404, { error: 'pin not found or not yours' });+ return json(res, 200, { ok: true, pinId: row.id, hidden: row.hidden_at != null });+}++// ── DELETE — pin | all | device, cascading to irl_interactions ────────────────+async function handleDelete(res, { userId, deviceToken, body }) {+ const scope = body.scope;+ if (!SCOPES.has(scope)) {+ return json(res, 400, { error: "scope must be 'pin', 'all' or 'device'" });+ }++ if (scope === 'pin') {+ const pinId = body.pinId;+ if (!isValidPinId(pinId)) return json(res, 400, { error: 'valid pinId required' });++ // Cascade first: remove the interactions snapshotting THIS pin's location, but+ // only when the caller owns the pin — the subquery is owner-scoped and+ // null-guarded so a stranger's request deletes nothing. Then delete the pin+ // itself under the same gate.+ const deletedInteractions = await sql`+ DELETE FROM irl_interactions+ WHERE pin_id = ${pinId}+ AND pin_id IN (+ SELECT id FROM irl_pins+ WHERE id = ${pinId}+ AND ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ )+ RETURNING id+ `;+ const deletedPins = await sql`+ DELETE FROM irl_pins+ WHERE id = ${pinId}+ AND ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ RETURNING id+ `;+ if (!deletedPins.length) return json(res, 404, { error: 'pin not found or not yours' });+ return json(res, 200, {+ ok: true,+ deletedPins: deletedPins.length,+ deletedInteractions: deletedInteractions.length,+ });+ }++ // scope: 'all' and 'device' both wipe every pin this caller owns + the inbox on+ // them. 'device' additionally purges the trail this device left elsewhere.+ const deletedInbox = await sql`+ DELETE FROM irl_interactions+ WHERE pin_id IN (+ SELECT id FROM irl_pins+ WHERE ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ )+ RETURNING id+ `;+ const deletedPins = await sql`+ DELETE FROM irl_pins+ WHERE ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))+ RETURNING id+ `;++ let deletedAuthored = 0;+ if (scope === 'device') {+ // "Forget this device" — also drop every interaction this device authored on+ // OTHER people's pins, so no row references the device id anywhere. Strictly+ // keyed on a non-empty viewer_device: an empty/NULL token matches nothing.+ if (deviceToken) {+ const rows = await sql`+ DELETE FROM irl_interactions+ WHERE viewer_device IS NOT NULL AND viewer_device = ${deviceToken}+ RETURNING id+ `;+ deletedAuthored = rows.length;+ }+ }++ return json(res, 200, {+ ok: true,+ scope,+ deletedPins: deletedPins.length,+ deletedInteractions: deletedInbox.length + deletedAuthored,+ });+}diff --git a/api/leaderboard.js b/api/leaderboard.jsnew file mode 100644index 000000000..f9353cfb7--- /dev/null+++ b/api/leaderboard.js@@ -0,0 +1,172 @@+// GET /api/leaderboard — public $THREE holder leaderboard (clean, paginated)+// --------------------------------------------------------------------------+// The canonical holder board for /leaderboard's "$THREE Holders" view. It wraps+// the real Helius DAS holder scan (api/_lib/coin/holders.js) and the live market+// module (price / supply / holder count), then derives a holder TIER from each+// wallet's on-chain balance so the page can render badges and gate the 3D PFP+// generator without re-deriving thresholds client-side.+//+// Query params:+// ?limit=<1..100> page size (default 50)+// ?offset=<n> page offset (default 0)+// ?wallet=<base58> optional — also returns this wallet's own rank + tier even+// when it falls outside the requested page, so a connected+// holder always sees "you are #N".+//+// Response:+// {+// holders: [{ rank, wallet, wallet_short, amount, pct_of_supply, tier }],+// total, limit, offset, supply, mint, decimals,+// tiers: [{ id, label, min, accent }], // tier ladder (for the legend)+// market: { price_usd, market_cap, holders }, // live, for the header strip+// you: { rank, amount, pct_of_supply, tier } | null,+// ts+// }+//+// Never 500s a public board: a Helius outage / missing key returns an empty,+// well-formed board so the page renders its empty state instead of an error.++import { cors, json, method, wrap } from './_lib/http.js';+import { TOKEN_MINT as THREE_MINT } from './_lib/token/config.js';+import { fetchTokenMarketData } from './_lib/market/token-market.js';+import { fetchHolderBalances } from './_lib/coin/holders.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// $THREE holder tier ladder — derived purely from on-chain balance. Thresholds+// ascend by ~10× so the tiers read as clear membership bands (whole-token+// amounts). The same ladder is mirrored in public/leaderboard-holders.js (badge+// styling) and api/og-leaderboard.js (share-card accent) so a holder's tier is+// consistent across the board, the 3D badge, and the OG card.+const HOLDER_TIERS = [+ { id: 'genesis', label: 'Genesis', min: 10_000_000, accent: '#f5d0a9' },+ { id: 'diamond', label: 'Diamond', min: 1_000_000, accent: '#7dd3fc' },+ { id: 'platinum', label: 'Platinum', min: 100_000, accent: '#c4b5fd' },+ { id: 'gold', label: 'Gold', min: 10_000, accent: '#fbbf24' },+ { id: 'silver', label: 'Silver', min: 1_000, accent: '#cbd5e1' },+ { id: 'bronze', label: 'Bronze', min: 1, accent: '#d8a07a' },+ { id: 'none', label: 'Not holding', min: 0, accent: '#6b7280' },+];++function tierForBalance(amount) {+ const n = Number(amount) || 0;+ for (const t of HOLDER_TIERS) {+ if (n >= t.min && t.min > 0) return t;+ }+ return HOLDER_TIERS[HOLDER_TIERS.length - 1];+}++function shortWallet(addr) {+ const s = String(addr || '');+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit')) || 50));+ const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);+ const wallet = (url.searchParams.get('wallet') || '').trim();+ const wantWallet = BASE58_RE.test(wallet) ? wallet : null;++ const tiers = HOLDER_TIERS.map((t) => ({ id: t.id, label: t.label, min: t.min, accent: t.accent }));++ try {+ // Real holder set (every $THREE holder across both token programs) + live+ // market data for supply → % of supply and the header price strip. Both are+ // independently resilient: a market blip just nulls the percentages.+ const [balances, market] = await Promise.all([+ fetchHolderBalances({ mint: THREE_MINT }),+ fetchTokenMarketData(THREE_MINT).catch(() => null),+ ]);++ const decimals = Number(market?.decimals ?? 6);+ const atomicsPerToken = 10 ** decimals;+ const supply = market?.supply != null ? Number(market.supply) : null;++ // Rank by exact atomic balance (BigInt) so whales past Number's 2^53 ceiling+ // still order correctly; convert to display Number only for emitted rows.+ const ranked = [...balances.entries()]+ .filter(([, atomic]) => atomic > 0n)+ .sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0));++ const total = ranked.length;+ const toRow = (entry, idx) => {+ const [w, atomic] = entry;+ const amount = Number(atomic) / atomicsPerToken;+ return {+ rank: idx + 1,+ wallet: w,+ wallet_short: shortWallet(w),+ amount,+ pct_of_supply: supply ? amount / supply : null,+ tier: tierForBalance(amount).id,+ };+ };++ const holders = ranked+ .slice(offset, offset + limit)+ .map((entry, i) => toRow(entry, offset + i));++ // Connected wallet's own standing — even outside the page window.+ let you = null;+ if (wantWallet) {+ const idx = ranked.findIndex(([w]) => w === wantWallet);+ if (idx >= 0) {+ const row = toRow(ranked[idx], idx);+ you = { rank: row.rank, amount: row.amount, pct_of_supply: row.pct_of_supply, tier: row.tier };+ } else {+ you = { rank: null, amount: 0, pct_of_supply: 0, tier: tierForBalance(0).id };+ }+ }++ return json(+ res,+ 200,+ {+ holders,+ total,+ limit,+ offset,+ supply,+ mint: THREE_MINT,+ decimals,+ tiers,+ market: market+ ? {+ price_usd: market.price_usd ?? null,+ market_cap: market.market_cap ?? null,+ holders: market.holders ?? null,+ }+ : null,+ you,+ ts: Date.now(),+ },+ // Holder sets change slowly; the Helius scan is seconds + thousands of+ // accounts, so cache at the edge and run it at most ~once a minute.+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },+ );+ } catch (err) {+ console.error('[leaderboard]', err?.message || err);+ return json(+ res,+ 200,+ {+ holders: [],+ total: 0,+ limit,+ offset,+ supply: null,+ mint: THREE_MINT,+ decimals: 6,+ tiers,+ market: null,+ you: wantWallet ? { rank: null, amount: 0, pct_of_supply: 0, tier: tierForBalance(0).id } : null,+ ts: Date.now(),+ },+ { 'cache-control': 'public, s-maxage=30' },+ );+ }+});diff --git a/api/loom.js b/api/loom.jsnew file mode 100644index 000000000..60cbe335bBinary files /dev/null and b/api/loom.js differdiff --git a/api/og-leaderboard.js b/api/og-leaderboard.jsnew file mode 100644index 000000000..52eb980da--- /dev/null+++ b/api/og-leaderboard.js@@ -0,0 +1,251 @@+// api/og-leaderboard.js — dynamic Open Graph / share image for the $THREE+// holder leaderboard. Renders a real 1200×630 PNG (not SVG: X, Facebook,+// LinkedIn and iMessage do not preview image/svg+xml cards) via @vercel/og's+// ImageResponse on the Node runtime — the same proven path as api/page-og.js.+//+// Two modes, both fed by real data:+// • Board card /api/og-leaderboard+// Top $THREE holders by on-chain balance + live price/market cap.+// • Holder card /api/og-leaderboard?wallet=<base58>+// A single holder's rank, balance, tier and % of supply — the "I'm a+// Diamond holder, ranked #12" flex that drives the share flywheel.+//+// Data sources (real, server-side, cached at the edge):+// • Holder set + ranks → /api/leaderboard (Helius DAS scan)+// • Live price / market cap → token market module (Birdeye → Dexscreener → Gecko)+//+// Cached aggressively (s-maxage=1h) so the card is generated at most once per+// hour per variant rather than per crawl.++import { ImageResponse } from '@vercel/og';+import { TOKEN_MINT as THREE_MINT } from './_lib/token/config.js';+import { fetchTokenMarketData } from './_lib/market/token-market.js';+import { fetchHolderBalances } from './_lib/coin/holders.js';++const WIDTH = 1200;+const HEIGHT = 630;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const HOLDER_TIERS = [+ { id: 'genesis', label: 'Genesis', min: 10_000_000, accent: '#f5d0a9' },+ { id: 'diamond', label: 'Diamond', min: 1_000_000, accent: '#7dd3fc' },+ { id: 'platinum', label: 'Platinum', min: 100_000, accent: '#c4b5fd' },+ { id: 'gold', label: 'Gold', min: 10_000, accent: '#fbbf24' },+ { id: 'silver', label: 'Silver', min: 1_000, accent: '#cbd5e1' },+ { id: 'bronze', label: 'Bronze', min: 1, accent: '#d8a07a' },+ { id: 'none', label: 'Not holding', min: 0, accent: '#6b7280' },+];+function tierForBalance(amount) {+ const n = Number(amount) || 0;+ for (const t of HOLDER_TIERS) if (n >= t.min && t.min > 0) return t;+ return HOLDER_TIERS[HOLDER_TIERS.length - 1];+}++function shortWallet(addr) {+ const s = String(addr || '');+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}+function fmtAmount(n) {+ const v = Number(n) || 0;+ if (v >= 1e9) return `${(v / 1e9).toFixed(2)}B`;+ if (v >= 1e6) return `${(v / 1e6).toFixed(2)}M`;+ if (v >= 1e3) return `${(v / 1e3).toFixed(1)}K`;+ return v.toLocaleString('en-US', { maximumFractionDigits: 0 });+}+function fmtUsd(n) {+ const v = Number(n);+ if (!Number.isFinite(v) || v <= 0) return null;+ if (v >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;+ if (v >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;+ if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;+ if (v < 0.01) return `$${v.toPrecision(2)}`;+ return `$${v.toFixed(2)}`;+}++// Build the ranked holder list + market context once, shared by both card modes.+async function loadBoard() {+ const [balances, market] = await Promise.all([+ fetchHolderBalances({ mint: THREE_MINT }).catch(() => new Map()),+ fetchTokenMarketData(THREE_MINT).catch(() => null),+ ]);+ const decimals = Number(market?.decimals ?? 6);+ const per = 10 ** decimals;+ const supply = market?.supply != null ? Number(market.supply) : null;+ const ranked = [...balances.entries()]+ .filter(([, a]) => a > 0n)+ .sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0))+ .map(([wallet, atomic], i) => {+ const amount = Number(atomic) / per;+ return { rank: i + 1, wallet, amount, pct: supply ? amount / supply : null };+ });+ return { ranked, market, supply };+}++const FOOTER = (accent) => ({+ type: 'div',+ props: {+ style: {+ position: 'absolute', left: 0, right: 0, bottom: 0, height: 56,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '0 56px', background: '#030305',+ borderTop: '1px solid rgba(255,255,255,0.06)',+ },+ children: [+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', fontSize: 20, fontWeight: 700, color: 'rgba(235,235,245,0.55)', letterSpacing: '0.04em' }, children: [+ { type: 'div', props: { style: { width: 10, height: 10, borderRadius: 10, background: accent, marginRight: 14 } } },+ { type: 'div', props: { children: 'THREE.WS · $THREE HOLDER LEADERBOARD' } },+ ] } },+ { type: 'div', props: { style: { fontSize: 20, fontWeight: 600, color: 'rgba(235,235,245,0.35)' }, children: 'three.ws/leaderboard' } },+ ],+ },+});++function baseShell(accent, children) {+ return {+ type: 'div',+ props: {+ style: {+ width: '100%', height: '100%', display: 'flex', flexDirection: 'column',+ position: 'relative', background: '#06060b', color: '#f5f5fa',+ fontFamily: 'ui-sans-serif, system-ui, sans-serif',+ },+ children: [+ { type: 'div', props: { style: { position: 'absolute', top: 0, left: 0, width: 520, height: 520, background: `radial-gradient(circle at 0% 0%, ${accent}33, transparent 70%)`, display: 'flex' } } },+ { type: 'div', props: { style: { position: 'absolute', top: 0, left: 0, width: 6, height: '100%', background: accent, display: 'flex' } } },+ ...children,+ FOOTER(accent),+ ],+ },+ };+}++function statPill(label, value, accent) {+ return {+ type: 'div',+ props: {+ style: { display: 'flex', flexDirection: 'column', gap: 6 },+ children: [+ { type: 'div', props: { style: { fontSize: 22, color: 'rgba(235,235,245,0.45)', letterSpacing: '0.04em', textTransform: 'uppercase' }, children: label } },+ { type: 'div', props: { style: { fontSize: 40, fontWeight: 800, color: value === '—' ? 'rgba(235,235,245,0.4)' : accent }, children: value } },+ ],+ },+ };+}++function holderCard(holder, market) {+ const tier = tierForBalance(holder?.amount || 0);+ const accent = tier.accent;+ const price = fmtUsd(market?.price_usd);+ const usdValue = market?.price_usd ? fmtUsd((holder?.amount || 0) * market.price_usd) : null;+ return baseShell(accent, [+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', padding: '64px 64px 0', flex: 1 }, children: [+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', gap: 18, marginBottom: 8 }, children: [+ { type: 'div', props: { style: { fontSize: 24, fontWeight: 700, letterSpacing: '0.16em', color: 'rgba(235,235,245,0.5)' }, children: '$THREE HOLDER' } },+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', padding: '6px 18px', borderRadius: 999, fontSize: 24, fontWeight: 800, color: '#06060b', background: accent }, children: tier.label.toUpperCase() } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', alignItems: 'baseline', gap: 24, marginTop: 18 }, children: [+ { type: 'div', props: { style: { fontSize: 150, fontWeight: 900, lineHeight: 1, color: accent }, children: holder?.rank ? `#${holder.rank}` : '—' } },+ { type: 'div', props: { style: { fontSize: 40, fontWeight: 600, color: 'rgba(235,235,245,0.55)' }, children: shortWallet(holder?.wallet) } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', gap: 64, marginTop: 56 }, children: [+ statPill('Balance', `${fmtAmount(holder?.amount || 0)} $THREE`, accent),+ statPill('Value', usdValue || '—', accent),+ statPill('% of supply', holder?.pct != null ? `${(holder.pct * 100).toFixed(holder.pct < 0.001 ? 4 : 2)}%` : '—', accent),+ statPill('$THREE price', price || '—', accent),+ ] } },+ ] } },+ ]);+}++function boardCard(ranked, market) {+ const accent = '#8b5cf6';+ const top = ranked.slice(0, 5);+ const price = fmtUsd(market?.price_usd);+ const mcap = fmtUsd(market?.market_cap);+ const holderCount = market?.holders != null ? Number(market.holders).toLocaleString('en-US') : (ranked.length ? ranked.length.toLocaleString('en-US') : '—');+ return baseShell(accent, [+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', padding: '60px 64px 0', flex: 1 }, children: [+ { type: 'div', props: { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }, children: [+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', gap: 10 }, children: [+ { type: 'div', props: { style: { fontSize: 24, fontWeight: 700, letterSpacing: '0.16em', color: 'rgba(235,235,245,0.5)' }, children: 'ON-CHAIN · LIVE' } },+ { type: 'div', props: { style: { fontSize: 64, fontWeight: 900, color: '#f5f5fa' }, children: '$THREE Holders' } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', gap: 40 }, children: [+ statPill('Price', price || '—', accent),+ statPill('Market cap', mcap || '—', accent),+ statPill('Holders', holderCount, accent),+ ] } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', marginTop: 40, gap: 12 }, children:+ top.length+ ? top.map((h) => {+ const tier = tierForBalance(h.amount);+ return { type: 'div', props: { style: { display: 'flex', alignItems: 'center', gap: 24, padding: '12px 0', borderBottom: '1px solid rgba(255,255,255,0.06)' }, children: [+ { type: 'div', props: { style: { width: 64, fontSize: 36, fontWeight: 900, color: tier.accent }, children: `#${h.rank}` } },+ { type: 'div', props: { style: { flex: 1, fontSize: 34, fontWeight: 600, color: 'rgba(235,235,245,0.85)' }, children: shortWallet(h.wallet) } },+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', padding: '4px 14px', borderRadius: 999, fontSize: 22, fontWeight: 800, color: '#06060b', background: tier.accent }, children: tier.label } },+ { type: 'div', props: { style: { width: 240, textAlign: 'right', fontSize: 34, fontWeight: 800, color: '#f5f5fa' }, children: `${fmtAmount(h.amount)}` } },+ ] } };+ })+ : [{ type: 'div', props: { style: { fontSize: 34, color: 'rgba(235,235,245,0.45)', paddingTop: 30 }, children: 'Holder snapshot warming up — check back shortly.' } }],+ } },+ ] } },+ ]);+}++function imageResponse(node) {+ return new ImageResponse(node, {+ width: WIDTH,+ height: HEIGHT,+ headers: {+ 'cache-control': 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400',+ 'access-control-allow-origin': '*',+ },+ });+}++async function sendImage(res, response) {+ for (const [key, value] of response.headers.entries()) res.setHeader(key, value);+ const ab = await response.arrayBuffer();+ res.statusCode = response.status;+ res.end(Buffer.from(ab));+}++export default async function handler(req, res) {+ if (req.method === 'OPTIONS') {+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('access-control-allow-methods', 'GET,OPTIONS');+ res.statusCode = 204;+ res.end();+ return;+ }+ if (req.method !== 'GET') {+ res.statusCode = 405;+ res.setHeader('allow', 'GET, OPTIONS');+ res.end('method not allowed');+ return;+ }++ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const wallet = (url.searchParams.get('wallet') || '').trim();+ const wantWallet = BASE58_RE.test(wallet) ? wallet : null;++ try {+ const { ranked, market } = await loadBoard();+ let node;+ if (wantWallet) {+ const found = ranked.find((h) => h.wallet === wantWallet) || { wallet: wantWallet, rank: null, amount: 0, pct: 0 };+ node = holderCard(found, market);+ } else {+ node = boardCard(ranked, market);+ }+ await sendImage(res, imageResponse(node));+ } catch (err) {+ console.error('[og-leaderboard]', err?.message || err);+ // Never break a crawler's preview: fall back to the static brand card.+ res.statusCode = 302;+ res.setHeader('location', 'https://three.ws/og-image.png');+ res.setHeader('cache-control', 'no-cache');+ res.end();+ }+}diff --git a/api/og/three-token-badge.js b/api/og/three-token-badge.jsnew file mode 100644index 000000000..4f299bb01--- /dev/null+++ b/api/og/three-token-badge.js@@ -0,0 +1,217 @@+/**+ * GET /api/og/three-token-badge+ *+ * Dynamic Open Graph image for the $THREE token — a shareable badge that+ * previews with live market data wherever the link is posted (X, Telegram,+ * Discord, Slack, iMessage, Farcaster).+ *+ * Mirrors the conventions of api/og/agent.js: an SVG 1200×630 card returned+ * with image/svg+xml + a CDN cache header, no heavy canvas/satori deps in the+ * serverless bundle. Social crawlers accept image/svg+xml for og:image.+ *+ * Every figure on the card is real: price, 24h change, market cap, holders,+ * volume and on-chain agent count are pulled from the same source the+ * /three-token page uses — GET /api/three-token/stats (Birdeye → DexScreener →+ * GeckoTerminal failover with a stale cache, plus DB-derived protocol metrics).+ * Nothing is hardcoded. $THREE is the only coin this card ever references.+ *+ * The card degrades gracefully: if the stats fetch fails or a field is missing+ * we render the figure as "—" and still emit a valid, branded 1200×630 card —+ * we never 5xx and never redirect to a static fallback over missing enrichment.+ *+ * Card anatomy (1200×630, dark):+ * top — three.ws wordmark + "TOKEN"+ * hero — $THREE glyph mark + symbol + truncated mint+ * price — large USD price + 24h change pill (green up / red down)+ * stats — market cap · holders · 24h volume · on-chain agents grid+ * footer — contract address + "three.ws/three-token"+ */++import { cors, wrap } from '../_lib/http.js';+import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';+import { fetchTokenMarketData } from '../_lib/market/token-market.js';+import { sql } from '../_lib/db.js';++// Edge-cache the card: 60s fresh, 10m at the CDN, serve-stale-while-revalidate.+// A token price is fine to be a minute stale and this keeps crawlers (which hit+// the OG URL repeatedly) off the lambda and off the market-data providers.+const CACHE = 'public, max-age=60, s-maxage=600, stale-while-revalidate=120';++// $THREE brand gradient — the violet→cyan pair used across the platform.+const C1 = '#8b5cf6';+const C2 = '#06b6d4';+const UP = '#10b981';+const DOWN = '#ef4444';++function x(s) {+ return String(s ?? '')+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}++// Truncate a base58 mint for display: "FeMb…Jpump".+function shortMint(addr) {+ const s = String(addr || '');+ return s.length > 12 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++// USD price: keep enough significant digits for a sub-cent token without a wall+// of zeros. >= $1 → 2dp; >= $0.01 → 4dp; otherwise 6 significant figures.+function fmtPrice(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ if (n >= 1) return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+ if (n >= 0.01) return `$${n.toFixed(4)}`;+ return `$${n.toPrecision(6).replace(/0+$/, '').replace(/\.$/, '')}`;+}++// Compact USD for market cap / volume: $1.2M, $640K, $12.3B.+function fmtCompactUsd(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ const abs = Math.abs(n);+ if (abs >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;+ if (abs >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;+ if (abs >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;+ return `$${n.toFixed(0)}`;+}++function fmtInt(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ return Math.round(n).toLocaleString('en-US');+}++function fmtPct(n) {+ if (n == null || !Number.isFinite(n)) return null;+ const sign = n > 0 ? '+' : '';+ return `${sign}${n.toFixed(2)}%`;+}++// Resolve every datum the card shows from real sources, each independently+// resilient so one failing provider blanks a single figure rather than the card.+async function loadBadgeData() {+ const [market, agentRow] = await Promise.all([+ fetchTokenMarketData(THREE_MINT).catch(() => null),+ sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`+ .catch(() => [{ total: null }]),+ ]);+ return {+ price: market?.price_usd ?? null,+ change24h: market?.price_change_24h ?? null,+ marketCap: market?.market_cap ?? null,+ volume24h: market?.volume_24h ?? null,+ holders: market?.holders ?? null,+ agents: agentRow?.[0]?.total ?? null,+ };+}++function statCell(xPos, label, value) {+ return (+ `<text x="${xPos}" y="470" font-family="Inter,system-ui,sans-serif" font-size="14" ` ++ `letter-spacing=".08em" fill="#6b7280">${x(label)}</text>` ++ `<text x="${xPos}" y="508" font-family="Inter,system-ui,sans-serif" font-size="30" ` ++ `font-weight="700" fill="#f9fafb">${x(value)}</text>`+ );+}++function renderCard(d) {+ const priceStr = fmtPrice(d.price);+ const pct = fmtPct(d.change24h);+ const up = (d.change24h ?? 0) >= 0;+ const changeColor = up ? UP : DOWN;+ const arrow = up ? '▲' : '▼';+ const mintShort = shortMint(THREE_MINT);++ // 24h-change pill, only when we actually have the datum.+ const pillW = pct ? 40 + pct.length * 13 : 0;+ const changePill = pct+ ? `<rect x="468" y="300" width="${pillW}" height="44" rx="22"+ fill="${changeColor}" fill-opacity=".12" stroke="${changeColor}" stroke-opacity=".4" stroke-width="1.5"/>+ <text x="${468 + pillW / 2}" y="329" text-anchor="middle"+ font-family="Inter,system-ui,sans-serif" font-size="20" font-weight="700"+ fill="${changeColor}">${x(arrow)} ${x(pct)}</text>`+ : '';++ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#050508"/>+ <stop offset="1" stop-color="#0c0a16"/>+ </linearGradient>+ <linearGradient id="mark" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="${C1}"/>+ <stop offset="1" stop-color="${C2}"/>+ </linearGradient>+ <radialGradient id="glow" cx="50%" cy="50%" r="50%">+ <stop offset="0" stop-color="${C1}" stop-opacity=".30"/>+ <stop offset="1" stop-color="${C1}" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="accent" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="${C1}"/>+ <stop offset="1" stop-color="${C2}"/>+ </linearGradient>+ </defs>++ <!-- background -->+ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect x="0" y="0" width="6" height="630" fill="url(#accent)"/>+ <ellipse cx="980" cy="180" rx="320" ry="280" fill="url(#glow)"/>++ <!-- top bar -->+ <text x="72" y="78" font-family="Inter,system-ui,sans-serif" font-size="15" font-weight="600"+ letter-spacing=".14em" fill="#4b5563">THREE.WS</text>+ <text x="1128" y="78" font-family="Inter,system-ui,sans-serif" font-size="15"+ letter-spacing=".14em" fill="#4b5563" text-anchor="end">TOKEN</text>+ <line x1="72" y1="100" x2="1128" y2="100" stroke="#1f2937" stroke-width="1"/>++ <!-- hero: $THREE mark + symbol -->+ <circle cx="128" cy="208" r="48" fill="url(#mark)"/>+ <text x="128" y="224" text-anchor="middle" font-family="Inter,system-ui,sans-serif"+ font-size="40" font-weight="800" fill="#ffffff">3</text>+ <text x="200" y="200" font-family="Inter,system-ui,sans-serif" font-size="64" font-weight="800"+ fill="#f9fafb">$THREE</text>+ <text x="202" y="240" font-family="ui-monospace,Menlo,monospace" font-size="20"+ fill="#6b7280">${x(mintShort)}</text>++ <!-- price -->+ <text x="72" y="332" font-family="Inter,system-ui,sans-serif" font-size="84" font-weight="800"+ fill="#ffffff">${x(priceStr)}</text>+ ${changePill}++ <!-- divider -->+ <line x1="72" y1="404" x2="1128" y2="404" stroke="#1f2937" stroke-width="1"/>++ <!-- stats grid -->+ ${statCell(72, 'MARKET CAP', fmtCompactUsd(d.marketCap))}+ ${statCell(372, 'HOLDERS', fmtInt(d.holders))}+ ${statCell(672, '24H VOLUME', fmtCompactUsd(d.volume24h))}+ ${statCell(948, 'ON-CHAIN AGENTS', fmtInt(d.agents))}++ <!-- footer -->+ <rect x="0" y="566" width="1200" height="64" fill="#030305"/>+ <text x="72" y="606" font-family="ui-monospace,Menlo,monospace" font-size="14" fill="#374151">+ ${x(THREE_MINT)}</text>+ <text x="1128" y="606" font-family="Inter,system-ui,sans-serif" font-size="14" fill="#4b5563"+ letter-spacing=".06em" text-anchor="end">three.ws/three-token</text>+</svg>`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;++ let data;+ try {+ data = await loadBadgeData();+ } catch {+ // Never 5xx a crawler — render the branded card with blank figures.+ data = { price: null, change24h: null, marketCap: null, volume24h: null, holders: null, agents: null };+ }++ const svg = renderCard(data);+ res.statusCode = 200;+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', CACHE);+ res.end(svg);+});++// Exposed for unit tests: lets a test render the card from fixed figures and+// assert the SVG shape without touching the network or DB.+export const __testInternals = { renderCard, fmtPrice, fmtCompactUsd, fmtPct, fmtInt, shortMint };diff --git a/contracts/DEPLOYMENTS.md b/contracts/DEPLOYMENTS.mdindex bb07a0d73..444aa378b 100644--- a/contracts/DEPLOYMENTS.md+++ b/contracts/DEPLOYMENTS.md@@ -3,29 +3,58 @@All three registries are deployed via CREATE2, giving the same address on everysupported EVM chain within each environment class (mainnet vs. testnet).-## Mainnet+## Provenance++Deployment transaction hashes from the original CREATE2 broadcast were not+captured per chain at deploy time. Rather than leave the record as bare `TODO`s,+each live contract is **verified by on-chain bytecode**: `scripts/verify-onchain-parity.mjs`+performs an `eth_getCode` sweep against the public RPCs in `api/_lib/erc8004-chains.js`+and asserts non-empty runtime code at every declared address. The+`bytecode ✓ (YYYY-MM-DD)` notes below are the dates of those reads. Re-run any+time with:-Chains: Ethereum (1), Optimism (10), BSC (56), Gnosis (100), Polygon (137),-Fantom (250), zkSync Era (324), Moonbeam (1284), Mantle (5000), Base (8453),-Arbitrum One (42161), Celo (42220), Avalanche (43114), Linea (59144), Scroll (534352)+```+VERIFY_ONCHAIN_CHAINS=all npm run verify:onchain # full sweep+npm run verify:onchain # build-gate subset (Base + Base Sepolia)+```++The IdentityRegistry + ReputationRegistry share one address per network class+(CREATE2-deterministic). A single explorer link below resolves to the contract+on any listed chain; the per-chain bytecode-verified status is the authoritative+liveness signal.++## Mainnet-| Contract | Address | Tx Hash |-| -------------------- | -------------------------------------------- | -------------------- |-| IdentityRegistry | `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` | TODO: fill after deployment |-| ReputationRegistry | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` | TODO: fill after deployment |-| ValidationRegistry | `TODO: fill after deployment` (same address on all chains) | TODO: one tx hash per chain |+Chains with confirmed bytecode (verified 2026-06-19): Ethereum (1), Optimism (10),+BSC (56), Gnosis (100), Polygon (137), Mantle (5000), Base (8453),+Arbitrum One (42161), Celo (42220), Avalanche (43114), Linea (59144), Scroll (534352).++> **Not yet deployed on Fantom (250), zkSync Era (324), Moonbeam (1284).** An+> `eth_getCode` sweep on 2026-06-19 returned `0x` (no code) at the registry+> addresses on these three chains across multiple independent RPCs. zkSync Era+> derives CREATE2 addresses differently from the EVM, so the canonical address is+> not reachable there without a chain-specific deploy. Registration / reputation+> writes on these chains will revert until the registries are deployed (deploy+> backlog). The address columns are kept for parity; liveness is per the bytecode+> notes only.++| Contract | Address | Provenance |+| -------------------- | -------------------------------------------- | ----------------------- |+| IdentityRegistry | [`0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`](https://basescan.org/address/0x8004A169FB4a3325136EB29fA0ceB6D2e539a432) | bytecode ✓ (2026-06-19) on 12 chains; tx unrecoverable |+| ReputationRegistry | [`0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`](https://basescan.org/address/0x8004BAa17C55a88189AE136b182e5fdA19dE9b63) | bytecode ✓ (2026-06-19) on 12 chains; tx unrecoverable |+| ValidationRegistry | not deployed on mainnet | pending mainnet deploy (`src/erc8004/abi.js` MAINNET.validationRegistry = '') |## Testnet-Chains: BSC Testnet (97), Ethereum Sepolia (11155111), Base Sepolia (84532),-Arbitrum Sepolia (421614), Optimism Sepolia (11155420), Polygon Amoy (80002),-Avalanche Fuji (43113)+Chains (all bytecode-verified 2026-06-19): BSC Testnet (97), Ethereum Sepolia (11155111),+Base Sepolia (84532), Arbitrum Sepolia (421614), Optimism Sepolia (11155420),+Polygon Amoy (80002), Avalanche Fuji (43113).-| Contract | Address | Tx Hash |-| -------------------- | -------------------------------------------- | -------------------- |-| IdentityRegistry | `0x8004A818BFB912233c491871b3d84c89A494BD9e` | TODO: fill after deployment |-| ReputationRegistry | `0x8004B663056A597Dffe9eCcC1965A193B7388713` | TODO: fill after deployment |-| ValidationRegistry | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` | TODO: fill after deployment |+| Contract | Address | Provenance |+| -------------------- | -------------------------------------------- | ----------------------- |+| IdentityRegistry | [`0x8004A818BFB912233c491871b3d84c89A494BD9e`](https://sepolia.basescan.org/address/0x8004A818BFB912233c491871b3d84c89A494BD9e) | bytecode ✓ (2026-06-19) on 7 testnets; tx unrecoverable |+| ReputationRegistry | [`0x8004B663056A597Dffe9eCcC1965A193B7388713`](https://sepolia.basescan.org/address/0x8004B663056A597Dffe9eCcC1965A193B7388713) | bytecode ✓ (2026-06-19) on 7 testnets; tx unrecoverable |+| ValidationRegistry | [`0x8004Cb1BF31DAf7788923b405b754f57acEB4272`](https://sepolia.basescan.org/address/0x8004Cb1BF31DAf7788923b405b754f57acEB4272) | bytecode ✓ (2026-06-19) on 7 testnets; tx unrecoverable |## Platform validator (ValidationRegistry attestor)diff --git a/extensions/walk-avatar/background.js b/extensions/walk-avatar/background.jsindex f7b77f479..d1e2ed44e 100644--- a/extensions/walk-avatar/background.js+++ b/extensions/walk-avatar/background.js@@ -1,124 +1,192 @@-// background.js — service worker for the Walk Avatar extension.-// Manages state persistence, auth token relay, and per-tab enable/disable.+// background.js — service worker for the three.ws Walk Avatar extension.+//+// Responsibilities:+// • Seed and serve default settings (chrome.storage.sync, roams across installs).+// • Relay the popup/options UI to the per-tab content scripts.+// • Capture the session token from the three.ws auth-callback tab.+// • Inject content.js + content-narrator.js on demand and keep their iframes+// in sync as settings change.+// • Enforce the site allow/blocklist before an avatar is ever mounted.const THREEWS_ORIGIN = 'https://three.ws';-// Default settings merged into chrome.storage.local on first install.+// Defaults are written on install and used as the merge base everywhere the UI+// reads settings, so a missing key never produces `undefined` downstream.const DEFAULTS = {avatarId: '',walkSpeed: 1.0,position: 'bottom-right',+ sizePreset: 'medium',width: 180,height: 260,- enabledGlobal: false,siteAllowlist: [],siteBlocklist: [],narrationEnabled: false,- voice: 'default',+ voice: 'nova',theme: 'auto',};chrome.runtime.onInstalled.addListener(async ({ reason }) => {+ const existing = await chrome.storage.sync.get(null);+ // Merge so an upgrade keeps the user's choices but backfills new keys.+ const merged = { ...DEFAULTS, ...existing };+ await chrome.storage.sync.set(merged);if (reason === 'install') {- await chrome.storage.sync.set(DEFAULTS);+ chrome.tabs.create({ url: `${THREEWS_ORIGIN}/extension` }).catch(() => {});}});-// Relay messages between popup and content scripts.-chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {- if (msg.type === 'get-state') {- Promise.all([- chrome.storage.local.get(['threews_session']),- chrome.storage.sync.get(null),- ]).then(([local, sync]) => {- sendResponse({ session: local.threews_session || null, settings: sync });- });- return true; // async- }+// ── Host filter ─────────────────────────────────────────────────────────────+// A blocklisted host always wins. An empty allowlist means "every site"; a+// non-empty allowlist restricts the avatar to those hosts only. Entries match+// the host and any subdomain (`example.com` covers `www.example.com`).+function hostMatches(host, pattern) {+ const p = pattern.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');+ if (!p) return false;+ host = host.toLowerCase();+ return host === p || host.endsWith('.' + p);+}- if (msg.type === 'set-avatar') {- chrome.storage.sync.set({ avatarId: msg.avatarId }).then(() => {- // Push new avatar to all active content scripts.- chrome.tabs.query({ status: 'complete' }, (tabs) => {- tabs.forEach((tab) => {- chrome.tabs.sendMessage(tab.id, {- type: 'walk:setAvatar',- avatarId: msg.avatarId,- }).catch(() => {}); // tab may not have content script- });- });- sendResponse({ ok: true });- });- return true;+function siteAllowed(url, settings) {+ let host;+ try {+ host = new URL(url).hostname;+ } catch {+ return false;}+ const block = settings.siteBlocklist || [];+ if (block.some((p) => hostMatches(host, p))) return false;+ const allow = settings.siteAllowlist || [];+ if (allow.length > 0 && !allow.some((p) => hostMatches(host, p))) return false;+ return true;+}- if (msg.type === 'toggle-tab') {- const { tabId, enabled, avatarId } = msg;- if (enabled) {- // Inject content script into the tab.- chrome.scripting.executeScript({- target: { tabId },- files: ['content.js'],- }).then(() => {- chrome.tabs.sendMessage(tabId, {- type: 'walk:mount',- avatarId,- }).catch(() => {});- sendResponse({ ok: true });- }).catch((err) => {- sendResponse({ ok: false, error: err.message });- });- } else {- chrome.tabs.sendMessage(tabId, { type: 'walk:unmount' }).catch(() => {});- sendResponse({ ok: true });- }- return true;- }+async function getSettings() {+ const sync = await chrome.storage.sync.get(null);+ return { ...DEFAULTS, ...sync };+}- if (msg.type === 'store-session') {- chrome.storage.local.set({ threews_session: msg.token }).then(() => {- sendResponse({ ok: true });- });- return true;- }+// Inject both content modules (idempotent — re-injection is a no-op once the+// guard flag is set inside content.js).+async function injectContent(tabId) {+ await chrome.scripting.executeScript({+ target: { tabId },+ files: ['content-narrator.js', 'content.js'],+ });+}- if (msg.type === 'clear-session') {- chrome.storage.local.remove('threews_session').then(() => {- sendResponse({ ok: true });- });- return true;- }+// ── Message relay ─────────────────────────────────────────────────────────────+chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {+ (async () => {+ try {+ switch (msg.type) {+ case 'get-state': {+ const [local, settings] = await Promise.all([+ chrome.storage.local.get(['threews_session']),+ getSettings(),+ ]);+ sendResponse({ session: local.threews_session || null, settings });+ break;+ }- if (msg.type === 'update-settings') {- chrome.storage.sync.set(msg.settings).then(() => {- sendResponse({ ok: true });- });- return true;- }+ case 'set-avatar': {+ await chrome.storage.sync.set({ avatarId: msg.avatarId });+ broadcast({ type: 'walk:setAvatar', avatarId: msg.avatarId });+ sendResponse({ ok: true });+ break;+ }++ case 'toggle-tab': {+ const { tabId, enabled, avatarId } = msg;+ if (enabled) {+ const tab = await chrome.tabs.get(tabId);+ const settings = await getSettings();+ if (!siteAllowed(tab.url || '', settings)) {+ sendResponse({ ok: false, error: 'blocked', reason: 'site filtered' });+ break;+ }+ await injectContent(tabId);+ await chrome.tabs.sendMessage(tabId, {+ type: 'walk:mount',+ avatarId: avatarId || settings.avatarId,+ }).catch(() => {});+ sendResponse({ ok: true });+ } else {+ await chrome.tabs.sendMessage(tabId, { type: 'walk:unmount' }).catch(() => {});+ sendResponse({ ok: true });+ }+ break;+ }++ case 'store-session': {+ await chrome.storage.local.set({ threews_session: msg.token });+ sendResponse({ ok: true });+ break;+ }++ case 'clear-session': {+ await chrome.storage.local.remove('threews_session');+ sendResponse({ ok: true });+ break;+ }++ case 'update-settings': {+ await chrome.storage.sync.set(msg.settings);+ const settings = await getSettings();+ // Push the full settings object so every open iframe re-applies+ // speed, position, size, theme, and narration state at once.+ broadcast({ type: 'walk:applySettings', settings });+ sendResponse({ ok: true });+ break;+ }++ case 'check-site': {+ const settings = await getSettings();+ sendResponse({ allowed: siteAllowed(msg.url || '', settings) });+ break;+ }++ default:+ sendResponse({ ok: false, error: 'unknown_message' });+ }+ } catch (err) {+ sendResponse({ ok: false, error: String(err?.message || err) });+ }+ })();+ return true; // keep the channel open for the async response});-// Listen for the auth callback page posting the session token via postMessage.-// The login page at three.ws/login?redirect=ext fires a broadcast that the-// background service worker intercepts here via declarativeNetRequest or-// chrome.tabs, then stores it.+// Send a message to every tab that has a mounted avatar. Tabs without the+// content script simply reject — swallowed here.+function broadcast(message) {+ chrome.tabs.query({}, (tabs) => {+ for (const tab of tabs) {+ if (tab.id == null) continue;+ chrome.tabs.sendMessage(tab.id, message).catch(() => {});+ }+ });+}++// ── Auth callback capture ─────────────────────────────────────────────────────+// The popup opens three.ws/login?redirect=extension. After a successful sign-in+// the site redirects to /extension/auth-callback?token=<session>. We read the+// token out of that tab's URL, persist it, close the tab, and notify any open+// popup so it can re-render the signed-in state.chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {- if (- changeInfo.status === 'complete' &&- tab.url &&- tab.url.startsWith(THREEWS_ORIGIN + '/extension/auth-callback')- ) {- chrome.scripting.executeScript({- target: { tabId },- func: () => {- const params = new URLSearchParams(location.search);- return params.get('token');- },- }).then(([result]) => {- const token = result?.result;- if (token) {- chrome.storage.local.set({ threews_session: token });- chrome.tabs.remove(tabId).catch(() => {});- }- }).catch(() => {});+ if (changeInfo.status !== 'complete' || !tab.url) return;+ if (!tab.url.startsWith(THREEWS_ORIGIN + '/extension/auth-callback')) return;++ let token = null;+ try {+ const u = new URL(tab.url);+ token = u.searchParams.get('token') || u.hash.replace(/^#token=/, '') || null;+ } catch {+ token = null;}+ if (!token) return;++ chrome.storage.local.set({ threews_session: token }).then(() => {+ chrome.runtime.sendMessage({ type: 'session-updated', token }).catch(() => {});+ chrome.tabs.remove(tabId).catch(() => {});+ });});diff --git a/extensions/walk-avatar/content-narrator.js b/extensions/walk-avatar/content-narrator.jsnew file mode 100644index 000000000..ffaa8a012--- /dev/null+++ b/extensions/walk-avatar/content-narrator.js@@ -0,0 +1,223 @@+// content-narrator.js — page-section narrator for the Walk Avatar extension.+//+// Injected as a CLASSIC script before content.js. Exposes a constructor on+// window.__ThreewsWalkNarrator so content.js can instantiate it without ES+// modules. The narrator:+// • Finds readable sections (Readability for the lead block, plus the page's+// own headings/paragraphs so scrolling tracks individual sections).+// • Tracks which section is ≥60% in view with an IntersectionObserver.+// • Debounces active-section changes by 600 ms to avoid double-narration.+// • Fetches real audio from POST /api/tts/speak and plays it in the page.+// • Posts walk:narrate / walk:narrateEnd to the iframe so the avatar shows a+// speech bubble and plays its reading gesture.++(function () {+ 'use strict';+ if (window.__ThreewsWalkNarrator) return;++ const THREEWS = 'https://three.ws';+ const SECTION_DEBOUNCE_MS = 600;+ const MAX_CHARS = 400;+ const MIN_SECTION_CHARS = 80;+ const VISIBILITY_RATIO = 0.6;++ class Narrator {+ constructor({ getIframe, getSession, getSettings, isMuted }) {+ this.getIframe = getIframe;+ this.getSession = getSession;+ this.getSettings = getSettings;+ this.isMuted = isMuted || (() => false);++ this._observer = null;+ this._currentSection = null;+ this._debounceTimer = null;+ this._audio = null;+ this._controller = null;+ this._sections = [];+ }++ start() {+ this._collectSections();+ }++ refresh() {+ // Re-scan after settings change or significant DOM mutation.+ this._collectSections();+ }++ stop() {+ clearTimeout(this._debounceTimer);+ this._observer?.disconnect();+ this._observer = null;+ this._cancelAudio();+ this._currentSection = null;+ }++ mute() { this._cancelAudio(); this._endBubble(); }+ unmute() { /* next visible section narrates again */ }++ // ── Section discovery ──────────────────────────────────────────────────+ _collectSections() {+ this._observer?.disconnect();+ const sections = this._findReadableSections();+ this._sections = sections;+ if (sections.length === 0) return;++ this._observer = new IntersectionObserver((entries) => {+ // Pick the most-visible intersecting section.+ let best = null;+ for (const entry of entries) {+ if (entry.isIntersecting && entry.intersectionRatio >= VISIBILITY_RATIO) {+ if (!best || entry.intersectionRatio > best.intersectionRatio) best = entry;+ }+ }+ if (best) this._onSectionVisible(best.target);+ }, { threshold: [VISIBILITY_RATIO, 0.75, 1] });++ for (const el of sections) this._observer.observe(el);+ }++ _findReadableSections() {+ // 1) Use Readability to isolate the main article, then narrate its+ // block-level children. This strips nav/footer/ads reliably.+ const fromReadability = this._readabilitySections();+ if (fromReadability.length > 0) return fromReadability;++ // 2) Author-marked sections.+ const marked = Array.from(document.querySelectorAll('[data-walk-narrate]'))+ .filter((el) => el.dataset.walkNarrate !== 'skip' && this._textOf(el).length >= 20);+ if (marked.length > 0) return marked;++ // 3) Semantic fallback: headings, article/section/main paragraphs.+ const root = document.querySelector('article, main, [role="main"]') || document.body;+ const candidates = Array.from(+ root.querySelectorAll('h1, h2, h3, p, li, blockquote'),+ );+ return candidates.filter((el) => {+ if (this._isChrome(el)) return false;+ return this._textOf(el).length >= MIN_SECTION_CHARS;+ });+ }++ _readabilitySections() {+ const R = window.__ThreewsReadability;+ if (!R) return [];+ let articleRoot = null;+ try {+ // Parse a clone so the live page is never mutated.+ const clone = document.cloneNode(true);+ const parsed = new R(clone, { charThreshold: 200 }).parse();+ if (!parsed || !parsed.content) return [];+ // Re-anchor parsed blocks back onto live nodes by matching text, so+ // the IntersectionObserver observes elements that actually scroll.+ const holder = document.createElement('div');+ holder.innerHTML = parsed.content;+ const blocks = Array.from(holder.querySelectorAll('p, h1, h2, h3, li, blockquote'))+ .map((b) => b.textContent.replace(/\s+/g, ' ').trim())+ .filter((t) => t.length >= MIN_SECTION_CHARS);+ if (blocks.length === 0) return [];++ const live = Array.from(document.querySelectorAll('p, h1, h2, h3, li, blockquote'))+ .filter((el) => !this._isChrome(el));+ const liveByText = new Map();+ for (const el of live) {+ const t = this._textOf(el);+ if (t.length >= MIN_SECTION_CHARS && !liveByText.has(t)) liveByText.set(t, el);+ }+ articleRoot = [];+ for (const t of blocks) {+ const el = liveByText.get(t);+ if (el && !articleRoot.includes(el)) articleRoot.push(el);+ }+ } catch {+ return [];+ }+ return articleRoot || [];+ }++ _isChrome(el) {+ // Skip nav/header/footer/aside chrome and hidden nodes.+ if (el.closest('nav, header, footer, aside, [role="navigation"], [aria-hidden="true"]')) return true;+ const cs = window.getComputedStyle(el);+ return cs.display === 'none' || cs.visibility === 'hidden';+ }++ _textOf(el) {+ return (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();+ }++ _onSectionVisible(el) {+ if (el === this._currentSection) return;+ clearTimeout(this._debounceTimer);+ this._debounceTimer = setTimeout(() => {+ this._currentSection = el;+ if (!this.isMuted()) this._narrate(el);+ }, SECTION_DEBOUNCE_MS);+ }++ // ── Narration ──────────────────────────────────────────────────────────+ _extractText(el) {+ if (el.dataset?.walkScript) return el.dataset.walkScript.trim().slice(0, MAX_CHARS);+ return this._textOf(el).slice(0, MAX_CHARS);+ }++ async _narrate(el) {+ const text = this._extractText(el);+ if (!text) return;++ this._cancelAudio();++ const settings = this.getSettings() || {};+ const session = this.getSession();+ const voice = settings.voice || 'nova';+ const iframe = this.getIframe();++ // Avatar: reading gesture + speech bubble.+ iframe?.contentWindow?.postMessage({ type: 'walk:setMotion', motion: 'idle' }, THREEWS);+ iframe?.contentWindow?.postMessage({ type: 'walk:narrate', text }, THREEWS);++ try {+ this._controller = new AbortController();+ const headers = { 'Content-Type': 'application/json' };+ if (session) headers['Authorization'] = `Bearer ${session}`;++ const res = await fetch(`${THREEWS}/api/tts/speak`, {+ method: 'POST',+ headers,+ credentials: 'include',+ body: JSON.stringify({ text, voice, format: 'mp3' }),+ signal: this._controller.signal,+ });+ if (!res.ok || this.isMuted()) { this._endBubble(); return; }++ const blob = await res.blob();+ if (this.isMuted()) { this._endBubble(); return; }++ const url = URL.createObjectURL(blob);+ this._audio = new Audio(url);+ this._audio.onended = () => { URL.revokeObjectURL(url); this._endBubble(); };+ this._audio.onerror = () => { URL.revokeObjectURL(url); this._endBubble(); };+ await this._audio.play().catch(() => { this._endBubble(); });+ } catch (err) {+ if (err.name !== 'AbortError') this._endBubble();+ }+ }++ _endBubble() {+ this.getIframe()?.contentWindow?.postMessage({ type: 'walk:narrateEnd' }, THREEWS);+ }++ _cancelAudio() {+ if (this._controller) { this._controller.abort(); this._controller = null; }+ if (this._audio) {+ this._audio.pause();+ this._audio.onended = null;+ this._audio.onerror = null;+ this._audio.src = '';+ this._audio = null;+ }+ }+ }++ window.__ThreewsWalkNarrator = Narrator;+})();diff --git a/extensions/walk-avatar/content.js b/extensions/walk-avatar/content.jsindex 22b8c118b..4b00b398b 100644--- a/extensions/walk-avatar/content.js+++ b/extensions/walk-avatar/content.js@@ -1,282 +1,360 @@-// content.js — injected into pages to mount the walking avatar iframe.-// Handles: mounting, dragging, close, SPA navigation survival, postMessage relay.--import { Narrator } from './narrator.js';+// content.js — injected into the host page to mount the walking avatar iframe.+//+// Injected via chrome.scripting.executeScript({ files: [...] }) as a CLASSIC+// script (no ES modules), so the narrator is exposed on window by+// content-narrator.js (injected just before this file) rather than imported.+//+// Responsibilities: mount/unmount the avatar iframe, drag-to-reposition, a+// hover-revealed mute + close toolbar, live settings application, and relaying+// the iframe's postMessage events. Page narration is delegated to the Narrator.(function () {'use strict';+ // Guard against double-injection on re-enable / SPA re-runs.+ if (window.__threewsWalkLoaded) return;+ window.__threewsWalkLoaded = true;+const THREEWS = 'https://three.ws';const CONTAINER_ID = '__threews_walk_container__';let container = null;let iframe = null;let mounted = false;+ let narrator = null;+ let muted = false;+ let settings = {};+ let session = null;// Drag statelet dragging = false;- let dragOffX = 0, dragOffY = 0;+ let dragOffX = 0;+ let dragOffY = 0;++ const SIZE_PRESETS = {+ small: { width: 120, height: 180 },+ medium: { width: 180, height: 260 },+ large: { width: 240, height: 340 },+ };++ function resolveSize(s) {+ if (s.sizePreset === 'custom') {+ return {+ width: clamp(parseInt(s.width, 10) || 180, 80, 600),+ height: clamp(parseInt(s.height, 10) || 260, 120, 800),+ };+ }+ return SIZE_PRESETS[s.sizePreset] || SIZE_PRESETS.medium;+ }++ function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }- function buildEmbedSrc(avatarId, settings) {+ function buildEmbedSrc(avatarId) {const p = new URLSearchParams();if (avatarId) p.set('avatar', avatarId);- p.set('controls', 'joystick');+ p.set('controls', 'none');p.set('autoplay', 'true');p.set('ground', 'false');p.set('orbit', 'false');p.set('bg', 'transparent');- if (settings?.walkSpeed && settings.walkSpeed !== 1) p.set('speed', String(settings.walkSpeed));- return `${THREEWS}/walk-embed?${p}`;+ return `${THREEWS}/walk-embed?${p.toString()}`;}- function getPosition(pos) {- const margin = '16px';+ function getPositionStyle(pos) {+ const m = '16px';switch (pos) {- case 'top-left': return { top: margin, left: margin, bottom: 'auto', right: 'auto' };- case 'top-right': return { top: margin, right: margin, bottom: 'auto', left: 'auto' };- case 'bottom-left': return { bottom: margin, left: margin, top: 'auto', right: 'auto' };- default: return { bottom: margin, right: margin, top: 'auto', left: 'auto' };+ case 'top-left': return { top: m, left: m, bottom: 'auto', right: 'auto' };+ case 'top-right': return { top: m, right: m, bottom: 'auto', left: 'auto' };+ case 'bottom-left': return { bottom: m, left: m, top: 'auto', right: 'auto' };+ default: return { bottom: m, right: m, top: 'auto', left: 'auto' };}}- function applyPosition(el, pos) {- const p = getPosition(pos);- Object.assign(el.style, p);+ // ── Follow-cursor ──────────────────────────────────────────────────────────+ let followHandler = null;+ function enableFollowCursor() {+ disableFollowCursor();+ followHandler = (e) => {+ if (!container || dragging) return;+ const w = container.offsetWidth;+ const h = container.offsetHeight;+ const x = clamp(e.clientX + 24, 0, window.innerWidth - w);+ const y = clamp(e.clientY - h / 2, 0, window.innerHeight - h);+ container.style.left = x + 'px';+ container.style.top = y + 'px';+ container.style.right = 'auto';+ container.style.bottom = 'auto';+ };+ document.addEventListener('mousemove', followHandler, { passive: true });+ }+ function disableFollowCursor() {+ if (followHandler) {+ document.removeEventListener('mousemove', followHandler);+ followHandler = null;+ }}- function mount(avatarId, settings) {- if (mounted || document.getElementById(CONTAINER_ID)) {- // Already mounted — just update avatar if needed+ // ── Mount / unmount ──────────────────────────────────────────────────────────+ function mount(avatarId) {+ if (mounted) {if (iframe && avatarId) {iframe.contentWindow?.postMessage({ type: 'walk:setAvatar', id: avatarId }, THREEWS);}return;}- const w = settings?.width || 180;- const h = settings?.height || 260;- const pos = settings?.position || 'bottom-right';+ const { width, height } = resolveSize(settings);+ const pos = settings.position || 'bottom-right';container = document.createElement('div');container.id = CONTAINER_ID;+ container.setAttribute('role', 'complementary');+ container.setAttribute('aria-label', 'three.ws walking avatar');container.style.cssText = `position: fixed;- width: ${w}px;- height: ${h}px;+ width: ${width}px;+ height: ${height}px;z-index: 2147483647;background: transparent;- border-radius: 12px;- overflow: hidden;+ border-radius: 14px;+ overflow: visible;pointer-events: auto;- box-shadow: 0 8px 32px rgba(0,0,0,0.28);+ filter: drop-shadow(0 10px 28px rgba(0,0,0,0.32));`;- applyPosition(container, pos);+ Object.assign(container.style, getPositionStyle(pos));- // Drag handle at top of container- const handle = document.createElement('div');- handle.style.cssText = `+ // Hover toolbar (drag handle + mute + close)+ const toolbar = document.createElement('div');+ toolbar.style.cssText = `position: absolute;- top: 0; left: 0; right: 0;- height: 20px;- cursor: grab;+ top: -2px; left: 0; right: 0;+ height: 26px;+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 4px;+ padding: 0 4px;+ opacity: 0;+ transition: opacity 0.18s ease;z-index: 10;- background: rgba(0,0,0,0.18);- backdrop-filter: blur(4px);- -webkit-backdrop-filter: blur(4px);`;- // Close button- const closeBtn = document.createElement('button');- closeBtn.textContent = '×';- closeBtn.title = 'Close avatar';- closeBtn.style.cssText = `- position: absolute;- top: 2px; right: 4px;- width: 16px; height: 16px;- border: 0;- background: transparent;- color: rgba(255,255,255,0.7);- font-size: 13px;- line-height: 1;- cursor: pointer;- padding: 0;- display: flex;- align-items: center;- justify-content: center;+ const grip = document.createElement('div');+ grip.title = 'Drag to move';+ grip.style.cssText = `+ flex: 1;+ height: 22px;+ cursor: grab;+ border-radius: 8px;+ background: rgba(0,0,0,0.22);+ backdrop-filter: blur(6px);+ -webkit-backdrop-filter: blur(6px);`;++ const muteBtn = iconButton(muteIcon(muted), muted ? 'Unmute narration' : 'Mute narration');+ muteBtn.id = '__threews_mute_btn__';+ muteBtn.addEventListener('click', toggleMute);++ const closeBtn = iconButton('×', 'Hide avatar');+ closeBtn.style.fontSize = '16px';closeBtn.addEventListener('click', () => unmount());- handle.appendChild(closeBtn);++ toolbar.appendChild(grip);+ toolbar.appendChild(muteBtn);+ toolbar.appendChild(closeBtn);iframe = document.createElement('iframe');- iframe.src = buildEmbedSrc(avatarId, settings);+ iframe.src = buildEmbedSrc(avatarId);iframe.title = 'three.ws walking avatar';- iframe.allow = 'accelerometer; gyroscope';+ iframe.allow = 'accelerometer; gyroscope; autoplay';+ iframe.setAttribute('scrolling', 'no');iframe.style.cssText = `width: 100%;height: 100%;border: 0;background: transparent;display: block;+ border-radius: 14px;`;- container.appendChild(handle);container.appendChild(iframe);- document.body.appendChild(container);+ container.appendChild(toolbar);+ (document.body || document.documentElement).appendChild(container);mounted = true;- // Drag on handle- handle.addEventListener('mousedown', startDrag);- handle.addEventListener('touchstart', startDragTouch, { passive: false });+ container.addEventListener('mouseenter', () => { toolbar.style.opacity = '1'; });+ container.addEventListener('mouseleave', () => { toolbar.style.opacity = '0'; });++ grip.addEventListener('mousedown', startDrag);+ grip.addEventListener('touchstart', startDragTouch, { passive: false });- // Relay postMessage from iframe to extension backgroundwindow.addEventListener('message', onIframeMessage);++ // Apply runtime config once the embed signals readiness.+ applyLiveConfig();++ if (settings.position === 'follow-cursor') enableFollowCursor();++ // Start narration if enabled and motion is allowed.+ maybeStartNarrator();}function unmount() {if (!mounted) return;window.removeEventListener('message', onIframeMessage);+ disableFollowCursor();+ narrator?.stop();+ narrator = null;if (container && container.parentNode) container.parentNode.removeChild(container);container = null;iframe = null;mounted = false;+ window.__threewsWalkLoaded = false; // allow a clean re-mount later}- // ── Drag implementation ───────────────────────────────────────────────- function startDrag(e) {- if (e.target.tagName === 'BUTTON') return;- dragging = true;- const rect = container.getBoundingClientRect();- dragOffX = e.clientX - rect.left;- dragOffY = e.clientY - rect.top;- document.addEventListener('mousemove', onDrag);- document.addEventListener('mouseup', stopDrag);- e.preventDefault();+ function iconButton(label, title) {+ const b = document.createElement('button');+ b.type = 'button';+ b.title = title;+ b.setAttribute('aria-label', title);+ b.innerHTML = label;+ b.style.cssText = `+ width: 22px; height: 22px;+ border: 0;+ border-radius: 7px;+ background: rgba(0,0,0,0.34);+ color: rgba(255,255,255,0.86);+ font-size: 13px;+ line-height: 1;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ backdrop-filter: blur(6px);+ -webkit-backdrop-filter: blur(6px);+ padding: 0;+ `;+ b.addEventListener('mouseenter', () => { b.style.background = 'rgba(0,0,0,0.55)'; });+ b.addEventListener('mouseleave', () => { b.style.background = 'rgba(0,0,0,0.34)'; });+ return b;}- function onDrag(e) {- if (!dragging || !container) return;- const x = Math.max(0, Math.min(window.innerWidth - container.offsetWidth, e.clientX - dragOffX));- const y = Math.max(0, Math.min(window.innerHeight - container.offsetHeight, e.clientY - dragOffY));- container.style.left = x + 'px';- container.style.top = y + 'px';- container.style.right = 'auto';- container.style.bottom = 'auto';+ function muteIcon(isMuted) {+ return isMuted+ ? '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>'+ : '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>';}- function stopDrag() {- dragging = false;- document.removeEventListener('mousemove', onDrag);- document.removeEventListener('mouseup', stopDrag);+ function toggleMute() {+ muted = !muted;+ const btn = document.getElementById('__threews_mute_btn__');+ if (btn) {+ btn.innerHTML = muteIcon(muted);+ btn.title = muted ? 'Unmute narration' : 'Mute narration';+ btn.setAttribute('aria-label', btn.title);+ }+ if (muted) narrator?.mute();+ else narrator?.unmute();}- function startDragTouch(e) {- if (e.touches.length !== 1) return;- const t = e.touches[0];- dragging = true;- const rect = container.getBoundingClientRect();- dragOffX = t.clientX - rect.left;- dragOffY = t.clientY - rect.top;- document.addEventListener('touchmove', onDragTouch, { passive: false });- document.addEventListener('touchend', stopDragTouch);- e.preventDefault();+ // ── Live config ──────────────────────────────────────────────────────────────+ function applyLiveConfig() {+ if (!iframe) return;+ const speed = settings.walkSpeed || 1;+ const send = () => {+ iframe.contentWindow?.postMessage({ type: 'walk:config', speed }, THREEWS);+ iframe.contentWindow?.postMessage({ type: 'walk:setMotion', motion: 'walk' }, THREEWS);+ };+ // The embed posts walk:ready when its scene is up; send immediately and+ // once more shortly after to cover the race before the listener attaches.+ send();+ setTimeout(send, 800);}- function onDragTouch(e) {- if (!dragging || !container || e.touches.length !== 1) return;- const t = e.touches[0];- const x = Math.max(0, Math.min(window.innerWidth - container.offsetWidth, t.clientX - dragOffX));- const y = Math.max(0, Math.min(window.innerHeight - container.offsetHeight, t.clientY - dragOffY));- container.style.left = x + 'px';- container.style.top = y + 'px';- container.style.right = 'auto';- container.style.bottom = 'auto';- e.preventDefault();+ function applySettings(next) {+ settings = { ...settings, ...next };+ if (!mounted || !container) return;++ const { width, height } = resolveSize(settings);+ container.style.width = width + 'px';+ container.style.height = height + 'px';++ if (settings.position === 'follow-cursor') {+ enableFollowCursor();+ } else {+ disableFollowCursor();+ Object.assign(container.style, getPositionStyle(settings.position || 'bottom-right'));+ }++ applyLiveConfig();+ maybeStartNarrator();}- function stopDragTouch() {- dragging = false;- document.removeEventListener('touchmove', onDragTouch);- document.removeEventListener('touchend', stopDragTouch);+ // ── Narrator ───────────────────────────────────────────────────────────────+ function maybeStartNarrator() {+ const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;+ if (!settings.narrationEnabled || reduced) {+ narrator?.stop();+ narrator = null;+ return;+ }+ if (narrator) {+ narrator.refresh();+ return;+ }+ const NarratorClass = window.__ThreewsWalkNarrator;+ if (!NarratorClass) return;+ narrator = new NarratorClass({+ getIframe: () => iframe,+ getSession: () => session,+ getSettings: () => settings,+ isMuted: () => muted,+ });+ narrator.start();}- // ── postMessage from iframe ───────────────────────────────────────────+ // ── iframe → host relay ──────────────────────────────────────────────────────function onIframeMessage(e) {if (!iframe || e.source !== iframe.contentWindow) return;- const msg = e.data;- if (!msg || typeof msg !== 'object') return;- // Re-dispatch as a DOM event on document for any host-page listeners+ const data = e.data;+ if (!data || typeof data !== 'object') return;+ if (data.type === 'walk:ready') applyLiveConfig();+ // Surface avatar events to the host page for any listeners.try {- document.dispatchEvent(new CustomEvent(msg.type, { detail: msg }));+ document.dispatchEvent(new CustomEvent('threews-walk', { detail: data }));} catch {}}- // ── SPA navigation: survive pushState ────────────────────────────────- (function patchHistory() {- const orig = history.pushState.bind(history);- history.pushState = function (...args) {- orig(...args);- // Keep avatar alive — do nothing. Container is fixed-position so- // SPA route changes don't affect it.- };- })();+ // SPA route changes don't disturb a fixed-position overlay, so no history+ // patching is needed — the container persists across pushState navigations.- window.addEventListener('popstate', () => {- // Avatar survives popstate naturally.- });-- // ── Narrator ──────────────────────────────────────────────────────────- let narrator = null;-- function initNarrator(settings) {- if (!settings?.narrationEnabled) return;- if (narrator) return;- narrator = new Narrator({- getIframe: () => iframe,- getSession: () => {- // Session is accessed async but cached here for sync use- return contentSession;- },- getSettings: () => {- return syncSettings;- },- });- narrator.start();- }-- // Cache settings/session for narrator access- let contentSession = null;- let syncSettings = {};- chrome.storage.local.get('threews_session', ({ threews_session }) => {- contentSession = threews_session || null;- });- chrome.storage.sync.get(null, (s) => {- syncSettings = s || {};- });-- // ── Message listener from background / popup ──────────────────────────+ // ── Runtime messaging ────────────────────────────────────────────────────────chrome.runtime.onMessage.addListener((msg) => {- if (msg.type === 'walk:mount') {- chrome.storage.sync.get(null, (settings) => {- syncSettings = settings;- mount(msg.avatarId || settings.avatarId, settings);- initNarrator(settings);- });- } else if (msg.type === 'walk:unmount') {- narrator?.stop();- narrator = null;- unmount();- } else if (msg.type === 'walk:setAvatar') {- if (iframe) {- iframe.contentWindow?.postMessage({ type: 'walk:setAvatar', id: msg.avatarId }, THREEWS);- }- } else if (msg.type === 'walk:setSpeed') {- if (iframe) {- iframe.contentWindow?.postMessage({ type: 'walk:config', speed: msg.speed }, THREEWS);- }- } else if (msg.type === 'walk:muteNarration') {- narrator?.mute();- } else if (msg.type === 'walk:unmuteNarration') {- narrator?.unmute();+ switch (msg.type) {+ case 'walk:mount':+ loadContext().then(() => mount(msg.avatarId || settings.avatarId));+ break;+ case 'walk:unmount':+ unmount();+ break;+ case 'walk:setAvatar':+ if (iframe) iframe.contentWindow?.postMessage({ type: 'walk:setAvatar', id: msg.avatarId }, THREEWS);+ break;+ case 'walk:applySettings':+ applySettings(msg.settings || {});+ break;+ default:+ break;}});++ // Load cached settings + session before the first mount.+ async function loadContext() {+ const [{ threews_session }, sync] = await Promise.all([+ chrome.storage.local.get('threews_session'),+ chrome.storage.sync.get(null),+ ]);+ session = threews_session || null;+ settings = { ...settings, ...sync };+ }})();diff --git a/extensions/walk-avatar/manifest.json b/extensions/walk-avatar/manifest.jsonindex 4c0070b84..2343f5837 100644--- a/extensions/walk-avatar/manifest.json+++ b/extensions/walk-avatar/manifest.json@@ -3,7 +3,7 @@"name": "three.ws Walk Avatar","short_name": "Walk Avatar","version": "1.0.0",- "description": "Walk your three.ws avatar on any website you visit — browse the web with a living 3D companion.",+ "description": "Walk your three.ws avatar on any site and have it read pages aloud — a living 3D browsing companion.","homepage_url": "https://three.ws/extension","icons": {@@ -34,22 +34,17 @@"permissions": ["storage","activeTab",- "scripting"+ "scripting",+ "tabs"],"host_permissions": [+ "https://three.ws/*","<all_urls>"],"options_page": "options.html",- "web_accessible_resources": [- {- "resources": ["styles/inject.css"],- "matches": ["<all_urls>"]- }- ],-"content_security_policy": {"extension_pages": "script-src 'self'; object-src 'self'"},diff --git a/extensions/walk-avatar/popup.html b/extensions/walk-avatar/popup.htmlindex 96a4966ae..4cd33f862 100644--- a/extensions/walk-avatar/popup.html+++ b/extensions/walk-avatar/popup.html@@ -8,10 +8,12 @@:root {--bg: #0a0a0a;--surface: #141414;+ --surface-2: #1c1c1c;--border: rgba(255,255,255,0.08);--text: #fafafa;--text-2: #a1a1aa;--accent: #7dd3fc;+ --accent-soft: rgba(125,211,252,0.12);--danger: #f87171;--success: #34d399;}@@ -25,6 +27,7 @@font-size: 13px;-webkit-font-smoothing: antialiased;}+.header {display: flex;align-items: center;@@ -32,24 +35,10 @@padding: 12px 16px;border-bottom: 1px solid var(--border);}- .header-logo {- font-size: 14px;- font-weight: 600;- color: var(--text);- }+ .header-logo { font-size: 14px; font-weight: 600; color: var(--text); }.header-logo span { color: var(--accent); }- .auth-pill {- display: flex;- align-items: center;- gap: 6px;- font-size: 11px;- color: var(--text-2);- }- .auth-pill .dot {- width: 6px; height: 6px;- border-radius: 50%;- background: var(--text-2);- }+ .auth-pill { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--text-2); }+ .auth-pill .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--text-2); transition: background 0.2s; }.auth-pill.signed-in .dot { background: var(--success); }.sign-in-btn {background: transparent;@@ -59,16 +48,15 @@padding: 3px 8px;border-radius: 6px;cursor: pointer;+ transition: background 0.15s, border-color 0.15s;}- .sign-in-btn:hover { background: rgba(125,211,252,0.08); }+ .sign-in-btn:hover { background: var(--accent-soft); border-color: var(--accent); }+ .sign-in-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }- .tabs {- display: flex;- border-bottom: 1px solid var(--border);- }+ .tabs { display: flex; border-bottom: 1px solid var(--border); }.tab-btn {flex: 1;- padding: 8px;+ padding: 9px 8px;background: transparent;border: 0;border-bottom: 2px solid transparent;@@ -77,11 +65,17 @@cursor: pointer;transition: color 0.15s, border-color 0.15s;}+ .tab-btn:hover { color: var(--text); }.tab-btn.active { color: var(--text); border-bottom-color: var(--accent); }+ .tab-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }.tab-panel { display: none; }.tab-panel.active { display: block; }+ .scroll-area { max-height: 248px; overflow-y: auto; }+ .scroll-area::-webkit-scrollbar { width: 8px; }+ .scroll-area::-webkit-scrollbar-thumb { background: var(--border); border-radius: 8px; }+.avatar-grid {display: grid;grid-template-columns: repeat(3, 1fr);@@ -89,88 +83,80 @@padding: 12px;}.avatar-thumb {+ position: relative;aspect-ratio: 1;border-radius: 10px;overflow: hidden;cursor: pointer;border: 2px solid transparent;- transition: border-color 0.15s;+ transition: border-color 0.15s, transform 0.12s, box-shadow 0.15s;background: var(--surface);+ padding: 0;}- .avatar-thumb.selected { border-color: var(--accent); }- .avatar-thumb img {- width: 100%; height: 100%;- object-fit: cover;- display: block;- }+ .avatar-thumb:hover { transform: translateY(-2px); box-shadow: 0 6px 18px rgba(0,0,0,0.4); }+ .avatar-thumb:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .avatar-thumb.selected { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }+ .avatar-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }+ .avatar-thumb.no-thumb { display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, var(--surface-2), var(--surface)); }+ .thumb-glyph { font-size: 28px; font-weight: 600; color: var(--accent); }+.skeleton {- background: linear-gradient(90deg, var(--surface) 25%, rgba(255,255,255,0.05) 50%, var(--surface) 75%);+ background: linear-gradient(90deg, var(--surface) 25%, rgba(255,255,255,0.06) 50%, var(--surface) 75%);background-size: 200% 100%;animation: shimmer 1.4s infinite;+ cursor: default;}- @keyframes shimmer {- 0% { background-position: -200% 0; }- 100% { background-position: 200% 0; }- }- .empty-state {- padding: 32px 16px;- text-align: center;- color: var(--text-2);- }- .empty-state a {- color: var(--accent);- text-decoration: none;+ @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }++ .empty-state { grid-column: 1 / -1; padding: 28px 16px; text-align: center; color: var(--text-2); }+ .empty-emoji { font-size: 30px; margin-bottom: 8px; }+ .empty-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 4px; }+ .empty-sub { font-size: 11.5px; line-height: 1.5; margin: 0 0 14px; }+ .cta-btn {+ background: var(--accent);+ color: #001018;+ border: 0;+ padding: 8px 16px;+ border-radius: 8px;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ transition: opacity 0.15s, transform 0.1s;}+ .cta-btn:hover { opacity: 0.9; }+ .cta-btn:active { transform: scale(0.98); }+ .cta-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .cta-btn.ghost { background: transparent; color: var(--accent); border: 1px solid var(--border); }+ .cta-btn.ghost:hover { background: var(--accent-soft); border-color: var(--accent); }- .footer {- padding: 12px 16px;- border-top: 1px solid var(--border);- display: flex;+ .error-msg {+ margin: 0 12px 12px;+ padding: 10px 12px;+ font-size: 11.5px;+ color: var(--danger);+ background: rgba(248,113,113,0.08);+ border: 1px solid rgba(248,113,113,0.3);+ border-radius: 8px;+ display: none;align-items: center;justify-content: space-between;- gap: 12px;+ gap: 10px;}- .toggle-label {- font-size: 12px;- font-weight: 500;- color: var(--text);- }- .toggle-sub {+ .err-text { flex: 1; }+ .retry-btn {+ background: transparent;+ border: 1px solid var(--danger);+ color: var(--danger);+ padding: 3px 10px;+ border-radius: 6px;font-size: 11px;- color: var(--text-2);- }- .toggle-switch {- position: relative;- width: 44px; height: 24px;- flex-shrink: 0;- }- .toggle-switch input {- opacity: 0; width: 0; height: 0;- }- .toggle-track {- position: absolute;- inset: 0;- border-radius: 24px;- background: var(--border);cursor: pointer;- transition: background 0.2s;- }- .toggle-switch input:checked + .toggle-track { background: var(--accent); }- .toggle-track::after {- content: '';- position: absolute;- top: 3px; left: 3px;- width: 18px; height: 18px;- border-radius: 50%;- background: white;- transition: transform 0.2s;- }- .toggle-switch input:checked + .toggle-track::after {- transform: translateX(20px);+ flex-shrink: 0;}+ .retry-btn:hover { background: rgba(248,113,113,0.12); }.speed-row {- padding: 8px 16px 0;+ padding: 10px 16px 0;display: flex;align-items: center;gap: 8px;@@ -178,12 +164,42 @@color: var(--text-2);}.speed-row input[type=range] { flex: 1; accent-color: var(--accent); }+ #speed-val { width: 34px; text-align: right; font-variant-numeric: tabular-nums; color: var(--text); }- .error-msg {- padding: 8px 16px;- font-size: 11px;+ .footer {+ padding: 12px 16px;+ border-top: 1px solid var(--border);+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ }+ .footer.disabled { opacity: 0.5; }+ .toggle-label { font-size: 12px; font-weight: 500; color: var(--text); }+ .toggle-sub { font-size: 11px; color: var(--text-2); margin-top: 2px; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .filtered-tag {+ display: inline-block;+ margin-left: 4px;+ padding: 1px 6px;+ border-radius: 999px;+ font-size: 9.5px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ background: rgba(248,113,113,0.14);color: var(--danger);}+ .toggle-switch { position: relative; width: 44px; height: 24px; flex-shrink: 0; }+ .toggle-switch input { opacity: 0; width: 0; height: 0; }+ .toggle-track { position: absolute; inset: 0; border-radius: 24px; background: var(--border); cursor: pointer; transition: background 0.2s; }+ .toggle-switch input:checked + .toggle-track { background: var(--accent); }+ .toggle-switch input:focus-visible + .toggle-track { outline: 2px solid var(--accent); outline-offset: 2px; }+ .toggle-switch input:disabled + .toggle-track { cursor: not-allowed; }+ .toggle-track::after { content: ''; position: absolute; top: 3px; left: 3px; width: 18px; height: 18px; border-radius: 50%; background: white; transition: transform 0.2s; }+ .toggle-switch input:checked + .toggle-track::after { transform: translateX(20px); }++ .subnav { display: flex; justify-content: flex-end; padding: 6px 16px 0; }+ .settings-link { font-size: 11px; color: var(--text-2); text-decoration: none; display: inline-flex; align-items: center; gap: 4px; }+ .settings-link:hover { color: var(--accent); }</style></head><body>@@ -196,32 +212,40 @@</div></div>- <div class="tabs">- <button class="tab-btn active" data-tab="mine">My Avatars</button>- <button class="tab-btn" data-tab="featured">Featured</button>+ <div class="tabs" role="tablist">+ <button class="tab-btn active" data-tab="mine" role="tab" aria-selected="true">My Avatars</button>+ <button class="tab-btn" data-tab="featured" role="tab" aria-selected="false">Featured</button></div>- <div class="tab-panel active" id="tab-mine">- <div class="avatar-grid" id="grid-mine">- <div class="avatar-thumb skeleton"></div>- <div class="avatar-thumb skeleton"></div>- <div class="avatar-thumb skeleton"></div>+ <div class="scroll-area">+ <div class="tab-panel active" id="tab-mine" role="tabpanel">+ <div class="avatar-grid" id="grid-mine">+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ </div>+ <div class="error-msg" id="error-mine"></div></div>- <div class="error-msg" id="error-mine" style="display:none"></div>- </div>- <div class="tab-panel" id="tab-featured">- <div class="avatar-grid" id="grid-featured">- <div class="avatar-thumb skeleton"></div>- <div class="avatar-thumb skeleton"></div>- <div class="avatar-thumb skeleton"></div>+ <div class="tab-panel" id="tab-featured" role="tabpanel">+ <div class="avatar-grid" id="grid-featured">+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ <div class="avatar-thumb skeleton"></div>+ </div>+ <div class="error-msg" id="error-featured"></div></div>- <div class="error-msg" id="error-featured" style="display:none"></div></div><div class="speed-row">- <span>Speed</span>- <input type="range" id="speed-slider" min="0.5" max="2" step="0.1" value="1" />+ <span>Walk speed</span>+ <input type="range" id="speed-slider" min="0.5" max="2" step="0.1" value="1" aria-label="Walk speed" /><span id="speed-val">1.0×</span></div>@@ -231,11 +255,15 @@<div class="toggle-sub" id="current-site">–</div></div><label class="toggle-switch">- <input type="checkbox" id="enable-toggle" />+ <input type="checkbox" id="enable-toggle" aria-label="Enable avatar on this site" /><div class="toggle-track"></div></label></div>+ <div class="subnav">+ <a href="#" class="settings-link" id="settings-link">All settings →</a>+ </div>+<script src="popup.js"></script></body></html>diff --git a/extensions/walk-avatar/popup.js b/extensions/walk-avatar/popup.jsindex 82eda462d..94c9e17c2 100644--- a/extensions/walk-avatar/popup.js+++ b/extensions/walk-avatar/popup.js@@ -1,20 +1,33 @@-// popup.js — popup controller for the Walk Avatar extension.+// popup.js — controller for the Walk Avatar popup.+//+// Wires the real three.ws API:+// GET /api/threews/me — session identity (username)+// GET /api/avatars — the signed-in user's avatars+// GET /api/avatars?include_public=true&visibility=public — featured/public+// Thumbnails come back on each avatar as `thumbnail_url` (a CDN URL); the GLB+// model is `model_url`. No per-thumb endpoint is needed.const THREEWS = 'https://three.ws';-let state = {+const state = {session: null,settings: {},selectedAvatarId: '',currentTab: null,tabEnabled: false,+ activeTab: 'mine',};-// ── Helpers ───────────────────────────────────────────────────────────────-async function apiFetch(path, opts = {}) {- const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };+// ── API ───────────────────────────────────────────────────────────────────+async function apiFetch(path) {+ const headers = { Accept: 'application/json' };if (state.session) headers['Authorization'] = `Bearer ${state.session}`;- const res = await fetch(`${THREEWS}${path}`, { ...opts, headers });+ const res = await fetch(`${THREEWS}${path}`, { headers, credentials: 'include' });+ if (res.status === 401) {+ const err = new Error('unauthorized');+ err.status = 401;+ throw err;+ }if (!res.ok) throw new Error(`HTTP ${res.status}`);return res.json();}@@ -23,7 +36,11 @@ function msg(type, data = {}) {return chrome.runtime.sendMessage({ type, ...data });}-// ── Auth ──────────────────────────────────────────────────────────────────+function openLogin() {+ chrome.tabs.create({ url: `${THREEWS}/login?redirect=extension` });+}++// ── Auth header ────────────────────────────────────────────────────────────async function renderAuth() {const pill = document.getElementById('auth-pill');const label = document.getElementById('auth-label');@@ -31,9 +48,10 @@ async function renderAuth() {if (state.session) {try {- const { user } = await apiFetch('/api/me');+ const body = await apiFetch('/api/threews/me');+ const user = body?.data?.user || body?.user || {};pill.classList.add('signed-in');- label.textContent = `@${user.handle || user.email}`;+ label.textContent = user.username ? `@${user.username}` : (user.display_name || 'signed in');signInBtn.textContent = 'Sign out';signInBtn.onclick = async () => {await msg('clear-session');@@ -41,172 +59,267 @@ async function renderAuth() {renderAuth();loadAvatars('mine');};- } catch {- // Token invalid — clear it- await msg('clear-session');- state.session = null;- renderAuth();+ return;+ } catch (err) {+ if (err.status === 401) {+ await msg('clear-session');+ state.session = null;+ }}- } else {- pill.classList.remove('signed-in');- label.textContent = 'not signed in';- signInBtn.textContent = 'Sign in';- signInBtn.onclick = () => {- chrome.tabs.create({ url: `${THREEWS}/login?redirect=extension` });- };}++ pill.classList.remove('signed-in');+ label.textContent = 'not signed in';+ signInBtn.textContent = 'Sign in';+ signInBtn.onclick = openLogin;}-// ── Avatar grids ──────────────────────────────────────────────────────────-function renderAvatarGrid(gridEl, errorEl, avatars) {- gridEl.innerHTML = '';- errorEl.style.display = 'none';+// ── Avatar grids ────────────────────────────────────────────────────────────+function skeleton(n = 6) {+ return Array.from({ length: n }, () => '<div class="avatar-thumb skeleton" aria-hidden="true"></div>').join('');+}- if (!avatars || avatars.length === 0) {- gridEl.innerHTML = `<div class="empty-state" style="grid-column:1/-1">- No avatars yet. <a href="${THREEWS}/create-selfie" target="_blank">Create one →</a>- </div>`;- return;+function renderEmpty(gridEl, tab) {+ if (tab === 'mine') {+ gridEl.innerHTML = `+ <div class="empty-state" role="status">+ <div class="empty-emoji" aria-hidden="true">🚶</div>+ <div class="empty-title">No avatars yet</div>+ <p class="empty-sub">Create a 3D avatar from a selfie, then walk it on any site.</p>+ <button class="cta-btn" id="create-cta">Create your first avatar</button>+ </div>`;+ gridEl.querySelector('#create-cta')?.addEventListener('click', () => {+ chrome.tabs.create({ url: `${THREEWS}/create-selfie` });+ });+ } else {+ gridEl.innerHTML = `+ <div class="empty-state" role="status">+ <div class="empty-emoji" aria-hidden="true">✨</div>+ <div class="empty-title">No featured avatars right now</div>+ <p class="empty-sub">Check back soon, or browse the gallery.</p>+ <button class="cta-btn ghost" id="gallery-cta">Open gallery</button>+ </div>`;+ gridEl.querySelector('#gallery-cta')?.addEventListener('click', () => {+ chrome.tabs.create({ url: `${THREEWS}/gallery` });+ });}+}- avatars.forEach((av) => {- const thumb = document.createElement('div');+function renderError(gridEl, errorEl, tab, message) {+ gridEl.innerHTML = '';+ errorEl.innerHTML = `+ <span class="err-text">Couldn't load avatars — ${message}</span>+ <button class="retry-btn" id="retry-${tab}">Retry</button>`;+ errorEl.style.display = 'flex';+ errorEl.querySelector(`#retry-${tab}`)?.addEventListener('click', () => loadAvatars(tab));+}++function renderAvatarGrid(gridEl, avatars) {+ gridEl.innerHTML = '';+ for (const av of avatars) {+ const thumb = document.createElement('button');thumb.className = 'avatar-thumb' + (av.id === state.selectedAvatarId ? ' selected' : '');- thumb.title = av.name || av.id;-- const img = document.createElement('img');- img.src = av.thumbnail_url || `${THREEWS}/api/avatars/${av.id}/thumb`;- img.alt = av.name || 'avatar';- img.onerror = () => { img.src = `${THREEWS}/public/og-image.png`; };-- thumb.appendChild(img);- thumb.addEventListener('click', () => {- state.selectedAvatarId = av.id;- gridEl.querySelectorAll('.avatar-thumb').forEach(t => t.classList.remove('selected'));- thumb.classList.add('selected');- // Persist selection and update active tab- msg('set-avatar', { avatarId: av.id });- });+ thumb.type = 'button';+ thumb.title = av.name || 'Avatar';+ thumb.setAttribute('aria-label', `Select avatar ${av.name || ''}`.trim());+ thumb.setAttribute('aria-pressed', av.id === state.selectedAvatarId ? 'true' : 'false');++ if (av.thumbnail_url) {+ const img = document.createElement('img');+ img.src = av.thumbnail_url;+ img.alt = av.name || 'avatar';+ img.loading = 'lazy';+ img.addEventListener('error', () => {+ img.remove();+ thumb.classList.add('no-thumb');+ thumb.appendChild(fallbackGlyph(av.name));+ });+ thumb.appendChild(img);+ } else {+ thumb.classList.add('no-thumb');+ thumb.appendChild(fallbackGlyph(av.name));+ }+ thumb.addEventListener('click', () => selectAvatar(av.id, gridEl, thumb));gridEl.appendChild(thumb);- });+ }+}++function fallbackGlyph(name) {+ const span = document.createElement('span');+ span.className = 'thumb-glyph';+ span.textContent = (name || '?').trim().charAt(0).toUpperCase() || '?';+ return span;+}++function selectAvatar(avatarId, gridEl, thumbEl) {+ state.selectedAvatarId = avatarId;+ for (const t of gridEl.parentElement.parentElement.querySelectorAll('.avatar-thumb')) {+ const on = t === thumbEl;+ t.classList.toggle('selected', on);+ t.setAttribute('aria-pressed', on ? 'true' : 'false');+ }+ msg('set-avatar', { avatarId });+ // If the avatar is already running on this tab, the background broadcast+ // swaps it live; otherwise the selection is stored for the next enable.}async function loadAvatars(tab) {+ state.activeTab = tab;const gridEl = document.getElementById(`grid-${tab}`);const errorEl = document.getElementById(`error-${tab}`);-- // Show skeletons- gridEl.innerHTML = Array.from({ length: 3 }, () =>- '<div class="avatar-thumb skeleton"></div>'- ).join('');+ errorEl.style.display = 'none';+ gridEl.innerHTML = skeleton();try {- if (tab === 'mine') {- if (!state.session) {- gridEl.innerHTML = `<div class="empty-state" style="grid-column:1/-1">- <a href="#" id="sign-in-link">Sign in</a> to see your avatars.+ if (tab === 'mine' && !state.session) {+ gridEl.innerHTML = `+ <div class="empty-state" role="status">+ <div class="empty-emoji" aria-hidden="true">🔑</div>+ <div class="empty-title">Sign in to see your avatars</div>+ <p class="empty-sub">Your three.ws avatars sync here once you sign in.</p>+ <button class="cta-btn" id="signin-cta">Sign in</button></div>`;- document.getElementById('sign-in-link')?.addEventListener('click', (e) => {- e.preventDefault();- chrome.tabs.create({ url: `${THREEWS}/login?redirect=extension` });- });- return;- }- const { avatars } = await apiFetch('/api/avatars/mine');- renderAvatarGrid(gridEl, errorEl, avatars);- } else {- const { avatars } = await apiFetch('/api/avatars/featured');- renderAvatarGrid(gridEl, errorEl, avatars);+ gridEl.querySelector('#signin-cta')?.addEventListener('click', openLogin);+ return;}++ const path = tab === 'mine'+ ? '/api/avatars?limit=60'+ : '/api/avatars?include_public=true&visibility=public&limit=60';+ const body = await apiFetch(path);+ const avatars = (body.avatars || []).filter((a) => a && a.id);++ if (avatars.length === 0) {+ renderEmpty(gridEl, tab);+ return;+ }+ renderAvatarGrid(gridEl, avatars);} catch (err) {- gridEl.innerHTML = '';- errorEl.textContent = `Failed to load avatars: ${err.message}`;- errorEl.style.display = 'block';+ if (err.status === 401) {+ await msg('clear-session');+ state.session = null;+ renderAuth();+ loadAvatars(tab);+ return;+ }+ renderError(gridEl, errorEl, tab, err.message);}}-// ── Current tab ───────────────────────────────────────────────────────────+// ── Current tab ──────────────────────────────────────────────────────────────async function initCurrentTab() {const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });state.currentTab = tab;const siteEl = document.getElementById('current-site');- if (tab?.url) {- try {- siteEl.textContent = new URL(tab.url).hostname;- } catch {- siteEl.textContent = tab.url.slice(0, 40);- }+ const toggle = document.getElementById('enable-toggle');++ const restricted = !tab?.url || /^(chrome|edge|about|chrome-extension|devtools):/i.test(tab.url);+ if (restricted) {+ siteEl.textContent = 'unavailable on this page';+ toggle.disabled = true;+ toggle.closest('.footer')?.classList.add('disabled');+ return;}- // Restore toggle state from session storage (per-tab)- const stored = await chrome.storage.session.get(`tab_enabled_${tab?.id}`).catch(() => ({}));- state.tabEnabled = !!stored[`tab_enabled_${tab?.id}`];- document.getElementById('enable-toggle').checked = state.tabEnabled;+ let host = tab.url;+ try { host = new URL(tab.url).hostname; } catch {}+ siteEl.textContent = host;++ // Per-tab enable state is kept in session storage, set when the popup toggles.+ const key = `tab_enabled_${tab.id}`;+ const stored = await chrome.storage.session.get(key).catch(() => ({}));+ state.tabEnabled = !!stored[key];+ toggle.checked = state.tabEnabled;++ // Surface allow/blocklist filtering so the user knows why a toggle is a no-op.+ const { allowed } = await msg('check-site', { url: tab.url }).catch(() => ({ allowed: true }));+ if (!allowed) {+ siteEl.innerHTML = `${host} <span class="filtered-tag">filtered</span>`;+ }}-// ── Toggle ────────────────────────────────────────────────────────────────+// ── Toggle ────────────────────────────────────────────────────────────────────document.getElementById('enable-toggle').addEventListener('change', async (e) => {const enabled = e.target.checked;- state.tabEnabled = enabled;-if (!state.currentTab) return;const key = `tab_enabled_${state.currentTab.id}`;- chrome.storage.session.set({ [key]: enabled }).catch(() => {});-- await msg('toggle-tab', {+ const res = await msg('toggle-tab', {tabId: state.currentTab.id,enabled,avatarId: state.selectedAvatarId || state.settings.avatarId,});++ if (enabled && res && res.ok === false) {+ // Site filtered or injection blocked — revert the switch and explain.+ e.target.checked = false;+ const siteEl = document.getElementById('current-site');+ siteEl.innerHTML = `${siteEl.textContent} <span class="filtered-tag">${res.reason || res.error}</span>`;+ await chrome.storage.session.set({ [key]: false }).catch(() => {});+ return;+ }++ state.tabEnabled = enabled;+ await chrome.storage.session.set({ [key]: enabled }).catch(() => {});});-// ── Speed slider ──────────────────────────────────────────────────────────+// ── Speed slider ──────────────────────────────────────────────────────────────const speedSlider = document.getElementById('speed-slider');const speedVal = document.getElementById('speed-val');speedSlider.addEventListener('input', () => {- const v = parseFloat(speedSlider.value);- speedVal.textContent = v.toFixed(1) + '×';+ speedVal.textContent = parseFloat(speedSlider.value).toFixed(1) + '×';});speedSlider.addEventListener('change', async () => {const v = parseFloat(speedSlider.value);await msg('update-settings', { settings: { walkSpeed: v } });- // Send live update to active tab- if (state.currentTab) {- chrome.tabs.sendMessage(state.currentTab.id, {- type: 'walk:setSpeed',- speed: v,- }).catch(() => {});- }});-// ── Tab switching ─────────────────────────────────────────────────────────+// ── Tab bar ────────────────────────────────────────────────────────────────────document.querySelectorAll('.tab-btn').forEach((btn) => {btn.addEventListener('click', () => {const tab = btn.dataset.tab;- document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b === btn));- document.querySelectorAll('.tab-panel').forEach(p => {+ document.querySelectorAll('.tab-btn').forEach((b) => {+ const on = b === btn;+ b.classList.toggle('active', on);+ b.setAttribute('aria-selected', on ? 'true' : 'false');+ });+ document.querySelectorAll('.tab-panel').forEach((p) => {p.classList.toggle('active', p.id === `tab-${tab}`);});loadAvatars(tab);});});-// ── Boot ──────────────────────────────────────────────────────────────────+// Open the full settings page.+document.getElementById('settings-link').addEventListener('click', (e) => {+ e.preventDefault();+ chrome.runtime.openOptionsPage();+});++// React to the session token arriving from the auth-callback tab while the+// popup is still open.+chrome.runtime.onMessage.addListener((m) => {+ if (m.type === 'session-updated' && m.token) {+ state.session = m.token;+ renderAuth();+ loadAvatars(state.activeTab);+ }+});++// ── Boot ──────────────────────────────────────────────────────────────────────(async () => {const { session, settings } = await msg('get-state');state.session = session;state.settings = settings || {};state.selectedAvatarId = state.settings.avatarId || '';- if (state.settings.walkSpeed) {- speedSlider.value = String(state.settings.walkSpeed);- speedVal.textContent = parseFloat(state.settings.walkSpeed).toFixed(1) + '×';- }+ const speed = state.settings.walkSpeed || 1;+ speedSlider.value = String(speed);+ speedVal.textContent = parseFloat(speed).toFixed(1) + '×';await Promise.all([renderAuth(),diff --git a/package.json b/package.jsonindex 78d1812bd..d9a912456 100644--- a/package.json+++ b/package.json@@ -79,6 +79,7 @@"changelog:push": "node scripts/changelog-telegram.mjs","audit:deploy": "node scripts/audit-deploy-artifacts.mjs","verify:solana": "node scripts/verify-solana-parity.mjs",+ "verify:onchain": "node scripts/verify-onchain-parity.mjs","smoke:onchain": "node scripts/onchain-smoke.mjs","smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity","smoke:agent-wallet": "node scripts/agent-wallet-smoke.mjs",diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex df2d0a3bb..bbc89460e 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -476,17 +476,17 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- quality tier --><div class="tier-row" id="fgTiers" role="radiogroup" aria-label="Generation quality tier">- <button class="tier" type="button" role="radio" aria-checked="true" data-tier="draft">+ <button class="tier" type="button" role="radio" aria-checked="true" tabindex="0" data-tier="draft"><span class="t-name"><span class="t-tier">Draft</span><span class="t-price" data-price>$0.05</span></span><span class="t-blurb">Fast preview geometry. Best to try the flow.</span><span class="t-eta" data-eta>~40s</span></button>- <button class="tier" type="button" role="radio" aria-checked="false" data-tier="standard">+ <button class="tier" type="button" role="radio" aria-checked="false" tabindex="-1" data-tier="standard"><span class="t-name"><span class="t-tier">Standard</span><span class="t-price" data-price>$0.15</span></span><span class="t-blurb">Balanced detail. The default for most assets.</span><span class="t-eta" data-eta>~60s</span></button>- <button class="tier" type="button" role="radio" aria-checked="false" data-tier="high">+ <button class="tier" type="button" role="radio" aria-checked="false" tabindex="-1" data-tier="high"><span class="t-name"><span class="t-tier">High</span><span class="t-price" data-price>$0.50</span></span><span class="t-blurb">Maximum geometry + PBR textures. Slower.</span><span class="t-eta" data-eta>~130s</span>@@ -1602,21 +1602,43 @@ agent-3d:defined ~ .agent-skel{display:none}});}- // ── tier selection ─────────────────────────────────────────────────────────- function selectTier(tier) {- if (tier === selectedTier || !TIER_ATOMIC[tier]) return;+ // ── tier selection (WAI-ARIA radiogroup) ─────────────────────────────────────+ // Selection drives a roving tabindex: only the checked radio is in the tab+ // order, so Tab lands on the group once and Arrow/Home/End move within it —+ // the operable behaviour the role="radiogroup"/role="radio" markup promises.+ function tierButtons() {+ return Array.prototype.slice.call(document.querySelectorAll('#fgTiers .tier'));+ }+ function selectTier(tier, focusIt) {+ if (!TIER_ATOMIC[tier]) return;+ var changed = tier !== selectedTier;selectedTier = tier;- document.querySelectorAll('#fgTiers .tier').forEach(function (btn) {- btn.setAttribute('aria-checked', btn.getAttribute('data-tier') === tier ? 'true' : 'false');+ tierButtons().forEach(function (btn) {+ var on = btn.getAttribute('data-tier') === tier;+ btn.setAttribute('aria-checked', on ? 'true' : 'false');+ btn.tabIndex = on ? 0 : -1;+ if (on && focusIt) { try { btn.focus(); } catch (_) {} }});- syncTierUi();- loadChallengePreview();+ if (changed) { syncTierUi(); loadChallengePreview(); }}// ── wiring ──────────────────────────────────────────────────────────────────- document.querySelectorAll('#fgTiers .tier').forEach(function (btn) {- btn.addEventListener('click', function () { selectTier(btn.getAttribute('data-tier')); });- });+ (function wireTierKeys() {+ var btns = tierButtons();+ btns.forEach(function (btn, i) {+ btn.addEventListener('click', function () { selectTier(btn.getAttribute('data-tier')); });+ btn.addEventListener('keydown', function (e) {+ var key = e.key, next = -1;+ if (key === 'ArrowRight' || key === 'ArrowDown') next = (i + 1) % btns.length;+ else if (key === 'ArrowLeft' || key === 'ArrowUp') next = (i - 1 + btns.length) % btns.length;+ else if (key === 'Home') next = 0;+ else if (key === 'End') next = btns.length - 1;+ else return;+ e.preventDefault();+ selectTier(btns[next].getAttribute('data-tier'), true);+ });+ });+ })();$('fgBtn').addEventListener('click', runForge);$('fgPrompt').addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); runForge(); } });var pvTimer;diff --git a/public/app-demo.css b/public/app-demo.cssindex 4a6ec39a5..ae02517ff 100644--- a/public/app-demo.css+++ b/public/app-demo.css@@ -12,7 +12,7 @@body.app-demo-body {background: #0a0a0a;color: #eee;- font-family: 'Inter', system-ui, -apple-system, sans-serif;+ font-family: var(--font-body);font-size: 14px;line-height: 1.45;}@@ -329,7 +329,7 @@ body.app-demo-body .auth-gate__eyebrow {}body.app-demo-body .auth-gate__title {- font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ font-family: var(--font-display);font-size: 1.35rem;font-weight: 600;color: #fff;@@ -402,7 +402,7 @@ body.app-demo-body .agent-onboarding {}body.app-demo-body .agent-onboarding__title {- font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ font-family: var(--font-display);}body.app-demo-body .agent-onboarding__btn {diff --git a/public/app-next.css b/public/app-next.cssindex 205186ba6..fdafa32c1 100644--- a/public/app-next.css+++ b/public/app-next.css@@ -41,7 +41,7 @@ body.app-next-body {/* Base depth gradient */radial-gradient(ellipse 90% 70% at 50% 60%, #0e0e0e 0%, #080808 55%, #020202 100%);color: var(--nxt-ink);- font-family: 'Inter', system-ui, -apple-system, sans-serif;+ font-family: var(--font-body);overflow: hidden;}@@ -1753,7 +1753,7 @@ body.app-next-body .dg.ac { display: none !important; }}.nxt-visitor-card__name {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 16px;font-weight: 600;color: #f5f5f7;diff --git a/public/avatar-sdk.css b/public/avatar-sdk.cssindex f6150075f..fa4c6b9fb 100644--- a/public/avatar-sdk.css+++ b/public/avatar-sdk.css@@ -15,7 +15,7 @@ body {display: flex;flex-direction: column;min-height: 100vh;- font-family: 'Inter', system-ui, sans-serif;+ font-family: var(--font-body);}/* ── Scroll reveal ─────────────────────────────────────────────────── */@@ -130,7 +130,7 @@ body {50% { box-shadow: 0 0 16px rgba(160, 160, 160, 1); }}.sdk-hero-h1 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(36px, 5vw, 56px);font-weight: 700;letter-spacing: -0.03em;@@ -170,7 +170,7 @@ body {border: 1px solid var(--stroke-strong);border-radius: var(--radius-control);padding: 12px 16px;- font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-family: var(--font-mono);font-size: 13.5px;color: var(--ink);cursor: pointer;@@ -304,7 +304,7 @@ body {gap: 4px;}.sdk-stat-value {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 24px;font-weight: 700;color: #ffffff;@@ -373,7 +373,7 @@ body {background: var(--accent);}.sdk-h2 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(26px, 3.5vw, 38px);font-weight: 700;letter-spacing: -0.02em;@@ -430,7 +430,7 @@ body {border: 1px solid var(--icon-border, rgba(160, 160, 160, 0.2));}.sdk-feat-title {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 16px;font-weight: 600;color: var(--ink);@@ -515,7 +515,7 @@ pre.sdk-pre {border-radius: var(--radius-control);padding: 18px 20px;overflow-x: auto;- font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-family: var(--font-mono);font-size: 13px;line-height: 1.75;color: #d3d3d3;@@ -603,7 +603,7 @@ pre.sdk-pre .t-op { color: #a1a1a1; }display: flex;align-items: center;justify-content: center;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 16px;font-weight: 700;color: var(--accent);@@ -612,7 +612,7 @@ pre.sdk-pre .t-op { color: #a1a1a1; }}.sdk-step-body {}.sdk-step-title {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 18px;font-weight: 600;color: var(--ink);@@ -821,7 +821,7 @@ table.sdk-table {background: rgba(255, 255, 255, 0.04);padding: 14px 20px;text-align: left;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 13px;font-weight: 600;color: var(--ink);@@ -946,7 +946,7 @@ table.sdk-table {pointer-events: none;}.sdk-cta-banner h2 {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 28px;font-weight: 700;letter-spacing: -0.02em;diff --git a/public/avatar-studio-demo.css b/public/avatar-studio-demo.cssindex 64b0f99d1..28feeab3f 100644--- a/public/avatar-studio-demo.css+++ b/public/avatar-studio-demo.css@@ -23,7 +23,7 @@ html, body {padding: 0;background: var(--as-bg);color: var(--as-text);- font-family: 'Inter', system-ui, -apple-system, sans-serif;+ font-family: var(--font-body);-webkit-font-smoothing: antialiased;overflow: hidden;height: 100%;@@ -49,7 +49,7 @@ html, body {gap: 10px;text-decoration: none;color: var(--as-text);- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 15px;font-weight: 600;letter-spacing: -0.02em;diff --git a/public/changelog.json b/public/changelog.jsonindex c46ea53fe..c4b4b6e1b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T01:33:56.909Z",+ "generated_at": "2026-06-19T01:47:46.340Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.css b/public/features.cssindex ab9a3d57a..edf3f1a8d 100644--- a/public/features.css+++ b/public/features.css@@ -217,7 +217,7 @@background: rgba(255, 255, 255, 0.035);border: 1px solid rgba(255, 255, 255, 0.08);border-radius: 999px;- font-family: 'JetBrains Mono', 'SF Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;color: rgba(255, 255, 255, 0.7);letter-spacing: 0.08em;@@ -255,7 +255,7 @@}.hero-chip-spec {- color: rgba(255, 215, 0, 0.9);+ color: rgba(var(--gold-rgb), 0.9);}.hero-title {@@ -338,7 +338,7 @@display: flex;flex-wrap: wrap;gap: var(--space-md) var(--space-lg);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.72rem;color: rgba(255, 255, 255, 0.35);letter-spacing: 0.14em;@@ -393,7 +393,7 @@}.hero-avatar-link:focus-visible {- box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.55);+ box-shadow: 0 0 0 2px rgba(var(--gold-rgb), 0.55);}.hero-avatar-viewer {@@ -461,7 +461,7 @@background: rgba(10, 10, 14, 0.7);border: 1px solid rgba(255, 255, 255, 0.08);border-radius: var(--radius-lg);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;color: rgba(255, 255, 255, 0.8);backdrop-filter: blur(12px);@@ -471,7 +471,7 @@}.hero-avatar-tag-label {- color: rgba(255, 215, 0, 0.7);+ color: rgba(var(--gold-rgb), 0.7);letter-spacing: 0.08em;text-transform: uppercase;font-size: 0.6rem;@@ -493,7 +493,7 @@flex-direction: column;align-items: center;gap: 0.5rem;- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.6rem;color: rgba(255, 255, 255, 0.25);letter-spacing: 0.25em;@@ -598,9 +598,9 @@}.section-label {- font-family: 'JetBrains Mono', 'SF Mono', monospace;+ font-family: var(--font-mono);font-size: var(--text-xs);- color: rgba(255, 215, 0, 0.6);+ color: rgba(var(--gold-rgb), 0.6);letter-spacing: 0.15em;text-transform: uppercase;margin: 0 0 var(--space-xl);@@ -637,10 +637,10 @@}.step-num {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: var(--text-2xl);font-weight: 600;- color: rgba(255, 215, 0, 0.15);+ color: rgba(var(--gold-rgb), 0.15);line-height: 1;margin-bottom: var(--space-sm);}@@ -660,10 +660,10 @@}.step code {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.85em;- color: rgba(255, 215, 0, 0.6);- background: rgba(255, 215, 0, 0.06);+ color: rgba(var(--gold-rgb), 0.6);+ background: rgba(var(--gold-rgb), 0.06);padding: 0.1em 0.4em;border-radius: var(--radius-sm);}@@ -706,7 +706,7 @@.code-filename {margin-left: var(--space-sm);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: var(--text-xs);color: rgba(255, 255, 255, 0.35);}@@ -715,7 +715,7 @@margin: 0;padding: var(--space-lg);overflow-x: auto;- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.8rem;line-height: var(--leading-loose);color: rgba(255, 255, 255, 0.6);@@ -773,10 +773,10 @@}.registry-card code {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.8em;- color: rgba(255, 215, 0, 0.6);- background: rgba(255, 215, 0, 0.06);+ color: rgba(var(--gold-rgb), 0.6);+ background: rgba(var(--gold-rgb), 0.06);padding: 0.1em 0.4em;border-radius: var(--radius-sm);}@@ -802,7 +802,7 @@.integration-item {padding: var(--space-lg);- border-left: 2px solid rgba(255, 215, 0, 0.15);+ border-left: 2px solid rgba(var(--gold-rgb), 0.15);}.integration-item h4 {@@ -820,10 +820,10 @@}.integration-item code {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.85em;- color: rgba(255, 215, 0, 0.6);- background: rgba(255, 215, 0, 0.06);+ color: rgba(var(--gold-rgb), 0.6);+ background: rgba(var(--gold-rgb), 0.06);padding: 0.1em 0.4em;border-radius: var(--radius-sm);}@@ -861,7 +861,7 @@.features-footer p {color: rgba(255, 255, 255, 0.25);font-size: var(--text-xs);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);margin: 0;}@@ -1078,7 +1078,7 @@.feat-eyebrow {font-family: var(--font-mono);font-size: var(--text-xs);- color: rgba(255, 215, 0, 0.6);+ color: rgba(var(--gold-rgb), 0.6);letter-spacing: 0.15em;text-transform: uppercase;margin: 0 0 var(--space-lg);@@ -1290,7 +1290,7 @@.feat-forge-cursor {width: 2px;height: 1em;- background: rgba(255, 215, 0, 0.7);+ background: rgba(var(--gold-rgb), 0.7);animation: forgeBlink 1.1s step-end infinite;}@@ -2022,9 +2022,9 @@flex: 0 0 auto;}.feat-goal-pill--core::before { background: var(--success); }-.feat-goal-pill--optional::before { background: rgba(255, 215, 0, 0.85); }+.feat-goal-pill--optional::before { background: rgba(var(--gold-rgb), 0.85); }.feat-goal-pill--core:hover { border-color: rgba(74, 222, 128, 0.4); }-.feat-goal-pill--optional:hover { border-color: rgba(255, 215, 0, 0.4); }+.feat-goal-pill--optional:hover { border-color: rgba(var(--gold-rgb), 0.4); }/* Reassurance / requirements banner that opens each tier */.feat-tier-banner {@@ -2063,10 +2063,10 @@.feat-tier-banner--core .feat-tier-banner-icon { color: var(--success); }.feat-tier-banner--optional {- border-color: rgba(255, 215, 0, 0.22);- background: rgba(255, 215, 0, 0.04);+ border-color: rgba(var(--gold-rgb), 0.22);+ background: rgba(var(--gold-rgb), 0.04);}-.feat-tier-banner--optional .feat-tier-banner-icon { color: rgba(255, 215, 0, 0.85); }+.feat-tier-banner--optional .feat-tier-banner-icon { color: rgba(var(--gold-rgb), 0.85); }/* Per-card requirement chip — what a single Optional feature needs */.feat-req {@@ -2171,7 +2171,7 @@height: 34px;border-radius: 50%;flex: 0 0 auto;- background: radial-gradient(circle at 35% 30%, rgba(255, 215, 0, 0.35), rgba(255, 255, 255, 0.06));+ background: radial-gradient(circle at 35% 30%, rgba(var(--gold-rgb), 0.35), rgba(255, 255, 255, 0.06));border: 1px solid var(--stroke-strong);}@@ -2252,7 +2252,7 @@.feat-dev-eyebrow {font-family: var(--font-mono);font-size: var(--text-xs);- color: rgba(255,215,0,0.6);+ color: rgba(var(--gold-rgb), 0.6);letter-spacing: 0.15em;text-transform: uppercase;margin: 0 0 var(--space-sm);@@ -2270,8 +2270,8 @@.feat-dev-title code {font-family: var(--font-mono);font-size: 0.85em;- color: rgba(255,215,0,0.8);- background: rgba(255,215,0,0.06);+ color: rgba(var(--gold-rgb), 0.8);+ background: rgba(var(--gold-rgb), 0.06);padding: 0.1em 0.35em;border-radius: var(--radius-sm);}@@ -2286,7 +2286,7 @@.feat-dev-sub code {font-family: var(--font-mono);font-size: 0.9em;- color: rgba(255,215,0,0.65);+ color: rgba(var(--gold-rgb), 0.65);}.feat-dev-links {diff --git a/public/features.json b/public/features.jsonindex 56ae7df00..66f805e07 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T01:33:56.767Z",+ "generated_at": "2026-06-19T01:47:46.204Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/footer.css b/public/footer.cssindex e13ebd995..511d4aeee 100644--- a/public/footer.css+++ b/public/footer.css@@ -72,7 +72,7 @@left: 50%;bottom: -0.15em;transform: translateX(-50%);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-weight: 700;font-size: clamp(7rem, 22vw, 22rem);line-height: 0.85;@@ -125,7 +125,7 @@}.h-footer-cta h3 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.4rem;font-weight: 600;margin: 0 0 0.5rem;@@ -135,7 +135,7 @@.h-footer-cta p {margin: 0 0 1.25rem;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.9rem;color: rgba(255, 255, 255, 0.5);line-height: 1.5;@@ -166,7 +166,7 @@border: none;outline: none;color: #fff;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.9rem;padding: 0.6rem 0;}@@ -208,7 +208,7 @@.h-footer-newsletter-msg {margin: 0.6rem 0 0;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.78rem;color: rgba(255, 255, 255, 0.5);min-height: 1em;@@ -231,7 +231,7 @@border: 1px solid rgba(255, 255, 255, 0.1);background: rgba(255, 255, 255, 0.04);color: #fff;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.9rem;font-weight: 500;text-decoration: none;@@ -271,7 +271,7 @@display: flex;align-items: center;gap: 0.4rem;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.1rem;font-weight: 600;color: #fff;@@ -295,7 +295,7 @@}.h-footer-tagline {- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.85rem;color: rgba(255, 255, 255, 0.45);margin: 0;@@ -315,7 +315,7 @@}.h-footer-link-heading {- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.7rem;font-weight: 600;letter-spacing: 0.12em;@@ -377,7 +377,7 @@.h-footer-legal-links a {color: rgba(255, 255, 255, 0.55);text-decoration: none;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.78rem;transition: color 0.2s ease;}@@ -402,7 +402,7 @@.h-footer-legal {margin: 0;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.78rem;font-weight: 400;color: rgba(255, 255, 255, 0.42);@@ -425,7 +425,7 @@border: 1px solid rgba(255, 255, 255, 0.09);background: rgba(255, 255, 255, 0.025);color: rgba(255, 255, 255, 0.62);- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.72rem;font-weight: 500;letter-spacing: 0.01em;@@ -468,7 +468,7 @@}.h-footer-ca-label {- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.72rem;font-weight: 600;color: rgba(255, 255, 255, 0.55);diff --git a/public/home-polish.css b/public/home-polish.cssindex efaf75036..62c375427 100644--- a/public/home-polish.css+++ b/public/home-polish.css@@ -92,7 +92,7 @@right: calc(100% + 0.75rem);top: 50%;transform: translateY(-50%) translateX(4px);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 0.66rem;font-weight: 500;letter-spacing: 0.1em;@@ -171,7 +171,7 @@display: inline-flex;align-items: center;gap: 0.55rem;- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.68rem;font-weight: 500;letter-spacing: 0.14em;@@ -228,7 +228,7 @@}.h-bento-id .h-id-addr {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.72rem;color: rgba(255, 255, 255, 0.6);letter-spacing: 0.02em;@@ -249,7 +249,7 @@display: inline-flex;align-items: center;gap: 0.45em;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 0.7rem;font-weight: 500;color: rgba(255, 255, 255, 0.50);@@ -283,7 +283,7 @@align-items: center;gap: 0.4em;padding: 0.35rem 0.65rem;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 0.66rem;font-weight: 600;letter-spacing: 0.1em;@@ -373,7 +373,7 @@}.h-journey-title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(2rem, 3.8vw, 3.2rem);font-weight: 700;color: #fff;@@ -449,7 +449,7 @@.h-journey-card:hover::before { opacity: 1; }.h-jc-num {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 11px;font-weight: 700;letter-spacing: 0.14em;@@ -483,7 +483,7 @@}.h-jc-body h3 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 16px;font-weight: 600;color: #fff;diff --git a/public/home.css b/public/home.cssindex e39be948c..de484b06b 100644--- a/public/home.css+++ b/public/home.css@@ -114,7 +114,7 @@}.h-trust-num {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.4rem;font-weight: 700;background: #ffffff;@@ -130,7 +130,7 @@letter-spacing: 0.1em;text-transform: uppercase;color: rgba(255, 255, 255, 0.5);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-trust-sep {@@ -169,7 +169,7 @@}.h-traction-val {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(1.6rem, 3vw, 2.2rem);font-weight: 700;color: #fff;@@ -236,7 +236,7 @@}.h-pillar h3 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.15rem;font-weight: 700;color: #fff;@@ -366,7 +366,7 @@letter-spacing: 0.14em;text-transform: uppercase;color: rgba(255, 255, 255, 0.4);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-bento-anim-stop {@@ -470,7 +470,7 @@letter-spacing: 0.14em;text-transform: uppercase;color: rgba(255, 255, 255, 0.8);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);margin-bottom: 0.2rem;}@@ -482,7 +482,7 @@}.h-bento-card h3 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.1rem;font-weight: 600;color: #fff;@@ -504,7 +504,7 @@border: 1px solid rgba(255, 255, 255, 0.05);border-radius: var(--radius-sm);padding: 0.7rem 0.9rem;- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;color: rgba(255, 255, 255, 0.55);line-height: 1.6;@@ -531,7 +531,7 @@.h-bento-emotions span {font-size: 0.68rem;color: rgba(255, 255, 255, 0.40);- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);border: 1px solid rgba(255, 255, 255, 0.10);border-radius: var(--radius-sm);padding: 0.2rem 0.55rem;@@ -563,7 +563,7 @@}.h-dev-text h2 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(1.8rem, 3vw, 2.6rem);font-weight: 700;color: #fff;@@ -580,7 +580,7 @@}.h-dev-sub code {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.88em;color: rgba(255, 255, 255, 0.8);background: rgba(255, 255, 255, 0.08);@@ -618,7 +618,7 @@}.h-dev-code-filename {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;color: rgba(255, 255, 255, 0.3);margin-left: 0.5rem;@@ -631,7 +631,7 @@}.h-dev-pre code {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.82rem;line-height: 1.75;color: rgba(255, 255, 255, 0.55);@@ -733,7 +733,7 @@left: 50%;bottom: -0.15em;transform: translateX(-50%);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-weight: 700;font-size: clamp(7rem, 22vw, 22rem);line-height: 0.85;@@ -793,14 +793,14 @@display: flex;align-items: center;gap: 0.4rem;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.1rem;font-weight: 600;color: #fff;}.h-footer-tagline {- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.85rem;color: rgba(255, 255, 255, 0.45);margin: 0;@@ -844,7 +844,7 @@.h-footer-legal {margin: 0;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.78rem;font-weight: 400;color: rgba(255, 255, 255, 0.42);@@ -867,7 +867,7 @@border: 1px solid rgba(255, 255, 255, 0.09);background: rgba(255, 255, 255, 0.025);color: rgba(255, 255, 255, 0.62);- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: 0.72rem;font-weight: 500;letter-spacing: 0.01em;@@ -1383,7 +1383,7 @@}.h-layer-chains .chain-pill {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 17px;font-weight: 600;letter-spacing: 0.08em;@@ -1493,7 +1493,7 @@text-transform: uppercase;color: rgba(255, 255, 255, 0.65);margin-bottom: 1rem;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-act-dot {@@ -1559,7 +1559,7 @@color: rgba(255, 255, 255, 0.65);font-size: 13px;font-weight: 500;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);cursor: pointer;transition: all 0.2s ease;}@@ -1595,7 +1595,7 @@color: rgba(255, 255, 255, 0.8);font-size: 13px;font-weight: 500;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);cursor: pointer;transition: all 0.15s ease;}@@ -1632,7 +1632,7 @@letter-spacing: 0.12em;text-transform: uppercase;color: rgba(255, 255, 255, 0.42);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-form-input,@@ -1643,7 +1643,7 @@padding: 0.7rem 1rem;color: #fff;font-size: 15px;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);outline: none;transition: border-color 0.2s ease;width: 100%;@@ -1676,7 +1676,7 @@letter-spacing: 0.14em;text-transform: uppercase;color: rgba(255, 255, 255, 0.38);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);margin-bottom: 0.2rem;}@@ -1685,7 +1685,7 @@font-size: 1.15rem;font-weight: 600;color: #6ee7b7;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-btn-deploy {@@ -1899,7 +1899,7 @@margin-bottom: var(--space-lg);backdrop-filter: blur(12px);-webkit-backdrop-filter: blur(12px);- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-weight: 500;}@@ -1925,7 +1925,7 @@}.h-title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(3.2rem, 8.5vw, 6.4rem);font-weight: 700;color: #fff;@@ -1983,7 +1983,7 @@border-radius: var(--radius-sm);text-decoration: none;letter-spacing: 0.005em;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);transition: all 0.3s cubic-bezier(0.2, 0.9, 0.3, 1);box-shadow:0 6px 24px -8px rgba(255, 255, 255, 0.55),@@ -2015,7 +2015,7 @@font-weight: 500;text-decoration: none;letter-spacing: 0.005em;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);border: 1px solid rgba(255, 255, 255, 0.18);border-radius: var(--radius-sm);transition: all 0.3s cubic-bezier(0.2, 0.9, 0.3, 1);@@ -2038,7 +2038,7 @@display: flex;flex-wrap: wrap;gap: var(--space-md) var(--space-lg);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.68rem;color: rgba(255, 255, 255, 0.3);letter-spacing: 0.14em;@@ -2137,7 +2137,7 @@background: rgba(10, 10, 14, 0.72);border: 1px solid rgba(255, 255, 255, 0.07);border-radius: var(--radius-lg);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.68rem;color: rgba(255, 255, 255, 0.75);backdrop-filter: blur(12px);@@ -2162,7 +2162,7 @@flex-direction: column;align-items: center;gap: 0.5rem;- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.58rem;color: rgba(255, 255, 255, 0.22);letter-spacing: 0.25em;@@ -2215,7 +2215,7 @@}.h-section-label {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 0.78rem;color: rgba(255, 255, 255, 0.85);letter-spacing: 0.18em;@@ -2226,7 +2226,7 @@}.h-section-title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(2.2rem, 4.2vw, 3.6rem);font-weight: 700;color: #fff;@@ -2282,7 +2282,7 @@}.h-step-num {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: var(--text-2xl);font-weight: 600;color: rgba(255, 255, 255, 0.13);@@ -2393,7 +2393,7 @@}.h-widget-card-label {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.65rem;color: rgba(255, 255, 255, 0.6);letter-spacing: 0.12em;@@ -2418,7 +2418,7 @@border: 1px solid rgba(255, 255, 255, 0.05);border-radius: var(--radius-sm);padding: var(--space-sm) var(--space-md);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.68rem;color: rgba(255, 255, 255, 0.45);white-space: nowrap;@@ -2455,7 +2455,7 @@}.h-id-title {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;color: rgba(255, 255, 255, 0.5);letter-spacing: 0.08em;@@ -2475,14 +2475,14 @@}.h-id-key {- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);color: rgba(255, 255, 255, 0.3);letter-spacing: 0.05em;}.h-id-val {color: rgba(255, 255, 255, 0.65);- font-family: 'JetBrains Mono', monospace;+ font-family: var(--font-mono);font-size: 0.7rem;}@@ -2516,7 +2516,7 @@}.h-cta-section h2 {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: clamp(2.6rem, 6vw, 4.6rem);font-weight: 700;color: #fff;@@ -2530,7 +2530,7 @@font-size: 1.15rem;color: rgba(255, 255, 255, 0.6);margin: 0 0 2rem;- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);}.h-cta-row-center {diff --git a/public/marketplace-v2.css b/public/marketplace-v2.cssindex ea6856eea..b1615df05 100644--- a/public/marketplace-v2.css+++ b/public/marketplace-v2.css@@ -363,7 +363,7 @@ body.market-page > #footer-container {display: flex;align-items: center;justify-content: center;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-weight: 700;font-size: 24px;color: #fafafa;@@ -378,7 +378,7 @@ body.market-page > #footer-container {flex: 1;}.creator-modal-eyebrow {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 10px;letter-spacing: 0.18em;text-transform: uppercase;@@ -386,7 +386,7 @@ body.market-page > #footer-container {font-weight: 600;}.creator-modal-title {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 22px;font-weight: 700;color: #fafafa;@@ -407,7 +407,7 @@ body.market-page > #footer-container {}.creator-modal-stats strong {color: #fafafa;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-weight: 700;margin-right: 4px;}diff --git a/public/marketplace.css b/public/marketplace.cssindex 402efdd8c..f6b2f6814 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -5,11 +5,7 @@ body.market-page {margin: 0;background: #000;color: var(--ink);- font-family:- 'Inter',- -apple-system,- BlinkMacSystemFont,- sans-serif;+ font-family: var(--font-body);-webkit-font-smoothing: antialiased;}@@ -311,7 +307,7 @@ body.market-page > header {linear-gradient(180deg, #0a0a0a, #050505);}.market-card-agent .thumb .mv-placeholder-initial {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 42px;font-weight: 700;line-height: 1;@@ -589,7 +585,7 @@ body.market-page > header {}.avatar-detail-empty-title {margin: var(--space-2xs) 0 0;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 18px;font-weight: 600;color: var(--ink);@@ -611,7 +607,7 @@ body.market-page > header {padding-top: var(--space-xs);}.market-avatar-detail-name {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 28px;font-weight: 700;color: var(--ink);@@ -712,7 +708,7 @@ body.market-page > header {border: 1px solid var(--stroke);display: grid;place-items: center;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 28px;font-weight: 700;color: var(--ink);@@ -722,7 +718,7 @@ body.market-page > header {.tool-detail-icon img { width: 100%; height: 100%; object-fit: cover; }.tool-detail-hero-text { flex: 1; min-width: 0; }.tool-detail-name {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 30px;font-weight: 700;color: var(--ink);@@ -808,7 +804,7 @@ body.market-page > header {margin-bottom: var(--space-md);}.tool-detail-block-title {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 18px;font-weight: 600;color: var(--ink);@@ -928,7 +924,7 @@ body.market-page > header {.tool-detail-empty-glyph { font-size: 44px; color: var(--ink-dim); line-height: 1; }.tool-detail-empty-title {margin: var(--space-xs) 0 0;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 20px;font-weight: 600;color: var(--ink);@@ -3165,7 +3161,7 @@ body.market-page > header {}.market-hero-title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 36px;font-weight: 700;line-height: 1.1;@@ -3332,7 +3328,7 @@ body.market-page > header {opacity: 0;}.market-card-avatar .thumb .mv-placeholder-initial {- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);font-size: 42px;font-weight: 700;line-height: 1;@@ -3703,7 +3699,7 @@ body.market-page > header {.market-card-avatar .thumb-fallback-initial {font-size: 48px;font-weight: 700;- font-family: 'Space Grotesk', sans-serif;+ font-family: var(--font-display);letter-spacing: -0.04em;line-height: 1;background: linear-gradient(180deg, rgba(244,244,245,0.3), rgba(113,113,122,0.18));diff --git a/public/style.css b/public/style.cssindex f8203ce6f..f4393cabb 100644--- a/public/style.css+++ b/public/style.css@@ -1443,12 +1443,12 @@ footer:not([class*="h-footer"]) .separator {.phi-grid::before {left: 38.2%;- background: rgba(255, 215, 0, 0.5);+ background: rgba(var(--gold-rgb), 0.5);}.phi-grid::after {left: 61.8%;- background: rgba(255, 215, 0, 0.5);+ background: rgba(var(--gold-rgb), 0.5);}/* Horizontal golden split + thirds via inner spans */@@ -1504,12 +1504,12 @@ footer:not([class*="h-footer"]) .separator {.phi-grid-h::before {top: 38.2%;- background: rgba(255, 215, 0, 0.5);+ background: rgba(var(--gold-rgb), 0.5);}.phi-grid-h::after {top: 61.8%;- background: rgba(255, 215, 0, 0.5);+ background: rgba(var(--gold-rgb), 0.5);}/* Rule-of-thirds lines (dimmer) */@@ -1554,7 +1554,7 @@ footer:not([class*="h-footer"]) .separator {transform: translateX(-50%);font-family: 'SF Mono', 'Fira Code', monospace;font-size: var(--text-xs);- color: rgba(255, 215, 0, 0.7);+ color: rgba(var(--gold-rgb), 0.7);background: rgba(0, 0, 0, 0.7);padding: var(--space-3xs) var(--space-xs);border-radius: var(--radius-sm);@@ -1739,7 +1739,7 @@ footer:not([class*="h-footer"]) .separator {border-radius: var(--radius-lg);padding: var(--space-xs) var(--space-sm);color: #fff;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);font-size: var(--text-sm);outline: none;transition: border-color 0.2s ease;@@ -5215,7 +5215,7 @@ body[data-viewer-mode='explore'] #layout-switch {.agent-home-editable.is-editing,.agent-home-editable:focus-visible {background: rgba(255, 255, 255, 0.08);- box-shadow: 0 0 0 1px rgba(255, 215, 0, 0.5);+ box-shadow: 0 0 0 1px rgba(var(--gold-rgb), 0.5);}.agent-home-editable.is-saving {box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.18);@@ -5802,7 +5802,7 @@ body[data-viewer-mode='explore'] #layout-switch {min-width: 48px;font-size: 13px;line-height: 1.45;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);word-wrap: break-word;text-align: center;position: relative;@@ -5876,7 +5876,7 @@ body[data-viewer-mode='explore'] #layout-switch {min-height: 100vh;background: #000;color: #e0e0e0;- font-family: 'Inter', sans-serif;+ font-family: var(--font-body);display: flex;flex-direction: column;align-items: center;@@ -6704,7 +6704,7 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {}.agent-onboarding__title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);margin: 0 0 var(--space-xs);font-size: 1.1rem;font-weight: 600;@@ -6832,7 +6832,7 @@ body[data-viewer-mode='main'][data-authed='false'] .auth-gate {}.auth-gate__title {- font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-family: var(--font-display);font-size: 1.32rem;font-weight: 600;color: #fff;@@ -7977,7 +7977,7 @@ textarea.erc8004-code {}.explore-hero h1,.explore-hero h2 {- font-family: 'Space Grotesk', system-ui, sans-serif;+ font-family: var(--font-display);font-size: clamp(1.9rem, 6vw, 3.2rem);font-weight: 700;letter-spacing: -0.02em;@@ -8266,7 +8266,7 @@ textarea.erc8004-code {}.explore-card-name {margin: 0;- font-family: 'Space Grotesk', system-ui, sans-serif;+ font-family: var(--font-display);font-size: 15px;font-weight: 600;color: #fff;diff --git a/public/tokens.css b/public/tokens.cssindex 5834b2599..3c606cbb1 100644--- a/public/tokens.css+++ b/public/tokens.css@@ -88,6 +88,12 @@--accent: #ffffff;--accent-soft: rgba(255, 255, 255, 0.10);+ /* Gold brand channel (B08) — the reused features/optional-tier gold. Stored as+ raw RGB channels so every translucent variant references one source:+ rgba(var(--gold-rgb), <alpha>). Keeps the many alpha tints on a single token+ without collapsing them to one opacity. */+ --gold-rgb: 255, 215, 0;+/* Surface system — mirrors the /dashboard (dashboard-next) palette so everysurface across the site reads as one product. Monochrome glass on near-black,soft 14px cards, semantic green/red/amber. Reference these instead ofdiff --git a/public/vendor/mediapipe/face_landmarker.task b/public/vendor/mediapipe/face_landmarker.tasknew file mode 100644index 000000000..c50c845d1Binary files /dev/null and b/public/vendor/mediapipe/face_landmarker.task differdiff --git a/public/vendor/mediapipe/wasm/vision_wasm_internal.js b/public/vendor/mediapipe/wasm/vision_wasm_internal.jsnew file mode 100644index 000000000..164a24102--- /dev/null+++ b/public/vendor/mediapipe/wasm/vision_wasm_internal.js@@ -0,0 +1,8827 @@+// This code implements the `-sMODULARIZE` settings by taking the generated+// JS program code (INNER_JS_CODE) and wrapping it in a factory function.++// Single threaded MINIMAL_RUNTIME programs do not need access to+// document.currentScript, so a simple export declaration is enough.+var ModuleFactory = (() => {+ // When MODULARIZE this JS may be executed later,+ // after document.currentScript is gone, so we save it.+ // In EXPORT_ES6 mode we can just use 'import.meta.url'.+ var _scriptName = globalThis.document?.currentScript?.src;+ return async function(moduleArg = {}) {+ var moduleRtn;++// include: shell.js+// include: minimum_runtime_check.js+// end include: minimum_runtime_check.js+// The Module object: Our interface to the outside world. We import+// and export values on it. There are various ways Module can be used:+// 1. Not defined. We create it here+// 2. A function parameter, function(moduleArg) => Promise<Module>+// 3. pre-run appended it, var Module = {}; ..generated code..+// 4. External script tag defines var Module.+// We need to check if Module already exists (e.g. case 3 above).+// Substitution will be replaced with actual code on later stage of the build,+// this way Closure Compiler will not mangle it (e.g. case 4. above).+// Note that if you want to run closure, and also to use Module+// after the generated code, you will need to define var Module = {};+// before the code. Then that object will be used in the code, and you+// can continue to use Module afterwards as well.+var Module = moduleArg;++// Determine the runtime environment we are in. You can customize this by+// setting the ENVIRONMENT setting at compile time (see settings.js).+// Attempt to auto-detect the environment+var ENVIRONMENT_IS_WEB = !!globalThis.window;++var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;++// N.b. Electron.js environment is simultaneously a NODE-environment, but+// also a web environment.+var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer";++// --pre-jses are emitted after the Module integration code, so that they can+// refer to Module (if they choose; they can also define Module)+var arguments_ = [];++var thisProgram = "./this.program";++var quit_ = (status, toThrow) => {+ throw toThrow;+};++if (typeof __filename != "undefined") {+ // Node+ _scriptName = __filename;+} else if (ENVIRONMENT_IS_WORKER) {+ _scriptName = self.location.href;+}++// `/` should be present at the end if `scriptDirectory` is not empty+var scriptDirectory = "";++function locateFile(path) {+ if (Module["locateFile"]) {+ return Module["locateFile"](path, scriptDirectory);+ }+ return scriptDirectory + path;+}++// Hooks that are implemented differently in different runtime environments.+var readAsync, readBinary;++if (ENVIRONMENT_IS_NODE) {+ // These modules will usually be used on Node.js. Load them eagerly to avoid+ // the complexity of lazy-loading.+ var fs = require("node:fs");+ scriptDirectory = __dirname + "/";+ // include: node_shell_read.js+ readBinary = filename => {+ // We need to re-wrap `file://` strings to URLs.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename);+ return ret;+ };+ readAsync = async (filename, binary = true) => {+ // See the comment in the `readBinary` function.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename, binary ? undefined : "utf8");+ return ret;+ };+ // end include: node_shell_read.js+ if (process.argv.length > 1) {+ thisProgram = process.argv[1].replace(/\\/g, "/");+ }+ arguments_ = process.argv.slice(2);+ quit_ = (status, toThrow) => {+ process.exitCode = status;+ throw toThrow;+ };+} else // Note that this includes Node.js workers when relevant (pthreads is enabled).+// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and+// ENVIRONMENT_IS_NODE.+if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {+ try {+ scriptDirectory = new URL(".", _scriptName).href;+ } catch {}+ {+ // include: web_or_worker_shell_read.js+ if (ENVIRONMENT_IS_WORKER) {+ readBinary = url => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ xhr.responseType = "arraybuffer";+ xhr.send(null);+ return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));+ };+ }+ readAsync = async url => {+ // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.+ // See https://github.com/github/fetch/pull/92#issuecomment-140665932+ // Cordova or Electron apps are typically loaded from a file:// url.+ // So use XHR on webview if URL is a file URL.+ if (isFileURI(url)) {+ return new Promise((resolve, reject) => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, true);+ xhr.responseType = "arraybuffer";+ xhr.onload = () => {+ if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {+ // file URLs can return 0+ resolve(xhr.response);+ return;+ }+ reject(xhr.status);+ };+ xhr.onerror = reject;+ xhr.send(null);+ });+ }+ var response = await fetch(url, {+ credentials: "same-origin"+ });+ if (response.ok) {+ return response.arrayBuffer();+ }+ throw new Error(response.status + " : " + response.url);+ };+ }+} else {}++var out = console.log.bind(console);++var err = console.error.bind(console);++// end include: shell.js+// include: preamble.js+// === Preamble library stuff ===+// Documentation for the public APIs defined in this file must be updated in:+// site/source/docs/api_reference/preamble.js.rst+// A prebuilt local version of the documentation is available at:+// site/build/text/docs/api_reference/preamble.js.txt+// You can also build docs locally as HTML or other formats in site/+// An online HTML version (which may be of a different version of Emscripten)+// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html+var wasmBinary;++// Wasm globals+//========================================+// Runtime essentials+//========================================+// whether we are quitting the application. no code should run after this.+// set in exit() and abort()+var ABORT = false;++// set by exit() and abort(). Passed to 'onExit' handler.+// NOTE: This is also used as the process return code in shell environments+// but only when noExitRuntime is false.+var EXITSTATUS;++// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we+// don't define it at all in release modes. This matches the behaviour of+// MINIMAL_RUNTIME.+// TODO(sbc): Make this the default even without STRICT enabled.+/** @type {function(*, string=)} */ function assert(condition, text) {+ if (!condition) {+ // This build was created without ASSERTIONS defined. `assert()` should not+ // ever be called in this configuration but in case there are callers in+ // the wild leave this simple abort() implementation here for now.+ abort(text);+ }+}++/**+ * Indicates whether filename is delivered via file protocol (as opposed to http/https)+ * @noinline+ */ var isFileURI = filename => filename.startsWith("file://");++// include: runtime_common.js+// include: runtime_stack_check.js+// end include: runtime_stack_check.js+// include: runtime_exceptions.js+// Base Emscripten EH error class+class EmscriptenEH {}++class EmscriptenSjLj extends EmscriptenEH {}++// end include: runtime_exceptions.js+// include: runtime_debug.js+// end include: runtime_debug.js+var readyPromiseResolve, readyPromiseReject;++// Memory management+var runtimeInitialized = false;++function updateMemoryViews() {+ var b = wasmMemory.buffer;+ HEAP8 = new Int8Array(b);+ HEAP16 = new Int16Array(b);+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);+ HEAPU16 = new Uint16Array(b);+ HEAP32 = new Int32Array(b);+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);+ Module["HEAPF32"] = HEAPF32 = new Float32Array(b);+ Module["HEAPF64"] = HEAPF64 = new Float64Array(b);+}++// include: memoryprofiler.js+// end include: memoryprofiler.js+// end include: runtime_common.js+function preRun() {+ if (Module["preRun"]) {+ if (typeof Module["preRun"] == "function") Module["preRun"] = [ Module["preRun"] ];+ while (Module["preRun"].length) {+ addOnPreRun(Module["preRun"].shift());+ }+ }+ // Begin ATPRERUNS hooks+ callRuntimeCallbacks(onPreRuns);+}++function initRuntime() {+ runtimeInitialized = true;+ // Begin ATINITS hooks+ if (!Module["noFSInit"] && !FS.initialized) FS.init();+ TTY.init();+ // End ATINITS hooks+ wasmExports["jd"]();+ // Begin ATPOSTCTORS hooks+ FS.ignorePermissions = false;+}++function postRun() {+ // PThreads reuse the runtime from the main thread.+ if (Module["postRun"]) {+ if (typeof Module["postRun"] == "function") Module["postRun"] = [ Module["postRun"] ];+ while (Module["postRun"].length) {+ addOnPostRun(Module["postRun"].shift());+ }+ }+ // Begin ATPOSTRUNS hooks+ callRuntimeCallbacks(onPostRuns);+}++/**+ * @param {string|number=} what+ */ function abort(what) {+ Module["onAbort"]?.(what);+ what = `Aborted(${what})`;+ // TODO(sbc): Should we remove printing and leave it up to whoever+ // catches the exception?+ err(what);+ ABORT = true;+ what += ". Build with -sASSERTIONS for more info.";+ // Use a wasm runtime error, because a JS error might be seen as a foreign+ // exception, which means we'd run destructors on it. We need the error to+ // simply make the program stop.+ // FIXME This approach does not work in Wasm EH because it currently does not assume+ // all RuntimeErrors are from traps; it decides whether a RuntimeError is from+ // a trap or not based on a hidden field within the object. So at the moment+ // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that+ // allows this in the wasm spec.+ // Suppress closure compiler warning here. Closure compiler's builtin extern+ // definition for WebAssembly.RuntimeError claims it takes no arguments even+ // though it can.+ // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.+ /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);+ readyPromiseReject?.(e);+ // Throw the error whether or not MODULARIZE is set because abort is used+ // in code paths apart from instantiation where an exception is expected+ // to be thrown when abort is called.+ throw e;+}++var wasmBinaryFile;++function findWasmBinary() {+ return locateFile("vision_wasm_internal.wasm");+}++function getBinarySync(file) {+ if (file == wasmBinaryFile && wasmBinary) {+ return new Uint8Array(wasmBinary);+ }+ if (readBinary) {+ return readBinary(file);+ }+ // Throwing a plain string here, even though it not normally advisable since+ // this gets turning into an `abort` in instantiateArrayBuffer.+ throw "both async and sync fetching of the wasm failed";+}++async function getWasmBinary(binaryFile) {+ // If we don't have the binary yet, load it asynchronously using readAsync.+ if (!wasmBinary) {+ // Fetch the binary using readAsync+ try {+ var response = await readAsync(binaryFile);+ return new Uint8Array(response);+ } catch {}+ }+ // Otherwise, getBinarySync should be able to get it synchronously+ return getBinarySync(binaryFile);+}++async function instantiateArrayBuffer(binaryFile, imports) {+ try {+ var binary = await getWasmBinary(binaryFile);+ var instance = await WebAssembly.instantiate(binary, imports);+ return instance;+ } catch (reason) {+ err(`failed to asynchronously prepare wasm: ${reason}`);+ abort(reason);+ }+}++async function instantiateAsync(binary, binaryFile, imports) {+ if (!binary && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {+ try {+ var response = fetch(binaryFile, {+ credentials: "same-origin"+ });+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);+ return instantiationResult;+ } catch (reason) {+ // We expect the most common failure cause to be a bad MIME type for the binary,+ // in which case falling back to ArrayBuffer instantiation should work.+ err(`wasm streaming compile failed: ${reason}`);+ err("falling back to ArrayBuffer instantiation");+ }+ }+ return instantiateArrayBuffer(binaryFile, imports);+}++function getWasmImports() {+ // prepare imports+ var imports = {+ "a": wasmImports+ };+ return imports;+}++// Create the wasm instance.+// Receives the wasm imports, returns the exports.+async function createWasm() {+ // Load the wasm module and create an instance of using native support in the JS engine.+ // handle a generated wasm instance, receiving its exports and+ // performing other necessary setup+ /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) {+ wasmExports = instance.exports;+ assignWasmExports(wasmExports);+ updateMemoryViews();+ return wasmExports;+ }+ // Prefer streaming instantiation if available.+ function receiveInstantiationResult(result) {+ // 'result' is a ResultObject object which has both the module and instance.+ // receiveInstance() will swap in the exports (to Module.asm) so they can be called+ // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.+ // When the regression is fixed, can restore the above PTHREADS-enabled path.+ return receiveInstance(result["instance"]);+ }+ var info = getWasmImports();+ // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback+ // to manually instantiate the Wasm module themselves. This allows pages to+ // run the instantiation parallel to any other async startup actions they are+ // performing.+ // Also pthreads and wasm workers initialize the wasm instance through this+ // path.+ if (Module["instantiateWasm"]) {+ return new Promise((resolve, reject) => {+ Module["instantiateWasm"](info, (inst, mod) => {+ resolve(receiveInstance(inst, mod));+ });+ });+ }+ wasmBinaryFile ??= findWasmBinary();+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);+ var exports = receiveInstantiationResult(result);+ return exports;+}++// Globals used by JS i64 conversions (see makeSetValue)+var tempDouble;++var tempI64;++// end include: preamble.js+// Begin JS library code+var handleException = e => {+ // Certain exception types we do not treat as errors since they are used for+ // internal control flow.+ // 1. ExitStatus, which is thrown by exit()+ // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others+ // that wish to return to JS event loop.+ if (e instanceof ExitStatus || e == "unwind") {+ return EXITSTATUS;+ }+ quit_(1, e);+};++class ExitStatus {+ name="ExitStatus";+ constructor(status) {+ this.message = `Program terminated with exit(${status})`;+ this.status = status;+ }+}++var runtimeKeepaliveCounter = 0;++var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;++var _proc_exit = code => {+ EXITSTATUS = code;+ if (!keepRuntimeAlive()) {+ Module["onExit"]?.(code);+ ABORT = true;+ }+ quit_(code, new ExitStatus(code));+};++/** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => {+ EXITSTATUS = status;+ _proc_exit(status);+};++var _exit = exitJS;++var maybeExit = () => {+ if (!keepRuntimeAlive()) {+ try {+ _exit(EXITSTATUS);+ } catch (e) {+ handleException(e);+ }+ }+};++var callUserCallback = func => {+ if (ABORT) {+ return;+ }+ try {+ return func();+ } catch (e) {+ handleException(e);+ } finally {+ maybeExit();+ }+};++function getFullscreenElement() {+ return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.webkitCurrentFullScreenElement || document.msFullscreenElement;+}++/** @param {number=} timeout */ var safeSetTimeout = (func, timeout) => setTimeout(() => {+ callUserCallback(func);+}, timeout);++var warnOnce = text => {+ warnOnce.shown ||= {};+ if (!warnOnce.shown[text]) {+ warnOnce.shown[text] = 1;+ if (ENVIRONMENT_IS_NODE) text = "warning: " + text;+ err(text);+ }+};++var preloadPlugins = [];++var Browser = {+ useWebGL: false,+ isFullscreen: false,+ pointerLock: false,+ moduleContextCreatedCallbacks: [],+ workers: [],+ preloadedImages: {},+ preloadedAudios: {},+ getCanvas: () => Module["canvas"],+ init() {+ if (Browser.initted) return;+ Browser.initted = true;+ // Support for plugins that can process preloaded files. You can add more of these to+ // your app by creating and appending to preloadPlugins.+ // Each plugin is asked if it can handle a file based on the file's name. If it can,+ // it is given the file's raw data. When it is done, it calls a callback with the file's+ // (possibly modified) data. For example, a plugin might decompress a file, or it+ // might create some side data structure for use later (like an Image element, etc.).+ var imagePlugin = {};+ imagePlugin["canHandle"] = name => !Module["noImageDecoding"] && /\.(jpg|jpeg|png|bmp|webp)$/i.test(name);+ imagePlugin["handle"] = async (byteArray, name) => {+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ if (b.size !== byteArray.length) {+ // Safari bug #118630+ // Safari's Blob can only take an ArrayBuffer+ b = new Blob([ (new Uint8Array(byteArray)).buffer ], {+ type: Browser.getMimetype(name)+ });+ }+ var url = URL.createObjectURL(b);+ return new Promise((resolve, reject) => {+ var img = new Image;+ img.onload = () => {+ var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement("canvas"));+ canvas.width = img.width;+ canvas.height = img.height;+ var ctx = canvas.getContext("2d");+ ctx.drawImage(img, 0, 0);+ Browser.preloadedImages[name] = canvas;+ URL.revokeObjectURL(url);+ resolve(byteArray);+ };+ img.onerror = event => {+ err(`Image ${url} could not be decoded`);+ reject();+ };+ img.src = url;+ });+ };+ preloadPlugins.push(imagePlugin);+ var audioPlugin = {};+ audioPlugin["canHandle"] = name => !Module["noAudioDecoding"] && name.slice(-4) in {+ ".ogg": 1,+ ".wav": 1,+ ".mp3": 1+ };+ audioPlugin["handle"] = async (byteArray, name) => new Promise((resolve, reject) => {+ var done = false;+ function finish(audio) {+ if (done) return;+ done = true;+ Browser.preloadedAudios[name] = audio;+ resolve(byteArray);+ }+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ var url = URL.createObjectURL(b);+ // XXX we never revoke this!+ var audio = new Audio;+ audio.addEventListener("canplaythrough", () => finish(audio), false);+ // use addEventListener due to chromium bug 124926+ audio.onerror = event => {+ if (done) return;+ err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);+ function encode64(data) {+ var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ var PAD = "=";+ var ret = "";+ var leftchar = 0;+ var leftbits = 0;+ for (var i = 0; i < data.length; i++) {+ leftchar = (leftchar << 8) | data[i];+ leftbits += 8;+ while (leftbits >= 6) {+ var curr = (leftchar >> (leftbits - 6)) & 63;+ leftbits -= 6;+ ret += BASE[curr];+ }+ }+ if (leftbits == 2) {+ ret += BASE[(leftchar & 3) << 4];+ ret += PAD + PAD;+ } else if (leftbits == 4) {+ ret += BASE[(leftchar & 15) << 2];+ ret += PAD;+ }+ return ret;+ }+ audio.src = "data:audio/x-" + name.slice(-3) + ";base64," + encode64(byteArray);+ finish(audio);+ };+ audio.src = url;+ // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror+ safeSetTimeout(() => {+ finish(audio);+ }, 1e4);+ });+ preloadPlugins.push(audioPlugin);+ // Canvas event setup+ function pointerLockChange() {+ var canvas = Browser.getCanvas();+ Browser.pointerLock = document.pointerLockElement === canvas;+ }+ var canvas = Browser.getCanvas();+ if (canvas) {+ // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module+ // Module['forcedAspectRatio'] = 4 / 3;+ document.addEventListener("pointerlockchange", pointerLockChange, false);+ if (Module["elementPointerLock"]) {+ canvas.addEventListener("click", ev => {+ if (!Browser.pointerLock && Browser.getCanvas().requestPointerLock) {+ Browser.getCanvas().requestPointerLock();+ ev.preventDefault();+ }+ }, false);+ }+ }+ },+ createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) {+ if (useWebGL && Module["ctx"] && canvas == Browser.getCanvas()) return Module["ctx"];+ // no need to recreate GL context if it's already been created for this canvas.+ var ctx;+ var contextHandle;+ if (useWebGL) {+ // For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.+ var contextAttributes = {+ antialias: false,+ alpha: false,+ majorVersion: (typeof WebGL2RenderingContext != "undefined") ? 2 : 1+ };+ if (webGLContextAttributes) {+ for (var attribute in webGLContextAttributes) {+ contextAttributes[attribute] = webGLContextAttributes[attribute];+ }+ }+ // This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not+ // actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function+ // Browser.createContext() should not even be emitted.+ if (typeof GL != "undefined") {+ contextHandle = GL.createContext(canvas, contextAttributes);+ if (contextHandle) {+ ctx = GL.getContext(contextHandle).GLctx;+ }+ }+ } else {+ ctx = canvas.getContext("2d");+ }+ if (!ctx) return null;+ if (setInModule) {+ Module["ctx"] = ctx;+ if (useWebGL) GL.makeContextCurrent(contextHandle);+ Browser.useWebGL = useWebGL;+ Browser.moduleContextCreatedCallbacks.forEach(callback => callback());+ Browser.init();+ }+ return ctx;+ },+ fullscreenHandlersInstalled: false,+ lockPointer: undefined,+ resizeCanvas: undefined,+ requestFullscreen(lockPointer, resizeCanvas) {+ Browser.lockPointer = lockPointer;+ Browser.resizeCanvas = resizeCanvas;+ if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true;+ if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false;+ var canvas = Browser.getCanvas();+ function fullscreenChange() {+ Browser.isFullscreen = false;+ var canvasContainer = canvas.parentNode;+ if (getFullscreenElement() === canvasContainer) {+ canvas.exitFullscreen = Browser.exitFullscreen;+ if (Browser.lockPointer) canvas.requestPointerLock();+ Browser.isFullscreen = true;+ if (Browser.resizeCanvas) {+ Browser.setFullscreenCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ } else {+ // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen+ canvasContainer.parentNode.insertBefore(canvas, canvasContainer);+ canvasContainer.parentNode.removeChild(canvasContainer);+ if (Browser.resizeCanvas) {+ Browser.setWindowedCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ }+ Module["onFullScreen"]?.(Browser.isFullscreen);+ Module["onFullscreen"]?.(Browser.isFullscreen);+ }+ if (!Browser.fullscreenHandlersInstalled) {+ Browser.fullscreenHandlersInstalled = true;+ document.addEventListener("fullscreenchange", fullscreenChange, false);+ document.addEventListener("mozfullscreenchange", fullscreenChange, false);+ document.addEventListener("webkitfullscreenchange", fullscreenChange, false);+ document.addEventListener("MSFullscreenChange", fullscreenChange, false);+ }+ // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root+ var canvasContainer = document.createElement("div");+ canvas.parentNode.insertBefore(canvasContainer, canvas);+ canvasContainer.appendChild(canvas);+ // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)+ canvasContainer.requestFullscreen = canvasContainer["requestFullscreen"] || canvasContainer["mozRequestFullScreen"] || canvasContainer["msRequestFullscreen"] || (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null) || (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null);+ canvasContainer.requestFullscreen();+ },+ exitFullscreen() {+ // This is workaround for chrome. Trying to exit from fullscreen+ // not in fullscreen state will cause "TypeError: Document not active"+ // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236+ if (!Browser.isFullscreen) {+ return false;+ }+ var CFS = document["exitFullscreen"] || document["cancelFullScreen"] || document["mozCancelFullScreen"] || document["msExitFullscreen"] || document["webkitCancelFullScreen"] || (() => {});+ CFS.apply(document, []);+ return true;+ },+ safeSetTimeout(func, timeout) {+ // Legacy function, this is used by the SDL2 port so we need to keep it+ // around at least until that is updated.+ // See https://github.com/libsdl-org/SDL/pull/6304+ return safeSetTimeout(func, timeout);+ },+ getMimetype(name) {+ return {+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "png": "image/png",+ "bmp": "image/bmp",+ "ogg": "audio/ogg",+ "wav": "audio/wav",+ "mp3": "audio/mpeg"+ }[name.slice(name.lastIndexOf(".") + 1)];+ },+ getUserMedia(func) {+ window.getUserMedia ||= navigator["getUserMedia"] || navigator["mozGetUserMedia"];+ window.getUserMedia(func);+ },+ getMovementX(event) {+ return event["movementX"] || event["mozMovementX"] || event["webkitMovementX"] || 0;+ },+ getMovementY(event) {+ return event["movementY"] || event["mozMovementY"] || event["webkitMovementY"] || 0;+ },+ getMouseWheelDelta(event) {+ var delta = 0;+ switch (event.type) {+ case "DOMMouseScroll":+ // 3 lines make up a step+ delta = event.detail / 3;+ break;++ case "mousewheel":+ // 120 units make up a step+ delta = event.wheelDelta / 120;+ break;++ case "wheel":+ delta = event.deltaY;+ switch (event.deltaMode) {+ case 0:+ // DOM_DELTA_PIXEL: 100 pixels make up a step+ delta /= 100;+ break;++ case 1:+ // DOM_DELTA_LINE: 3 lines make up a step+ delta /= 3;+ break;++ case 2:+ // DOM_DELTA_PAGE: A page makes up 80 steps+ delta *= 80;+ break;++ default:+ abort("unrecognized mouse wheel delta mode: " + event.deltaMode);+ }+ break;++ default:+ abort("unrecognized mouse wheel event: " + event.type);+ }+ return delta;+ },+ mouseX: 0,+ mouseY: 0,+ mouseMovementX: 0,+ mouseMovementY: 0,+ touches: {},+ lastTouches: {},+ calculateMouseCoords(pageX, pageY) {+ // Calculate the movement based on the changes+ // in the coordinates.+ var canvas = Browser.getCanvas();+ var rect = canvas.getBoundingClientRect();+ // Neither .scrollX or .pageXOffset are defined in a spec, but+ // we prefer .scrollX because it is currently in a spec draft.+ // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)+ var scrollX = ((typeof window.scrollX != "undefined") ? window.scrollX : window.pageXOffset);+ var scrollY = ((typeof window.scrollY != "undefined") ? window.scrollY : window.pageYOffset);+ var adjustedX = pageX - (scrollX + rect.left);+ var adjustedY = pageY - (scrollY + rect.top);+ // the canvas might be CSS-scaled compared to its backbuffer;+ // SDL-using content will want mouse coordinates in terms+ // of backbuffer units.+ adjustedX = adjustedX * (canvas.width / rect.width);+ adjustedY = adjustedY * (canvas.height / rect.height);+ return {+ x: adjustedX,+ y: adjustedY+ };+ },+ setMouseCoords(pageX, pageY) {+ const {x, y} = Browser.calculateMouseCoords(pageX, pageY);+ Browser.mouseMovementX = x - Browser.mouseX;+ Browser.mouseMovementY = y - Browser.mouseY;+ Browser.mouseX = x;+ Browser.mouseY = y;+ },+ calculateMouseEvent(event) {+ // event should be mousemove, mousedown or mouseup+ if (Browser.pointerLock) {+ // When the pointer is locked, calculate the coordinates+ // based on the movement of the mouse.+ // Workaround for Firefox bug 764498+ if (event.type != "mousemove" && ("mozMovementX" in event)) {+ Browser.mouseMovementX = Browser.mouseMovementY = 0;+ } else {+ Browser.mouseMovementX = Browser.getMovementX(event);+ Browser.mouseMovementY = Browser.getMovementY(event);+ }+ // add the mouse delta to the current absolute mouse position+ Browser.mouseX += Browser.mouseMovementX;+ Browser.mouseY += Browser.mouseMovementY;+ } else {+ if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") {+ var touch = event.touch;+ if (touch === undefined) {+ return;+ }+ var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY);+ if (event.type === "touchstart") {+ Browser.lastTouches[touch.identifier] = coords;+ Browser.touches[touch.identifier] = coords;+ } else if (event.type === "touchend" || event.type === "touchmove") {+ var last = Browser.touches[touch.identifier];+ last ||= coords;+ Browser.lastTouches[touch.identifier] = last;+ Browser.touches[touch.identifier] = coords;+ }+ return;+ }+ Browser.setMouseCoords(event.pageX, event.pageY);+ }+ },+ resizeListeners: [],+ updateResizeListeners() {+ var canvas = Browser.getCanvas();+ Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height));+ },+ setCanvasSize(width, height, noUpdates) {+ var canvas = Browser.getCanvas();+ Browser.updateCanvasDimensions(canvas, width, height);+ if (!noUpdates) Browser.updateResizeListeners();+ },+ windowedWidth: 0,+ windowedHeight: 0,+ setFullscreenCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags | 8388608;+ // set SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ setWindowedCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags & ~8388608;+ // clear SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ updateCanvasDimensions(canvas, wNative, hNative) {+ if (wNative && hNative) {+ canvas.widthNative = wNative;+ canvas.heightNative = hNative;+ } else {+ wNative = canvas.widthNative;+ hNative = canvas.heightNative;+ }+ var w = wNative;+ var h = hNative;+ if (Module["forcedAspectRatio"] > 0) {+ if (w / h < Module["forcedAspectRatio"]) {+ w = Math.round(h * Module["forcedAspectRatio"]);+ } else {+ h = Math.round(w / Module["forcedAspectRatio"]);+ }+ }+ if ((getFullscreenElement() === canvas.parentNode) && (typeof screen != "undefined")) {+ var factor = Math.min(screen.width / w, screen.height / h);+ w = Math.round(w * factor);+ h = Math.round(h * factor);+ }+ if (Browser.resizeCanvas) {+ if (canvas.width != w) canvas.width = w;+ if (canvas.height != h) canvas.height = h;+ if (typeof canvas.style != "undefined") {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ } else {+ if (canvas.width != wNative) canvas.width = wNative;+ if (canvas.height != hNative) canvas.height = hNative;+ if (typeof canvas.style != "undefined") {+ if (w != wNative || h != hNative) {+ canvas.style.setProperty("width", w + "px", "important");+ canvas.style.setProperty("height", h + "px", "important");+ } else {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ }+ }+ }+};++/** @type {!Int16Array} */ var HEAP16;++/** @type {!Int32Array} */ var HEAP32;++/** @type {!Int8Array} */ var HEAP8;++/** @type {!Float32Array} */ var HEAPF32;++/** @type {!Float64Array} */ var HEAPF64;++/** @type {!Uint16Array} */ var HEAPU16;++/** @type {!Uint32Array} */ var HEAPU32;++/** @type {!Uint8Array} */ var HEAPU8;++var callRuntimeCallbacks = callbacks => {+ while (callbacks.length > 0) {+ // Pass the module as the first argument.+ callbacks.shift()(Module);+ }+};++var onPostRuns = [];++var addOnPostRun = cb => onPostRuns.push(cb);++var onPreRuns = [];++var addOnPreRun = cb => onPreRuns.push(cb);++var noExitRuntime = true;++var stackRestore = val => __emscripten_stack_restore(val);++var stackSave = () => _emscripten_stack_get_current();++class ExceptionInfo {+ // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.+ constructor(excPtr) {+ this.excPtr = excPtr;+ this.ptr = excPtr - 24;+ }+ set_type(type) {+ HEAPU32[(((this.ptr) + (4)) >> 2)] = type;+ }+ get_type() {+ return HEAPU32[(((this.ptr) + (4)) >> 2)];+ }+ set_destructor(destructor) {+ HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor;+ }+ get_destructor() {+ return HEAPU32[(((this.ptr) + (8)) >> 2)];+ }+ set_caught(caught) {+ caught = caught ? 1 : 0;+ HEAP8[(this.ptr) + (12)] = caught;+ }+ get_caught() {+ return HEAP8[(this.ptr) + (12)] != 0;+ }+ set_rethrown(rethrown) {+ rethrown = rethrown ? 1 : 0;+ HEAP8[(this.ptr) + (13)] = rethrown;+ }+ get_rethrown() {+ return HEAP8[(this.ptr) + (13)] != 0;+ }+ // Initialize native structure fields. Should be called once after allocated.+ init(type, destructor) {+ this.set_adjusted_ptr(0);+ this.set_type(type);+ this.set_destructor(destructor);+ }+ set_adjusted_ptr(adjustedPtr) {+ HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr;+ }+ get_adjusted_ptr() {+ return HEAPU32[(((this.ptr) + (16)) >> 2)];+ }+}++var uncaughtExceptionCount = 0;++var ___cxa_throw = (ptr, type, destructor) => {+ var info = new ExceptionInfo(ptr);+ // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.+ info.init(type, destructor);+ uncaughtExceptionCount++;+ abort();+};++var PATH = {+ isAbs: path => path.charAt(0) === "/",+ splitPath: filename => {+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;+ return splitPathRe.exec(filename).slice(1);+ },+ normalizeArray: (parts, allowAboveRoot) => {+ // if the path tries to go above the root, `up` ends up > 0+ var up = 0;+ for (var i = parts.length - 1; i >= 0; i--) {+ var last = parts[i];+ if (last === ".") {+ parts.splice(i, 1);+ } else if (last === "..") {+ parts.splice(i, 1);+ up++;+ } else if (up) {+ parts.splice(i, 1);+ up--;+ }+ }+ // if the path is allowed to go above the root, restore leading ..s+ if (allowAboveRoot) {+ for (;up; up--) {+ parts.unshift("..");+ }+ }+ return parts;+ },+ normalize: path => {+ var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/";+ // Normalize the path+ path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");+ if (!path && !isAbsolute) {+ path = ".";+ }+ if (path && trailingSlash) {+ path += "/";+ }+ return (isAbsolute ? "/" : "") + path;+ },+ dirname: path => {+ var result = PATH.splitPath(path), root = result[0], dir = result[1];+ if (!root && !dir) {+ // No dirname whatsoever+ return ".";+ }+ if (dir) {+ // It has a dirname, strip trailing slash+ dir = dir.slice(0, -1);+ }+ return root + dir;+ },+ basename: path => path && path.match(/([^\/]+|\/)\/*$/)[1],+ join: (...paths) => PATH.normalize(paths.join("/")),+ join2: (l, r) => PATH.normalize(l + "/" + r)+};++var initRandomFill = () => {+ // This block is not needed on v19+ since crypto.getRandomValues is builtin+ if (ENVIRONMENT_IS_NODE) {+ var nodeCrypto = require("node:crypto");+ return view => nodeCrypto.randomFillSync(view);+ }+ return view => (crypto.getRandomValues(view), 0);+};++var randomFill = view => (randomFill = initRandomFill())(view);++var PATH_FS = {+ resolve: (...args) => {+ var resolvedPath = "", resolvedAbsolute = false;+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {+ var path = (i >= 0) ? args[i] : FS.cwd();+ // Skip empty and invalid entries+ if (typeof path != "string") {+ throw new TypeError("Arguments to path.resolve must be strings");+ } else if (!path) {+ return "";+ }+ resolvedPath = path + "/" + resolvedPath;+ resolvedAbsolute = PATH.isAbs(path);+ }+ // At this point the path should be resolved to a full absolute path, but+ // handle relative paths to be safe (might happen when process.cwd() fails)+ resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");+ return ((resolvedAbsolute ? "/" : "") + resolvedPath) || ".";+ },+ relative: (from, to) => {+ from = PATH_FS.resolve(from).slice(1);+ to = PATH_FS.resolve(to).slice(1);+ function trim(arr) {+ var start = 0;+ for (;start < arr.length; start++) {+ if (arr[start] !== "") break;+ }+ var end = arr.length - 1;+ for (;end >= 0; end--) {+ if (arr[end] !== "") break;+ }+ if (start > end) return [];+ return arr.slice(start, end - start + 1);+ }+ var fromParts = trim(from.split("/"));+ var toParts = trim(to.split("/"));+ var length = Math.min(fromParts.length, toParts.length);+ var samePartsLength = length;+ for (var i = 0; i < length; i++) {+ if (fromParts[i] !== toParts[i]) {+ samePartsLength = i;+ break;+ }+ }+ var outputParts = [];+ for (var i = samePartsLength; i < fromParts.length; i++) {+ outputParts.push("..");+ }+ outputParts = outputParts.concat(toParts.slice(samePartsLength));+ return outputParts.join("/");+ }+};++var UTF8Decoder = new TextDecoder;++var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {+ var maxIdx = idx + maxBytesToRead;+ if (ignoreNul) return maxIdx;+ // TextDecoder needs to know the byte length in advance, it doesn't stop on+ // null terminator by itself.+ // As a tiny code save trick, compare idx against maxIdx using a negation,+ // so that maxBytesToRead=undefined/NaN means Infinity.+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;+ return idx;+};++/**+ * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given+ * array that contains uint8 values, returns a copy of that string as a+ * Javascript String object.+ * heapOrArray is either a regular array, or a JavaScript typed array view.+ * @param {number=} idx+ * @param {number=} maxBytesToRead+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr)));+};++var FS_stdin_getChar_buffer = [];++var lengthBytesUTF8 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code+ // unit, not a Unicode code point of the character! So decode+ // UTF16->UTF32->UTF8.+ // See http://unicode.org/faq/utf_bom.html#utf16-3+ var c = str.charCodeAt(i);+ // possibly a lead surrogate+ if (c <= 127) {+ len++;+ } else if (c <= 2047) {+ len += 2;+ } else if (c >= 55296 && c <= 57343) {+ len += 4;+ ++i;+ } else {+ len += 3;+ }+ }+ return len;+};++var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {+ // Parameter maxBytesToWrite is not optional. Negative values, 0, null,+ // undefined and false each don't write out any bytes.+ if (!(maxBytesToWrite > 0)) return 0;+ var startIdx = outIdx;+ var endIdx = outIdx + maxBytesToWrite - 1;+ // -1 for string null terminator.+ for (var i = 0; i < str.length; ++i) {+ // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description+ // and https://www.ietf.org/rfc/rfc2279.txt+ // and https://tools.ietf.org/html/rfc3629+ var u = str.codePointAt(i);+ if (u <= 127) {+ if (outIdx >= endIdx) break;+ heap[outIdx++] = u;+ } else if (u <= 2047) {+ if (outIdx + 1 >= endIdx) break;+ heap[outIdx++] = 192 | (u >> 6);+ heap[outIdx++] = 128 | (u & 63);+ } else if (u <= 65535) {+ if (outIdx + 2 >= endIdx) break;+ heap[outIdx++] = 224 | (u >> 12);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ } else {+ if (outIdx + 3 >= endIdx) break;+ heap[outIdx++] = 240 | (u >> 18);+ heap[outIdx++] = 128 | ((u >> 12) & 63);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ i++;+ }+ }+ // Null-terminate the pointer to the buffer.+ heap[outIdx] = 0;+ return outIdx - startIdx;+};++/** @type {function(string, boolean=, number=)} */ var intArrayFromString = (stringy, dontAddNull, length) => {+ var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;+ var u8array = new Array(len);+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);+ if (dontAddNull) u8array.length = numBytesWritten;+ return u8array;+};++var FS_stdin_getChar = () => {+ if (!FS_stdin_getChar_buffer.length) {+ var result = null;+ if (ENVIRONMENT_IS_NODE) {+ // we will read data by chunks of BUFSIZE+ var BUFSIZE = 256;+ var buf = Buffer.alloc(BUFSIZE);+ var bytesRead = 0;+ // For some reason we must suppress a closure warning here, even though+ // fd definitely exists on process.stdin, and is even the proper way to+ // get the fd of stdin,+ // https://github.com/nodejs/help/issues/2136#issuecomment-523649904+ // This started to happen after moving this logic out of library_tty.js,+ // so it is related to the surrounding code in some unclear manner.+ /** @suppress {missingProperties} */ var fd = process.stdin.fd;+ try {+ bytesRead = fs.readSync(fd, buf, 0, BUFSIZE);+ } catch (e) {+ // Cross-platform differences: on Windows, reading EOF throws an+ // exception, but on other OSes, reading EOF returns 0. Uniformize+ // behavior by treating the EOF exception to return 0.+ if (e.toString().includes("EOF")) bytesRead = 0; else throw e;+ }+ if (bytesRead > 0) {+ result = buf.slice(0, bytesRead).toString("utf-8");+ }+ } else if (globalThis.window?.prompt) {+ // Browser.+ result = window.prompt("Input: ");+ // returns null on cancel+ if (result !== null) {+ result += "\n";+ }+ } else {}+ if (!result) {+ return null;+ }+ FS_stdin_getChar_buffer = intArrayFromString(result, true);+ }+ return FS_stdin_getChar_buffer.shift();+};++var TTY = {+ ttys: [],+ init() {},+ shutdown() {},+ register(dev, ops) {+ TTY.ttys[dev] = {+ input: [],+ output: [],+ ops+ };+ FS.registerDevice(dev, TTY.stream_ops);+ },+ stream_ops: {+ open(stream) {+ var tty = TTY.ttys[stream.node.rdev];+ if (!tty) {+ throw new FS.ErrnoError(43);+ }+ stream.tty = tty;+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ stream.tty.ops.fsync(stream.tty);+ },+ fsync(stream) {+ stream.tty.ops.fsync(stream.tty);+ },+ read(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.get_char) {+ throw new FS.ErrnoError(60);+ }+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = stream.tty.ops.get_char(stream.tty);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.put_char) {+ throw new FS.ErrnoError(60);+ }+ try {+ for (var i = 0; i < length; i++) {+ stream.tty.ops.put_char(stream.tty, buffer[offset + i]);+ }+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ },+ default_tty_ops: {+ get_char(tty) {+ return FS_stdin_getChar();+ },+ put_char(tty, val) {+ if (val === null || val === 10) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ },+ ioctl_tcgets(tty) {+ // typical setting+ return {+ c_iflag: 25856,+ c_oflag: 5,+ c_cflag: 191,+ c_lflag: 35387,+ c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]+ };+ },+ ioctl_tcsets(tty, optional_actions, data) {+ // currently just ignore+ return 0;+ },+ ioctl_tiocgwinsz(tty) {+ return [ 24, 80 ];+ }+ },+ default_tty1_ops: {+ put_char(tty, val) {+ if (val === null || val === 10) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ }+ }+};++var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size);++var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;++var mmapAlloc = size => {+ size = alignMemory(size, 65536);+ var ptr = _emscripten_builtin_memalign(65536, size);+ if (ptr) zeroMemory(ptr, size);+ return ptr;+};++var MEMFS = {+ ops_table: null,+ mount(mount) {+ return MEMFS.createNode(null, "/", 16895, 0);+ },+ createNode(parent, name, mode, dev) {+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {+ // not supported+ throw new FS.ErrnoError(63);+ }+ MEMFS.ops_table ||= {+ dir: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ lookup: MEMFS.node_ops.lookup,+ mknod: MEMFS.node_ops.mknod,+ rename: MEMFS.node_ops.rename,+ unlink: MEMFS.node_ops.unlink,+ rmdir: MEMFS.node_ops.rmdir,+ readdir: MEMFS.node_ops.readdir,+ symlink: MEMFS.node_ops.symlink+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek+ }+ },+ file: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek,+ read: MEMFS.stream_ops.read,+ write: MEMFS.stream_ops.write,+ mmap: MEMFS.stream_ops.mmap,+ msync: MEMFS.stream_ops.msync+ }+ },+ link: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ readlink: MEMFS.node_ops.readlink+ },+ stream: {}+ },+ chrdev: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: FS.chrdev_stream_ops+ }+ };+ var node = FS.createNode(parent, name, mode, dev);+ if (FS.isDir(node.mode)) {+ node.node_ops = MEMFS.ops_table.dir.node;+ node.stream_ops = MEMFS.ops_table.dir.stream;+ node.contents = {};+ } else if (FS.isFile(node.mode)) {+ node.node_ops = MEMFS.ops_table.file.node;+ node.stream_ops = MEMFS.ops_table.file.stream;+ // The actual number of bytes used in the typed array, as opposed to+ // contents.length which gives the whole capacity.+ node.usedBytes = 0;+ // The byte data of the file is stored in a typed array.+ // Note: typed arrays are not resizable like normal JS arrays are, so+ // there is a small penalty involved for appending file writes that+ // continuously grow a file similar to std::vector capacity vs used.+ node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0);+ } else if (FS.isLink(node.mode)) {+ node.node_ops = MEMFS.ops_table.link.node;+ node.stream_ops = MEMFS.ops_table.link.stream;+ } else if (FS.isChrdev(node.mode)) {+ node.node_ops = MEMFS.ops_table.chrdev.node;+ node.stream_ops = MEMFS.ops_table.chrdev.stream;+ }+ node.atime = node.mtime = node.ctime = Date.now();+ // add the new node to the parent+ if (parent) {+ parent.contents[name] = node;+ parent.atime = parent.mtime = parent.ctime = node.atime;+ }+ return node;+ },+ getFileDataAsTypedArray(node) {+ return node.contents.subarray(0, node.usedBytes);+ },+ expandFileStorage(node, newCapacity) {+ var prevCapacity = node.contents.length;+ if (prevCapacity >= newCapacity) return;+ // No need to expand, the storage was already large enough.+ // Don't expand strictly to the given requested limit if it's only a very+ // small increase, but instead geometrically grow capacity.+ // For small filesizes (<1MB), perform size*2 geometric increase, but for+ // large sizes, do a much more conservative size*1.125 increase to avoid+ // overshooting the allocation cap by a very large margin.+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0);+ if (prevCapacity) newCapacity = Math.max(newCapacity, 256);+ // At minimum allocate 256b for each file when expanding.+ var oldContents = MEMFS.getFileDataAsTypedArray(node);+ node.contents = new Uint8Array(newCapacity);+ // Allocate new storage.+ node.contents.set(oldContents);+ },+ resizeFileStorage(node, newSize) {+ if (node.usedBytes == newSize) return;+ var oldContents = node.contents;+ node.contents = new Uint8Array(newSize);+ // Allocate new storage.+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));+ // Copy old data over to the new storage.+ node.usedBytes = newSize;+ },+ node_ops: {+ getattr(node) {+ var attr = {};+ // device numbers reuse inode numbers.+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;+ attr.ino = node.id;+ attr.mode = node.mode;+ attr.nlink = 1;+ attr.uid = 0;+ attr.gid = 0;+ attr.rdev = node.rdev;+ if (FS.isDir(node.mode)) {+ attr.size = 4096;+ } else if (FS.isFile(node.mode)) {+ attr.size = node.usedBytes;+ } else if (FS.isLink(node.mode)) {+ attr.size = node.link.length;+ } else {+ attr.size = 0;+ }+ attr.atime = new Date(node.atime);+ attr.mtime = new Date(node.mtime);+ attr.ctime = new Date(node.ctime);+ // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),+ // but this is not required by the standard.+ attr.blksize = 4096;+ attr.blocks = Math.ceil(attr.size / attr.blksize);+ return attr;+ },+ setattr(node, attr) {+ for (const key of [ "mode", "atime", "mtime", "ctime" ]) {+ if (attr[key] != null) {+ node[key] = attr[key];+ }+ }+ if (attr.size !== undefined) {+ MEMFS.resizeFileStorage(node, attr.size);+ }+ },+ lookup(parent, name) {+ // This error may happen quite a bit. To avoid overhead we reuse it (and+ // suffer a lack of stack info).+ if (!MEMFS.doesNotExistError) {+ MEMFS.doesNotExistError = new FS.ErrnoError(44);+ /** @suppress {checkTypes} */ MEMFS.doesNotExistError.stack = "<generic error, no stack>";+ }+ throw MEMFS.doesNotExistError;+ },+ mknod(parent, name, mode, dev) {+ return MEMFS.createNode(parent, name, mode, dev);+ },+ rename(old_node, new_dir, new_name) {+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ if (new_node) {+ if (FS.isDir(old_node.mode)) {+ // if we're overwriting a directory at new_name, make sure it's empty.+ for (var i in new_node.contents) {+ throw new FS.ErrnoError(55);+ }+ }+ FS.hashRemoveNode(new_node);+ }+ // do the internal rewiring+ delete old_node.parent.contents[old_node.name];+ new_dir.contents[new_name] = old_node;+ old_node.name = new_name;+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();+ },+ unlink(parent, name) {+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ rmdir(parent, name) {+ var node = FS.lookupNode(parent, name);+ for (var i in node.contents) {+ throw new FS.ErrnoError(55);+ }+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ readdir(node) {+ return [ ".", "..", ...Object.keys(node.contents) ];+ },+ symlink(parent, newname, oldpath) {+ var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);+ node.link = oldpath;+ return node;+ },+ readlink(node) {+ if (!FS.isLink(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ return node.link;+ }+ },+ stream_ops: {+ read(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= stream.node.usedBytes) return 0;+ var size = Math.min(stream.node.usedBytes - position, length);+ buffer.set(contents.subarray(position, position + size), offset);+ return size;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ // If the buffer is located in main memory (HEAP), and if+ // memory can grow, we can't hold on to references of the+ // memory buffer, as they may get invalidated. That means we+ // need to copy its contents.+ if (buffer.buffer === HEAP8.buffer) {+ canOwn = false;+ }+ if (!length) return 0;+ var node = stream.node;+ node.mtime = node.ctime = Date.now();+ if (canOwn) {+ node.contents = buffer.subarray(offset, offset + length);+ node.usedBytes = length;+ } else if (node.usedBytes === 0 && position === 0) {+ // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.+ node.contents = buffer.slice(offset, offset + length);+ node.usedBytes = length;+ } else {+ MEMFS.expandFileStorage(node, position + length);+ // Use typed array write which is available.+ node.contents.set(buffer.subarray(offset, offset + length), position);+ node.usedBytes = Math.max(node.usedBytes, position + length);+ }+ return length;+ },+ llseek(stream, offset, whence) {+ var position = offset;+ if (whence === 1) {+ position += stream.position;+ } else if (whence === 2) {+ if (FS.isFile(stream.node.mode)) {+ position += stream.node.usedBytes;+ }+ }+ if (position < 0) {+ throw new FS.ErrnoError(28);+ }+ return position;+ },+ mmap(stream, length, position, prot, flags) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ var ptr;+ var allocated;+ var contents = stream.node.contents;+ // Only make a new copy when MAP_PRIVATE is specified.+ if (!(flags & 2) && contents.buffer === HEAP8.buffer) {+ // We can't emulate MAP_SHARED when the file is not backed by the+ // buffer we're mapping to (e.g. the HEAP buffer).+ allocated = false;+ ptr = contents.byteOffset;+ } else {+ allocated = true;+ ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ if (contents) {+ // Try to avoid unnecessary slices.+ if (position > 0 || position + length < contents.length) {+ if (contents.subarray) {+ contents = contents.subarray(position, position + length);+ } else {+ contents = Array.prototype.slice.call(contents, position, position + length);+ }+ }+ HEAP8.set(contents, ptr);+ }+ }+ return {+ ptr,+ allocated+ };+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);+ // should we check if bytesWritten and length are the same?+ return 0;+ }+ }+};++var FS_modeStringToFlags = str => {+ if (typeof str != "string") return str;+ var flagModes = {+ "r": 0,+ "r+": 2,+ "w": 512 | 64 | 1,+ "w+": 512 | 64 | 2,+ "a": 1024 | 64 | 1,+ "a+": 1024 | 64 | 2+ };+ var flags = flagModes[str];+ if (typeof flags == "undefined") {+ throw new Error(`Unknown file open mode: ${str}`);+ }+ return flags;+};++var FS_fileDataToTypedArray = data => {+ if (typeof data == "string") {+ data = intArrayFromString(data, true);+ }+ if (!data.subarray) {+ data = new Uint8Array(data);+ }+ return data;+};++var FS_getMode = (canRead, canWrite) => {+ var mode = 0;+ if (canRead) mode |= 292 | 73;+ if (canWrite) mode |= 146;+ return mode;+};++var asyncLoad = async url => {+ var arrayBuffer = await readAsync(url);+ return new Uint8Array(arrayBuffer);+};++var FS_createDataFile = (...args) => FS.createDataFile(...args);++var getUniqueRunDependency = id => id;++var runDependencies = 0;++var dependenciesFulfilled = null;++var removeRunDependency = id => {+ runDependencies--;+ Module["monitorRunDependencies"]?.(runDependencies);+ if (runDependencies == 0) {+ if (dependenciesFulfilled) {+ var callback = dependenciesFulfilled;+ dependenciesFulfilled = null;+ callback();+ }+ }+};++var addRunDependency = id => {+ runDependencies++;+ Module["monitorRunDependencies"]?.(runDependencies);+};++var FS_handledByPreloadPlugin = async (byteArray, fullname) => {+ // Ensure plugins are ready.+ if (typeof Browser != "undefined") Browser.init();+ for (var plugin of preloadPlugins) {+ if (plugin["canHandle"](fullname)) {+ return plugin["handle"](byteArray, fullname);+ }+ }+ // If no plugin handled this file then return the original/unmodified+ // byteArray.+ return byteArray;+};++var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {+ // TODO we should allow people to just pass in a complete filename instead+ // of parent and name being that we just join them anyways+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;+ var dep = getUniqueRunDependency(`cp ${fullname}`);+ // might have several active requests for the same fullname+ addRunDependency(dep);+ try {+ var byteArray = url;+ if (typeof url == "string") {+ byteArray = await asyncLoad(url);+ }+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);+ preFinish?.();+ if (!dontCreateFile) {+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);+ }+ } finally {+ removeRunDependency(dep);+ }+};++var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);+};++var FS = {+ root: null,+ mounts: [],+ devices: {},+ streams: [],+ nextInode: 1,+ nameTable: null,+ currentPath: "/",+ initialized: false,+ ignorePermissions: true,+ filesystems: null,+ syncFSRequests: 0,+ ErrnoError: class {+ name="ErrnoError";+ // We set the `name` property to be able to identify `FS.ErrnoError`+ // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.+ // - when using PROXYFS, an error can come from an underlying FS+ // as different FS objects have their own FS.ErrnoError each,+ // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.+ // we'll use the reliable test `err.name == "ErrnoError"` instead+ constructor(errno) {+ this.errno = errno;+ }+ },+ FSStream: class {+ shared={};+ get object() {+ return this.node;+ }+ set object(val) {+ this.node = val;+ }+ get isRead() {+ return (this.flags & 2097155) !== 1;+ }+ get isWrite() {+ return (this.flags & 2097155) !== 0;+ }+ get isAppend() {+ return (this.flags & 1024);+ }+ get flags() {+ return this.shared.flags;+ }+ set flags(val) {+ this.shared.flags = val;+ }+ get position() {+ return this.shared.position;+ }+ set position(val) {+ this.shared.position = val;+ }+ },+ FSNode: class {+ node_ops={};+ stream_ops={};+ readMode=292 | 73;+ writeMode=146;+ mounted=null;+ constructor(parent, name, mode, rdev) {+ if (!parent) {+ parent = this;+ }+ this.parent = parent;+ this.mount = parent.mount;+ this.id = FS.nextInode++;+ this.name = name;+ this.mode = mode;+ this.rdev = rdev;+ this.atime = this.mtime = this.ctime = Date.now();+ }+ get read() {+ return (this.mode & this.readMode) === this.readMode;+ }+ set read(val) {+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;+ }+ get write() {+ return (this.mode & this.writeMode) === this.writeMode;+ }+ set write(val) {+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;+ }+ get isFolder() {+ return FS.isDir(this.mode);+ }+ get isDevice() {+ return FS.isChrdev(this.mode);+ }+ },+ lookupPath(path, opts = {}) {+ if (!path) {+ throw new FS.ErrnoError(44);+ }+ opts.follow_mount ??= true;+ if (!PATH.isAbs(path)) {+ path = FS.cwd() + "/" + path;+ }+ // limit max consecutive symlinks to 40 (SYMLOOP_MAX).+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {+ // split the absolute path+ var parts = path.split("/").filter(p => !!p);+ // start at the root+ var current = FS.root;+ var current_path = "/";+ for (var i = 0; i < parts.length; i++) {+ var islast = (i === parts.length - 1);+ if (islast && opts.parent) {+ // stop resolving+ break;+ }+ if (parts[i] === ".") {+ continue;+ }+ if (parts[i] === "..") {+ current_path = PATH.dirname(current_path);+ if (FS.isRoot(current)) {+ path = current_path + "/" + parts.slice(i + 1).join("/");+ // We're making progress here, don't let many consecutive ..'s+ // lead to ELOOP+ nlinks--;+ continue linkloop;+ } else {+ current = current.parent;+ }+ continue;+ }+ current_path = PATH.join2(current_path, parts[i]);+ try {+ current = FS.lookupNode(current, parts[i]);+ } catch (e) {+ // if noent_okay is true, suppress a ENOENT in the last component+ // and return an object with an undefined node. This is needed for+ // resolving symlinks in the path when creating a file.+ if ((e?.errno === 44) && islast && opts.noent_okay) {+ return {+ path: current_path+ };+ }+ throw e;+ }+ // jump to the mount's root node if this is a mountpoint+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {+ current = current.mounted.root;+ }+ // by default, lookupPath will not follow a symlink if it is the final path component.+ // setting opts.follow = true will override this behavior.+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {+ if (!current.node_ops.readlink) {+ throw new FS.ErrnoError(52);+ }+ var link = current.node_ops.readlink(current);+ if (!PATH.isAbs(link)) {+ link = PATH.dirname(current_path) + "/" + link;+ }+ path = link + "/" + parts.slice(i + 1).join("/");+ continue linkloop;+ }+ }+ return {+ path: current_path,+ node: current+ };+ }+ throw new FS.ErrnoError(32);+ },+ getPath(node) {+ var path;+ while (true) {+ if (FS.isRoot(node)) {+ var mount = node.mount.mountpoint;+ if (!path) return mount;+ return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;+ }+ path = path ? `${node.name}/${path}` : node.name;+ node = node.parent;+ }+ },+ hashName(parentid, name) {+ var hash = 0;+ for (var i = 0; i < name.length; i++) {+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;+ }+ return ((parentid + hash) >>> 0) % FS.nameTable.length;+ },+ hashAddNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ node.name_next = FS.nameTable[hash];+ FS.nameTable[hash] = node;+ },+ hashRemoveNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ if (FS.nameTable[hash] === node) {+ FS.nameTable[hash] = node.name_next;+ } else {+ var current = FS.nameTable[hash];+ while (current) {+ if (current.name_next === node) {+ current.name_next = node.name_next;+ break;+ }+ current = current.name_next;+ }+ }+ },+ lookupNode(parent, name) {+ var errCode = FS.mayLookup(parent);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ var hash = FS.hashName(parent.id, name);+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {+ var nodeName = node.name;+ if (node.parent.id === parent.id && nodeName === name) {+ return node;+ }+ }+ // if we failed to find it in the cache, call into the VFS+ return FS.lookup(parent, name);+ },+ createNode(parent, name, mode, rdev) {+ var node = new FS.FSNode(parent, name, mode, rdev);+ FS.hashAddNode(node);+ return node;+ },+ destroyNode(node) {+ FS.hashRemoveNode(node);+ },+ isRoot(node) {+ return node === node.parent;+ },+ isMountpoint(node) {+ return !!node.mounted;+ },+ isFile(mode) {+ return (mode & 61440) === 32768;+ },+ isDir(mode) {+ return (mode & 61440) === 16384;+ },+ isLink(mode) {+ return (mode & 61440) === 40960;+ },+ isChrdev(mode) {+ return (mode & 61440) === 8192;+ },+ isBlkdev(mode) {+ return (mode & 61440) === 24576;+ },+ isFIFO(mode) {+ return (mode & 61440) === 4096;+ },+ isSocket(mode) {+ return (mode & 49152) === 49152;+ },+ flagsToPermissionString(flag) {+ var perms = [ "r", "w", "rw" ][flag & 3];+ if ((flag & 512)) {+ perms += "w";+ }+ return perms;+ },+ nodePermissions(node, perms) {+ if (FS.ignorePermissions) {+ return 0;+ }+ // return 0 if any user, group or owner bits are set.+ if (perms.includes("r") && !(node.mode & 292)) {+ return 2;+ }+ if (perms.includes("w") && !(node.mode & 146)) {+ return 2;+ }+ if (perms.includes("x") && !(node.mode & 73)) {+ return 2;+ }+ return 0;+ },+ mayLookup(dir) {+ if (!FS.isDir(dir.mode)) return 54;+ var errCode = FS.nodePermissions(dir, "x");+ if (errCode) return errCode;+ if (!dir.node_ops.lookup) return 2;+ return 0;+ },+ mayCreate(dir, name) {+ if (!FS.isDir(dir.mode)) {+ return 54;+ }+ try {+ var node = FS.lookupNode(dir, name);+ return 20;+ } catch (e) {}+ return FS.nodePermissions(dir, "wx");+ },+ mayDelete(dir, name, isdir) {+ var node;+ try {+ node = FS.lookupNode(dir, name);+ } catch (e) {+ return e.errno;+ }+ var errCode = FS.nodePermissions(dir, "wx");+ if (errCode) {+ return errCode;+ }+ if (isdir) {+ if (!FS.isDir(node.mode)) {+ return 54;+ }+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {+ return 10;+ }+ } else if (FS.isDir(node.mode)) {+ return 31;+ }+ return 0;+ },+ mayOpen(node, flags) {+ if (!node) {+ return 44;+ }+ if (FS.isLink(node.mode)) {+ return 32;+ }+ var mode = FS.flagsToPermissionString(flags);+ if (FS.isDir(node.mode)) {+ // opening for write+ // TODO: check for O_SEARCH? (== search for dir only)+ if (mode !== "r" || (flags & (512 | 64))) {+ return 31;+ }+ }+ return FS.nodePermissions(node, mode);+ },+ checkOpExists(op, err) {+ if (!op) {+ throw new FS.ErrnoError(err);+ }+ return op;+ },+ MAX_OPEN_FDS: 4096,+ nextfd() {+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {+ if (!FS.streams[fd]) {+ return fd;+ }+ }+ throw new FS.ErrnoError(33);+ },+ getStreamChecked(fd) {+ var stream = FS.getStream(fd);+ if (!stream) {+ throw new FS.ErrnoError(8);+ }+ return stream;+ },+ getStream: fd => FS.streams[fd],+ createStream(stream, fd = -1) {+ // clone it, so we can return an instance of FSStream+ stream = Object.assign(new FS.FSStream, stream);+ if (fd == -1) {+ fd = FS.nextfd();+ }+ stream.fd = fd;+ FS.streams[fd] = stream;+ return stream;+ },+ closeStream(fd) {+ FS.streams[fd] = null;+ },+ dupStream(origStream, fd = -1) {+ var stream = FS.createStream(origStream, fd);+ stream.stream_ops?.dup?.(stream);+ return stream;+ },+ doSetAttr(stream, node, attr) {+ var setattr = stream?.stream_ops.setattr;+ var arg = setattr ? stream : node;+ setattr ??= node.node_ops.setattr;+ FS.checkOpExists(setattr, 63);+ setattr(arg, attr);+ },+ chrdev_stream_ops: {+ open(stream) {+ var device = FS.getDevice(stream.node.rdev);+ // override node's stream ops with the device's+ stream.stream_ops = device.stream_ops;+ // forward the open call+ stream.stream_ops.open?.(stream);+ },+ llseek() {+ throw new FS.ErrnoError(70);+ }+ },+ major: dev => ((dev) >> 8),+ minor: dev => ((dev) & 255),+ makedev: (ma, mi) => ((ma) << 8 | (mi)),+ registerDevice(dev, ops) {+ FS.devices[dev] = {+ stream_ops: ops+ };+ },+ getDevice: dev => FS.devices[dev],+ getMounts(mount) {+ var mounts = [];+ var check = [ mount ];+ while (check.length) {+ var m = check.pop();+ mounts.push(m);+ check.push(...m.mounts);+ }+ return mounts;+ },+ syncfs(populate, callback) {+ if (typeof populate == "function") {+ callback = populate;+ populate = false;+ }+ FS.syncFSRequests++;+ if (FS.syncFSRequests > 1) {+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);+ }+ var mounts = FS.getMounts(FS.root.mount);+ var completed = 0;+ function doCallback(errCode) {+ FS.syncFSRequests--;+ return callback(errCode);+ }+ function done(errCode) {+ if (errCode) {+ if (!done.errored) {+ done.errored = true;+ return doCallback(errCode);+ }+ return;+ }+ if (++completed >= mounts.length) {+ doCallback(null);+ }+ }+ // sync all mounts+ for (var mount of mounts) {+ if (mount.type.syncfs) {+ mount.type.syncfs(mount, populate, done);+ } else {+ done(null);+ }+ }+ },+ mount(type, opts, mountpoint) {+ var root = mountpoint === "/";+ var pseudo = !mountpoint;+ var node;+ if (root && FS.root) {+ throw new FS.ErrnoError(10);+ } else if (!root && !pseudo) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ mountpoint = lookup.path;+ // use the absolute path+ node = lookup.node;+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ if (!FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ }+ var mount = {+ type,+ opts,+ mountpoint,+ mounts: []+ };+ // create a root node for the fs+ var mountRoot = type.mount(mount);+ mountRoot.mount = mount;+ mount.root = mountRoot;+ if (root) {+ FS.root = mountRoot;+ } else if (node) {+ // set as a mountpoint+ node.mounted = mount;+ // add the new mount to the current mount's children+ if (node.mount) {+ node.mount.mounts.push(mount);+ }+ }+ return mountRoot;+ },+ unmount(mountpoint) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ if (!FS.isMountpoint(lookup.node)) {+ throw new FS.ErrnoError(28);+ }+ // destroy the nodes for this mount, and all its child mounts+ var node = lookup.node;+ var mount = node.mounted;+ var mounts = FS.getMounts(mount);+ for (var [hash, current] of Object.entries(FS.nameTable)) {+ while (current) {+ var next = current.name_next;+ if (mounts.includes(current.mount)) {+ FS.destroyNode(current);+ }+ current = next;+ }+ }+ // no longer a mountpoint+ node.mounted = null;+ // remove this mount from the child mounts+ var idx = node.mount.mounts.indexOf(mount);+ node.mount.mounts.splice(idx, 1);+ },+ lookup(parent, name) {+ return parent.node_ops.lookup(parent, name);+ },+ mknod(path, mode, dev) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ if (!name) {+ throw new FS.ErrnoError(28);+ }+ if (name === "." || name === "..") {+ throw new FS.ErrnoError(20);+ }+ var errCode = FS.mayCreate(parent, name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.mknod) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.mknod(parent, name, mode, dev);+ },+ statfs(path) {+ return FS.statfsNode(FS.lookupPath(path, {+ follow: true+ }).node);+ },+ statfsStream(stream) {+ // We keep a separate statfsStream function because noderawfs overrides+ // it. In noderawfs, stream.node is sometimes null. Instead, we need to+ // look at stream.path.+ return FS.statfsNode(stream.node);+ },+ statfsNode(node) {+ // NOTE: None of the defaults here are true. We're just returning safe and+ // sane values. Currently nodefs and rawfs replace these defaults,+ // other file systems leave them alone.+ var rtn = {+ bsize: 4096,+ frsize: 4096,+ blocks: 1e6,+ bfree: 5e5,+ bavail: 5e5,+ files: FS.nextInode,+ ffree: FS.nextInode - 1,+ fsid: 42,+ flags: 2,+ namelen: 255+ };+ if (node.node_ops.statfs) {+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));+ }+ return rtn;+ },+ create(path, mode = 438) {+ mode &= 4095;+ mode |= 32768;+ return FS.mknod(path, mode, 0);+ },+ mkdir(path, mode = 511) {+ mode &= 511 | 512;+ mode |= 16384;+ return FS.mknod(path, mode, 0);+ },+ mkdirTree(path, mode) {+ var dirs = path.split("/");+ var d = "";+ for (var dir of dirs) {+ if (!dir) continue;+ if (d || PATH.isAbs(path)) d += "/";+ d += dir;+ try {+ FS.mkdir(d, mode);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ }+ },+ mkdev(path, mode, dev) {+ if (typeof dev == "undefined") {+ dev = mode;+ mode = 438;+ }+ mode |= 8192;+ return FS.mknod(path, mode, dev);+ },+ symlink(oldpath, newpath) {+ if (!PATH_FS.resolve(oldpath)) {+ throw new FS.ErrnoError(44);+ }+ var lookup = FS.lookupPath(newpath, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var newname = PATH.basename(newpath);+ var errCode = FS.mayCreate(parent, newname);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.symlink) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.symlink(parent, newname, oldpath);+ },+ rename(old_path, new_path) {+ var old_dirname = PATH.dirname(old_path);+ var new_dirname = PATH.dirname(new_path);+ var old_name = PATH.basename(old_path);+ var new_name = PATH.basename(new_path);+ // parents must exist+ var lookup, old_dir, new_dir;+ // let the errors from non existent directories percolate up+ lookup = FS.lookupPath(old_path, {+ parent: true+ });+ old_dir = lookup.node;+ lookup = FS.lookupPath(new_path, {+ parent: true+ });+ new_dir = lookup.node;+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);+ // need to be part of the same mount+ if (old_dir.mount !== new_dir.mount) {+ throw new FS.ErrnoError(75);+ }+ // source must exist+ var old_node = FS.lookupNode(old_dir, old_name);+ // old path should not be an ancestor of the new path+ var relative = PATH_FS.relative(old_path, new_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(28);+ }+ // new path should not be an ancestor of the old path+ relative = PATH_FS.relative(new_path, old_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(55);+ }+ // see if the new path already exists+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ // early out if nothing needs to change+ if (old_node === new_node) {+ return;+ }+ // we'll need to delete the old entry+ var isdir = FS.isDir(old_node.mode);+ var errCode = FS.mayDelete(old_dir, old_name, isdir);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ // need delete permissions if we'll be overwriting.+ // need create permissions if new doesn't already exist.+ errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!old_dir.node_ops.rename) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {+ throw new FS.ErrnoError(10);+ }+ // if we are going to change the parent, check write permissions+ if (new_dir !== old_dir) {+ errCode = FS.nodePermissions(old_dir, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // remove the node from the lookup hash+ FS.hashRemoveNode(old_node);+ // do the underlying fs rename+ try {+ old_dir.node_ops.rename(old_node, new_dir, new_name);+ // update old node (we do this here to avoid each backend+ // needing to)+ old_node.parent = new_dir;+ } catch (e) {+ throw e;+ } finally {+ // add the node back to the hash (in case node_ops.rename+ // changed its name)+ FS.hashAddNode(old_node);+ }+ },+ rmdir(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, true);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.rmdir) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.rmdir(parent, name);+ FS.destroyNode(node);+ },+ readdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);+ return readdir(node);+ },+ unlink(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, false);+ if (errCode) {+ // According to POSIX, we should map EISDIR to EPERM, but+ // we instead do what Linux does (and we must, as we use+ // the musl linux libc).+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.unlink) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.unlink(parent, name);+ FS.destroyNode(node);+ },+ readlink(path) {+ var lookup = FS.lookupPath(path);+ var link = lookup.node;+ if (!link) {+ throw new FS.ErrnoError(44);+ }+ if (!link.node_ops.readlink) {+ throw new FS.ErrnoError(28);+ }+ return link.node_ops.readlink(link);+ },+ stat(path, dontFollow) {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ var node = lookup.node;+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);+ return getattr(node);+ },+ fstat(fd) {+ var stream = FS.getStreamChecked(fd);+ var node = stream.node;+ var getattr = stream.stream_ops.getattr;+ var arg = getattr ? stream : node;+ getattr ??= node.node_ops.getattr;+ FS.checkOpExists(getattr, 63);+ return getattr(arg);+ },+ lstat(path) {+ return FS.stat(path, true);+ },+ doChmod(stream, node, mode, dontFollow) {+ FS.doSetAttr(stream, node, {+ mode: (mode & 4095) | (node.mode & ~4095),+ ctime: Date.now(),+ dontFollow+ });+ },+ chmod(path, mode, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChmod(null, node, mode, dontFollow);+ },+ lchmod(path, mode) {+ FS.chmod(path, mode, true);+ },+ fchmod(fd, mode) {+ var stream = FS.getStreamChecked(fd);+ FS.doChmod(stream, stream.node, mode, false);+ },+ doChown(stream, node, dontFollow) {+ FS.doSetAttr(stream, node, {+ timestamp: Date.now(),+ dontFollow+ });+ },+ chown(path, uid, gid, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChown(null, node, dontFollow);+ },+ lchown(path, uid, gid) {+ FS.chown(path, uid, gid, true);+ },+ fchown(fd, uid, gid) {+ var stream = FS.getStreamChecked(fd);+ FS.doChown(stream, stream.node, false);+ },+ doTruncate(stream, node, len) {+ if (FS.isDir(node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!FS.isFile(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ var errCode = FS.nodePermissions(node, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.doSetAttr(stream, node, {+ size: len,+ timestamp: Date.now()+ });+ },+ truncate(path, len) {+ if (len < 0) {+ throw new FS.ErrnoError(28);+ }+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doTruncate(null, node, len);+ },+ ftruncate(fd, len) {+ var stream = FS.getStreamChecked(fd);+ if (len < 0 || (stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(28);+ }+ FS.doTruncate(stream, stream.node, len);+ },+ utime(path, atime, mtime) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var setattr = FS.checkOpExists(node.node_ops.setattr, 63);+ setattr(node, {+ atime,+ mtime+ });+ },+ open(path, flags, mode = 438) {+ if (path === "") {+ throw new FS.ErrnoError(44);+ }+ flags = FS_modeStringToFlags(flags);+ if ((flags & 64)) {+ mode = (mode & 4095) | 32768;+ } else {+ mode = 0;+ }+ var node;+ var isDirPath;+ if (typeof path == "object") {+ node = path;+ } else {+ isDirPath = path.endsWith("/");+ // noent_okay makes it so that if the final component of the path+ // doesn't exist, lookupPath returns `node: undefined`. `path` will be+ // updated to point to the target of all symlinks.+ var lookup = FS.lookupPath(path, {+ follow: !(flags & 131072),+ noent_okay: true+ });+ node = lookup.node;+ path = lookup.path;+ }+ // perhaps we need to create the node+ var created = false;+ if ((flags & 64)) {+ if (node) {+ // if O_CREAT and O_EXCL are set, error out if the node already exists+ if ((flags & 128)) {+ throw new FS.ErrnoError(20);+ }+ } else if (isDirPath) {+ throw new FS.ErrnoError(31);+ } else {+ // node doesn't exist, try to create it+ // Ignore the permission bits here to ensure we can `open` this new+ // file below. We use chmod below to apply the permissions once the+ // file is open.+ node = FS.mknod(path, mode | 511, 0);+ created = true;+ }+ }+ if (!node) {+ throw new FS.ErrnoError(44);+ }+ // can't truncate a device+ if (FS.isChrdev(node.mode)) {+ flags &= ~512;+ }+ // if asked only for a directory, then this must be one+ if ((flags & 65536) && !FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ // check permissions, if this is not a file we just created now (it is ok to+ // create and write to a file with read-only permissions; it is read-only+ // for later use)+ if (!created) {+ var errCode = FS.mayOpen(node, flags);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // do truncation if necessary+ if ((flags & 512) && !created) {+ FS.truncate(node, 0);+ }+ // we've already handled these, don't pass down to the underlying vfs+ flags &= ~(128 | 512 | 131072);+ // register the stream with the filesystem+ var stream = FS.createStream({+ node,+ path: FS.getPath(node),+ // we want the absolute path to the node+ flags,+ seekable: true,+ position: 0,+ stream_ops: node.stream_ops,+ // used by the file family libc calls (fopen, fwrite, ferror, etc.)+ ungotten: [],+ error: false+ });+ // call the new stream's open function+ if (stream.stream_ops.open) {+ stream.stream_ops.open(stream);+ }+ if (created) {+ FS.chmod(node, mode & 511);+ }+ return stream;+ },+ close(stream) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (stream.getdents) stream.getdents = null;+ // free readdir state+ try {+ if (stream.stream_ops.close) {+ stream.stream_ops.close(stream);+ }+ } catch (e) {+ throw e;+ } finally {+ FS.closeStream(stream.fd);+ }+ stream.fd = null;+ },+ isClosed(stream) {+ return stream.fd === null;+ },+ llseek(stream, offset, whence) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (!stream.seekable || !stream.stream_ops.llseek) {+ throw new FS.ErrnoError(70);+ }+ if (whence != 0 && whence != 1 && whence != 2) {+ throw new FS.ErrnoError(28);+ }+ stream.position = stream.stream_ops.llseek(stream, offset, whence);+ stream.ungotten = [];+ return stream.position;+ },+ read(stream, buffer, offset, length, position) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.read) {+ throw new FS.ErrnoError(28);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);+ if (!seeking) stream.position += bytesRead;+ return bytesRead;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.write) {+ throw new FS.ErrnoError(28);+ }+ if (stream.seekable && stream.flags & 1024) {+ // seek to the end before writing in append mode+ FS.llseek(stream, 0, 2);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);+ if (!seeking) stream.position += bytesWritten;+ return bytesWritten;+ },+ mmap(stream, length, position, prot, flags) {+ // User requests writing to file (prot & PROT_WRITE != 0).+ // Checking if we have permissions to write to the file unless+ // MAP_PRIVATE flag is set. According to POSIX spec it is possible+ // to write to file opened in read-only mode with MAP_PRIVATE flag,+ // as all modifications will be visible only in the memory of+ // the current process.+ if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {+ throw new FS.ErrnoError(2);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(2);+ }+ if (!stream.stream_ops.mmap) {+ throw new FS.ErrnoError(43);+ }+ if (!length) {+ throw new FS.ErrnoError(28);+ }+ return stream.stream_ops.mmap(stream, length, position, prot, flags);+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ if (!stream.stream_ops.msync) {+ return 0;+ }+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);+ },+ ioctl(stream, cmd, arg) {+ if (!stream.stream_ops.ioctl) {+ throw new FS.ErrnoError(59);+ }+ return stream.stream_ops.ioctl(stream, cmd, arg);+ },+ readFile(path, opts = {}) {+ opts.flags = opts.flags || 0;+ opts.encoding = opts.encoding || "binary";+ if (opts.encoding !== "utf8" && opts.encoding !== "binary") {+ abort(`Invalid encoding type "${opts.encoding}"`);+ }+ var stream = FS.open(path, opts.flags);+ var stat = FS.stat(path);+ var length = stat.size;+ var buf = new Uint8Array(length);+ FS.read(stream, buf, 0, length, 0);+ if (opts.encoding === "utf8") {+ buf = UTF8ArrayToString(buf);+ }+ FS.close(stream);+ return buf;+ },+ writeFile(path, data, opts = {}) {+ opts.flags = opts.flags || 577;+ var stream = FS.open(path, opts.flags, opts.mode);+ data = FS_fileDataToTypedArray(data);+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);+ FS.close(stream);+ },+ cwd: () => FS.currentPath,+ chdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ if (lookup.node === null) {+ throw new FS.ErrnoError(44);+ }+ if (!FS.isDir(lookup.node.mode)) {+ throw new FS.ErrnoError(54);+ }+ var errCode = FS.nodePermissions(lookup.node, "x");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.currentPath = lookup.path;+ },+ createDefaultDirectories() {+ FS.mkdir("/tmp");+ FS.mkdir("/home");+ FS.mkdir("/home/web_user");+ },+ createDefaultDevices() {+ // create /dev+ FS.mkdir("/dev");+ // setup /dev/null+ FS.registerDevice(FS.makedev(1, 3), {+ read: () => 0,+ write: (stream, buffer, offset, length, pos) => length,+ llseek: () => 0+ });+ FS.mkdev("/dev/null", FS.makedev(1, 3));+ // setup /dev/tty and /dev/tty1+ // stderr needs to print output using err() rather than out()+ // so we register a second tty just for it.+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);+ FS.mkdev("/dev/tty", FS.makedev(5, 0));+ FS.mkdev("/dev/tty1", FS.makedev(6, 0));+ // setup /dev/[u]random+ // use a buffer to avoid overhead of individual crypto calls per byte+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;+ var randomByte = () => {+ if (randomLeft === 0) {+ randomFill(randomBuffer);+ randomLeft = randomBuffer.byteLength;+ }+ return randomBuffer[--randomLeft];+ };+ FS.createDevice("/dev", "random", randomByte);+ FS.createDevice("/dev", "urandom", randomByte);+ // we're not going to emulate the actual shm device,+ // just create the tmp dirs that reside in it commonly+ FS.mkdir("/dev/shm");+ FS.mkdir("/dev/shm/tmp");+ },+ createSpecialDirectories() {+ // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the+ // name of the stream for fd 6 (see test_unistd_ttyname)+ FS.mkdir("/proc");+ var proc_self = FS.mkdir("/proc/self");+ FS.mkdir("/proc/self/fd");+ FS.mount({+ mount() {+ var node = FS.createNode(proc_self, "fd", 16895, 73);+ node.stream_ops = {+ llseek: MEMFS.stream_ops.llseek+ };+ node.node_ops = {+ lookup(parent, name) {+ var fd = +name;+ var stream = FS.getStreamChecked(fd);+ var ret = {+ parent: null,+ mount: {+ mountpoint: "fake"+ },+ node_ops: {+ readlink: () => stream.path+ },+ id: fd + 1+ };+ ret.parent = ret;+ // make it look like a simple root node+ return ret;+ },+ readdir() {+ return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString());+ }+ };+ return node;+ }+ }, {}, "/proc/self/fd");+ },+ createStandardStreams(input, output, error) {+ // TODO deprecate the old functionality of a single+ // input / output callback and that utilizes FS.createDevice+ // and instead require a unique set of stream ops+ // by default, we symlink the standard streams to the+ // default tty devices. however, if the standard streams+ // have been overwritten we create a unique device for+ // them instead.+ if (input) {+ FS.createDevice("/dev", "stdin", input);+ } else {+ FS.symlink("/dev/tty", "/dev/stdin");+ }+ if (output) {+ FS.createDevice("/dev", "stdout", null, output);+ } else {+ FS.symlink("/dev/tty", "/dev/stdout");+ }+ if (error) {+ FS.createDevice("/dev", "stderr", null, error);+ } else {+ FS.symlink("/dev/tty1", "/dev/stderr");+ }+ // open default streams for the stdin, stdout and stderr devices+ var stdin = FS.open("/dev/stdin", 0);+ var stdout = FS.open("/dev/stdout", 1);+ var stderr = FS.open("/dev/stderr", 1);+ },+ staticInit() {+ FS.nameTable = new Array(4096);+ FS.mount(MEMFS, {}, "/");+ FS.createDefaultDirectories();+ FS.createDefaultDevices();+ FS.createSpecialDirectories();+ FS.filesystems = {+ "MEMFS": MEMFS+ };+ },+ init(input, output, error) {+ FS.initialized = true;+ // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here+ input ??= Module["stdin"];+ output ??= Module["stdout"];+ error ??= Module["stderr"];+ FS.createStandardStreams(input, output, error);+ },+ quit() {+ FS.initialized = false;+ // force-flush all streams, so we get musl std streams printed out+ // close all of our streams+ for (var stream of FS.streams) {+ if (stream) {+ FS.close(stream);+ }+ }+ },+ findObject(path, dontResolveLastLink) {+ var ret = FS.analyzePath(path, dontResolveLastLink);+ if (!ret.exists) {+ return null;+ }+ return ret.object;+ },+ analyzePath(path, dontResolveLastLink) {+ // operate from within the context of the symlink's target+ try {+ var lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ path = lookup.path;+ } catch (e) {}+ var ret = {+ isRoot: false,+ exists: false,+ error: 0,+ name: null,+ path: null,+ object: null,+ parentExists: false,+ parentPath: null,+ parentObject: null+ };+ try {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ ret.parentExists = true;+ ret.parentPath = lookup.path;+ ret.parentObject = lookup.node;+ ret.name = PATH.basename(path);+ lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ ret.exists = true;+ ret.path = lookup.path;+ ret.object = lookup.node;+ ret.name = lookup.node.name;+ ret.isRoot = lookup.path === "/";+ } catch (e) {+ ret.error = e.errno;+ }+ return ret;+ },+ createPath(parent, path, canRead, canWrite) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ var parts = path.split("/").reverse();+ while (parts.length) {+ var part = parts.pop();+ if (!part) continue;+ var current = PATH.join2(parent, part);+ try {+ FS.mkdir(current);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ parent = current;+ }+ return current;+ },+ createFile(parent, name, properties, canRead, canWrite) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(canRead, canWrite);+ return FS.create(path, mode);+ },+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {+ var path = name;+ if (parent) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ path = name ? PATH.join2(parent, name) : parent;+ }+ var mode = FS_getMode(canRead, canWrite);+ var node = FS.create(path, mode);+ if (data) {+ data = FS_fileDataToTypedArray(data);+ // make sure we can write to the file+ FS.chmod(node, mode | 146);+ var stream = FS.open(node, 577);+ FS.write(stream, data, 0, data.length, 0, canOwn);+ FS.close(stream);+ FS.chmod(node, mode);+ }+ },+ createDevice(parent, name, input, output) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(!!input, !!output);+ FS.createDevice.major ??= 64;+ var dev = FS.makedev(FS.createDevice.major++, 0);+ // Create a fake device that a set of stream ops to emulate+ // the old behavior.+ FS.registerDevice(dev, {+ open(stream) {+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ if (output?.buffer?.length) {+ output(10);+ }+ },+ read(stream, buffer, offset, length, pos) {+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = input();+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ for (var i = 0; i < length; i++) {+ try {+ output(buffer[offset + i]);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ });+ return FS.mkdev(path, mode, dev);+ },+ forceLoadFile(obj) {+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;+ if (globalThis.XMLHttpRequest) {+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");+ } else {+ // Command-line.+ try {+ obj.contents = readBinary(obj.url);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ },+ createLazyFile(parent, name, url, canRead, canWrite) {+ // Lazy chunked Uint8Array (implements get and length from Uint8Array).+ // Actual getting is abstracted away for eventual reuse.+ class LazyUint8Array {+ lengthKnown=false;+ chunks=[];+ // Loaded chunks. Index is the chunk number+ get(idx) {+ if (idx > this.length - 1 || idx < 0) {+ return undefined;+ }+ var chunkOffset = idx % this.chunkSize;+ var chunkNum = (idx / this.chunkSize) | 0;+ return this.getter(chunkNum)[chunkOffset];+ }+ setDataGetter(getter) {+ this.getter = getter;+ }+ cacheLength() {+ // Find length+ var xhr = new XMLHttpRequest;+ xhr.open("HEAD", url, false);+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ var datalength = Number(xhr.getResponseHeader("Content-length"));+ var header;+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";+ var chunkSize = 1024 * 1024;+ // Chunk size in bytes+ if (!hasByteServing) chunkSize = datalength;+ // Function to get a range from the remote URL.+ var doXHR = (from, to) => {+ if (from > to) abort("invalid range (" + from + ", " + to + ") or no bytes requested!");+ if (to > datalength - 1) abort("only " + datalength + " bytes available! programmer error!");+ // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);+ // Some hints to the browser that we want binary data.+ xhr.responseType = "arraybuffer";+ if (xhr.overrideMimeType) {+ xhr.overrideMimeType("text/plain; charset=x-user-defined");+ }+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ if (xhr.response !== undefined) {+ return new Uint8Array(/** @type{Array<number>} */ (xhr.response || []));+ }+ return intArrayFromString(xhr.responseText || "", true);+ };+ var lazyArray = this;+ lazyArray.setDataGetter(chunkNum => {+ var start = chunkNum * chunkSize;+ var end = (chunkNum + 1) * chunkSize - 1;+ // including this byte+ end = Math.min(end, datalength - 1);+ // if datalength-1 is selected, this is the last block+ if (typeof lazyArray.chunks[chunkNum] == "undefined") {+ lazyArray.chunks[chunkNum] = doXHR(start, end);+ }+ if (typeof lazyArray.chunks[chunkNum] == "undefined") abort("doXHR failed!");+ return lazyArray.chunks[chunkNum];+ });+ if (usesGzip || !datalength) {+ // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length+ chunkSize = datalength = 1;+ // this will force getter(0)/doXHR do download the whole file+ datalength = this.getter(0).length;+ chunkSize = datalength;+ out("LazyFiles on gzip forces download of the whole file when length is accessed");+ }+ this._length = datalength;+ this._chunkSize = chunkSize;+ this.lengthKnown = true;+ }+ get length() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._length;+ }+ get chunkSize() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._chunkSize;+ }+ }+ if (globalThis.XMLHttpRequest) {+ if (!ENVIRONMENT_IS_WORKER) abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");+ var lazyArray = new LazyUint8Array;+ var properties = {+ isDevice: false,+ contents: lazyArray+ };+ } else {+ var properties = {+ isDevice: false,+ url+ };+ }+ var node = FS.createFile(parent, name, properties, canRead, canWrite);+ // This is a total hack, but I want to get this lazy file code out of the+ // core of MEMFS. If we want to keep this lazy file concept I feel it should+ // be its own thin LAZYFS proxying calls to MEMFS.+ if (properties.contents) {+ node.contents = properties.contents;+ } else if (properties.url) {+ node.contents = null;+ node.url = properties.url;+ }+ // Add a function that defers querying the file size until it is asked the first time.+ Object.defineProperties(node, {+ usedBytes: {+ get: function() {+ return this.contents.length;+ }+ }+ });+ // override each stream op with one that tries to force load the lazy file first+ var stream_ops = {};+ for (const [key, fn] of Object.entries(node.stream_ops)) {+ stream_ops[key] = (...args) => {+ FS.forceLoadFile(node);+ return fn(...args);+ };+ }+ function writeChunks(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= contents.length) return 0;+ var size = Math.min(contents.length - position, length);+ if (contents.slice) {+ // normal array+ for (var i = 0; i < size; i++) {+ buffer[offset + i] = contents[position + i];+ }+ } else {+ for (var i = 0; i < size; i++) {+ // LazyUint8Array from sync binary XHR+ buffer[offset + i] = contents.get(position + i);+ }+ }+ return size;+ }+ // use a custom read function+ stream_ops.read = (stream, buffer, offset, length, position) => {+ FS.forceLoadFile(node);+ return writeChunks(stream, buffer, offset, length, position);+ };+ // use a custom mmap function+ stream_ops.mmap = (stream, length, position, prot, flags) => {+ FS.forceLoadFile(node);+ var ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ writeChunks(stream, HEAP8, ptr, length, position);+ return {+ ptr,+ allocated: true+ };+ };+ node.stream_ops = stream_ops;+ return node;+ }+};++/**+ * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the+ * emscripten HEAP, returns a copy of that string as a Javascript String object.+ *+ * @param {number} ptr+ * @param {number=} maxBytesToRead - An optional length that specifies the+ * maximum number of bytes to read. You can omit this parameter to scan the+ * string until the first 0 byte. If maxBytesToRead is passed, and the string+ * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the+ * string will cut short at that byte index.+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {+ if (!ptr) return "";+ var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));+};++var SYSCALLS = {+ calculateAt(dirfd, path, allowEmpty) {+ if (PATH.isAbs(path)) {+ return path;+ }+ // relative path+ var dir;+ if (dirfd === -100) {+ dir = FS.cwd();+ } else {+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);+ dir = dirstream.path;+ }+ if (path.length == 0) {+ if (!allowEmpty) {+ throw new FS.ErrnoError(44);+ }+ return dir;+ }+ return dir + "/" + path;+ },+ writeStat(buf, stat) {+ HEAPU32[((buf) >> 2)] = stat.dev;+ HEAPU32[(((buf) + (4)) >> 2)] = stat.mode;+ HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink;+ HEAPU32[(((buf) + (12)) >> 2)] = stat.uid;+ HEAPU32[(((buf) + (16)) >> 2)] = stat.gid;+ HEAPU32[(((buf) + (20)) >> 2)] = stat.rdev;+ (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ HEAP32[(((buf) + (32)) >> 2)] = 4096;+ HEAP32[(((buf) + (36)) >> 2)] = stat.blocks;+ var atime = stat.atime.getTime();+ var mtime = stat.mtime.getTime();+ var ctime = stat.ctime.getTime();+ (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]);+ return 0;+ },+ writeStatFs(buf, stats) {+ HEAPU32[(((buf) + (4)) >> 2)] = stats.bsize;+ HEAPU32[(((buf) + (60)) >> 2)] = stats.bsize;+ (tempI64 = [ stats.blocks >>> 0, (tempDouble = stats.blocks, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (8)) >> 2)] = tempI64[0], HEAP32[(((buf) + (12)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bfree >>> 0, (tempDouble = stats.bfree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (16)) >> 2)] = tempI64[0], HEAP32[(((buf) + (20)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bavail >>> 0, (tempDouble = stats.bavail, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.files >>> 0, (tempDouble = stats.files, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (32)) >> 2)] = tempI64[0], HEAP32[(((buf) + (36)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.ffree >>> 0, (tempDouble = stats.ffree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = stats.fsid;+ HEAPU32[(((buf) + (64)) >> 2)] = stats.flags;+ // ST_NOSUID+ HEAPU32[(((buf) + (56)) >> 2)] = stats.namelen;+ },+ doMsync(addr, stream, len, flags, offset) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ if (flags & 2) {+ // MAP_PRIVATE calls need not to be synced back to underlying fs+ return 0;+ }+ var buffer = HEAPU8.slice(addr, addr + len);+ FS.msync(stream, buffer, offset, len, flags);+ },+ getStreamFromFD(fd) {+ var stream = FS.getStreamChecked(fd);+ return stream;+ },+ varargs: undefined,+ getStr(ptr) {+ var ret = UTF8ToString(ptr);+ return ret;+ }+};++function ___syscall_dup(fd) {+ try {+ var old = SYSCALLS.getStreamFromFD(fd);+ return FS.dupStream(old).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_faccessat(dirfd, path, amode, flags) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (amode & ~7) {+ // need a valid mode+ return -28;+ }+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ if (!node) {+ return -44;+ }+ var perms = "";+ if (amode & 4) perms += "r";+ if (amode & 2) perms += "w";+ if (amode & 1) perms += "x";+ if (perms && FS.nodePermissions(node, perms)) {+ return -2;+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var syscallGetVarargI = () => {+ // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.+ var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];+ SYSCALLS.varargs += 4;+ return ret;+};++var syscallGetVarargP = syscallGetVarargI;++function ___syscall_fcntl64(fd, cmd, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (cmd) {+ case 0:+ {+ var arg = syscallGetVarargI();+ if (arg < 0) {+ return -28;+ }+ while (FS.streams[arg]) {+ arg++;+ }+ var newStream;+ newStream = FS.dupStream(stream, arg);+ return newStream.fd;+ }++ case 1:+ case 2:+ return 0;++ // FD_CLOEXEC makes no sense for a single process.+ case 3:+ return stream.flags;++ case 4:+ {+ var arg = syscallGetVarargI();+ stream.flags |= arg;+ return 0;+ }++ case 12:+ {+ var arg = syscallGetVarargP();+ var offset = 0;+ // We're always unlocked.+ HEAP16[(((arg) + (offset)) >> 1)] = 2;+ return 0;+ }++ case 13:+ case 14:+ // Pretend that the locking is successful. These are process-level locks,+ // and Emscripten programs are a single process. If we supported linking a+ // filesystem between programs, we'd need to do more here.+ // See https://github.com/emscripten-core/emscripten/issues/23697+ return 0;+ }+ return -28;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_fstat64(fd, buf) {+ try {+ return SYSCALLS.writeStat(buf, FS.fstat(fd));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;++function ___syscall_ftruncate64(fd, length_low, length_high) {+ var length = convertI32PairToI53Checked(length_low, length_high);+ try {+ if (isNaN(length)) return -61;+ FS.ftruncate(fd, length);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_ioctl(fd, op, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (op) {+ case 21509:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21505:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcgets) {+ var termios = stream.tty.ops.ioctl_tcgets(stream);+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = termios.c_iflag || 0;+ HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0;+ HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0;+ HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0;+ for (var i = 0; i < 32; i++) {+ HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0;+ }+ return 0;+ }+ return 0;+ }++ case 21510:+ case 21511:+ case 21512:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21506:+ case 21507:+ case 21508:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcsets) {+ var argp = syscallGetVarargP();+ var c_iflag = HEAP32[((argp) >> 2)];+ var c_oflag = HEAP32[(((argp) + (4)) >> 2)];+ var c_cflag = HEAP32[(((argp) + (8)) >> 2)];+ var c_lflag = HEAP32[(((argp) + (12)) >> 2)];+ var c_cc = [];+ for (var i = 0; i < 32; i++) {+ c_cc.push(HEAP8[(argp + i) + (17)]);+ }+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, {+ c_iflag,+ c_oflag,+ c_cflag,+ c_lflag,+ c_cc+ });+ }+ return 0;+ }++ case 21519:+ {+ if (!stream.tty) return -59;+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = 0;+ return 0;+ }++ case 21520:+ {+ if (!stream.tty) return -59;+ return -28;+ }++ case 21537:+ case 21531:+ {+ var argp = syscallGetVarargP();+ return FS.ioctl(stream, op, argp);+ }++ case 21523:+ {+ // TODO: in theory we should write to the winsize struct that gets+ // passed in, but for now musl doesn't read anything on it+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tiocgwinsz) {+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);+ var argp = syscallGetVarargP();+ HEAP16[((argp) >> 1)] = winsize[0];+ HEAP16[(((argp) + (2)) >> 1)] = winsize[1];+ }+ return 0;+ }++ case 21524:+ {+ // TODO: technically, this ioctl call should change the window size.+ // but, since emscripten doesn't have any concept of a terminal window+ // yet, we'll just silently throw it away as we do TIOCGWINSZ+ if (!stream.tty) return -59;+ return 0;+ }++ case 21515:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ default:+ return -28;+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_lstat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.lstat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_newfstatat(dirfd, path, buf, flags) {+ try {+ path = SYSCALLS.getStr(path);+ var nofollow = flags & 256;+ var allowEmpty = flags & 4096;+ flags = flags & (~6400);+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_openat(dirfd, path, flags, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ var mode = varargs ? syscallGetVarargI() : 0;+ return FS.open(path, flags, mode).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_stat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __abort_js = () => abort("");++var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {};++var AsciiToString = ptr => {+ var str = "";+ while (1) {+ var ch = HEAPU8[ptr++];+ if (!ch) return str;+ str += String.fromCharCode(ch);+ }+};++var awaitingDependencies = {};++var registeredTypes = {};++var typeDependencies = {};++var BindingError = class BindingError extends Error {+ constructor(message) {+ super(message);+ this.name = "BindingError";+ }+};++var throwBindingError = message => {+ throw new BindingError(message);+};++/** @param {Object=} options */ function sharedRegisterType(rawType, registeredInstance, options = {}) {+ var name = registeredInstance.name;+ if (!rawType) {+ throwBindingError(`type "${name}" must have a positive integer typeid pointer`);+ }+ if (registeredTypes.hasOwnProperty(rawType)) {+ if (options.ignoreDuplicateRegistrations) {+ return;+ } else {+ throwBindingError(`Cannot register type '${name}' twice`);+ }+ }+ registeredTypes[rawType] = registeredInstance;+ delete typeDependencies[rawType];+ if (awaitingDependencies.hasOwnProperty(rawType)) {+ var callbacks = awaitingDependencies[rawType];+ delete awaitingDependencies[rawType];+ callbacks.forEach(cb => cb());+ }+}++/** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) {+ return sharedRegisterType(rawType, registeredInstance, options);+}++/** @suppress {globalThis} */ var __embind_register_bool = (rawType, name, trueValue, falseValue) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: function(wt) {+ // ambiguous emscripten ABI: sometimes return values are+ // true or false, and sometimes integers (0 or 1)+ return !!wt;+ },+ toWireType: function(destructors, o) {+ return o ? trueValue : falseValue;+ },+ readValueFromPointer: function(pointer) {+ return this.fromWireType(HEAPU8[pointer]);+ },+ destructorFunction: null+ });+};++var emval_freelist = [];++var emval_handles = [ 0, 1, , 1, null, 1, true, 1, false, 1 ];++var __emval_decref = handle => {+ if (handle > 9 && 0 === --emval_handles[handle + 1]) {+ var value = emval_handles[handle];+ emval_handles[handle] = undefined;+ emval_freelist.push(handle);+ }+};++var Emval = {+ toValue: handle => {+ if (!handle) {+ throwBindingError(`Cannot use deleted val. handle = ${handle}`);+ }+ return emval_handles[handle];+ },+ toHandle: value => {+ switch (value) {+ case undefined:+ return 2;++ case null:+ return 4;++ case true:+ return 6;++ case false:+ return 8;++ default:+ {+ const handle = emval_freelist.pop() || emval_handles.length;+ emval_handles[handle] = value;+ emval_handles[handle + 1] = 1;+ return handle;+ }+ }+ }+};++/** @suppress {globalThis} */ function readPointer(pointer) {+ return this.fromWireType(HEAPU32[((pointer) >> 2)]);+}++var EmValType = {+ name: "emscripten::val",+ fromWireType: handle => {+ var rv = Emval.toValue(handle);+ __emval_decref(handle);+ return rv;+ },+ toWireType: (destructors, value) => Emval.toHandle(value),+ readValueFromPointer: readPointer,+ destructorFunction: null+};++var __embind_register_emval = rawType => registerType(rawType, EmValType);++var floatReadValueFromPointer = (name, width) => {+ switch (width) {+ case 4:+ return function(pointer) {+ return this.fromWireType(HEAPF32[((pointer) >> 2)]);+ };++ case 8:+ return function(pointer) {+ return this.fromWireType(HEAPF64[((pointer) >> 3)]);+ };++ default:+ throw new TypeError(`invalid float width (${width}): ${name}`);+ }+};++var __embind_register_float = (rawType, name, size) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: value => value,+ toWireType: (destructors, value) => value,+ readValueFromPointer: floatReadValueFromPointer(name, size),+ destructorFunction: null+ });+};++var integerReadValueFromPointer = (name, width, signed) => {+ // integers are quite common, so generate very specialized functions+ switch (width) {+ case 1:+ return signed ? pointer => HEAP8[pointer] : pointer => HEAPU8[pointer];++ case 2:+ return signed ? pointer => HEAP16[((pointer) >> 1)] : pointer => HEAPU16[((pointer) >> 1)];++ case 4:+ return signed ? pointer => HEAP32[((pointer) >> 2)] : pointer => HEAPU32[((pointer) >> 2)];++ default:+ throw new TypeError(`invalid integer width (${width}): ${name}`);+ }+};++/** @suppress {globalThis} */ var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => {+ name = AsciiToString(name);+ const isUnsignedType = minRange === 0;+ let fromWireType = value => value;+ if (isUnsignedType) {+ var bitshift = 32 - 8 * size;+ fromWireType = value => (value << bitshift) >>> bitshift;+ maxRange = fromWireType(maxRange);+ }+ registerType(primitiveType, {+ name,+ fromWireType,+ toWireType: (destructors, value) => value,+ readValueFromPointer: integerReadValueFromPointer(name, size, minRange !== 0),+ destructorFunction: null+ });+};++var __embind_register_memory_view = (rawType, dataTypeIndex, name) => {+ var typeMapping = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];+ var TA = typeMapping[dataTypeIndex];+ function decodeMemoryView(handle) {+ var size = HEAPU32[((handle) >> 2)];+ var data = HEAPU32[(((handle) + (4)) >> 2)];+ return new TA(HEAP8.buffer, data, size);+ }+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: decodeMemoryView,+ readValueFromPointer: decodeMemoryView+ }, {+ ignoreDuplicateRegistrations: true+ });+};++var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);++var __embind_register_std_string = (rawType, name) => {+ name = AsciiToString(name);+ var stdStringIsUTF8 = true;+ registerType(rawType, {+ name,+ // For some method names we use string keys here since they are part of+ // the public/external API and/or used by the runtime-generated code.+ fromWireType(value) {+ var length = HEAPU32[((value) >> 2)];+ var payload = value + 4;+ var str;+ if (stdStringIsUTF8) {+ str = UTF8ToString(payload, length, true);+ } else {+ str = "";+ for (var i = 0; i < length; ++i) {+ str += String.fromCharCode(HEAPU8[payload + i]);+ }+ }+ _free(value);+ return str;+ },+ toWireType(destructors, value) {+ if (value instanceof ArrayBuffer) {+ value = new Uint8Array(value);+ }+ var length;+ var valueIsOfTypeString = (typeof value == "string");+ // We accept `string` or array views with single byte elements+ if (!(valueIsOfTypeString || (ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1))) {+ throwBindingError("Cannot pass non-string to std::string");+ }+ if (stdStringIsUTF8 && valueIsOfTypeString) {+ length = lengthBytesUTF8(value);+ } else {+ length = value.length;+ }+ // assumes POINTER_SIZE alignment+ var base = _malloc(4 + length + 1);+ var ptr = base + 4;+ HEAPU32[((base) >> 2)] = length;+ if (valueIsOfTypeString) {+ if (stdStringIsUTF8) {+ stringToUTF8(value, ptr, length + 1);+ } else {+ for (var i = 0; i < length; ++i) {+ var charCode = value.charCodeAt(i);+ if (charCode > 255) {+ _free(base);+ throwBindingError("String has UTF-16 code units that do not fit in 8 bits");+ }+ HEAPU8[ptr + i] = charCode;+ }+ }+ } else {+ HEAPU8.set(value, ptr);+ }+ if (destructors !== null) {+ destructors.push(_free, base);+ }+ return base;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var UTF16Decoder = new TextDecoder("utf-16le");++var UTF16ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var idx = ((ptr) >> 1);+ var endIdx = findStringEnd(HEAPU16, idx, maxBytesToRead / 2, ignoreNul);+ return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx));+};++var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 2) return 0;+ maxBytesToWrite -= 2;+ // Null terminator.+ var startPtr = outPtr;+ var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length;+ for (var i = 0; i < numCharsToWrite; ++i) {+ // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.+ var codeUnit = str.charCodeAt(i);+ // possibly a lead surrogate+ HEAP16[((outPtr) >> 1)] = codeUnit;+ outPtr += 2;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP16[((outPtr) >> 1)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF16 = str => str.length * 2;++var UTF32ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var str = "";+ var startIdx = ((ptr) >> 2);+ // If maxBytesToRead is not passed explicitly, it will be undefined, and this+ // will always evaluate to true. This saves on code size.+ for (var i = 0; !(i >= maxBytesToRead / 4); i++) {+ var utf32 = HEAPU32[startIdx + i];+ if (!utf32 && !ignoreNul) break;+ str += String.fromCodePoint(utf32);+ }+ return str;+};++var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 4) return 0;+ var startPtr = outPtr;+ var endPtr = startPtr + maxBytesToWrite - 4;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ HEAP32[((outPtr) >> 2)] = codePoint;+ outPtr += 4;+ if (outPtr + 4 > endPtr) break;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP32[((outPtr) >> 2)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF32 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ len += 4;+ }+ return len;+};++var __embind_register_std_wstring = (rawType, charSize, name) => {+ name = AsciiToString(name);+ var decodeString, encodeString, lengthBytesUTF;+ if (charSize === 2) {+ decodeString = UTF16ToString;+ encodeString = stringToUTF16;+ lengthBytesUTF = lengthBytesUTF16;+ } else {+ decodeString = UTF32ToString;+ encodeString = stringToUTF32;+ lengthBytesUTF = lengthBytesUTF32;+ }+ registerType(rawType, {+ name,+ fromWireType: value => {+ // Code mostly taken from _embind_register_std_string fromWireType+ var length = HEAPU32[((value) >> 2)];+ var str = decodeString(value + 4, length * charSize, true);+ _free(value);+ return str;+ },+ toWireType: (destructors, value) => {+ if (!(typeof value == "string")) {+ throwBindingError(`Cannot pass non-string to C++ string type ${name}`);+ }+ // assumes POINTER_SIZE alignment+ var length = lengthBytesUTF(value);+ var ptr = _malloc(4 + length + charSize);+ HEAPU32[((ptr) >> 2)] = length / charSize;+ encodeString(value, ptr + 4, length + charSize);+ if (destructors !== null) {+ destructors.push(_free, ptr);+ }+ return ptr;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var __embind_register_void = (rawType, name) => {+ name = AsciiToString(name);+ registerType(rawType, {+ isVoid: true,+ // void return values can be optimized out sometimes+ name,+ fromWireType: () => undefined,+ // TODO: assert if anything else is given?+ toWireType: (destructors, o) => undefined+ });+};++var emval_methodCallers = [];++var emval_addMethodCaller = caller => {+ var id = emval_methodCallers.length;+ emval_methodCallers.push(caller);+ return id;+};++var getTypeName = type => {+ var ptr = ___getTypeName(type);+ var rv = AsciiToString(ptr);+ _free(ptr);+ return rv;+};++var requireRegisteredType = (rawType, humanName) => {+ var impl = registeredTypes[rawType];+ if (undefined === impl) {+ throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);+ }+ return impl;+};++var emval_lookupTypes = (argCount, argTypes) => {+ var a = new Array(argCount);+ for (var i = 0; i < argCount; ++i) {+ a[i] = requireRegisteredType(HEAPU32[(((argTypes) + (i * 4)) >> 2)], `parameter ${i}`);+ }+ return a;+};++var createNamedFunction = (name, func) => Object.defineProperty(func, "name", {+ value: name+});++var emval_returnValue = (toReturnWire, destructorsRef, handle) => {+ var destructors = [];+ var result = toReturnWire(destructors, handle);+ if (destructors.length) {+ // void, primitives and any other types w/o destructors don't need to allocate a handle+ HEAPU32[((destructorsRef) >> 2)] = Emval.toHandle(destructors);+ }+ return result;+};++var emval_symbols = {};++var getStringOrSymbol = address => {+ var symbol = emval_symbols[address];+ if (symbol === undefined) {+ return AsciiToString(address);+ }+ return symbol;+};++var __emval_create_invoker = (argCount, argTypesPtr, kind) => {+ var GenericWireTypeSize = 8;+ var [retType, ...argTypes] = emval_lookupTypes(argCount, argTypesPtr);+ var toReturnWire = retType.toWireType.bind(retType);+ var argFromPtr = argTypes.map(type => type.readValueFromPointer.bind(type));+ argCount--;+ // remove the extracted return type+ var argN = new Array(argCount);+ var invokerFunction = (handle, methodName, destructorsRef, args) => {+ var offset = 0;+ for (var i = 0; i < argCount; ++i) {+ argN[i] = argFromPtr[i](args + offset);+ offset += GenericWireTypeSize;+ }+ var rv;+ switch (kind) {+ case 0:+ rv = Emval.toValue(handle).apply(null, argN);+ break;++ case 2:+ rv = Reflect.construct(Emval.toValue(handle), argN);+ break;++ case 3:+ // no-op, just return the argument+ rv = argN[0];+ break;++ case 1:+ rv = Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);+ break;+ }+ return emval_returnValue(toReturnWire, destructorsRef, rv);+ };+ var functionName = `methodCaller<(${argTypes.map(t => t.name)}) => ${retType.name}>`;+ return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction));+};++var __emval_get_global = name => {+ if (!name) {+ return Emval.toHandle(globalThis);+ }+ name = getStringOrSymbol(name);+ return Emval.toHandle(globalThis[name]);+};++var __emval_get_property = (handle, key) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ return Emval.toHandle(handle[key]);+};++var __emval_incref = handle => {+ if (handle > 9) {+ emval_handles[handle + 1] += 1;+ }+};++var __emval_instanceof = (object, constructor) => {+ object = Emval.toValue(object);+ constructor = Emval.toValue(constructor);+ return object instanceof constructor;+};++var __emval_invoke = (caller, handle, methodName, destructorsRef, args) => emval_methodCallers[caller](handle, methodName, destructorsRef, args);++var __emval_new_cstring = v => Emval.toHandle(getStringOrSymbol(v));++var runDestructors = destructors => {+ while (destructors.length) {+ var ptr = destructors.pop();+ var del = destructors.pop();+ del(ptr);+ }+};++var __emval_run_destructors = handle => {+ var destructors = Emval.toValue(handle);+ runDestructors(destructors);+ __emval_decref(handle);+};++var __emval_set_property = (handle, key, value) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ value = Emval.toValue(value);+ handle[key] = value;+};++var __emval_typeof = handle => {+ handle = Emval.toValue(handle);+ return Emval.toHandle(typeof handle);+};++function __gmtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getUTCSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getUTCMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getUTCHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getUTCDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getUTCMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getUTCFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getUTCDay();+ var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);+ var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+}++var isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);++var MONTH_DAYS_LEAP_CUMULATIVE = [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ];++var MONTH_DAYS_REGULAR_CUMULATIVE = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ];++var ydayFromDate = date => {+ var leap = isLeapYear(date.getFullYear());+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;+ // -1 since it's days since Jan 1+ return yday;+};++function __localtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ HEAP32[(((tmPtr) + (36)) >> 2)] = -(date.getTimezoneOffset() * 60);+ // Attention: DST is in December in South, and some regions don't have DST at all.+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;+ HEAP32[(((tmPtr) + (32)) >> 2)] = dst;+}++var setTempRet0 = val => __emscripten_tempret_set(val);++var __mktime_js = function(tmPtr) {+ var ret = (() => {+ var date = new Date(HEAP32[(((tmPtr) + (20)) >> 2)] + 1900, HEAP32[(((tmPtr) + (16)) >> 2)], HEAP32[(((tmPtr) + (12)) >> 2)], HEAP32[(((tmPtr) + (8)) >> 2)], HEAP32[(((tmPtr) + (4)) >> 2)], HEAP32[((tmPtr) >> 2)], 0);+ // There's an ambiguous hour when the time goes back; the tm_isdst field is+ // used to disambiguate it. Date() basically guesses, so we fix it up if it+ // guessed wrong, or fill in tm_isdst with the guess if it's -1.+ var dst = HEAP32[(((tmPtr) + (32)) >> 2)];+ var guessedOffset = date.getTimezoneOffset();+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dstOffset = Math.min(winterOffset, summerOffset);+ // DST is in December in South+ if (dst < 0) {+ // Attention: some regions don't have DST at all.+ HEAP32[(((tmPtr) + (32)) >> 2)] = Number(summerOffset != winterOffset && dstOffset == guessedOffset);+ } else if ((dst > 0) != (dstOffset == guessedOffset)) {+ var nonDstOffset = Math.max(winterOffset, summerOffset);+ var trueOffset = dst > 0 ? dstOffset : nonDstOffset;+ // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.+ date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4);+ }+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ // To match expected behavior, update fields from date+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getYear();+ var timeMs = date.getTime();+ if (isNaN(timeMs)) {+ return -1;+ }+ // Return time in microseconds+ return timeMs / 1e3;+ })();+ return (setTempRet0((tempDouble = ret, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0)),+ ret >>> 0);+};++function __mmap_js(len, prot, flags, fd, offset_low, offset_high, allocated, addr) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var res = FS.mmap(stream, len, offset, prot, flags);+ var ptr = res.ptr;+ HEAP32[((allocated) >> 2)] = res.allocated;+ HEAPU32[((addr) >> 2)] = ptr;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function __munmap_js(addr, len, prot, flags, fd, offset_low, offset_high) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ if (prot & 2) {+ SYSCALLS.doMsync(addr, stream, len, flags, offset);+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __tzset_js = (timezone, daylight, std_name, dst_name) => {+ // TODO: Use (malleable) environment variables instead of system settings.+ var currentYear = (new Date).getFullYear();+ var winter = new Date(currentYear, 0, 1);+ var summer = new Date(currentYear, 6, 1);+ var winterOffset = winter.getTimezoneOffset();+ var summerOffset = summer.getTimezoneOffset();+ // Local standard timezone offset. Local standard time is not adjusted for+ // daylight savings. This code uses the fact that getTimezoneOffset returns+ // a greater value during Standard Time versus Daylight Saving Time (DST).+ // Thus it determines the expected output during Standard Time, and it+ // compares whether the output of the given date the same (Standard) or less+ // (DST).+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);+ // timezone is specified as seconds west of UTC ("The external variable+ // `timezone` shall be set to the difference, in seconds, between+ // Coordinated Universal Time (UTC) and local standard time."), the same+ // as returned by stdTimezoneOffset.+ // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html+ HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60;+ HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset);+ var extractZone = timezoneOffset => {+ // Why inverse sign?+ // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset+ var sign = timezoneOffset >= 0 ? "-" : "+";+ var absOffset = Math.abs(timezoneOffset);+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");+ var minutes = String(absOffset % 60).padStart(2, "0");+ return `UTC${sign}${hours}${minutes}`;+ };+ var winterName = extractZone(winterOffset);+ var summerName = extractZone(summerOffset);+ if (summerOffset < winterOffset) {+ // Northern hemisphere+ stringToUTF8(winterName, std_name, 17);+ stringToUTF8(summerName, dst_name, 17);+ } else {+ stringToUTF8(winterName, dst_name, 17);+ stringToUTF8(summerName, std_name, 17);+ }+};++var _emscripten_get_now = () => performance.now();++var _emscripten_date_now = () => Date.now();++var nowIsMonotonic = 1;++var checkWasiClock = clock_id => clock_id >= 0 && clock_id <= 3;++function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) {+ var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high);+ if (!checkWasiClock(clk_id)) {+ return 28;+ }+ var now;+ // all wasi clocks but realtime are monotonic+ if (clk_id === 0) {+ now = _emscripten_date_now();+ } else if (nowIsMonotonic) {+ now = _emscripten_get_now();+ } else {+ return 52;+ }+ // "now" is in ms, and wasi times are in ns.+ var nsec = Math.round(now * 1e3 * 1e3);+ (tempI64 = [ nsec >>> 0, (tempDouble = nsec, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((ptime) >> 2)] = tempI64[0], HEAP32[(((ptime) + (4)) >> 2)] = tempI64[1]);+ return 0;+}++var readEmAsmArgsArray = [];++var readEmAsmArgs = (sigPtr, buf) => {+ readEmAsmArgsArray.length = 0;+ var ch;+ // Most arguments are i32s, so shift the buffer pointer so it is a plain+ // index into HEAP32.+ while (ch = HEAPU8[sigPtr++]) {+ // Floats are always passed as doubles, so all types except for 'i'+ // are 8 bytes and require alignment.+ var wide = (ch != 105);+ wide &= (ch != 112);+ buf += wide && (buf % 8) ? 4 : 0;+ readEmAsmArgsArray.push(// Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode.+ ch == 112 ? HEAPU32[((buf) >> 2)] : ch == 105 ? HEAP32[((buf) >> 2)] : HEAPF64[((buf) >> 3)]);+ buf += wide ? 8 : 4;+ }+ return readEmAsmArgsArray;+};++var runEmAsmFunction = (code, sigPtr, argbuf) => {+ var args = readEmAsmArgs(sigPtr, argbuf);+ return ASM_CONSTS[code](...args);+};++var _emscripten_asm_const_int = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_errn = (str, len) => err(UTF8ToString(str, len));++var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate+// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side+// for any code that deals with heap sizes, which would require special+// casing all heap size related code to treat 0 specially.+2147483648;++var _emscripten_get_heap_max = () => getHeapMax();++var _emscripten_has_asyncify = () => 0;++var _emscripten_outn = (str, len) => out(UTF8ToString(str, len));++var UNWIND_CACHE = {};++var stringToNewUTF8 = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = _malloc(size);+ if (ret) stringToUTF8(str, ret, size);+ return ret;+};++/** @returns {number} */ var convertFrameToPC = frame => {+ var match;+ if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) {+ // Wasm engines give the binary offset directly, so we use that as return address+ return +match[1];+ } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) {+ // If we are in js, we can use the js line number as the "return address".+ // This should work for wasm2js. We tag the high bit to distinguish this+ // from wasm addresses.+ return 2147483648 | +match[1];+ }+ // return 0 if we can't find any+ return 0;+};++var saveInUnwindCache = callstack => {+ for (var line of callstack) {+ var pc = convertFrameToPC(line);+ if (pc) {+ UNWIND_CACHE[pc] = line;+ }+ }+};++var jsStackTrace = () => (new Error).stack.toString();++var _emscripten_stack_snapshot = () => {+ var callstack = jsStackTrace().split("\n");+ if (callstack[0] == "Error") {+ callstack.shift();+ }+ saveInUnwindCache(callstack);+ // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can+ // unwind from this spot.+ UNWIND_CACHE.last_addr = convertFrameToPC(callstack[3]);+ UNWIND_CACHE.last_stack = callstack;+ return UNWIND_CACHE.last_addr;+};++var _emscripten_pc_get_function = pc => {+ var frame = UNWIND_CACHE[pc];+ if (!frame) return 0;+ var name;+ var match;+ // First try to match foo.wasm.sym files explcitly. e.g.+ // at test_return_address.wasm.main (wasm://wasm/test_return_address.wasm-0012cc2a:wasm-function[26]:0x9f3+ // Then match JS symbols which don't include that module name:+ // at invokeEntryPoint (.../test_return_address.js:1500:42)+ // Finally match firefox format:+ // Object._main@http://server.com:4324:12'+ if (match = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^(.+?)@/.exec(frame)) {+ name = match[1];+ } else {+ return 0;+ }+ _free(_emscripten_pc_get_function.ret ?? 0);+ _emscripten_pc_get_function.ret = stringToNewUTF8(name);+ return _emscripten_pc_get_function.ret;+};++var growMemory = size => {+ var oldHeapSize = wasmMemory.buffer.byteLength;+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;+ try {+ // round size grow request up to wasm page size (fixed 64KB per spec)+ wasmMemory.grow(pages);+ // .grow() takes a delta compared to the previous size+ updateMemoryViews();+ return 1;+ } catch (e) {}+};++var _emscripten_resize_heap = requestedSize => {+ var oldSize = HEAPU8.length;+ // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.+ requestedSize >>>= 0;+ // With multithreaded builds, races can happen (another thread might increase the size+ // in between), so return a failure, and let the caller retry.+ // Memory resize rules:+ // 1. Always increase heap size to at least the requested size, rounded up+ // to next page multiple.+ // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap+ // geometrically: increase the heap size according to+ // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most+ // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).+ // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap+ // linearly: increase the heap size by at least+ // MEMORY_GROWTH_LINEAR_STEP bytes.+ // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by+ // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest+ // 4. If we were unable to allocate as much memory, it may be due to+ // over-eager decision to excessively reserve due to (3) above.+ // Hence if an allocation fails, cut down on the amount of excess+ // growth, in an attempt to succeed to perform a smaller allocation.+ // A limit is set for how much we can grow. We should not exceed that+ // (the wasm binary specifies it, so if we tried, we'd fail anyhow).+ var maxHeapSize = getHeapMax();+ if (requestedSize > maxHeapSize) {+ return false;+ }+ // Loop through potential heap size increases. If we attempt a too eager+ // reservation that fails, cut down on the attempted size and reserve a+ // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {+ var overGrownHeapSize = oldSize * (1 + .2 / cutDown);+ // ensure geometric growth+ // but limit overreserving (default to capping at +96MB overgrowth at most)+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));+ var replacement = growMemory(newSize);+ if (replacement) {+ return true;+ }+ }+ return false;+};++var _emscripten_stack_unwind_buffer = (addr, buffer, count) => {+ var stack;+ if (UNWIND_CACHE.last_addr == addr) {+ stack = UNWIND_CACHE.last_stack;+ } else {+ stack = jsStackTrace().split("\n");+ if (stack[0] == "Error") {+ stack.shift();+ }+ saveInUnwindCache(stack);+ }+ var offset = 3;+ while (stack[offset] && convertFrameToPC(stack[offset]) != addr) {+ ++offset;+ }+ for (var i = 0; i < count && stack[i + offset]; ++i) {+ HEAP32[(((buffer) + (i * 4)) >> 2)] = convertFrameToPC(stack[i + offset]);+ }+ return i;+};++var GLctx;++var webgl_enable_ANGLE_instanced_arrays = ctx => {+ // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("ANGLE_instanced_arrays");+ // Because this extension is a core function in WebGL 2, assign the extension entry points in place of+ // where the core functions will reside in WebGL 2. This way the calling code can call these without+ // having to dynamically branch depending if running against WebGL 1 or WebGL 2.+ if (ext) {+ ctx["vertexAttribDivisor"] = (index, divisor) => ext["vertexAttribDivisorANGLE"](index, divisor);+ ctx["drawArraysInstanced"] = (mode, first, count, primcount) => ext["drawArraysInstancedANGLE"](mode, first, count, primcount);+ ctx["drawElementsInstanced"] = (mode, count, type, indices, primcount) => ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount);+ return 1;+ }+};++var webgl_enable_OES_vertex_array_object = ctx => {+ // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("OES_vertex_array_object");+ if (ext) {+ ctx["createVertexArray"] = () => ext["createVertexArrayOES"]();+ ctx["deleteVertexArray"] = vao => ext["deleteVertexArrayOES"](vao);+ ctx["bindVertexArray"] = vao => ext["bindVertexArrayOES"](vao);+ ctx["isVertexArray"] = vao => ext["isVertexArrayOES"](vao);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_buffers = ctx => {+ // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("WEBGL_draw_buffers");+ if (ext) {+ ctx["drawBuffers"] = (n, bufs) => ext["drawBuffersWEBGL"](n, bufs);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance = ctx => // Closure is expected to be allowed to minify the '.dibvbi' property, so not accessing it quoted.+!!(ctx.dibvbi = ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));++var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance = ctx => !!(ctx.mdibvbi = ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));++var webgl_enable_EXT_polygon_offset_clamp = ctx => !!(ctx.extPolygonOffsetClamp = ctx.getExtension("EXT_polygon_offset_clamp"));++var webgl_enable_EXT_clip_control = ctx => !!(ctx.extClipControl = ctx.getExtension("EXT_clip_control"));++var webgl_enable_WEBGL_polygon_mode = ctx => !!(ctx.webglPolygonMode = ctx.getExtension("WEBGL_polygon_mode"));++var webgl_enable_WEBGL_multi_draw = ctx => // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted.+!!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw"));++var getEmscriptenSupportedExtensions = ctx => {+ // Restrict the list of advertised extensions to those that we actually+ // support.+ var supportedExtensions = [ // WebGL 1 extensions+ "ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_disjoint_timer_query", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_sRGB", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_depth_texture", "WEBGL_draw_buffers", // WebGL 2 extensions+ "EXT_color_buffer_float", "EXT_conservative_depth", "EXT_disjoint_timer_query_webgl2", "EXT_texture_norm16", "NV_shader_noperspective_interpolation", "WEBGL_clip_cull_distance", // WebGL 1 and WebGL 2 extensions+ "EXT_clip_control", "EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_float_blend", "EXT_polygon_offset_clamp", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "KHR_parallel_shader_compile", "OES_texture_float_linear", "WEBGL_blend_func_extended", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_lose_context", "WEBGL_multi_draw", "WEBGL_polygon_mode" ];+ // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.+ return (ctx.getSupportedExtensions() || []).filter(ext => supportedExtensions.includes(ext));+};++var registerPreMainLoop = f => {+ // Does nothing unless $MainLoop is included/used.+ typeof MainLoop != "undefined" && MainLoop.preMainLoop.push(f);+};++var GL = {+ counter: 1,+ buffers: [],+ mappedBuffers: {},+ programs: [],+ framebuffers: [],+ renderbuffers: [],+ textures: [],+ shaders: [],+ vaos: [],+ contexts: [],+ offscreenCanvases: {},+ queries: [],+ samplers: [],+ transformFeedbacks: [],+ syncs: [],+ byteSizeByTypeRoot: 5120,+ byteSizeByType: [ 1, 1, 2, 2, 4, 4, 4, 2, 3, 4, 8 ],+ stringCache: {},+ stringiCache: {},+ unpackAlignment: 4,+ unpackRowLength: 0,+ recordError: errorCode => {+ if (!GL.lastError) {+ GL.lastError = errorCode;+ }+ },+ getNewId: table => {+ var ret = GL.counter++;+ for (var i = table.length; i < ret; i++) {+ table[i] = null;+ }+ // Skip over any non-null elements that might have been created by+ // glBindBuffer.+ while (table[ret]) {+ ret = GL.counter++;+ }+ return ret;+ },+ genObject: (n, buffers, createFunction, objectTable) => {+ for (var i = 0; i < n; i++) {+ var buffer = GLctx[createFunction]();+ var id = buffer && GL.getNewId(objectTable);+ if (buffer) {+ buffer.name = id;+ objectTable[id] = buffer;+ } else {+ GL.recordError(1282);+ }+ HEAP32[(((buffers) + (i * 4)) >> 2)] = id;+ }+ },+ MAX_TEMP_BUFFER_SIZE: 2097152,+ numTempVertexBuffersPerSize: 64,+ log2ceilLookup: i => 32 - Math.clz32(i === 0 ? 0 : i - 1),+ generateTempBuffers: (quads, context) => {+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ context.tempVertexBufferCounters1 = [];+ context.tempVertexBufferCounters2 = [];+ context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex + 1;+ context.tempVertexBuffers1 = [];+ context.tempVertexBuffers2 = [];+ context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex + 1;+ context.tempIndexBuffers = [];+ context.tempIndexBuffers.length = largestIndex + 1;+ for (var i = 0; i <= largestIndex; ++i) {+ context.tempIndexBuffers[i] = null;+ // Created on-demand+ context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;+ var ringbufferLength = GL.numTempVertexBuffersPerSize;+ context.tempVertexBuffers1[i] = [];+ context.tempVertexBuffers2[i] = [];+ var ringbuffer1 = context.tempVertexBuffers1[i];+ var ringbuffer2 = context.tempVertexBuffers2[i];+ ringbuffer1.length = ringbuffer2.length = ringbufferLength;+ for (var j = 0; j < ringbufferLength; ++j) {+ ringbuffer1[j] = ringbuffer2[j] = null;+ }+ }+ if (quads) {+ // GL_QUAD indexes can be precalculated+ context.tempQuadIndexBuffer = GLctx.createBuffer();+ context.GLctx.bindBuffer(34963, context.tempQuadIndexBuffer);+ var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;+ var quadIndexes = new Uint16Array(numIndexes);+ var i = 0, v = 0;+ while (1) {+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 1;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 3;+ if (i >= numIndexes) break;+ v += 4;+ }+ context.GLctx.bufferData(34963, quadIndexes, 35044);+ context.GLctx.bindBuffer(34963, null);+ }+ },+ getTempVertexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];+ var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];+ GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx] + 1) & (GL.numTempVertexBuffersPerSize - 1);+ var vbo = ringbuffer[nextFreeBufferIndex];+ if (vbo) {+ return vbo;+ }+ var prevVBO = GLctx.getParameter(34964);+ ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();+ GLctx.bindBuffer(34962, ringbuffer[nextFreeBufferIndex]);+ GLctx.bufferData(34962, 1 << idx, 35048);+ GLctx.bindBuffer(34962, prevVBO);+ return ringbuffer[nextFreeBufferIndex];+ },+ getTempIndexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ibo = GL.currentContext.tempIndexBuffers[idx];+ if (ibo) {+ return ibo;+ }+ var prevIBO = GLctx.getParameter(34965);+ GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();+ GLctx.bindBuffer(34963, GL.currentContext.tempIndexBuffers[idx]);+ GLctx.bufferData(34963, 1 << idx, 35048);+ GLctx.bindBuffer(34963, prevIBO);+ return GL.currentContext.tempIndexBuffers[idx];+ },+ newRenderingFrameStarted: () => {+ if (!GL.currentContext) {+ return;+ }+ var vb = GL.currentContext.tempVertexBuffers1;+ GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;+ GL.currentContext.tempVertexBuffers2 = vb;+ vb = GL.currentContext.tempVertexBufferCounters1;+ GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;+ GL.currentContext.tempVertexBufferCounters2 = vb;+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ for (var i = 0; i <= largestIndex; ++i) {+ GL.currentContext.tempVertexBufferCounters1[i] = 0;+ }+ },+ getSource: (shader, count, string, length) => {+ var source = "";+ for (var i = 0; i < count; ++i) {+ var len = length ? HEAPU32[(((length) + (i * 4)) >> 2)] : undefined;+ source += UTF8ToString(HEAPU32[(((string) + (i * 4)) >> 2)], len);+ }+ return source;+ },+ calcBufLength: (size, type, stride, count) => {+ if (stride > 0) {+ return count * stride;+ }+ var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];+ return size * typeSize * count;+ },+ usedTempBuffers: [],+ preDrawHandleClientVertexAttribBindings: count => {+ GL.resetBufferBinding = false;+ // TODO: initial pass to detect ranges we need to upload, might not need+ // an upload per attrib+ for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {+ var cb = GL.currentContext.clientBuffers[i];+ if (!cb.clientside || !cb.enabled) continue;+ GL.resetBufferBinding = true;+ var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);+ var buf = GL.getTempVertexBuffer(size);+ GLctx.bindBuffer(34962, buf);+ GLctx.bufferSubData(34962, 0, HEAPU8.subarray(cb.ptr, cb.ptr + size));+ cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0);+ }+ },+ postDrawHandleClientVertexAttribBindings: () => {+ if (GL.resetBufferBinding) {+ GLctx.bindBuffer(34962, GL.buffers[GLctx.currentArrayBufferBinding]);+ }+ },+ createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => {+ // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL+ // context on a canvas, calling .getContext() will always return that+ // context independent of which 'webgl' or 'webgl2'+ // context version was passed. See:+ // https://webkit.org/b/222758+ // and:+ // https://github.com/emscripten-core/emscripten/issues/13295.+ // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari+ // version field in above check.+ if (!canvas.getContextSafariWebGL2Fixed) {+ canvas.getContextSafariWebGL2Fixed = canvas.getContext;+ /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ function fixedGetContext(ver, attrs) {+ var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs);+ return ((ver == "webgl") == (gl instanceof WebGLRenderingContext)) ? gl : null;+ }+ canvas.getContext = fixedGetContext;+ }+ var ctx = (webGLContextAttributes.majorVersion > 1) ? canvas.getContext("webgl2", webGLContextAttributes) : canvas.getContext("webgl", webGLContextAttributes);+ if (!ctx) return 0;+ var handle = GL.registerContext(ctx, webGLContextAttributes);+ return handle;+ },+ registerContext: (ctx, webGLContextAttributes) => {+ // without pthreads a context is just an integer ID+ var handle = GL.getNewId(GL.contexts);+ var context = {+ handle,+ attributes: webGLContextAttributes,+ version: webGLContextAttributes.majorVersion,+ GLctx: ctx+ };+ // Store the created context object so that we can access the context+ // given a canvas without having to pass the parameters again.+ if (ctx.canvas) ctx.canvas.GLctxObject = context;+ GL.contexts[handle] = context;+ if (typeof webGLContextAttributes.enableExtensionsByDefault == "undefined" || webGLContextAttributes.enableExtensionsByDefault) {+ GL.initExtensions(context);+ }+ context.maxVertexAttribs = context.GLctx.getParameter(34921);+ context.clientBuffers = [];+ for (var i = 0; i < context.maxVertexAttribs; i++) {+ context.clientBuffers[i] = {+ enabled: false,+ clientside: false,+ size: 0,+ type: 0,+ normalized: 0,+ stride: 0,+ ptr: 0,+ vertexAttribPointerAdaptor: null+ };+ }+ GL.generateTempBuffers(false, context);+ return handle;+ },+ makeContextCurrent: contextHandle => {+ // Active Emscripten GL layer context object.+ GL.currentContext = GL.contexts[contextHandle];+ // Active WebGL context object.+ Module["ctx"] = GLctx = GL.currentContext?.GLctx;+ return !(contextHandle && !GLctx);+ },+ getContext: contextHandle => GL.contexts[contextHandle],+ deleteContext: contextHandle => {+ if (GL.currentContext === GL.contexts[contextHandle]) {+ GL.currentContext = null;+ }+ if (typeof JSEvents == "object") {+ // Release all JS event handlers on the DOM element that the GL context is+ // associated with since the context is now deleted.+ JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);+ }+ // Make sure the canvas object no longer refers to the context object so+ // there are no GC surprises.+ if (GL.contexts[contextHandle]?.GLctx.canvas) {+ GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined;+ }+ GL.contexts[contextHandle] = null;+ },+ initExtensions: context => {+ // If this function is called without a specific context object, init the+ // extensions of the currently active context.+ context ||= GL.currentContext;+ if (context.initExtensionsDone) return;+ context.initExtensionsDone = true;+ var GLctx = context.GLctx;+ // Detect the presence of a few extensions manually, since the GL interop+ // layer itself will need to know if they exist.+ // Extensions that are available in both WebGL 1 and WebGL 2+ webgl_enable_WEBGL_multi_draw(GLctx);+ webgl_enable_EXT_polygon_offset_clamp(GLctx);+ webgl_enable_EXT_clip_control(GLctx);+ webgl_enable_WEBGL_polygon_mode(GLctx);+ // Extensions that are only available in WebGL 1 (the calls will be no-ops+ // if called on a WebGL 2 context active)+ webgl_enable_ANGLE_instanced_arrays(GLctx);+ webgl_enable_OES_vertex_array_object(GLctx);+ webgl_enable_WEBGL_draw_buffers(GLctx);+ // Extensions that are available from WebGL >= 2 (no-op if called on a WebGL 1 context active)+ webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);+ webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);+ // On WebGL 2, EXT_disjoint_timer_query is replaced with an alternative+ // that's based on core APIs, and exposes only the queryCounterEXT()+ // entrypoint.+ if (context.version >= 2) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query_webgl2");+ }+ // However, Firefox exposes the WebGL 1 version on WebGL 2 as well and+ // thus we look for the WebGL 1 version again if the WebGL 2 version+ // isn't present. https://bugzil.la/1328882+ if (context.version < 2 || !GLctx.disjointTimerQueryExt) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");+ }+ for (var ext of getEmscriptenSupportedExtensions(GLctx)) {+ // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders+ // are not enabled by default.+ if (!ext.includes("lose_context") && !ext.includes("debug")) {+ // Call .getExtension() to enable that extension permanently.+ GLctx.getExtension(ext);+ }+ }+ }+};++var webglPowerPreferences = [ "default", "low-power", "high-performance" ];++/** @type {Object} */ var specialHTMLTargets = [ 0, globalThis.document ?? 0, globalThis.window ?? 0 ];++var findEventTarget = target => {+ // The sensible "default" target varies between events, but use window as the default+ // since DOM events mostly can default to that. Specific callback registrations+ // override their own defaults.+ if (!target) return window;+ if (typeof target == "number") target = specialHTMLTargets[target] || UTF8ToString(target);+ if (target === "#window") return window; else if (target === "#document") return document; else if (target === "#screen") return screen; else if (target === "#canvas") return Module["canvas"]; else if (typeof target == "string") return globalThis.document?.getElementById(target);+ return target;+};++var findCanvasEventTarget = target => {+ if (typeof target == "number") target = UTF8ToString(target);+ if (!target || target === "#canvas") {+ if (typeof GL != "undefined" && GL.offscreenCanvases["canvas"]) return GL.offscreenCanvases["canvas"];+ // TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.+ return Module["canvas"];+ }+ if (typeof GL != "undefined" && GL.offscreenCanvases[target]) return GL.offscreenCanvases[target];+ return findEventTarget(target);+};++var _emscripten_webgl_do_create_context = (target, attributes) => {+ var attr32 = ((attributes) >> 2);+ var powerPreference = HEAP32[attr32 + (8 >> 2)];+ var contextAttributes = {+ "alpha": !!HEAP8[attributes + 0],+ "depth": !!HEAP8[attributes + 1],+ "stencil": !!HEAP8[attributes + 2],+ "antialias": !!HEAP8[attributes + 3],+ "premultipliedAlpha": !!HEAP8[attributes + 4],+ "preserveDrawingBuffer": !!HEAP8[attributes + 5],+ "powerPreference": webglPowerPreferences[powerPreference],+ "failIfMajorPerformanceCaveat": !!HEAP8[attributes + 12],+ // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure.+ majorVersion: HEAP32[attr32 + (16 >> 2)],+ minorVersion: HEAP32[attr32 + (20 >> 2)],+ enableExtensionsByDefault: HEAP8[attributes + 24],+ explicitSwapControl: HEAP8[attributes + 25],+ proxyContextToMainThread: HEAP32[attr32 + (28 >> 2)],+ renderViaOffscreenBackBuffer: HEAP8[attributes + 32]+ };+ var canvas = findCanvasEventTarget(target);+ if (!canvas) {+ return 0;+ }+ if (contextAttributes.explicitSwapControl) {+ return 0;+ }+ var contextHandle = GL.createContext(canvas, contextAttributes);+ return contextHandle;+};++var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context;++var _emscripten_webgl_destroy_context = contextHandle => {+ if (GL.currentContext == contextHandle) GL.currentContext = 0;+ GL.deleteContext(contextHandle);+};++var _emscripten_webgl_get_context_attributes = (c, a) => {+ if (!a) return -5;+ c = GL.contexts[c];+ if (!c) return -3;+ var t = c.GLctx?.getContextAttributes();+ if (!t) return -3;+ HEAP8[a] = t.alpha;+ HEAP8[(a) + (1)] = t.depth;+ HEAP8[(a) + (2)] = t.stencil;+ HEAP8[(a) + (3)] = t.antialias;+ HEAP8[(a) + (4)] = t.premultipliedAlpha;+ HEAP8[(a) + (5)] = t.preserveDrawingBuffer;+ var power = t["powerPreference"] && webglPowerPreferences.indexOf(t["powerPreference"]);+ HEAP32[(((a) + (8)) >> 2)] = power;+ HEAP8[(a) + (12)] = t.failIfMajorPerformanceCaveat;+ HEAP32[(((a) + (16)) >> 2)] = c.version;+ HEAP32[(((a) + (20)) >> 2)] = 0;+ HEAP8[(a) + (24)] = c.attributes.enableExtensionsByDefault;+ return 0;+};++var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0;++var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context;++var _emscripten_webgl_make_context_current = contextHandle => {+ var success = GL.makeContextCurrent(contextHandle);+ return success ? 0 : -5;+};++var stackAlloc = sz => __emscripten_stack_alloc(sz);++var stringToUTF8OnStack = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = stackAlloc(size);+ stringToUTF8(str, ret, size);+ return ret;+};++var writeI53ToI64 = (ptr, num) => {+ HEAPU32[((ptr) >> 2)] = num;+ var lower = HEAPU32[((ptr) >> 2)];+ HEAPU32[(((ptr) + (4)) >> 2)] = (num - lower) / 4294967296;+};++var readI53FromI64 = ptr => HEAPU32[((ptr) >> 2)] + HEAP32[(((ptr) + (4)) >> 2)] * 4294967296;++var wasmTableMirror = [];++var getWasmTableEntry = funcPtr => {+ var func = wasmTableMirror[funcPtr];+ if (!func) {+ /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);+ }+ return func;+};++var WebGPU = {+ Internals: {+ jsObjects: [],+ jsObjectInsert: (ptr, jsObject) => {+ ptr >>>= 0;+ WebGPU.Internals.jsObjects[ptr] = jsObject;+ },+ bufferOnUnmaps: [],+ futures: [],+ futureInsert: (futureId, promise) => {}+ },+ getJsObject: ptr => {+ if (!ptr) return undefined;+ ptr >>>= 0;+ return WebGPU.Internals.jsObjects[ptr];+ },+ importJsAdapter: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateAdapter(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroup: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroup(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroupLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroupLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBuffer: (buffer, parentPtr = 0) => {+ // At the moment, we do not allow importing pending buffers.+ assert(buffer.mapState === "unmapped");+ var bufferPtr = _emwgpuImportBuffer(parentPtr);+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ return bufferPtr;+ },+ importJsCommandBuffer: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandBuffer(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsCommandEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsDevice: (device, parentPtr = 0) => {+ var queuePtr = _emwgpuCreateQueue(parentPtr);+ var devicePtr = _emwgpuCreateDevice(parentPtr, queuePtr);+ WebGPU.Internals.jsObjectInsert(queuePtr, device.queue);+ WebGPU.Internals.jsObjectInsert(devicePtr, device);+ return devicePtr;+ },+ importJsExternalTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateExternalTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsPipelineLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreatePipelineLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQuerySet: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQuerySet(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQueue: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQueue(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundle: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundle(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundleEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundleEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSampler: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSampler(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsShaderModule: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateShaderModule(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSurface: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSurface(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTextureView: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTextureView(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ errorCallback: (callback, type, message, userdata) => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(message);+ getWasmTableEntry(callback)(type, messagePtr, userdata);+ stackRestore(sp);+ },+ iterateExtensions: (root, handlers) => {+ for (var ptr = HEAPU32[((root) >> 2)]; ptr; ptr = HEAPU32[((ptr) >> 2)]) {+ var sType = HEAP32[(((ptr) + (4)) >> 2)];+ // This will crash if there's no handler indicating either a bogus+ // sType, or one we haven't implemented yet.+ var handler = handlers[sType](ptr);+ }+ },+ setStringView: (ptr, data, length) => {+ HEAPU32[((ptr) >> 2)] = data;+ HEAPU32[(((ptr) + (4)) >> 2)] = length;+ },+ makeStringFromStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeStringFromOptionalStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // If we don't have a valid string pointer, just return undefined when+ // optional.+ if (!ptr) {+ if (length === 0) {+ return "";+ }+ return undefined;+ }+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeColor: ptr => ({+ "r": HEAPF64[((ptr) >> 3)],+ "g": HEAPF64[(((ptr) + (8)) >> 3)],+ "b": HEAPF64[(((ptr) + (16)) >> 3)],+ "a": HEAPF64[(((ptr) + (24)) >> 3)]+ }),+ makeExtent3D: ptr => ({+ "width": HEAPU32[((ptr) >> 2)],+ "height": HEAPU32[(((ptr) + (4)) >> 2)],+ "depthOrArrayLayers": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeOrigin3D: ptr => ({+ "x": HEAPU32[((ptr) >> 2)],+ "y": HEAPU32[(((ptr) + (4)) >> 2)],+ "z": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeTexelCopyTextureInfo: ptr => ({+ "texture": WebGPU.getJsObject(HEAPU32[((ptr) >> 2)]),+ "mipLevel": HEAPU32[(((ptr) + (4)) >> 2)],+ "origin": WebGPU.makeOrigin3D(ptr + 8),+ "aspect": WebGPU.TextureAspect[HEAP32[(((ptr) + (20)) >> 2)]]+ }),+ makeTexelCopyBufferLayout: ptr => {+ var bytesPerRow = HEAPU32[(((ptr) + (8)) >> 2)];+ var rowsPerImage = HEAPU32[(((ptr) + (12)) >> 2)];+ return {+ "offset": readI53FromI64(ptr),+ "bytesPerRow": bytesPerRow === 4294967295 ? undefined : bytesPerRow,+ "rowsPerImage": rowsPerImage === 4294967295 ? undefined : rowsPerImage+ };+ },+ makeTexelCopyBufferInfo: ptr => {+ var layoutPtr = ptr + 0;+ var bufferCopyView = WebGPU.makeTexelCopyBufferLayout(layoutPtr);+ bufferCopyView["buffer"] = WebGPU.getJsObject(HEAPU32[(((ptr) + (16)) >> 2)]);+ return bufferCopyView;+ },+ makePassTimestampWrites: ptr => {+ if (ptr === 0) return undefined;+ return {+ "querySet": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "beginningOfPassWriteIndex": HEAPU32[(((ptr) + (8)) >> 2)],+ "endOfPassWriteIndex": HEAPU32[(((ptr) + (12)) >> 2)]+ };+ },+ makePipelineConstants: (constantCount, constantsPtr) => {+ if (!constantCount) return;+ var constants = {};+ for (var i = 0; i < constantCount; ++i) {+ var entryPtr = constantsPtr + 24 * i;+ var key = WebGPU.makeStringFromStringView(entryPtr + 4);+ constants[key] = HEAPF64[(((entryPtr) + (16)) >> 3)];+ }+ return constants;+ },+ makePipelineLayout: layoutPtr => {+ if (!layoutPtr) return "auto";+ return WebGPU.getJsObject(layoutPtr);+ },+ makeComputeState: ptr => {+ if (!ptr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((ptr) + (16)) >> 2)], HEAPU32[(((ptr) + (20)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(ptr + 8)+ };+ return desc;+ },+ makeComputePipelineDesc: descriptor => {+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "compute": WebGPU.makeComputeState(descriptor + 16)+ };+ return desc;+ },+ makeRenderPipelineDesc: descriptor => {+ function makePrimitiveState(psPtr) {+ if (!psPtr) return undefined;+ return {+ "topology": WebGPU.PrimitiveTopology[HEAP32[(((psPtr) + (4)) >> 2)]],+ "stripIndexFormat": WebGPU.IndexFormat[HEAP32[(((psPtr) + (8)) >> 2)]],+ "frontFace": WebGPU.FrontFace[HEAP32[(((psPtr) + (12)) >> 2)]],+ "cullMode": WebGPU.CullMode[HEAP32[(((psPtr) + (16)) >> 2)]],+ "unclippedDepth": !!(HEAPU32[(((psPtr) + (20)) >> 2)])+ };+ }+ function makeBlendComponent(bdPtr) {+ if (!bdPtr) return undefined;+ return {+ "operation": WebGPU.BlendOperation[HEAP32[((bdPtr) >> 2)]],+ "srcFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (4)) >> 2)]],+ "dstFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (8)) >> 2)]]+ };+ }+ function makeBlendState(bsPtr) {+ if (!bsPtr) return undefined;+ return {+ "alpha": makeBlendComponent(bsPtr + 12),+ "color": makeBlendComponent(bsPtr + 0)+ };+ }+ function makeColorState(csPtr) {+ var format = WebGPU.TextureFormat[HEAP32[(((csPtr) + (4)) >> 2)]];+ return format ? {+ "format": format,+ "blend": makeBlendState(HEAPU32[(((csPtr) + (8)) >> 2)]),+ "writeMask": HEAPU32[(((csPtr) + (16)) >> 2)]+ } : undefined;+ }+ function makeColorStates(count, csArrayPtr) {+ var states = [];+ for (var i = 0; i < count; ++i) {+ states.push(makeColorState(csArrayPtr + 24 * i));+ }+ return states;+ }+ function makeStencilStateFace(ssfPtr) {+ return {+ "compare": WebGPU.CompareFunction[HEAP32[((ssfPtr) >> 2)]],+ "failOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (4)) >> 2)]],+ "depthFailOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (8)) >> 2)]],+ "passOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (12)) >> 2)]]+ };+ }+ function makeDepthStencilState(dssPtr) {+ if (!dssPtr) return undefined;+ return {+ "format": WebGPU.TextureFormat[HEAP32[(((dssPtr) + (4)) >> 2)]],+ "depthWriteEnabled": !!(HEAPU32[(((dssPtr) + (8)) >> 2)]),+ "depthCompare": WebGPU.CompareFunction[HEAP32[(((dssPtr) + (12)) >> 2)]],+ "stencilFront": makeStencilStateFace(dssPtr + 16),+ "stencilBack": makeStencilStateFace(dssPtr + 32),+ "stencilReadMask": HEAPU32[(((dssPtr) + (48)) >> 2)],+ "stencilWriteMask": HEAPU32[(((dssPtr) + (52)) >> 2)],+ "depthBias": HEAP32[(((dssPtr) + (56)) >> 2)],+ "depthBiasSlopeScale": HEAPF32[(((dssPtr) + (60)) >> 2)],+ "depthBiasClamp": HEAPF32[(((dssPtr) + (64)) >> 2)]+ };+ }+ function makeVertexAttribute(vaPtr) {+ return {+ "format": WebGPU.VertexFormat[HEAP32[(((vaPtr) + (4)) >> 2)]],+ "offset": readI53FromI64((vaPtr) + (8)),+ "shaderLocation": HEAPU32[(((vaPtr) + (16)) >> 2)]+ };+ }+ function makeVertexAttributes(count, vaArrayPtr) {+ var vas = [];+ for (var i = 0; i < count; ++i) {+ vas.push(makeVertexAttribute(vaArrayPtr + i * 24));+ }+ return vas;+ }+ function makeVertexBuffer(vbPtr) {+ if (!vbPtr) return undefined;+ var stepMode = WebGPU.VertexStepMode[HEAP32[(((vbPtr) + (4)) >> 2)]];+ var attributeCount = HEAPU32[(((vbPtr) + (16)) >> 2)];+ if (!stepMode && !attributeCount) {+ return null;+ }+ return {+ "arrayStride": readI53FromI64((vbPtr) + (8)),+ "stepMode": stepMode,+ "attributes": makeVertexAttributes(attributeCount, HEAPU32[(((vbPtr) + (20)) >> 2)])+ };+ }+ function makeVertexBuffers(count, vbArrayPtr) {+ if (!count) return undefined;+ var vbs = [];+ for (var i = 0; i < count; ++i) {+ vbs.push(makeVertexBuffer(vbArrayPtr + i * 24));+ }+ return vbs;+ }+ function makeVertexState(viPtr) {+ if (!viPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((viPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((viPtr) + (16)) >> 2)], HEAPU32[(((viPtr) + (20)) >> 2)]),+ "buffers": makeVertexBuffers(HEAPU32[(((viPtr) + (24)) >> 2)], HEAPU32[(((viPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(viPtr + 8)+ };+ return desc;+ }+ function makeMultisampleState(msPtr) {+ if (!msPtr) return undefined;+ return {+ "count": HEAPU32[(((msPtr) + (4)) >> 2)],+ "mask": HEAPU32[(((msPtr) + (8)) >> 2)],+ "alphaToCoverageEnabled": !!(HEAPU32[(((msPtr) + (12)) >> 2)])+ };+ }+ function makeFragmentState(fsPtr) {+ if (!fsPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((fsPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((fsPtr) + (16)) >> 2)], HEAPU32[(((fsPtr) + (20)) >> 2)]),+ "targets": makeColorStates(HEAPU32[(((fsPtr) + (24)) >> 2)], HEAPU32[(((fsPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(fsPtr + 8)+ };+ return desc;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "vertex": makeVertexState(descriptor + 16),+ "primitive": makePrimitiveState(descriptor + 48),+ "depthStencil": makeDepthStencilState(HEAPU32[(((descriptor) + (72)) >> 2)]),+ "multisample": makeMultisampleState(descriptor + 76),+ "fragment": makeFragmentState(HEAPU32[(((descriptor) + (92)) >> 2)])+ };+ return desc;+ },+ fillLimitStruct: (limits, limitsOutPtr) => {+ var nextInChainPtr = HEAPU32[((limitsOutPtr) >> 2)];+ function setLimitValueU32(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ HEAPU32[(((basePtr) + (limitOffset)) >> 2)] = limitValue;+ }+ function setLimitValueU64(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ // Limits are integer-valued JS `Number`s, so they fit in 'i53'.+ writeI53ToI64((basePtr) + (limitOffset), limitValue);+ }+ setLimitValueU32("maxTextureDimension1D", limitsOutPtr, 4);+ setLimitValueU32("maxTextureDimension2D", limitsOutPtr, 8);+ setLimitValueU32("maxTextureDimension3D", limitsOutPtr, 12);+ setLimitValueU32("maxTextureArrayLayers", limitsOutPtr, 16);+ setLimitValueU32("maxBindGroups", limitsOutPtr, 20);+ setLimitValueU32("maxBindGroupsPlusVertexBuffers", limitsOutPtr, 24);+ setLimitValueU32("maxBindingsPerBindGroup", limitsOutPtr, 28);+ setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout", limitsOutPtr, 32);+ setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout", limitsOutPtr, 36);+ setLimitValueU32("maxSampledTexturesPerShaderStage", limitsOutPtr, 40);+ setLimitValueU32("maxSamplersPerShaderStage", limitsOutPtr, 44);+ setLimitValueU32("maxStorageBuffersPerShaderStage", limitsOutPtr, 48);+ setLimitValueU32("maxStorageTexturesPerShaderStage", limitsOutPtr, 52);+ setLimitValueU32("maxUniformBuffersPerShaderStage", limitsOutPtr, 56);+ setLimitValueU32("minUniformBufferOffsetAlignment", limitsOutPtr, 80);+ setLimitValueU32("minStorageBufferOffsetAlignment", limitsOutPtr, 84);+ setLimitValueU64("maxUniformBufferBindingSize", limitsOutPtr, 64);+ setLimitValueU64("maxStorageBufferBindingSize", limitsOutPtr, 72);+ setLimitValueU32("maxVertexBuffers", limitsOutPtr, 88);+ setLimitValueU64("maxBufferSize", limitsOutPtr, 96);+ setLimitValueU32("maxVertexAttributes", limitsOutPtr, 104);+ setLimitValueU32("maxVertexBufferArrayStride", limitsOutPtr, 108);+ setLimitValueU32("maxInterStageShaderVariables", limitsOutPtr, 112);+ setLimitValueU32("maxColorAttachments", limitsOutPtr, 116);+ setLimitValueU32("maxColorAttachmentBytesPerSample", limitsOutPtr, 120);+ setLimitValueU32("maxComputeWorkgroupStorageSize", limitsOutPtr, 124);+ setLimitValueU32("maxComputeInvocationsPerWorkgroup", limitsOutPtr, 128);+ setLimitValueU32("maxComputeWorkgroupSizeX", limitsOutPtr, 132);+ setLimitValueU32("maxComputeWorkgroupSizeY", limitsOutPtr, 136);+ setLimitValueU32("maxComputeWorkgroupSizeZ", limitsOutPtr, 140);+ setLimitValueU32("maxComputeWorkgroupsPerDimension", limitsOutPtr, 144);+ // Note this limit is new and won't be present in all browsers for a while. Fall back to 0.+ setLimitValueU32("maxImmediateSize", limitsOutPtr, 148);+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var compatibilityModeLimitsPtr = nextInChainPtr;+ // Note these limits are new and won't be present in all browsers for a while. Fall back to exposing the PerShaderStage limit.+ setLimitValueU32("maxStorageBuffersInVertexStage", compatibilityModeLimitsPtr, 8, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageBuffersInFragmentStage", compatibilityModeLimitsPtr, 16, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageTexturesInVertexStage", compatibilityModeLimitsPtr, 12, limits.maxStorageTexturesPerShaderStage);+ setLimitValueU32("maxStorageTexturesInFragmentStage", compatibilityModeLimitsPtr, 20, limits.maxStorageTexturesPerShaderStage);+ }+ },+ fillAdapterInfoStruct: (info, infoStruct) => {+ // Populate subgroup limits.+ HEAPU32[(((infoStruct) + (52)) >> 2)] = info.subgroupMinSize;+ HEAPU32[(((infoStruct) + (56)) >> 2)] = info.subgroupMaxSize;+ // Append all the strings together to condense into a single malloc.+ var strs = info.vendor + info.architecture + info.device + info.description;+ var strPtr = stringToNewUTF8(strs);+ var vendorLen = lengthBytesUTF8(info.vendor);+ WebGPU.setStringView(infoStruct + 4, strPtr, vendorLen);+ strPtr += vendorLen;+ var architectureLen = lengthBytesUTF8(info.architecture);+ WebGPU.setStringView(infoStruct + 12, strPtr, architectureLen);+ strPtr += architectureLen;+ var deviceLen = lengthBytesUTF8(info.device);+ WebGPU.setStringView(infoStruct + 20, strPtr, deviceLen);+ strPtr += deviceLen;+ var descriptionLen = lengthBytesUTF8(info.description);+ WebGPU.setStringView(infoStruct + 28, strPtr, descriptionLen);+ strPtr += descriptionLen;+ HEAP32[(((infoStruct) + (36)) >> 2)] = 2;+ var adapterType = info.isFallbackAdapter ? 3 : 4;+ HEAP32[(((infoStruct) + (40)) >> 2)] = adapterType;+ HEAPU32[(((infoStruct) + (44)) >> 2)] = 0;+ HEAPU32[(((infoStruct) + (48)) >> 2)] = 0;+ },+ AddressMode: [ , "clamp-to-edge", "repeat", "mirror-repeat" ],+ BlendFactor: [ , "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha" ],+ BlendOperation: [ , "add", "subtract", "reverse-subtract", "min", "max" ],+ BufferBindingType: [ , , "uniform", "storage", "read-only-storage" ],+ BufferMapState: [ , "unmapped", "pending", "mapped" ],+ CompareFunction: [ , "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always" ],+ CompilationInfoRequestStatus: [ , "success", "callback-cancelled" ],+ ComponentSwizzle: [ , "0", "1", "r", "g", "b", "a" ],+ CompositeAlphaMode: [ , "opaque", "premultiplied", "unpremultiplied", "inherit" ],+ CullMode: [ , "none", "front", "back" ],+ ErrorFilter: [ , "validation", "out-of-memory", "internal" ],+ FeatureLevel: [ , "compatibility", "core" ],+ FeatureName: {+ 1: "core-features-and-limits",+ 2: "depth-clip-control",+ 3: "depth32float-stencil8",+ 4: "texture-compression-bc",+ 5: "texture-compression-bc-sliced-3d",+ 6: "texture-compression-etc2",+ 7: "texture-compression-astc",+ 8: "texture-compression-astc-sliced-3d",+ 9: "timestamp-query",+ 10: "indirect-first-instance",+ 11: "shader-f16",+ 12: "rg11b10ufloat-renderable",+ 13: "bgra8unorm-storage",+ 14: "float32-filterable",+ 15: "float32-blendable",+ 16: "clip-distances",+ 17: "dual-source-blending",+ 18: "subgroups",+ 19: "texture-formats-tier1",+ 20: "texture-formats-tier2",+ 21: "primitive-index",+ 22: "texture-component-swizzle",+ 327692: "chromium-experimental-unorm16-texture-formats",+ 327729: "chromium-experimental-multi-draw-indirect"+ },+ FilterMode: [ , "nearest", "linear" ],+ FrontFace: [ , "ccw", "cw" ],+ IndexFormat: [ , "uint16", "uint32" ],+ InstanceFeatureName: [ , "timed-wait-any", "shader-source-spirv", "multiple-devices-per-adapter" ],+ LoadOp: [ , "load", "clear" ],+ MipmapFilterMode: [ , "nearest", "linear" ],+ OptionalBool: [ "false", "true" ],+ PowerPreference: [ , "low-power", "high-performance" ],+ PredefinedColorSpace: [ , "srgb", "display-p3" ],+ PrimitiveTopology: [ , "point-list", "line-list", "line-strip", "triangle-list", "triangle-strip" ],+ QueryType: [ , "occlusion", "timestamp" ],+ SamplerBindingType: [ , , "filtering", "non-filtering", "comparison" ],+ Status: [ , "success", "error" ],+ StencilOperation: [ , "keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap" ],+ StorageTextureAccess: [ , , "write-only", "read-only", "read-write" ],+ StoreOp: [ , "store", "discard" ],+ SurfaceGetCurrentTextureStatus: [ , "success-optimal", "success-suboptimal", "timeout", "outdated", "lost", "error" ],+ TextureAspect: [ , "all", "stencil-only", "depth-only" ],+ TextureDimension: [ , "1d", "2d", "3d" ],+ TextureFormat: [ , "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb" ],+ TextureSampleType: [ , , "float", "unfilterable-float", "depth", "sint", "uint" ],+ TextureViewDimension: [ , "1d", "2d", "2d-array", "cube", "cube-array", "3d" ],+ ToneMappingMode: [ , "standard", "extended" ],+ VertexFormat: [ , "uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra" ],+ VertexStepMode: [ , "vertex", "instance" ],+ WGSLLanguageFeatureName: [ , "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", "uniform_buffer_standard_layout", "subgroup_id", "texture_and_sampler_let", "subgroup_uniformity", "texture_formats_tier1", "linear_indexing" ]+};++var _emscripten_webgpu_get_device = () => {+ if (WebGPU.preinitializedDeviceId === undefined) {+ WebGPU.preinitializedDeviceId = WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]);+ // Some users depend on this keeping the device alive, so we add an+ // additional reference when we first initialize it.+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ }+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ return WebGPU.preinitializedDeviceId;+};++var _emwgpuBufferDestroy = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (onUnmap) {+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ }+ buffer.destroy();+};++var _emwgpuBufferGetMappedRange = (bufferPtr, offset, size) => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ if (size == -1) size = undefined;+ var mapped;+ try {+ mapped = buffer.getMappedRange(offset, size);+ } catch (ex) {+ return 0;+ }+ var data = _memalign(16, mapped.byteLength);+ HEAPU8.fill(0, data, mapped.byteLength);+ WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(() => {+ new Uint8Array(mapped).set(HEAPU8.subarray(data, data + mapped.byteLength));+ _free(data);+ });+ return data;+};++var _emwgpuBufferUnmap = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (!onUnmap) {+ // Already unmapped+ return;+ }+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ buffer.unmap();+};++var _emwgpuDelete = ptr => {+ delete WebGPU.Internals.jsObjects[ptr];+};++var _emwgpuDeviceCreateBuffer = (devicePtr, descriptor, bufferPtr) => {+ var mappedAtCreation = !!(HEAPU32[(((descriptor) + (32)) >> 2)]);+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "size": readI53FromI64((descriptor) + (24)),+ "mappedAtCreation": mappedAtCreation+ };+ var device = WebGPU.getJsObject(devicePtr);+ var buffer;+ try {+ buffer = device.createBuffer(desc);+ } catch (ex) {+ // The only exception should be RangeError if mapping at creation ran out of memory.+ return false;+ }+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ if (mappedAtCreation) {+ WebGPU.Internals.bufferOnUnmaps[bufferPtr] = [];+ }+ return true;+};++var _emwgpuDeviceCreateComputePipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createComputePipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createComputePipelineAsync(desc).then(pipeline => {+ // createComputePipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateComputePipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createComputePipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateComputePipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateRenderPipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createRenderPipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createRenderPipelineAsync(desc).then(pipeline => {+ // createRenderPipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateRenderPipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createRenderPipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateRenderPipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateShaderModule = (devicePtr, descriptor, shaderModulePtr) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "code": ""+ };+ switch (sType) {+ case 2:+ {+ desc["code"] = WebGPU.makeStringFromStringView(nextInChainPtr + 8);+ break;+ }+ }+ var device = WebGPU.getJsObject(devicePtr);+ WebGPU.Internals.jsObjectInsert(shaderModulePtr, device.createShaderModule(desc));+};++var _emwgpuDeviceDestroy = devicePtr => {+ const device = WebGPU.getJsObject(devicePtr);+ // Remove the onuncapturederror handler which holds a pointer to the WGPUDevice.+ device.onuncapturederror = null;+ device.destroy();+};++var _emwgpuWaitAny = (futurePtr, futureCount, timeoutMSPtr) => {+ abort("TODO: Implement asyncify-free WaitAny for timeout=0");+};++var ENV = {};++var getExecutableName = () => thisProgram || "./this.program";++var getEnvStrings = () => {+ if (!getEnvStrings.strings) {+ // Default values.+ // Browser language detection #8751+ var lang = (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8";+ var env = {+ "USER": "web_user",+ "LOGNAME": "web_user",+ "PATH": "/",+ "PWD": "/",+ "HOME": "/home/web_user",+ "LANG": lang,+ "_": getExecutableName()+ };+ // Apply the user-provided values, if any.+ for (var x in ENV) {+ // x is a key in ENV; if ENV[x] is undefined, that means it was+ // explicitly set to be so. We allow user code to do that to+ // force variables with default values to remain unset.+ if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x];+ }+ var strings = [];+ for (var x in env) {+ strings.push(`${x}=${env[x]}`);+ }+ getEnvStrings.strings = strings;+ }+ return getEnvStrings.strings;+};++var _environ_get = (__environ, environ_buf) => {+ var bufSize = 0;+ var envp = 0;+ for (var string of getEnvStrings()) {+ var ptr = environ_buf + bufSize;+ HEAPU32[(((__environ) + (envp)) >> 2)] = ptr;+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;+ envp += 4;+ }+ return 0;+};++var _environ_sizes_get = (penviron_count, penviron_buf_size) => {+ var strings = getEnvStrings();+ HEAPU32[((penviron_count) >> 2)] = strings.length;+ var bufSize = 0;+ for (var string of strings) {+ bufSize += lengthBytesUTF8(string) + 1;+ }+ HEAPU32[((penviron_buf_size) >> 2)] = bufSize;+ return 0;+};++function _fd_close(fd) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.close(stream);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.read(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) break;+ // nothing more to read+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_read(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doReadv(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ if (isNaN(offset)) return 61;+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.llseek(stream, offset, whence);+ (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]);+ if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;+ // reset readdir state+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.write(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) {+ // No more space to write.+ break;+ }+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_write(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doWritev(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++var _emscripten_glActiveTexture = x0 => GLctx.activeTexture(x0);++var _glActiveTexture = _emscripten_glActiveTexture;++var _emscripten_glAttachShader = (program, shader) => {+ GLctx.attachShader(GL.programs[program], GL.shaders[shader]);+};++var _glAttachShader = _emscripten_glAttachShader;++var _emscripten_glBindAttribLocation = (program, index, name) => {+ GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));+};++var _glBindAttribLocation = _emscripten_glBindAttribLocation;++var _emscripten_glBindBuffer = (target, buffer) => {+ // Calling glBindBuffer with an unknown buffer will implicitly create a+ // new one. Here we bypass `GL.counter` and directly using the ID passed+ // in.+ if (buffer && !GL.buffers[buffer]) {+ var b = GLctx.createBuffer();+ b.name = buffer;+ GL.buffers[buffer] = b;+ }+ if (target == 34962) {+ GLctx.currentArrayBufferBinding = buffer;+ } else if (target == 34963) {+ GLctx.currentElementArrayBufferBinding = buffer;+ }+ if (target == 35051) {+ // In WebGL 2 glReadPixels entry point, we need to use a different WebGL 2+ // API function call when a buffer is bound to+ // GL_PIXEL_PACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelPackBufferBinding = buffer;+ } else if (target == 35052) {+ // In WebGL 2 gl(Compressed)Tex(Sub)Image[23]D entry points, we need to+ // use a different WebGL 2 API function call when a buffer is bound to+ // GL_PIXEL_UNPACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelUnpackBufferBinding = buffer;+ }+ GLctx.bindBuffer(target, GL.buffers[buffer]);+};++var _glBindBuffer = _emscripten_glBindBuffer;++var _emscripten_glBindBufferBase = (target, index, buffer) => {+ GLctx.bindBufferBase(target, index, GL.buffers[buffer]);+};++var _glBindBufferBase = _emscripten_glBindBufferBase;++var _emscripten_glBindFramebuffer = (target, framebuffer) => {+ GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);+};++var _glBindFramebuffer = _emscripten_glBindFramebuffer;++var _emscripten_glBindTexture = (target, texture) => {+ GLctx.bindTexture(target, GL.textures[texture]);+};++var _glBindTexture = _emscripten_glBindTexture;++var _emscripten_glBindVertexArray = vao => {+ GLctx.bindVertexArray(GL.vaos[vao]);+ var ibo = GLctx.getParameter(34965);+ GLctx.currentElementArrayBufferBinding = ibo ? (ibo.name | 0) : 0;+};++var _glBindVertexArray = _emscripten_glBindVertexArray;++var _emscripten_glBlendEquation = x0 => GLctx.blendEquation(x0);++var _glBlendEquation = _emscripten_glBlendEquation;++var _emscripten_glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1);++var _glBlendFunc = _emscripten_glBlendFunc;++var _emscripten_glBufferData = (target, size, data, usage) => {+ if (GL.currentContext.version >= 2) {+ // If size is zero, WebGL would interpret uploading the whole input+ // arraybuffer (starting from given offset), which would not make sense in+ // WebAssembly, so avoid uploading if size is zero. However we must still+ // call bufferData to establish a backing storage of zero bytes.+ if (data && size) {+ GLctx.bufferData(target, HEAPU8, usage, data, size);+ } else {+ GLctx.bufferData(target, size, usage);+ }+ return;+ }+ // N.b. here first form specifies a heap subarray, second form an integer+ // size, so the ?: code here is polymorphic. It is advised to avoid+ // randomly mixing both uses in calling code, to avoid any potential JS+ // engine JIT issues.+ GLctx.bufferData(target, data ? HEAPU8.subarray(data, data + size) : size, usage);+};++var _glBufferData = _emscripten_glBufferData;++var _emscripten_glClear = x0 => GLctx.clear(x0);++var _glClear = _emscripten_glClear;++var _emscripten_glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3);++var _glClearColor = _emscripten_glClearColor;++var convertI32PairToI53 = (lo, hi) => (lo >>> 0) + hi * 4294967296;++var _emscripten_glClientWaitSync = (sync, flags, timeout_low, timeout_high) => {+ // WebGL2 vs GLES3 differences: in GLES3, the timeout parameter is a uint64, where 0xFFFFFFFFFFFFFFFFULL means GL_TIMEOUT_IGNORED.+ // In JS, there's no 64-bit value types, so instead timeout is taken to be signed, and GL_TIMEOUT_IGNORED is given value -1.+ // Inherently the value accepted in the timeout is lossy, and can't take in arbitrary u64 bit pattern (but most likely doesn't matter)+ // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.15+ var timeout = convertI32PairToI53(timeout_low, timeout_high);+ return GLctx.clientWaitSync(GL.syncs[sync], flags, timeout);+};++var _glClientWaitSync = _emscripten_glClientWaitSync;++var _emscripten_glColorMask = (red, green, blue, alpha) => {+ GLctx.colorMask(!!red, !!green, !!blue, !!alpha);+};++var _glColorMask = _emscripten_glColorMask;++var _emscripten_glCompileShader = shader => {+ GLctx.compileShader(GL.shaders[shader]);+};++var _glCompileShader = _emscripten_glCompileShader;++var _emscripten_glCreateProgram = () => {+ var id = GL.getNewId(GL.programs);+ var program = GLctx.createProgram();+ // Store additional information needed for each shader program:+ program.name = id;+ // Lazy cache results of+ // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH)+ program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0;+ program.uniformIdCounter = 1;+ GL.programs[id] = program;+ return id;+};++var _glCreateProgram = _emscripten_glCreateProgram;++var _emscripten_glCreateShader = shaderType => {+ var id = GL.getNewId(GL.shaders);+ GL.shaders[id] = GLctx.createShader(shaderType);+ return id;+};++var _glCreateShader = _emscripten_glCreateShader;++var _emscripten_glDeleteBuffers = (n, buffers) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((buffers) + (i * 4)) >> 2)];+ var buffer = GL.buffers[id];+ // From spec: "glDeleteBuffers silently ignores 0's and names that do not+ // correspond to existing buffer objects."+ if (!buffer) continue;+ GLctx.deleteBuffer(buffer);+ buffer.name = 0;+ GL.buffers[id] = null;+ if (id == GLctx.currentArrayBufferBinding) GLctx.currentArrayBufferBinding = 0;+ if (id == GLctx.currentElementArrayBufferBinding) GLctx.currentElementArrayBufferBinding = 0;+ if (id == GLctx.currentPixelPackBufferBinding) GLctx.currentPixelPackBufferBinding = 0;+ if (id == GLctx.currentPixelUnpackBufferBinding) GLctx.currentPixelUnpackBufferBinding = 0;+ }+};++var _glDeleteBuffers = _emscripten_glDeleteBuffers;++var _emscripten_glDeleteFramebuffers = (n, framebuffers) => {+ for (var i = 0; i < n; ++i) {+ var id = HEAP32[(((framebuffers) + (i * 4)) >> 2)];+ var framebuffer = GL.framebuffers[id];+ if (!framebuffer) continue;+ // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".+ GLctx.deleteFramebuffer(framebuffer);+ framebuffer.name = 0;+ GL.framebuffers[id] = null;+ }+};++var _glDeleteFramebuffers = _emscripten_glDeleteFramebuffers;++var _emscripten_glDeleteProgram = id => {+ if (!id) return;+ var program = GL.programs[id];+ if (!program) {+ // glDeleteProgram actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteProgram(program);+ program.name = 0;+ GL.programs[id] = null;+};++var _glDeleteProgram = _emscripten_glDeleteProgram;++var _emscripten_glDeleteShader = id => {+ if (!id) return;+ var shader = GL.shaders[id];+ if (!shader) {+ // glDeleteShader actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteShader(shader);+ GL.shaders[id] = null;+};++var _glDeleteShader = _emscripten_glDeleteShader;++var _emscripten_glDeleteSync = id => {+ if (!id) return;+ var sync = GL.syncs[id];+ if (!sync) {+ // glDeleteSync signals an error when deleting a nonexisting object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteSync(sync);+ sync.name = 0;+ GL.syncs[id] = null;+};++var _glDeleteSync = _emscripten_glDeleteSync;++var _emscripten_glDeleteTextures = (n, textures) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((textures) + (i * 4)) >> 2)];+ var texture = GL.textures[id];+ // GL spec: "glDeleteTextures silently ignores 0s and names that do not+ // correspond to existing textures".+ if (!texture) continue;+ GLctx.deleteTexture(texture);+ texture.name = 0;+ GL.textures[id] = null;+ }+};++var _glDeleteTextures = _emscripten_glDeleteTextures;++var _emscripten_glDeleteVertexArrays = (n, vaos) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((vaos) + (i * 4)) >> 2)];+ GLctx.deleteVertexArray(GL.vaos[id]);+ GL.vaos[id] = null;+ }+};++var _glDeleteVertexArrays = _emscripten_glDeleteVertexArrays;++var _emscripten_glDetachShader = (program, shader) => {+ GLctx.detachShader(GL.programs[program], GL.shaders[shader]);+};++var _glDetachShader = _emscripten_glDetachShader;++var _emscripten_glDisable = x0 => GLctx.disable(x0);++var _glDisable = _emscripten_glDisable;++var _emscripten_glDisableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = false;+ GLctx.disableVertexAttribArray(index);+};++var _glDisableVertexAttribArray = _emscripten_glDisableVertexAttribArray;++var _emscripten_glDrawArrays = (mode, first, count) => {+ // bind any client-side buffers+ GL.preDrawHandleClientVertexAttribBindings(first + count);+ GLctx.drawArrays(mode, first, count);+ GL.postDrawHandleClientVertexAttribBindings();+};++var _glDrawArrays = _emscripten_glDrawArrays;++var tempFixedLengthArray = [];++var _emscripten_glDrawBuffers = (n, bufs) => {+ var bufArray = tempFixedLengthArray[n];+ for (var i = 0; i < n; i++) {+ bufArray[i] = HEAP32[(((bufs) + (i * 4)) >> 2)];+ }+ GLctx.drawBuffers(bufArray);+};++var _glDrawBuffers = _emscripten_glDrawBuffers;++var _emscripten_glEnable = x0 => GLctx.enable(x0);++var _glEnable = _emscripten_glEnable;++var _emscripten_glEnableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = true;+ GLctx.enableVertexAttribArray(index);+};++var _glEnableVertexAttribArray = _emscripten_glEnableVertexAttribArray;++var _emscripten_glFenceSync = (condition, flags) => {+ var sync = GLctx.fenceSync(condition, flags);+ if (sync) {+ var id = GL.getNewId(GL.syncs);+ sync.name = id;+ GL.syncs[id] = sync;+ return id;+ }+ return 0;+};++var _glFenceSync = _emscripten_glFenceSync;++var _emscripten_glFinish = () => GLctx.finish();++var _glFinish = _emscripten_glFinish;++var _emscripten_glFlush = () => GLctx.flush();++var _glFlush = _emscripten_glFlush;++var _emscripten_glFramebufferTexture2D = (target, attachment, textarget, texture, level) => {+ GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level);+};++var _glFramebufferTexture2D = _emscripten_glFramebufferTexture2D;++var _emscripten_glFramebufferTextureLayer = (target, attachment, texture, level, layer) => {+ GLctx.framebufferTextureLayer(target, attachment, GL.textures[texture], level, layer);+};++var _glFramebufferTextureLayer = _emscripten_glFramebufferTextureLayer;++var _emscripten_glGenBuffers = (n, buffers) => {+ GL.genObject(n, buffers, "createBuffer", GL.buffers);+};++var _glGenBuffers = _emscripten_glGenBuffers;++var _emscripten_glGenFramebuffers = (n, ids) => {+ GL.genObject(n, ids, "createFramebuffer", GL.framebuffers);+};++var _glGenFramebuffers = _emscripten_glGenFramebuffers;++var _emscripten_glGenTextures = (n, textures) => {+ GL.genObject(n, textures, "createTexture", GL.textures);+};++var _glGenTextures = _emscripten_glGenTextures;++var _emscripten_glGenVertexArrays = (n, arrays) => {+ GL.genObject(n, arrays, "createVertexArray", GL.vaos);+};++var _glGenVertexArrays = _emscripten_glGenVertexArrays;++var _emscripten_glGetAttribLocation = (program, name) => GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));++var _glGetAttribLocation = _emscripten_glGetAttribLocation;++var _emscripten_glGetError = () => {+ var error = GLctx.getError() || GL.lastError;+ GL.lastError = 0;+ return error;+};++var _glGetError = _emscripten_glGetError;++var webglGetExtensions = () => {+ var exts = getEmscriptenSupportedExtensions(GLctx);+ exts = exts.concat(exts.map(e => "GL_" + e));+ return exts;+};++var emscriptenWebGLGet = (name_, p, type) => {+ // Guard against user passing a null pointer.+ // Note that GLES2 spec does not say anything about how passing a null+ // pointer should be treated. Testing on desktop core GL 3, the application+ // crashes on glGetIntegerv to a null pointer, but better to report an error+ // instead of doing anything random.+ if (!p) {+ GL.recordError(1281);+ return;+ }+ var ret = undefined;+ switch (name_) {+ // Handle a few trivial GLES values+ case 36346:+ // GL_SHADER_COMPILER+ ret = 1;+ break;++ case 36344:+ // GL_SHADER_BINARY_FORMATS+ if (type != 0 && type != 1) {+ GL.recordError(1280);+ }+ // Do not write anything to the out pointer, since no binary formats are+ // supported.+ return;++ case 34814:+ // GL_NUM_PROGRAM_BINARY_FORMATS+ case 36345:+ // GL_NUM_SHADER_BINARY_FORMATS+ ret = 0;+ break;++ case 34466:+ // GL_NUM_COMPRESSED_TEXTURE_FORMATS+ // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete+ // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be+ // queried for length), so implement it ourselves to allow C++ GLES2+ // code to get the length.+ var formats = GLctx.getParameter(34467);+ ret = formats ? formats.length : 0;+ break;++ case 33309:+ // GL_NUM_EXTENSIONS+ if (GL.currentContext.version < 2) {+ // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context+ GL.recordError(1282);+ return;+ }+ ret = webglGetExtensions().length;+ break;++ case 33307:+ // GL_MAJOR_VERSION+ case 33308:+ // GL_MINOR_VERSION+ if (GL.currentContext.version < 2) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ ret = name_ == 33307 ? 3 : 0;+ // return version 3.0+ break;+ }+ if (ret === undefined) {+ var result = GLctx.getParameter(name_);+ switch (typeof result) {+ case "number":+ ret = result;+ break;++ case "boolean":+ ret = result ? 1 : 0;+ break;++ case "string":+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;++ case "object":+ if (result === null) {+ // null is a valid result for some (e.g., which buffer is bound -+ // perhaps nothing is bound), but otherwise can mean an invalid+ // name_, which we need to report as an error+ switch (name_) {+ case 34964:+ // ARRAY_BUFFER_BINDING+ case 35725:+ // CURRENT_PROGRAM+ case 34965:+ // ELEMENT_ARRAY_BUFFER_BINDING+ case 36006:+ // FRAMEBUFFER_BINDING or DRAW_FRAMEBUFFER_BINDING+ case 36007:+ // RENDERBUFFER_BINDING+ case 32873:+ // TEXTURE_BINDING_2D+ case 34229:+ // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES+ case 36662:+ // COPY_READ_BUFFER_BINDING or COPY_READ_BUFFER+ case 36663:+ // COPY_WRITE_BUFFER_BINDING or COPY_WRITE_BUFFER+ case 35053:+ // PIXEL_PACK_BUFFER_BINDING+ case 35055:+ // PIXEL_UNPACK_BUFFER_BINDING+ case 36010:+ // READ_FRAMEBUFFER_BINDING+ case 35097:+ // SAMPLER_BINDING+ case 35869:+ // TEXTURE_BINDING_2D_ARRAY+ case 32874:+ // TEXTURE_BINDING_3D+ case 36389:+ // TRANSFORM_FEEDBACK_BINDING+ case 35983:+ // TRANSFORM_FEEDBACK_BUFFER_BINDING+ case 35368:+ // UNIFORM_BUFFER_BINDING+ case 34068:+ {+ // TEXTURE_BINDING_CUBE_MAP+ ret = 0;+ break;+ }++ default:+ {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ }+ } else if (result instanceof Float32Array || result instanceof Uint32Array || result instanceof Int32Array || result instanceof Array) {+ for (var i = 0; i < result.length; ++i) {+ switch (type) {+ case 0:+ HEAP32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 2:+ HEAPF32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 4:+ HEAP8[(p) + (i)] = result[i] ? 1 : 0;+ break;+ }+ }+ return;+ } else {+ try {+ ret = result.name | 0;+ } catch (e) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);+ return;+ }+ }+ break;++ default:+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof (result)}!`);+ return;+ }+ }+ switch (type) {+ case 1:+ writeI53ToI64(p, ret);+ break;++ case 0:+ HEAP32[((p) >> 2)] = ret;+ break;++ case 2:+ HEAPF32[((p) >> 2)] = ret;+ break;++ case 4:+ HEAP8[p] = ret ? 1 : 0;+ break;+ }+};++var _emscripten_glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2);++var _glGetFloatv = _emscripten_glGetFloatv;++var _emscripten_glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0);++var _glGetIntegerv = _emscripten_glGetIntegerv;++var _emscripten_glGetProgramiv = (program, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (program >= GL.counter) {+ GL.recordError(1281);+ return;+ }+ program = GL.programs[program];+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getProgramInfoLog(program);+ if (log === null) log = "(unknown error)";+ HEAP32[((p) >> 2)] = log.length + 1;+ } else if (pname == 35719) {+ if (!program.maxUniformLength) {+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (var i = 0; i < numActiveUniforms; ++i) {+ program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformLength;+ } else if (pname == 35722) {+ if (!program.maxAttributeLength) {+ var numActiveAttributes = GLctx.getProgramParameter(program, 35721);+ for (var i = 0; i < numActiveAttributes; ++i) {+ program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxAttributeLength;+ } else if (pname == 35381) {+ if (!program.maxUniformBlockNameLength) {+ var numActiveUniformBlocks = GLctx.getProgramParameter(program, 35382);+ for (var i = 0; i < numActiveUniformBlocks; ++i) {+ program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformBlockNameLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getProgramParameter(program, pname);+ }+};++var _glGetProgramiv = _emscripten_glGetProgramiv;++var _emscripten_glGetShaderInfoLog = (shader, maxLength, length, infoLog) => {+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;+ if (length) HEAP32[((length) >> 2)] = numBytesWrittenExclNull;+};++var _glGetShaderInfoLog = _emscripten_glGetShaderInfoLog;++var _emscripten_glGetShaderiv = (shader, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ // The GLES2 specification says that if the shader has an empty info log,+ // a value of 0 is returned. Otherwise the log has a null char appended.+ // (An empty string is falsey, so we can just check that instead of+ // looking at log.length.)+ var logLength = log ? log.length + 1 : 0;+ HEAP32[((p) >> 2)] = logLength;+ } else if (pname == 35720) {+ // GL_SHADER_SOURCE_LENGTH+ var source = GLctx.getShaderSource(GL.shaders[shader]);+ // source may be a null, or the empty string, both of which are falsey+ // values that we report a 0 length for.+ var sourceLength = source ? source.length + 1 : 0;+ HEAP32[((p) >> 2)] = sourceLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getShaderParameter(GL.shaders[shader], pname);+ }+};++var _glGetShaderiv = _emscripten_glGetShaderiv;++var _emscripten_glGetString = name_ => {+ var ret = GL.stringCache[name_];+ if (!ret) {+ switch (name_) {+ case 7939:+ ret = stringToNewUTF8(webglGetExtensions().join(" "));+ break;++ case 7936:+ case 7937:+ case 37445:+ case 37446:+ var s = GLctx.getParameter(name_);+ if (!s) {+ GL.recordError(1280);+ }+ ret = s ? stringToNewUTF8(s) : 0;+ break;++ case 7938:+ var webGLVersion = GLctx.getParameter(7938);+ // return GLES version string corresponding to the version of the WebGL context+ var glVersion = `OpenGL ES 2.0 (${webGLVersion})`;+ if (GL.currentContext.version >= 2) glVersion = `OpenGL ES 3.0 (${webGLVersion})`;+ ret = stringToNewUTF8(glVersion);+ break;++ case 35724:+ var glslVersion = GLctx.getParameter(35724);+ // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'+ var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;+ var ver_num = glslVersion.match(ver_re);+ if (ver_num !== null) {+ if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + "0";+ // ensure minor version has 2 digits+ glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`;+ }+ ret = stringToNewUTF8(glslVersion);+ break;++ default:+ GL.recordError(1280);+ }+ GL.stringCache[name_] = ret;+ }+ return ret;+};++var _glGetString = _emscripten_glGetString;++var _emscripten_glGetUniformBlockIndex = (program, uniformBlockName) => GLctx.getUniformBlockIndex(GL.programs[program], UTF8ToString(uniformBlockName));++var _glGetUniformBlockIndex = _emscripten_glGetUniformBlockIndex;++/** @suppress {checkTypes} */ var jstoi_q = str => parseInt(str);++/** @noinline */ var webglGetLeftBracePos = name => name.slice(-1) == "]" && name.lastIndexOf("[");++var webglPrepareUniformLocationsBeforeFirstUse = program => {+ var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation+ uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint]+ i, j;+ // On the first time invocation of glGetUniformLocation on this shader program:+ // initialize cache data structures and discover which uniforms are arrays.+ if (!uniformLocsById) {+ // maps GLint integer locations to WebGLUniformLocations+ program.uniformLocsById = uniformLocsById = {};+ // maps integer locations back to uniform name strings, so that we can lazily fetch uniform array locations+ program.uniformArrayNamesById = {};+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (i = 0; i < numActiveUniforms; ++i) {+ var u = GLctx.getActiveUniform(program, i);+ var nm = u.name;+ var sz = u.size;+ var lb = webglGetLeftBracePos(nm);+ var arrayName = lb > 0 ? nm.slice(0, lb) : nm;+ // Assign a new location.+ var id = program.uniformIdCounter;+ program.uniformIdCounter += sz;+ // Eagerly get the location of the uniformArray[0] base element.+ // The remaining indices >0 will be left for lazy evaluation to+ // improve performance. Those may never be needed to fetch, if the+ // application fills arrays always in full starting from the first+ // element of the array.+ uniformSizeAndIdsByName[arrayName] = [ sz, id ];+ // Store placeholder integers in place that highlight that these+ // >0 index locations are array indices pending population.+ for (j = 0; j < sz; ++j) {+ uniformLocsById[id] = j;+ program.uniformArrayNamesById[id++] = arrayName;+ }+ }+ }+};++var _emscripten_glGetUniformLocation = (program, name) => {+ name = UTF8ToString(name);+ if (program = GL.programs[program]) {+ webglPrepareUniformLocationsBeforeFirstUse(program);+ var uniformLocsById = program.uniformLocsById;+ // Maps GLuint -> WebGLUniformLocation+ var arrayIndex = 0;+ var uniformBaseName = name;+ // Invariant: when populating integer IDs for uniform locations, we must+ // maintain the precondition that arrays reside in contiguous addresses,+ // i.e. for a 'vec4 colors[10];', colors[4] must be at location+ // colors[0]+4. However, user might call glGetUniformLocation(program,+ // "colors") for an array, so we cannot discover based on the user input+ // arguments whether the uniform we are dealing with is an array. The only+ // way to discover which uniforms are arrays is to enumerate over all the+ // active uniforms in the program.+ var leftBrace = webglGetLeftBracePos(name);+ // If user passed an array accessor "[index]", parse the array index off the accessor.+ if (leftBrace > 0) {+ arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0;+ // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds.+ uniformBaseName = name.slice(0, leftBrace);+ }+ // Have we cached the location of this uniform before?+ // A pair [array length, GLint of the uniform location]+ var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName];+ // If a uniform with this name exists, and if its index is within the+ // array limits (if it's even an array), query the WebGLlocation, or+ // return an existing cached location.+ if (sizeAndId && arrayIndex < sizeAndId[0]) {+ arrayIndex += sizeAndId[1];+ // Add the base location of the uniform to the array index offset.+ if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) {+ return arrayIndex;+ }+ }+ } else {+ // N.b. we are currently unable to distinguish between GL program IDs that+ // never existed vs GL program IDs that have been deleted, so report+ // GL_INVALID_VALUE in both cases.+ GL.recordError(1281);+ }+ return -1;+};++var _glGetUniformLocation = _emscripten_glGetUniformLocation;++var _emscripten_glLineWidth = x0 => GLctx.lineWidth(x0);++var _glLineWidth = _emscripten_glLineWidth;++var _emscripten_glLinkProgram = program => {+ program = GL.programs[program];+ GLctx.linkProgram(program);+ // Invalidate earlier computed uniform->ID mappings, those have now become stale+ program.uniformLocsById = 0;+ // Mark as null-like so that glGetUniformLocation() knows to populate this again.+ program.uniformSizeAndIdsByName = {};+};++var _glLinkProgram = _emscripten_glLinkProgram;++var _emscripten_glPixelStorei = (pname, param) => {+ if (pname == 3317) {+ GL.unpackAlignment = param;+ } else if (pname == 3314) {+ GL.unpackRowLength = param;+ }+ GLctx.pixelStorei(pname, param);+};++var _glPixelStorei = _emscripten_glPixelStorei;++var computeUnpackAlignedImageSize = (width, height, sizePerPixel) => {+ function roundedToNextMultipleOf(x, y) {+ return (x + y - 1) & -y;+ }+ var plainRowSize = (GL.unpackRowLength || width) * sizePerPixel;+ var alignedRowSize = roundedToNextMultipleOf(plainRowSize, GL.unpackAlignment);+ return height * alignedRowSize;+};++var colorChannelsInGlTextureFormat = format => {+ // Micro-optimizations for size: map format to size by subtracting smallest+ // enum value (0x1902) from all values first. Also omit the most common+ // size value (1) from the list, which is assumed by formats not on the+ // list.+ var colorChannels = {+ // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,+ // 0x1906 /* GL_ALPHA */ - 0x1902: 1,+ 5: 3,+ 6: 4,+ // 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,+ 8: 2,+ 29502: 3,+ 29504: 4,+ // 0x1903 /* GL_RED */ - 0x1902: 1,+ 26917: 2,+ 26918: 2,+ // 0x8D94 /* GL_RED_INTEGER */ - 0x1902: 1,+ 29846: 3,+ 29847: 4+ };+ return colorChannels[format - 6402] || 1;+};++var heapObjectForWebGLType = type => {+ // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare+ // smaller values for the heap, for shorter generated code size.+ // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.+ // (since most types are HEAPU16)+ type -= 5120;+ if (type == 0) return HEAP8;+ if (type == 1) return HEAPU8;+ if (type == 2) return HEAP16;+ if (type == 4) return HEAP32;+ if (type == 6) return HEAPF32;+ if (type == 5 || type == 28922 || type == 28520 || type == 30779 || type == 30782) return HEAPU32;+ return HEAPU16;+};++var toTypedArrayIndex = (pointer, heap) => pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT));++var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels, internalFormat) => {+ var heap = heapObjectForWebGLType(type);+ var sizePerPixel = colorChannelsInGlTextureFormat(format) * heap.BYTES_PER_ELEMENT;+ var bytes = computeUnpackAlignedImageSize(width, height, sizePerPixel);+ return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap));+};++var _emscripten_glReadPixels = (x, y, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelPackBufferBinding) {+ GLctx.readPixels(x, y, width, height, format, type, pixels);+ return;+ }+ var heap = heapObjectForWebGLType(type);+ var target = toTypedArrayIndex(pixels, heap);+ GLctx.readPixels(x, y, width, height, format, type, heap, target);+ return;+ }+ var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format);+ if (!pixelData) {+ GL.recordError(1280);+ return;+ }+ GLctx.readPixels(x, y, width, height, format, type, pixelData);+};++var _glReadPixels = _emscripten_glReadPixels;++var _emscripten_glShaderSource = (shader, count, string, length) => {+ var source = GL.getSource(shader, count, string, length);+ GLctx.shaderSource(GL.shaders[shader], source);+};++var _glShaderSource = _emscripten_glShaderSource;++var _emscripten_glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ var index = toTypedArrayIndex(pixels, heap);+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, heap, index);+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null;+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData);+};++var _glTexImage2D = _emscripten_glTexImage2D;++var _emscripten_glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2);++var _glTexParameterf = _emscripten_glTexParameterf;++var _emscripten_glTexParameterfv = (target, pname, params) => {+ var param = HEAPF32[((params) >> 2)];+ GLctx.texParameterf(target, pname, param);+};++var _glTexParameterfv = _emscripten_glTexParameterfv;++var _emscripten_glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2);++var _glTexParameteri = _emscripten_glTexParameteri;++var _emscripten_glTexStorage2D = (x0, x1, x2, x3, x4) => GLctx.texStorage2D(x0, x1, x2, x3, x4);++var _glTexStorage2D = _emscripten_glTexStorage2D;++var _emscripten_glTexStorage3D = (x0, x1, x2, x3, x4, x5) => GLctx.texStorage3D(x0, x1, x2, x3, x4, x5);++var _glTexStorage3D = _emscripten_glTexStorage3D;++var _emscripten_glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, heap, toTypedArrayIndex(pixels, heap));+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0) : null;+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);+};++var _glTexSubImage2D = _emscripten_glTexSubImage2D;++var _emscripten_glTexSubImage3D = (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels) => {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);+ } else if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, heap, toTypedArrayIndex(pixels, heap));+ } else {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, null);+ }+};++var _glTexSubImage3D = _emscripten_glTexSubImage3D;++var webglGetUniformLocation = location => {+ var p = GLctx.currentProgram;+ if (p) {+ var webglLoc = p.uniformLocsById[location];+ // p.uniformLocsById[location] stores either an integer, or a+ // WebGLUniformLocation.+ // If an integer, we have not yet bound the location, so do it now. The+ // integer value specifies the array index we should bind to.+ if (typeof webglLoc == "number") {+ p.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(p, p.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : ""));+ }+ // Else an already cached WebGLUniformLocation, return it.+ return webglLoc;+ } else {+ GL.recordError(1282);+ }+};++var _emscripten_glUniform1f = (location, v0) => {+ GLctx.uniform1f(webglGetUniformLocation(location), v0);+};++var _glUniform1f = _emscripten_glUniform1f;++var miniTempWebGLFloatBuffers = [];++var _emscripten_glUniform1fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform1fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count);+ return;+ }+ if (count <= 288) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; ++i) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 4) >> 2));+ }+ GLctx.uniform1fv(webglGetUniformLocation(location), view);+};++var _glUniform1fv = _emscripten_glUniform1fv;++var _emscripten_glUniform1i = (location, v0) => {+ GLctx.uniform1i(webglGetUniformLocation(location), v0);+};++var _glUniform1i = _emscripten_glUniform1i;++var _emscripten_glUniform2f = (location, v0, v1) => {+ GLctx.uniform2f(webglGetUniformLocation(location), v0, v1);+};++var _glUniform2f = _emscripten_glUniform2f;++var _emscripten_glUniform2fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform2fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 2);+ return;+ }+ if (count <= 144) {+ // avoid allocation when uploading few enough uniforms+ count *= 2;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 2) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 8) >> 2));+ }+ GLctx.uniform2fv(webglGetUniformLocation(location), view);+};++var _glUniform2fv = _emscripten_glUniform2fv;++var _emscripten_glUniform3f = (location, v0, v1, v2) => {+ GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2);+};++var _glUniform3f = _emscripten_glUniform3f;++var _emscripten_glUniform4f = (location, v0, v1, v2, v3) => {+ GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3);+};++var _glUniform4f = _emscripten_glUniform4f;++var _emscripten_glUniform4fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[4 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 4;+ for (var i = 0; i < count; i += 4) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4fv(webglGetUniformLocation(location), view);+};++var _glUniform4fv = _emscripten_glUniform4fv;++var miniTempWebGLIntBuffers = [];++var _emscripten_glUniform4iv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4iv(webglGetUniformLocation(location), HEAP32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLIntBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAP32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAP32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAP32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAP32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAP32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4iv(webglGetUniformLocation(location), view);+};++var _glUniform4iv = _emscripten_glUniform4iv;++var _emscripten_glUniformBlockBinding = (program, uniformBlockIndex, uniformBlockBinding) => {+ program = GL.programs[program];+ GLctx.uniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);+};++var _glUniformBlockBinding = _emscripten_glUniformBlockBinding;++var _emscripten_glUniformMatrix2fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix2fv = _emscripten_glUniformMatrix2fv;++var _emscripten_glUniformMatrix3fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 9);+ return;+ }+ if (count <= 32) {+ // avoid allocation when uploading few enough uniforms+ count *= 9;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 9) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ view[i + 4] = HEAPF32[(((value) + (4 * i + 16)) >> 2)];+ view[i + 5] = HEAPF32[(((value) + (4 * i + 20)) >> 2)];+ view[i + 6] = HEAPF32[(((value) + (4 * i + 24)) >> 2)];+ view[i + 7] = HEAPF32[(((value) + (4 * i + 28)) >> 2)];+ view[i + 8] = HEAPF32[(((value) + (4 * i + 32)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 36) >> 2));+ }+ GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix3fv = _emscripten_glUniformMatrix3fv;++var _emscripten_glUniformMatrix4fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 16);+ return;+ }+ if (count <= 18) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[16 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 16;+ for (var i = 0; i < count; i += 16) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ view[i + 4] = heap[dst + 4];+ view[i + 5] = heap[dst + 5];+ view[i + 6] = heap[dst + 6];+ view[i + 7] = heap[dst + 7];+ view[i + 8] = heap[dst + 8];+ view[i + 9] = heap[dst + 9];+ view[i + 10] = heap[dst + 10];+ view[i + 11] = heap[dst + 11];+ view[i + 12] = heap[dst + 12];+ view[i + 13] = heap[dst + 13];+ view[i + 14] = heap[dst + 14];+ view[i + 15] = heap[dst + 15];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 64) >> 2));+ }+ GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix4fv = _emscripten_glUniformMatrix4fv;++var _emscripten_glUseProgram = program => {+ program = GL.programs[program];+ GLctx.useProgram(program);+ // Record the currently active program so that we can access the uniform+ // mapping table of that program.+ GLctx.currentProgram = program;+};++var _glUseProgram = _emscripten_glUseProgram;++var _emscripten_glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => {+ var cb = GL.currentContext.clientBuffers[index];+ if (!GLctx.currentArrayBufferBinding) {+ cb.size = size;+ cb.type = type;+ cb.normalized = normalized;+ cb.stride = stride;+ cb.ptr = ptr;+ cb.clientside = true;+ cb.vertexAttribPointerAdaptor = function(index, size, type, normalized, stride, ptr) {+ this.vertexAttribPointer(index, size, type, normalized, stride, ptr);+ };+ return;+ }+ cb.clientside = false;+ GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);+};++var _glVertexAttribPointer = _emscripten_glVertexAttribPointer;++var _emscripten_glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3);++var _glViewport = _emscripten_glViewport;++function _mediapipe_find_canvas_event_target(canvasSelector) {+ let target = findCanvasEventTarget(canvasSelector);+ // WebGPU-on-worker uses this function to try to grab the canvas, but+ // doesn't have a DOM element to find. So as a quick patch, if the default+ // behavior is unsuccessful here then we try a webgpu canvas property+ // which is set by the user directly on the Module, much like how our old+ // pipeline used the Module.canvas property. See b/265271517 for details.+ if (Module && !target) {+ target = Module.canvasWebGpu;+ }+ return Emval.toHandle(target);+}++function _mediapipe_webgl_tex_image_drawable(drawableHandle) {+ const drawable = Emval.toValue(drawableHandle);+ GLctx.texImage2D(GLctx.TEXTURE_2D, 0, GLctx.RGBA, GLctx.RGBA, GLctx.UNSIGNED_BYTE, drawable);+}++var _random_get = (buffer, size) => randomFill(HEAPU8.subarray(buffer, buffer + size));++var _wgpuCommandEncoderBeginComputePass = (encoderPtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (12)) >> 2)])+ };+ }+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateComputePassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginComputePass(desc));+ return ptr;+};++var _wgpuCommandEncoderBeginRenderPass = (encoderPtr, descriptor) => {+ function makeColorAttachment(caPtr) {+ var viewPtr = HEAPU32[(((caPtr) + (4)) >> 2)];+ if (viewPtr === 0) {+ // Null `view` means no attachment in this slot.+ return undefined;+ }+ var depthSlice = HEAPU32[(((caPtr) + (8)) >> 2)];+ if (depthSlice == 4294967295) depthSlice = undefined;+ return {+ "view": WebGPU.getJsObject(viewPtr),+ "depthSlice": depthSlice,+ "resolveTarget": WebGPU.getJsObject(HEAPU32[(((caPtr) + (12)) >> 2)]),+ "clearValue": WebGPU.makeColor(caPtr + 24),+ "loadOp": WebGPU.LoadOp[HEAP32[(((caPtr) + (16)) >> 2)]],+ "storeOp": WebGPU.StoreOp[HEAP32[(((caPtr) + (20)) >> 2)]]+ };+ }+ function makeColorAttachments(count, caPtr) {+ var attachments = [];+ for (var i = 0; i < count; ++i) {+ attachments.push(makeColorAttachment(caPtr + 56 * i));+ }+ return attachments;+ }+ function makeDepthStencilAttachment(dsaPtr) {+ if (dsaPtr === 0) return undefined;+ return {+ "view": WebGPU.getJsObject(HEAPU32[(((dsaPtr) + (4)) >> 2)]),+ "depthClearValue": HEAPF32[(((dsaPtr) + (16)) >> 2)],+ "depthLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (8)) >> 2)]],+ "depthStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (12)) >> 2)]],+ "depthReadOnly": !!(HEAPU32[(((dsaPtr) + (20)) >> 2)]),+ "stencilClearValue": HEAPU32[(((dsaPtr) + (32)) >> 2)],+ "stencilLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (24)) >> 2)]],+ "stencilStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (28)) >> 2)]],+ "stencilReadOnly": !!(HEAPU32[(((dsaPtr) + (36)) >> 2)])+ };+ }+ function makeRenderPassDescriptor(descriptor) {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var maxDrawCount = undefined;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var renderPassMaxDrawCount = nextInChainPtr;+ // Note: The user could have passed a really huge value here, which is technically valid in+ // C but will not be allowed by WebGPU in JS because of [EnforceRange]. We intentionally+ // ignore that case because it's not useful - apps can just pick a smaller maxDrawCount.+ maxDrawCount = readI53FromI64((renderPassMaxDrawCount) + (8));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "colorAttachments": makeColorAttachments(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]),+ "depthStencilAttachment": makeDepthStencilAttachment(HEAPU32[(((descriptor) + (20)) >> 2)]),+ "occlusionQuerySet": WebGPU.getJsObject(HEAPU32[(((descriptor) + (24)) >> 2)]),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (28)) >> 2)]),+ "maxDrawCount": maxDrawCount+ };+ return desc;+ }+ var desc = makeRenderPassDescriptor(descriptor);+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateRenderPassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginRenderPass(desc));+ return ptr;+};++var _wgpuCommandEncoderCopyBufferToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToBuffer = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyBufferInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderFinish = (encoderPtr, descriptor) => {+ // TODO: Use the descriptor.+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateCommandBuffer(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.finish());+ return ptr;+};++var _wgpuComputePassEncoderDispatchWorkgroups = (passPtr, x, y, z) => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.dispatchWorkgroups(x, y, z);+};++var _wgpuComputePassEncoderEnd = passPtr => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.end();+};++var _wgpuComputePassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuComputePassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuComputePipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuDeviceCreateBindGroup = (devicePtr, descriptor) => {+ function makeEntry(entryPtr) {+ var bufferPtr = HEAPU32[(((entryPtr) + (8)) >> 2)];+ var samplerPtr = HEAPU32[(((entryPtr) + (32)) >> 2)];+ var textureViewPtr = HEAPU32[(((entryPtr) + (36)) >> 2)];+ var externalTexturePtr = 0;+ WebGPU.iterateExtensions(entryPtr, {+ 14: ptr => {+ externalTexturePtr = HEAPU32[(((ptr) + (8)) >> 2)];+ }+ });+ var resource;+ if (bufferPtr) {+ // Note the sentinel UINT64_MAX will be read as -1.+ var size = readI53FromI64((entryPtr) + (24));+ if (size == -1) size = undefined;+ resource = {+ "buffer": WebGPU.getJsObject(bufferPtr),+ "offset": readI53FromI64((entryPtr) + (16)),+ "size": size+ };+ } else {+ resource = WebGPU.getJsObject(samplerPtr || textureViewPtr || externalTexturePtr);+ }+ return {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "resource": resource+ };+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 40 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.getJsObject(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "entries": makeEntries(HEAPU32[(((descriptor) + (16)) >> 2)], HEAPU32[(((descriptor) + (20)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroup(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroup(desc));+ return ptr;+};++var _wgpuDeviceCreateBindGroupLayout = (devicePtr, descriptor) => {+ function makeBufferEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.BufferBindingType[typeInt],+ "hasDynamicOffset": !!(HEAPU32[(((substructPtr) + (8)) >> 2)]),+ "minBindingSize": readI53FromI64((substructPtr) + (16))+ };+ }+ function makeSamplerEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.SamplerBindingType[typeInt]+ };+ }+ function makeTextureEntry(substructPtr) {+ var sampleTypeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!sampleTypeInt) return undefined;+ return {+ "sampleType": WebGPU.TextureSampleType[sampleTypeInt],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "multisampled": !!(HEAPU32[(((substructPtr) + (12)) >> 2)])+ };+ }+ function makeStorageTextureEntry(substructPtr) {+ var accessInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!accessInt) return undefined;+ return {+ "access": WebGPU.StorageTextureAccess[accessInt],+ "format": WebGPU.TextureFormat[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (12)) >> 2)]]+ };+ }+ function makeEntry(entryPtr) {+ var entry = {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "visibility": HEAPU32[(((entryPtr) + (8)) >> 2)],+ "buffer": makeBufferEntry(entryPtr + 24),+ "sampler": makeSamplerEntry(entryPtr + 48),+ "texture": makeTextureEntry(entryPtr + 56),+ "storageTexture": makeStorageTextureEntry(entryPtr + 72)+ };+ WebGPU.iterateExtensions(entryPtr, {+ 13: ptr => {+ entry["externalTexture"] = {};+ }+ });+ return entry;+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 88 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "entries": makeEntries(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroupLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateCommandEncoder = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4)+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateCommandEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createCommandEncoder(desc));+ return ptr;+};++var _wgpuDeviceCreateComputePipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateComputePipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createComputePipeline(desc));+ return ptr;+};++var _wgpuDeviceCreatePipelineLayout = (devicePtr, descriptor) => {+ var bglCount = HEAPU32[(((descriptor) + (12)) >> 2)];+ var bglPtr = HEAPU32[(((descriptor) + (16)) >> 2)];+ var bgls = [];+ for (var i = 0; i < bglCount; ++i) {+ bgls.push(WebGPU.getJsObject(HEAPU32[(((bglPtr) + (4 * i)) >> 2)]));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "bindGroupLayouts": bgls+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreatePipelineLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createPipelineLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateRenderPipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateRenderPipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createRenderPipeline(desc));+ return ptr;+};++var _wgpuDeviceCreateSampler = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "addressModeU": WebGPU.AddressMode[HEAP32[(((descriptor) + (12)) >> 2)]],+ "addressModeV": WebGPU.AddressMode[HEAP32[(((descriptor) + (16)) >> 2)]],+ "addressModeW": WebGPU.AddressMode[HEAP32[(((descriptor) + (20)) >> 2)]],+ "magFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (24)) >> 2)]],+ "minFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (28)) >> 2)]],+ "mipmapFilter": WebGPU.MipmapFilterMode[HEAP32[(((descriptor) + (32)) >> 2)]],+ "lodMinClamp": HEAPF32[(((descriptor) + (36)) >> 2)],+ "lodMaxClamp": HEAPF32[(((descriptor) + (40)) >> 2)],+ "compare": WebGPU.CompareFunction[HEAP32[(((descriptor) + (44)) >> 2)]],+ "maxAnisotropy": HEAPU16[(((descriptor) + (48)) >> 1)]+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateSampler(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createSampler(desc));+ return ptr;+};++var _wgpuDeviceCreateTexture = (devicePtr, descriptor) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var textureBindingViewDimension;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var textureBindingViewDimensionDescriptor = nextInChainPtr;+ textureBindingViewDimension = WebGPU.TextureViewDimension[HEAP32[(((textureBindingViewDimensionDescriptor) + (8)) >> 2)]];+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "size": WebGPU.makeExtent3D(descriptor + 28),+ "mipLevelCount": HEAPU32[(((descriptor) + (44)) >> 2)],+ "sampleCount": HEAPU32[(((descriptor) + (48)) >> 2)],+ "dimension": WebGPU.TextureDimension[HEAP32[(((descriptor) + (24)) >> 2)]],+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (40)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "textureBindingViewDimension": textureBindingViewDimension+ };+ var viewFormatCount = HEAPU32[(((descriptor) + (52)) >> 2)];+ if (viewFormatCount) {+ var viewFormatsPtr = HEAPU32[(((descriptor) + (56)) >> 2)];+ // viewFormatsPtr pointer to an array of TextureFormat which is an enum of size uint32_t+ desc["viewFormats"] = Array.from(HEAP32.subarray((((viewFormatsPtr) >> 2)), ((viewFormatsPtr + viewFormatCount * 4) >> 2)), format => WebGPU.TextureFormat[format]);+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateTexture(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createTexture(desc));+ return ptr;+};++var _wgpuQueueSubmit = (queuePtr, commandCount, commands) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var cmds = Array.from(HEAP32.subarray((((commands) >> 2)), ((commands + commandCount * 4) >> 2)), id => WebGPU.getJsObject(id));+ queue.submit(cmds);+};++function _wgpuQueueWriteBuffer(queuePtr, bufferPtr, bufferOffset_low, bufferOffset_high, data, size) {+ var bufferOffset = convertI32PairToI53Checked(bufferOffset_low, bufferOffset_high);+ var queue = WebGPU.getJsObject(queuePtr);+ var buffer = WebGPU.getJsObject(bufferPtr);+ // There is a size limitation for ArrayBufferView. Work around by passing in a subarray+ // instead of the whole heap. crbug.com/1201109+ var subarray = HEAPU8.subarray(data, data + size);+ queue.writeBuffer(buffer, bufferOffset, subarray, 0, size);+}++var _wgpuQueueWriteTexture = (queuePtr, destinationPtr, data, dataSize, dataLayoutPtr, writeSizePtr) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var destination = WebGPU.makeTexelCopyTextureInfo(destinationPtr);+ var dataLayout = WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr);+ var writeSize = WebGPU.makeExtent3D(writeSizePtr);+ // This subarray isn't strictly necessary, but helps work around an issue+ // where Chromium makes a copy of the entire heap. crbug.com/1134457+ var subarray = HEAPU8.subarray(data, data + dataSize);+ queue.writeTexture(destination, subarray, dataLayout, writeSize);+};++var _wgpuRenderPassEncoderDraw = (passPtr, vertexCount, instanceCount, firstVertex, firstInstance) => {+ firstVertex >>>= 0;+ firstInstance >>>= 0;+ var pass = WebGPU.getJsObject(passPtr);+ pass.draw(vertexCount, instanceCount, firstVertex, firstInstance);+};++var _wgpuRenderPassEncoderEnd = encoderPtr => {+ var encoder = WebGPU.getJsObject(encoderPtr);+ encoder.end();+};++var _wgpuRenderPassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuRenderPassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuRenderPipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuTextureCreateView = (texturePtr, descriptor) => {+ var desc;+ if (descriptor) {+ var swizzle;+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var swizzleDescriptor = nextInChainPtr;+ var swizzlePtr = swizzleDescriptor + 8;+ var r = WebGPU.ComponentSwizzle[HEAP32[((swizzlePtr) >> 2)]] || "r";+ var g = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (4)) >> 2)]] || "g";+ var b = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (8)) >> 2)]] || "b";+ var a = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (12)) >> 2)]] || "a";+ swizzle = `${r}${g}${b}${a}`;+ }+ var mipLevelCount = HEAPU32[(((descriptor) + (24)) >> 2)];+ var arrayLayerCount = HEAPU32[(((descriptor) + (32)) >> 2)];+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (12)) >> 2)]],+ "dimension": WebGPU.TextureViewDimension[HEAP32[(((descriptor) + (16)) >> 2)]],+ "baseMipLevel": HEAPU32[(((descriptor) + (20)) >> 2)],+ "mipLevelCount": mipLevelCount === 4294967295 ? undefined : mipLevelCount,+ "baseArrayLayer": HEAPU32[(((descriptor) + (28)) >> 2)],+ "arrayLayerCount": arrayLayerCount === 4294967295 ? undefined : arrayLayerCount,+ "aspect": WebGPU.TextureAspect[HEAP32[(((descriptor) + (36)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (40)) >> 2)],+ "swizzle": swizzle+ };+ }+ var texture = WebGPU.getJsObject(texturePtr);+ var ptr = _emwgpuCreateTextureView(0);+ WebGPU.Internals.jsObjectInsert(ptr, texture.createView(desc));+ return ptr;+};++var _wgpuTextureDestroy = texturePtr => {+ WebGPU.getJsObject(texturePtr).destroy();+};++var _wgpuTextureGetFormat = texturePtr => {+ var texture = WebGPU.getJsObject(texturePtr);+ // Should return the enum integer instead of string.+ return WebGPU.TextureFormat.indexOf(texture.format);+};++var getCFunc = ident => {+ var func = Module["_" + ident];+ // closure exported function+ return func;+};++var writeArrayToMemory = (array, buffer) => {+ HEAP8.set(array, buffer);+};++/**+ * @param {string|null=} returnType+ * @param {Array=} argTypes+ * @param {Array=} args+ * @param {Object=} opts+ */ var ccall = (ident, returnType, argTypes, args, opts) => {+ // For fast lookup of conversion functions+ var toC = {+ "string": str => {+ var ret = 0;+ if (str !== null && str !== undefined && str !== 0) {+ // null string+ ret = stringToUTF8OnStack(str);+ }+ return ret;+ },+ "array": arr => {+ var ret = stackAlloc(arr.length);+ writeArrayToMemory(arr, ret);+ return ret;+ }+ };+ function convertReturnValue(ret) {+ if (returnType === "string") {+ return UTF8ToString(ret);+ }+ if (returnType === "boolean") return Boolean(ret);+ return ret;+ }+ var func = getCFunc(ident);+ var cArgs = [];+ var stack = 0;+ if (args) {+ for (var i = 0; i < args.length; i++) {+ var converter = toC[argTypes[i]];+ if (converter) {+ if (stack === 0) stack = stackSave();+ cArgs[i] = converter(args[i]);+ } else {+ cArgs[i] = args[i];+ }+ }+ }+ var ret = func(...cArgs);+ function onDone(ret) {+ if (stack !== 0) stackRestore(stack);+ return convertReturnValue(ret);+ }+ ret = onDone(ret);+ return ret;+};++var FS_createPath = (...args) => FS.createPath(...args);++var FS_unlink = (...args) => FS.unlink(...args);++var FS_createLazyFile = (...args) => FS.createLazyFile(...args);++var FS_createDevice = (...args) => FS.createDevice(...args);++FS.createPreloadedFile = FS_createPreloadedFile;++FS.preloadFile = FS_preloadFile;++FS.staticInit();++// Signal GL rendering layer that processing of a new frame is about to+// start. This helps it optimize VBO double-buffering and reduce GPU stalls.+registerPreMainLoop(() => GL.newRenderingFrameStarted());++for (let i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i));++var miniTempWebGLFloatBuffersStorage = new Float32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i);+}++var miniTempWebGLIntBuffersStorage = new Int32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i);+}++// End JS library code+// include: postlibrary.js+// This file is included after the automatically-generated JS library code+// but before the wasm module is created.+{+ // Begin ATMODULES hooks+ if (Module["preloadPlugins"]) preloadPlugins = Module["preloadPlugins"];+ if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];+ if (Module["print"]) out = Module["print"];+ if (Module["printErr"]) err = Module["printErr"];+ if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];+ // End ATMODULES hooks+ if (Module["arguments"]) arguments_ = Module["arguments"];+ if (Module["thisProgram"]) thisProgram = Module["thisProgram"];+ if (Module["preInit"]) {+ if (typeof Module["preInit"] == "function") Module["preInit"] = [ Module["preInit"] ];+ while (Module["preInit"].length > 0) {+ Module["preInit"].shift()();+ }+ }+}++// Begin runtime exports+Module["addRunDependency"] = addRunDependency;++Module["removeRunDependency"] = removeRunDependency;++Module["ccall"] = ccall;++Module["stringToNewUTF8"] = stringToNewUTF8;++Module["FS_preloadFile"] = FS_preloadFile;++Module["FS_unlink"] = FS_unlink;++Module["FS_createPath"] = FS_createPath;++Module["FS_createDevice"] = FS_createDevice;++Module["FS_createDataFile"] = FS_createDataFile;++Module["FS_createLazyFile"] = FS_createLazyFile;++// End runtime exports+// Begin JS library exports+// End JS library exports+// end include: postlibrary.js+var ASM_CONSTS = {+ 1462283: $0 => {+ const canvas = Emval.toValue($0);+ const context = canvas.getContext("webgpu");+ return WebGPU.importJsTexture(context.getCurrentTexture());+ },+ 1462426: ($0, $1, $2, $3, $4) => {+ const drawable = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const texture = WebGPU.getJsObject($2);+ const width = $3;+ const height = $4;+ device.queue.copyExternalImageToTexture({+ source: drawable+ }, {+ texture+ }, [ width, height ]);+ },+ 1462685: ($0, $1, $2, $3) => {+ const sourceExtTex = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const sampler = WebGPU.getJsObject($2);+ const bgLayout = WebGPU.getJsObject($3);+ const bindGroup = device.createBindGroup({+ layout: bgLayout,+ entries: [ {+ binding: 0,+ resource: sampler+ }, {+ binding: 1,+ resource: sourceExtTex+ } ]+ });+ return WebGPU.importJsBindGroup(bindGroup);+ },+ 1463055: ($0, $1) => {+ const input = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ ctx.drawImage(input, 0, 0, output.width, output.height);+ },+ 1463220: ($0, $1) => {+ const inputArray = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ const image_data = new ImageData(inputArray, output.width, output.height);+ ctx.putImageData(image_data, 0, 0);+ },+ 1463444: ($0, $1) => {+ const input = Emval.toValue($0);+ const outputArray = Emval.toValue($1);+ const ctx = input.getContext("2d");+ const data = ctx.getImageData(0, 0, input.width, input.height);+ outputArray.set(data.data);+ },+ 1463648: () => (typeof HTMLCanvasElement !== "undefined"),+ 1463703: () => !!Module["preinitializedWebGPUDevice"],+ 1463754: () => {+ specialHTMLTargets["#canvas"] = Module.canvas;+ }+};++function BeginGlQueryTiming(calc_name, num_repetitions) {+ const gl = Module.canvas.getContext("webgl2");+ const query = gl.createQuery();+ Module.WEBGL_SHADER_CALC_METRICS = Module.WEBGL_SHADER_CALC_METRICS || {};+ Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)] = {+ query,+ repetitions: num_repetitions+ };+ Module.WEBGL_QUERY_TIMER_EXT = Module.WEBGL_QUERY_TIMER_EXT || gl.getExtension("EXT_disjoint_timer_query_webgl2");+ gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, query);+}++function EndGlQueryTiming(calc_name) {+ const gl = Module.canvas.getContext("webgl2");+ gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query);+}++function JsWrapImageConverter() {+ if (!Module._imageConverter) {+ Module._imageConverter = (binaryPtr, binarySize, width, height, numChannels, makeDeepCopy, outputType) => {+ const imageData = new outputType(makeDeepCopy ? Module.HEAPU8.slice(binaryPtr, binaryPtr + binarySize).buffer : Module.HEAPU8.buffer, binaryPtr, width * height * numChannels);+ return {+ data: imageData,+ width,+ height+ };+ };+ }+}++function JsOnUint8ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnFloat32ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnWebGLTextureListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, timestamp_ms);+}++function JsOnUint8ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnFloat32ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnWebGLTextureVectorListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, false, timestamp_ms);+}++function JsOnEmptyPacketListener(output_stream_name, timestamp) {+ Module._wrapEmptyPacketListenerOutput(output_stream_name, timestamp);+}++function JsOnVectorFinishedListener(output_stream_name, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, undefined, true, timestamp);+}++function JsOnSimpleListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), timestamp);+}++function JsOnVectorListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), false, timestamp);+}++function JsOnVectorListenerProto(output_stream_name, proto_ptr, proto_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(proto_ptr, proto_ptr + proto_size) : new Uint8Array(Module.HEAPU8.buffer, proto_ptr, proto_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, false, timestamp);+}++function JsWrapSimpleListeners() {+ if (!Module._wrapSimpleListenerOutput) {+ Module._wrapSimpleListenerOutput = (outputStreamName, ...args) => {+ if (Module.simpleListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.simpleListeners[streamName]) {+ Module.simpleListeners[streamName](...args);+ }+ }+ };+ }+ if (!Module._wrapEmptyPacketListenerOutput) {+ Module._wrapEmptyPacketListenerOutput = (outputStreamName, timestamp) => {+ if (Module.emptyPacketListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.emptyPacketListeners[streamName]) {+ Module.emptyPacketListeners[streamName](timestamp);+ }+ }+ };+ }+}++function JsOnSimpleListenerBinaryArray(output_stream_name, binary_ptr, binary_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(binary_ptr, binary_ptr + binary_size) : new Uint8Array(Module.HEAPU8.buffer, binary_ptr, binary_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, timestamp);+}++function mediapipe_import_external_texture(device_handle, source_handle) {+ const device = WebGPU.getJsObject(device_handle);+ const source = Emval.toValue(source_handle);+ const externalTexture = device.importExternalTexture({+ source+ });+ return Emval.toHandle(externalTexture);+}++function mediapipe_create_utility_canvas2d() {+ let canvas;+ if (typeof HTMLCanvasElement !== "undefined") {+ canvas = document.createElement("canvas");+ canvas.style.display = "none";+ } else {+ canvas = new OffscreenCanvas(0, 0);+ }+ return Emval.toHandle(canvas);+}++function GetAdapterArchitecture() {+ const device = Module["preinitializedWebGPUDevice"];+ const architecture = device.adapterInfo ? device.adapterInfo.architecture : "Unknown";+ return stringToNewUTF8(architecture);+}++function GetAdapterDescription() {+ const device = Module["preinitializedWebGPUDevice"];+ const description = device.adapterInfo ? device.adapterInfo.description : "Unknown";+ return stringToNewUTF8(description);+}++function GetAdapterDeviceName() {+ const device = Module["preinitializedWebGPUDevice"];+ const deviceName = device.adapterInfo ? device.adapterInfo.device : "Unknown";+ return stringToNewUTF8(deviceName);+}++function GetAdapterVendor() {+ const device = Module["preinitializedWebGPUDevice"];+ const vendor = device.adapterInfo ? device.adapterInfo.vendor : "Unknown";+ return stringToNewUTF8(vendor);+}++function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle, data) {+ return Asyncify.handleAsync(async () => {+ const buffer = WebGPU.getJsObject(buffer_handle);+ if ("mapSync" in buffer) {+ buffer.mapSync(GPUMapMode.READ);+ } else {+ await buffer.mapAsync(GPUMapMode.READ);+ }+ const mapped = buffer.getMappedRange();+ HEAPU8.set(new Uint8Array(mapped), data);+ buffer.unmap();+ });+}++function hardware_concurrency() {+ var concurrency = 1;+ try {+ concurrency = self.navigator.hardwareConcurrency;+ } catch (e) {}+ return concurrency;+}++function JsWrapErrorListener(code, message) {+ if (Module.errorListener) {+ const stringMessage = UTF8ToString(message);+ Module.errorListener(code, stringMessage);+ }+}++function UseBottomLeftGpuOrigin() {+ return (Module && Module.gpuOriginForWebTexturesIsBottomLeft);+}++function custom_emscripten_dbgn(str, len) {+ if (typeof (dbg) !== "undefined") {+ dbg(UTF8ToString(str, len));+ } else {+ if (typeof (custom_dbg) === "undefined") {+ function custom_dbg(text) {+ console.warn.apply(console, arguments);+ }+ }+ custom_dbg(UTF8ToString(str, len));+ }+}++// Imports from the Wasm binary.+var _free, _malloc, _wgpuDeviceAddRef, _addBoundTextureAsImageToStream, _attachImageListener, _attachImageVectorListener, _registerModelResourcesGraphService, _bindTextureToStream, _addBoundTextureToStream, _addDoubleToInputStream, _addFloatToInputStream, _addBoolToInputStream, _addIntToInputStream, _addUintToInputStream, _addStringToInputStream, _addRawDataSpanToInputStream, _allocateBoolVector, _allocateFloatVector, _allocateDoubleVector, _allocateIntVector, _allocateUintVector, _allocateStringVector, _addBoolVectorEntry, _addFloatVectorEntry, _addDoubleVectorEntry, _addIntVectorEntry, _addUintVectorEntry, _addStringVectorEntry, _addBoolVectorToInputStream, _addFloatVectorToInputStream, _addDoubleVectorToInputStream, _addIntVectorToInputStream, _addUintVectorToInputStream, _addStringVectorToInputStream, _addFlatHashMapToInputStream, _addProtoToInputStream, _addEmptyPacketToInputStream, _addBoolToInputSidePacket, _addDoubleToInputSidePacket, _addFloatToInputSidePacket, _addIntToInputSidePacket, _addUintToInputSidePacket, _addStringToInputSidePacket, _addRawDataSpanToInputSidePacket, _addProtoToInputSidePacket, _addBoolVectorToInputSidePacket, _addDoubleVectorToInputSidePacket, _addFloatVectorToInputSidePacket, _addIntVectorToInputSidePacket, _addUintVectorToInputSidePacket, _addStringVectorToInputSidePacket, _attachBoolListener, _attachBoolVectorListener, _attachDoubleListener, _attachDoubleVectorListener, _attachFloatListener, _attachFloatVectorListener, _attachIntListener, _attachIntVectorListener, _attachUintListener, _attachUintVectorListener, _attachStringListener, _attachStringVectorListener, _attachProtoListener, _attachProtoVectorListener, _getGraphConfig, ___getTypeName, _emwgpuCreateBindGroup, _emwgpuCreateBindGroupLayout, _emwgpuCreateCommandBuffer, _emwgpuCreateCommandEncoder, _emwgpuCreateComputePassEncoder, _emwgpuCreateComputePipeline, _emwgpuCreateExternalTexture, _emwgpuCreatePipelineLayout, _emwgpuCreateQuerySet, _emwgpuCreateRenderBundle, _emwgpuCreateRenderBundleEncoder, _emwgpuCreateRenderPassEncoder, _emwgpuCreateRenderPipeline, _emwgpuCreateSampler, _emwgpuCreateSurface, _emwgpuCreateTexture, _emwgpuCreateTextureView, _emwgpuCreateAdapter, _emwgpuImportBuffer, _emwgpuCreateDevice, _emwgpuCreateQueue, _emwgpuCreateShaderModule, _emwgpuOnCreateComputePipelineCompleted, _emwgpuOnCreateRenderPipelineCompleted, _clearSubgraphs, _pushBinarySubgraph, _pushTextSubgraph, _changeBinaryGraph, _changeTextGraph, _processGl, _process, _bindTextureToCanvas, _requestShaderRefreshOnGraphChange, _waitUntilIdle, _closeGraph, _setAutoRenderToScreen, _emscripten_builtin_memalign, _memalign, __emscripten_tempret_set, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, dynCall_ji, dynCall_jii, dynCall_iiiijij, dynCall_viiji, dynCall_viji, dynCall_iiiji, dynCall_jjj, dynCall_iiiijj, dynCall_viijj, dynCall_viiijjj, dynCall_vij, dynCall_viiiji, dynCall_viijii, dynCall_vijjj, dynCall_vj, dynCall_viij, dynCall_jiji, dynCall_iiiiij, dynCall_iiiiijj, dynCall_iiiiiijj, memory, _kVersionStampBuildChangelistStr, _kVersionStampCitcSnapshotStr, _kVersionStampCitcWorkspaceIdStr, _kVersionStampSourceUriStr, _kVersionStampBuildClientStr, _kVersionStampBuildClientMintStatusStr, _kVersionStampBuildCompilerStr, _kVersionStampBuildDateTimePstStr, _kVersionStampBuildDepotPathStr, _kVersionStampBuildIdStr, _kVersionStampBuildInfoStr, _kVersionStampBuildLabelStr, _kVersionStampBuildTargetStr, _kVersionStampBuildTimestampStr, _kVersionStampBuildToolStr, _kVersionStampG3BuildTargetStr, _kVersionStampVerifiableStr, _kVersionStampBuildFdoTypeStr, _kVersionStampBuildBaselineChangelistStr, _kVersionStampBuildLtoTypeStr, _kVersionStampBuildPropellerTypeStr, _kVersionStampBuildPghoTypeStr, _kVersionStampBuildUsernameStr, _kVersionStampBuildHostnameStr, _kVersionStampBuildDirectoryStr, _kVersionStampBuildChangelistInt, _kVersionStampCitcSnapshotInt, _kVersionStampBuildClientMintStatusInt, _kVersionStampBuildTimestampInt, _kVersionStampVerifiableInt, _kVersionStampBuildCoverageEnabledInt, _kVersionStampBuildBaselineChangelistInt, _kVersionStampPrecookedTimestampStr, _kVersionStampPrecookedClientInfoStr, __indirect_function_table, wasmMemory, wasmTable;++function assignWasmExports(wasmExports) {+ _free = Module["_free"] = wasmExports["Td"];+ _malloc = Module["_malloc"] = wasmExports["Ud"];+ _wgpuDeviceAddRef = wasmExports["Vd"];+ _addBoundTextureAsImageToStream = Module["_addBoundTextureAsImageToStream"] = wasmExports["Wd"];+ _attachImageListener = Module["_attachImageListener"] = wasmExports["Xd"];+ _attachImageVectorListener = Module["_attachImageVectorListener"] = wasmExports["Yd"];+ _registerModelResourcesGraphService = Module["_registerModelResourcesGraphService"] = wasmExports["Zd"];+ _bindTextureToStream = Module["_bindTextureToStream"] = wasmExports["_d"];+ _addBoundTextureToStream = Module["_addBoundTextureToStream"] = wasmExports["$d"];+ _addDoubleToInputStream = Module["_addDoubleToInputStream"] = wasmExports["ae"];+ _addFloatToInputStream = Module["_addFloatToInputStream"] = wasmExports["be"];+ _addBoolToInputStream = Module["_addBoolToInputStream"] = wasmExports["ce"];+ _addIntToInputStream = Module["_addIntToInputStream"] = wasmExports["de"];+ _addUintToInputStream = Module["_addUintToInputStream"] = wasmExports["ee"];+ _addStringToInputStream = Module["_addStringToInputStream"] = wasmExports["fe"];+ _addRawDataSpanToInputStream = Module["_addRawDataSpanToInputStream"] = wasmExports["ge"];+ _allocateBoolVector = Module["_allocateBoolVector"] = wasmExports["he"];+ _allocateFloatVector = Module["_allocateFloatVector"] = wasmExports["ie"];+ _allocateDoubleVector = Module["_allocateDoubleVector"] = wasmExports["je"];+ _allocateIntVector = Module["_allocateIntVector"] = wasmExports["ke"];+ _allocateUintVector = Module["_allocateUintVector"] = wasmExports["le"];+ _allocateStringVector = Module["_allocateStringVector"] = wasmExports["me"];+ _addBoolVectorEntry = Module["_addBoolVectorEntry"] = wasmExports["ne"];+ _addFloatVectorEntry = Module["_addFloatVectorEntry"] = wasmExports["oe"];+ _addDoubleVectorEntry = Module["_addDoubleVectorEntry"] = wasmExports["pe"];+ _addIntVectorEntry = Module["_addIntVectorEntry"] = wasmExports["qe"];+ _addUintVectorEntry = Module["_addUintVectorEntry"] = wasmExports["re"];+ _addStringVectorEntry = Module["_addStringVectorEntry"] = wasmExports["se"];+ _addBoolVectorToInputStream = Module["_addBoolVectorToInputStream"] = wasmExports["te"];+ _addFloatVectorToInputStream = Module["_addFloatVectorToInputStream"] = wasmExports["ue"];+ _addDoubleVectorToInputStream = Module["_addDoubleVectorToInputStream"] = wasmExports["ve"];+ _addIntVectorToInputStream = Module["_addIntVectorToInputStream"] = wasmExports["we"];+ _addUintVectorToInputStream = Module["_addUintVectorToInputStream"] = wasmExports["xe"];+ _addStringVectorToInputStream = Module["_addStringVectorToInputStream"] = wasmExports["ye"];+ _addFlatHashMapToInputStream = Module["_addFlatHashMapToInputStream"] = wasmExports["ze"];+ _addProtoToInputStream = Module["_addProtoToInputStream"] = wasmExports["Ae"];+ _addEmptyPacketToInputStream = Module["_addEmptyPacketToInputStream"] = wasmExports["Be"];+ _addBoolToInputSidePacket = Module["_addBoolToInputSidePacket"] = wasmExports["Ce"];+ _addDoubleToInputSidePacket = Module["_addDoubleToInputSidePacket"] = wasmExports["De"];+ _addFloatToInputSidePacket = Module["_addFloatToInputSidePacket"] = wasmExports["Ee"];+ _addIntToInputSidePacket = Module["_addIntToInputSidePacket"] = wasmExports["Fe"];+ _addUintToInputSidePacket = Module["_addUintToInputSidePacket"] = wasmExports["Ge"];+ _addStringToInputSidePacket = Module["_addStringToInputSidePacket"] = wasmExports["He"];+ _addRawDataSpanToInputSidePacket = Module["_addRawDataSpanToInputSidePacket"] = wasmExports["Ie"];+ _addProtoToInputSidePacket = Module["_addProtoToInputSidePacket"] = wasmExports["Je"];+ _addBoolVectorToInputSidePacket = Module["_addBoolVectorToInputSidePacket"] = wasmExports["Ke"];+ _addDoubleVectorToInputSidePacket = Module["_addDoubleVectorToInputSidePacket"] = wasmExports["Le"];+ _addFloatVectorToInputSidePacket = Module["_addFloatVectorToInputSidePacket"] = wasmExports["Me"];+ _addIntVectorToInputSidePacket = Module["_addIntVectorToInputSidePacket"] = wasmExports["Ne"];+ _addUintVectorToInputSidePacket = Module["_addUintVectorToInputSidePacket"] = wasmExports["Oe"];+ _addStringVectorToInputSidePacket = Module["_addStringVectorToInputSidePacket"] = wasmExports["Pe"];+ _attachBoolListener = Module["_attachBoolListener"] = wasmExports["Qe"];+ _attachBoolVectorListener = Module["_attachBoolVectorListener"] = wasmExports["Re"];+ _attachDoubleListener = Module["_attachDoubleListener"] = wasmExports["Se"];+ _attachDoubleVectorListener = Module["_attachDoubleVectorListener"] = wasmExports["Te"];+ _attachFloatListener = Module["_attachFloatListener"] = wasmExports["Ue"];+ _attachFloatVectorListener = Module["_attachFloatVectorListener"] = wasmExports["Ve"];+ _attachIntListener = Module["_attachIntListener"] = wasmExports["We"];+ _attachIntVectorListener = Module["_attachIntVectorListener"] = wasmExports["Xe"];+ _attachUintListener = Module["_attachUintListener"] = wasmExports["Ye"];+ _attachUintVectorListener = Module["_attachUintVectorListener"] = wasmExports["Ze"];+ _attachStringListener = Module["_attachStringListener"] = wasmExports["_e"];+ _attachStringVectorListener = Module["_attachStringVectorListener"] = wasmExports["$e"];+ _attachProtoListener = Module["_attachProtoListener"] = wasmExports["af"];+ _attachProtoVectorListener = Module["_attachProtoVectorListener"] = wasmExports["bf"];+ _getGraphConfig = Module["_getGraphConfig"] = wasmExports["cf"];+ ___getTypeName = wasmExports["df"];+ _emwgpuCreateBindGroup = wasmExports["ef"];+ _emwgpuCreateBindGroupLayout = wasmExports["ff"];+ _emwgpuCreateCommandBuffer = wasmExports["gf"];+ _emwgpuCreateCommandEncoder = wasmExports["hf"];+ _emwgpuCreateComputePassEncoder = wasmExports["jf"];+ _emwgpuCreateComputePipeline = wasmExports["kf"];+ _emwgpuCreateExternalTexture = wasmExports["lf"];+ _emwgpuCreatePipelineLayout = wasmExports["mf"];+ _emwgpuCreateQuerySet = wasmExports["nf"];+ _emwgpuCreateRenderBundle = wasmExports["of"];+ _emwgpuCreateRenderBundleEncoder = wasmExports["pf"];+ _emwgpuCreateRenderPassEncoder = wasmExports["qf"];+ _emwgpuCreateRenderPipeline = wasmExports["rf"];+ _emwgpuCreateSampler = wasmExports["sf"];+ _emwgpuCreateSurface = wasmExports["tf"];+ _emwgpuCreateTexture = wasmExports["uf"];+ _emwgpuCreateTextureView = wasmExports["vf"];+ _emwgpuCreateAdapter = wasmExports["wf"];+ _emwgpuImportBuffer = wasmExports["xf"];+ _emwgpuCreateDevice = wasmExports["yf"];+ _emwgpuCreateQueue = wasmExports["zf"];+ _emwgpuCreateShaderModule = wasmExports["Af"];+ _emwgpuOnCreateComputePipelineCompleted = wasmExports["Bf"];+ _emwgpuOnCreateRenderPipelineCompleted = wasmExports["Cf"];+ _clearSubgraphs = Module["_clearSubgraphs"] = wasmExports["Df"];+ _pushBinarySubgraph = Module["_pushBinarySubgraph"] = wasmExports["Ef"];+ _pushTextSubgraph = Module["_pushTextSubgraph"] = wasmExports["Ff"];+ _changeBinaryGraph = Module["_changeBinaryGraph"] = wasmExports["Gf"];+ _changeTextGraph = Module["_changeTextGraph"] = wasmExports["Hf"];+ _processGl = Module["_processGl"] = wasmExports["If"];+ _process = Module["_process"] = wasmExports["Jf"];+ _bindTextureToCanvas = Module["_bindTextureToCanvas"] = wasmExports["Kf"];+ _requestShaderRefreshOnGraphChange = Module["_requestShaderRefreshOnGraphChange"] = wasmExports["Lf"];+ _waitUntilIdle = Module["_waitUntilIdle"] = wasmExports["Mf"];+ _closeGraph = Module["_closeGraph"] = wasmExports["Nf"];+ _setAutoRenderToScreen = Module["_setAutoRenderToScreen"] = wasmExports["Of"];+ _emscripten_builtin_memalign = wasmExports["Pf"];+ _memalign = wasmExports["Qf"];+ __emscripten_tempret_set = wasmExports["Rf"];+ __emscripten_stack_restore = wasmExports["Sf"];+ __emscripten_stack_alloc = wasmExports["Tf"];+ _emscripten_stack_get_current = wasmExports["Uf"];+ dynCall_ji = wasmExports["dynCall_ji"];+ dynCall_jii = wasmExports["dynCall_jii"];+ dynCall_iiiijij = wasmExports["dynCall_iiiijij"];+ dynCall_viiji = wasmExports["dynCall_viiji"];+ dynCall_viji = wasmExports["dynCall_viji"];+ dynCall_iiiji = wasmExports["dynCall_iiiji"];+ dynCall_jjj = wasmExports["dynCall_jjj"];+ dynCall_iiiijj = wasmExports["dynCall_iiiijj"];+ dynCall_viijj = wasmExports["dynCall_viijj"];+ dynCall_viiijjj = wasmExports["dynCall_viiijjj"];+ dynCall_vij = wasmExports["dynCall_vij"];+ dynCall_viiiji = wasmExports["dynCall_viiiji"];+ dynCall_viijii = wasmExports["dynCall_viijii"];+ dynCall_vijjj = wasmExports["dynCall_vijjj"];+ dynCall_vj = wasmExports["dynCall_vj"];+ dynCall_viij = wasmExports["dynCall_viij"];+ dynCall_jiji = wasmExports["dynCall_jiji"];+ dynCall_iiiiij = wasmExports["dynCall_iiiiij"];+ dynCall_iiiiijj = wasmExports["dynCall_iiiiijj"];+ dynCall_iiiiiijj = wasmExports["dynCall_iiiiiijj"];+ memory = wasmMemory = wasmExports["id"];+ _kVersionStampBuildChangelistStr = Module["_kVersionStampBuildChangelistStr"] = wasmExports["kd"].value;+ _kVersionStampCitcSnapshotStr = Module["_kVersionStampCitcSnapshotStr"] = wasmExports["ld"].value;+ _kVersionStampCitcWorkspaceIdStr = Module["_kVersionStampCitcWorkspaceIdStr"] = wasmExports["md"].value;+ _kVersionStampSourceUriStr = Module["_kVersionStampSourceUriStr"] = wasmExports["nd"].value;+ _kVersionStampBuildClientStr = Module["_kVersionStampBuildClientStr"] = wasmExports["od"].value;+ _kVersionStampBuildClientMintStatusStr = Module["_kVersionStampBuildClientMintStatusStr"] = wasmExports["pd"].value;+ _kVersionStampBuildCompilerStr = Module["_kVersionStampBuildCompilerStr"] = wasmExports["qd"].value;+ _kVersionStampBuildDateTimePstStr = Module["_kVersionStampBuildDateTimePstStr"] = wasmExports["rd"].value;+ _kVersionStampBuildDepotPathStr = Module["_kVersionStampBuildDepotPathStr"] = wasmExports["sd"].value;+ _kVersionStampBuildIdStr = Module["_kVersionStampBuildIdStr"] = wasmExports["td"].value;+ _kVersionStampBuildInfoStr = Module["_kVersionStampBuildInfoStr"] = wasmExports["ud"].value;+ _kVersionStampBuildLabelStr = Module["_kVersionStampBuildLabelStr"] = wasmExports["vd"].value;+ _kVersionStampBuildTargetStr = Module["_kVersionStampBuildTargetStr"] = wasmExports["wd"].value;+ _kVersionStampBuildTimestampStr = Module["_kVersionStampBuildTimestampStr"] = wasmExports["xd"].value;+ _kVersionStampBuildToolStr = Module["_kVersionStampBuildToolStr"] = wasmExports["yd"].value;+ _kVersionStampG3BuildTargetStr = Module["_kVersionStampG3BuildTargetStr"] = wasmExports["zd"].value;+ _kVersionStampVerifiableStr = Module["_kVersionStampVerifiableStr"] = wasmExports["Ad"].value;+ _kVersionStampBuildFdoTypeStr = Module["_kVersionStampBuildFdoTypeStr"] = wasmExports["Bd"].value;+ _kVersionStampBuildBaselineChangelistStr = Module["_kVersionStampBuildBaselineChangelistStr"] = wasmExports["Cd"].value;+ _kVersionStampBuildLtoTypeStr = Module["_kVersionStampBuildLtoTypeStr"] = wasmExports["Dd"].value;+ _kVersionStampBuildPropellerTypeStr = Module["_kVersionStampBuildPropellerTypeStr"] = wasmExports["Ed"].value;+ _kVersionStampBuildPghoTypeStr = Module["_kVersionStampBuildPghoTypeStr"] = wasmExports["Fd"].value;+ _kVersionStampBuildUsernameStr = Module["_kVersionStampBuildUsernameStr"] = wasmExports["Gd"].value;+ _kVersionStampBuildHostnameStr = Module["_kVersionStampBuildHostnameStr"] = wasmExports["Hd"].value;+ _kVersionStampBuildDirectoryStr = Module["_kVersionStampBuildDirectoryStr"] = wasmExports["Id"].value;+ _kVersionStampBuildChangelistInt = Module["_kVersionStampBuildChangelistInt"] = wasmExports["Jd"].value;+ _kVersionStampCitcSnapshotInt = Module["_kVersionStampCitcSnapshotInt"] = wasmExports["Kd"].value;+ _kVersionStampBuildClientMintStatusInt = Module["_kVersionStampBuildClientMintStatusInt"] = wasmExports["Ld"].value;+ _kVersionStampBuildTimestampInt = Module["_kVersionStampBuildTimestampInt"] = wasmExports["Md"].value;+ _kVersionStampVerifiableInt = Module["_kVersionStampVerifiableInt"] = wasmExports["Nd"].value;+ _kVersionStampBuildCoverageEnabledInt = Module["_kVersionStampBuildCoverageEnabledInt"] = wasmExports["Od"].value;+ _kVersionStampBuildBaselineChangelistInt = Module["_kVersionStampBuildBaselineChangelistInt"] = wasmExports["Pd"].value;+ _kVersionStampPrecookedTimestampStr = Module["_kVersionStampPrecookedTimestampStr"] = wasmExports["Qd"].value;+ _kVersionStampPrecookedClientInfoStr = Module["_kVersionStampPrecookedClientInfoStr"] = wasmExports["Rd"].value;+ __indirect_function_table = wasmTable = wasmExports["Sd"];+}++var wasmImports = {+ /** @export */ hd: BeginGlQueryTiming,+ /** @export */ gd: EndGlQueryTiming,+ /** @export */ fd: GetAdapterArchitecture,+ /** @export */ ed: GetAdapterDescription,+ /** @export */ dd: GetAdapterDeviceName,+ /** @export */ cd: GetAdapterVendor,+ /** @export */ bd: JsOnEmptyPacketListener,+ /** @export */ ad: JsOnFloat32ArrayImageListener,+ /** @export */ $c: JsOnFloat32ArrayImageVectorListener,+ /** @export */ pb: JsOnSimpleListenerBinaryArray,+ /** @export */ _c: JsOnSimpleListenerBool,+ /** @export */ Zc: JsOnSimpleListenerDouble,+ /** @export */ Yc: JsOnSimpleListenerFloat,+ /** @export */ Xc: JsOnSimpleListenerInt,+ /** @export */ Wc: JsOnSimpleListenerString,+ /** @export */ Vc: JsOnSimpleListenerUint,+ /** @export */ Uc: JsOnUint8ArrayImageListener,+ /** @export */ Tc: JsOnUint8ArrayImageVectorListener,+ /** @export */ P: JsOnVectorFinishedListener,+ /** @export */ Sc: JsOnVectorListenerBool,+ /** @export */ Rc: JsOnVectorListenerDouble,+ /** @export */ Qc: JsOnVectorListenerFloat,+ /** @export */ Pc: JsOnVectorListenerInt,+ /** @export */ Oc: JsOnVectorListenerProto,+ /** @export */ Nc: JsOnVectorListenerString,+ /** @export */ Mc: JsOnVectorListenerUint,+ /** @export */ Lc: JsOnWebGLTextureListener,+ /** @export */ Kc: JsOnWebGLTextureVectorListener,+ /** @export */ Pa: JsWrapErrorListener,+ /** @export */ ob: JsWrapImageConverter,+ /** @export */ u: JsWrapSimpleListeners,+ /** @export */ nb: UseBottomLeftGpuOrigin,+ /** @export */ yb: __asyncjs__mediapipe_map_buffer_jspi,+ /** @export */ r: ___cxa_throw,+ /** @export */ Jc: ___syscall_dup,+ /** @export */ Ic: ___syscall_faccessat,+ /** @export */ mb: ___syscall_fcntl64,+ /** @export */ Hc: ___syscall_fstat64,+ /** @export */ Mb: ___syscall_ftruncate64,+ /** @export */ Gc: ___syscall_ioctl,+ /** @export */ Fc: ___syscall_lstat64,+ /** @export */ Ec: ___syscall_newfstatat,+ /** @export */ lb: ___syscall_openat,+ /** @export */ Dc: ___syscall_stat64,+ /** @export */ yc: __abort_js,+ /** @export */ Jb: __embind_register_bigint,+ /** @export */ xc: __embind_register_bool,+ /** @export */ wc: __embind_register_emval,+ /** @export */ jb: __embind_register_float,+ /** @export */ J: __embind_register_integer,+ /** @export */ q: __embind_register_memory_view,+ /** @export */ vc: __embind_register_std_string,+ /** @export */ Ma: __embind_register_std_wstring,+ /** @export */ uc: __embind_register_void,+ /** @export */ $: __emval_create_invoker,+ /** @export */ p: __emval_decref,+ /** @export */ La: __emval_get_global,+ /** @export */ ib: __emval_get_property,+ /** @export */ ja: __emval_incref,+ /** @export */ Ka: __emval_instanceof,+ /** @export */ _: __emval_invoke,+ /** @export */ ua: __emval_new_cstring,+ /** @export */ Z: __emval_run_destructors,+ /** @export */ hb: __emval_set_property,+ /** @export */ tc: __emval_typeof,+ /** @export */ Ib: __gmtime_js,+ /** @export */ Hb: __localtime_js,+ /** @export */ Gb: __mktime_js,+ /** @export */ Fb: __mmap_js,+ /** @export */ Eb: __munmap_js,+ /** @export */ sc: __tzset_js,+ /** @export */ Lb: _clock_time_get,+ /** @export */ rc: custom_emscripten_dbgn,+ /** @export */ Y: _emscripten_asm_const_int,+ /** @export */ gb: _emscripten_asm_const_ptr,+ /** @export */ Ja: _emscripten_errn,+ /** @export */ qc: _emscripten_get_heap_max,+ /** @export */ y: _emscripten_get_now,+ /** @export */ ia: _emscripten_has_asyncify,+ /** @export */ pc: _emscripten_outn,+ /** @export */ oc: _emscripten_pc_get_function,+ /** @export */ nc: _emscripten_resize_heap,+ /** @export */ fb: _emscripten_stack_snapshot,+ /** @export */ mc: _emscripten_stack_unwind_buffer,+ /** @export */ lc: _emscripten_webgl_create_context,+ /** @export */ kc: _emscripten_webgl_destroy_context,+ /** @export */ jc: _emscripten_webgl_get_context_attributes,+ /** @export */ ha: _emscripten_webgl_get_current_context,+ /** @export */ ic: _emscripten_webgl_make_context_current,+ /** @export */ R: _emscripten_webgpu_get_device,+ /** @export */ hc: _emwgpuBufferDestroy,+ /** @export */ gc: _emwgpuBufferGetMappedRange,+ /** @export */ fc: _emwgpuBufferUnmap,+ /** @export */ x: _emwgpuDelete,+ /** @export */ ec: _emwgpuDeviceCreateBuffer,+ /** @export */ Db: _emwgpuDeviceCreateComputePipelineAsync,+ /** @export */ Cb: _emwgpuDeviceCreateRenderPipelineAsync,+ /** @export */ dc: _emwgpuDeviceCreateShaderModule,+ /** @export */ cc: _emwgpuDeviceDestroy,+ /** @export */ bc: _emwgpuWaitAny,+ /** @export */ Cc: _environ_get,+ /** @export */ Bc: _environ_sizes_get,+ /** @export */ eb: _exit,+ /** @export */ Oa: _fd_close,+ /** @export */ kb: _fd_read,+ /** @export */ Kb: _fd_seek,+ /** @export */ Na: _fd_write,+ /** @export */ b: _glActiveTexture,+ /** @export */ ta: _glAttachShader,+ /** @export */ ac: _glBindAttribLocation,+ /** @export */ c: _glBindBuffer,+ /** @export */ db: _glBindBufferBase,+ /** @export */ t: _glBindFramebuffer,+ /** @export */ a: _glBindTexture,+ /** @export */ m: _glBindVertexArray,+ /** @export */ cb: _glBlendEquation,+ /** @export */ $b: _glBlendFunc,+ /** @export */ j: _glBufferData,+ /** @export */ I: _glClear,+ /** @export */ H: _glClearColor,+ /** @export */ da: _glClientWaitSync,+ /** @export */ ga: _glColorMask,+ /** @export */ bb: _glCompileShader,+ /** @export */ ab: _glCreateProgram,+ /** @export */ $a: _glCreateShader,+ /** @export */ o: _glDeleteBuffers,+ /** @export */ Q: _glDeleteFramebuffers,+ /** @export */ h: _glDeleteProgram,+ /** @export */ sa: _glDeleteShader,+ /** @export */ ra: _glDeleteSync,+ /** @export */ D: _glDeleteTextures,+ /** @export */ A: _glDeleteVertexArrays,+ /** @export */ _a: _glDetachShader,+ /** @export */ G: _glDisable,+ /** @export */ n: _glDisableVertexAttribArray,+ /** @export */ i: _glDrawArrays,+ /** @export */ fa: _glDrawBuffers,+ /** @export */ _b: _glEnable,+ /** @export */ l: _glEnableVertexAttribArray,+ /** @export */ Za: _glFenceSync,+ /** @export */ qa: _glFinish,+ /** @export */ v: _glFlush,+ /** @export */ C: _glFramebufferTexture2D,+ /** @export */ Ya: _glFramebufferTextureLayer,+ /** @export */ s: _glGenBuffers,+ /** @export */ X: _glGenFramebuffers,+ /** @export */ F: _glGenTextures,+ /** @export */ B: _glGenVertexArrays,+ /** @export */ Xa: _glGetAttribLocation,+ /** @export */ ea: _glGetError,+ /** @export */ Zb: _glGetFloatv,+ /** @export */ w: _glGetIntegerv,+ /** @export */ Yb: _glGetProgramiv,+ /** @export */ Xb: _glGetShaderInfoLog,+ /** @export */ Wb: _glGetShaderiv,+ /** @export */ O: _glGetString,+ /** @export */ Vb: _glGetUniformBlockIndex,+ /** @export */ d: _glGetUniformLocation,+ /** @export */ Ub: _glLineWidth,+ /** @export */ Wa: _glLinkProgram,+ /** @export */ pa: _glPixelStorei,+ /** @export */ oa: _glReadPixels,+ /** @export */ Va: _glShaderSource,+ /** @export */ E: _glTexImage2D,+ /** @export */ na: _glTexParameterf,+ /** @export */ Ua: _glTexParameterfv,+ /** @export */ f: _glTexParameteri,+ /** @export */ ma: _glTexStorage2D,+ /** @export */ Tb: _glTexStorage3D,+ /** @export */ W: _glTexSubImage2D,+ /** @export */ Sb: _glTexSubImage3D,+ /** @export */ N: _glUniform1f,+ /** @export */ la: _glUniform1fv,+ /** @export */ e: _glUniform1i,+ /** @export */ V: _glUniform2f,+ /** @export */ Rb: _glUniform2fv,+ /** @export */ Ia: _glUniform3f,+ /** @export */ Ta: _glUniform4f,+ /** @export */ U: _glUniform4fv,+ /** @export */ Qb: _glUniform4iv,+ /** @export */ Pb: _glUniformBlockBinding,+ /** @export */ Ob: _glUniformMatrix2fv,+ /** @export */ Nb: _glUniformMatrix3fv,+ /** @export */ Ha: _glUniformMatrix4fv,+ /** @export */ g: _glUseProgram,+ /** @export */ k: _glVertexAttribPointer,+ /** @export */ T: _glViewport,+ /** @export */ Ga: hardware_concurrency,+ /** @export */ Bb: mediapipe_create_utility_canvas2d,+ /** @export */ Ab: _mediapipe_find_canvas_event_target,+ /** @export */ zb: mediapipe_import_external_texture,+ /** @export */ xb: _mediapipe_webgl_tex_image_drawable,+ /** @export */ Ac: _proc_exit,+ /** @export */ zc: _random_get,+ /** @export */ Fa: _wgpuCommandEncoderBeginComputePass,+ /** @export */ Ea: _wgpuCommandEncoderBeginRenderPass,+ /** @export */ wb: _wgpuCommandEncoderCopyBufferToTexture,+ /** @export */ vb: _wgpuCommandEncoderCopyTextureToBuffer,+ /** @export */ ub: _wgpuCommandEncoderCopyTextureToTexture,+ /** @export */ M: _wgpuCommandEncoderFinish,+ /** @export */ Da: _wgpuComputePassEncoderDispatchWorkgroups,+ /** @export */ Ca: _wgpuComputePassEncoderEnd,+ /** @export */ Ba: _wgpuComputePassEncoderSetBindGroup,+ /** @export */ Aa: _wgpuComputePassEncoderSetPipeline,+ /** @export */ za: _wgpuComputePipelineGetBindGroupLayout,+ /** @export */ ca: _wgpuDeviceCreateBindGroup,+ /** @export */ tb: _wgpuDeviceCreateBindGroupLayout,+ /** @export */ L: _wgpuDeviceCreateCommandEncoder,+ /** @export */ sb: _wgpuDeviceCreateComputePipeline,+ /** @export */ rb: _wgpuDeviceCreatePipelineLayout,+ /** @export */ Sa: _wgpuDeviceCreateRenderPipeline,+ /** @export */ S: _wgpuDeviceCreateSampler,+ /** @export */ ba: _wgpuDeviceCreateTexture,+ /** @export */ K: _wgpuQueueSubmit,+ /** @export */ ka: _wgpuQueueWriteBuffer,+ /** @export */ qb: _wgpuQueueWriteTexture,+ /** @export */ ya: _wgpuRenderPassEncoderDraw,+ /** @export */ xa: _wgpuRenderPassEncoderEnd,+ /** @export */ wa: _wgpuRenderPassEncoderSetBindGroup,+ /** @export */ va: _wgpuRenderPassEncoderSetPipeline,+ /** @export */ Ra: _wgpuRenderPipelineGetBindGroupLayout,+ /** @export */ z: _wgpuTextureCreateView,+ /** @export */ Qa: _wgpuTextureDestroy,+ /** @export */ aa: _wgpuTextureGetFormat+};++// include: postamble.js+// === Auto-generated postamble setup entry stuff ===+function run() {+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ preRun();+ // a preRun added a dependency, run will be called later+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ function doRun() {+ // run may have just been called through dependencies being fulfilled just in this very frame,+ // or while the async setStatus time below was happening+ Module["calledRun"] = true;+ if (ABORT) return;+ initRuntime();+ readyPromiseResolve?.(Module);+ Module["onRuntimeInitialized"]?.();+ postRun();+ }+ if (Module["setStatus"]) {+ Module["setStatus"]("Running...");+ setTimeout(() => {+ setTimeout(() => Module["setStatus"](""), 1);+ doRun();+ }, 1);+ } else {+ doRun();+ }+}++var wasmExports;++// In modularize mode the generated code is within a factory function so we+// can use await here (since it's not top-level-await).+wasmExports = await (createWasm());++run();++// end include: postamble.js+// include: postamble_modularize.js+// In MODULARIZE mode we wrap the generated code in a factory function+// and return either the Module itself, or a promise of the module.+// We assign to the `moduleRtn` global here and configure closure to see+// this as an extern so it won't get minified.+if (runtimeInitialized) {+ moduleRtn = Module;+} else {+ // Set up the promise that indicates the Module is initialized+ moduleRtn = new Promise((resolve, reject) => {+ readyPromiseResolve = resolve;+ readyPromiseReject = reject;+ });+}+++ return moduleRtn;+ };+})();++// Export using a UMD style export, or ES6 exports if selected+if (typeof exports === 'object' && typeof module === 'object') {+ module.exports = ModuleFactory;+ // This default export looks redundant, but it allows TS to import this+ // commonjs style module.+ module.exports.default = ModuleFactory;+} else if (typeof define === 'function' && define['amd'])+ define([], () => ModuleFactory);+diff --git a/public/vendor/mediapipe/wasm/vision_wasm_internal.wasm b/public/vendor/mediapipe/wasm/vision_wasm_internal.wasmnew file mode 100644index 000000000..7ca3e0582Binary files /dev/null and b/public/vendor/mediapipe/wasm/vision_wasm_internal.wasm differdiff --git a/public/vendor/mediapipe/wasm/vision_wasm_module_internal.js b/public/vendor/mediapipe/wasm/vision_wasm_module_internal.jsnew file mode 100644index 000000000..8cd573002--- /dev/null+++ b/public/vendor/mediapipe/wasm/vision_wasm_module_internal.js@@ -0,0 +1,8823 @@+// This code implements the `-sMODULARIZE` settings by taking the generated+// JS program code (INNER_JS_CODE) and wrapping it in a factory function.++// When targeting node and ES6 we use `await import ..` in the generated code+// so the outer function needs to be marked as async.+async function ModuleFactory(moduleArg = {}) {+ var moduleRtn;++// include: shell.js+// include: minimum_runtime_check.js+// end include: minimum_runtime_check.js+// The Module object: Our interface to the outside world. We import+// and export values on it. There are various ways Module can be used:+// 1. Not defined. We create it here+// 2. A function parameter, function(moduleArg) => Promise<Module>+// 3. pre-run appended it, var Module = {}; ..generated code..+// 4. External script tag defines var Module.+// We need to check if Module already exists (e.g. case 3 above).+// Substitution will be replaced with actual code on later stage of the build,+// this way Closure Compiler will not mangle it (e.g. case 4. above).+// Note that if you want to run closure, and also to use Module+// after the generated code, you will need to define var Module = {};+// before the code. Then that object will be used in the code, and you+// can continue to use Module afterwards as well.+var Module = moduleArg;++// Determine the runtime environment we are in. You can customize this by+// setting the ENVIRONMENT setting at compile time (see settings.js).+// Attempt to auto-detect the environment+var ENVIRONMENT_IS_WEB = !!globalThis.window;++var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;++// N.b. Electron.js environment is simultaneously a NODE-environment, but+// also a web environment.+var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer";++if (ENVIRONMENT_IS_NODE) {+ // When building an ES module `require` is not normally available.+ // We need to use `createRequire()` to construct the require()` function.+ const {createRequire} = await import("node:module");+ /** @suppress{duplicate} */ var require = createRequire(import.meta.url);+}++// --pre-jses are emitted after the Module integration code, so that they can+// refer to Module (if they choose; they can also define Module)+var arguments_ = [];++var thisProgram = "./this.program";++var quit_ = (status, toThrow) => {+ throw toThrow;+};++var _scriptName = import.meta.url;++// `/` should be present at the end if `scriptDirectory` is not empty+var scriptDirectory = "";++function locateFile(path) {+ if (Module["locateFile"]) {+ return Module["locateFile"](path, scriptDirectory);+ }+ return scriptDirectory + path;+}++// Hooks that are implemented differently in different runtime environments.+var readAsync, readBinary;++if (ENVIRONMENT_IS_NODE) {+ // These modules will usually be used on Node.js. Load them eagerly to avoid+ // the complexity of lazy-loading.+ var fs = require("node:fs");+ if (_scriptName.startsWith("file:")) {+ scriptDirectory = require("node:path").dirname(require("node:url").fileURLToPath(_scriptName)) + "/";+ }+ // include: node_shell_read.js+ readBinary = filename => {+ // We need to re-wrap `file://` strings to URLs.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename);+ return ret;+ };+ readAsync = async (filename, binary = true) => {+ // See the comment in the `readBinary` function.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename, binary ? undefined : "utf8");+ return ret;+ };+ // end include: node_shell_read.js+ if (process.argv.length > 1) {+ thisProgram = process.argv[1].replace(/\\/g, "/");+ }+ arguments_ = process.argv.slice(2);+ quit_ = (status, toThrow) => {+ process.exitCode = status;+ throw toThrow;+ };+} else // Note that this includes Node.js workers when relevant (pthreads is enabled).+// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and+// ENVIRONMENT_IS_NODE.+if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {+ try {+ scriptDirectory = new URL(".", _scriptName).href;+ } catch {}+ {+ // include: web_or_worker_shell_read.js+ if (ENVIRONMENT_IS_WORKER) {+ readBinary = url => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ xhr.responseType = "arraybuffer";+ xhr.send(null);+ return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));+ };+ }+ readAsync = async url => {+ // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.+ // See https://github.com/github/fetch/pull/92#issuecomment-140665932+ // Cordova or Electron apps are typically loaded from a file:// url.+ // So use XHR on webview if URL is a file URL.+ if (isFileURI(url)) {+ return new Promise((resolve, reject) => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, true);+ xhr.responseType = "arraybuffer";+ xhr.onload = () => {+ if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {+ // file URLs can return 0+ resolve(xhr.response);+ return;+ }+ reject(xhr.status);+ };+ xhr.onerror = reject;+ xhr.send(null);+ });+ }+ var response = await fetch(url, {+ credentials: "same-origin"+ });+ if (response.ok) {+ return response.arrayBuffer();+ }+ throw new Error(response.status + " : " + response.url);+ };+ }+} else {}++var out = console.log.bind(console);++var err = console.error.bind(console);++// end include: shell.js+// include: preamble.js+// === Preamble library stuff ===+// Documentation for the public APIs defined in this file must be updated in:+// site/source/docs/api_reference/preamble.js.rst+// A prebuilt local version of the documentation is available at:+// site/build/text/docs/api_reference/preamble.js.txt+// You can also build docs locally as HTML or other formats in site/+// An online HTML version (which may be of a different version of Emscripten)+// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html+var wasmBinary;++// Wasm globals+//========================================+// Runtime essentials+//========================================+// whether we are quitting the application. no code should run after this.+// set in exit() and abort()+var ABORT = false;++// set by exit() and abort(). Passed to 'onExit' handler.+// NOTE: This is also used as the process return code in shell environments+// but only when noExitRuntime is false.+var EXITSTATUS;++// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we+// don't define it at all in release modes. This matches the behaviour of+// MINIMAL_RUNTIME.+// TODO(sbc): Make this the default even without STRICT enabled.+/** @type {function(*, string=)} */ function assert(condition, text) {+ if (!condition) {+ // This build was created without ASSERTIONS defined. `assert()` should not+ // ever be called in this configuration but in case there are callers in+ // the wild leave this simple abort() implementation here for now.+ abort(text);+ }+}++/**+ * Indicates whether filename is delivered via file protocol (as opposed to http/https)+ * @noinline+ */ var isFileURI = filename => filename.startsWith("file://");++// include: runtime_common.js+// include: runtime_stack_check.js+// end include: runtime_stack_check.js+// include: runtime_exceptions.js+// Base Emscripten EH error class+class EmscriptenEH {}++class EmscriptenSjLj extends EmscriptenEH {}++// end include: runtime_exceptions.js+// include: runtime_debug.js+// end include: runtime_debug.js+var readyPromiseResolve, readyPromiseReject;++// Memory management+var runtimeInitialized = false;++function updateMemoryViews() {+ var b = wasmMemory.buffer;+ HEAP8 = new Int8Array(b);+ HEAP16 = new Int16Array(b);+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);+ HEAPU16 = new Uint16Array(b);+ HEAP32 = new Int32Array(b);+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);+ Module["HEAPF32"] = HEAPF32 = new Float32Array(b);+ Module["HEAPF64"] = HEAPF64 = new Float64Array(b);+}++// include: memoryprofiler.js+// end include: memoryprofiler.js+// end include: runtime_common.js+function preRun() {+ if (Module["preRun"]) {+ if (typeof Module["preRun"] == "function") Module["preRun"] = [ Module["preRun"] ];+ while (Module["preRun"].length) {+ addOnPreRun(Module["preRun"].shift());+ }+ }+ // Begin ATPRERUNS hooks+ callRuntimeCallbacks(onPreRuns);+}++function initRuntime() {+ runtimeInitialized = true;+ // Begin ATINITS hooks+ if (!Module["noFSInit"] && !FS.initialized) FS.init();+ TTY.init();+ // End ATINITS hooks+ wasmExports["jd"]();+ // Begin ATPOSTCTORS hooks+ FS.ignorePermissions = false;+}++function postRun() {+ // PThreads reuse the runtime from the main thread.+ if (Module["postRun"]) {+ if (typeof Module["postRun"] == "function") Module["postRun"] = [ Module["postRun"] ];+ while (Module["postRun"].length) {+ addOnPostRun(Module["postRun"].shift());+ }+ }+ // Begin ATPOSTRUNS hooks+ callRuntimeCallbacks(onPostRuns);+}++/**+ * @param {string|number=} what+ */ function abort(what) {+ Module["onAbort"]?.(what);+ what = `Aborted(${what})`;+ // TODO(sbc): Should we remove printing and leave it up to whoever+ // catches the exception?+ err(what);+ ABORT = true;+ what += ". Build with -sASSERTIONS for more info.";+ // Use a wasm runtime error, because a JS error might be seen as a foreign+ // exception, which means we'd run destructors on it. We need the error to+ // simply make the program stop.+ // FIXME This approach does not work in Wasm EH because it currently does not assume+ // all RuntimeErrors are from traps; it decides whether a RuntimeError is from+ // a trap or not based on a hidden field within the object. So at the moment+ // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that+ // allows this in the wasm spec.+ // Suppress closure compiler warning here. Closure compiler's builtin extern+ // definition for WebAssembly.RuntimeError claims it takes no arguments even+ // though it can.+ // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.+ /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);+ readyPromiseReject?.(e);+ // Throw the error whether or not MODULARIZE is set because abort is used+ // in code paths apart from instantiation where an exception is expected+ // to be thrown when abort is called.+ throw e;+}++var wasmBinaryFile;++function findWasmBinary() {+ if (Module["locateFile"]) {+ return locateFile("vision_wasm_module_raw_internal.wasm");+ }+ // Use bundler-friendly `new URL(..., import.meta.url)` pattern; works in browsers too.+ return new URL("vision_wasm_module_raw_internal.wasm", import.meta.url).href;+}++function getBinarySync(file) {+ if (file == wasmBinaryFile && wasmBinary) {+ return new Uint8Array(wasmBinary);+ }+ if (readBinary) {+ return readBinary(file);+ }+ // Throwing a plain string here, even though it not normally advisable since+ // this gets turning into an `abort` in instantiateArrayBuffer.+ throw "both async and sync fetching of the wasm failed";+}++async function getWasmBinary(binaryFile) {+ // If we don't have the binary yet, load it asynchronously using readAsync.+ if (!wasmBinary) {+ // Fetch the binary using readAsync+ try {+ var response = await readAsync(binaryFile);+ return new Uint8Array(response);+ } catch {}+ }+ // Otherwise, getBinarySync should be able to get it synchronously+ return getBinarySync(binaryFile);+}++async function instantiateArrayBuffer(binaryFile, imports) {+ try {+ var binary = await getWasmBinary(binaryFile);+ var instance = await WebAssembly.instantiate(binary, imports);+ return instance;+ } catch (reason) {+ err(`failed to asynchronously prepare wasm: ${reason}`);+ abort(reason);+ }+}++async function instantiateAsync(binary, binaryFile, imports) {+ if (!binary && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {+ try {+ var response = fetch(binaryFile, {+ credentials: "same-origin"+ });+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);+ return instantiationResult;+ } catch (reason) {+ // We expect the most common failure cause to be a bad MIME type for the binary,+ // in which case falling back to ArrayBuffer instantiation should work.+ err(`wasm streaming compile failed: ${reason}`);+ err("falling back to ArrayBuffer instantiation");+ }+ }+ return instantiateArrayBuffer(binaryFile, imports);+}++function getWasmImports() {+ // prepare imports+ var imports = {+ "a": wasmImports+ };+ return imports;+}++// Create the wasm instance.+// Receives the wasm imports, returns the exports.+async function createWasm() {+ // Load the wasm module and create an instance of using native support in the JS engine.+ // handle a generated wasm instance, receiving its exports and+ // performing other necessary setup+ /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) {+ wasmExports = instance.exports;+ assignWasmExports(wasmExports);+ updateMemoryViews();+ return wasmExports;+ }+ // Prefer streaming instantiation if available.+ function receiveInstantiationResult(result) {+ // 'result' is a ResultObject object which has both the module and instance.+ // receiveInstance() will swap in the exports (to Module.asm) so they can be called+ // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.+ // When the regression is fixed, can restore the above PTHREADS-enabled path.+ return receiveInstance(result["instance"]);+ }+ var info = getWasmImports();+ // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback+ // to manually instantiate the Wasm module themselves. This allows pages to+ // run the instantiation parallel to any other async startup actions they are+ // performing.+ // Also pthreads and wasm workers initialize the wasm instance through this+ // path.+ if (Module["instantiateWasm"]) {+ return new Promise((resolve, reject) => {+ Module["instantiateWasm"](info, (inst, mod) => {+ resolve(receiveInstance(inst, mod));+ });+ });+ }+ wasmBinaryFile ??= findWasmBinary();+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);+ var exports = receiveInstantiationResult(result);+ return exports;+}++// Globals used by JS i64 conversions (see makeSetValue)+var tempDouble;++var tempI64;++// end include: preamble.js+// Begin JS library code+var handleException = e => {+ // Certain exception types we do not treat as errors since they are used for+ // internal control flow.+ // 1. ExitStatus, which is thrown by exit()+ // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others+ // that wish to return to JS event loop.+ if (e instanceof ExitStatus || e == "unwind") {+ return EXITSTATUS;+ }+ quit_(1, e);+};++class ExitStatus {+ name="ExitStatus";+ constructor(status) {+ this.message = `Program terminated with exit(${status})`;+ this.status = status;+ }+}++var runtimeKeepaliveCounter = 0;++var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;++var _proc_exit = code => {+ EXITSTATUS = code;+ if (!keepRuntimeAlive()) {+ Module["onExit"]?.(code);+ ABORT = true;+ }+ quit_(code, new ExitStatus(code));+};++/** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => {+ EXITSTATUS = status;+ _proc_exit(status);+};++var _exit = exitJS;++var maybeExit = () => {+ if (!keepRuntimeAlive()) {+ try {+ _exit(EXITSTATUS);+ } catch (e) {+ handleException(e);+ }+ }+};++var callUserCallback = func => {+ if (ABORT) {+ return;+ }+ try {+ return func();+ } catch (e) {+ handleException(e);+ } finally {+ maybeExit();+ }+};++function getFullscreenElement() {+ return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.webkitCurrentFullScreenElement || document.msFullscreenElement;+}++/** @param {number=} timeout */ var safeSetTimeout = (func, timeout) => setTimeout(() => {+ callUserCallback(func);+}, timeout);++var warnOnce = text => {+ warnOnce.shown ||= {};+ if (!warnOnce.shown[text]) {+ warnOnce.shown[text] = 1;+ if (ENVIRONMENT_IS_NODE) text = "warning: " + text;+ err(text);+ }+};++var preloadPlugins = [];++var Browser = {+ useWebGL: false,+ isFullscreen: false,+ pointerLock: false,+ moduleContextCreatedCallbacks: [],+ workers: [],+ preloadedImages: {},+ preloadedAudios: {},+ getCanvas: () => Module["canvas"],+ init() {+ if (Browser.initted) return;+ Browser.initted = true;+ // Support for plugins that can process preloaded files. You can add more of these to+ // your app by creating and appending to preloadPlugins.+ // Each plugin is asked if it can handle a file based on the file's name. If it can,+ // it is given the file's raw data. When it is done, it calls a callback with the file's+ // (possibly modified) data. For example, a plugin might decompress a file, or it+ // might create some side data structure for use later (like an Image element, etc.).+ var imagePlugin = {};+ imagePlugin["canHandle"] = name => !Module["noImageDecoding"] && /\.(jpg|jpeg|png|bmp|webp)$/i.test(name);+ imagePlugin["handle"] = async (byteArray, name) => {+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ if (b.size !== byteArray.length) {+ // Safari bug #118630+ // Safari's Blob can only take an ArrayBuffer+ b = new Blob([ (new Uint8Array(byteArray)).buffer ], {+ type: Browser.getMimetype(name)+ });+ }+ var url = URL.createObjectURL(b);+ return new Promise((resolve, reject) => {+ var img = new Image;+ img.onload = () => {+ var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement("canvas"));+ canvas.width = img.width;+ canvas.height = img.height;+ var ctx = canvas.getContext("2d");+ ctx.drawImage(img, 0, 0);+ Browser.preloadedImages[name] = canvas;+ URL.revokeObjectURL(url);+ resolve(byteArray);+ };+ img.onerror = event => {+ err(`Image ${url} could not be decoded`);+ reject();+ };+ img.src = url;+ });+ };+ preloadPlugins.push(imagePlugin);+ var audioPlugin = {};+ audioPlugin["canHandle"] = name => !Module["noAudioDecoding"] && name.slice(-4) in {+ ".ogg": 1,+ ".wav": 1,+ ".mp3": 1+ };+ audioPlugin["handle"] = async (byteArray, name) => new Promise((resolve, reject) => {+ var done = false;+ function finish(audio) {+ if (done) return;+ done = true;+ Browser.preloadedAudios[name] = audio;+ resolve(byteArray);+ }+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ var url = URL.createObjectURL(b);+ // XXX we never revoke this!+ var audio = new Audio;+ audio.addEventListener("canplaythrough", () => finish(audio), false);+ // use addEventListener due to chromium bug 124926+ audio.onerror = event => {+ if (done) return;+ err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);+ function encode64(data) {+ var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ var PAD = "=";+ var ret = "";+ var leftchar = 0;+ var leftbits = 0;+ for (var i = 0; i < data.length; i++) {+ leftchar = (leftchar << 8) | data[i];+ leftbits += 8;+ while (leftbits >= 6) {+ var curr = (leftchar >> (leftbits - 6)) & 63;+ leftbits -= 6;+ ret += BASE[curr];+ }+ }+ if (leftbits == 2) {+ ret += BASE[(leftchar & 3) << 4];+ ret += PAD + PAD;+ } else if (leftbits == 4) {+ ret += BASE[(leftchar & 15) << 2];+ ret += PAD;+ }+ return ret;+ }+ audio.src = "data:audio/x-" + name.slice(-3) + ";base64," + encode64(byteArray);+ finish(audio);+ };+ audio.src = url;+ // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror+ safeSetTimeout(() => {+ finish(audio);+ }, 1e4);+ });+ preloadPlugins.push(audioPlugin);+ // Canvas event setup+ function pointerLockChange() {+ var canvas = Browser.getCanvas();+ Browser.pointerLock = document.pointerLockElement === canvas;+ }+ var canvas = Browser.getCanvas();+ if (canvas) {+ // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module+ // Module['forcedAspectRatio'] = 4 / 3;+ document.addEventListener("pointerlockchange", pointerLockChange, false);+ if (Module["elementPointerLock"]) {+ canvas.addEventListener("click", ev => {+ if (!Browser.pointerLock && Browser.getCanvas().requestPointerLock) {+ Browser.getCanvas().requestPointerLock();+ ev.preventDefault();+ }+ }, false);+ }+ }+ },+ createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) {+ if (useWebGL && Module["ctx"] && canvas == Browser.getCanvas()) return Module["ctx"];+ // no need to recreate GL context if it's already been created for this canvas.+ var ctx;+ var contextHandle;+ if (useWebGL) {+ // For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.+ var contextAttributes = {+ antialias: false,+ alpha: false,+ majorVersion: (typeof WebGL2RenderingContext != "undefined") ? 2 : 1+ };+ if (webGLContextAttributes) {+ for (var attribute in webGLContextAttributes) {+ contextAttributes[attribute] = webGLContextAttributes[attribute];+ }+ }+ // This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not+ // actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function+ // Browser.createContext() should not even be emitted.+ if (typeof GL != "undefined") {+ contextHandle = GL.createContext(canvas, contextAttributes);+ if (contextHandle) {+ ctx = GL.getContext(contextHandle).GLctx;+ }+ }+ } else {+ ctx = canvas.getContext("2d");+ }+ if (!ctx) return null;+ if (setInModule) {+ Module["ctx"] = ctx;+ if (useWebGL) GL.makeContextCurrent(contextHandle);+ Browser.useWebGL = useWebGL;+ Browser.moduleContextCreatedCallbacks.forEach(callback => callback());+ Browser.init();+ }+ return ctx;+ },+ fullscreenHandlersInstalled: false,+ lockPointer: undefined,+ resizeCanvas: undefined,+ requestFullscreen(lockPointer, resizeCanvas) {+ Browser.lockPointer = lockPointer;+ Browser.resizeCanvas = resizeCanvas;+ if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true;+ if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false;+ var canvas = Browser.getCanvas();+ function fullscreenChange() {+ Browser.isFullscreen = false;+ var canvasContainer = canvas.parentNode;+ if (getFullscreenElement() === canvasContainer) {+ canvas.exitFullscreen = Browser.exitFullscreen;+ if (Browser.lockPointer) canvas.requestPointerLock();+ Browser.isFullscreen = true;+ if (Browser.resizeCanvas) {+ Browser.setFullscreenCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ } else {+ // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen+ canvasContainer.parentNode.insertBefore(canvas, canvasContainer);+ canvasContainer.parentNode.removeChild(canvasContainer);+ if (Browser.resizeCanvas) {+ Browser.setWindowedCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ }+ Module["onFullScreen"]?.(Browser.isFullscreen);+ Module["onFullscreen"]?.(Browser.isFullscreen);+ }+ if (!Browser.fullscreenHandlersInstalled) {+ Browser.fullscreenHandlersInstalled = true;+ document.addEventListener("fullscreenchange", fullscreenChange, false);+ document.addEventListener("mozfullscreenchange", fullscreenChange, false);+ document.addEventListener("webkitfullscreenchange", fullscreenChange, false);+ document.addEventListener("MSFullscreenChange", fullscreenChange, false);+ }+ // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root+ var canvasContainer = document.createElement("div");+ canvas.parentNode.insertBefore(canvasContainer, canvas);+ canvasContainer.appendChild(canvas);+ // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)+ canvasContainer.requestFullscreen = canvasContainer["requestFullscreen"] || canvasContainer["mozRequestFullScreen"] || canvasContainer["msRequestFullscreen"] || (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null) || (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null);+ canvasContainer.requestFullscreen();+ },+ exitFullscreen() {+ // This is workaround for chrome. Trying to exit from fullscreen+ // not in fullscreen state will cause "TypeError: Document not active"+ // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236+ if (!Browser.isFullscreen) {+ return false;+ }+ var CFS = document["exitFullscreen"] || document["cancelFullScreen"] || document["mozCancelFullScreen"] || document["msExitFullscreen"] || document["webkitCancelFullScreen"] || (() => {});+ CFS.apply(document, []);+ return true;+ },+ safeSetTimeout(func, timeout) {+ // Legacy function, this is used by the SDL2 port so we need to keep it+ // around at least until that is updated.+ // See https://github.com/libsdl-org/SDL/pull/6304+ return safeSetTimeout(func, timeout);+ },+ getMimetype(name) {+ return {+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "png": "image/png",+ "bmp": "image/bmp",+ "ogg": "audio/ogg",+ "wav": "audio/wav",+ "mp3": "audio/mpeg"+ }[name.slice(name.lastIndexOf(".") + 1)];+ },+ getUserMedia(func) {+ window.getUserMedia ||= navigator["getUserMedia"] || navigator["mozGetUserMedia"];+ window.getUserMedia(func);+ },+ getMovementX(event) {+ return event["movementX"] || event["mozMovementX"] || event["webkitMovementX"] || 0;+ },+ getMovementY(event) {+ return event["movementY"] || event["mozMovementY"] || event["webkitMovementY"] || 0;+ },+ getMouseWheelDelta(event) {+ var delta = 0;+ switch (event.type) {+ case "DOMMouseScroll":+ // 3 lines make up a step+ delta = event.detail / 3;+ break;++ case "mousewheel":+ // 120 units make up a step+ delta = event.wheelDelta / 120;+ break;++ case "wheel":+ delta = event.deltaY;+ switch (event.deltaMode) {+ case 0:+ // DOM_DELTA_PIXEL: 100 pixels make up a step+ delta /= 100;+ break;++ case 1:+ // DOM_DELTA_LINE: 3 lines make up a step+ delta /= 3;+ break;++ case 2:+ // DOM_DELTA_PAGE: A page makes up 80 steps+ delta *= 80;+ break;++ default:+ abort("unrecognized mouse wheel delta mode: " + event.deltaMode);+ }+ break;++ default:+ abort("unrecognized mouse wheel event: " + event.type);+ }+ return delta;+ },+ mouseX: 0,+ mouseY: 0,+ mouseMovementX: 0,+ mouseMovementY: 0,+ touches: {},+ lastTouches: {},+ calculateMouseCoords(pageX, pageY) {+ // Calculate the movement based on the changes+ // in the coordinates.+ var canvas = Browser.getCanvas();+ var rect = canvas.getBoundingClientRect();+ // Neither .scrollX or .pageXOffset are defined in a spec, but+ // we prefer .scrollX because it is currently in a spec draft.+ // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)+ var scrollX = ((typeof window.scrollX != "undefined") ? window.scrollX : window.pageXOffset);+ var scrollY = ((typeof window.scrollY != "undefined") ? window.scrollY : window.pageYOffset);+ var adjustedX = pageX - (scrollX + rect.left);+ var adjustedY = pageY - (scrollY + rect.top);+ // the canvas might be CSS-scaled compared to its backbuffer;+ // SDL-using content will want mouse coordinates in terms+ // of backbuffer units.+ adjustedX = adjustedX * (canvas.width / rect.width);+ adjustedY = adjustedY * (canvas.height / rect.height);+ return {+ x: adjustedX,+ y: adjustedY+ };+ },+ setMouseCoords(pageX, pageY) {+ const {x, y} = Browser.calculateMouseCoords(pageX, pageY);+ Browser.mouseMovementX = x - Browser.mouseX;+ Browser.mouseMovementY = y - Browser.mouseY;+ Browser.mouseX = x;+ Browser.mouseY = y;+ },+ calculateMouseEvent(event) {+ // event should be mousemove, mousedown or mouseup+ if (Browser.pointerLock) {+ // When the pointer is locked, calculate the coordinates+ // based on the movement of the mouse.+ // Workaround for Firefox bug 764498+ if (event.type != "mousemove" && ("mozMovementX" in event)) {+ Browser.mouseMovementX = Browser.mouseMovementY = 0;+ } else {+ Browser.mouseMovementX = Browser.getMovementX(event);+ Browser.mouseMovementY = Browser.getMovementY(event);+ }+ // add the mouse delta to the current absolute mouse position+ Browser.mouseX += Browser.mouseMovementX;+ Browser.mouseY += Browser.mouseMovementY;+ } else {+ if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") {+ var touch = event.touch;+ if (touch === undefined) {+ return;+ }+ var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY);+ if (event.type === "touchstart") {+ Browser.lastTouches[touch.identifier] = coords;+ Browser.touches[touch.identifier] = coords;+ } else if (event.type === "touchend" || event.type === "touchmove") {+ var last = Browser.touches[touch.identifier];+ last ||= coords;+ Browser.lastTouches[touch.identifier] = last;+ Browser.touches[touch.identifier] = coords;+ }+ return;+ }+ Browser.setMouseCoords(event.pageX, event.pageY);+ }+ },+ resizeListeners: [],+ updateResizeListeners() {+ var canvas = Browser.getCanvas();+ Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height));+ },+ setCanvasSize(width, height, noUpdates) {+ var canvas = Browser.getCanvas();+ Browser.updateCanvasDimensions(canvas, width, height);+ if (!noUpdates) Browser.updateResizeListeners();+ },+ windowedWidth: 0,+ windowedHeight: 0,+ setFullscreenCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags | 8388608;+ // set SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ setWindowedCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags & ~8388608;+ // clear SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ updateCanvasDimensions(canvas, wNative, hNative) {+ if (wNative && hNative) {+ canvas.widthNative = wNative;+ canvas.heightNative = hNative;+ } else {+ wNative = canvas.widthNative;+ hNative = canvas.heightNative;+ }+ var w = wNative;+ var h = hNative;+ if (Module["forcedAspectRatio"] > 0) {+ if (w / h < Module["forcedAspectRatio"]) {+ w = Math.round(h * Module["forcedAspectRatio"]);+ } else {+ h = Math.round(w / Module["forcedAspectRatio"]);+ }+ }+ if ((getFullscreenElement() === canvas.parentNode) && (typeof screen != "undefined")) {+ var factor = Math.min(screen.width / w, screen.height / h);+ w = Math.round(w * factor);+ h = Math.round(h * factor);+ }+ if (Browser.resizeCanvas) {+ if (canvas.width != w) canvas.width = w;+ if (canvas.height != h) canvas.height = h;+ if (typeof canvas.style != "undefined") {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ } else {+ if (canvas.width != wNative) canvas.width = wNative;+ if (canvas.height != hNative) canvas.height = hNative;+ if (typeof canvas.style != "undefined") {+ if (w != wNative || h != hNative) {+ canvas.style.setProperty("width", w + "px", "important");+ canvas.style.setProperty("height", h + "px", "important");+ } else {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ }+ }+ }+};++/** @type {!Int16Array} */ var HEAP16;++/** @type {!Int32Array} */ var HEAP32;++/** @type {!Int8Array} */ var HEAP8;++/** @type {!Float32Array} */ var HEAPF32;++/** @type {!Float64Array} */ var HEAPF64;++/** @type {!Uint16Array} */ var HEAPU16;++/** @type {!Uint32Array} */ var HEAPU32;++/** @type {!Uint8Array} */ var HEAPU8;++var callRuntimeCallbacks = callbacks => {+ while (callbacks.length > 0) {+ // Pass the module as the first argument.+ callbacks.shift()(Module);+ }+};++var onPostRuns = [];++var addOnPostRun = cb => onPostRuns.push(cb);++var onPreRuns = [];++var addOnPreRun = cb => onPreRuns.push(cb);++var noExitRuntime = true;++var stackRestore = val => __emscripten_stack_restore(val);++var stackSave = () => _emscripten_stack_get_current();++class ExceptionInfo {+ // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.+ constructor(excPtr) {+ this.excPtr = excPtr;+ this.ptr = excPtr - 24;+ }+ set_type(type) {+ HEAPU32[(((this.ptr) + (4)) >> 2)] = type;+ }+ get_type() {+ return HEAPU32[(((this.ptr) + (4)) >> 2)];+ }+ set_destructor(destructor) {+ HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor;+ }+ get_destructor() {+ return HEAPU32[(((this.ptr) + (8)) >> 2)];+ }+ set_caught(caught) {+ caught = caught ? 1 : 0;+ HEAP8[(this.ptr) + (12)] = caught;+ }+ get_caught() {+ return HEAP8[(this.ptr) + (12)] != 0;+ }+ set_rethrown(rethrown) {+ rethrown = rethrown ? 1 : 0;+ HEAP8[(this.ptr) + (13)] = rethrown;+ }+ get_rethrown() {+ return HEAP8[(this.ptr) + (13)] != 0;+ }+ // Initialize native structure fields. Should be called once after allocated.+ init(type, destructor) {+ this.set_adjusted_ptr(0);+ this.set_type(type);+ this.set_destructor(destructor);+ }+ set_adjusted_ptr(adjustedPtr) {+ HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr;+ }+ get_adjusted_ptr() {+ return HEAPU32[(((this.ptr) + (16)) >> 2)];+ }+}++var uncaughtExceptionCount = 0;++var ___cxa_throw = (ptr, type, destructor) => {+ var info = new ExceptionInfo(ptr);+ // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.+ info.init(type, destructor);+ uncaughtExceptionCount++;+ abort();+};++var PATH = {+ isAbs: path => path.charAt(0) === "/",+ splitPath: filename => {+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;+ return splitPathRe.exec(filename).slice(1);+ },+ normalizeArray: (parts, allowAboveRoot) => {+ // if the path tries to go above the root, `up` ends up > 0+ var up = 0;+ for (var i = parts.length - 1; i >= 0; i--) {+ var last = parts[i];+ if (last === ".") {+ parts.splice(i, 1);+ } else if (last === "..") {+ parts.splice(i, 1);+ up++;+ } else if (up) {+ parts.splice(i, 1);+ up--;+ }+ }+ // if the path is allowed to go above the root, restore leading ..s+ if (allowAboveRoot) {+ for (;up; up--) {+ parts.unshift("..");+ }+ }+ return parts;+ },+ normalize: path => {+ var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/";+ // Normalize the path+ path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");+ if (!path && !isAbsolute) {+ path = ".";+ }+ if (path && trailingSlash) {+ path += "/";+ }+ return (isAbsolute ? "/" : "") + path;+ },+ dirname: path => {+ var result = PATH.splitPath(path), root = result[0], dir = result[1];+ if (!root && !dir) {+ // No dirname whatsoever+ return ".";+ }+ if (dir) {+ // It has a dirname, strip trailing slash+ dir = dir.slice(0, -1);+ }+ return root + dir;+ },+ basename: path => path && path.match(/([^\/]+|\/)\/*$/)[1],+ join: (...paths) => PATH.normalize(paths.join("/")),+ join2: (l, r) => PATH.normalize(l + "/" + r)+};++var initRandomFill = () => {+ // This block is not needed on v19+ since crypto.getRandomValues is builtin+ if (ENVIRONMENT_IS_NODE) {+ var nodeCrypto = require("node:crypto");+ return view => nodeCrypto.randomFillSync(view);+ }+ return view => (crypto.getRandomValues(view), 0);+};++var randomFill = view => (randomFill = initRandomFill())(view);++var PATH_FS = {+ resolve: (...args) => {+ var resolvedPath = "", resolvedAbsolute = false;+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {+ var path = (i >= 0) ? args[i] : FS.cwd();+ // Skip empty and invalid entries+ if (typeof path != "string") {+ throw new TypeError("Arguments to path.resolve must be strings");+ } else if (!path) {+ return "";+ }+ resolvedPath = path + "/" + resolvedPath;+ resolvedAbsolute = PATH.isAbs(path);+ }+ // At this point the path should be resolved to a full absolute path, but+ // handle relative paths to be safe (might happen when process.cwd() fails)+ resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");+ return ((resolvedAbsolute ? "/" : "") + resolvedPath) || ".";+ },+ relative: (from, to) => {+ from = PATH_FS.resolve(from).slice(1);+ to = PATH_FS.resolve(to).slice(1);+ function trim(arr) {+ var start = 0;+ for (;start < arr.length; start++) {+ if (arr[start] !== "") break;+ }+ var end = arr.length - 1;+ for (;end >= 0; end--) {+ if (arr[end] !== "") break;+ }+ if (start > end) return [];+ return arr.slice(start, end - start + 1);+ }+ var fromParts = trim(from.split("/"));+ var toParts = trim(to.split("/"));+ var length = Math.min(fromParts.length, toParts.length);+ var samePartsLength = length;+ for (var i = 0; i < length; i++) {+ if (fromParts[i] !== toParts[i]) {+ samePartsLength = i;+ break;+ }+ }+ var outputParts = [];+ for (var i = samePartsLength; i < fromParts.length; i++) {+ outputParts.push("..");+ }+ outputParts = outputParts.concat(toParts.slice(samePartsLength));+ return outputParts.join("/");+ }+};++var UTF8Decoder = new TextDecoder;++var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {+ var maxIdx = idx + maxBytesToRead;+ if (ignoreNul) return maxIdx;+ // TextDecoder needs to know the byte length in advance, it doesn't stop on+ // null terminator by itself.+ // As a tiny code save trick, compare idx against maxIdx using a negation,+ // so that maxBytesToRead=undefined/NaN means Infinity.+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;+ return idx;+};++/**+ * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given+ * array that contains uint8 values, returns a copy of that string as a+ * Javascript String object.+ * heapOrArray is either a regular array, or a JavaScript typed array view.+ * @param {number=} idx+ * @param {number=} maxBytesToRead+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr)));+};++var FS_stdin_getChar_buffer = [];++var lengthBytesUTF8 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code+ // unit, not a Unicode code point of the character! So decode+ // UTF16->UTF32->UTF8.+ // See http://unicode.org/faq/utf_bom.html#utf16-3+ var c = str.charCodeAt(i);+ // possibly a lead surrogate+ if (c <= 127) {+ len++;+ } else if (c <= 2047) {+ len += 2;+ } else if (c >= 55296 && c <= 57343) {+ len += 4;+ ++i;+ } else {+ len += 3;+ }+ }+ return len;+};++var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {+ // Parameter maxBytesToWrite is not optional. Negative values, 0, null,+ // undefined and false each don't write out any bytes.+ if (!(maxBytesToWrite > 0)) return 0;+ var startIdx = outIdx;+ var endIdx = outIdx + maxBytesToWrite - 1;+ // -1 for string null terminator.+ for (var i = 0; i < str.length; ++i) {+ // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description+ // and https://www.ietf.org/rfc/rfc2279.txt+ // and https://tools.ietf.org/html/rfc3629+ var u = str.codePointAt(i);+ if (u <= 127) {+ if (outIdx >= endIdx) break;+ heap[outIdx++] = u;+ } else if (u <= 2047) {+ if (outIdx + 1 >= endIdx) break;+ heap[outIdx++] = 192 | (u >> 6);+ heap[outIdx++] = 128 | (u & 63);+ } else if (u <= 65535) {+ if (outIdx + 2 >= endIdx) break;+ heap[outIdx++] = 224 | (u >> 12);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ } else {+ if (outIdx + 3 >= endIdx) break;+ heap[outIdx++] = 240 | (u >> 18);+ heap[outIdx++] = 128 | ((u >> 12) & 63);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ i++;+ }+ }+ // Null-terminate the pointer to the buffer.+ heap[outIdx] = 0;+ return outIdx - startIdx;+};++/** @type {function(string, boolean=, number=)} */ var intArrayFromString = (stringy, dontAddNull, length) => {+ var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;+ var u8array = new Array(len);+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);+ if (dontAddNull) u8array.length = numBytesWritten;+ return u8array;+};++var FS_stdin_getChar = () => {+ if (!FS_stdin_getChar_buffer.length) {+ var result = null;+ if (ENVIRONMENT_IS_NODE) {+ // we will read data by chunks of BUFSIZE+ var BUFSIZE = 256;+ var buf = Buffer.alloc(BUFSIZE);+ var bytesRead = 0;+ // For some reason we must suppress a closure warning here, even though+ // fd definitely exists on process.stdin, and is even the proper way to+ // get the fd of stdin,+ // https://github.com/nodejs/help/issues/2136#issuecomment-523649904+ // This started to happen after moving this logic out of library_tty.js,+ // so it is related to the surrounding code in some unclear manner.+ /** @suppress {missingProperties} */ var fd = process.stdin.fd;+ try {+ bytesRead = fs.readSync(fd, buf, 0, BUFSIZE);+ } catch (e) {+ // Cross-platform differences: on Windows, reading EOF throws an+ // exception, but on other OSes, reading EOF returns 0. Uniformize+ // behavior by treating the EOF exception to return 0.+ if (e.toString().includes("EOF")) bytesRead = 0; else throw e;+ }+ if (bytesRead > 0) {+ result = buf.slice(0, bytesRead).toString("utf-8");+ }+ } else if (globalThis.window?.prompt) {+ // Browser.+ result = window.prompt("Input: ");+ // returns null on cancel+ if (result !== null) {+ result += "\n";+ }+ } else {}+ if (!result) {+ return null;+ }+ FS_stdin_getChar_buffer = intArrayFromString(result, true);+ }+ return FS_stdin_getChar_buffer.shift();+};++var TTY = {+ ttys: [],+ init() {},+ shutdown() {},+ register(dev, ops) {+ TTY.ttys[dev] = {+ input: [],+ output: [],+ ops+ };+ FS.registerDevice(dev, TTY.stream_ops);+ },+ stream_ops: {+ open(stream) {+ var tty = TTY.ttys[stream.node.rdev];+ if (!tty) {+ throw new FS.ErrnoError(43);+ }+ stream.tty = tty;+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ stream.tty.ops.fsync(stream.tty);+ },+ fsync(stream) {+ stream.tty.ops.fsync(stream.tty);+ },+ read(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.get_char) {+ throw new FS.ErrnoError(60);+ }+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = stream.tty.ops.get_char(stream.tty);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.put_char) {+ throw new FS.ErrnoError(60);+ }+ try {+ for (var i = 0; i < length; i++) {+ stream.tty.ops.put_char(stream.tty, buffer[offset + i]);+ }+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ },+ default_tty_ops: {+ get_char(tty) {+ return FS_stdin_getChar();+ },+ put_char(tty, val) {+ if (val === null || val === 10) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ },+ ioctl_tcgets(tty) {+ // typical setting+ return {+ c_iflag: 25856,+ c_oflag: 5,+ c_cflag: 191,+ c_lflag: 35387,+ c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]+ };+ },+ ioctl_tcsets(tty, optional_actions, data) {+ // currently just ignore+ return 0;+ },+ ioctl_tiocgwinsz(tty) {+ return [ 24, 80 ];+ }+ },+ default_tty1_ops: {+ put_char(tty, val) {+ if (val === null || val === 10) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ }+ }+};++var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size);++var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;++var mmapAlloc = size => {+ size = alignMemory(size, 65536);+ var ptr = _emscripten_builtin_memalign(65536, size);+ if (ptr) zeroMemory(ptr, size);+ return ptr;+};++var MEMFS = {+ ops_table: null,+ mount(mount) {+ return MEMFS.createNode(null, "/", 16895, 0);+ },+ createNode(parent, name, mode, dev) {+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {+ // not supported+ throw new FS.ErrnoError(63);+ }+ MEMFS.ops_table ||= {+ dir: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ lookup: MEMFS.node_ops.lookup,+ mknod: MEMFS.node_ops.mknod,+ rename: MEMFS.node_ops.rename,+ unlink: MEMFS.node_ops.unlink,+ rmdir: MEMFS.node_ops.rmdir,+ readdir: MEMFS.node_ops.readdir,+ symlink: MEMFS.node_ops.symlink+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek+ }+ },+ file: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek,+ read: MEMFS.stream_ops.read,+ write: MEMFS.stream_ops.write,+ mmap: MEMFS.stream_ops.mmap,+ msync: MEMFS.stream_ops.msync+ }+ },+ link: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ readlink: MEMFS.node_ops.readlink+ },+ stream: {}+ },+ chrdev: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: FS.chrdev_stream_ops+ }+ };+ var node = FS.createNode(parent, name, mode, dev);+ if (FS.isDir(node.mode)) {+ node.node_ops = MEMFS.ops_table.dir.node;+ node.stream_ops = MEMFS.ops_table.dir.stream;+ node.contents = {};+ } else if (FS.isFile(node.mode)) {+ node.node_ops = MEMFS.ops_table.file.node;+ node.stream_ops = MEMFS.ops_table.file.stream;+ // The actual number of bytes used in the typed array, as opposed to+ // contents.length which gives the whole capacity.+ node.usedBytes = 0;+ // The byte data of the file is stored in a typed array.+ // Note: typed arrays are not resizable like normal JS arrays are, so+ // there is a small penalty involved for appending file writes that+ // continuously grow a file similar to std::vector capacity vs used.+ node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0);+ } else if (FS.isLink(node.mode)) {+ node.node_ops = MEMFS.ops_table.link.node;+ node.stream_ops = MEMFS.ops_table.link.stream;+ } else if (FS.isChrdev(node.mode)) {+ node.node_ops = MEMFS.ops_table.chrdev.node;+ node.stream_ops = MEMFS.ops_table.chrdev.stream;+ }+ node.atime = node.mtime = node.ctime = Date.now();+ // add the new node to the parent+ if (parent) {+ parent.contents[name] = node;+ parent.atime = parent.mtime = parent.ctime = node.atime;+ }+ return node;+ },+ getFileDataAsTypedArray(node) {+ return node.contents.subarray(0, node.usedBytes);+ },+ expandFileStorage(node, newCapacity) {+ var prevCapacity = node.contents.length;+ if (prevCapacity >= newCapacity) return;+ // No need to expand, the storage was already large enough.+ // Don't expand strictly to the given requested limit if it's only a very+ // small increase, but instead geometrically grow capacity.+ // For small filesizes (<1MB), perform size*2 geometric increase, but for+ // large sizes, do a much more conservative size*1.125 increase to avoid+ // overshooting the allocation cap by a very large margin.+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0);+ if (prevCapacity) newCapacity = Math.max(newCapacity, 256);+ // At minimum allocate 256b for each file when expanding.+ var oldContents = MEMFS.getFileDataAsTypedArray(node);+ node.contents = new Uint8Array(newCapacity);+ // Allocate new storage.+ node.contents.set(oldContents);+ },+ resizeFileStorage(node, newSize) {+ if (node.usedBytes == newSize) return;+ var oldContents = node.contents;+ node.contents = new Uint8Array(newSize);+ // Allocate new storage.+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));+ // Copy old data over to the new storage.+ node.usedBytes = newSize;+ },+ node_ops: {+ getattr(node) {+ var attr = {};+ // device numbers reuse inode numbers.+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;+ attr.ino = node.id;+ attr.mode = node.mode;+ attr.nlink = 1;+ attr.uid = 0;+ attr.gid = 0;+ attr.rdev = node.rdev;+ if (FS.isDir(node.mode)) {+ attr.size = 4096;+ } else if (FS.isFile(node.mode)) {+ attr.size = node.usedBytes;+ } else if (FS.isLink(node.mode)) {+ attr.size = node.link.length;+ } else {+ attr.size = 0;+ }+ attr.atime = new Date(node.atime);+ attr.mtime = new Date(node.mtime);+ attr.ctime = new Date(node.ctime);+ // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),+ // but this is not required by the standard.+ attr.blksize = 4096;+ attr.blocks = Math.ceil(attr.size / attr.blksize);+ return attr;+ },+ setattr(node, attr) {+ for (const key of [ "mode", "atime", "mtime", "ctime" ]) {+ if (attr[key] != null) {+ node[key] = attr[key];+ }+ }+ if (attr.size !== undefined) {+ MEMFS.resizeFileStorage(node, attr.size);+ }+ },+ lookup(parent, name) {+ // This error may happen quite a bit. To avoid overhead we reuse it (and+ // suffer a lack of stack info).+ if (!MEMFS.doesNotExistError) {+ MEMFS.doesNotExistError = new FS.ErrnoError(44);+ /** @suppress {checkTypes} */ MEMFS.doesNotExistError.stack = "<generic error, no stack>";+ }+ throw MEMFS.doesNotExistError;+ },+ mknod(parent, name, mode, dev) {+ return MEMFS.createNode(parent, name, mode, dev);+ },+ rename(old_node, new_dir, new_name) {+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ if (new_node) {+ if (FS.isDir(old_node.mode)) {+ // if we're overwriting a directory at new_name, make sure it's empty.+ for (var i in new_node.contents) {+ throw new FS.ErrnoError(55);+ }+ }+ FS.hashRemoveNode(new_node);+ }+ // do the internal rewiring+ delete old_node.parent.contents[old_node.name];+ new_dir.contents[new_name] = old_node;+ old_node.name = new_name;+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();+ },+ unlink(parent, name) {+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ rmdir(parent, name) {+ var node = FS.lookupNode(parent, name);+ for (var i in node.contents) {+ throw new FS.ErrnoError(55);+ }+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ readdir(node) {+ return [ ".", "..", ...Object.keys(node.contents) ];+ },+ symlink(parent, newname, oldpath) {+ var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);+ node.link = oldpath;+ return node;+ },+ readlink(node) {+ if (!FS.isLink(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ return node.link;+ }+ },+ stream_ops: {+ read(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= stream.node.usedBytes) return 0;+ var size = Math.min(stream.node.usedBytes - position, length);+ buffer.set(contents.subarray(position, position + size), offset);+ return size;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ // If the buffer is located in main memory (HEAP), and if+ // memory can grow, we can't hold on to references of the+ // memory buffer, as they may get invalidated. That means we+ // need to copy its contents.+ if (buffer.buffer === HEAP8.buffer) {+ canOwn = false;+ }+ if (!length) return 0;+ var node = stream.node;+ node.mtime = node.ctime = Date.now();+ if (canOwn) {+ node.contents = buffer.subarray(offset, offset + length);+ node.usedBytes = length;+ } else if (node.usedBytes === 0 && position === 0) {+ // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.+ node.contents = buffer.slice(offset, offset + length);+ node.usedBytes = length;+ } else {+ MEMFS.expandFileStorage(node, position + length);+ // Use typed array write which is available.+ node.contents.set(buffer.subarray(offset, offset + length), position);+ node.usedBytes = Math.max(node.usedBytes, position + length);+ }+ return length;+ },+ llseek(stream, offset, whence) {+ var position = offset;+ if (whence === 1) {+ position += stream.position;+ } else if (whence === 2) {+ if (FS.isFile(stream.node.mode)) {+ position += stream.node.usedBytes;+ }+ }+ if (position < 0) {+ throw new FS.ErrnoError(28);+ }+ return position;+ },+ mmap(stream, length, position, prot, flags) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ var ptr;+ var allocated;+ var contents = stream.node.contents;+ // Only make a new copy when MAP_PRIVATE is specified.+ if (!(flags & 2) && contents.buffer === HEAP8.buffer) {+ // We can't emulate MAP_SHARED when the file is not backed by the+ // buffer we're mapping to (e.g. the HEAP buffer).+ allocated = false;+ ptr = contents.byteOffset;+ } else {+ allocated = true;+ ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ if (contents) {+ // Try to avoid unnecessary slices.+ if (position > 0 || position + length < contents.length) {+ if (contents.subarray) {+ contents = contents.subarray(position, position + length);+ } else {+ contents = Array.prototype.slice.call(contents, position, position + length);+ }+ }+ HEAP8.set(contents, ptr);+ }+ }+ return {+ ptr,+ allocated+ };+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);+ // should we check if bytesWritten and length are the same?+ return 0;+ }+ }+};++var FS_modeStringToFlags = str => {+ if (typeof str != "string") return str;+ var flagModes = {+ "r": 0,+ "r+": 2,+ "w": 512 | 64 | 1,+ "w+": 512 | 64 | 2,+ "a": 1024 | 64 | 1,+ "a+": 1024 | 64 | 2+ };+ var flags = flagModes[str];+ if (typeof flags == "undefined") {+ throw new Error(`Unknown file open mode: ${str}`);+ }+ return flags;+};++var FS_fileDataToTypedArray = data => {+ if (typeof data == "string") {+ data = intArrayFromString(data, true);+ }+ if (!data.subarray) {+ data = new Uint8Array(data);+ }+ return data;+};++var FS_getMode = (canRead, canWrite) => {+ var mode = 0;+ if (canRead) mode |= 292 | 73;+ if (canWrite) mode |= 146;+ return mode;+};++var asyncLoad = async url => {+ var arrayBuffer = await readAsync(url);+ return new Uint8Array(arrayBuffer);+};++var FS_createDataFile = (...args) => FS.createDataFile(...args);++var getUniqueRunDependency = id => id;++var runDependencies = 0;++var dependenciesFulfilled = null;++var removeRunDependency = id => {+ runDependencies--;+ Module["monitorRunDependencies"]?.(runDependencies);+ if (runDependencies == 0) {+ if (dependenciesFulfilled) {+ var callback = dependenciesFulfilled;+ dependenciesFulfilled = null;+ callback();+ }+ }+};++var addRunDependency = id => {+ runDependencies++;+ Module["monitorRunDependencies"]?.(runDependencies);+};++var FS_handledByPreloadPlugin = async (byteArray, fullname) => {+ // Ensure plugins are ready.+ if (typeof Browser != "undefined") Browser.init();+ for (var plugin of preloadPlugins) {+ if (plugin["canHandle"](fullname)) {+ return plugin["handle"](byteArray, fullname);+ }+ }+ // If no plugin handled this file then return the original/unmodified+ // byteArray.+ return byteArray;+};++var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {+ // TODO we should allow people to just pass in a complete filename instead+ // of parent and name being that we just join them anyways+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;+ var dep = getUniqueRunDependency(`cp ${fullname}`);+ // might have several active requests for the same fullname+ addRunDependency(dep);+ try {+ var byteArray = url;+ if (typeof url == "string") {+ byteArray = await asyncLoad(url);+ }+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);+ preFinish?.();+ if (!dontCreateFile) {+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);+ }+ } finally {+ removeRunDependency(dep);+ }+};++var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);+};++var FS = {+ root: null,+ mounts: [],+ devices: {},+ streams: [],+ nextInode: 1,+ nameTable: null,+ currentPath: "/",+ initialized: false,+ ignorePermissions: true,+ filesystems: null,+ syncFSRequests: 0,+ ErrnoError: class {+ name="ErrnoError";+ // We set the `name` property to be able to identify `FS.ErrnoError`+ // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.+ // - when using PROXYFS, an error can come from an underlying FS+ // as different FS objects have their own FS.ErrnoError each,+ // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.+ // we'll use the reliable test `err.name == "ErrnoError"` instead+ constructor(errno) {+ this.errno = errno;+ }+ },+ FSStream: class {+ shared={};+ get object() {+ return this.node;+ }+ set object(val) {+ this.node = val;+ }+ get isRead() {+ return (this.flags & 2097155) !== 1;+ }+ get isWrite() {+ return (this.flags & 2097155) !== 0;+ }+ get isAppend() {+ return (this.flags & 1024);+ }+ get flags() {+ return this.shared.flags;+ }+ set flags(val) {+ this.shared.flags = val;+ }+ get position() {+ return this.shared.position;+ }+ set position(val) {+ this.shared.position = val;+ }+ },+ FSNode: class {+ node_ops={};+ stream_ops={};+ readMode=292 | 73;+ writeMode=146;+ mounted=null;+ constructor(parent, name, mode, rdev) {+ if (!parent) {+ parent = this;+ }+ this.parent = parent;+ this.mount = parent.mount;+ this.id = FS.nextInode++;+ this.name = name;+ this.mode = mode;+ this.rdev = rdev;+ this.atime = this.mtime = this.ctime = Date.now();+ }+ get read() {+ return (this.mode & this.readMode) === this.readMode;+ }+ set read(val) {+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;+ }+ get write() {+ return (this.mode & this.writeMode) === this.writeMode;+ }+ set write(val) {+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;+ }+ get isFolder() {+ return FS.isDir(this.mode);+ }+ get isDevice() {+ return FS.isChrdev(this.mode);+ }+ },+ lookupPath(path, opts = {}) {+ if (!path) {+ throw new FS.ErrnoError(44);+ }+ opts.follow_mount ??= true;+ if (!PATH.isAbs(path)) {+ path = FS.cwd() + "/" + path;+ }+ // limit max consecutive symlinks to 40 (SYMLOOP_MAX).+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {+ // split the absolute path+ var parts = path.split("/").filter(p => !!p);+ // start at the root+ var current = FS.root;+ var current_path = "/";+ for (var i = 0; i < parts.length; i++) {+ var islast = (i === parts.length - 1);+ if (islast && opts.parent) {+ // stop resolving+ break;+ }+ if (parts[i] === ".") {+ continue;+ }+ if (parts[i] === "..") {+ current_path = PATH.dirname(current_path);+ if (FS.isRoot(current)) {+ path = current_path + "/" + parts.slice(i + 1).join("/");+ // We're making progress here, don't let many consecutive ..'s+ // lead to ELOOP+ nlinks--;+ continue linkloop;+ } else {+ current = current.parent;+ }+ continue;+ }+ current_path = PATH.join2(current_path, parts[i]);+ try {+ current = FS.lookupNode(current, parts[i]);+ } catch (e) {+ // if noent_okay is true, suppress a ENOENT in the last component+ // and return an object with an undefined node. This is needed for+ // resolving symlinks in the path when creating a file.+ if ((e?.errno === 44) && islast && opts.noent_okay) {+ return {+ path: current_path+ };+ }+ throw e;+ }+ // jump to the mount's root node if this is a mountpoint+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {+ current = current.mounted.root;+ }+ // by default, lookupPath will not follow a symlink if it is the final path component.+ // setting opts.follow = true will override this behavior.+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {+ if (!current.node_ops.readlink) {+ throw new FS.ErrnoError(52);+ }+ var link = current.node_ops.readlink(current);+ if (!PATH.isAbs(link)) {+ link = PATH.dirname(current_path) + "/" + link;+ }+ path = link + "/" + parts.slice(i + 1).join("/");+ continue linkloop;+ }+ }+ return {+ path: current_path,+ node: current+ };+ }+ throw new FS.ErrnoError(32);+ },+ getPath(node) {+ var path;+ while (true) {+ if (FS.isRoot(node)) {+ var mount = node.mount.mountpoint;+ if (!path) return mount;+ return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;+ }+ path = path ? `${node.name}/${path}` : node.name;+ node = node.parent;+ }+ },+ hashName(parentid, name) {+ var hash = 0;+ for (var i = 0; i < name.length; i++) {+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;+ }+ return ((parentid + hash) >>> 0) % FS.nameTable.length;+ },+ hashAddNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ node.name_next = FS.nameTable[hash];+ FS.nameTable[hash] = node;+ },+ hashRemoveNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ if (FS.nameTable[hash] === node) {+ FS.nameTable[hash] = node.name_next;+ } else {+ var current = FS.nameTable[hash];+ while (current) {+ if (current.name_next === node) {+ current.name_next = node.name_next;+ break;+ }+ current = current.name_next;+ }+ }+ },+ lookupNode(parent, name) {+ var errCode = FS.mayLookup(parent);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ var hash = FS.hashName(parent.id, name);+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {+ var nodeName = node.name;+ if (node.parent.id === parent.id && nodeName === name) {+ return node;+ }+ }+ // if we failed to find it in the cache, call into the VFS+ return FS.lookup(parent, name);+ },+ createNode(parent, name, mode, rdev) {+ var node = new FS.FSNode(parent, name, mode, rdev);+ FS.hashAddNode(node);+ return node;+ },+ destroyNode(node) {+ FS.hashRemoveNode(node);+ },+ isRoot(node) {+ return node === node.parent;+ },+ isMountpoint(node) {+ return !!node.mounted;+ },+ isFile(mode) {+ return (mode & 61440) === 32768;+ },+ isDir(mode) {+ return (mode & 61440) === 16384;+ },+ isLink(mode) {+ return (mode & 61440) === 40960;+ },+ isChrdev(mode) {+ return (mode & 61440) === 8192;+ },+ isBlkdev(mode) {+ return (mode & 61440) === 24576;+ },+ isFIFO(mode) {+ return (mode & 61440) === 4096;+ },+ isSocket(mode) {+ return (mode & 49152) === 49152;+ },+ flagsToPermissionString(flag) {+ var perms = [ "r", "w", "rw" ][flag & 3];+ if ((flag & 512)) {+ perms += "w";+ }+ return perms;+ },+ nodePermissions(node, perms) {+ if (FS.ignorePermissions) {+ return 0;+ }+ // return 0 if any user, group or owner bits are set.+ if (perms.includes("r") && !(node.mode & 292)) {+ return 2;+ }+ if (perms.includes("w") && !(node.mode & 146)) {+ return 2;+ }+ if (perms.includes("x") && !(node.mode & 73)) {+ return 2;+ }+ return 0;+ },+ mayLookup(dir) {+ if (!FS.isDir(dir.mode)) return 54;+ var errCode = FS.nodePermissions(dir, "x");+ if (errCode) return errCode;+ if (!dir.node_ops.lookup) return 2;+ return 0;+ },+ mayCreate(dir, name) {+ if (!FS.isDir(dir.mode)) {+ return 54;+ }+ try {+ var node = FS.lookupNode(dir, name);+ return 20;+ } catch (e) {}+ return FS.nodePermissions(dir, "wx");+ },+ mayDelete(dir, name, isdir) {+ var node;+ try {+ node = FS.lookupNode(dir, name);+ } catch (e) {+ return e.errno;+ }+ var errCode = FS.nodePermissions(dir, "wx");+ if (errCode) {+ return errCode;+ }+ if (isdir) {+ if (!FS.isDir(node.mode)) {+ return 54;+ }+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {+ return 10;+ }+ } else if (FS.isDir(node.mode)) {+ return 31;+ }+ return 0;+ },+ mayOpen(node, flags) {+ if (!node) {+ return 44;+ }+ if (FS.isLink(node.mode)) {+ return 32;+ }+ var mode = FS.flagsToPermissionString(flags);+ if (FS.isDir(node.mode)) {+ // opening for write+ // TODO: check for O_SEARCH? (== search for dir only)+ if (mode !== "r" || (flags & (512 | 64))) {+ return 31;+ }+ }+ return FS.nodePermissions(node, mode);+ },+ checkOpExists(op, err) {+ if (!op) {+ throw new FS.ErrnoError(err);+ }+ return op;+ },+ MAX_OPEN_FDS: 4096,+ nextfd() {+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {+ if (!FS.streams[fd]) {+ return fd;+ }+ }+ throw new FS.ErrnoError(33);+ },+ getStreamChecked(fd) {+ var stream = FS.getStream(fd);+ if (!stream) {+ throw new FS.ErrnoError(8);+ }+ return stream;+ },+ getStream: fd => FS.streams[fd],+ createStream(stream, fd = -1) {+ // clone it, so we can return an instance of FSStream+ stream = Object.assign(new FS.FSStream, stream);+ if (fd == -1) {+ fd = FS.nextfd();+ }+ stream.fd = fd;+ FS.streams[fd] = stream;+ return stream;+ },+ closeStream(fd) {+ FS.streams[fd] = null;+ },+ dupStream(origStream, fd = -1) {+ var stream = FS.createStream(origStream, fd);+ stream.stream_ops?.dup?.(stream);+ return stream;+ },+ doSetAttr(stream, node, attr) {+ var setattr = stream?.stream_ops.setattr;+ var arg = setattr ? stream : node;+ setattr ??= node.node_ops.setattr;+ FS.checkOpExists(setattr, 63);+ setattr(arg, attr);+ },+ chrdev_stream_ops: {+ open(stream) {+ var device = FS.getDevice(stream.node.rdev);+ // override node's stream ops with the device's+ stream.stream_ops = device.stream_ops;+ // forward the open call+ stream.stream_ops.open?.(stream);+ },+ llseek() {+ throw new FS.ErrnoError(70);+ }+ },+ major: dev => ((dev) >> 8),+ minor: dev => ((dev) & 255),+ makedev: (ma, mi) => ((ma) << 8 | (mi)),+ registerDevice(dev, ops) {+ FS.devices[dev] = {+ stream_ops: ops+ };+ },+ getDevice: dev => FS.devices[dev],+ getMounts(mount) {+ var mounts = [];+ var check = [ mount ];+ while (check.length) {+ var m = check.pop();+ mounts.push(m);+ check.push(...m.mounts);+ }+ return mounts;+ },+ syncfs(populate, callback) {+ if (typeof populate == "function") {+ callback = populate;+ populate = false;+ }+ FS.syncFSRequests++;+ if (FS.syncFSRequests > 1) {+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);+ }+ var mounts = FS.getMounts(FS.root.mount);+ var completed = 0;+ function doCallback(errCode) {+ FS.syncFSRequests--;+ return callback(errCode);+ }+ function done(errCode) {+ if (errCode) {+ if (!done.errored) {+ done.errored = true;+ return doCallback(errCode);+ }+ return;+ }+ if (++completed >= mounts.length) {+ doCallback(null);+ }+ }+ // sync all mounts+ for (var mount of mounts) {+ if (mount.type.syncfs) {+ mount.type.syncfs(mount, populate, done);+ } else {+ done(null);+ }+ }+ },+ mount(type, opts, mountpoint) {+ var root = mountpoint === "/";+ var pseudo = !mountpoint;+ var node;+ if (root && FS.root) {+ throw new FS.ErrnoError(10);+ } else if (!root && !pseudo) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ mountpoint = lookup.path;+ // use the absolute path+ node = lookup.node;+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ if (!FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ }+ var mount = {+ type,+ opts,+ mountpoint,+ mounts: []+ };+ // create a root node for the fs+ var mountRoot = type.mount(mount);+ mountRoot.mount = mount;+ mount.root = mountRoot;+ if (root) {+ FS.root = mountRoot;+ } else if (node) {+ // set as a mountpoint+ node.mounted = mount;+ // add the new mount to the current mount's children+ if (node.mount) {+ node.mount.mounts.push(mount);+ }+ }+ return mountRoot;+ },+ unmount(mountpoint) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ if (!FS.isMountpoint(lookup.node)) {+ throw new FS.ErrnoError(28);+ }+ // destroy the nodes for this mount, and all its child mounts+ var node = lookup.node;+ var mount = node.mounted;+ var mounts = FS.getMounts(mount);+ for (var [hash, current] of Object.entries(FS.nameTable)) {+ while (current) {+ var next = current.name_next;+ if (mounts.includes(current.mount)) {+ FS.destroyNode(current);+ }+ current = next;+ }+ }+ // no longer a mountpoint+ node.mounted = null;+ // remove this mount from the child mounts+ var idx = node.mount.mounts.indexOf(mount);+ node.mount.mounts.splice(idx, 1);+ },+ lookup(parent, name) {+ return parent.node_ops.lookup(parent, name);+ },+ mknod(path, mode, dev) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ if (!name) {+ throw new FS.ErrnoError(28);+ }+ if (name === "." || name === "..") {+ throw new FS.ErrnoError(20);+ }+ var errCode = FS.mayCreate(parent, name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.mknod) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.mknod(parent, name, mode, dev);+ },+ statfs(path) {+ return FS.statfsNode(FS.lookupPath(path, {+ follow: true+ }).node);+ },+ statfsStream(stream) {+ // We keep a separate statfsStream function because noderawfs overrides+ // it. In noderawfs, stream.node is sometimes null. Instead, we need to+ // look at stream.path.+ return FS.statfsNode(stream.node);+ },+ statfsNode(node) {+ // NOTE: None of the defaults here are true. We're just returning safe and+ // sane values. Currently nodefs and rawfs replace these defaults,+ // other file systems leave them alone.+ var rtn = {+ bsize: 4096,+ frsize: 4096,+ blocks: 1e6,+ bfree: 5e5,+ bavail: 5e5,+ files: FS.nextInode,+ ffree: FS.nextInode - 1,+ fsid: 42,+ flags: 2,+ namelen: 255+ };+ if (node.node_ops.statfs) {+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));+ }+ return rtn;+ },+ create(path, mode = 438) {+ mode &= 4095;+ mode |= 32768;+ return FS.mknod(path, mode, 0);+ },+ mkdir(path, mode = 511) {+ mode &= 511 | 512;+ mode |= 16384;+ return FS.mknod(path, mode, 0);+ },+ mkdirTree(path, mode) {+ var dirs = path.split("/");+ var d = "";+ for (var dir of dirs) {+ if (!dir) continue;+ if (d || PATH.isAbs(path)) d += "/";+ d += dir;+ try {+ FS.mkdir(d, mode);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ }+ },+ mkdev(path, mode, dev) {+ if (typeof dev == "undefined") {+ dev = mode;+ mode = 438;+ }+ mode |= 8192;+ return FS.mknod(path, mode, dev);+ },+ symlink(oldpath, newpath) {+ if (!PATH_FS.resolve(oldpath)) {+ throw new FS.ErrnoError(44);+ }+ var lookup = FS.lookupPath(newpath, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var newname = PATH.basename(newpath);+ var errCode = FS.mayCreate(parent, newname);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.symlink) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.symlink(parent, newname, oldpath);+ },+ rename(old_path, new_path) {+ var old_dirname = PATH.dirname(old_path);+ var new_dirname = PATH.dirname(new_path);+ var old_name = PATH.basename(old_path);+ var new_name = PATH.basename(new_path);+ // parents must exist+ var lookup, old_dir, new_dir;+ // let the errors from non existent directories percolate up+ lookup = FS.lookupPath(old_path, {+ parent: true+ });+ old_dir = lookup.node;+ lookup = FS.lookupPath(new_path, {+ parent: true+ });+ new_dir = lookup.node;+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);+ // need to be part of the same mount+ if (old_dir.mount !== new_dir.mount) {+ throw new FS.ErrnoError(75);+ }+ // source must exist+ var old_node = FS.lookupNode(old_dir, old_name);+ // old path should not be an ancestor of the new path+ var relative = PATH_FS.relative(old_path, new_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(28);+ }+ // new path should not be an ancestor of the old path+ relative = PATH_FS.relative(new_path, old_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(55);+ }+ // see if the new path already exists+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ // early out if nothing needs to change+ if (old_node === new_node) {+ return;+ }+ // we'll need to delete the old entry+ var isdir = FS.isDir(old_node.mode);+ var errCode = FS.mayDelete(old_dir, old_name, isdir);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ // need delete permissions if we'll be overwriting.+ // need create permissions if new doesn't already exist.+ errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!old_dir.node_ops.rename) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {+ throw new FS.ErrnoError(10);+ }+ // if we are going to change the parent, check write permissions+ if (new_dir !== old_dir) {+ errCode = FS.nodePermissions(old_dir, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // remove the node from the lookup hash+ FS.hashRemoveNode(old_node);+ // do the underlying fs rename+ try {+ old_dir.node_ops.rename(old_node, new_dir, new_name);+ // update old node (we do this here to avoid each backend+ // needing to)+ old_node.parent = new_dir;+ } catch (e) {+ throw e;+ } finally {+ // add the node back to the hash (in case node_ops.rename+ // changed its name)+ FS.hashAddNode(old_node);+ }+ },+ rmdir(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, true);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.rmdir) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.rmdir(parent, name);+ FS.destroyNode(node);+ },+ readdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);+ return readdir(node);+ },+ unlink(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, false);+ if (errCode) {+ // According to POSIX, we should map EISDIR to EPERM, but+ // we instead do what Linux does (and we must, as we use+ // the musl linux libc).+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.unlink) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.unlink(parent, name);+ FS.destroyNode(node);+ },+ readlink(path) {+ var lookup = FS.lookupPath(path);+ var link = lookup.node;+ if (!link) {+ throw new FS.ErrnoError(44);+ }+ if (!link.node_ops.readlink) {+ throw new FS.ErrnoError(28);+ }+ return link.node_ops.readlink(link);+ },+ stat(path, dontFollow) {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ var node = lookup.node;+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);+ return getattr(node);+ },+ fstat(fd) {+ var stream = FS.getStreamChecked(fd);+ var node = stream.node;+ var getattr = stream.stream_ops.getattr;+ var arg = getattr ? stream : node;+ getattr ??= node.node_ops.getattr;+ FS.checkOpExists(getattr, 63);+ return getattr(arg);+ },+ lstat(path) {+ return FS.stat(path, true);+ },+ doChmod(stream, node, mode, dontFollow) {+ FS.doSetAttr(stream, node, {+ mode: (mode & 4095) | (node.mode & ~4095),+ ctime: Date.now(),+ dontFollow+ });+ },+ chmod(path, mode, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChmod(null, node, mode, dontFollow);+ },+ lchmod(path, mode) {+ FS.chmod(path, mode, true);+ },+ fchmod(fd, mode) {+ var stream = FS.getStreamChecked(fd);+ FS.doChmod(stream, stream.node, mode, false);+ },+ doChown(stream, node, dontFollow) {+ FS.doSetAttr(stream, node, {+ timestamp: Date.now(),+ dontFollow+ });+ },+ chown(path, uid, gid, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChown(null, node, dontFollow);+ },+ lchown(path, uid, gid) {+ FS.chown(path, uid, gid, true);+ },+ fchown(fd, uid, gid) {+ var stream = FS.getStreamChecked(fd);+ FS.doChown(stream, stream.node, false);+ },+ doTruncate(stream, node, len) {+ if (FS.isDir(node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!FS.isFile(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ var errCode = FS.nodePermissions(node, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.doSetAttr(stream, node, {+ size: len,+ timestamp: Date.now()+ });+ },+ truncate(path, len) {+ if (len < 0) {+ throw new FS.ErrnoError(28);+ }+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doTruncate(null, node, len);+ },+ ftruncate(fd, len) {+ var stream = FS.getStreamChecked(fd);+ if (len < 0 || (stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(28);+ }+ FS.doTruncate(stream, stream.node, len);+ },+ utime(path, atime, mtime) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var setattr = FS.checkOpExists(node.node_ops.setattr, 63);+ setattr(node, {+ atime,+ mtime+ });+ },+ open(path, flags, mode = 438) {+ if (path === "") {+ throw new FS.ErrnoError(44);+ }+ flags = FS_modeStringToFlags(flags);+ if ((flags & 64)) {+ mode = (mode & 4095) | 32768;+ } else {+ mode = 0;+ }+ var node;+ var isDirPath;+ if (typeof path == "object") {+ node = path;+ } else {+ isDirPath = path.endsWith("/");+ // noent_okay makes it so that if the final component of the path+ // doesn't exist, lookupPath returns `node: undefined`. `path` will be+ // updated to point to the target of all symlinks.+ var lookup = FS.lookupPath(path, {+ follow: !(flags & 131072),+ noent_okay: true+ });+ node = lookup.node;+ path = lookup.path;+ }+ // perhaps we need to create the node+ var created = false;+ if ((flags & 64)) {+ if (node) {+ // if O_CREAT and O_EXCL are set, error out if the node already exists+ if ((flags & 128)) {+ throw new FS.ErrnoError(20);+ }+ } else if (isDirPath) {+ throw new FS.ErrnoError(31);+ } else {+ // node doesn't exist, try to create it+ // Ignore the permission bits here to ensure we can `open` this new+ // file below. We use chmod below to apply the permissions once the+ // file is open.+ node = FS.mknod(path, mode | 511, 0);+ created = true;+ }+ }+ if (!node) {+ throw new FS.ErrnoError(44);+ }+ // can't truncate a device+ if (FS.isChrdev(node.mode)) {+ flags &= ~512;+ }+ // if asked only for a directory, then this must be one+ if ((flags & 65536) && !FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ // check permissions, if this is not a file we just created now (it is ok to+ // create and write to a file with read-only permissions; it is read-only+ // for later use)+ if (!created) {+ var errCode = FS.mayOpen(node, flags);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // do truncation if necessary+ if ((flags & 512) && !created) {+ FS.truncate(node, 0);+ }+ // we've already handled these, don't pass down to the underlying vfs+ flags &= ~(128 | 512 | 131072);+ // register the stream with the filesystem+ var stream = FS.createStream({+ node,+ path: FS.getPath(node),+ // we want the absolute path to the node+ flags,+ seekable: true,+ position: 0,+ stream_ops: node.stream_ops,+ // used by the file family libc calls (fopen, fwrite, ferror, etc.)+ ungotten: [],+ error: false+ });+ // call the new stream's open function+ if (stream.stream_ops.open) {+ stream.stream_ops.open(stream);+ }+ if (created) {+ FS.chmod(node, mode & 511);+ }+ return stream;+ },+ close(stream) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (stream.getdents) stream.getdents = null;+ // free readdir state+ try {+ if (stream.stream_ops.close) {+ stream.stream_ops.close(stream);+ }+ } catch (e) {+ throw e;+ } finally {+ FS.closeStream(stream.fd);+ }+ stream.fd = null;+ },+ isClosed(stream) {+ return stream.fd === null;+ },+ llseek(stream, offset, whence) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (!stream.seekable || !stream.stream_ops.llseek) {+ throw new FS.ErrnoError(70);+ }+ if (whence != 0 && whence != 1 && whence != 2) {+ throw new FS.ErrnoError(28);+ }+ stream.position = stream.stream_ops.llseek(stream, offset, whence);+ stream.ungotten = [];+ return stream.position;+ },+ read(stream, buffer, offset, length, position) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.read) {+ throw new FS.ErrnoError(28);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);+ if (!seeking) stream.position += bytesRead;+ return bytesRead;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.write) {+ throw new FS.ErrnoError(28);+ }+ if (stream.seekable && stream.flags & 1024) {+ // seek to the end before writing in append mode+ FS.llseek(stream, 0, 2);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);+ if (!seeking) stream.position += bytesWritten;+ return bytesWritten;+ },+ mmap(stream, length, position, prot, flags) {+ // User requests writing to file (prot & PROT_WRITE != 0).+ // Checking if we have permissions to write to the file unless+ // MAP_PRIVATE flag is set. According to POSIX spec it is possible+ // to write to file opened in read-only mode with MAP_PRIVATE flag,+ // as all modifications will be visible only in the memory of+ // the current process.+ if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {+ throw new FS.ErrnoError(2);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(2);+ }+ if (!stream.stream_ops.mmap) {+ throw new FS.ErrnoError(43);+ }+ if (!length) {+ throw new FS.ErrnoError(28);+ }+ return stream.stream_ops.mmap(stream, length, position, prot, flags);+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ if (!stream.stream_ops.msync) {+ return 0;+ }+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);+ },+ ioctl(stream, cmd, arg) {+ if (!stream.stream_ops.ioctl) {+ throw new FS.ErrnoError(59);+ }+ return stream.stream_ops.ioctl(stream, cmd, arg);+ },+ readFile(path, opts = {}) {+ opts.flags = opts.flags || 0;+ opts.encoding = opts.encoding || "binary";+ if (opts.encoding !== "utf8" && opts.encoding !== "binary") {+ abort(`Invalid encoding type "${opts.encoding}"`);+ }+ var stream = FS.open(path, opts.flags);+ var stat = FS.stat(path);+ var length = stat.size;+ var buf = new Uint8Array(length);+ FS.read(stream, buf, 0, length, 0);+ if (opts.encoding === "utf8") {+ buf = UTF8ArrayToString(buf);+ }+ FS.close(stream);+ return buf;+ },+ writeFile(path, data, opts = {}) {+ opts.flags = opts.flags || 577;+ var stream = FS.open(path, opts.flags, opts.mode);+ data = FS_fileDataToTypedArray(data);+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);+ FS.close(stream);+ },+ cwd: () => FS.currentPath,+ chdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ if (lookup.node === null) {+ throw new FS.ErrnoError(44);+ }+ if (!FS.isDir(lookup.node.mode)) {+ throw new FS.ErrnoError(54);+ }+ var errCode = FS.nodePermissions(lookup.node, "x");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.currentPath = lookup.path;+ },+ createDefaultDirectories() {+ FS.mkdir("/tmp");+ FS.mkdir("/home");+ FS.mkdir("/home/web_user");+ },+ createDefaultDevices() {+ // create /dev+ FS.mkdir("/dev");+ // setup /dev/null+ FS.registerDevice(FS.makedev(1, 3), {+ read: () => 0,+ write: (stream, buffer, offset, length, pos) => length,+ llseek: () => 0+ });+ FS.mkdev("/dev/null", FS.makedev(1, 3));+ // setup /dev/tty and /dev/tty1+ // stderr needs to print output using err() rather than out()+ // so we register a second tty just for it.+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);+ FS.mkdev("/dev/tty", FS.makedev(5, 0));+ FS.mkdev("/dev/tty1", FS.makedev(6, 0));+ // setup /dev/[u]random+ // use a buffer to avoid overhead of individual crypto calls per byte+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;+ var randomByte = () => {+ if (randomLeft === 0) {+ randomFill(randomBuffer);+ randomLeft = randomBuffer.byteLength;+ }+ return randomBuffer[--randomLeft];+ };+ FS.createDevice("/dev", "random", randomByte);+ FS.createDevice("/dev", "urandom", randomByte);+ // we're not going to emulate the actual shm device,+ // just create the tmp dirs that reside in it commonly+ FS.mkdir("/dev/shm");+ FS.mkdir("/dev/shm/tmp");+ },+ createSpecialDirectories() {+ // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the+ // name of the stream for fd 6 (see test_unistd_ttyname)+ FS.mkdir("/proc");+ var proc_self = FS.mkdir("/proc/self");+ FS.mkdir("/proc/self/fd");+ FS.mount({+ mount() {+ var node = FS.createNode(proc_self, "fd", 16895, 73);+ node.stream_ops = {+ llseek: MEMFS.stream_ops.llseek+ };+ node.node_ops = {+ lookup(parent, name) {+ var fd = +name;+ var stream = FS.getStreamChecked(fd);+ var ret = {+ parent: null,+ mount: {+ mountpoint: "fake"+ },+ node_ops: {+ readlink: () => stream.path+ },+ id: fd + 1+ };+ ret.parent = ret;+ // make it look like a simple root node+ return ret;+ },+ readdir() {+ return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString());+ }+ };+ return node;+ }+ }, {}, "/proc/self/fd");+ },+ createStandardStreams(input, output, error) {+ // TODO deprecate the old functionality of a single+ // input / output callback and that utilizes FS.createDevice+ // and instead require a unique set of stream ops+ // by default, we symlink the standard streams to the+ // default tty devices. however, if the standard streams+ // have been overwritten we create a unique device for+ // them instead.+ if (input) {+ FS.createDevice("/dev", "stdin", input);+ } else {+ FS.symlink("/dev/tty", "/dev/stdin");+ }+ if (output) {+ FS.createDevice("/dev", "stdout", null, output);+ } else {+ FS.symlink("/dev/tty", "/dev/stdout");+ }+ if (error) {+ FS.createDevice("/dev", "stderr", null, error);+ } else {+ FS.symlink("/dev/tty1", "/dev/stderr");+ }+ // open default streams for the stdin, stdout and stderr devices+ var stdin = FS.open("/dev/stdin", 0);+ var stdout = FS.open("/dev/stdout", 1);+ var stderr = FS.open("/dev/stderr", 1);+ },+ staticInit() {+ FS.nameTable = new Array(4096);+ FS.mount(MEMFS, {}, "/");+ FS.createDefaultDirectories();+ FS.createDefaultDevices();+ FS.createSpecialDirectories();+ FS.filesystems = {+ "MEMFS": MEMFS+ };+ },+ init(input, output, error) {+ FS.initialized = true;+ // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here+ input ??= Module["stdin"];+ output ??= Module["stdout"];+ error ??= Module["stderr"];+ FS.createStandardStreams(input, output, error);+ },+ quit() {+ FS.initialized = false;+ // force-flush all streams, so we get musl std streams printed out+ // close all of our streams+ for (var stream of FS.streams) {+ if (stream) {+ FS.close(stream);+ }+ }+ },+ findObject(path, dontResolveLastLink) {+ var ret = FS.analyzePath(path, dontResolveLastLink);+ if (!ret.exists) {+ return null;+ }+ return ret.object;+ },+ analyzePath(path, dontResolveLastLink) {+ // operate from within the context of the symlink's target+ try {+ var lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ path = lookup.path;+ } catch (e) {}+ var ret = {+ isRoot: false,+ exists: false,+ error: 0,+ name: null,+ path: null,+ object: null,+ parentExists: false,+ parentPath: null,+ parentObject: null+ };+ try {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ ret.parentExists = true;+ ret.parentPath = lookup.path;+ ret.parentObject = lookup.node;+ ret.name = PATH.basename(path);+ lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ ret.exists = true;+ ret.path = lookup.path;+ ret.object = lookup.node;+ ret.name = lookup.node.name;+ ret.isRoot = lookup.path === "/";+ } catch (e) {+ ret.error = e.errno;+ }+ return ret;+ },+ createPath(parent, path, canRead, canWrite) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ var parts = path.split("/").reverse();+ while (parts.length) {+ var part = parts.pop();+ if (!part) continue;+ var current = PATH.join2(parent, part);+ try {+ FS.mkdir(current);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ parent = current;+ }+ return current;+ },+ createFile(parent, name, properties, canRead, canWrite) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(canRead, canWrite);+ return FS.create(path, mode);+ },+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {+ var path = name;+ if (parent) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ path = name ? PATH.join2(parent, name) : parent;+ }+ var mode = FS_getMode(canRead, canWrite);+ var node = FS.create(path, mode);+ if (data) {+ data = FS_fileDataToTypedArray(data);+ // make sure we can write to the file+ FS.chmod(node, mode | 146);+ var stream = FS.open(node, 577);+ FS.write(stream, data, 0, data.length, 0, canOwn);+ FS.close(stream);+ FS.chmod(node, mode);+ }+ },+ createDevice(parent, name, input, output) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(!!input, !!output);+ FS.createDevice.major ??= 64;+ var dev = FS.makedev(FS.createDevice.major++, 0);+ // Create a fake device that a set of stream ops to emulate+ // the old behavior.+ FS.registerDevice(dev, {+ open(stream) {+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ if (output?.buffer?.length) {+ output(10);+ }+ },+ read(stream, buffer, offset, length, pos) {+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = input();+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ for (var i = 0; i < length; i++) {+ try {+ output(buffer[offset + i]);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ });+ return FS.mkdev(path, mode, dev);+ },+ forceLoadFile(obj) {+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;+ if (globalThis.XMLHttpRequest) {+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");+ } else {+ // Command-line.+ try {+ obj.contents = readBinary(obj.url);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ },+ createLazyFile(parent, name, url, canRead, canWrite) {+ // Lazy chunked Uint8Array (implements get and length from Uint8Array).+ // Actual getting is abstracted away for eventual reuse.+ class LazyUint8Array {+ lengthKnown=false;+ chunks=[];+ // Loaded chunks. Index is the chunk number+ get(idx) {+ if (idx > this.length - 1 || idx < 0) {+ return undefined;+ }+ var chunkOffset = idx % this.chunkSize;+ var chunkNum = (idx / this.chunkSize) | 0;+ return this.getter(chunkNum)[chunkOffset];+ }+ setDataGetter(getter) {+ this.getter = getter;+ }+ cacheLength() {+ // Find length+ var xhr = new XMLHttpRequest;+ xhr.open("HEAD", url, false);+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ var datalength = Number(xhr.getResponseHeader("Content-length"));+ var header;+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";+ var chunkSize = 1024 * 1024;+ // Chunk size in bytes+ if (!hasByteServing) chunkSize = datalength;+ // Function to get a range from the remote URL.+ var doXHR = (from, to) => {+ if (from > to) abort("invalid range (" + from + ", " + to + ") or no bytes requested!");+ if (to > datalength - 1) abort("only " + datalength + " bytes available! programmer error!");+ // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);+ // Some hints to the browser that we want binary data.+ xhr.responseType = "arraybuffer";+ if (xhr.overrideMimeType) {+ xhr.overrideMimeType("text/plain; charset=x-user-defined");+ }+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ if (xhr.response !== undefined) {+ return new Uint8Array(/** @type{Array<number>} */ (xhr.response || []));+ }+ return intArrayFromString(xhr.responseText || "", true);+ };+ var lazyArray = this;+ lazyArray.setDataGetter(chunkNum => {+ var start = chunkNum * chunkSize;+ var end = (chunkNum + 1) * chunkSize - 1;+ // including this byte+ end = Math.min(end, datalength - 1);+ // if datalength-1 is selected, this is the last block+ if (typeof lazyArray.chunks[chunkNum] == "undefined") {+ lazyArray.chunks[chunkNum] = doXHR(start, end);+ }+ if (typeof lazyArray.chunks[chunkNum] == "undefined") abort("doXHR failed!");+ return lazyArray.chunks[chunkNum];+ });+ if (usesGzip || !datalength) {+ // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length+ chunkSize = datalength = 1;+ // this will force getter(0)/doXHR do download the whole file+ datalength = this.getter(0).length;+ chunkSize = datalength;+ out("LazyFiles on gzip forces download of the whole file when length is accessed");+ }+ this._length = datalength;+ this._chunkSize = chunkSize;+ this.lengthKnown = true;+ }+ get length() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._length;+ }+ get chunkSize() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._chunkSize;+ }+ }+ if (globalThis.XMLHttpRequest) {+ if (!ENVIRONMENT_IS_WORKER) abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");+ var lazyArray = new LazyUint8Array;+ var properties = {+ isDevice: false,+ contents: lazyArray+ };+ } else {+ var properties = {+ isDevice: false,+ url+ };+ }+ var node = FS.createFile(parent, name, properties, canRead, canWrite);+ // This is a total hack, but I want to get this lazy file code out of the+ // core of MEMFS. If we want to keep this lazy file concept I feel it should+ // be its own thin LAZYFS proxying calls to MEMFS.+ if (properties.contents) {+ node.contents = properties.contents;+ } else if (properties.url) {+ node.contents = null;+ node.url = properties.url;+ }+ // Add a function that defers querying the file size until it is asked the first time.+ Object.defineProperties(node, {+ usedBytes: {+ get: function() {+ return this.contents.length;+ }+ }+ });+ // override each stream op with one that tries to force load the lazy file first+ var stream_ops = {};+ for (const [key, fn] of Object.entries(node.stream_ops)) {+ stream_ops[key] = (...args) => {+ FS.forceLoadFile(node);+ return fn(...args);+ };+ }+ function writeChunks(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= contents.length) return 0;+ var size = Math.min(contents.length - position, length);+ if (contents.slice) {+ // normal array+ for (var i = 0; i < size; i++) {+ buffer[offset + i] = contents[position + i];+ }+ } else {+ for (var i = 0; i < size; i++) {+ // LazyUint8Array from sync binary XHR+ buffer[offset + i] = contents.get(position + i);+ }+ }+ return size;+ }+ // use a custom read function+ stream_ops.read = (stream, buffer, offset, length, position) => {+ FS.forceLoadFile(node);+ return writeChunks(stream, buffer, offset, length, position);+ };+ // use a custom mmap function+ stream_ops.mmap = (stream, length, position, prot, flags) => {+ FS.forceLoadFile(node);+ var ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ writeChunks(stream, HEAP8, ptr, length, position);+ return {+ ptr,+ allocated: true+ };+ };+ node.stream_ops = stream_ops;+ return node;+ }+};++/**+ * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the+ * emscripten HEAP, returns a copy of that string as a Javascript String object.+ *+ * @param {number} ptr+ * @param {number=} maxBytesToRead - An optional length that specifies the+ * maximum number of bytes to read. You can omit this parameter to scan the+ * string until the first 0 byte. If maxBytesToRead is passed, and the string+ * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the+ * string will cut short at that byte index.+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {+ if (!ptr) return "";+ var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));+};++var SYSCALLS = {+ calculateAt(dirfd, path, allowEmpty) {+ if (PATH.isAbs(path)) {+ return path;+ }+ // relative path+ var dir;+ if (dirfd === -100) {+ dir = FS.cwd();+ } else {+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);+ dir = dirstream.path;+ }+ if (path.length == 0) {+ if (!allowEmpty) {+ throw new FS.ErrnoError(44);+ }+ return dir;+ }+ return dir + "/" + path;+ },+ writeStat(buf, stat) {+ HEAPU32[((buf) >> 2)] = stat.dev;+ HEAPU32[(((buf) + (4)) >> 2)] = stat.mode;+ HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink;+ HEAPU32[(((buf) + (12)) >> 2)] = stat.uid;+ HEAPU32[(((buf) + (16)) >> 2)] = stat.gid;+ HEAPU32[(((buf) + (20)) >> 2)] = stat.rdev;+ (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ HEAP32[(((buf) + (32)) >> 2)] = 4096;+ HEAP32[(((buf) + (36)) >> 2)] = stat.blocks;+ var atime = stat.atime.getTime();+ var mtime = stat.mtime.getTime();+ var ctime = stat.ctime.getTime();+ (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]);+ return 0;+ },+ writeStatFs(buf, stats) {+ HEAPU32[(((buf) + (4)) >> 2)] = stats.bsize;+ HEAPU32[(((buf) + (60)) >> 2)] = stats.bsize;+ (tempI64 = [ stats.blocks >>> 0, (tempDouble = stats.blocks, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (8)) >> 2)] = tempI64[0], HEAP32[(((buf) + (12)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bfree >>> 0, (tempDouble = stats.bfree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (16)) >> 2)] = tempI64[0], HEAP32[(((buf) + (20)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bavail >>> 0, (tempDouble = stats.bavail, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.files >>> 0, (tempDouble = stats.files, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (32)) >> 2)] = tempI64[0], HEAP32[(((buf) + (36)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.ffree >>> 0, (tempDouble = stats.ffree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = stats.fsid;+ HEAPU32[(((buf) + (64)) >> 2)] = stats.flags;+ // ST_NOSUID+ HEAPU32[(((buf) + (56)) >> 2)] = stats.namelen;+ },+ doMsync(addr, stream, len, flags, offset) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ if (flags & 2) {+ // MAP_PRIVATE calls need not to be synced back to underlying fs+ return 0;+ }+ var buffer = HEAPU8.slice(addr, addr + len);+ FS.msync(stream, buffer, offset, len, flags);+ },+ getStreamFromFD(fd) {+ var stream = FS.getStreamChecked(fd);+ return stream;+ },+ varargs: undefined,+ getStr(ptr) {+ var ret = UTF8ToString(ptr);+ return ret;+ }+};++function ___syscall_dup(fd) {+ try {+ var old = SYSCALLS.getStreamFromFD(fd);+ return FS.dupStream(old).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_faccessat(dirfd, path, amode, flags) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (amode & ~7) {+ // need a valid mode+ return -28;+ }+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ if (!node) {+ return -44;+ }+ var perms = "";+ if (amode & 4) perms += "r";+ if (amode & 2) perms += "w";+ if (amode & 1) perms += "x";+ if (perms && FS.nodePermissions(node, perms)) {+ return -2;+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var syscallGetVarargI = () => {+ // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.+ var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];+ SYSCALLS.varargs += 4;+ return ret;+};++var syscallGetVarargP = syscallGetVarargI;++function ___syscall_fcntl64(fd, cmd, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (cmd) {+ case 0:+ {+ var arg = syscallGetVarargI();+ if (arg < 0) {+ return -28;+ }+ while (FS.streams[arg]) {+ arg++;+ }+ var newStream;+ newStream = FS.dupStream(stream, arg);+ return newStream.fd;+ }++ case 1:+ case 2:+ return 0;++ // FD_CLOEXEC makes no sense for a single process.+ case 3:+ return stream.flags;++ case 4:+ {+ var arg = syscallGetVarargI();+ stream.flags |= arg;+ return 0;+ }++ case 12:+ {+ var arg = syscallGetVarargP();+ var offset = 0;+ // We're always unlocked.+ HEAP16[(((arg) + (offset)) >> 1)] = 2;+ return 0;+ }++ case 13:+ case 14:+ // Pretend that the locking is successful. These are process-level locks,+ // and Emscripten programs are a single process. If we supported linking a+ // filesystem between programs, we'd need to do more here.+ // See https://github.com/emscripten-core/emscripten/issues/23697+ return 0;+ }+ return -28;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_fstat64(fd, buf) {+ try {+ return SYSCALLS.writeStat(buf, FS.fstat(fd));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;++function ___syscall_ftruncate64(fd, length_low, length_high) {+ var length = convertI32PairToI53Checked(length_low, length_high);+ try {+ if (isNaN(length)) return -61;+ FS.ftruncate(fd, length);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_ioctl(fd, op, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (op) {+ case 21509:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21505:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcgets) {+ var termios = stream.tty.ops.ioctl_tcgets(stream);+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = termios.c_iflag || 0;+ HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0;+ HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0;+ HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0;+ for (var i = 0; i < 32; i++) {+ HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0;+ }+ return 0;+ }+ return 0;+ }++ case 21510:+ case 21511:+ case 21512:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21506:+ case 21507:+ case 21508:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcsets) {+ var argp = syscallGetVarargP();+ var c_iflag = HEAP32[((argp) >> 2)];+ var c_oflag = HEAP32[(((argp) + (4)) >> 2)];+ var c_cflag = HEAP32[(((argp) + (8)) >> 2)];+ var c_lflag = HEAP32[(((argp) + (12)) >> 2)];+ var c_cc = [];+ for (var i = 0; i < 32; i++) {+ c_cc.push(HEAP8[(argp + i) + (17)]);+ }+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, {+ c_iflag,+ c_oflag,+ c_cflag,+ c_lflag,+ c_cc+ });+ }+ return 0;+ }++ case 21519:+ {+ if (!stream.tty) return -59;+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = 0;+ return 0;+ }++ case 21520:+ {+ if (!stream.tty) return -59;+ return -28;+ }++ case 21537:+ case 21531:+ {+ var argp = syscallGetVarargP();+ return FS.ioctl(stream, op, argp);+ }++ case 21523:+ {+ // TODO: in theory we should write to the winsize struct that gets+ // passed in, but for now musl doesn't read anything on it+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tiocgwinsz) {+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);+ var argp = syscallGetVarargP();+ HEAP16[((argp) >> 1)] = winsize[0];+ HEAP16[(((argp) + (2)) >> 1)] = winsize[1];+ }+ return 0;+ }++ case 21524:+ {+ // TODO: technically, this ioctl call should change the window size.+ // but, since emscripten doesn't have any concept of a terminal window+ // yet, we'll just silently throw it away as we do TIOCGWINSZ+ if (!stream.tty) return -59;+ return 0;+ }++ case 21515:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ default:+ return -28;+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_lstat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.lstat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_newfstatat(dirfd, path, buf, flags) {+ try {+ path = SYSCALLS.getStr(path);+ var nofollow = flags & 256;+ var allowEmpty = flags & 4096;+ flags = flags & (~6400);+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_openat(dirfd, path, flags, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ var mode = varargs ? syscallGetVarargI() : 0;+ return FS.open(path, flags, mode).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_stat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __abort_js = () => abort("");++var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {};++var AsciiToString = ptr => {+ var str = "";+ while (1) {+ var ch = HEAPU8[ptr++];+ if (!ch) return str;+ str += String.fromCharCode(ch);+ }+};++var awaitingDependencies = {};++var registeredTypes = {};++var typeDependencies = {};++var BindingError = class BindingError extends Error {+ constructor(message) {+ super(message);+ this.name = "BindingError";+ }+};++var throwBindingError = message => {+ throw new BindingError(message);+};++/** @param {Object=} options */ function sharedRegisterType(rawType, registeredInstance, options = {}) {+ var name = registeredInstance.name;+ if (!rawType) {+ throwBindingError(`type "${name}" must have a positive integer typeid pointer`);+ }+ if (registeredTypes.hasOwnProperty(rawType)) {+ if (options.ignoreDuplicateRegistrations) {+ return;+ } else {+ throwBindingError(`Cannot register type '${name}' twice`);+ }+ }+ registeredTypes[rawType] = registeredInstance;+ delete typeDependencies[rawType];+ if (awaitingDependencies.hasOwnProperty(rawType)) {+ var callbacks = awaitingDependencies[rawType];+ delete awaitingDependencies[rawType];+ callbacks.forEach(cb => cb());+ }+}++/** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) {+ return sharedRegisterType(rawType, registeredInstance, options);+}++/** @suppress {globalThis} */ var __embind_register_bool = (rawType, name, trueValue, falseValue) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: function(wt) {+ // ambiguous emscripten ABI: sometimes return values are+ // true or false, and sometimes integers (0 or 1)+ return !!wt;+ },+ toWireType: function(destructors, o) {+ return o ? trueValue : falseValue;+ },+ readValueFromPointer: function(pointer) {+ return this.fromWireType(HEAPU8[pointer]);+ },+ destructorFunction: null+ });+};++var emval_freelist = [];++var emval_handles = [ 0, 1, , 1, null, 1, true, 1, false, 1 ];++var __emval_decref = handle => {+ if (handle > 9 && 0 === --emval_handles[handle + 1]) {+ var value = emval_handles[handle];+ emval_handles[handle] = undefined;+ emval_freelist.push(handle);+ }+};++var Emval = {+ toValue: handle => {+ if (!handle) {+ throwBindingError(`Cannot use deleted val. handle = ${handle}`);+ }+ return emval_handles[handle];+ },+ toHandle: value => {+ switch (value) {+ case undefined:+ return 2;++ case null:+ return 4;++ case true:+ return 6;++ case false:+ return 8;++ default:+ {+ const handle = emval_freelist.pop() || emval_handles.length;+ emval_handles[handle] = value;+ emval_handles[handle + 1] = 1;+ return handle;+ }+ }+ }+};++/** @suppress {globalThis} */ function readPointer(pointer) {+ return this.fromWireType(HEAPU32[((pointer) >> 2)]);+}++var EmValType = {+ name: "emscripten::val",+ fromWireType: handle => {+ var rv = Emval.toValue(handle);+ __emval_decref(handle);+ return rv;+ },+ toWireType: (destructors, value) => Emval.toHandle(value),+ readValueFromPointer: readPointer,+ destructorFunction: null+};++var __embind_register_emval = rawType => registerType(rawType, EmValType);++var floatReadValueFromPointer = (name, width) => {+ switch (width) {+ case 4:+ return function(pointer) {+ return this.fromWireType(HEAPF32[((pointer) >> 2)]);+ };++ case 8:+ return function(pointer) {+ return this.fromWireType(HEAPF64[((pointer) >> 3)]);+ };++ default:+ throw new TypeError(`invalid float width (${width}): ${name}`);+ }+};++var __embind_register_float = (rawType, name, size) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: value => value,+ toWireType: (destructors, value) => value,+ readValueFromPointer: floatReadValueFromPointer(name, size),+ destructorFunction: null+ });+};++var integerReadValueFromPointer = (name, width, signed) => {+ // integers are quite common, so generate very specialized functions+ switch (width) {+ case 1:+ return signed ? pointer => HEAP8[pointer] : pointer => HEAPU8[pointer];++ case 2:+ return signed ? pointer => HEAP16[((pointer) >> 1)] : pointer => HEAPU16[((pointer) >> 1)];++ case 4:+ return signed ? pointer => HEAP32[((pointer) >> 2)] : pointer => HEAPU32[((pointer) >> 2)];++ default:+ throw new TypeError(`invalid integer width (${width}): ${name}`);+ }+};++/** @suppress {globalThis} */ var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => {+ name = AsciiToString(name);+ const isUnsignedType = minRange === 0;+ let fromWireType = value => value;+ if (isUnsignedType) {+ var bitshift = 32 - 8 * size;+ fromWireType = value => (value << bitshift) >>> bitshift;+ maxRange = fromWireType(maxRange);+ }+ registerType(primitiveType, {+ name,+ fromWireType,+ toWireType: (destructors, value) => value,+ readValueFromPointer: integerReadValueFromPointer(name, size, minRange !== 0),+ destructorFunction: null+ });+};++var __embind_register_memory_view = (rawType, dataTypeIndex, name) => {+ var typeMapping = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];+ var TA = typeMapping[dataTypeIndex];+ function decodeMemoryView(handle) {+ var size = HEAPU32[((handle) >> 2)];+ var data = HEAPU32[(((handle) + (4)) >> 2)];+ return new TA(HEAP8.buffer, data, size);+ }+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: decodeMemoryView,+ readValueFromPointer: decodeMemoryView+ }, {+ ignoreDuplicateRegistrations: true+ });+};++var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);++var __embind_register_std_string = (rawType, name) => {+ name = AsciiToString(name);+ var stdStringIsUTF8 = true;+ registerType(rawType, {+ name,+ // For some method names we use string keys here since they are part of+ // the public/external API and/or used by the runtime-generated code.+ fromWireType(value) {+ var length = HEAPU32[((value) >> 2)];+ var payload = value + 4;+ var str;+ if (stdStringIsUTF8) {+ str = UTF8ToString(payload, length, true);+ } else {+ str = "";+ for (var i = 0; i < length; ++i) {+ str += String.fromCharCode(HEAPU8[payload + i]);+ }+ }+ _free(value);+ return str;+ },+ toWireType(destructors, value) {+ if (value instanceof ArrayBuffer) {+ value = new Uint8Array(value);+ }+ var length;+ var valueIsOfTypeString = (typeof value == "string");+ // We accept `string` or array views with single byte elements+ if (!(valueIsOfTypeString || (ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1))) {+ throwBindingError("Cannot pass non-string to std::string");+ }+ if (stdStringIsUTF8 && valueIsOfTypeString) {+ length = lengthBytesUTF8(value);+ } else {+ length = value.length;+ }+ // assumes POINTER_SIZE alignment+ var base = _malloc(4 + length + 1);+ var ptr = base + 4;+ HEAPU32[((base) >> 2)] = length;+ if (valueIsOfTypeString) {+ if (stdStringIsUTF8) {+ stringToUTF8(value, ptr, length + 1);+ } else {+ for (var i = 0; i < length; ++i) {+ var charCode = value.charCodeAt(i);+ if (charCode > 255) {+ _free(base);+ throwBindingError("String has UTF-16 code units that do not fit in 8 bits");+ }+ HEAPU8[ptr + i] = charCode;+ }+ }+ } else {+ HEAPU8.set(value, ptr);+ }+ if (destructors !== null) {+ destructors.push(_free, base);+ }+ return base;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var UTF16Decoder = new TextDecoder("utf-16le");++var UTF16ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var idx = ((ptr) >> 1);+ var endIdx = findStringEnd(HEAPU16, idx, maxBytesToRead / 2, ignoreNul);+ return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx));+};++var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 2) return 0;+ maxBytesToWrite -= 2;+ // Null terminator.+ var startPtr = outPtr;+ var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length;+ for (var i = 0; i < numCharsToWrite; ++i) {+ // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.+ var codeUnit = str.charCodeAt(i);+ // possibly a lead surrogate+ HEAP16[((outPtr) >> 1)] = codeUnit;+ outPtr += 2;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP16[((outPtr) >> 1)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF16 = str => str.length * 2;++var UTF32ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var str = "";+ var startIdx = ((ptr) >> 2);+ // If maxBytesToRead is not passed explicitly, it will be undefined, and this+ // will always evaluate to true. This saves on code size.+ for (var i = 0; !(i >= maxBytesToRead / 4); i++) {+ var utf32 = HEAPU32[startIdx + i];+ if (!utf32 && !ignoreNul) break;+ str += String.fromCodePoint(utf32);+ }+ return str;+};++var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 4) return 0;+ var startPtr = outPtr;+ var endPtr = startPtr + maxBytesToWrite - 4;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ HEAP32[((outPtr) >> 2)] = codePoint;+ outPtr += 4;+ if (outPtr + 4 > endPtr) break;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP32[((outPtr) >> 2)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF32 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ len += 4;+ }+ return len;+};++var __embind_register_std_wstring = (rawType, charSize, name) => {+ name = AsciiToString(name);+ var decodeString, encodeString, lengthBytesUTF;+ if (charSize === 2) {+ decodeString = UTF16ToString;+ encodeString = stringToUTF16;+ lengthBytesUTF = lengthBytesUTF16;+ } else {+ decodeString = UTF32ToString;+ encodeString = stringToUTF32;+ lengthBytesUTF = lengthBytesUTF32;+ }+ registerType(rawType, {+ name,+ fromWireType: value => {+ // Code mostly taken from _embind_register_std_string fromWireType+ var length = HEAPU32[((value) >> 2)];+ var str = decodeString(value + 4, length * charSize, true);+ _free(value);+ return str;+ },+ toWireType: (destructors, value) => {+ if (!(typeof value == "string")) {+ throwBindingError(`Cannot pass non-string to C++ string type ${name}`);+ }+ // assumes POINTER_SIZE alignment+ var length = lengthBytesUTF(value);+ var ptr = _malloc(4 + length + charSize);+ HEAPU32[((ptr) >> 2)] = length / charSize;+ encodeString(value, ptr + 4, length + charSize);+ if (destructors !== null) {+ destructors.push(_free, ptr);+ }+ return ptr;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var __embind_register_void = (rawType, name) => {+ name = AsciiToString(name);+ registerType(rawType, {+ isVoid: true,+ // void return values can be optimized out sometimes+ name,+ fromWireType: () => undefined,+ // TODO: assert if anything else is given?+ toWireType: (destructors, o) => undefined+ });+};++var emval_methodCallers = [];++var emval_addMethodCaller = caller => {+ var id = emval_methodCallers.length;+ emval_methodCallers.push(caller);+ return id;+};++var getTypeName = type => {+ var ptr = ___getTypeName(type);+ var rv = AsciiToString(ptr);+ _free(ptr);+ return rv;+};++var requireRegisteredType = (rawType, humanName) => {+ var impl = registeredTypes[rawType];+ if (undefined === impl) {+ throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);+ }+ return impl;+};++var emval_lookupTypes = (argCount, argTypes) => {+ var a = new Array(argCount);+ for (var i = 0; i < argCount; ++i) {+ a[i] = requireRegisteredType(HEAPU32[(((argTypes) + (i * 4)) >> 2)], `parameter ${i}`);+ }+ return a;+};++var createNamedFunction = (name, func) => Object.defineProperty(func, "name", {+ value: name+});++var emval_returnValue = (toReturnWire, destructorsRef, handle) => {+ var destructors = [];+ var result = toReturnWire(destructors, handle);+ if (destructors.length) {+ // void, primitives and any other types w/o destructors don't need to allocate a handle+ HEAPU32[((destructorsRef) >> 2)] = Emval.toHandle(destructors);+ }+ return result;+};++var emval_symbols = {};++var getStringOrSymbol = address => {+ var symbol = emval_symbols[address];+ if (symbol === undefined) {+ return AsciiToString(address);+ }+ return symbol;+};++var __emval_create_invoker = (argCount, argTypesPtr, kind) => {+ var GenericWireTypeSize = 8;+ var [retType, ...argTypes] = emval_lookupTypes(argCount, argTypesPtr);+ var toReturnWire = retType.toWireType.bind(retType);+ var argFromPtr = argTypes.map(type => type.readValueFromPointer.bind(type));+ argCount--;+ // remove the extracted return type+ var argN = new Array(argCount);+ var invokerFunction = (handle, methodName, destructorsRef, args) => {+ var offset = 0;+ for (var i = 0; i < argCount; ++i) {+ argN[i] = argFromPtr[i](args + offset);+ offset += GenericWireTypeSize;+ }+ var rv;+ switch (kind) {+ case 0:+ rv = Emval.toValue(handle).apply(null, argN);+ break;++ case 2:+ rv = Reflect.construct(Emval.toValue(handle), argN);+ break;++ case 3:+ // no-op, just return the argument+ rv = argN[0];+ break;++ case 1:+ rv = Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);+ break;+ }+ return emval_returnValue(toReturnWire, destructorsRef, rv);+ };+ var functionName = `methodCaller<(${argTypes.map(t => t.name)}) => ${retType.name}>`;+ return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction));+};++var __emval_get_global = name => {+ if (!name) {+ return Emval.toHandle(globalThis);+ }+ name = getStringOrSymbol(name);+ return Emval.toHandle(globalThis[name]);+};++var __emval_get_property = (handle, key) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ return Emval.toHandle(handle[key]);+};++var __emval_incref = handle => {+ if (handle > 9) {+ emval_handles[handle + 1] += 1;+ }+};++var __emval_instanceof = (object, constructor) => {+ object = Emval.toValue(object);+ constructor = Emval.toValue(constructor);+ return object instanceof constructor;+};++var __emval_invoke = (caller, handle, methodName, destructorsRef, args) => emval_methodCallers[caller](handle, methodName, destructorsRef, args);++var __emval_new_cstring = v => Emval.toHandle(getStringOrSymbol(v));++var runDestructors = destructors => {+ while (destructors.length) {+ var ptr = destructors.pop();+ var del = destructors.pop();+ del(ptr);+ }+};++var __emval_run_destructors = handle => {+ var destructors = Emval.toValue(handle);+ runDestructors(destructors);+ __emval_decref(handle);+};++var __emval_set_property = (handle, key, value) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ value = Emval.toValue(value);+ handle[key] = value;+};++var __emval_typeof = handle => {+ handle = Emval.toValue(handle);+ return Emval.toHandle(typeof handle);+};++function __gmtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getUTCSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getUTCMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getUTCHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getUTCDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getUTCMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getUTCFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getUTCDay();+ var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);+ var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+}++var isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);++var MONTH_DAYS_LEAP_CUMULATIVE = [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ];++var MONTH_DAYS_REGULAR_CUMULATIVE = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ];++var ydayFromDate = date => {+ var leap = isLeapYear(date.getFullYear());+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;+ // -1 since it's days since Jan 1+ return yday;+};++function __localtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ HEAP32[(((tmPtr) + (36)) >> 2)] = -(date.getTimezoneOffset() * 60);+ // Attention: DST is in December in South, and some regions don't have DST at all.+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;+ HEAP32[(((tmPtr) + (32)) >> 2)] = dst;+}++var setTempRet0 = val => __emscripten_tempret_set(val);++var __mktime_js = function(tmPtr) {+ var ret = (() => {+ var date = new Date(HEAP32[(((tmPtr) + (20)) >> 2)] + 1900, HEAP32[(((tmPtr) + (16)) >> 2)], HEAP32[(((tmPtr) + (12)) >> 2)], HEAP32[(((tmPtr) + (8)) >> 2)], HEAP32[(((tmPtr) + (4)) >> 2)], HEAP32[((tmPtr) >> 2)], 0);+ // There's an ambiguous hour when the time goes back; the tm_isdst field is+ // used to disambiguate it. Date() basically guesses, so we fix it up if it+ // guessed wrong, or fill in tm_isdst with the guess if it's -1.+ var dst = HEAP32[(((tmPtr) + (32)) >> 2)];+ var guessedOffset = date.getTimezoneOffset();+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dstOffset = Math.min(winterOffset, summerOffset);+ // DST is in December in South+ if (dst < 0) {+ // Attention: some regions don't have DST at all.+ HEAP32[(((tmPtr) + (32)) >> 2)] = Number(summerOffset != winterOffset && dstOffset == guessedOffset);+ } else if ((dst > 0) != (dstOffset == guessedOffset)) {+ var nonDstOffset = Math.max(winterOffset, summerOffset);+ var trueOffset = dst > 0 ? dstOffset : nonDstOffset;+ // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.+ date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4);+ }+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ // To match expected behavior, update fields from date+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getYear();+ var timeMs = date.getTime();+ if (isNaN(timeMs)) {+ return -1;+ }+ // Return time in microseconds+ return timeMs / 1e3;+ })();+ return (setTempRet0((tempDouble = ret, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0)),+ ret >>> 0);+};++function __mmap_js(len, prot, flags, fd, offset_low, offset_high, allocated, addr) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var res = FS.mmap(stream, len, offset, prot, flags);+ var ptr = res.ptr;+ HEAP32[((allocated) >> 2)] = res.allocated;+ HEAPU32[((addr) >> 2)] = ptr;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function __munmap_js(addr, len, prot, flags, fd, offset_low, offset_high) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ if (prot & 2) {+ SYSCALLS.doMsync(addr, stream, len, flags, offset);+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __tzset_js = (timezone, daylight, std_name, dst_name) => {+ // TODO: Use (malleable) environment variables instead of system settings.+ var currentYear = (new Date).getFullYear();+ var winter = new Date(currentYear, 0, 1);+ var summer = new Date(currentYear, 6, 1);+ var winterOffset = winter.getTimezoneOffset();+ var summerOffset = summer.getTimezoneOffset();+ // Local standard timezone offset. Local standard time is not adjusted for+ // daylight savings. This code uses the fact that getTimezoneOffset returns+ // a greater value during Standard Time versus Daylight Saving Time (DST).+ // Thus it determines the expected output during Standard Time, and it+ // compares whether the output of the given date the same (Standard) or less+ // (DST).+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);+ // timezone is specified as seconds west of UTC ("The external variable+ // `timezone` shall be set to the difference, in seconds, between+ // Coordinated Universal Time (UTC) and local standard time."), the same+ // as returned by stdTimezoneOffset.+ // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html+ HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60;+ HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset);+ var extractZone = timezoneOffset => {+ // Why inverse sign?+ // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset+ var sign = timezoneOffset >= 0 ? "-" : "+";+ var absOffset = Math.abs(timezoneOffset);+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");+ var minutes = String(absOffset % 60).padStart(2, "0");+ return `UTC${sign}${hours}${minutes}`;+ };+ var winterName = extractZone(winterOffset);+ var summerName = extractZone(summerOffset);+ if (summerOffset < winterOffset) {+ // Northern hemisphere+ stringToUTF8(winterName, std_name, 17);+ stringToUTF8(summerName, dst_name, 17);+ } else {+ stringToUTF8(winterName, dst_name, 17);+ stringToUTF8(summerName, std_name, 17);+ }+};++var _emscripten_get_now = () => performance.now();++var _emscripten_date_now = () => Date.now();++var nowIsMonotonic = 1;++var checkWasiClock = clock_id => clock_id >= 0 && clock_id <= 3;++function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) {+ var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high);+ if (!checkWasiClock(clk_id)) {+ return 28;+ }+ var now;+ // all wasi clocks but realtime are monotonic+ if (clk_id === 0) {+ now = _emscripten_date_now();+ } else if (nowIsMonotonic) {+ now = _emscripten_get_now();+ } else {+ return 52;+ }+ // "now" is in ms, and wasi times are in ns.+ var nsec = Math.round(now * 1e3 * 1e3);+ (tempI64 = [ nsec >>> 0, (tempDouble = nsec, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((ptime) >> 2)] = tempI64[0], HEAP32[(((ptime) + (4)) >> 2)] = tempI64[1]);+ return 0;+}++var readEmAsmArgsArray = [];++var readEmAsmArgs = (sigPtr, buf) => {+ readEmAsmArgsArray.length = 0;+ var ch;+ // Most arguments are i32s, so shift the buffer pointer so it is a plain+ // index into HEAP32.+ while (ch = HEAPU8[sigPtr++]) {+ // Floats are always passed as doubles, so all types except for 'i'+ // are 8 bytes and require alignment.+ var wide = (ch != 105);+ wide &= (ch != 112);+ buf += wide && (buf % 8) ? 4 : 0;+ readEmAsmArgsArray.push(// Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode.+ ch == 112 ? HEAPU32[((buf) >> 2)] : ch == 105 ? HEAP32[((buf) >> 2)] : HEAPF64[((buf) >> 3)]);+ buf += wide ? 8 : 4;+ }+ return readEmAsmArgsArray;+};++var runEmAsmFunction = (code, sigPtr, argbuf) => {+ var args = readEmAsmArgs(sigPtr, argbuf);+ return ASM_CONSTS[code](...args);+};++var _emscripten_asm_const_int = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_errn = (str, len) => err(UTF8ToString(str, len));++var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate+// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side+// for any code that deals with heap sizes, which would require special+// casing all heap size related code to treat 0 specially.+2147483648;++var _emscripten_get_heap_max = () => getHeapMax();++var _emscripten_has_asyncify = () => 0;++var _emscripten_outn = (str, len) => out(UTF8ToString(str, len));++var UNWIND_CACHE = {};++var stringToNewUTF8 = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = _malloc(size);+ if (ret) stringToUTF8(str, ret, size);+ return ret;+};++/** @returns {number} */ var convertFrameToPC = frame => {+ var match;+ if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) {+ // Wasm engines give the binary offset directly, so we use that as return address+ return +match[1];+ } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) {+ // If we are in js, we can use the js line number as the "return address".+ // This should work for wasm2js. We tag the high bit to distinguish this+ // from wasm addresses.+ return 2147483648 | +match[1];+ }+ // return 0 if we can't find any+ return 0;+};++var saveInUnwindCache = callstack => {+ for (var line of callstack) {+ var pc = convertFrameToPC(line);+ if (pc) {+ UNWIND_CACHE[pc] = line;+ }+ }+};++var jsStackTrace = () => (new Error).stack.toString();++var _emscripten_stack_snapshot = () => {+ var callstack = jsStackTrace().split("\n");+ if (callstack[0] == "Error") {+ callstack.shift();+ }+ saveInUnwindCache(callstack);+ // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can+ // unwind from this spot.+ UNWIND_CACHE.last_addr = convertFrameToPC(callstack[3]);+ UNWIND_CACHE.last_stack = callstack;+ return UNWIND_CACHE.last_addr;+};++var _emscripten_pc_get_function = pc => {+ var frame = UNWIND_CACHE[pc];+ if (!frame) return 0;+ var name;+ var match;+ // First try to match foo.wasm.sym files explcitly. e.g.+ // at test_return_address.wasm.main (wasm://wasm/test_return_address.wasm-0012cc2a:wasm-function[26]:0x9f3+ // Then match JS symbols which don't include that module name:+ // at invokeEntryPoint (.../test_return_address.js:1500:42)+ // Finally match firefox format:+ // Object._main@http://server.com:4324:12'+ if (match = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^(.+?)@/.exec(frame)) {+ name = match[1];+ } else {+ return 0;+ }+ _free(_emscripten_pc_get_function.ret ?? 0);+ _emscripten_pc_get_function.ret = stringToNewUTF8(name);+ return _emscripten_pc_get_function.ret;+};++var growMemory = size => {+ var oldHeapSize = wasmMemory.buffer.byteLength;+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;+ try {+ // round size grow request up to wasm page size (fixed 64KB per spec)+ wasmMemory.grow(pages);+ // .grow() takes a delta compared to the previous size+ updateMemoryViews();+ return 1;+ } catch (e) {}+};++var _emscripten_resize_heap = requestedSize => {+ var oldSize = HEAPU8.length;+ // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.+ requestedSize >>>= 0;+ // With multithreaded builds, races can happen (another thread might increase the size+ // in between), so return a failure, and let the caller retry.+ // Memory resize rules:+ // 1. Always increase heap size to at least the requested size, rounded up+ // to next page multiple.+ // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap+ // geometrically: increase the heap size according to+ // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most+ // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).+ // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap+ // linearly: increase the heap size by at least+ // MEMORY_GROWTH_LINEAR_STEP bytes.+ // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by+ // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest+ // 4. If we were unable to allocate as much memory, it may be due to+ // over-eager decision to excessively reserve due to (3) above.+ // Hence if an allocation fails, cut down on the amount of excess+ // growth, in an attempt to succeed to perform a smaller allocation.+ // A limit is set for how much we can grow. We should not exceed that+ // (the wasm binary specifies it, so if we tried, we'd fail anyhow).+ var maxHeapSize = getHeapMax();+ if (requestedSize > maxHeapSize) {+ return false;+ }+ // Loop through potential heap size increases. If we attempt a too eager+ // reservation that fails, cut down on the attempted size and reserve a+ // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {+ var overGrownHeapSize = oldSize * (1 + .2 / cutDown);+ // ensure geometric growth+ // but limit overreserving (default to capping at +96MB overgrowth at most)+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));+ var replacement = growMemory(newSize);+ if (replacement) {+ return true;+ }+ }+ return false;+};++var _emscripten_stack_unwind_buffer = (addr, buffer, count) => {+ var stack;+ if (UNWIND_CACHE.last_addr == addr) {+ stack = UNWIND_CACHE.last_stack;+ } else {+ stack = jsStackTrace().split("\n");+ if (stack[0] == "Error") {+ stack.shift();+ }+ saveInUnwindCache(stack);+ }+ var offset = 3;+ while (stack[offset] && convertFrameToPC(stack[offset]) != addr) {+ ++offset;+ }+ for (var i = 0; i < count && stack[i + offset]; ++i) {+ HEAP32[(((buffer) + (i * 4)) >> 2)] = convertFrameToPC(stack[i + offset]);+ }+ return i;+};++var GLctx;++var webgl_enable_ANGLE_instanced_arrays = ctx => {+ // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("ANGLE_instanced_arrays");+ // Because this extension is a core function in WebGL 2, assign the extension entry points in place of+ // where the core functions will reside in WebGL 2. This way the calling code can call these without+ // having to dynamically branch depending if running against WebGL 1 or WebGL 2.+ if (ext) {+ ctx["vertexAttribDivisor"] = (index, divisor) => ext["vertexAttribDivisorANGLE"](index, divisor);+ ctx["drawArraysInstanced"] = (mode, first, count, primcount) => ext["drawArraysInstancedANGLE"](mode, first, count, primcount);+ ctx["drawElementsInstanced"] = (mode, count, type, indices, primcount) => ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount);+ return 1;+ }+};++var webgl_enable_OES_vertex_array_object = ctx => {+ // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("OES_vertex_array_object");+ if (ext) {+ ctx["createVertexArray"] = () => ext["createVertexArrayOES"]();+ ctx["deleteVertexArray"] = vao => ext["deleteVertexArrayOES"](vao);+ ctx["bindVertexArray"] = vao => ext["bindVertexArrayOES"](vao);+ ctx["isVertexArray"] = vao => ext["isVertexArrayOES"](vao);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_buffers = ctx => {+ // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("WEBGL_draw_buffers");+ if (ext) {+ ctx["drawBuffers"] = (n, bufs) => ext["drawBuffersWEBGL"](n, bufs);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance = ctx => // Closure is expected to be allowed to minify the '.dibvbi' property, so not accessing it quoted.+!!(ctx.dibvbi = ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));++var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance = ctx => !!(ctx.mdibvbi = ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));++var webgl_enable_EXT_polygon_offset_clamp = ctx => !!(ctx.extPolygonOffsetClamp = ctx.getExtension("EXT_polygon_offset_clamp"));++var webgl_enable_EXT_clip_control = ctx => !!(ctx.extClipControl = ctx.getExtension("EXT_clip_control"));++var webgl_enable_WEBGL_polygon_mode = ctx => !!(ctx.webglPolygonMode = ctx.getExtension("WEBGL_polygon_mode"));++var webgl_enable_WEBGL_multi_draw = ctx => // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted.+!!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw"));++var getEmscriptenSupportedExtensions = ctx => {+ // Restrict the list of advertised extensions to those that we actually+ // support.+ var supportedExtensions = [ // WebGL 1 extensions+ "ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_disjoint_timer_query", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_sRGB", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_depth_texture", "WEBGL_draw_buffers", // WebGL 2 extensions+ "EXT_color_buffer_float", "EXT_conservative_depth", "EXT_disjoint_timer_query_webgl2", "EXT_texture_norm16", "NV_shader_noperspective_interpolation", "WEBGL_clip_cull_distance", // WebGL 1 and WebGL 2 extensions+ "EXT_clip_control", "EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_float_blend", "EXT_polygon_offset_clamp", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "KHR_parallel_shader_compile", "OES_texture_float_linear", "WEBGL_blend_func_extended", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_lose_context", "WEBGL_multi_draw", "WEBGL_polygon_mode" ];+ // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.+ return (ctx.getSupportedExtensions() || []).filter(ext => supportedExtensions.includes(ext));+};++var registerPreMainLoop = f => {+ // Does nothing unless $MainLoop is included/used.+ typeof MainLoop != "undefined" && MainLoop.preMainLoop.push(f);+};++var GL = {+ counter: 1,+ buffers: [],+ mappedBuffers: {},+ programs: [],+ framebuffers: [],+ renderbuffers: [],+ textures: [],+ shaders: [],+ vaos: [],+ contexts: [],+ offscreenCanvases: {},+ queries: [],+ samplers: [],+ transformFeedbacks: [],+ syncs: [],+ byteSizeByTypeRoot: 5120,+ byteSizeByType: [ 1, 1, 2, 2, 4, 4, 4, 2, 3, 4, 8 ],+ stringCache: {},+ stringiCache: {},+ unpackAlignment: 4,+ unpackRowLength: 0,+ recordError: errorCode => {+ if (!GL.lastError) {+ GL.lastError = errorCode;+ }+ },+ getNewId: table => {+ var ret = GL.counter++;+ for (var i = table.length; i < ret; i++) {+ table[i] = null;+ }+ // Skip over any non-null elements that might have been created by+ // glBindBuffer.+ while (table[ret]) {+ ret = GL.counter++;+ }+ return ret;+ },+ genObject: (n, buffers, createFunction, objectTable) => {+ for (var i = 0; i < n; i++) {+ var buffer = GLctx[createFunction]();+ var id = buffer && GL.getNewId(objectTable);+ if (buffer) {+ buffer.name = id;+ objectTable[id] = buffer;+ } else {+ GL.recordError(1282);+ }+ HEAP32[(((buffers) + (i * 4)) >> 2)] = id;+ }+ },+ MAX_TEMP_BUFFER_SIZE: 2097152,+ numTempVertexBuffersPerSize: 64,+ log2ceilLookup: i => 32 - Math.clz32(i === 0 ? 0 : i - 1),+ generateTempBuffers: (quads, context) => {+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ context.tempVertexBufferCounters1 = [];+ context.tempVertexBufferCounters2 = [];+ context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex + 1;+ context.tempVertexBuffers1 = [];+ context.tempVertexBuffers2 = [];+ context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex + 1;+ context.tempIndexBuffers = [];+ context.tempIndexBuffers.length = largestIndex + 1;+ for (var i = 0; i <= largestIndex; ++i) {+ context.tempIndexBuffers[i] = null;+ // Created on-demand+ context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;+ var ringbufferLength = GL.numTempVertexBuffersPerSize;+ context.tempVertexBuffers1[i] = [];+ context.tempVertexBuffers2[i] = [];+ var ringbuffer1 = context.tempVertexBuffers1[i];+ var ringbuffer2 = context.tempVertexBuffers2[i];+ ringbuffer1.length = ringbuffer2.length = ringbufferLength;+ for (var j = 0; j < ringbufferLength; ++j) {+ ringbuffer1[j] = ringbuffer2[j] = null;+ }+ }+ if (quads) {+ // GL_QUAD indexes can be precalculated+ context.tempQuadIndexBuffer = GLctx.createBuffer();+ context.GLctx.bindBuffer(34963, context.tempQuadIndexBuffer);+ var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;+ var quadIndexes = new Uint16Array(numIndexes);+ var i = 0, v = 0;+ while (1) {+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 1;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 3;+ if (i >= numIndexes) break;+ v += 4;+ }+ context.GLctx.bufferData(34963, quadIndexes, 35044);+ context.GLctx.bindBuffer(34963, null);+ }+ },+ getTempVertexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];+ var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];+ GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx] + 1) & (GL.numTempVertexBuffersPerSize - 1);+ var vbo = ringbuffer[nextFreeBufferIndex];+ if (vbo) {+ return vbo;+ }+ var prevVBO = GLctx.getParameter(34964);+ ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();+ GLctx.bindBuffer(34962, ringbuffer[nextFreeBufferIndex]);+ GLctx.bufferData(34962, 1 << idx, 35048);+ GLctx.bindBuffer(34962, prevVBO);+ return ringbuffer[nextFreeBufferIndex];+ },+ getTempIndexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ibo = GL.currentContext.tempIndexBuffers[idx];+ if (ibo) {+ return ibo;+ }+ var prevIBO = GLctx.getParameter(34965);+ GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();+ GLctx.bindBuffer(34963, GL.currentContext.tempIndexBuffers[idx]);+ GLctx.bufferData(34963, 1 << idx, 35048);+ GLctx.bindBuffer(34963, prevIBO);+ return GL.currentContext.tempIndexBuffers[idx];+ },+ newRenderingFrameStarted: () => {+ if (!GL.currentContext) {+ return;+ }+ var vb = GL.currentContext.tempVertexBuffers1;+ GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;+ GL.currentContext.tempVertexBuffers2 = vb;+ vb = GL.currentContext.tempVertexBufferCounters1;+ GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;+ GL.currentContext.tempVertexBufferCounters2 = vb;+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ for (var i = 0; i <= largestIndex; ++i) {+ GL.currentContext.tempVertexBufferCounters1[i] = 0;+ }+ },+ getSource: (shader, count, string, length) => {+ var source = "";+ for (var i = 0; i < count; ++i) {+ var len = length ? HEAPU32[(((length) + (i * 4)) >> 2)] : undefined;+ source += UTF8ToString(HEAPU32[(((string) + (i * 4)) >> 2)], len);+ }+ return source;+ },+ calcBufLength: (size, type, stride, count) => {+ if (stride > 0) {+ return count * stride;+ }+ var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];+ return size * typeSize * count;+ },+ usedTempBuffers: [],+ preDrawHandleClientVertexAttribBindings: count => {+ GL.resetBufferBinding = false;+ // TODO: initial pass to detect ranges we need to upload, might not need+ // an upload per attrib+ for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {+ var cb = GL.currentContext.clientBuffers[i];+ if (!cb.clientside || !cb.enabled) continue;+ GL.resetBufferBinding = true;+ var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);+ var buf = GL.getTempVertexBuffer(size);+ GLctx.bindBuffer(34962, buf);+ GLctx.bufferSubData(34962, 0, HEAPU8.subarray(cb.ptr, cb.ptr + size));+ cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0);+ }+ },+ postDrawHandleClientVertexAttribBindings: () => {+ if (GL.resetBufferBinding) {+ GLctx.bindBuffer(34962, GL.buffers[GLctx.currentArrayBufferBinding]);+ }+ },+ createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => {+ // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL+ // context on a canvas, calling .getContext() will always return that+ // context independent of which 'webgl' or 'webgl2'+ // context version was passed. See:+ // https://webkit.org/b/222758+ // and:+ // https://github.com/emscripten-core/emscripten/issues/13295.+ // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari+ // version field in above check.+ if (!canvas.getContextSafariWebGL2Fixed) {+ canvas.getContextSafariWebGL2Fixed = canvas.getContext;+ /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ function fixedGetContext(ver, attrs) {+ var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs);+ return ((ver == "webgl") == (gl instanceof WebGLRenderingContext)) ? gl : null;+ }+ canvas.getContext = fixedGetContext;+ }+ var ctx = (webGLContextAttributes.majorVersion > 1) ? canvas.getContext("webgl2", webGLContextAttributes) : canvas.getContext("webgl", webGLContextAttributes);+ if (!ctx) return 0;+ var handle = GL.registerContext(ctx, webGLContextAttributes);+ return handle;+ },+ registerContext: (ctx, webGLContextAttributes) => {+ // without pthreads a context is just an integer ID+ var handle = GL.getNewId(GL.contexts);+ var context = {+ handle,+ attributes: webGLContextAttributes,+ version: webGLContextAttributes.majorVersion,+ GLctx: ctx+ };+ // Store the created context object so that we can access the context+ // given a canvas without having to pass the parameters again.+ if (ctx.canvas) ctx.canvas.GLctxObject = context;+ GL.contexts[handle] = context;+ if (typeof webGLContextAttributes.enableExtensionsByDefault == "undefined" || webGLContextAttributes.enableExtensionsByDefault) {+ GL.initExtensions(context);+ }+ context.maxVertexAttribs = context.GLctx.getParameter(34921);+ context.clientBuffers = [];+ for (var i = 0; i < context.maxVertexAttribs; i++) {+ context.clientBuffers[i] = {+ enabled: false,+ clientside: false,+ size: 0,+ type: 0,+ normalized: 0,+ stride: 0,+ ptr: 0,+ vertexAttribPointerAdaptor: null+ };+ }+ GL.generateTempBuffers(false, context);+ return handle;+ },+ makeContextCurrent: contextHandle => {+ // Active Emscripten GL layer context object.+ GL.currentContext = GL.contexts[contextHandle];+ // Active WebGL context object.+ Module["ctx"] = GLctx = GL.currentContext?.GLctx;+ return !(contextHandle && !GLctx);+ },+ getContext: contextHandle => GL.contexts[contextHandle],+ deleteContext: contextHandle => {+ if (GL.currentContext === GL.contexts[contextHandle]) {+ GL.currentContext = null;+ }+ if (typeof JSEvents == "object") {+ // Release all JS event handlers on the DOM element that the GL context is+ // associated with since the context is now deleted.+ JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);+ }+ // Make sure the canvas object no longer refers to the context object so+ // there are no GC surprises.+ if (GL.contexts[contextHandle]?.GLctx.canvas) {+ GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined;+ }+ GL.contexts[contextHandle] = null;+ },+ initExtensions: context => {+ // If this function is called without a specific context object, init the+ // extensions of the currently active context.+ context ||= GL.currentContext;+ if (context.initExtensionsDone) return;+ context.initExtensionsDone = true;+ var GLctx = context.GLctx;+ // Detect the presence of a few extensions manually, since the GL interop+ // layer itself will need to know if they exist.+ // Extensions that are available in both WebGL 1 and WebGL 2+ webgl_enable_WEBGL_multi_draw(GLctx);+ webgl_enable_EXT_polygon_offset_clamp(GLctx);+ webgl_enable_EXT_clip_control(GLctx);+ webgl_enable_WEBGL_polygon_mode(GLctx);+ // Extensions that are only available in WebGL 1 (the calls will be no-ops+ // if called on a WebGL 2 context active)+ webgl_enable_ANGLE_instanced_arrays(GLctx);+ webgl_enable_OES_vertex_array_object(GLctx);+ webgl_enable_WEBGL_draw_buffers(GLctx);+ // Extensions that are available from WebGL >= 2 (no-op if called on a WebGL 1 context active)+ webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);+ webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);+ // On WebGL 2, EXT_disjoint_timer_query is replaced with an alternative+ // that's based on core APIs, and exposes only the queryCounterEXT()+ // entrypoint.+ if (context.version >= 2) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query_webgl2");+ }+ // However, Firefox exposes the WebGL 1 version on WebGL 2 as well and+ // thus we look for the WebGL 1 version again if the WebGL 2 version+ // isn't present. https://bugzil.la/1328882+ if (context.version < 2 || !GLctx.disjointTimerQueryExt) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");+ }+ for (var ext of getEmscriptenSupportedExtensions(GLctx)) {+ // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders+ // are not enabled by default.+ if (!ext.includes("lose_context") && !ext.includes("debug")) {+ // Call .getExtension() to enable that extension permanently.+ GLctx.getExtension(ext);+ }+ }+ }+};++var webglPowerPreferences = [ "default", "low-power", "high-performance" ];++/** @type {Object} */ var specialHTMLTargets = [ 0, globalThis.document ?? 0, globalThis.window ?? 0 ];++var findEventTarget = target => {+ // The sensible "default" target varies between events, but use window as the default+ // since DOM events mostly can default to that. Specific callback registrations+ // override their own defaults.+ if (!target) return window;+ if (typeof target == "number") target = specialHTMLTargets[target] || UTF8ToString(target);+ if (target === "#window") return window; else if (target === "#document") return document; else if (target === "#screen") return screen; else if (target === "#canvas") return Module["canvas"]; else if (typeof target == "string") return globalThis.document?.getElementById(target);+ return target;+};++var findCanvasEventTarget = target => {+ if (typeof target == "number") target = UTF8ToString(target);+ if (!target || target === "#canvas") {+ if (typeof GL != "undefined" && GL.offscreenCanvases["canvas"]) return GL.offscreenCanvases["canvas"];+ // TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.+ return Module["canvas"];+ }+ if (typeof GL != "undefined" && GL.offscreenCanvases[target]) return GL.offscreenCanvases[target];+ return findEventTarget(target);+};++var _emscripten_webgl_do_create_context = (target, attributes) => {+ var attr32 = ((attributes) >> 2);+ var powerPreference = HEAP32[attr32 + (8 >> 2)];+ var contextAttributes = {+ "alpha": !!HEAP8[attributes + 0],+ "depth": !!HEAP8[attributes + 1],+ "stencil": !!HEAP8[attributes + 2],+ "antialias": !!HEAP8[attributes + 3],+ "premultipliedAlpha": !!HEAP8[attributes + 4],+ "preserveDrawingBuffer": !!HEAP8[attributes + 5],+ "powerPreference": webglPowerPreferences[powerPreference],+ "failIfMajorPerformanceCaveat": !!HEAP8[attributes + 12],+ // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure.+ majorVersion: HEAP32[attr32 + (16 >> 2)],+ minorVersion: HEAP32[attr32 + (20 >> 2)],+ enableExtensionsByDefault: HEAP8[attributes + 24],+ explicitSwapControl: HEAP8[attributes + 25],+ proxyContextToMainThread: HEAP32[attr32 + (28 >> 2)],+ renderViaOffscreenBackBuffer: HEAP8[attributes + 32]+ };+ var canvas = findCanvasEventTarget(target);+ if (!canvas) {+ return 0;+ }+ if (contextAttributes.explicitSwapControl) {+ return 0;+ }+ var contextHandle = GL.createContext(canvas, contextAttributes);+ return contextHandle;+};++var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context;++var _emscripten_webgl_destroy_context = contextHandle => {+ if (GL.currentContext == contextHandle) GL.currentContext = 0;+ GL.deleteContext(contextHandle);+};++var _emscripten_webgl_get_context_attributes = (c, a) => {+ if (!a) return -5;+ c = GL.contexts[c];+ if (!c) return -3;+ var t = c.GLctx?.getContextAttributes();+ if (!t) return -3;+ HEAP8[a] = t.alpha;+ HEAP8[(a) + (1)] = t.depth;+ HEAP8[(a) + (2)] = t.stencil;+ HEAP8[(a) + (3)] = t.antialias;+ HEAP8[(a) + (4)] = t.premultipliedAlpha;+ HEAP8[(a) + (5)] = t.preserveDrawingBuffer;+ var power = t["powerPreference"] && webglPowerPreferences.indexOf(t["powerPreference"]);+ HEAP32[(((a) + (8)) >> 2)] = power;+ HEAP8[(a) + (12)] = t.failIfMajorPerformanceCaveat;+ HEAP32[(((a) + (16)) >> 2)] = c.version;+ HEAP32[(((a) + (20)) >> 2)] = 0;+ HEAP8[(a) + (24)] = c.attributes.enableExtensionsByDefault;+ return 0;+};++var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0;++var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context;++var _emscripten_webgl_make_context_current = contextHandle => {+ var success = GL.makeContextCurrent(contextHandle);+ return success ? 0 : -5;+};++var stackAlloc = sz => __emscripten_stack_alloc(sz);++var stringToUTF8OnStack = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = stackAlloc(size);+ stringToUTF8(str, ret, size);+ return ret;+};++var writeI53ToI64 = (ptr, num) => {+ HEAPU32[((ptr) >> 2)] = num;+ var lower = HEAPU32[((ptr) >> 2)];+ HEAPU32[(((ptr) + (4)) >> 2)] = (num - lower) / 4294967296;+};++var readI53FromI64 = ptr => HEAPU32[((ptr) >> 2)] + HEAP32[(((ptr) + (4)) >> 2)] * 4294967296;++var wasmTableMirror = [];++var getWasmTableEntry = funcPtr => {+ var func = wasmTableMirror[funcPtr];+ if (!func) {+ /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);+ }+ return func;+};++var WebGPU = {+ Internals: {+ jsObjects: [],+ jsObjectInsert: (ptr, jsObject) => {+ ptr >>>= 0;+ WebGPU.Internals.jsObjects[ptr] = jsObject;+ },+ bufferOnUnmaps: [],+ futures: [],+ futureInsert: (futureId, promise) => {}+ },+ getJsObject: ptr => {+ if (!ptr) return undefined;+ ptr >>>= 0;+ return WebGPU.Internals.jsObjects[ptr];+ },+ importJsAdapter: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateAdapter(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroup: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroup(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroupLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroupLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBuffer: (buffer, parentPtr = 0) => {+ // At the moment, we do not allow importing pending buffers.+ assert(buffer.mapState === "unmapped");+ var bufferPtr = _emwgpuImportBuffer(parentPtr);+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ return bufferPtr;+ },+ importJsCommandBuffer: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandBuffer(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsCommandEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsDevice: (device, parentPtr = 0) => {+ var queuePtr = _emwgpuCreateQueue(parentPtr);+ var devicePtr = _emwgpuCreateDevice(parentPtr, queuePtr);+ WebGPU.Internals.jsObjectInsert(queuePtr, device.queue);+ WebGPU.Internals.jsObjectInsert(devicePtr, device);+ return devicePtr;+ },+ importJsExternalTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateExternalTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsPipelineLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreatePipelineLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQuerySet: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQuerySet(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQueue: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQueue(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundle: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundle(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundleEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundleEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSampler: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSampler(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsShaderModule: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateShaderModule(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSurface: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSurface(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTextureView: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTextureView(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ errorCallback: (callback, type, message, userdata) => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(message);+ getWasmTableEntry(callback)(type, messagePtr, userdata);+ stackRestore(sp);+ },+ iterateExtensions: (root, handlers) => {+ for (var ptr = HEAPU32[((root) >> 2)]; ptr; ptr = HEAPU32[((ptr) >> 2)]) {+ var sType = HEAP32[(((ptr) + (4)) >> 2)];+ // This will crash if there's no handler indicating either a bogus+ // sType, or one we haven't implemented yet.+ var handler = handlers[sType](ptr);+ }+ },+ setStringView: (ptr, data, length) => {+ HEAPU32[((ptr) >> 2)] = data;+ HEAPU32[(((ptr) + (4)) >> 2)] = length;+ },+ makeStringFromStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeStringFromOptionalStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // If we don't have a valid string pointer, just return undefined when+ // optional.+ if (!ptr) {+ if (length === 0) {+ return "";+ }+ return undefined;+ }+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeColor: ptr => ({+ "r": HEAPF64[((ptr) >> 3)],+ "g": HEAPF64[(((ptr) + (8)) >> 3)],+ "b": HEAPF64[(((ptr) + (16)) >> 3)],+ "a": HEAPF64[(((ptr) + (24)) >> 3)]+ }),+ makeExtent3D: ptr => ({+ "width": HEAPU32[((ptr) >> 2)],+ "height": HEAPU32[(((ptr) + (4)) >> 2)],+ "depthOrArrayLayers": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeOrigin3D: ptr => ({+ "x": HEAPU32[((ptr) >> 2)],+ "y": HEAPU32[(((ptr) + (4)) >> 2)],+ "z": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeTexelCopyTextureInfo: ptr => ({+ "texture": WebGPU.getJsObject(HEAPU32[((ptr) >> 2)]),+ "mipLevel": HEAPU32[(((ptr) + (4)) >> 2)],+ "origin": WebGPU.makeOrigin3D(ptr + 8),+ "aspect": WebGPU.TextureAspect[HEAP32[(((ptr) + (20)) >> 2)]]+ }),+ makeTexelCopyBufferLayout: ptr => {+ var bytesPerRow = HEAPU32[(((ptr) + (8)) >> 2)];+ var rowsPerImage = HEAPU32[(((ptr) + (12)) >> 2)];+ return {+ "offset": readI53FromI64(ptr),+ "bytesPerRow": bytesPerRow === 4294967295 ? undefined : bytesPerRow,+ "rowsPerImage": rowsPerImage === 4294967295 ? undefined : rowsPerImage+ };+ },+ makeTexelCopyBufferInfo: ptr => {+ var layoutPtr = ptr + 0;+ var bufferCopyView = WebGPU.makeTexelCopyBufferLayout(layoutPtr);+ bufferCopyView["buffer"] = WebGPU.getJsObject(HEAPU32[(((ptr) + (16)) >> 2)]);+ return bufferCopyView;+ },+ makePassTimestampWrites: ptr => {+ if (ptr === 0) return undefined;+ return {+ "querySet": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "beginningOfPassWriteIndex": HEAPU32[(((ptr) + (8)) >> 2)],+ "endOfPassWriteIndex": HEAPU32[(((ptr) + (12)) >> 2)]+ };+ },+ makePipelineConstants: (constantCount, constantsPtr) => {+ if (!constantCount) return;+ var constants = {};+ for (var i = 0; i < constantCount; ++i) {+ var entryPtr = constantsPtr + 24 * i;+ var key = WebGPU.makeStringFromStringView(entryPtr + 4);+ constants[key] = HEAPF64[(((entryPtr) + (16)) >> 3)];+ }+ return constants;+ },+ makePipelineLayout: layoutPtr => {+ if (!layoutPtr) return "auto";+ return WebGPU.getJsObject(layoutPtr);+ },+ makeComputeState: ptr => {+ if (!ptr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((ptr) + (16)) >> 2)], HEAPU32[(((ptr) + (20)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(ptr + 8)+ };+ return desc;+ },+ makeComputePipelineDesc: descriptor => {+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "compute": WebGPU.makeComputeState(descriptor + 16)+ };+ return desc;+ },+ makeRenderPipelineDesc: descriptor => {+ function makePrimitiveState(psPtr) {+ if (!psPtr) return undefined;+ return {+ "topology": WebGPU.PrimitiveTopology[HEAP32[(((psPtr) + (4)) >> 2)]],+ "stripIndexFormat": WebGPU.IndexFormat[HEAP32[(((psPtr) + (8)) >> 2)]],+ "frontFace": WebGPU.FrontFace[HEAP32[(((psPtr) + (12)) >> 2)]],+ "cullMode": WebGPU.CullMode[HEAP32[(((psPtr) + (16)) >> 2)]],+ "unclippedDepth": !!(HEAPU32[(((psPtr) + (20)) >> 2)])+ };+ }+ function makeBlendComponent(bdPtr) {+ if (!bdPtr) return undefined;+ return {+ "operation": WebGPU.BlendOperation[HEAP32[((bdPtr) >> 2)]],+ "srcFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (4)) >> 2)]],+ "dstFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (8)) >> 2)]]+ };+ }+ function makeBlendState(bsPtr) {+ if (!bsPtr) return undefined;+ return {+ "alpha": makeBlendComponent(bsPtr + 12),+ "color": makeBlendComponent(bsPtr + 0)+ };+ }+ function makeColorState(csPtr) {+ var format = WebGPU.TextureFormat[HEAP32[(((csPtr) + (4)) >> 2)]];+ return format ? {+ "format": format,+ "blend": makeBlendState(HEAPU32[(((csPtr) + (8)) >> 2)]),+ "writeMask": HEAPU32[(((csPtr) + (16)) >> 2)]+ } : undefined;+ }+ function makeColorStates(count, csArrayPtr) {+ var states = [];+ for (var i = 0; i < count; ++i) {+ states.push(makeColorState(csArrayPtr + 24 * i));+ }+ return states;+ }+ function makeStencilStateFace(ssfPtr) {+ return {+ "compare": WebGPU.CompareFunction[HEAP32[((ssfPtr) >> 2)]],+ "failOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (4)) >> 2)]],+ "depthFailOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (8)) >> 2)]],+ "passOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (12)) >> 2)]]+ };+ }+ function makeDepthStencilState(dssPtr) {+ if (!dssPtr) return undefined;+ return {+ "format": WebGPU.TextureFormat[HEAP32[(((dssPtr) + (4)) >> 2)]],+ "depthWriteEnabled": !!(HEAPU32[(((dssPtr) + (8)) >> 2)]),+ "depthCompare": WebGPU.CompareFunction[HEAP32[(((dssPtr) + (12)) >> 2)]],+ "stencilFront": makeStencilStateFace(dssPtr + 16),+ "stencilBack": makeStencilStateFace(dssPtr + 32),+ "stencilReadMask": HEAPU32[(((dssPtr) + (48)) >> 2)],+ "stencilWriteMask": HEAPU32[(((dssPtr) + (52)) >> 2)],+ "depthBias": HEAP32[(((dssPtr) + (56)) >> 2)],+ "depthBiasSlopeScale": HEAPF32[(((dssPtr) + (60)) >> 2)],+ "depthBiasClamp": HEAPF32[(((dssPtr) + (64)) >> 2)]+ };+ }+ function makeVertexAttribute(vaPtr) {+ return {+ "format": WebGPU.VertexFormat[HEAP32[(((vaPtr) + (4)) >> 2)]],+ "offset": readI53FromI64((vaPtr) + (8)),+ "shaderLocation": HEAPU32[(((vaPtr) + (16)) >> 2)]+ };+ }+ function makeVertexAttributes(count, vaArrayPtr) {+ var vas = [];+ for (var i = 0; i < count; ++i) {+ vas.push(makeVertexAttribute(vaArrayPtr + i * 24));+ }+ return vas;+ }+ function makeVertexBuffer(vbPtr) {+ if (!vbPtr) return undefined;+ var stepMode = WebGPU.VertexStepMode[HEAP32[(((vbPtr) + (4)) >> 2)]];+ var attributeCount = HEAPU32[(((vbPtr) + (16)) >> 2)];+ if (!stepMode && !attributeCount) {+ return null;+ }+ return {+ "arrayStride": readI53FromI64((vbPtr) + (8)),+ "stepMode": stepMode,+ "attributes": makeVertexAttributes(attributeCount, HEAPU32[(((vbPtr) + (20)) >> 2)])+ };+ }+ function makeVertexBuffers(count, vbArrayPtr) {+ if (!count) return undefined;+ var vbs = [];+ for (var i = 0; i < count; ++i) {+ vbs.push(makeVertexBuffer(vbArrayPtr + i * 24));+ }+ return vbs;+ }+ function makeVertexState(viPtr) {+ if (!viPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((viPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((viPtr) + (16)) >> 2)], HEAPU32[(((viPtr) + (20)) >> 2)]),+ "buffers": makeVertexBuffers(HEAPU32[(((viPtr) + (24)) >> 2)], HEAPU32[(((viPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(viPtr + 8)+ };+ return desc;+ }+ function makeMultisampleState(msPtr) {+ if (!msPtr) return undefined;+ return {+ "count": HEAPU32[(((msPtr) + (4)) >> 2)],+ "mask": HEAPU32[(((msPtr) + (8)) >> 2)],+ "alphaToCoverageEnabled": !!(HEAPU32[(((msPtr) + (12)) >> 2)])+ };+ }+ function makeFragmentState(fsPtr) {+ if (!fsPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((fsPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((fsPtr) + (16)) >> 2)], HEAPU32[(((fsPtr) + (20)) >> 2)]),+ "targets": makeColorStates(HEAPU32[(((fsPtr) + (24)) >> 2)], HEAPU32[(((fsPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(fsPtr + 8)+ };+ return desc;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "vertex": makeVertexState(descriptor + 16),+ "primitive": makePrimitiveState(descriptor + 48),+ "depthStencil": makeDepthStencilState(HEAPU32[(((descriptor) + (72)) >> 2)]),+ "multisample": makeMultisampleState(descriptor + 76),+ "fragment": makeFragmentState(HEAPU32[(((descriptor) + (92)) >> 2)])+ };+ return desc;+ },+ fillLimitStruct: (limits, limitsOutPtr) => {+ var nextInChainPtr = HEAPU32[((limitsOutPtr) >> 2)];+ function setLimitValueU32(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ HEAPU32[(((basePtr) + (limitOffset)) >> 2)] = limitValue;+ }+ function setLimitValueU64(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ // Limits are integer-valued JS `Number`s, so they fit in 'i53'.+ writeI53ToI64((basePtr) + (limitOffset), limitValue);+ }+ setLimitValueU32("maxTextureDimension1D", limitsOutPtr, 4);+ setLimitValueU32("maxTextureDimension2D", limitsOutPtr, 8);+ setLimitValueU32("maxTextureDimension3D", limitsOutPtr, 12);+ setLimitValueU32("maxTextureArrayLayers", limitsOutPtr, 16);+ setLimitValueU32("maxBindGroups", limitsOutPtr, 20);+ setLimitValueU32("maxBindGroupsPlusVertexBuffers", limitsOutPtr, 24);+ setLimitValueU32("maxBindingsPerBindGroup", limitsOutPtr, 28);+ setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout", limitsOutPtr, 32);+ setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout", limitsOutPtr, 36);+ setLimitValueU32("maxSampledTexturesPerShaderStage", limitsOutPtr, 40);+ setLimitValueU32("maxSamplersPerShaderStage", limitsOutPtr, 44);+ setLimitValueU32("maxStorageBuffersPerShaderStage", limitsOutPtr, 48);+ setLimitValueU32("maxStorageTexturesPerShaderStage", limitsOutPtr, 52);+ setLimitValueU32("maxUniformBuffersPerShaderStage", limitsOutPtr, 56);+ setLimitValueU32("minUniformBufferOffsetAlignment", limitsOutPtr, 80);+ setLimitValueU32("minStorageBufferOffsetAlignment", limitsOutPtr, 84);+ setLimitValueU64("maxUniformBufferBindingSize", limitsOutPtr, 64);+ setLimitValueU64("maxStorageBufferBindingSize", limitsOutPtr, 72);+ setLimitValueU32("maxVertexBuffers", limitsOutPtr, 88);+ setLimitValueU64("maxBufferSize", limitsOutPtr, 96);+ setLimitValueU32("maxVertexAttributes", limitsOutPtr, 104);+ setLimitValueU32("maxVertexBufferArrayStride", limitsOutPtr, 108);+ setLimitValueU32("maxInterStageShaderVariables", limitsOutPtr, 112);+ setLimitValueU32("maxColorAttachments", limitsOutPtr, 116);+ setLimitValueU32("maxColorAttachmentBytesPerSample", limitsOutPtr, 120);+ setLimitValueU32("maxComputeWorkgroupStorageSize", limitsOutPtr, 124);+ setLimitValueU32("maxComputeInvocationsPerWorkgroup", limitsOutPtr, 128);+ setLimitValueU32("maxComputeWorkgroupSizeX", limitsOutPtr, 132);+ setLimitValueU32("maxComputeWorkgroupSizeY", limitsOutPtr, 136);+ setLimitValueU32("maxComputeWorkgroupSizeZ", limitsOutPtr, 140);+ setLimitValueU32("maxComputeWorkgroupsPerDimension", limitsOutPtr, 144);+ // Note this limit is new and won't be present in all browsers for a while. Fall back to 0.+ setLimitValueU32("maxImmediateSize", limitsOutPtr, 148);+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var compatibilityModeLimitsPtr = nextInChainPtr;+ // Note these limits are new and won't be present in all browsers for a while. Fall back to exposing the PerShaderStage limit.+ setLimitValueU32("maxStorageBuffersInVertexStage", compatibilityModeLimitsPtr, 8, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageBuffersInFragmentStage", compatibilityModeLimitsPtr, 16, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageTexturesInVertexStage", compatibilityModeLimitsPtr, 12, limits.maxStorageTexturesPerShaderStage);+ setLimitValueU32("maxStorageTexturesInFragmentStage", compatibilityModeLimitsPtr, 20, limits.maxStorageTexturesPerShaderStage);+ }+ },+ fillAdapterInfoStruct: (info, infoStruct) => {+ // Populate subgroup limits.+ HEAPU32[(((infoStruct) + (52)) >> 2)] = info.subgroupMinSize;+ HEAPU32[(((infoStruct) + (56)) >> 2)] = info.subgroupMaxSize;+ // Append all the strings together to condense into a single malloc.+ var strs = info.vendor + info.architecture + info.device + info.description;+ var strPtr = stringToNewUTF8(strs);+ var vendorLen = lengthBytesUTF8(info.vendor);+ WebGPU.setStringView(infoStruct + 4, strPtr, vendorLen);+ strPtr += vendorLen;+ var architectureLen = lengthBytesUTF8(info.architecture);+ WebGPU.setStringView(infoStruct + 12, strPtr, architectureLen);+ strPtr += architectureLen;+ var deviceLen = lengthBytesUTF8(info.device);+ WebGPU.setStringView(infoStruct + 20, strPtr, deviceLen);+ strPtr += deviceLen;+ var descriptionLen = lengthBytesUTF8(info.description);+ WebGPU.setStringView(infoStruct + 28, strPtr, descriptionLen);+ strPtr += descriptionLen;+ HEAP32[(((infoStruct) + (36)) >> 2)] = 2;+ var adapterType = info.isFallbackAdapter ? 3 : 4;+ HEAP32[(((infoStruct) + (40)) >> 2)] = adapterType;+ HEAPU32[(((infoStruct) + (44)) >> 2)] = 0;+ HEAPU32[(((infoStruct) + (48)) >> 2)] = 0;+ },+ AddressMode: [ , "clamp-to-edge", "repeat", "mirror-repeat" ],+ BlendFactor: [ , "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha" ],+ BlendOperation: [ , "add", "subtract", "reverse-subtract", "min", "max" ],+ BufferBindingType: [ , , "uniform", "storage", "read-only-storage" ],+ BufferMapState: [ , "unmapped", "pending", "mapped" ],+ CompareFunction: [ , "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always" ],+ CompilationInfoRequestStatus: [ , "success", "callback-cancelled" ],+ ComponentSwizzle: [ , "0", "1", "r", "g", "b", "a" ],+ CompositeAlphaMode: [ , "opaque", "premultiplied", "unpremultiplied", "inherit" ],+ CullMode: [ , "none", "front", "back" ],+ ErrorFilter: [ , "validation", "out-of-memory", "internal" ],+ FeatureLevel: [ , "compatibility", "core" ],+ FeatureName: {+ 1: "core-features-and-limits",+ 2: "depth-clip-control",+ 3: "depth32float-stencil8",+ 4: "texture-compression-bc",+ 5: "texture-compression-bc-sliced-3d",+ 6: "texture-compression-etc2",+ 7: "texture-compression-astc",+ 8: "texture-compression-astc-sliced-3d",+ 9: "timestamp-query",+ 10: "indirect-first-instance",+ 11: "shader-f16",+ 12: "rg11b10ufloat-renderable",+ 13: "bgra8unorm-storage",+ 14: "float32-filterable",+ 15: "float32-blendable",+ 16: "clip-distances",+ 17: "dual-source-blending",+ 18: "subgroups",+ 19: "texture-formats-tier1",+ 20: "texture-formats-tier2",+ 21: "primitive-index",+ 22: "texture-component-swizzle",+ 327692: "chromium-experimental-unorm16-texture-formats",+ 327729: "chromium-experimental-multi-draw-indirect"+ },+ FilterMode: [ , "nearest", "linear" ],+ FrontFace: [ , "ccw", "cw" ],+ IndexFormat: [ , "uint16", "uint32" ],+ InstanceFeatureName: [ , "timed-wait-any", "shader-source-spirv", "multiple-devices-per-adapter" ],+ LoadOp: [ , "load", "clear" ],+ MipmapFilterMode: [ , "nearest", "linear" ],+ OptionalBool: [ "false", "true" ],+ PowerPreference: [ , "low-power", "high-performance" ],+ PredefinedColorSpace: [ , "srgb", "display-p3" ],+ PrimitiveTopology: [ , "point-list", "line-list", "line-strip", "triangle-list", "triangle-strip" ],+ QueryType: [ , "occlusion", "timestamp" ],+ SamplerBindingType: [ , , "filtering", "non-filtering", "comparison" ],+ Status: [ , "success", "error" ],+ StencilOperation: [ , "keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap" ],+ StorageTextureAccess: [ , , "write-only", "read-only", "read-write" ],+ StoreOp: [ , "store", "discard" ],+ SurfaceGetCurrentTextureStatus: [ , "success-optimal", "success-suboptimal", "timeout", "outdated", "lost", "error" ],+ TextureAspect: [ , "all", "stencil-only", "depth-only" ],+ TextureDimension: [ , "1d", "2d", "3d" ],+ TextureFormat: [ , "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb" ],+ TextureSampleType: [ , , "float", "unfilterable-float", "depth", "sint", "uint" ],+ TextureViewDimension: [ , "1d", "2d", "2d-array", "cube", "cube-array", "3d" ],+ ToneMappingMode: [ , "standard", "extended" ],+ VertexFormat: [ , "uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra" ],+ VertexStepMode: [ , "vertex", "instance" ],+ WGSLLanguageFeatureName: [ , "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", "uniform_buffer_standard_layout", "subgroup_id", "texture_and_sampler_let", "subgroup_uniformity", "texture_formats_tier1", "linear_indexing" ]+};++var _emscripten_webgpu_get_device = () => {+ if (WebGPU.preinitializedDeviceId === undefined) {+ WebGPU.preinitializedDeviceId = WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]);+ // Some users depend on this keeping the device alive, so we add an+ // additional reference when we first initialize it.+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ }+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ return WebGPU.preinitializedDeviceId;+};++var _emwgpuBufferDestroy = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (onUnmap) {+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ }+ buffer.destroy();+};++var _emwgpuBufferGetMappedRange = (bufferPtr, offset, size) => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ if (size == -1) size = undefined;+ var mapped;+ try {+ mapped = buffer.getMappedRange(offset, size);+ } catch (ex) {+ return 0;+ }+ var data = _memalign(16, mapped.byteLength);+ HEAPU8.fill(0, data, mapped.byteLength);+ WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(() => {+ new Uint8Array(mapped).set(HEAPU8.subarray(data, data + mapped.byteLength));+ _free(data);+ });+ return data;+};++var _emwgpuBufferUnmap = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (!onUnmap) {+ // Already unmapped+ return;+ }+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ buffer.unmap();+};++var _emwgpuDelete = ptr => {+ delete WebGPU.Internals.jsObjects[ptr];+};++var _emwgpuDeviceCreateBuffer = (devicePtr, descriptor, bufferPtr) => {+ var mappedAtCreation = !!(HEAPU32[(((descriptor) + (32)) >> 2)]);+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "size": readI53FromI64((descriptor) + (24)),+ "mappedAtCreation": mappedAtCreation+ };+ var device = WebGPU.getJsObject(devicePtr);+ var buffer;+ try {+ buffer = device.createBuffer(desc);+ } catch (ex) {+ // The only exception should be RangeError if mapping at creation ran out of memory.+ return false;+ }+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ if (mappedAtCreation) {+ WebGPU.Internals.bufferOnUnmaps[bufferPtr] = [];+ }+ return true;+};++var _emwgpuDeviceCreateComputePipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createComputePipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createComputePipelineAsync(desc).then(pipeline => {+ // createComputePipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateComputePipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createComputePipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateComputePipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateRenderPipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createRenderPipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createRenderPipelineAsync(desc).then(pipeline => {+ // createRenderPipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateRenderPipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createRenderPipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateRenderPipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateShaderModule = (devicePtr, descriptor, shaderModulePtr) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "code": ""+ };+ switch (sType) {+ case 2:+ {+ desc["code"] = WebGPU.makeStringFromStringView(nextInChainPtr + 8);+ break;+ }+ }+ var device = WebGPU.getJsObject(devicePtr);+ WebGPU.Internals.jsObjectInsert(shaderModulePtr, device.createShaderModule(desc));+};++var _emwgpuDeviceDestroy = devicePtr => {+ const device = WebGPU.getJsObject(devicePtr);+ // Remove the onuncapturederror handler which holds a pointer to the WGPUDevice.+ device.onuncapturederror = null;+ device.destroy();+};++var _emwgpuWaitAny = (futurePtr, futureCount, timeoutMSPtr) => {+ abort("TODO: Implement asyncify-free WaitAny for timeout=0");+};++var ENV = {};++var getExecutableName = () => thisProgram || "./this.program";++var getEnvStrings = () => {+ if (!getEnvStrings.strings) {+ // Default values.+ // Browser language detection #8751+ var lang = (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8";+ var env = {+ "USER": "web_user",+ "LOGNAME": "web_user",+ "PATH": "/",+ "PWD": "/",+ "HOME": "/home/web_user",+ "LANG": lang,+ "_": getExecutableName()+ };+ // Apply the user-provided values, if any.+ for (var x in ENV) {+ // x is a key in ENV; if ENV[x] is undefined, that means it was+ // explicitly set to be so. We allow user code to do that to+ // force variables with default values to remain unset.+ if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x];+ }+ var strings = [];+ for (var x in env) {+ strings.push(`${x}=${env[x]}`);+ }+ getEnvStrings.strings = strings;+ }+ return getEnvStrings.strings;+};++var _environ_get = (__environ, environ_buf) => {+ var bufSize = 0;+ var envp = 0;+ for (var string of getEnvStrings()) {+ var ptr = environ_buf + bufSize;+ HEAPU32[(((__environ) + (envp)) >> 2)] = ptr;+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;+ envp += 4;+ }+ return 0;+};++var _environ_sizes_get = (penviron_count, penviron_buf_size) => {+ var strings = getEnvStrings();+ HEAPU32[((penviron_count) >> 2)] = strings.length;+ var bufSize = 0;+ for (var string of strings) {+ bufSize += lengthBytesUTF8(string) + 1;+ }+ HEAPU32[((penviron_buf_size) >> 2)] = bufSize;+ return 0;+};++function _fd_close(fd) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.close(stream);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.read(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) break;+ // nothing more to read+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_read(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doReadv(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ if (isNaN(offset)) return 61;+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.llseek(stream, offset, whence);+ (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]);+ if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;+ // reset readdir state+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.write(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) {+ // No more space to write.+ break;+ }+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_write(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doWritev(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++var _emscripten_glActiveTexture = x0 => GLctx.activeTexture(x0);++var _glActiveTexture = _emscripten_glActiveTexture;++var _emscripten_glAttachShader = (program, shader) => {+ GLctx.attachShader(GL.programs[program], GL.shaders[shader]);+};++var _glAttachShader = _emscripten_glAttachShader;++var _emscripten_glBindAttribLocation = (program, index, name) => {+ GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));+};++var _glBindAttribLocation = _emscripten_glBindAttribLocation;++var _emscripten_glBindBuffer = (target, buffer) => {+ // Calling glBindBuffer with an unknown buffer will implicitly create a+ // new one. Here we bypass `GL.counter` and directly using the ID passed+ // in.+ if (buffer && !GL.buffers[buffer]) {+ var b = GLctx.createBuffer();+ b.name = buffer;+ GL.buffers[buffer] = b;+ }+ if (target == 34962) {+ GLctx.currentArrayBufferBinding = buffer;+ } else if (target == 34963) {+ GLctx.currentElementArrayBufferBinding = buffer;+ }+ if (target == 35051) {+ // In WebGL 2 glReadPixels entry point, we need to use a different WebGL 2+ // API function call when a buffer is bound to+ // GL_PIXEL_PACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelPackBufferBinding = buffer;+ } else if (target == 35052) {+ // In WebGL 2 gl(Compressed)Tex(Sub)Image[23]D entry points, we need to+ // use a different WebGL 2 API function call when a buffer is bound to+ // GL_PIXEL_UNPACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelUnpackBufferBinding = buffer;+ }+ GLctx.bindBuffer(target, GL.buffers[buffer]);+};++var _glBindBuffer = _emscripten_glBindBuffer;++var _emscripten_glBindBufferBase = (target, index, buffer) => {+ GLctx.bindBufferBase(target, index, GL.buffers[buffer]);+};++var _glBindBufferBase = _emscripten_glBindBufferBase;++var _emscripten_glBindFramebuffer = (target, framebuffer) => {+ GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);+};++var _glBindFramebuffer = _emscripten_glBindFramebuffer;++var _emscripten_glBindTexture = (target, texture) => {+ GLctx.bindTexture(target, GL.textures[texture]);+};++var _glBindTexture = _emscripten_glBindTexture;++var _emscripten_glBindVertexArray = vao => {+ GLctx.bindVertexArray(GL.vaos[vao]);+ var ibo = GLctx.getParameter(34965);+ GLctx.currentElementArrayBufferBinding = ibo ? (ibo.name | 0) : 0;+};++var _glBindVertexArray = _emscripten_glBindVertexArray;++var _emscripten_glBlendEquation = x0 => GLctx.blendEquation(x0);++var _glBlendEquation = _emscripten_glBlendEquation;++var _emscripten_glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1);++var _glBlendFunc = _emscripten_glBlendFunc;++var _emscripten_glBufferData = (target, size, data, usage) => {+ if (GL.currentContext.version >= 2) {+ // If size is zero, WebGL would interpret uploading the whole input+ // arraybuffer (starting from given offset), which would not make sense in+ // WebAssembly, so avoid uploading if size is zero. However we must still+ // call bufferData to establish a backing storage of zero bytes.+ if (data && size) {+ GLctx.bufferData(target, HEAPU8, usage, data, size);+ } else {+ GLctx.bufferData(target, size, usage);+ }+ return;+ }+ // N.b. here first form specifies a heap subarray, second form an integer+ // size, so the ?: code here is polymorphic. It is advised to avoid+ // randomly mixing both uses in calling code, to avoid any potential JS+ // engine JIT issues.+ GLctx.bufferData(target, data ? HEAPU8.subarray(data, data + size) : size, usage);+};++var _glBufferData = _emscripten_glBufferData;++var _emscripten_glClear = x0 => GLctx.clear(x0);++var _glClear = _emscripten_glClear;++var _emscripten_glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3);++var _glClearColor = _emscripten_glClearColor;++var convertI32PairToI53 = (lo, hi) => (lo >>> 0) + hi * 4294967296;++var _emscripten_glClientWaitSync = (sync, flags, timeout_low, timeout_high) => {+ // WebGL2 vs GLES3 differences: in GLES3, the timeout parameter is a uint64, where 0xFFFFFFFFFFFFFFFFULL means GL_TIMEOUT_IGNORED.+ // In JS, there's no 64-bit value types, so instead timeout is taken to be signed, and GL_TIMEOUT_IGNORED is given value -1.+ // Inherently the value accepted in the timeout is lossy, and can't take in arbitrary u64 bit pattern (but most likely doesn't matter)+ // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.15+ var timeout = convertI32PairToI53(timeout_low, timeout_high);+ return GLctx.clientWaitSync(GL.syncs[sync], flags, timeout);+};++var _glClientWaitSync = _emscripten_glClientWaitSync;++var _emscripten_glColorMask = (red, green, blue, alpha) => {+ GLctx.colorMask(!!red, !!green, !!blue, !!alpha);+};++var _glColorMask = _emscripten_glColorMask;++var _emscripten_glCompileShader = shader => {+ GLctx.compileShader(GL.shaders[shader]);+};++var _glCompileShader = _emscripten_glCompileShader;++var _emscripten_glCreateProgram = () => {+ var id = GL.getNewId(GL.programs);+ var program = GLctx.createProgram();+ // Store additional information needed for each shader program:+ program.name = id;+ // Lazy cache results of+ // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH)+ program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0;+ program.uniformIdCounter = 1;+ GL.programs[id] = program;+ return id;+};++var _glCreateProgram = _emscripten_glCreateProgram;++var _emscripten_glCreateShader = shaderType => {+ var id = GL.getNewId(GL.shaders);+ GL.shaders[id] = GLctx.createShader(shaderType);+ return id;+};++var _glCreateShader = _emscripten_glCreateShader;++var _emscripten_glDeleteBuffers = (n, buffers) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((buffers) + (i * 4)) >> 2)];+ var buffer = GL.buffers[id];+ // From spec: "glDeleteBuffers silently ignores 0's and names that do not+ // correspond to existing buffer objects."+ if (!buffer) continue;+ GLctx.deleteBuffer(buffer);+ buffer.name = 0;+ GL.buffers[id] = null;+ if (id == GLctx.currentArrayBufferBinding) GLctx.currentArrayBufferBinding = 0;+ if (id == GLctx.currentElementArrayBufferBinding) GLctx.currentElementArrayBufferBinding = 0;+ if (id == GLctx.currentPixelPackBufferBinding) GLctx.currentPixelPackBufferBinding = 0;+ if (id == GLctx.currentPixelUnpackBufferBinding) GLctx.currentPixelUnpackBufferBinding = 0;+ }+};++var _glDeleteBuffers = _emscripten_glDeleteBuffers;++var _emscripten_glDeleteFramebuffers = (n, framebuffers) => {+ for (var i = 0; i < n; ++i) {+ var id = HEAP32[(((framebuffers) + (i * 4)) >> 2)];+ var framebuffer = GL.framebuffers[id];+ if (!framebuffer) continue;+ // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".+ GLctx.deleteFramebuffer(framebuffer);+ framebuffer.name = 0;+ GL.framebuffers[id] = null;+ }+};++var _glDeleteFramebuffers = _emscripten_glDeleteFramebuffers;++var _emscripten_glDeleteProgram = id => {+ if (!id) return;+ var program = GL.programs[id];+ if (!program) {+ // glDeleteProgram actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteProgram(program);+ program.name = 0;+ GL.programs[id] = null;+};++var _glDeleteProgram = _emscripten_glDeleteProgram;++var _emscripten_glDeleteShader = id => {+ if (!id) return;+ var shader = GL.shaders[id];+ if (!shader) {+ // glDeleteShader actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteShader(shader);+ GL.shaders[id] = null;+};++var _glDeleteShader = _emscripten_glDeleteShader;++var _emscripten_glDeleteSync = id => {+ if (!id) return;+ var sync = GL.syncs[id];+ if (!sync) {+ // glDeleteSync signals an error when deleting a nonexisting object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteSync(sync);+ sync.name = 0;+ GL.syncs[id] = null;+};++var _glDeleteSync = _emscripten_glDeleteSync;++var _emscripten_glDeleteTextures = (n, textures) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((textures) + (i * 4)) >> 2)];+ var texture = GL.textures[id];+ // GL spec: "glDeleteTextures silently ignores 0s and names that do not+ // correspond to existing textures".+ if (!texture) continue;+ GLctx.deleteTexture(texture);+ texture.name = 0;+ GL.textures[id] = null;+ }+};++var _glDeleteTextures = _emscripten_glDeleteTextures;++var _emscripten_glDeleteVertexArrays = (n, vaos) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((vaos) + (i * 4)) >> 2)];+ GLctx.deleteVertexArray(GL.vaos[id]);+ GL.vaos[id] = null;+ }+};++var _glDeleteVertexArrays = _emscripten_glDeleteVertexArrays;++var _emscripten_glDetachShader = (program, shader) => {+ GLctx.detachShader(GL.programs[program], GL.shaders[shader]);+};++var _glDetachShader = _emscripten_glDetachShader;++var _emscripten_glDisable = x0 => GLctx.disable(x0);++var _glDisable = _emscripten_glDisable;++var _emscripten_glDisableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = false;+ GLctx.disableVertexAttribArray(index);+};++var _glDisableVertexAttribArray = _emscripten_glDisableVertexAttribArray;++var _emscripten_glDrawArrays = (mode, first, count) => {+ // bind any client-side buffers+ GL.preDrawHandleClientVertexAttribBindings(first + count);+ GLctx.drawArrays(mode, first, count);+ GL.postDrawHandleClientVertexAttribBindings();+};++var _glDrawArrays = _emscripten_glDrawArrays;++var tempFixedLengthArray = [];++var _emscripten_glDrawBuffers = (n, bufs) => {+ var bufArray = tempFixedLengthArray[n];+ for (var i = 0; i < n; i++) {+ bufArray[i] = HEAP32[(((bufs) + (i * 4)) >> 2)];+ }+ GLctx.drawBuffers(bufArray);+};++var _glDrawBuffers = _emscripten_glDrawBuffers;++var _emscripten_glEnable = x0 => GLctx.enable(x0);++var _glEnable = _emscripten_glEnable;++var _emscripten_glEnableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = true;+ GLctx.enableVertexAttribArray(index);+};++var _glEnableVertexAttribArray = _emscripten_glEnableVertexAttribArray;++var _emscripten_glFenceSync = (condition, flags) => {+ var sync = GLctx.fenceSync(condition, flags);+ if (sync) {+ var id = GL.getNewId(GL.syncs);+ sync.name = id;+ GL.syncs[id] = sync;+ return id;+ }+ return 0;+};++var _glFenceSync = _emscripten_glFenceSync;++var _emscripten_glFinish = () => GLctx.finish();++var _glFinish = _emscripten_glFinish;++var _emscripten_glFlush = () => GLctx.flush();++var _glFlush = _emscripten_glFlush;++var _emscripten_glFramebufferTexture2D = (target, attachment, textarget, texture, level) => {+ GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level);+};++var _glFramebufferTexture2D = _emscripten_glFramebufferTexture2D;++var _emscripten_glFramebufferTextureLayer = (target, attachment, texture, level, layer) => {+ GLctx.framebufferTextureLayer(target, attachment, GL.textures[texture], level, layer);+};++var _glFramebufferTextureLayer = _emscripten_glFramebufferTextureLayer;++var _emscripten_glGenBuffers = (n, buffers) => {+ GL.genObject(n, buffers, "createBuffer", GL.buffers);+};++var _glGenBuffers = _emscripten_glGenBuffers;++var _emscripten_glGenFramebuffers = (n, ids) => {+ GL.genObject(n, ids, "createFramebuffer", GL.framebuffers);+};++var _glGenFramebuffers = _emscripten_glGenFramebuffers;++var _emscripten_glGenTextures = (n, textures) => {+ GL.genObject(n, textures, "createTexture", GL.textures);+};++var _glGenTextures = _emscripten_glGenTextures;++var _emscripten_glGenVertexArrays = (n, arrays) => {+ GL.genObject(n, arrays, "createVertexArray", GL.vaos);+};++var _glGenVertexArrays = _emscripten_glGenVertexArrays;++var _emscripten_glGetAttribLocation = (program, name) => GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));++var _glGetAttribLocation = _emscripten_glGetAttribLocation;++var _emscripten_glGetError = () => {+ var error = GLctx.getError() || GL.lastError;+ GL.lastError = 0;+ return error;+};++var _glGetError = _emscripten_glGetError;++var webglGetExtensions = () => {+ var exts = getEmscriptenSupportedExtensions(GLctx);+ exts = exts.concat(exts.map(e => "GL_" + e));+ return exts;+};++var emscriptenWebGLGet = (name_, p, type) => {+ // Guard against user passing a null pointer.+ // Note that GLES2 spec does not say anything about how passing a null+ // pointer should be treated. Testing on desktop core GL 3, the application+ // crashes on glGetIntegerv to a null pointer, but better to report an error+ // instead of doing anything random.+ if (!p) {+ GL.recordError(1281);+ return;+ }+ var ret = undefined;+ switch (name_) {+ // Handle a few trivial GLES values+ case 36346:+ // GL_SHADER_COMPILER+ ret = 1;+ break;++ case 36344:+ // GL_SHADER_BINARY_FORMATS+ if (type != 0 && type != 1) {+ GL.recordError(1280);+ }+ // Do not write anything to the out pointer, since no binary formats are+ // supported.+ return;++ case 34814:+ // GL_NUM_PROGRAM_BINARY_FORMATS+ case 36345:+ // GL_NUM_SHADER_BINARY_FORMATS+ ret = 0;+ break;++ case 34466:+ // GL_NUM_COMPRESSED_TEXTURE_FORMATS+ // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete+ // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be+ // queried for length), so implement it ourselves to allow C++ GLES2+ // code to get the length.+ var formats = GLctx.getParameter(34467);+ ret = formats ? formats.length : 0;+ break;++ case 33309:+ // GL_NUM_EXTENSIONS+ if (GL.currentContext.version < 2) {+ // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context+ GL.recordError(1282);+ return;+ }+ ret = webglGetExtensions().length;+ break;++ case 33307:+ // GL_MAJOR_VERSION+ case 33308:+ // GL_MINOR_VERSION+ if (GL.currentContext.version < 2) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ ret = name_ == 33307 ? 3 : 0;+ // return version 3.0+ break;+ }+ if (ret === undefined) {+ var result = GLctx.getParameter(name_);+ switch (typeof result) {+ case "number":+ ret = result;+ break;++ case "boolean":+ ret = result ? 1 : 0;+ break;++ case "string":+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;++ case "object":+ if (result === null) {+ // null is a valid result for some (e.g., which buffer is bound -+ // perhaps nothing is bound), but otherwise can mean an invalid+ // name_, which we need to report as an error+ switch (name_) {+ case 34964:+ // ARRAY_BUFFER_BINDING+ case 35725:+ // CURRENT_PROGRAM+ case 34965:+ // ELEMENT_ARRAY_BUFFER_BINDING+ case 36006:+ // FRAMEBUFFER_BINDING or DRAW_FRAMEBUFFER_BINDING+ case 36007:+ // RENDERBUFFER_BINDING+ case 32873:+ // TEXTURE_BINDING_2D+ case 34229:+ // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES+ case 36662:+ // COPY_READ_BUFFER_BINDING or COPY_READ_BUFFER+ case 36663:+ // COPY_WRITE_BUFFER_BINDING or COPY_WRITE_BUFFER+ case 35053:+ // PIXEL_PACK_BUFFER_BINDING+ case 35055:+ // PIXEL_UNPACK_BUFFER_BINDING+ case 36010:+ // READ_FRAMEBUFFER_BINDING+ case 35097:+ // SAMPLER_BINDING+ case 35869:+ // TEXTURE_BINDING_2D_ARRAY+ case 32874:+ // TEXTURE_BINDING_3D+ case 36389:+ // TRANSFORM_FEEDBACK_BINDING+ case 35983:+ // TRANSFORM_FEEDBACK_BUFFER_BINDING+ case 35368:+ // UNIFORM_BUFFER_BINDING+ case 34068:+ {+ // TEXTURE_BINDING_CUBE_MAP+ ret = 0;+ break;+ }++ default:+ {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ }+ } else if (result instanceof Float32Array || result instanceof Uint32Array || result instanceof Int32Array || result instanceof Array) {+ for (var i = 0; i < result.length; ++i) {+ switch (type) {+ case 0:+ HEAP32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 2:+ HEAPF32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 4:+ HEAP8[(p) + (i)] = result[i] ? 1 : 0;+ break;+ }+ }+ return;+ } else {+ try {+ ret = result.name | 0;+ } catch (e) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);+ return;+ }+ }+ break;++ default:+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof (result)}!`);+ return;+ }+ }+ switch (type) {+ case 1:+ writeI53ToI64(p, ret);+ break;++ case 0:+ HEAP32[((p) >> 2)] = ret;+ break;++ case 2:+ HEAPF32[((p) >> 2)] = ret;+ break;++ case 4:+ HEAP8[p] = ret ? 1 : 0;+ break;+ }+};++var _emscripten_glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2);++var _glGetFloatv = _emscripten_glGetFloatv;++var _emscripten_glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0);++var _glGetIntegerv = _emscripten_glGetIntegerv;++var _emscripten_glGetProgramiv = (program, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (program >= GL.counter) {+ GL.recordError(1281);+ return;+ }+ program = GL.programs[program];+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getProgramInfoLog(program);+ if (log === null) log = "(unknown error)";+ HEAP32[((p) >> 2)] = log.length + 1;+ } else if (pname == 35719) {+ if (!program.maxUniformLength) {+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (var i = 0; i < numActiveUniforms; ++i) {+ program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformLength;+ } else if (pname == 35722) {+ if (!program.maxAttributeLength) {+ var numActiveAttributes = GLctx.getProgramParameter(program, 35721);+ for (var i = 0; i < numActiveAttributes; ++i) {+ program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxAttributeLength;+ } else if (pname == 35381) {+ if (!program.maxUniformBlockNameLength) {+ var numActiveUniformBlocks = GLctx.getProgramParameter(program, 35382);+ for (var i = 0; i < numActiveUniformBlocks; ++i) {+ program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformBlockNameLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getProgramParameter(program, pname);+ }+};++var _glGetProgramiv = _emscripten_glGetProgramiv;++var _emscripten_glGetShaderInfoLog = (shader, maxLength, length, infoLog) => {+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;+ if (length) HEAP32[((length) >> 2)] = numBytesWrittenExclNull;+};++var _glGetShaderInfoLog = _emscripten_glGetShaderInfoLog;++var _emscripten_glGetShaderiv = (shader, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ // The GLES2 specification says that if the shader has an empty info log,+ // a value of 0 is returned. Otherwise the log has a null char appended.+ // (An empty string is falsey, so we can just check that instead of+ // looking at log.length.)+ var logLength = log ? log.length + 1 : 0;+ HEAP32[((p) >> 2)] = logLength;+ } else if (pname == 35720) {+ // GL_SHADER_SOURCE_LENGTH+ var source = GLctx.getShaderSource(GL.shaders[shader]);+ // source may be a null, or the empty string, both of which are falsey+ // values that we report a 0 length for.+ var sourceLength = source ? source.length + 1 : 0;+ HEAP32[((p) >> 2)] = sourceLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getShaderParameter(GL.shaders[shader], pname);+ }+};++var _glGetShaderiv = _emscripten_glGetShaderiv;++var _emscripten_glGetString = name_ => {+ var ret = GL.stringCache[name_];+ if (!ret) {+ switch (name_) {+ case 7939:+ ret = stringToNewUTF8(webglGetExtensions().join(" "));+ break;++ case 7936:+ case 7937:+ case 37445:+ case 37446:+ var s = GLctx.getParameter(name_);+ if (!s) {+ GL.recordError(1280);+ }+ ret = s ? stringToNewUTF8(s) : 0;+ break;++ case 7938:+ var webGLVersion = GLctx.getParameter(7938);+ // return GLES version string corresponding to the version of the WebGL context+ var glVersion = `OpenGL ES 2.0 (${webGLVersion})`;+ if (GL.currentContext.version >= 2) glVersion = `OpenGL ES 3.0 (${webGLVersion})`;+ ret = stringToNewUTF8(glVersion);+ break;++ case 35724:+ var glslVersion = GLctx.getParameter(35724);+ // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'+ var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;+ var ver_num = glslVersion.match(ver_re);+ if (ver_num !== null) {+ if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + "0";+ // ensure minor version has 2 digits+ glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`;+ }+ ret = stringToNewUTF8(glslVersion);+ break;++ default:+ GL.recordError(1280);+ }+ GL.stringCache[name_] = ret;+ }+ return ret;+};++var _glGetString = _emscripten_glGetString;++var _emscripten_glGetUniformBlockIndex = (program, uniformBlockName) => GLctx.getUniformBlockIndex(GL.programs[program], UTF8ToString(uniformBlockName));++var _glGetUniformBlockIndex = _emscripten_glGetUniformBlockIndex;++/** @suppress {checkTypes} */ var jstoi_q = str => parseInt(str);++/** @noinline */ var webglGetLeftBracePos = name => name.slice(-1) == "]" && name.lastIndexOf("[");++var webglPrepareUniformLocationsBeforeFirstUse = program => {+ var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation+ uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint]+ i, j;+ // On the first time invocation of glGetUniformLocation on this shader program:+ // initialize cache data structures and discover which uniforms are arrays.+ if (!uniformLocsById) {+ // maps GLint integer locations to WebGLUniformLocations+ program.uniformLocsById = uniformLocsById = {};+ // maps integer locations back to uniform name strings, so that we can lazily fetch uniform array locations+ program.uniformArrayNamesById = {};+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (i = 0; i < numActiveUniforms; ++i) {+ var u = GLctx.getActiveUniform(program, i);+ var nm = u.name;+ var sz = u.size;+ var lb = webglGetLeftBracePos(nm);+ var arrayName = lb > 0 ? nm.slice(0, lb) : nm;+ // Assign a new location.+ var id = program.uniformIdCounter;+ program.uniformIdCounter += sz;+ // Eagerly get the location of the uniformArray[0] base element.+ // The remaining indices >0 will be left for lazy evaluation to+ // improve performance. Those may never be needed to fetch, if the+ // application fills arrays always in full starting from the first+ // element of the array.+ uniformSizeAndIdsByName[arrayName] = [ sz, id ];+ // Store placeholder integers in place that highlight that these+ // >0 index locations are array indices pending population.+ for (j = 0; j < sz; ++j) {+ uniformLocsById[id] = j;+ program.uniformArrayNamesById[id++] = arrayName;+ }+ }+ }+};++var _emscripten_glGetUniformLocation = (program, name) => {+ name = UTF8ToString(name);+ if (program = GL.programs[program]) {+ webglPrepareUniformLocationsBeforeFirstUse(program);+ var uniformLocsById = program.uniformLocsById;+ // Maps GLuint -> WebGLUniformLocation+ var arrayIndex = 0;+ var uniformBaseName = name;+ // Invariant: when populating integer IDs for uniform locations, we must+ // maintain the precondition that arrays reside in contiguous addresses,+ // i.e. for a 'vec4 colors[10];', colors[4] must be at location+ // colors[0]+4. However, user might call glGetUniformLocation(program,+ // "colors") for an array, so we cannot discover based on the user input+ // arguments whether the uniform we are dealing with is an array. The only+ // way to discover which uniforms are arrays is to enumerate over all the+ // active uniforms in the program.+ var leftBrace = webglGetLeftBracePos(name);+ // If user passed an array accessor "[index]", parse the array index off the accessor.+ if (leftBrace > 0) {+ arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0;+ // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds.+ uniformBaseName = name.slice(0, leftBrace);+ }+ // Have we cached the location of this uniform before?+ // A pair [array length, GLint of the uniform location]+ var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName];+ // If a uniform with this name exists, and if its index is within the+ // array limits (if it's even an array), query the WebGLlocation, or+ // return an existing cached location.+ if (sizeAndId && arrayIndex < sizeAndId[0]) {+ arrayIndex += sizeAndId[1];+ // Add the base location of the uniform to the array index offset.+ if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) {+ return arrayIndex;+ }+ }+ } else {+ // N.b. we are currently unable to distinguish between GL program IDs that+ // never existed vs GL program IDs that have been deleted, so report+ // GL_INVALID_VALUE in both cases.+ GL.recordError(1281);+ }+ return -1;+};++var _glGetUniformLocation = _emscripten_glGetUniformLocation;++var _emscripten_glLineWidth = x0 => GLctx.lineWidth(x0);++var _glLineWidth = _emscripten_glLineWidth;++var _emscripten_glLinkProgram = program => {+ program = GL.programs[program];+ GLctx.linkProgram(program);+ // Invalidate earlier computed uniform->ID mappings, those have now become stale+ program.uniformLocsById = 0;+ // Mark as null-like so that glGetUniformLocation() knows to populate this again.+ program.uniformSizeAndIdsByName = {};+};++var _glLinkProgram = _emscripten_glLinkProgram;++var _emscripten_glPixelStorei = (pname, param) => {+ if (pname == 3317) {+ GL.unpackAlignment = param;+ } else if (pname == 3314) {+ GL.unpackRowLength = param;+ }+ GLctx.pixelStorei(pname, param);+};++var _glPixelStorei = _emscripten_glPixelStorei;++var computeUnpackAlignedImageSize = (width, height, sizePerPixel) => {+ function roundedToNextMultipleOf(x, y) {+ return (x + y - 1) & -y;+ }+ var plainRowSize = (GL.unpackRowLength || width) * sizePerPixel;+ var alignedRowSize = roundedToNextMultipleOf(plainRowSize, GL.unpackAlignment);+ return height * alignedRowSize;+};++var colorChannelsInGlTextureFormat = format => {+ // Micro-optimizations for size: map format to size by subtracting smallest+ // enum value (0x1902) from all values first. Also omit the most common+ // size value (1) from the list, which is assumed by formats not on the+ // list.+ var colorChannels = {+ // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,+ // 0x1906 /* GL_ALPHA */ - 0x1902: 1,+ 5: 3,+ 6: 4,+ // 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,+ 8: 2,+ 29502: 3,+ 29504: 4,+ // 0x1903 /* GL_RED */ - 0x1902: 1,+ 26917: 2,+ 26918: 2,+ // 0x8D94 /* GL_RED_INTEGER */ - 0x1902: 1,+ 29846: 3,+ 29847: 4+ };+ return colorChannels[format - 6402] || 1;+};++var heapObjectForWebGLType = type => {+ // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare+ // smaller values for the heap, for shorter generated code size.+ // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.+ // (since most types are HEAPU16)+ type -= 5120;+ if (type == 0) return HEAP8;+ if (type == 1) return HEAPU8;+ if (type == 2) return HEAP16;+ if (type == 4) return HEAP32;+ if (type == 6) return HEAPF32;+ if (type == 5 || type == 28922 || type == 28520 || type == 30779 || type == 30782) return HEAPU32;+ return HEAPU16;+};++var toTypedArrayIndex = (pointer, heap) => pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT));++var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels, internalFormat) => {+ var heap = heapObjectForWebGLType(type);+ var sizePerPixel = colorChannelsInGlTextureFormat(format) * heap.BYTES_PER_ELEMENT;+ var bytes = computeUnpackAlignedImageSize(width, height, sizePerPixel);+ return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap));+};++var _emscripten_glReadPixels = (x, y, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelPackBufferBinding) {+ GLctx.readPixels(x, y, width, height, format, type, pixels);+ return;+ }+ var heap = heapObjectForWebGLType(type);+ var target = toTypedArrayIndex(pixels, heap);+ GLctx.readPixels(x, y, width, height, format, type, heap, target);+ return;+ }+ var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format);+ if (!pixelData) {+ GL.recordError(1280);+ return;+ }+ GLctx.readPixels(x, y, width, height, format, type, pixelData);+};++var _glReadPixels = _emscripten_glReadPixels;++var _emscripten_glShaderSource = (shader, count, string, length) => {+ var source = GL.getSource(shader, count, string, length);+ GLctx.shaderSource(GL.shaders[shader], source);+};++var _glShaderSource = _emscripten_glShaderSource;++var _emscripten_glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ var index = toTypedArrayIndex(pixels, heap);+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, heap, index);+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null;+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData);+};++var _glTexImage2D = _emscripten_glTexImage2D;++var _emscripten_glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2);++var _glTexParameterf = _emscripten_glTexParameterf;++var _emscripten_glTexParameterfv = (target, pname, params) => {+ var param = HEAPF32[((params) >> 2)];+ GLctx.texParameterf(target, pname, param);+};++var _glTexParameterfv = _emscripten_glTexParameterfv;++var _emscripten_glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2);++var _glTexParameteri = _emscripten_glTexParameteri;++var _emscripten_glTexStorage2D = (x0, x1, x2, x3, x4) => GLctx.texStorage2D(x0, x1, x2, x3, x4);++var _glTexStorage2D = _emscripten_glTexStorage2D;++var _emscripten_glTexStorage3D = (x0, x1, x2, x3, x4, x5) => GLctx.texStorage3D(x0, x1, x2, x3, x4, x5);++var _glTexStorage3D = _emscripten_glTexStorage3D;++var _emscripten_glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, heap, toTypedArrayIndex(pixels, heap));+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0) : null;+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);+};++var _glTexSubImage2D = _emscripten_glTexSubImage2D;++var _emscripten_glTexSubImage3D = (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels) => {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);+ } else if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, heap, toTypedArrayIndex(pixels, heap));+ } else {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, null);+ }+};++var _glTexSubImage3D = _emscripten_glTexSubImage3D;++var webglGetUniformLocation = location => {+ var p = GLctx.currentProgram;+ if (p) {+ var webglLoc = p.uniformLocsById[location];+ // p.uniformLocsById[location] stores either an integer, or a+ // WebGLUniformLocation.+ // If an integer, we have not yet bound the location, so do it now. The+ // integer value specifies the array index we should bind to.+ if (typeof webglLoc == "number") {+ p.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(p, p.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : ""));+ }+ // Else an already cached WebGLUniformLocation, return it.+ return webglLoc;+ } else {+ GL.recordError(1282);+ }+};++var _emscripten_glUniform1f = (location, v0) => {+ GLctx.uniform1f(webglGetUniformLocation(location), v0);+};++var _glUniform1f = _emscripten_glUniform1f;++var miniTempWebGLFloatBuffers = [];++var _emscripten_glUniform1fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform1fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count);+ return;+ }+ if (count <= 288) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; ++i) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 4) >> 2));+ }+ GLctx.uniform1fv(webglGetUniformLocation(location), view);+};++var _glUniform1fv = _emscripten_glUniform1fv;++var _emscripten_glUniform1i = (location, v0) => {+ GLctx.uniform1i(webglGetUniformLocation(location), v0);+};++var _glUniform1i = _emscripten_glUniform1i;++var _emscripten_glUniform2f = (location, v0, v1) => {+ GLctx.uniform2f(webglGetUniformLocation(location), v0, v1);+};++var _glUniform2f = _emscripten_glUniform2f;++var _emscripten_glUniform2fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform2fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 2);+ return;+ }+ if (count <= 144) {+ // avoid allocation when uploading few enough uniforms+ count *= 2;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 2) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 8) >> 2));+ }+ GLctx.uniform2fv(webglGetUniformLocation(location), view);+};++var _glUniform2fv = _emscripten_glUniform2fv;++var _emscripten_glUniform3f = (location, v0, v1, v2) => {+ GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2);+};++var _glUniform3f = _emscripten_glUniform3f;++var _emscripten_glUniform4f = (location, v0, v1, v2, v3) => {+ GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3);+};++var _glUniform4f = _emscripten_glUniform4f;++var _emscripten_glUniform4fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[4 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 4;+ for (var i = 0; i < count; i += 4) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4fv(webglGetUniformLocation(location), view);+};++var _glUniform4fv = _emscripten_glUniform4fv;++var miniTempWebGLIntBuffers = [];++var _emscripten_glUniform4iv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4iv(webglGetUniformLocation(location), HEAP32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLIntBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAP32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAP32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAP32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAP32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAP32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4iv(webglGetUniformLocation(location), view);+};++var _glUniform4iv = _emscripten_glUniform4iv;++var _emscripten_glUniformBlockBinding = (program, uniformBlockIndex, uniformBlockBinding) => {+ program = GL.programs[program];+ GLctx.uniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);+};++var _glUniformBlockBinding = _emscripten_glUniformBlockBinding;++var _emscripten_glUniformMatrix2fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix2fv = _emscripten_glUniformMatrix2fv;++var _emscripten_glUniformMatrix3fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 9);+ return;+ }+ if (count <= 32) {+ // avoid allocation when uploading few enough uniforms+ count *= 9;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 9) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ view[i + 4] = HEAPF32[(((value) + (4 * i + 16)) >> 2)];+ view[i + 5] = HEAPF32[(((value) + (4 * i + 20)) >> 2)];+ view[i + 6] = HEAPF32[(((value) + (4 * i + 24)) >> 2)];+ view[i + 7] = HEAPF32[(((value) + (4 * i + 28)) >> 2)];+ view[i + 8] = HEAPF32[(((value) + (4 * i + 32)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 36) >> 2));+ }+ GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix3fv = _emscripten_glUniformMatrix3fv;++var _emscripten_glUniformMatrix4fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 16);+ return;+ }+ if (count <= 18) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[16 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 16;+ for (var i = 0; i < count; i += 16) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ view[i + 4] = heap[dst + 4];+ view[i + 5] = heap[dst + 5];+ view[i + 6] = heap[dst + 6];+ view[i + 7] = heap[dst + 7];+ view[i + 8] = heap[dst + 8];+ view[i + 9] = heap[dst + 9];+ view[i + 10] = heap[dst + 10];+ view[i + 11] = heap[dst + 11];+ view[i + 12] = heap[dst + 12];+ view[i + 13] = heap[dst + 13];+ view[i + 14] = heap[dst + 14];+ view[i + 15] = heap[dst + 15];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 64) >> 2));+ }+ GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix4fv = _emscripten_glUniformMatrix4fv;++var _emscripten_glUseProgram = program => {+ program = GL.programs[program];+ GLctx.useProgram(program);+ // Record the currently active program so that we can access the uniform+ // mapping table of that program.+ GLctx.currentProgram = program;+};++var _glUseProgram = _emscripten_glUseProgram;++var _emscripten_glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => {+ var cb = GL.currentContext.clientBuffers[index];+ if (!GLctx.currentArrayBufferBinding) {+ cb.size = size;+ cb.type = type;+ cb.normalized = normalized;+ cb.stride = stride;+ cb.ptr = ptr;+ cb.clientside = true;+ cb.vertexAttribPointerAdaptor = function(index, size, type, normalized, stride, ptr) {+ this.vertexAttribPointer(index, size, type, normalized, stride, ptr);+ };+ return;+ }+ cb.clientside = false;+ GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);+};++var _glVertexAttribPointer = _emscripten_glVertexAttribPointer;++var _emscripten_glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3);++var _glViewport = _emscripten_glViewport;++function _mediapipe_find_canvas_event_target(canvasSelector) {+ let target = findCanvasEventTarget(canvasSelector);+ // WebGPU-on-worker uses this function to try to grab the canvas, but+ // doesn't have a DOM element to find. So as a quick patch, if the default+ // behavior is unsuccessful here then we try a webgpu canvas property+ // which is set by the user directly on the Module, much like how our old+ // pipeline used the Module.canvas property. See b/265271517 for details.+ if (Module && !target) {+ target = Module.canvasWebGpu;+ }+ return Emval.toHandle(target);+}++function _mediapipe_webgl_tex_image_drawable(drawableHandle) {+ const drawable = Emval.toValue(drawableHandle);+ GLctx.texImage2D(GLctx.TEXTURE_2D, 0, GLctx.RGBA, GLctx.RGBA, GLctx.UNSIGNED_BYTE, drawable);+}++var _random_get = (buffer, size) => randomFill(HEAPU8.subarray(buffer, buffer + size));++var _wgpuCommandEncoderBeginComputePass = (encoderPtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (12)) >> 2)])+ };+ }+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateComputePassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginComputePass(desc));+ return ptr;+};++var _wgpuCommandEncoderBeginRenderPass = (encoderPtr, descriptor) => {+ function makeColorAttachment(caPtr) {+ var viewPtr = HEAPU32[(((caPtr) + (4)) >> 2)];+ if (viewPtr === 0) {+ // Null `view` means no attachment in this slot.+ return undefined;+ }+ var depthSlice = HEAPU32[(((caPtr) + (8)) >> 2)];+ if (depthSlice == 4294967295) depthSlice = undefined;+ return {+ "view": WebGPU.getJsObject(viewPtr),+ "depthSlice": depthSlice,+ "resolveTarget": WebGPU.getJsObject(HEAPU32[(((caPtr) + (12)) >> 2)]),+ "clearValue": WebGPU.makeColor(caPtr + 24),+ "loadOp": WebGPU.LoadOp[HEAP32[(((caPtr) + (16)) >> 2)]],+ "storeOp": WebGPU.StoreOp[HEAP32[(((caPtr) + (20)) >> 2)]]+ };+ }+ function makeColorAttachments(count, caPtr) {+ var attachments = [];+ for (var i = 0; i < count; ++i) {+ attachments.push(makeColorAttachment(caPtr + 56 * i));+ }+ return attachments;+ }+ function makeDepthStencilAttachment(dsaPtr) {+ if (dsaPtr === 0) return undefined;+ return {+ "view": WebGPU.getJsObject(HEAPU32[(((dsaPtr) + (4)) >> 2)]),+ "depthClearValue": HEAPF32[(((dsaPtr) + (16)) >> 2)],+ "depthLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (8)) >> 2)]],+ "depthStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (12)) >> 2)]],+ "depthReadOnly": !!(HEAPU32[(((dsaPtr) + (20)) >> 2)]),+ "stencilClearValue": HEAPU32[(((dsaPtr) + (32)) >> 2)],+ "stencilLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (24)) >> 2)]],+ "stencilStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (28)) >> 2)]],+ "stencilReadOnly": !!(HEAPU32[(((dsaPtr) + (36)) >> 2)])+ };+ }+ function makeRenderPassDescriptor(descriptor) {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var maxDrawCount = undefined;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var renderPassMaxDrawCount = nextInChainPtr;+ // Note: The user could have passed a really huge value here, which is technically valid in+ // C but will not be allowed by WebGPU in JS because of [EnforceRange]. We intentionally+ // ignore that case because it's not useful - apps can just pick a smaller maxDrawCount.+ maxDrawCount = readI53FromI64((renderPassMaxDrawCount) + (8));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "colorAttachments": makeColorAttachments(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]),+ "depthStencilAttachment": makeDepthStencilAttachment(HEAPU32[(((descriptor) + (20)) >> 2)]),+ "occlusionQuerySet": WebGPU.getJsObject(HEAPU32[(((descriptor) + (24)) >> 2)]),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (28)) >> 2)]),+ "maxDrawCount": maxDrawCount+ };+ return desc;+ }+ var desc = makeRenderPassDescriptor(descriptor);+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateRenderPassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginRenderPass(desc));+ return ptr;+};++var _wgpuCommandEncoderCopyBufferToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToBuffer = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyBufferInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderFinish = (encoderPtr, descriptor) => {+ // TODO: Use the descriptor.+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateCommandBuffer(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.finish());+ return ptr;+};++var _wgpuComputePassEncoderDispatchWorkgroups = (passPtr, x, y, z) => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.dispatchWorkgroups(x, y, z);+};++var _wgpuComputePassEncoderEnd = passPtr => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.end();+};++var _wgpuComputePassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuComputePassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuComputePipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuDeviceCreateBindGroup = (devicePtr, descriptor) => {+ function makeEntry(entryPtr) {+ var bufferPtr = HEAPU32[(((entryPtr) + (8)) >> 2)];+ var samplerPtr = HEAPU32[(((entryPtr) + (32)) >> 2)];+ var textureViewPtr = HEAPU32[(((entryPtr) + (36)) >> 2)];+ var externalTexturePtr = 0;+ WebGPU.iterateExtensions(entryPtr, {+ 14: ptr => {+ externalTexturePtr = HEAPU32[(((ptr) + (8)) >> 2)];+ }+ });+ var resource;+ if (bufferPtr) {+ // Note the sentinel UINT64_MAX will be read as -1.+ var size = readI53FromI64((entryPtr) + (24));+ if (size == -1) size = undefined;+ resource = {+ "buffer": WebGPU.getJsObject(bufferPtr),+ "offset": readI53FromI64((entryPtr) + (16)),+ "size": size+ };+ } else {+ resource = WebGPU.getJsObject(samplerPtr || textureViewPtr || externalTexturePtr);+ }+ return {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "resource": resource+ };+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 40 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.getJsObject(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "entries": makeEntries(HEAPU32[(((descriptor) + (16)) >> 2)], HEAPU32[(((descriptor) + (20)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroup(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroup(desc));+ return ptr;+};++var _wgpuDeviceCreateBindGroupLayout = (devicePtr, descriptor) => {+ function makeBufferEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.BufferBindingType[typeInt],+ "hasDynamicOffset": !!(HEAPU32[(((substructPtr) + (8)) >> 2)]),+ "minBindingSize": readI53FromI64((substructPtr) + (16))+ };+ }+ function makeSamplerEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.SamplerBindingType[typeInt]+ };+ }+ function makeTextureEntry(substructPtr) {+ var sampleTypeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!sampleTypeInt) return undefined;+ return {+ "sampleType": WebGPU.TextureSampleType[sampleTypeInt],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "multisampled": !!(HEAPU32[(((substructPtr) + (12)) >> 2)])+ };+ }+ function makeStorageTextureEntry(substructPtr) {+ var accessInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!accessInt) return undefined;+ return {+ "access": WebGPU.StorageTextureAccess[accessInt],+ "format": WebGPU.TextureFormat[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (12)) >> 2)]]+ };+ }+ function makeEntry(entryPtr) {+ var entry = {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "visibility": HEAPU32[(((entryPtr) + (8)) >> 2)],+ "buffer": makeBufferEntry(entryPtr + 24),+ "sampler": makeSamplerEntry(entryPtr + 48),+ "texture": makeTextureEntry(entryPtr + 56),+ "storageTexture": makeStorageTextureEntry(entryPtr + 72)+ };+ WebGPU.iterateExtensions(entryPtr, {+ 13: ptr => {+ entry["externalTexture"] = {};+ }+ });+ return entry;+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 88 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "entries": makeEntries(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroupLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateCommandEncoder = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4)+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateCommandEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createCommandEncoder(desc));+ return ptr;+};++var _wgpuDeviceCreateComputePipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateComputePipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createComputePipeline(desc));+ return ptr;+};++var _wgpuDeviceCreatePipelineLayout = (devicePtr, descriptor) => {+ var bglCount = HEAPU32[(((descriptor) + (12)) >> 2)];+ var bglPtr = HEAPU32[(((descriptor) + (16)) >> 2)];+ var bgls = [];+ for (var i = 0; i < bglCount; ++i) {+ bgls.push(WebGPU.getJsObject(HEAPU32[(((bglPtr) + (4 * i)) >> 2)]));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "bindGroupLayouts": bgls+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreatePipelineLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createPipelineLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateRenderPipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateRenderPipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createRenderPipeline(desc));+ return ptr;+};++var _wgpuDeviceCreateSampler = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "addressModeU": WebGPU.AddressMode[HEAP32[(((descriptor) + (12)) >> 2)]],+ "addressModeV": WebGPU.AddressMode[HEAP32[(((descriptor) + (16)) >> 2)]],+ "addressModeW": WebGPU.AddressMode[HEAP32[(((descriptor) + (20)) >> 2)]],+ "magFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (24)) >> 2)]],+ "minFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (28)) >> 2)]],+ "mipmapFilter": WebGPU.MipmapFilterMode[HEAP32[(((descriptor) + (32)) >> 2)]],+ "lodMinClamp": HEAPF32[(((descriptor) + (36)) >> 2)],+ "lodMaxClamp": HEAPF32[(((descriptor) + (40)) >> 2)],+ "compare": WebGPU.CompareFunction[HEAP32[(((descriptor) + (44)) >> 2)]],+ "maxAnisotropy": HEAPU16[(((descriptor) + (48)) >> 1)]+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateSampler(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createSampler(desc));+ return ptr;+};++var _wgpuDeviceCreateTexture = (devicePtr, descriptor) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var textureBindingViewDimension;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var textureBindingViewDimensionDescriptor = nextInChainPtr;+ textureBindingViewDimension = WebGPU.TextureViewDimension[HEAP32[(((textureBindingViewDimensionDescriptor) + (8)) >> 2)]];+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "size": WebGPU.makeExtent3D(descriptor + 28),+ "mipLevelCount": HEAPU32[(((descriptor) + (44)) >> 2)],+ "sampleCount": HEAPU32[(((descriptor) + (48)) >> 2)],+ "dimension": WebGPU.TextureDimension[HEAP32[(((descriptor) + (24)) >> 2)]],+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (40)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "textureBindingViewDimension": textureBindingViewDimension+ };+ var viewFormatCount = HEAPU32[(((descriptor) + (52)) >> 2)];+ if (viewFormatCount) {+ var viewFormatsPtr = HEAPU32[(((descriptor) + (56)) >> 2)];+ // viewFormatsPtr pointer to an array of TextureFormat which is an enum of size uint32_t+ desc["viewFormats"] = Array.from(HEAP32.subarray((((viewFormatsPtr) >> 2)), ((viewFormatsPtr + viewFormatCount * 4) >> 2)), format => WebGPU.TextureFormat[format]);+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateTexture(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createTexture(desc));+ return ptr;+};++var _wgpuQueueSubmit = (queuePtr, commandCount, commands) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var cmds = Array.from(HEAP32.subarray((((commands) >> 2)), ((commands + commandCount * 4) >> 2)), id => WebGPU.getJsObject(id));+ queue.submit(cmds);+};++function _wgpuQueueWriteBuffer(queuePtr, bufferPtr, bufferOffset_low, bufferOffset_high, data, size) {+ var bufferOffset = convertI32PairToI53Checked(bufferOffset_low, bufferOffset_high);+ var queue = WebGPU.getJsObject(queuePtr);+ var buffer = WebGPU.getJsObject(bufferPtr);+ // There is a size limitation for ArrayBufferView. Work around by passing in a subarray+ // instead of the whole heap. crbug.com/1201109+ var subarray = HEAPU8.subarray(data, data + size);+ queue.writeBuffer(buffer, bufferOffset, subarray, 0, size);+}++var _wgpuQueueWriteTexture = (queuePtr, destinationPtr, data, dataSize, dataLayoutPtr, writeSizePtr) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var destination = WebGPU.makeTexelCopyTextureInfo(destinationPtr);+ var dataLayout = WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr);+ var writeSize = WebGPU.makeExtent3D(writeSizePtr);+ // This subarray isn't strictly necessary, but helps work around an issue+ // where Chromium makes a copy of the entire heap. crbug.com/1134457+ var subarray = HEAPU8.subarray(data, data + dataSize);+ queue.writeTexture(destination, subarray, dataLayout, writeSize);+};++var _wgpuRenderPassEncoderDraw = (passPtr, vertexCount, instanceCount, firstVertex, firstInstance) => {+ firstVertex >>>= 0;+ firstInstance >>>= 0;+ var pass = WebGPU.getJsObject(passPtr);+ pass.draw(vertexCount, instanceCount, firstVertex, firstInstance);+};++var _wgpuRenderPassEncoderEnd = encoderPtr => {+ var encoder = WebGPU.getJsObject(encoderPtr);+ encoder.end();+};++var _wgpuRenderPassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuRenderPassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuRenderPipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuTextureCreateView = (texturePtr, descriptor) => {+ var desc;+ if (descriptor) {+ var swizzle;+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var swizzleDescriptor = nextInChainPtr;+ var swizzlePtr = swizzleDescriptor + 8;+ var r = WebGPU.ComponentSwizzle[HEAP32[((swizzlePtr) >> 2)]] || "r";+ var g = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (4)) >> 2)]] || "g";+ var b = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (8)) >> 2)]] || "b";+ var a = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (12)) >> 2)]] || "a";+ swizzle = `${r}${g}${b}${a}`;+ }+ var mipLevelCount = HEAPU32[(((descriptor) + (24)) >> 2)];+ var arrayLayerCount = HEAPU32[(((descriptor) + (32)) >> 2)];+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (12)) >> 2)]],+ "dimension": WebGPU.TextureViewDimension[HEAP32[(((descriptor) + (16)) >> 2)]],+ "baseMipLevel": HEAPU32[(((descriptor) + (20)) >> 2)],+ "mipLevelCount": mipLevelCount === 4294967295 ? undefined : mipLevelCount,+ "baseArrayLayer": HEAPU32[(((descriptor) + (28)) >> 2)],+ "arrayLayerCount": arrayLayerCount === 4294967295 ? undefined : arrayLayerCount,+ "aspect": WebGPU.TextureAspect[HEAP32[(((descriptor) + (36)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (40)) >> 2)],+ "swizzle": swizzle+ };+ }+ var texture = WebGPU.getJsObject(texturePtr);+ var ptr = _emwgpuCreateTextureView(0);+ WebGPU.Internals.jsObjectInsert(ptr, texture.createView(desc));+ return ptr;+};++var _wgpuTextureDestroy = texturePtr => {+ WebGPU.getJsObject(texturePtr).destroy();+};++var _wgpuTextureGetFormat = texturePtr => {+ var texture = WebGPU.getJsObject(texturePtr);+ // Should return the enum integer instead of string.+ return WebGPU.TextureFormat.indexOf(texture.format);+};++var getCFunc = ident => {+ var func = Module["_" + ident];+ // closure exported function+ return func;+};++var writeArrayToMemory = (array, buffer) => {+ HEAP8.set(array, buffer);+};++/**+ * @param {string|null=} returnType+ * @param {Array=} argTypes+ * @param {Array=} args+ * @param {Object=} opts+ */ var ccall = (ident, returnType, argTypes, args, opts) => {+ // For fast lookup of conversion functions+ var toC = {+ "string": str => {+ var ret = 0;+ if (str !== null && str !== undefined && str !== 0) {+ // null string+ ret = stringToUTF8OnStack(str);+ }+ return ret;+ },+ "array": arr => {+ var ret = stackAlloc(arr.length);+ writeArrayToMemory(arr, ret);+ return ret;+ }+ };+ function convertReturnValue(ret) {+ if (returnType === "string") {+ return UTF8ToString(ret);+ }+ if (returnType === "boolean") return Boolean(ret);+ return ret;+ }+ var func = getCFunc(ident);+ var cArgs = [];+ var stack = 0;+ if (args) {+ for (var i = 0; i < args.length; i++) {+ var converter = toC[argTypes[i]];+ if (converter) {+ if (stack === 0) stack = stackSave();+ cArgs[i] = converter(args[i]);+ } else {+ cArgs[i] = args[i];+ }+ }+ }+ var ret = func(...cArgs);+ function onDone(ret) {+ if (stack !== 0) stackRestore(stack);+ return convertReturnValue(ret);+ }+ ret = onDone(ret);+ return ret;+};++var FS_createPath = (...args) => FS.createPath(...args);++var FS_unlink = (...args) => FS.unlink(...args);++var FS_createLazyFile = (...args) => FS.createLazyFile(...args);++var FS_createDevice = (...args) => FS.createDevice(...args);++FS.createPreloadedFile = FS_createPreloadedFile;++FS.preloadFile = FS_preloadFile;++FS.staticInit();++// Signal GL rendering layer that processing of a new frame is about to+// start. This helps it optimize VBO double-buffering and reduce GPU stalls.+registerPreMainLoop(() => GL.newRenderingFrameStarted());++for (let i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i));++var miniTempWebGLFloatBuffersStorage = new Float32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i);+}++var miniTempWebGLIntBuffersStorage = new Int32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i);+}++// End JS library code+// include: postlibrary.js+// This file is included after the automatically-generated JS library code+// but before the wasm module is created.+{+ // Begin ATMODULES hooks+ if (Module["preloadPlugins"]) preloadPlugins = Module["preloadPlugins"];+ if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];+ if (Module["print"]) out = Module["print"];+ if (Module["printErr"]) err = Module["printErr"];+ if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];+ // End ATMODULES hooks+ if (Module["arguments"]) arguments_ = Module["arguments"];+ if (Module["thisProgram"]) thisProgram = Module["thisProgram"];+ if (Module["preInit"]) {+ if (typeof Module["preInit"] == "function") Module["preInit"] = [ Module["preInit"] ];+ while (Module["preInit"].length > 0) {+ Module["preInit"].shift()();+ }+ }+}++// Begin runtime exports+Module["addRunDependency"] = addRunDependency;++Module["removeRunDependency"] = removeRunDependency;++Module["ccall"] = ccall;++Module["stringToNewUTF8"] = stringToNewUTF8;++Module["FS_preloadFile"] = FS_preloadFile;++Module["FS_unlink"] = FS_unlink;++Module["FS_createPath"] = FS_createPath;++Module["FS_createDevice"] = FS_createDevice;++Module["FS_createDataFile"] = FS_createDataFile;++Module["FS_createLazyFile"] = FS_createLazyFile;++// End runtime exports+// Begin JS library exports+// End JS library exports+// end include: postlibrary.js+var ASM_CONSTS = {+ 1462283: $0 => {+ const canvas = Emval.toValue($0);+ const context = canvas.getContext("webgpu");+ return WebGPU.importJsTexture(context.getCurrentTexture());+ },+ 1462426: ($0, $1, $2, $3, $4) => {+ const drawable = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const texture = WebGPU.getJsObject($2);+ const width = $3;+ const height = $4;+ device.queue.copyExternalImageToTexture({+ source: drawable+ }, {+ texture+ }, [ width, height ]);+ },+ 1462685: ($0, $1, $2, $3) => {+ const sourceExtTex = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const sampler = WebGPU.getJsObject($2);+ const bgLayout = WebGPU.getJsObject($3);+ const bindGroup = device.createBindGroup({+ layout: bgLayout,+ entries: [ {+ binding: 0,+ resource: sampler+ }, {+ binding: 1,+ resource: sourceExtTex+ } ]+ });+ return WebGPU.importJsBindGroup(bindGroup);+ },+ 1463055: ($0, $1) => {+ const input = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ ctx.drawImage(input, 0, 0, output.width, output.height);+ },+ 1463220: ($0, $1) => {+ const inputArray = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ const image_data = new ImageData(inputArray, output.width, output.height);+ ctx.putImageData(image_data, 0, 0);+ },+ 1463444: ($0, $1) => {+ const input = Emval.toValue($0);+ const outputArray = Emval.toValue($1);+ const ctx = input.getContext("2d");+ const data = ctx.getImageData(0, 0, input.width, input.height);+ outputArray.set(data.data);+ },+ 1463648: () => (typeof HTMLCanvasElement !== "undefined"),+ 1463703: () => !!Module["preinitializedWebGPUDevice"],+ 1463754: () => {+ specialHTMLTargets["#canvas"] = Module.canvas;+ }+};++function BeginGlQueryTiming(calc_name, num_repetitions) {+ const gl = Module.canvas.getContext("webgl2");+ const query = gl.createQuery();+ Module.WEBGL_SHADER_CALC_METRICS = Module.WEBGL_SHADER_CALC_METRICS || {};+ Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)] = {+ query,+ repetitions: num_repetitions+ };+ Module.WEBGL_QUERY_TIMER_EXT = Module.WEBGL_QUERY_TIMER_EXT || gl.getExtension("EXT_disjoint_timer_query_webgl2");+ gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, query);+}++function EndGlQueryTiming(calc_name) {+ const gl = Module.canvas.getContext("webgl2");+ gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query);+}++function JsWrapImageConverter() {+ if (!Module._imageConverter) {+ Module._imageConverter = (binaryPtr, binarySize, width, height, numChannels, makeDeepCopy, outputType) => {+ const imageData = new outputType(makeDeepCopy ? Module.HEAPU8.slice(binaryPtr, binaryPtr + binarySize).buffer : Module.HEAPU8.buffer, binaryPtr, width * height * numChannels);+ return {+ data: imageData,+ width,+ height+ };+ };+ }+}++function JsOnUint8ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnFloat32ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnWebGLTextureListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, timestamp_ms);+}++function JsOnUint8ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnFloat32ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnWebGLTextureVectorListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, false, timestamp_ms);+}++function JsOnEmptyPacketListener(output_stream_name, timestamp) {+ Module._wrapEmptyPacketListenerOutput(output_stream_name, timestamp);+}++function JsOnVectorFinishedListener(output_stream_name, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, undefined, true, timestamp);+}++function JsOnSimpleListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), timestamp);+}++function JsOnVectorListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), false, timestamp);+}++function JsOnVectorListenerProto(output_stream_name, proto_ptr, proto_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(proto_ptr, proto_ptr + proto_size) : new Uint8Array(Module.HEAPU8.buffer, proto_ptr, proto_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, false, timestamp);+}++function JsWrapSimpleListeners() {+ if (!Module._wrapSimpleListenerOutput) {+ Module._wrapSimpleListenerOutput = (outputStreamName, ...args) => {+ if (Module.simpleListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.simpleListeners[streamName]) {+ Module.simpleListeners[streamName](...args);+ }+ }+ };+ }+ if (!Module._wrapEmptyPacketListenerOutput) {+ Module._wrapEmptyPacketListenerOutput = (outputStreamName, timestamp) => {+ if (Module.emptyPacketListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.emptyPacketListeners[streamName]) {+ Module.emptyPacketListeners[streamName](timestamp);+ }+ }+ };+ }+}++function JsOnSimpleListenerBinaryArray(output_stream_name, binary_ptr, binary_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(binary_ptr, binary_ptr + binary_size) : new Uint8Array(Module.HEAPU8.buffer, binary_ptr, binary_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, timestamp);+}++function mediapipe_import_external_texture(device_handle, source_handle) {+ const device = WebGPU.getJsObject(device_handle);+ const source = Emval.toValue(source_handle);+ const externalTexture = device.importExternalTexture({+ source+ });+ return Emval.toHandle(externalTexture);+}++function mediapipe_create_utility_canvas2d() {+ let canvas;+ if (typeof HTMLCanvasElement !== "undefined") {+ canvas = document.createElement("canvas");+ canvas.style.display = "none";+ } else {+ canvas = new OffscreenCanvas(0, 0);+ }+ return Emval.toHandle(canvas);+}++function GetAdapterArchitecture() {+ const device = Module["preinitializedWebGPUDevice"];+ const architecture = device.adapterInfo ? device.adapterInfo.architecture : "Unknown";+ return stringToNewUTF8(architecture);+}++function GetAdapterDescription() {+ const device = Module["preinitializedWebGPUDevice"];+ const description = device.adapterInfo ? device.adapterInfo.description : "Unknown";+ return stringToNewUTF8(description);+}++function GetAdapterDeviceName() {+ const device = Module["preinitializedWebGPUDevice"];+ const deviceName = device.adapterInfo ? device.adapterInfo.device : "Unknown";+ return stringToNewUTF8(deviceName);+}++function GetAdapterVendor() {+ const device = Module["preinitializedWebGPUDevice"];+ const vendor = device.adapterInfo ? device.adapterInfo.vendor : "Unknown";+ return stringToNewUTF8(vendor);+}++function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle, data) {+ return Asyncify.handleAsync(async () => {+ const buffer = WebGPU.getJsObject(buffer_handle);+ if ("mapSync" in buffer) {+ buffer.mapSync(GPUMapMode.READ);+ } else {+ await buffer.mapAsync(GPUMapMode.READ);+ }+ const mapped = buffer.getMappedRange();+ HEAPU8.set(new Uint8Array(mapped), data);+ buffer.unmap();+ });+}++function hardware_concurrency() {+ var concurrency = 1;+ try {+ concurrency = self.navigator.hardwareConcurrency;+ } catch (e) {}+ return concurrency;+}++function JsWrapErrorListener(code, message) {+ if (Module.errorListener) {+ const stringMessage = UTF8ToString(message);+ Module.errorListener(code, stringMessage);+ }+}++function UseBottomLeftGpuOrigin() {+ return (Module && Module.gpuOriginForWebTexturesIsBottomLeft);+}++function custom_emscripten_dbgn(str, len) {+ if (typeof (dbg) !== "undefined") {+ dbg(UTF8ToString(str, len));+ } else {+ if (typeof (custom_dbg) === "undefined") {+ function custom_dbg(text) {+ console.warn.apply(console, arguments);+ }+ }+ custom_dbg(UTF8ToString(str, len));+ }+}++// Imports from the Wasm binary.+var _free, _malloc, _wgpuDeviceAddRef, _addBoundTextureAsImageToStream, _attachImageListener, _attachImageVectorListener, _registerModelResourcesGraphService, _bindTextureToStream, _addBoundTextureToStream, _addDoubleToInputStream, _addFloatToInputStream, _addBoolToInputStream, _addIntToInputStream, _addUintToInputStream, _addStringToInputStream, _addRawDataSpanToInputStream, _allocateBoolVector, _allocateFloatVector, _allocateDoubleVector, _allocateIntVector, _allocateUintVector, _allocateStringVector, _addBoolVectorEntry, _addFloatVectorEntry, _addDoubleVectorEntry, _addIntVectorEntry, _addUintVectorEntry, _addStringVectorEntry, _addBoolVectorToInputStream, _addFloatVectorToInputStream, _addDoubleVectorToInputStream, _addIntVectorToInputStream, _addUintVectorToInputStream, _addStringVectorToInputStream, _addFlatHashMapToInputStream, _addProtoToInputStream, _addEmptyPacketToInputStream, _addBoolToInputSidePacket, _addDoubleToInputSidePacket, _addFloatToInputSidePacket, _addIntToInputSidePacket, _addUintToInputSidePacket, _addStringToInputSidePacket, _addRawDataSpanToInputSidePacket, _addProtoToInputSidePacket, _addBoolVectorToInputSidePacket, _addDoubleVectorToInputSidePacket, _addFloatVectorToInputSidePacket, _addIntVectorToInputSidePacket, _addUintVectorToInputSidePacket, _addStringVectorToInputSidePacket, _attachBoolListener, _attachBoolVectorListener, _attachDoubleListener, _attachDoubleVectorListener, _attachFloatListener, _attachFloatVectorListener, _attachIntListener, _attachIntVectorListener, _attachUintListener, _attachUintVectorListener, _attachStringListener, _attachStringVectorListener, _attachProtoListener, _attachProtoVectorListener, _getGraphConfig, ___getTypeName, _emwgpuCreateBindGroup, _emwgpuCreateBindGroupLayout, _emwgpuCreateCommandBuffer, _emwgpuCreateCommandEncoder, _emwgpuCreateComputePassEncoder, _emwgpuCreateComputePipeline, _emwgpuCreateExternalTexture, _emwgpuCreatePipelineLayout, _emwgpuCreateQuerySet, _emwgpuCreateRenderBundle, _emwgpuCreateRenderBundleEncoder, _emwgpuCreateRenderPassEncoder, _emwgpuCreateRenderPipeline, _emwgpuCreateSampler, _emwgpuCreateSurface, _emwgpuCreateTexture, _emwgpuCreateTextureView, _emwgpuCreateAdapter, _emwgpuImportBuffer, _emwgpuCreateDevice, _emwgpuCreateQueue, _emwgpuCreateShaderModule, _emwgpuOnCreateComputePipelineCompleted, _emwgpuOnCreateRenderPipelineCompleted, _clearSubgraphs, _pushBinarySubgraph, _pushTextSubgraph, _changeBinaryGraph, _changeTextGraph, _processGl, _process, _bindTextureToCanvas, _requestShaderRefreshOnGraphChange, _waitUntilIdle, _closeGraph, _setAutoRenderToScreen, _emscripten_builtin_memalign, _memalign, __emscripten_tempret_set, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, dynCall_ji, dynCall_jii, dynCall_iiiijij, dynCall_viiji, dynCall_viji, dynCall_iiiji, dynCall_jjj, dynCall_iiiijj, dynCall_viijj, dynCall_viiijjj, dynCall_vij, dynCall_viiiji, dynCall_viijii, dynCall_vijjj, dynCall_vj, dynCall_viij, dynCall_jiji, dynCall_iiiiij, dynCall_iiiiijj, dynCall_iiiiiijj, memory, _kVersionStampBuildChangelistStr, _kVersionStampCitcSnapshotStr, _kVersionStampCitcWorkspaceIdStr, _kVersionStampSourceUriStr, _kVersionStampBuildClientStr, _kVersionStampBuildClientMintStatusStr, _kVersionStampBuildCompilerStr, _kVersionStampBuildDateTimePstStr, _kVersionStampBuildDepotPathStr, _kVersionStampBuildIdStr, _kVersionStampBuildInfoStr, _kVersionStampBuildLabelStr, _kVersionStampBuildTargetStr, _kVersionStampBuildTimestampStr, _kVersionStampBuildToolStr, _kVersionStampG3BuildTargetStr, _kVersionStampVerifiableStr, _kVersionStampBuildFdoTypeStr, _kVersionStampBuildBaselineChangelistStr, _kVersionStampBuildLtoTypeStr, _kVersionStampBuildPropellerTypeStr, _kVersionStampBuildPghoTypeStr, _kVersionStampBuildUsernameStr, _kVersionStampBuildHostnameStr, _kVersionStampBuildDirectoryStr, _kVersionStampBuildChangelistInt, _kVersionStampCitcSnapshotInt, _kVersionStampBuildClientMintStatusInt, _kVersionStampBuildTimestampInt, _kVersionStampVerifiableInt, _kVersionStampBuildCoverageEnabledInt, _kVersionStampBuildBaselineChangelistInt, _kVersionStampPrecookedTimestampStr, _kVersionStampPrecookedClientInfoStr, __indirect_function_table, wasmMemory, wasmTable;++function assignWasmExports(wasmExports) {+ _free = Module["_free"] = wasmExports["Td"];+ _malloc = Module["_malloc"] = wasmExports["Ud"];+ _wgpuDeviceAddRef = wasmExports["Vd"];+ _addBoundTextureAsImageToStream = Module["_addBoundTextureAsImageToStream"] = wasmExports["Wd"];+ _attachImageListener = Module["_attachImageListener"] = wasmExports["Xd"];+ _attachImageVectorListener = Module["_attachImageVectorListener"] = wasmExports["Yd"];+ _registerModelResourcesGraphService = Module["_registerModelResourcesGraphService"] = wasmExports["Zd"];+ _bindTextureToStream = Module["_bindTextureToStream"] = wasmExports["_d"];+ _addBoundTextureToStream = Module["_addBoundTextureToStream"] = wasmExports["$d"];+ _addDoubleToInputStream = Module["_addDoubleToInputStream"] = wasmExports["ae"];+ _addFloatToInputStream = Module["_addFloatToInputStream"] = wasmExports["be"];+ _addBoolToInputStream = Module["_addBoolToInputStream"] = wasmExports["ce"];+ _addIntToInputStream = Module["_addIntToInputStream"] = wasmExports["de"];+ _addUintToInputStream = Module["_addUintToInputStream"] = wasmExports["ee"];+ _addStringToInputStream = Module["_addStringToInputStream"] = wasmExports["fe"];+ _addRawDataSpanToInputStream = Module["_addRawDataSpanToInputStream"] = wasmExports["ge"];+ _allocateBoolVector = Module["_allocateBoolVector"] = wasmExports["he"];+ _allocateFloatVector = Module["_allocateFloatVector"] = wasmExports["ie"];+ _allocateDoubleVector = Module["_allocateDoubleVector"] = wasmExports["je"];+ _allocateIntVector = Module["_allocateIntVector"] = wasmExports["ke"];+ _allocateUintVector = Module["_allocateUintVector"] = wasmExports["le"];+ _allocateStringVector = Module["_allocateStringVector"] = wasmExports["me"];+ _addBoolVectorEntry = Module["_addBoolVectorEntry"] = wasmExports["ne"];+ _addFloatVectorEntry = Module["_addFloatVectorEntry"] = wasmExports["oe"];+ _addDoubleVectorEntry = Module["_addDoubleVectorEntry"] = wasmExports["pe"];+ _addIntVectorEntry = Module["_addIntVectorEntry"] = wasmExports["qe"];+ _addUintVectorEntry = Module["_addUintVectorEntry"] = wasmExports["re"];+ _addStringVectorEntry = Module["_addStringVectorEntry"] = wasmExports["se"];+ _addBoolVectorToInputStream = Module["_addBoolVectorToInputStream"] = wasmExports["te"];+ _addFloatVectorToInputStream = Module["_addFloatVectorToInputStream"] = wasmExports["ue"];+ _addDoubleVectorToInputStream = Module["_addDoubleVectorToInputStream"] = wasmExports["ve"];+ _addIntVectorToInputStream = Module["_addIntVectorToInputStream"] = wasmExports["we"];+ _addUintVectorToInputStream = Module["_addUintVectorToInputStream"] = wasmExports["xe"];+ _addStringVectorToInputStream = Module["_addStringVectorToInputStream"] = wasmExports["ye"];+ _addFlatHashMapToInputStream = Module["_addFlatHashMapToInputStream"] = wasmExports["ze"];+ _addProtoToInputStream = Module["_addProtoToInputStream"] = wasmExports["Ae"];+ _addEmptyPacketToInputStream = Module["_addEmptyPacketToInputStream"] = wasmExports["Be"];+ _addBoolToInputSidePacket = Module["_addBoolToInputSidePacket"] = wasmExports["Ce"];+ _addDoubleToInputSidePacket = Module["_addDoubleToInputSidePacket"] = wasmExports["De"];+ _addFloatToInputSidePacket = Module["_addFloatToInputSidePacket"] = wasmExports["Ee"];+ _addIntToInputSidePacket = Module["_addIntToInputSidePacket"] = wasmExports["Fe"];+ _addUintToInputSidePacket = Module["_addUintToInputSidePacket"] = wasmExports["Ge"];+ _addStringToInputSidePacket = Module["_addStringToInputSidePacket"] = wasmExports["He"];+ _addRawDataSpanToInputSidePacket = Module["_addRawDataSpanToInputSidePacket"] = wasmExports["Ie"];+ _addProtoToInputSidePacket = Module["_addProtoToInputSidePacket"] = wasmExports["Je"];+ _addBoolVectorToInputSidePacket = Module["_addBoolVectorToInputSidePacket"] = wasmExports["Ke"];+ _addDoubleVectorToInputSidePacket = Module["_addDoubleVectorToInputSidePacket"] = wasmExports["Le"];+ _addFloatVectorToInputSidePacket = Module["_addFloatVectorToInputSidePacket"] = wasmExports["Me"];+ _addIntVectorToInputSidePacket = Module["_addIntVectorToInputSidePacket"] = wasmExports["Ne"];+ _addUintVectorToInputSidePacket = Module["_addUintVectorToInputSidePacket"] = wasmExports["Oe"];+ _addStringVectorToInputSidePacket = Module["_addStringVectorToInputSidePacket"] = wasmExports["Pe"];+ _attachBoolListener = Module["_attachBoolListener"] = wasmExports["Qe"];+ _attachBoolVectorListener = Module["_attachBoolVectorListener"] = wasmExports["Re"];+ _attachDoubleListener = Module["_attachDoubleListener"] = wasmExports["Se"];+ _attachDoubleVectorListener = Module["_attachDoubleVectorListener"] = wasmExports["Te"];+ _attachFloatListener = Module["_attachFloatListener"] = wasmExports["Ue"];+ _attachFloatVectorListener = Module["_attachFloatVectorListener"] = wasmExports["Ve"];+ _attachIntListener = Module["_attachIntListener"] = wasmExports["We"];+ _attachIntVectorListener = Module["_attachIntVectorListener"] = wasmExports["Xe"];+ _attachUintListener = Module["_attachUintListener"] = wasmExports["Ye"];+ _attachUintVectorListener = Module["_attachUintVectorListener"] = wasmExports["Ze"];+ _attachStringListener = Module["_attachStringListener"] = wasmExports["_e"];+ _attachStringVectorListener = Module["_attachStringVectorListener"] = wasmExports["$e"];+ _attachProtoListener = Module["_attachProtoListener"] = wasmExports["af"];+ _attachProtoVectorListener = Module["_attachProtoVectorListener"] = wasmExports["bf"];+ _getGraphConfig = Module["_getGraphConfig"] = wasmExports["cf"];+ ___getTypeName = wasmExports["df"];+ _emwgpuCreateBindGroup = wasmExports["ef"];+ _emwgpuCreateBindGroupLayout = wasmExports["ff"];+ _emwgpuCreateCommandBuffer = wasmExports["gf"];+ _emwgpuCreateCommandEncoder = wasmExports["hf"];+ _emwgpuCreateComputePassEncoder = wasmExports["jf"];+ _emwgpuCreateComputePipeline = wasmExports["kf"];+ _emwgpuCreateExternalTexture = wasmExports["lf"];+ _emwgpuCreatePipelineLayout = wasmExports["mf"];+ _emwgpuCreateQuerySet = wasmExports["nf"];+ _emwgpuCreateRenderBundle = wasmExports["of"];+ _emwgpuCreateRenderBundleEncoder = wasmExports["pf"];+ _emwgpuCreateRenderPassEncoder = wasmExports["qf"];+ _emwgpuCreateRenderPipeline = wasmExports["rf"];+ _emwgpuCreateSampler = wasmExports["sf"];+ _emwgpuCreateSurface = wasmExports["tf"];+ _emwgpuCreateTexture = wasmExports["uf"];+ _emwgpuCreateTextureView = wasmExports["vf"];+ _emwgpuCreateAdapter = wasmExports["wf"];+ _emwgpuImportBuffer = wasmExports["xf"];+ _emwgpuCreateDevice = wasmExports["yf"];+ _emwgpuCreateQueue = wasmExports["zf"];+ _emwgpuCreateShaderModule = wasmExports["Af"];+ _emwgpuOnCreateComputePipelineCompleted = wasmExports["Bf"];+ _emwgpuOnCreateRenderPipelineCompleted = wasmExports["Cf"];+ _clearSubgraphs = Module["_clearSubgraphs"] = wasmExports["Df"];+ _pushBinarySubgraph = Module["_pushBinarySubgraph"] = wasmExports["Ef"];+ _pushTextSubgraph = Module["_pushTextSubgraph"] = wasmExports["Ff"];+ _changeBinaryGraph = Module["_changeBinaryGraph"] = wasmExports["Gf"];+ _changeTextGraph = Module["_changeTextGraph"] = wasmExports["Hf"];+ _processGl = Module["_processGl"] = wasmExports["If"];+ _process = Module["_process"] = wasmExports["Jf"];+ _bindTextureToCanvas = Module["_bindTextureToCanvas"] = wasmExports["Kf"];+ _requestShaderRefreshOnGraphChange = Module["_requestShaderRefreshOnGraphChange"] = wasmExports["Lf"];+ _waitUntilIdle = Module["_waitUntilIdle"] = wasmExports["Mf"];+ _closeGraph = Module["_closeGraph"] = wasmExports["Nf"];+ _setAutoRenderToScreen = Module["_setAutoRenderToScreen"] = wasmExports["Of"];+ _emscripten_builtin_memalign = wasmExports["Pf"];+ _memalign = wasmExports["Qf"];+ __emscripten_tempret_set = wasmExports["Rf"];+ __emscripten_stack_restore = wasmExports["Sf"];+ __emscripten_stack_alloc = wasmExports["Tf"];+ _emscripten_stack_get_current = wasmExports["Uf"];+ dynCall_ji = wasmExports["dynCall_ji"];+ dynCall_jii = wasmExports["dynCall_jii"];+ dynCall_iiiijij = wasmExports["dynCall_iiiijij"];+ dynCall_viiji = wasmExports["dynCall_viiji"];+ dynCall_viji = wasmExports["dynCall_viji"];+ dynCall_iiiji = wasmExports["dynCall_iiiji"];+ dynCall_jjj = wasmExports["dynCall_jjj"];+ dynCall_iiiijj = wasmExports["dynCall_iiiijj"];+ dynCall_viijj = wasmExports["dynCall_viijj"];+ dynCall_viiijjj = wasmExports["dynCall_viiijjj"];+ dynCall_vij = wasmExports["dynCall_vij"];+ dynCall_viiiji = wasmExports["dynCall_viiiji"];+ dynCall_viijii = wasmExports["dynCall_viijii"];+ dynCall_vijjj = wasmExports["dynCall_vijjj"];+ dynCall_vj = wasmExports["dynCall_vj"];+ dynCall_viij = wasmExports["dynCall_viij"];+ dynCall_jiji = wasmExports["dynCall_jiji"];+ dynCall_iiiiij = wasmExports["dynCall_iiiiij"];+ dynCall_iiiiijj = wasmExports["dynCall_iiiiijj"];+ dynCall_iiiiiijj = wasmExports["dynCall_iiiiiijj"];+ memory = wasmMemory = wasmExports["id"];+ _kVersionStampBuildChangelistStr = Module["_kVersionStampBuildChangelistStr"] = wasmExports["kd"].value;+ _kVersionStampCitcSnapshotStr = Module["_kVersionStampCitcSnapshotStr"] = wasmExports["ld"].value;+ _kVersionStampCitcWorkspaceIdStr = Module["_kVersionStampCitcWorkspaceIdStr"] = wasmExports["md"].value;+ _kVersionStampSourceUriStr = Module["_kVersionStampSourceUriStr"] = wasmExports["nd"].value;+ _kVersionStampBuildClientStr = Module["_kVersionStampBuildClientStr"] = wasmExports["od"].value;+ _kVersionStampBuildClientMintStatusStr = Module["_kVersionStampBuildClientMintStatusStr"] = wasmExports["pd"].value;+ _kVersionStampBuildCompilerStr = Module["_kVersionStampBuildCompilerStr"] = wasmExports["qd"].value;+ _kVersionStampBuildDateTimePstStr = Module["_kVersionStampBuildDateTimePstStr"] = wasmExports["rd"].value;+ _kVersionStampBuildDepotPathStr = Module["_kVersionStampBuildDepotPathStr"] = wasmExports["sd"].value;+ _kVersionStampBuildIdStr = Module["_kVersionStampBuildIdStr"] = wasmExports["td"].value;+ _kVersionStampBuildInfoStr = Module["_kVersionStampBuildInfoStr"] = wasmExports["ud"].value;+ _kVersionStampBuildLabelStr = Module["_kVersionStampBuildLabelStr"] = wasmExports["vd"].value;+ _kVersionStampBuildTargetStr = Module["_kVersionStampBuildTargetStr"] = wasmExports["wd"].value;+ _kVersionStampBuildTimestampStr = Module["_kVersionStampBuildTimestampStr"] = wasmExports["xd"].value;+ _kVersionStampBuildToolStr = Module["_kVersionStampBuildToolStr"] = wasmExports["yd"].value;+ _kVersionStampG3BuildTargetStr = Module["_kVersionStampG3BuildTargetStr"] = wasmExports["zd"].value;+ _kVersionStampVerifiableStr = Module["_kVersionStampVerifiableStr"] = wasmExports["Ad"].value;+ _kVersionStampBuildFdoTypeStr = Module["_kVersionStampBuildFdoTypeStr"] = wasmExports["Bd"].value;+ _kVersionStampBuildBaselineChangelistStr = Module["_kVersionStampBuildBaselineChangelistStr"] = wasmExports["Cd"].value;+ _kVersionStampBuildLtoTypeStr = Module["_kVersionStampBuildLtoTypeStr"] = wasmExports["Dd"].value;+ _kVersionStampBuildPropellerTypeStr = Module["_kVersionStampBuildPropellerTypeStr"] = wasmExports["Ed"].value;+ _kVersionStampBuildPghoTypeStr = Module["_kVersionStampBuildPghoTypeStr"] = wasmExports["Fd"].value;+ _kVersionStampBuildUsernameStr = Module["_kVersionStampBuildUsernameStr"] = wasmExports["Gd"].value;+ _kVersionStampBuildHostnameStr = Module["_kVersionStampBuildHostnameStr"] = wasmExports["Hd"].value;+ _kVersionStampBuildDirectoryStr = Module["_kVersionStampBuildDirectoryStr"] = wasmExports["Id"].value;+ _kVersionStampBuildChangelistInt = Module["_kVersionStampBuildChangelistInt"] = wasmExports["Jd"].value;+ _kVersionStampCitcSnapshotInt = Module["_kVersionStampCitcSnapshotInt"] = wasmExports["Kd"].value;+ _kVersionStampBuildClientMintStatusInt = Module["_kVersionStampBuildClientMintStatusInt"] = wasmExports["Ld"].value;+ _kVersionStampBuildTimestampInt = Module["_kVersionStampBuildTimestampInt"] = wasmExports["Md"].value;+ _kVersionStampVerifiableInt = Module["_kVersionStampVerifiableInt"] = wasmExports["Nd"].value;+ _kVersionStampBuildCoverageEnabledInt = Module["_kVersionStampBuildCoverageEnabledInt"] = wasmExports["Od"].value;+ _kVersionStampBuildBaselineChangelistInt = Module["_kVersionStampBuildBaselineChangelistInt"] = wasmExports["Pd"].value;+ _kVersionStampPrecookedTimestampStr = Module["_kVersionStampPrecookedTimestampStr"] = wasmExports["Qd"].value;+ _kVersionStampPrecookedClientInfoStr = Module["_kVersionStampPrecookedClientInfoStr"] = wasmExports["Rd"].value;+ __indirect_function_table = wasmTable = wasmExports["Sd"];+}++var wasmImports = {+ /** @export */ hd: BeginGlQueryTiming,+ /** @export */ gd: EndGlQueryTiming,+ /** @export */ fd: GetAdapterArchitecture,+ /** @export */ ed: GetAdapterDescription,+ /** @export */ dd: GetAdapterDeviceName,+ /** @export */ cd: GetAdapterVendor,+ /** @export */ bd: JsOnEmptyPacketListener,+ /** @export */ ad: JsOnFloat32ArrayImageListener,+ /** @export */ $c: JsOnFloat32ArrayImageVectorListener,+ /** @export */ pb: JsOnSimpleListenerBinaryArray,+ /** @export */ _c: JsOnSimpleListenerBool,+ /** @export */ Zc: JsOnSimpleListenerDouble,+ /** @export */ Yc: JsOnSimpleListenerFloat,+ /** @export */ Xc: JsOnSimpleListenerInt,+ /** @export */ Wc: JsOnSimpleListenerString,+ /** @export */ Vc: JsOnSimpleListenerUint,+ /** @export */ Uc: JsOnUint8ArrayImageListener,+ /** @export */ Tc: JsOnUint8ArrayImageVectorListener,+ /** @export */ P: JsOnVectorFinishedListener,+ /** @export */ Sc: JsOnVectorListenerBool,+ /** @export */ Rc: JsOnVectorListenerDouble,+ /** @export */ Qc: JsOnVectorListenerFloat,+ /** @export */ Pc: JsOnVectorListenerInt,+ /** @export */ Oc: JsOnVectorListenerProto,+ /** @export */ Nc: JsOnVectorListenerString,+ /** @export */ Mc: JsOnVectorListenerUint,+ /** @export */ Lc: JsOnWebGLTextureListener,+ /** @export */ Kc: JsOnWebGLTextureVectorListener,+ /** @export */ Pa: JsWrapErrorListener,+ /** @export */ ob: JsWrapImageConverter,+ /** @export */ u: JsWrapSimpleListeners,+ /** @export */ nb: UseBottomLeftGpuOrigin,+ /** @export */ yb: __asyncjs__mediapipe_map_buffer_jspi,+ /** @export */ r: ___cxa_throw,+ /** @export */ Jc: ___syscall_dup,+ /** @export */ Ic: ___syscall_faccessat,+ /** @export */ mb: ___syscall_fcntl64,+ /** @export */ Hc: ___syscall_fstat64,+ /** @export */ Mb: ___syscall_ftruncate64,+ /** @export */ Gc: ___syscall_ioctl,+ /** @export */ Fc: ___syscall_lstat64,+ /** @export */ Ec: ___syscall_newfstatat,+ /** @export */ lb: ___syscall_openat,+ /** @export */ Dc: ___syscall_stat64,+ /** @export */ yc: __abort_js,+ /** @export */ Jb: __embind_register_bigint,+ /** @export */ xc: __embind_register_bool,+ /** @export */ wc: __embind_register_emval,+ /** @export */ jb: __embind_register_float,+ /** @export */ J: __embind_register_integer,+ /** @export */ q: __embind_register_memory_view,+ /** @export */ vc: __embind_register_std_string,+ /** @export */ Ma: __embind_register_std_wstring,+ /** @export */ uc: __embind_register_void,+ /** @export */ $: __emval_create_invoker,+ /** @export */ p: __emval_decref,+ /** @export */ La: __emval_get_global,+ /** @export */ ib: __emval_get_property,+ /** @export */ ja: __emval_incref,+ /** @export */ Ka: __emval_instanceof,+ /** @export */ _: __emval_invoke,+ /** @export */ ua: __emval_new_cstring,+ /** @export */ Z: __emval_run_destructors,+ /** @export */ hb: __emval_set_property,+ /** @export */ tc: __emval_typeof,+ /** @export */ Ib: __gmtime_js,+ /** @export */ Hb: __localtime_js,+ /** @export */ Gb: __mktime_js,+ /** @export */ Fb: __mmap_js,+ /** @export */ Eb: __munmap_js,+ /** @export */ sc: __tzset_js,+ /** @export */ Lb: _clock_time_get,+ /** @export */ rc: custom_emscripten_dbgn,+ /** @export */ Y: _emscripten_asm_const_int,+ /** @export */ gb: _emscripten_asm_const_ptr,+ /** @export */ Ja: _emscripten_errn,+ /** @export */ qc: _emscripten_get_heap_max,+ /** @export */ y: _emscripten_get_now,+ /** @export */ ia: _emscripten_has_asyncify,+ /** @export */ pc: _emscripten_outn,+ /** @export */ oc: _emscripten_pc_get_function,+ /** @export */ nc: _emscripten_resize_heap,+ /** @export */ fb: _emscripten_stack_snapshot,+ /** @export */ mc: _emscripten_stack_unwind_buffer,+ /** @export */ lc: _emscripten_webgl_create_context,+ /** @export */ kc: _emscripten_webgl_destroy_context,+ /** @export */ jc: _emscripten_webgl_get_context_attributes,+ /** @export */ ha: _emscripten_webgl_get_current_context,+ /** @export */ ic: _emscripten_webgl_make_context_current,+ /** @export */ R: _emscripten_webgpu_get_device,+ /** @export */ hc: _emwgpuBufferDestroy,+ /** @export */ gc: _emwgpuBufferGetMappedRange,+ /** @export */ fc: _emwgpuBufferUnmap,+ /** @export */ x: _emwgpuDelete,+ /** @export */ ec: _emwgpuDeviceCreateBuffer,+ /** @export */ Db: _emwgpuDeviceCreateComputePipelineAsync,+ /** @export */ Cb: _emwgpuDeviceCreateRenderPipelineAsync,+ /** @export */ dc: _emwgpuDeviceCreateShaderModule,+ /** @export */ cc: _emwgpuDeviceDestroy,+ /** @export */ bc: _emwgpuWaitAny,+ /** @export */ Cc: _environ_get,+ /** @export */ Bc: _environ_sizes_get,+ /** @export */ eb: _exit,+ /** @export */ Oa: _fd_close,+ /** @export */ kb: _fd_read,+ /** @export */ Kb: _fd_seek,+ /** @export */ Na: _fd_write,+ /** @export */ b: _glActiveTexture,+ /** @export */ ta: _glAttachShader,+ /** @export */ ac: _glBindAttribLocation,+ /** @export */ c: _glBindBuffer,+ /** @export */ db: _glBindBufferBase,+ /** @export */ t: _glBindFramebuffer,+ /** @export */ a: _glBindTexture,+ /** @export */ m: _glBindVertexArray,+ /** @export */ cb: _glBlendEquation,+ /** @export */ $b: _glBlendFunc,+ /** @export */ j: _glBufferData,+ /** @export */ I: _glClear,+ /** @export */ H: _glClearColor,+ /** @export */ da: _glClientWaitSync,+ /** @export */ ga: _glColorMask,+ /** @export */ bb: _glCompileShader,+ /** @export */ ab: _glCreateProgram,+ /** @export */ $a: _glCreateShader,+ /** @export */ o: _glDeleteBuffers,+ /** @export */ Q: _glDeleteFramebuffers,+ /** @export */ h: _glDeleteProgram,+ /** @export */ sa: _glDeleteShader,+ /** @export */ ra: _glDeleteSync,+ /** @export */ D: _glDeleteTextures,+ /** @export */ A: _glDeleteVertexArrays,+ /** @export */ _a: _glDetachShader,+ /** @export */ G: _glDisable,+ /** @export */ n: _glDisableVertexAttribArray,+ /** @export */ i: _glDrawArrays,+ /** @export */ fa: _glDrawBuffers,+ /** @export */ _b: _glEnable,+ /** @export */ l: _glEnableVertexAttribArray,+ /** @export */ Za: _glFenceSync,+ /** @export */ qa: _glFinish,+ /** @export */ v: _glFlush,+ /** @export */ C: _glFramebufferTexture2D,+ /** @export */ Ya: _glFramebufferTextureLayer,+ /** @export */ s: _glGenBuffers,+ /** @export */ X: _glGenFramebuffers,+ /** @export */ F: _glGenTextures,+ /** @export */ B: _glGenVertexArrays,+ /** @export */ Xa: _glGetAttribLocation,+ /** @export */ ea: _glGetError,+ /** @export */ Zb: _glGetFloatv,+ /** @export */ w: _glGetIntegerv,+ /** @export */ Yb: _glGetProgramiv,+ /** @export */ Xb: _glGetShaderInfoLog,+ /** @export */ Wb: _glGetShaderiv,+ /** @export */ O: _glGetString,+ /** @export */ Vb: _glGetUniformBlockIndex,+ /** @export */ d: _glGetUniformLocation,+ /** @export */ Ub: _glLineWidth,+ /** @export */ Wa: _glLinkProgram,+ /** @export */ pa: _glPixelStorei,+ /** @export */ oa: _glReadPixels,+ /** @export */ Va: _glShaderSource,+ /** @export */ E: _glTexImage2D,+ /** @export */ na: _glTexParameterf,+ /** @export */ Ua: _glTexParameterfv,+ /** @export */ f: _glTexParameteri,+ /** @export */ ma: _glTexStorage2D,+ /** @export */ Tb: _glTexStorage3D,+ /** @export */ W: _glTexSubImage2D,+ /** @export */ Sb: _glTexSubImage3D,+ /** @export */ N: _glUniform1f,+ /** @export */ la: _glUniform1fv,+ /** @export */ e: _glUniform1i,+ /** @export */ V: _glUniform2f,+ /** @export */ Rb: _glUniform2fv,+ /** @export */ Ia: _glUniform3f,+ /** @export */ Ta: _glUniform4f,+ /** @export */ U: _glUniform4fv,+ /** @export */ Qb: _glUniform4iv,+ /** @export */ Pb: _glUniformBlockBinding,+ /** @export */ Ob: _glUniformMatrix2fv,+ /** @export */ Nb: _glUniformMatrix3fv,+ /** @export */ Ha: _glUniformMatrix4fv,+ /** @export */ g: _glUseProgram,+ /** @export */ k: _glVertexAttribPointer,+ /** @export */ T: _glViewport,+ /** @export */ Ga: hardware_concurrency,+ /** @export */ Bb: mediapipe_create_utility_canvas2d,+ /** @export */ Ab: _mediapipe_find_canvas_event_target,+ /** @export */ zb: mediapipe_import_external_texture,+ /** @export */ xb: _mediapipe_webgl_tex_image_drawable,+ /** @export */ Ac: _proc_exit,+ /** @export */ zc: _random_get,+ /** @export */ Fa: _wgpuCommandEncoderBeginComputePass,+ /** @export */ Ea: _wgpuCommandEncoderBeginRenderPass,+ /** @export */ wb: _wgpuCommandEncoderCopyBufferToTexture,+ /** @export */ vb: _wgpuCommandEncoderCopyTextureToBuffer,+ /** @export */ ub: _wgpuCommandEncoderCopyTextureToTexture,+ /** @export */ M: _wgpuCommandEncoderFinish,+ /** @export */ Da: _wgpuComputePassEncoderDispatchWorkgroups,+ /** @export */ Ca: _wgpuComputePassEncoderEnd,+ /** @export */ Ba: _wgpuComputePassEncoderSetBindGroup,+ /** @export */ Aa: _wgpuComputePassEncoderSetPipeline,+ /** @export */ za: _wgpuComputePipelineGetBindGroupLayout,+ /** @export */ ca: _wgpuDeviceCreateBindGroup,+ /** @export */ tb: _wgpuDeviceCreateBindGroupLayout,+ /** @export */ L: _wgpuDeviceCreateCommandEncoder,+ /** @export */ sb: _wgpuDeviceCreateComputePipeline,+ /** @export */ rb: _wgpuDeviceCreatePipelineLayout,+ /** @export */ Sa: _wgpuDeviceCreateRenderPipeline,+ /** @export */ S: _wgpuDeviceCreateSampler,+ /** @export */ ba: _wgpuDeviceCreateTexture,+ /** @export */ K: _wgpuQueueSubmit,+ /** @export */ ka: _wgpuQueueWriteBuffer,+ /** @export */ qb: _wgpuQueueWriteTexture,+ /** @export */ ya: _wgpuRenderPassEncoderDraw,+ /** @export */ xa: _wgpuRenderPassEncoderEnd,+ /** @export */ wa: _wgpuRenderPassEncoderSetBindGroup,+ /** @export */ va: _wgpuRenderPassEncoderSetPipeline,+ /** @export */ Ra: _wgpuRenderPipelineGetBindGroupLayout,+ /** @export */ z: _wgpuTextureCreateView,+ /** @export */ Qa: _wgpuTextureDestroy,+ /** @export */ aa: _wgpuTextureGetFormat+};++// include: postamble.js+// === Auto-generated postamble setup entry stuff ===+function run() {+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ preRun();+ // a preRun added a dependency, run will be called later+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ function doRun() {+ // run may have just been called through dependencies being fulfilled just in this very frame,+ // or while the async setStatus time below was happening+ Module["calledRun"] = true;+ if (ABORT) return;+ initRuntime();+ readyPromiseResolve?.(Module);+ Module["onRuntimeInitialized"]?.();+ postRun();+ }+ if (Module["setStatus"]) {+ Module["setStatus"]("Running...");+ setTimeout(() => {+ setTimeout(() => Module["setStatus"](""), 1);+ doRun();+ }, 1);+ } else {+ doRun();+ }+}++var wasmExports;++// In modularize mode the generated code is within a factory function so we+// can use await here (since it's not top-level-await).+wasmExports = await (createWasm());++run();++// end include: postamble.js+// include: postamble_modularize.js+// In MODULARIZE mode we wrap the generated code in a factory function+// and return either the Module itself, or a promise of the module.+// We assign to the `moduleRtn` global here and configure closure to see+// this as an extern so it won't get minified.+if (runtimeInitialized) {+ moduleRtn = Module;+} else {+ // Set up the promise that indicates the Module is initialized+ moduleRtn = new Promise((resolve, reject) => {+ readyPromiseResolve = resolve;+ readyPromiseReject = reject;+ });+}+++ return moduleRtn;+}++// Export using a UMD style export, or ES6 exports if selected+globalThis.ModuleFactory = ModuleFactory; globalThis.custom_dbg = console.warn.bind(console); export default ModuleFactory;+diff --git a/public/vendor/mediapipe/wasm/vision_wasm_module_internal.wasm b/public/vendor/mediapipe/wasm/vision_wasm_module_internal.wasmnew file mode 100644index 000000000..9c82447f2Binary files /dev/null and b/public/vendor/mediapipe/wasm/vision_wasm_module_internal.wasm differdiff --git a/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js b/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.jsnew file mode 100644index 000000000..3dffe5f4b--- /dev/null+++ b/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js@@ -0,0 +1,8818 @@+// This code implements the `-sMODULARIZE` settings by taking the generated+// JS program code (INNER_JS_CODE) and wrapping it in a factory function.++// Single threaded MINIMAL_RUNTIME programs do not need access to+// document.currentScript, so a simple export declaration is enough.+var ModuleFactory = (() => {+ // When MODULARIZE this JS may be executed later,+ // after document.currentScript is gone, so we save it.+ // In EXPORT_ES6 mode we can just use 'import.meta.url'.+ var _scriptName = globalThis.document?.currentScript?.src;+ return async function(moduleArg = {}) {+ var moduleRtn;++// include: shell.js+// include: minimum_runtime_check.js+// end include: minimum_runtime_check.js+// The Module object: Our interface to the outside world. We import+// and export values on it. There are various ways Module can be used:+// 1. Not defined. We create it here+// 2. A function parameter, function(moduleArg) => Promise<Module>+// 3. pre-run appended it, var Module = {}; ..generated code..+// 4. External script tag defines var Module.+// We need to check if Module already exists (e.g. case 3 above).+// Substitution will be replaced with actual code on later stage of the build,+// this way Closure Compiler will not mangle it (e.g. case 4. above).+// Note that if you want to run closure, and also to use Module+// after the generated code, you will need to define var Module = {};+// before the code. Then that object will be used in the code, and you+// can continue to use Module afterwards as well.+var Module = moduleArg;++// Determine the runtime environment we are in. You can customize this by+// setting the ENVIRONMENT setting at compile time (see settings.js).+// Attempt to auto-detect the environment+var ENVIRONMENT_IS_WEB = !!globalThis.window;++var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope;++// N.b. Electron.js environment is simultaneously a NODE-environment, but+// also a web environment.+var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer";++// --pre-jses are emitted after the Module integration code, so that they can+// refer to Module (if they choose; they can also define Module)+var arguments_ = [];++var thisProgram = "./this.program";++var quit_ = (status, toThrow) => {+ throw toThrow;+};++if (typeof __filename != "undefined") {+ // Node+ _scriptName = __filename;+} else if (ENVIRONMENT_IS_WORKER) {+ _scriptName = self.location.href;+}++// `/` should be present at the end if `scriptDirectory` is not empty+var scriptDirectory = "";++function locateFile(path) {+ if (Module["locateFile"]) {+ return Module["locateFile"](path, scriptDirectory);+ }+ return scriptDirectory + path;+}++// Hooks that are implemented differently in different runtime environments.+var readAsync, readBinary;++if (ENVIRONMENT_IS_NODE) {+ // These modules will usually be used on Node.js. Load them eagerly to avoid+ // the complexity of lazy-loading.+ var fs = require("node:fs");+ scriptDirectory = __dirname + "/";+ // include: node_shell_read.js+ readBinary = filename => {+ // We need to re-wrap `file://` strings to URLs.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename);+ return ret;+ };+ readAsync = async (filename, binary = true) => {+ // See the comment in the `readBinary` function.+ filename = isFileURI(filename) ? new URL(filename) : filename;+ var ret = fs.readFileSync(filename, binary ? undefined : "utf8");+ return ret;+ };+ // end include: node_shell_read.js+ if (process.argv.length > 1) {+ thisProgram = process.argv[1].replace(/\\/g, "/");+ }+ arguments_ = process.argv.slice(2);+ quit_ = (status, toThrow) => {+ process.exitCode = status;+ throw toThrow;+ };+} else // Note that this includes Node.js workers when relevant (pthreads is enabled).+// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and+// ENVIRONMENT_IS_NODE.+if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {+ try {+ scriptDirectory = new URL(".", _scriptName).href;+ } catch {}+ {+ // include: web_or_worker_shell_read.js+ if (ENVIRONMENT_IS_WORKER) {+ readBinary = url => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ xhr.responseType = "arraybuffer";+ xhr.send(null);+ return new Uint8Array(/** @type{!ArrayBuffer} */ (xhr.response));+ };+ }+ readAsync = async url => {+ // Fetch has some additional restrictions over XHR, like it can't be used on a file:// url.+ // See https://github.com/github/fetch/pull/92#issuecomment-140665932+ // Cordova or Electron apps are typically loaded from a file:// url.+ // So use XHR on webview if URL is a file URL.+ if (isFileURI(url)) {+ return new Promise((resolve, reject) => {+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, true);+ xhr.responseType = "arraybuffer";+ xhr.onload = () => {+ if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) {+ // file URLs can return 0+ resolve(xhr.response);+ return;+ }+ reject(xhr.status);+ };+ xhr.onerror = reject;+ xhr.send(null);+ });+ }+ var response = await fetch(url, {+ credentials: "same-origin"+ });+ if (response.ok) {+ return response.arrayBuffer();+ }+ throw new Error(response.status + " : " + response.url);+ };+ }+} else {}++var out = console.log.bind(console);++var err = console.error.bind(console);++// end include: shell.js+// include: preamble.js+// === Preamble library stuff ===+// Documentation for the public APIs defined in this file must be updated in:+// site/source/docs/api_reference/preamble.js.rst+// A prebuilt local version of the documentation is available at:+// site/build/text/docs/api_reference/preamble.js.txt+// You can also build docs locally as HTML or other formats in site/+// An online HTML version (which may be of a different version of Emscripten)+// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html+var wasmBinary;++// Wasm globals+//========================================+// Runtime essentials+//========================================+// whether we are quitting the application. no code should run after this.+// set in exit() and abort()+var ABORT = false;++// set by exit() and abort(). Passed to 'onExit' handler.+// NOTE: This is also used as the process return code in shell environments+// but only when noExitRuntime is false.+var EXITSTATUS;++// In STRICT mode, we only define assert() when ASSERTIONS is set. i.e. we+// don't define it at all in release modes. This matches the behaviour of+// MINIMAL_RUNTIME.+// TODO(sbc): Make this the default even without STRICT enabled.+/** @type {function(*, string=)} */ function assert(condition, text) {+ if (!condition) {+ // This build was created without ASSERTIONS defined. `assert()` should not+ // ever be called in this configuration but in case there are callers in+ // the wild leave this simple abort() implementation here for now.+ abort(text);+ }+}++/**+ * Indicates whether filename is delivered via file protocol (as opposed to http/https)+ * @noinline+ */ var isFileURI = filename => filename.startsWith("file://");++// include: runtime_common.js+// include: runtime_stack_check.js+// end include: runtime_stack_check.js+// include: runtime_exceptions.js+// Base Emscripten EH error class+class EmscriptenEH {}++class EmscriptenSjLj extends EmscriptenEH {}++// end include: runtime_exceptions.js+// include: runtime_debug.js+// end include: runtime_debug.js+var readyPromiseResolve, readyPromiseReject;++// Memory management+var runtimeInitialized = false;++function updateMemoryViews() {+ var b = wasmMemory.buffer;+ HEAP8 = new Int8Array(b);+ HEAP16 = new Int16Array(b);+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);+ HEAPU16 = new Uint16Array(b);+ HEAP32 = new Int32Array(b);+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);+ Module["HEAPF32"] = HEAPF32 = new Float32Array(b);+ Module["HEAPF64"] = HEAPF64 = new Float64Array(b);+}++// include: memoryprofiler.js+// end include: memoryprofiler.js+// end include: runtime_common.js+function preRun() {+ if (Module["preRun"]) {+ if (typeof Module["preRun"] == "function") Module["preRun"] = [ Module["preRun"] ];+ while (Module["preRun"].length) {+ addOnPreRun(Module["preRun"].shift());+ }+ }+ // Begin ATPRERUNS hooks+ callRuntimeCallbacks(onPreRuns);+}++function initRuntime() {+ runtimeInitialized = true;+ // Begin ATINITS hooks+ if (!Module["noFSInit"] && !FS.initialized) FS.init();+ TTY.init();+ // End ATINITS hooks+ wasmExports["id"]();+ // Begin ATPOSTCTORS hooks+ FS.ignorePermissions = false;+}++function postRun() {+ // PThreads reuse the runtime from the main thread.+ if (Module["postRun"]) {+ if (typeof Module["postRun"] == "function") Module["postRun"] = [ Module["postRun"] ];+ while (Module["postRun"].length) {+ addOnPostRun(Module["postRun"].shift());+ }+ }+ // Begin ATPOSTRUNS hooks+ callRuntimeCallbacks(onPostRuns);+}++/**+ * @param {string|number=} what+ */ function abort(what) {+ Module["onAbort"]?.(what);+ what = `Aborted(${what})`;+ // TODO(sbc): Should we remove printing and leave it up to whoever+ // catches the exception?+ err(what);+ ABORT = true;+ what += ". Build with -sASSERTIONS for more info.";+ // Use a wasm runtime error, because a JS error might be seen as a foreign+ // exception, which means we'd run destructors on it. We need the error to+ // simply make the program stop.+ // FIXME This approach does not work in Wasm EH because it currently does not assume+ // all RuntimeErrors are from traps; it decides whether a RuntimeError is from+ // a trap or not based on a hidden field within the object. So at the moment+ // we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that+ // allows this in the wasm spec.+ // Suppress closure compiler warning here. Closure compiler's builtin extern+ // definition for WebAssembly.RuntimeError claims it takes no arguments even+ // though it can.+ // TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.+ /** @suppress {checkTypes} */ var e = new WebAssembly.RuntimeError(what);+ readyPromiseReject?.(e);+ // Throw the error whether or not MODULARIZE is set because abort is used+ // in code paths apart from instantiation where an exception is expected+ // to be thrown when abort is called.+ throw e;+}++var wasmBinaryFile;++function findWasmBinary() {+ return locateFile("vision_wasm_nosimd_internal.wasm");+}++function getBinarySync(file) {+ if (file == wasmBinaryFile && wasmBinary) {+ return new Uint8Array(wasmBinary);+ }+ if (readBinary) {+ return readBinary(file);+ }+ // Throwing a plain string here, even though it not normally advisable since+ // this gets turning into an `abort` in instantiateArrayBuffer.+ throw "both async and sync fetching of the wasm failed";+}++async function getWasmBinary(binaryFile) {+ // If we don't have the binary yet, load it asynchronously using readAsync.+ if (!wasmBinary) {+ // Fetch the binary using readAsync+ try {+ var response = await readAsync(binaryFile);+ return new Uint8Array(response);+ } catch {}+ }+ // Otherwise, getBinarySync should be able to get it synchronously+ return getBinarySync(binaryFile);+}++async function instantiateArrayBuffer(binaryFile, imports) {+ try {+ var binary = await getWasmBinary(binaryFile);+ var instance = await WebAssembly.instantiate(binary, imports);+ return instance;+ } catch (reason) {+ err(`failed to asynchronously prepare wasm: ${reason}`);+ abort(reason);+ }+}++async function instantiateAsync(binary, binaryFile, imports) {+ if (!binary && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {+ try {+ var response = fetch(binaryFile, {+ credentials: "same-origin"+ });+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);+ return instantiationResult;+ } catch (reason) {+ // We expect the most common failure cause to be a bad MIME type for the binary,+ // in which case falling back to ArrayBuffer instantiation should work.+ err(`wasm streaming compile failed: ${reason}`);+ err("falling back to ArrayBuffer instantiation");+ }+ }+ return instantiateArrayBuffer(binaryFile, imports);+}++function getWasmImports() {+ // prepare imports+ var imports = {+ "a": wasmImports+ };+ return imports;+}++// Create the wasm instance.+// Receives the wasm imports, returns the exports.+async function createWasm() {+ // Load the wasm module and create an instance of using native support in the JS engine.+ // handle a generated wasm instance, receiving its exports and+ // performing other necessary setup+ /** @param {WebAssembly.Module=} module*/ function receiveInstance(instance, module) {+ wasmExports = instance.exports;+ assignWasmExports(wasmExports);+ updateMemoryViews();+ return wasmExports;+ }+ // Prefer streaming instantiation if available.+ function receiveInstantiationResult(result) {+ // 'result' is a ResultObject object which has both the module and instance.+ // receiveInstance() will swap in the exports (to Module.asm) so they can be called+ // TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.+ // When the regression is fixed, can restore the above PTHREADS-enabled path.+ return receiveInstance(result["instance"]);+ }+ var info = getWasmImports();+ // User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback+ // to manually instantiate the Wasm module themselves. This allows pages to+ // run the instantiation parallel to any other async startup actions they are+ // performing.+ // Also pthreads and wasm workers initialize the wasm instance through this+ // path.+ if (Module["instantiateWasm"]) {+ return new Promise((resolve, reject) => {+ Module["instantiateWasm"](info, (inst, mod) => {+ resolve(receiveInstance(inst, mod));+ });+ });+ }+ wasmBinaryFile ??= findWasmBinary();+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);+ var exports = receiveInstantiationResult(result);+ return exports;+}++// Globals used by JS i64 conversions (see makeSetValue)+var tempDouble;++var tempI64;++// end include: preamble.js+// Begin JS library code+var handleException = e => {+ // Certain exception types we do not treat as errors since they are used for+ // internal control flow.+ // 1. ExitStatus, which is thrown by exit()+ // 2. "unwind", which is thrown by emscripten_unwind_to_js_event_loop() and others+ // that wish to return to JS event loop.+ if (e instanceof ExitStatus || e == "unwind") {+ return EXITSTATUS;+ }+ quit_(1, e);+};++class ExitStatus {+ name="ExitStatus";+ constructor(status) {+ this.message = `Program terminated with exit(${status})`;+ this.status = status;+ }+}++var runtimeKeepaliveCounter = 0;++var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;++var _proc_exit = code => {+ EXITSTATUS = code;+ if (!keepRuntimeAlive()) {+ Module["onExit"]?.(code);+ ABORT = true;+ }+ quit_(code, new ExitStatus(code));+};++/** @param {boolean|number=} implicit */ var exitJS = (status, implicit) => {+ EXITSTATUS = status;+ _proc_exit(status);+};++var _exit = exitJS;++var maybeExit = () => {+ if (!keepRuntimeAlive()) {+ try {+ _exit(EXITSTATUS);+ } catch (e) {+ handleException(e);+ }+ }+};++var callUserCallback = func => {+ if (ABORT) {+ return;+ }+ try {+ return func();+ } catch (e) {+ handleException(e);+ } finally {+ maybeExit();+ }+};++function getFullscreenElement() {+ return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.webkitCurrentFullScreenElement || document.msFullscreenElement;+}++/** @param {number=} timeout */ var safeSetTimeout = (func, timeout) => setTimeout(() => {+ callUserCallback(func);+}, timeout);++var warnOnce = text => {+ warnOnce.shown ||= {};+ if (!warnOnce.shown[text]) {+ warnOnce.shown[text] = 1;+ if (ENVIRONMENT_IS_NODE) text = "warning: " + text;+ err(text);+ }+};++var preloadPlugins = [];++var Browser = {+ useWebGL: false,+ isFullscreen: false,+ pointerLock: false,+ moduleContextCreatedCallbacks: [],+ workers: [],+ preloadedImages: {},+ preloadedAudios: {},+ getCanvas: () => Module["canvas"],+ init() {+ if (Browser.initted) return;+ Browser.initted = true;+ // Support for plugins that can process preloaded files. You can add more of these to+ // your app by creating and appending to preloadPlugins.+ // Each plugin is asked if it can handle a file based on the file's name. If it can,+ // it is given the file's raw data. When it is done, it calls a callback with the file's+ // (possibly modified) data. For example, a plugin might decompress a file, or it+ // might create some side data structure for use later (like an Image element, etc.).+ var imagePlugin = {};+ imagePlugin["canHandle"] = name => !Module["noImageDecoding"] && /\.(jpg|jpeg|png|bmp|webp)$/i.test(name);+ imagePlugin["handle"] = async (byteArray, name) => {+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ if (b.size !== byteArray.length) {+ // Safari bug #118630+ // Safari's Blob can only take an ArrayBuffer+ b = new Blob([ (new Uint8Array(byteArray)).buffer ], {+ type: Browser.getMimetype(name)+ });+ }+ var url = URL.createObjectURL(b);+ return new Promise((resolve, reject) => {+ var img = new Image;+ img.onload = () => {+ var canvas = /** @type {!HTMLCanvasElement} */ (document.createElement("canvas"));+ canvas.width = img.width;+ canvas.height = img.height;+ var ctx = canvas.getContext("2d");+ ctx.drawImage(img, 0, 0);+ Browser.preloadedImages[name] = canvas;+ URL.revokeObjectURL(url);+ resolve(byteArray);+ };+ img.onerror = event => {+ err(`Image ${url} could not be decoded`);+ reject();+ };+ img.src = url;+ });+ };+ preloadPlugins.push(imagePlugin);+ var audioPlugin = {};+ audioPlugin["canHandle"] = name => !Module["noAudioDecoding"] && name.slice(-4) in {+ ".ogg": 1,+ ".wav": 1,+ ".mp3": 1+ };+ audioPlugin["handle"] = async (byteArray, name) => new Promise((resolve, reject) => {+ var done = false;+ function finish(audio) {+ if (done) return;+ done = true;+ Browser.preloadedAudios[name] = audio;+ resolve(byteArray);+ }+ var b = new Blob([ byteArray ], {+ type: Browser.getMimetype(name)+ });+ var url = URL.createObjectURL(b);+ // XXX we never revoke this!+ var audio = new Audio;+ audio.addEventListener("canplaythrough", () => finish(audio), false);+ // use addEventListener due to chromium bug 124926+ audio.onerror = event => {+ if (done) return;+ err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);+ function encode64(data) {+ var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ var PAD = "=";+ var ret = "";+ var leftchar = 0;+ var leftbits = 0;+ for (var i = 0; i < data.length; i++) {+ leftchar = (leftchar << 8) | data[i];+ leftbits += 8;+ while (leftbits >= 6) {+ var curr = (leftchar >> (leftbits - 6)) & 63;+ leftbits -= 6;+ ret += BASE[curr];+ }+ }+ if (leftbits == 2) {+ ret += BASE[(leftchar & 3) << 4];+ ret += PAD + PAD;+ } else if (leftbits == 4) {+ ret += BASE[(leftchar & 15) << 2];+ ret += PAD;+ }+ return ret;+ }+ audio.src = "data:audio/x-" + name.slice(-3) + ";base64," + encode64(byteArray);+ finish(audio);+ };+ audio.src = url;+ // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror+ safeSetTimeout(() => {+ finish(audio);+ }, 1e4);+ });+ preloadPlugins.push(audioPlugin);+ // Canvas event setup+ function pointerLockChange() {+ var canvas = Browser.getCanvas();+ Browser.pointerLock = document.pointerLockElement === canvas;+ }+ var canvas = Browser.getCanvas();+ if (canvas) {+ // forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module+ // Module['forcedAspectRatio'] = 4 / 3;+ document.addEventListener("pointerlockchange", pointerLockChange, false);+ if (Module["elementPointerLock"]) {+ canvas.addEventListener("click", ev => {+ if (!Browser.pointerLock && Browser.getCanvas().requestPointerLock) {+ Browser.getCanvas().requestPointerLock();+ ev.preventDefault();+ }+ }, false);+ }+ }+ },+ createContext(/** @type {HTMLCanvasElement} */ canvas, useWebGL, setInModule, webGLContextAttributes) {+ if (useWebGL && Module["ctx"] && canvas == Browser.getCanvas()) return Module["ctx"];+ // no need to recreate GL context if it's already been created for this canvas.+ var ctx;+ var contextHandle;+ if (useWebGL) {+ // For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.+ var contextAttributes = {+ antialias: false,+ alpha: false,+ majorVersion: (typeof WebGL2RenderingContext != "undefined") ? 2 : 1+ };+ if (webGLContextAttributes) {+ for (var attribute in webGLContextAttributes) {+ contextAttributes[attribute] = webGLContextAttributes[attribute];+ }+ }+ // This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not+ // actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function+ // Browser.createContext() should not even be emitted.+ if (typeof GL != "undefined") {+ contextHandle = GL.createContext(canvas, contextAttributes);+ if (contextHandle) {+ ctx = GL.getContext(contextHandle).GLctx;+ }+ }+ } else {+ ctx = canvas.getContext("2d");+ }+ if (!ctx) return null;+ if (setInModule) {+ Module["ctx"] = ctx;+ if (useWebGL) GL.makeContextCurrent(contextHandle);+ Browser.useWebGL = useWebGL;+ Browser.moduleContextCreatedCallbacks.forEach(callback => callback());+ Browser.init();+ }+ return ctx;+ },+ fullscreenHandlersInstalled: false,+ lockPointer: undefined,+ resizeCanvas: undefined,+ requestFullscreen(lockPointer, resizeCanvas) {+ Browser.lockPointer = lockPointer;+ Browser.resizeCanvas = resizeCanvas;+ if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true;+ if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false;+ var canvas = Browser.getCanvas();+ function fullscreenChange() {+ Browser.isFullscreen = false;+ var canvasContainer = canvas.parentNode;+ if (getFullscreenElement() === canvasContainer) {+ canvas.exitFullscreen = Browser.exitFullscreen;+ if (Browser.lockPointer) canvas.requestPointerLock();+ Browser.isFullscreen = true;+ if (Browser.resizeCanvas) {+ Browser.setFullscreenCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ } else {+ // remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen+ canvasContainer.parentNode.insertBefore(canvas, canvasContainer);+ canvasContainer.parentNode.removeChild(canvasContainer);+ if (Browser.resizeCanvas) {+ Browser.setWindowedCanvasSize();+ } else {+ Browser.updateCanvasDimensions(canvas);+ }+ }+ Module["onFullScreen"]?.(Browser.isFullscreen);+ Module["onFullscreen"]?.(Browser.isFullscreen);+ }+ if (!Browser.fullscreenHandlersInstalled) {+ Browser.fullscreenHandlersInstalled = true;+ document.addEventListener("fullscreenchange", fullscreenChange, false);+ document.addEventListener("mozfullscreenchange", fullscreenChange, false);+ document.addEventListener("webkitfullscreenchange", fullscreenChange, false);+ document.addEventListener("MSFullscreenChange", fullscreenChange, false);+ }+ // create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root+ var canvasContainer = document.createElement("div");+ canvas.parentNode.insertBefore(canvasContainer, canvas);+ canvasContainer.appendChild(canvas);+ // use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)+ canvasContainer.requestFullscreen = canvasContainer["requestFullscreen"] || canvasContainer["mozRequestFullScreen"] || canvasContainer["msRequestFullscreen"] || (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null) || (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null);+ canvasContainer.requestFullscreen();+ },+ exitFullscreen() {+ // This is workaround for chrome. Trying to exit from fullscreen+ // not in fullscreen state will cause "TypeError: Document not active"+ // in chrome. See https://github.com/emscripten-core/emscripten/pull/8236+ if (!Browser.isFullscreen) {+ return false;+ }+ var CFS = document["exitFullscreen"] || document["cancelFullScreen"] || document["mozCancelFullScreen"] || document["msExitFullscreen"] || document["webkitCancelFullScreen"] || (() => {});+ CFS.apply(document, []);+ return true;+ },+ safeSetTimeout(func, timeout) {+ // Legacy function, this is used by the SDL2 port so we need to keep it+ // around at least until that is updated.+ // See https://github.com/libsdl-org/SDL/pull/6304+ return safeSetTimeout(func, timeout);+ },+ getMimetype(name) {+ return {+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "png": "image/png",+ "bmp": "image/bmp",+ "ogg": "audio/ogg",+ "wav": "audio/wav",+ "mp3": "audio/mpeg"+ }[name.slice(name.lastIndexOf(".") + 1)];+ },+ getUserMedia(func) {+ window.getUserMedia ||= navigator["getUserMedia"] || navigator["mozGetUserMedia"];+ window.getUserMedia(func);+ },+ getMovementX(event) {+ return event["movementX"] || event["mozMovementX"] || event["webkitMovementX"] || 0;+ },+ getMovementY(event) {+ return event["movementY"] || event["mozMovementY"] || event["webkitMovementY"] || 0;+ },+ getMouseWheelDelta(event) {+ var delta = 0;+ switch (event.type) {+ case "DOMMouseScroll":+ // 3 lines make up a step+ delta = event.detail / 3;+ break;++ case "mousewheel":+ // 120 units make up a step+ delta = event.wheelDelta / 120;+ break;++ case "wheel":+ delta = event.deltaY;+ switch (event.deltaMode) {+ case 0:+ // DOM_DELTA_PIXEL: 100 pixels make up a step+ delta /= 100;+ break;++ case 1:+ // DOM_DELTA_LINE: 3 lines make up a step+ delta /= 3;+ break;++ case 2:+ // DOM_DELTA_PAGE: A page makes up 80 steps+ delta *= 80;+ break;++ default:+ abort("unrecognized mouse wheel delta mode: " + event.deltaMode);+ }+ break;++ default:+ abort("unrecognized mouse wheel event: " + event.type);+ }+ return delta;+ },+ mouseX: 0,+ mouseY: 0,+ mouseMovementX: 0,+ mouseMovementY: 0,+ touches: {},+ lastTouches: {},+ calculateMouseCoords(pageX, pageY) {+ // Calculate the movement based on the changes+ // in the coordinates.+ var canvas = Browser.getCanvas();+ var rect = canvas.getBoundingClientRect();+ // Neither .scrollX or .pageXOffset are defined in a spec, but+ // we prefer .scrollX because it is currently in a spec draft.+ // (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)+ var scrollX = ((typeof window.scrollX != "undefined") ? window.scrollX : window.pageXOffset);+ var scrollY = ((typeof window.scrollY != "undefined") ? window.scrollY : window.pageYOffset);+ var adjustedX = pageX - (scrollX + rect.left);+ var adjustedY = pageY - (scrollY + rect.top);+ // the canvas might be CSS-scaled compared to its backbuffer;+ // SDL-using content will want mouse coordinates in terms+ // of backbuffer units.+ adjustedX = adjustedX * (canvas.width / rect.width);+ adjustedY = adjustedY * (canvas.height / rect.height);+ return {+ x: adjustedX,+ y: adjustedY+ };+ },+ setMouseCoords(pageX, pageY) {+ const {x, y} = Browser.calculateMouseCoords(pageX, pageY);+ Browser.mouseMovementX = x - Browser.mouseX;+ Browser.mouseMovementY = y - Browser.mouseY;+ Browser.mouseX = x;+ Browser.mouseY = y;+ },+ calculateMouseEvent(event) {+ // event should be mousemove, mousedown or mouseup+ if (Browser.pointerLock) {+ // When the pointer is locked, calculate the coordinates+ // based on the movement of the mouse.+ // Workaround for Firefox bug 764498+ if (event.type != "mousemove" && ("mozMovementX" in event)) {+ Browser.mouseMovementX = Browser.mouseMovementY = 0;+ } else {+ Browser.mouseMovementX = Browser.getMovementX(event);+ Browser.mouseMovementY = Browser.getMovementY(event);+ }+ // add the mouse delta to the current absolute mouse position+ Browser.mouseX += Browser.mouseMovementX;+ Browser.mouseY += Browser.mouseMovementY;+ } else {+ if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") {+ var touch = event.touch;+ if (touch === undefined) {+ return;+ }+ var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY);+ if (event.type === "touchstart") {+ Browser.lastTouches[touch.identifier] = coords;+ Browser.touches[touch.identifier] = coords;+ } else if (event.type === "touchend" || event.type === "touchmove") {+ var last = Browser.touches[touch.identifier];+ last ||= coords;+ Browser.lastTouches[touch.identifier] = last;+ Browser.touches[touch.identifier] = coords;+ }+ return;+ }+ Browser.setMouseCoords(event.pageX, event.pageY);+ }+ },+ resizeListeners: [],+ updateResizeListeners() {+ var canvas = Browser.getCanvas();+ Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height));+ },+ setCanvasSize(width, height, noUpdates) {+ var canvas = Browser.getCanvas();+ Browser.updateCanvasDimensions(canvas, width, height);+ if (!noUpdates) Browser.updateResizeListeners();+ },+ windowedWidth: 0,+ windowedHeight: 0,+ setFullscreenCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags | 8388608;+ // set SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ setWindowedCanvasSize() {+ // check if SDL is available+ if (typeof SDL != "undefined") {+ var flags = HEAPU32[((SDL.screen) >> 2)];+ flags = flags & ~8388608;+ // clear SDL_FULLSCREEN flag+ HEAP32[((SDL.screen) >> 2)] = flags;+ }+ Browser.updateCanvasDimensions(Browser.getCanvas());+ Browser.updateResizeListeners();+ },+ updateCanvasDimensions(canvas, wNative, hNative) {+ if (wNative && hNative) {+ canvas.widthNative = wNative;+ canvas.heightNative = hNative;+ } else {+ wNative = canvas.widthNative;+ hNative = canvas.heightNative;+ }+ var w = wNative;+ var h = hNative;+ if (Module["forcedAspectRatio"] > 0) {+ if (w / h < Module["forcedAspectRatio"]) {+ w = Math.round(h * Module["forcedAspectRatio"]);+ } else {+ h = Math.round(w / Module["forcedAspectRatio"]);+ }+ }+ if ((getFullscreenElement() === canvas.parentNode) && (typeof screen != "undefined")) {+ var factor = Math.min(screen.width / w, screen.height / h);+ w = Math.round(w * factor);+ h = Math.round(h * factor);+ }+ if (Browser.resizeCanvas) {+ if (canvas.width != w) canvas.width = w;+ if (canvas.height != h) canvas.height = h;+ if (typeof canvas.style != "undefined") {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ } else {+ if (canvas.width != wNative) canvas.width = wNative;+ if (canvas.height != hNative) canvas.height = hNative;+ if (typeof canvas.style != "undefined") {+ if (w != wNative || h != hNative) {+ canvas.style.setProperty("width", w + "px", "important");+ canvas.style.setProperty("height", h + "px", "important");+ } else {+ canvas.style.removeProperty("width");+ canvas.style.removeProperty("height");+ }+ }+ }+ }+};++/** @type {!Int16Array} */ var HEAP16;++/** @type {!Int32Array} */ var HEAP32;++/** @type {!Int8Array} */ var HEAP8;++/** @type {!Float32Array} */ var HEAPF32;++/** @type {!Float64Array} */ var HEAPF64;++/** @type {!Uint16Array} */ var HEAPU16;++/** @type {!Uint32Array} */ var HEAPU32;++/** @type {!Uint8Array} */ var HEAPU8;++var callRuntimeCallbacks = callbacks => {+ while (callbacks.length > 0) {+ // Pass the module as the first argument.+ callbacks.shift()(Module);+ }+};++var onPostRuns = [];++var addOnPostRun = cb => onPostRuns.push(cb);++var onPreRuns = [];++var addOnPreRun = cb => onPreRuns.push(cb);++var noExitRuntime = true;++var stackRestore = val => __emscripten_stack_restore(val);++var stackSave = () => _emscripten_stack_get_current();++class ExceptionInfo {+ // excPtr - Thrown object pointer to wrap. Metadata pointer is calculated from it.+ constructor(excPtr) {+ this.excPtr = excPtr;+ this.ptr = excPtr - 24;+ }+ set_type(type) {+ HEAPU32[(((this.ptr) + (4)) >> 2)] = type;+ }+ get_type() {+ return HEAPU32[(((this.ptr) + (4)) >> 2)];+ }+ set_destructor(destructor) {+ HEAPU32[(((this.ptr) + (8)) >> 2)] = destructor;+ }+ get_destructor() {+ return HEAPU32[(((this.ptr) + (8)) >> 2)];+ }+ set_caught(caught) {+ caught = caught ? 1 : 0;+ HEAP8[(this.ptr) + (12)] = caught;+ }+ get_caught() {+ return HEAP8[(this.ptr) + (12)] != 0;+ }+ set_rethrown(rethrown) {+ rethrown = rethrown ? 1 : 0;+ HEAP8[(this.ptr) + (13)] = rethrown;+ }+ get_rethrown() {+ return HEAP8[(this.ptr) + (13)] != 0;+ }+ // Initialize native structure fields. Should be called once after allocated.+ init(type, destructor) {+ this.set_adjusted_ptr(0);+ this.set_type(type);+ this.set_destructor(destructor);+ }+ set_adjusted_ptr(adjustedPtr) {+ HEAPU32[(((this.ptr) + (16)) >> 2)] = adjustedPtr;+ }+ get_adjusted_ptr() {+ return HEAPU32[(((this.ptr) + (16)) >> 2)];+ }+}++var uncaughtExceptionCount = 0;++var ___cxa_throw = (ptr, type, destructor) => {+ var info = new ExceptionInfo(ptr);+ // Initialize ExceptionInfo content after it was allocated in __cxa_allocate_exception.+ info.init(type, destructor);+ uncaughtExceptionCount++;+ abort();+};++var PATH = {+ isAbs: path => path.charAt(0) === "/",+ splitPath: filename => {+ var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;+ return splitPathRe.exec(filename).slice(1);+ },+ normalizeArray: (parts, allowAboveRoot) => {+ // if the path tries to go above the root, `up` ends up > 0+ var up = 0;+ for (var i = parts.length - 1; i >= 0; i--) {+ var last = parts[i];+ if (last === ".") {+ parts.splice(i, 1);+ } else if (last === "..") {+ parts.splice(i, 1);+ up++;+ } else if (up) {+ parts.splice(i, 1);+ up--;+ }+ }+ // if the path is allowed to go above the root, restore leading ..s+ if (allowAboveRoot) {+ for (;up; up--) {+ parts.unshift("..");+ }+ }+ return parts;+ },+ normalize: path => {+ var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/";+ // Normalize the path+ path = PATH.normalizeArray(path.split("/").filter(p => !!p), !isAbsolute).join("/");+ if (!path && !isAbsolute) {+ path = ".";+ }+ if (path && trailingSlash) {+ path += "/";+ }+ return (isAbsolute ? "/" : "") + path;+ },+ dirname: path => {+ var result = PATH.splitPath(path), root = result[0], dir = result[1];+ if (!root && !dir) {+ // No dirname whatsoever+ return ".";+ }+ if (dir) {+ // It has a dirname, strip trailing slash+ dir = dir.slice(0, -1);+ }+ return root + dir;+ },+ basename: path => path && path.match(/([^\/]+|\/)\/*$/)[1],+ join: (...paths) => PATH.normalize(paths.join("/")),+ join2: (l, r) => PATH.normalize(l + "/" + r)+};++var initRandomFill = () => {+ // This block is not needed on v19+ since crypto.getRandomValues is builtin+ if (ENVIRONMENT_IS_NODE) {+ var nodeCrypto = require("node:crypto");+ return view => nodeCrypto.randomFillSync(view);+ }+ return view => (crypto.getRandomValues(view), 0);+};++var randomFill = view => (randomFill = initRandomFill())(view);++var PATH_FS = {+ resolve: (...args) => {+ var resolvedPath = "", resolvedAbsolute = false;+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {+ var path = (i >= 0) ? args[i] : FS.cwd();+ // Skip empty and invalid entries+ if (typeof path != "string") {+ throw new TypeError("Arguments to path.resolve must be strings");+ } else if (!path) {+ return "";+ }+ resolvedPath = path + "/" + resolvedPath;+ resolvedAbsolute = PATH.isAbs(path);+ }+ // At this point the path should be resolved to a full absolute path, but+ // handle relative paths to be safe (might happen when process.cwd() fails)+ resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(p => !!p), !resolvedAbsolute).join("/");+ return ((resolvedAbsolute ? "/" : "") + resolvedPath) || ".";+ },+ relative: (from, to) => {+ from = PATH_FS.resolve(from).slice(1);+ to = PATH_FS.resolve(to).slice(1);+ function trim(arr) {+ var start = 0;+ for (;start < arr.length; start++) {+ if (arr[start] !== "") break;+ }+ var end = arr.length - 1;+ for (;end >= 0; end--) {+ if (arr[end] !== "") break;+ }+ if (start > end) return [];+ return arr.slice(start, end - start + 1);+ }+ var fromParts = trim(from.split("/"));+ var toParts = trim(to.split("/"));+ var length = Math.min(fromParts.length, toParts.length);+ var samePartsLength = length;+ for (var i = 0; i < length; i++) {+ if (fromParts[i] !== toParts[i]) {+ samePartsLength = i;+ break;+ }+ }+ var outputParts = [];+ for (var i = samePartsLength; i < fromParts.length; i++) {+ outputParts.push("..");+ }+ outputParts = outputParts.concat(toParts.slice(samePartsLength));+ return outputParts.join("/");+ }+};++var UTF8Decoder = new TextDecoder;++var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {+ var maxIdx = idx + maxBytesToRead;+ if (ignoreNul) return maxIdx;+ // TextDecoder needs to know the byte length in advance, it doesn't stop on+ // null terminator by itself.+ // As a tiny code save trick, compare idx against maxIdx using a negation,+ // so that maxBytesToRead=undefined/NaN means Infinity.+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;+ return idx;+};++/**+ * Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given+ * array that contains uint8 values, returns a copy of that string as a+ * Javascript String object.+ * heapOrArray is either a regular array, or a JavaScript typed array view.+ * @param {number=} idx+ * @param {number=} maxBytesToRead+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(heapOrArray.buffer ? heapOrArray.subarray(idx, endPtr) : new Uint8Array(heapOrArray.slice(idx, endPtr)));+};++var FS_stdin_getChar_buffer = [];++var lengthBytesUTF8 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code+ // unit, not a Unicode code point of the character! So decode+ // UTF16->UTF32->UTF8.+ // See http://unicode.org/faq/utf_bom.html#utf16-3+ var c = str.charCodeAt(i);+ // possibly a lead surrogate+ if (c <= 127) {+ len++;+ } else if (c <= 2047) {+ len += 2;+ } else if (c >= 55296 && c <= 57343) {+ len += 4;+ ++i;+ } else {+ len += 3;+ }+ }+ return len;+};++var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {+ // Parameter maxBytesToWrite is not optional. Negative values, 0, null,+ // undefined and false each don't write out any bytes.+ if (!(maxBytesToWrite > 0)) return 0;+ var startIdx = outIdx;+ var endIdx = outIdx + maxBytesToWrite - 1;+ // -1 for string null terminator.+ for (var i = 0; i < str.length; ++i) {+ // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description+ // and https://www.ietf.org/rfc/rfc2279.txt+ // and https://tools.ietf.org/html/rfc3629+ var u = str.codePointAt(i);+ if (u <= 127) {+ if (outIdx >= endIdx) break;+ heap[outIdx++] = u;+ } else if (u <= 2047) {+ if (outIdx + 1 >= endIdx) break;+ heap[outIdx++] = 192 | (u >> 6);+ heap[outIdx++] = 128 | (u & 63);+ } else if (u <= 65535) {+ if (outIdx + 2 >= endIdx) break;+ heap[outIdx++] = 224 | (u >> 12);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ } else {+ if (outIdx + 3 >= endIdx) break;+ heap[outIdx++] = 240 | (u >> 18);+ heap[outIdx++] = 128 | ((u >> 12) & 63);+ heap[outIdx++] = 128 | ((u >> 6) & 63);+ heap[outIdx++] = 128 | (u & 63);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ i++;+ }+ }+ // Null-terminate the pointer to the buffer.+ heap[outIdx] = 0;+ return outIdx - startIdx;+};++/** @type {function(string, boolean=, number=)} */ var intArrayFromString = (stringy, dontAddNull, length) => {+ var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;+ var u8array = new Array(len);+ var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);+ if (dontAddNull) u8array.length = numBytesWritten;+ return u8array;+};++var FS_stdin_getChar = () => {+ if (!FS_stdin_getChar_buffer.length) {+ var result = null;+ if (ENVIRONMENT_IS_NODE) {+ // we will read data by chunks of BUFSIZE+ var BUFSIZE = 256;+ var buf = Buffer.alloc(BUFSIZE);+ var bytesRead = 0;+ // For some reason we must suppress a closure warning here, even though+ // fd definitely exists on process.stdin, and is even the proper way to+ // get the fd of stdin,+ // https://github.com/nodejs/help/issues/2136#issuecomment-523649904+ // This started to happen after moving this logic out of library_tty.js,+ // so it is related to the surrounding code in some unclear manner.+ /** @suppress {missingProperties} */ var fd = process.stdin.fd;+ try {+ bytesRead = fs.readSync(fd, buf, 0, BUFSIZE);+ } catch (e) {+ // Cross-platform differences: on Windows, reading EOF throws an+ // exception, but on other OSes, reading EOF returns 0. Uniformize+ // behavior by treating the EOF exception to return 0.+ if (e.toString().includes("EOF")) bytesRead = 0; else throw e;+ }+ if (bytesRead > 0) {+ result = buf.slice(0, bytesRead).toString("utf-8");+ }+ } else if (globalThis.window?.prompt) {+ // Browser.+ result = window.prompt("Input: ");+ // returns null on cancel+ if (result !== null) {+ result += "\n";+ }+ } else {}+ if (!result) {+ return null;+ }+ FS_stdin_getChar_buffer = intArrayFromString(result, true);+ }+ return FS_stdin_getChar_buffer.shift();+};++var TTY = {+ ttys: [],+ init() {},+ shutdown() {},+ register(dev, ops) {+ TTY.ttys[dev] = {+ input: [],+ output: [],+ ops+ };+ FS.registerDevice(dev, TTY.stream_ops);+ },+ stream_ops: {+ open(stream) {+ var tty = TTY.ttys[stream.node.rdev];+ if (!tty) {+ throw new FS.ErrnoError(43);+ }+ stream.tty = tty;+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ stream.tty.ops.fsync(stream.tty);+ },+ fsync(stream) {+ stream.tty.ops.fsync(stream.tty);+ },+ read(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.get_char) {+ throw new FS.ErrnoError(60);+ }+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = stream.tty.ops.get_char(stream.tty);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ if (!stream.tty || !stream.tty.ops.put_char) {+ throw new FS.ErrnoError(60);+ }+ try {+ for (var i = 0; i < length; i++) {+ stream.tty.ops.put_char(stream.tty, buffer[offset + i]);+ }+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ },+ default_tty_ops: {+ get_char(tty) {+ return FS_stdin_getChar();+ },+ put_char(tty, val) {+ if (val === null || val === 10) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ out(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ },+ ioctl_tcgets(tty) {+ // typical setting+ return {+ c_iflag: 25856,+ c_oflag: 5,+ c_cflag: 191,+ c_lflag: 35387,+ c_cc: [ 3, 28, 127, 21, 4, 0, 1, 0, 17, 19, 26, 0, 18, 15, 23, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]+ };+ },+ ioctl_tcsets(tty, optional_actions, data) {+ // currently just ignore+ return 0;+ },+ ioctl_tiocgwinsz(tty) {+ return [ 24, 80 ];+ }+ },+ default_tty1_ops: {+ put_char(tty, val) {+ if (val === null || val === 10) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ } else {+ if (val != 0) tty.output.push(val);+ }+ },+ fsync(tty) {+ if (tty.output?.length > 0) {+ err(UTF8ArrayToString(tty.output));+ tty.output = [];+ }+ }+ }+};++var zeroMemory = (ptr, size) => HEAPU8.fill(0, ptr, ptr + size);++var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;++var mmapAlloc = size => {+ size = alignMemory(size, 65536);+ var ptr = _emscripten_builtin_memalign(65536, size);+ if (ptr) zeroMemory(ptr, size);+ return ptr;+};++var MEMFS = {+ ops_table: null,+ mount(mount) {+ return MEMFS.createNode(null, "/", 16895, 0);+ },+ createNode(parent, name, mode, dev) {+ if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {+ // not supported+ throw new FS.ErrnoError(63);+ }+ MEMFS.ops_table ||= {+ dir: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ lookup: MEMFS.node_ops.lookup,+ mknod: MEMFS.node_ops.mknod,+ rename: MEMFS.node_ops.rename,+ unlink: MEMFS.node_ops.unlink,+ rmdir: MEMFS.node_ops.rmdir,+ readdir: MEMFS.node_ops.readdir,+ symlink: MEMFS.node_ops.symlink+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek+ }+ },+ file: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: {+ llseek: MEMFS.stream_ops.llseek,+ read: MEMFS.stream_ops.read,+ write: MEMFS.stream_ops.write,+ mmap: MEMFS.stream_ops.mmap,+ msync: MEMFS.stream_ops.msync+ }+ },+ link: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr,+ readlink: MEMFS.node_ops.readlink+ },+ stream: {}+ },+ chrdev: {+ node: {+ getattr: MEMFS.node_ops.getattr,+ setattr: MEMFS.node_ops.setattr+ },+ stream: FS.chrdev_stream_ops+ }+ };+ var node = FS.createNode(parent, name, mode, dev);+ if (FS.isDir(node.mode)) {+ node.node_ops = MEMFS.ops_table.dir.node;+ node.stream_ops = MEMFS.ops_table.dir.stream;+ node.contents = {};+ } else if (FS.isFile(node.mode)) {+ node.node_ops = MEMFS.ops_table.file.node;+ node.stream_ops = MEMFS.ops_table.file.stream;+ // The actual number of bytes used in the typed array, as opposed to+ // contents.length which gives the whole capacity.+ node.usedBytes = 0;+ // The byte data of the file is stored in a typed array.+ // Note: typed arrays are not resizable like normal JS arrays are, so+ // there is a small penalty involved for appending file writes that+ // continuously grow a file similar to std::vector capacity vs used.+ node.contents = MEMFS.emptyFileContents ??= new Uint8Array(0);+ } else if (FS.isLink(node.mode)) {+ node.node_ops = MEMFS.ops_table.link.node;+ node.stream_ops = MEMFS.ops_table.link.stream;+ } else if (FS.isChrdev(node.mode)) {+ node.node_ops = MEMFS.ops_table.chrdev.node;+ node.stream_ops = MEMFS.ops_table.chrdev.stream;+ }+ node.atime = node.mtime = node.ctime = Date.now();+ // add the new node to the parent+ if (parent) {+ parent.contents[name] = node;+ parent.atime = parent.mtime = parent.ctime = node.atime;+ }+ return node;+ },+ getFileDataAsTypedArray(node) {+ return node.contents.subarray(0, node.usedBytes);+ },+ expandFileStorage(node, newCapacity) {+ var prevCapacity = node.contents.length;+ if (prevCapacity >= newCapacity) return;+ // No need to expand, the storage was already large enough.+ // Don't expand strictly to the given requested limit if it's only a very+ // small increase, but instead geometrically grow capacity.+ // For small filesizes (<1MB), perform size*2 geometric increase, but for+ // large sizes, do a much more conservative size*1.125 increase to avoid+ // overshooting the allocation cap by a very large margin.+ var CAPACITY_DOUBLING_MAX = 1024 * 1024;+ newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> 0);+ if (prevCapacity) newCapacity = Math.max(newCapacity, 256);+ // At minimum allocate 256b for each file when expanding.+ var oldContents = MEMFS.getFileDataAsTypedArray(node);+ node.contents = new Uint8Array(newCapacity);+ // Allocate new storage.+ node.contents.set(oldContents);+ },+ resizeFileStorage(node, newSize) {+ if (node.usedBytes == newSize) return;+ var oldContents = node.contents;+ node.contents = new Uint8Array(newSize);+ // Allocate new storage.+ node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));+ // Copy old data over to the new storage.+ node.usedBytes = newSize;+ },+ node_ops: {+ getattr(node) {+ var attr = {};+ // device numbers reuse inode numbers.+ attr.dev = FS.isChrdev(node.mode) ? node.id : 1;+ attr.ino = node.id;+ attr.mode = node.mode;+ attr.nlink = 1;+ attr.uid = 0;+ attr.gid = 0;+ attr.rdev = node.rdev;+ if (FS.isDir(node.mode)) {+ attr.size = 4096;+ } else if (FS.isFile(node.mode)) {+ attr.size = node.usedBytes;+ } else if (FS.isLink(node.mode)) {+ attr.size = node.link.length;+ } else {+ attr.size = 0;+ }+ attr.atime = new Date(node.atime);+ attr.mtime = new Date(node.mtime);+ attr.ctime = new Date(node.ctime);+ // NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),+ // but this is not required by the standard.+ attr.blksize = 4096;+ attr.blocks = Math.ceil(attr.size / attr.blksize);+ return attr;+ },+ setattr(node, attr) {+ for (const key of [ "mode", "atime", "mtime", "ctime" ]) {+ if (attr[key] != null) {+ node[key] = attr[key];+ }+ }+ if (attr.size !== undefined) {+ MEMFS.resizeFileStorage(node, attr.size);+ }+ },+ lookup(parent, name) {+ // This error may happen quite a bit. To avoid overhead we reuse it (and+ // suffer a lack of stack info).+ if (!MEMFS.doesNotExistError) {+ MEMFS.doesNotExistError = new FS.ErrnoError(44);+ /** @suppress {checkTypes} */ MEMFS.doesNotExistError.stack = "<generic error, no stack>";+ }+ throw MEMFS.doesNotExistError;+ },+ mknod(parent, name, mode, dev) {+ return MEMFS.createNode(parent, name, mode, dev);+ },+ rename(old_node, new_dir, new_name) {+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ if (new_node) {+ if (FS.isDir(old_node.mode)) {+ // if we're overwriting a directory at new_name, make sure it's empty.+ for (var i in new_node.contents) {+ throw new FS.ErrnoError(55);+ }+ }+ FS.hashRemoveNode(new_node);+ }+ // do the internal rewiring+ delete old_node.parent.contents[old_node.name];+ new_dir.contents[new_name] = old_node;+ old_node.name = new_name;+ new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();+ },+ unlink(parent, name) {+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ rmdir(parent, name) {+ var node = FS.lookupNode(parent, name);+ for (var i in node.contents) {+ throw new FS.ErrnoError(55);+ }+ delete parent.contents[name];+ parent.ctime = parent.mtime = Date.now();+ },+ readdir(node) {+ return [ ".", "..", ...Object.keys(node.contents) ];+ },+ symlink(parent, newname, oldpath) {+ var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);+ node.link = oldpath;+ return node;+ },+ readlink(node) {+ if (!FS.isLink(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ return node.link;+ }+ },+ stream_ops: {+ read(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= stream.node.usedBytes) return 0;+ var size = Math.min(stream.node.usedBytes - position, length);+ buffer.set(contents.subarray(position, position + size), offset);+ return size;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ // If the buffer is located in main memory (HEAP), and if+ // memory can grow, we can't hold on to references of the+ // memory buffer, as they may get invalidated. That means we+ // need to copy its contents.+ if (buffer.buffer === HEAP8.buffer) {+ canOwn = false;+ }+ if (!length) return 0;+ var node = stream.node;+ node.mtime = node.ctime = Date.now();+ if (canOwn) {+ node.contents = buffer.subarray(offset, offset + length);+ node.usedBytes = length;+ } else if (node.usedBytes === 0 && position === 0) {+ // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.+ node.contents = buffer.slice(offset, offset + length);+ node.usedBytes = length;+ } else {+ MEMFS.expandFileStorage(node, position + length);+ // Use typed array write which is available.+ node.contents.set(buffer.subarray(offset, offset + length), position);+ node.usedBytes = Math.max(node.usedBytes, position + length);+ }+ return length;+ },+ llseek(stream, offset, whence) {+ var position = offset;+ if (whence === 1) {+ position += stream.position;+ } else if (whence === 2) {+ if (FS.isFile(stream.node.mode)) {+ position += stream.node.usedBytes;+ }+ }+ if (position < 0) {+ throw new FS.ErrnoError(28);+ }+ return position;+ },+ mmap(stream, length, position, prot, flags) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ var ptr;+ var allocated;+ var contents = stream.node.contents;+ // Only make a new copy when MAP_PRIVATE is specified.+ if (!(flags & 2) && contents.buffer === HEAP8.buffer) {+ // We can't emulate MAP_SHARED when the file is not backed by the+ // buffer we're mapping to (e.g. the HEAP buffer).+ allocated = false;+ ptr = contents.byteOffset;+ } else {+ allocated = true;+ ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ if (contents) {+ // Try to avoid unnecessary slices.+ if (position > 0 || position + length < contents.length) {+ if (contents.subarray) {+ contents = contents.subarray(position, position + length);+ } else {+ contents = Array.prototype.slice.call(contents, position, position + length);+ }+ }+ HEAP8.set(contents, ptr);+ }+ }+ return {+ ptr,+ allocated+ };+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);+ // should we check if bytesWritten and length are the same?+ return 0;+ }+ }+};++var FS_modeStringToFlags = str => {+ if (typeof str != "string") return str;+ var flagModes = {+ "r": 0,+ "r+": 2,+ "w": 512 | 64 | 1,+ "w+": 512 | 64 | 2,+ "a": 1024 | 64 | 1,+ "a+": 1024 | 64 | 2+ };+ var flags = flagModes[str];+ if (typeof flags == "undefined") {+ throw new Error(`Unknown file open mode: ${str}`);+ }+ return flags;+};++var FS_fileDataToTypedArray = data => {+ if (typeof data == "string") {+ data = intArrayFromString(data, true);+ }+ if (!data.subarray) {+ data = new Uint8Array(data);+ }+ return data;+};++var FS_getMode = (canRead, canWrite) => {+ var mode = 0;+ if (canRead) mode |= 292 | 73;+ if (canWrite) mode |= 146;+ return mode;+};++var asyncLoad = async url => {+ var arrayBuffer = await readAsync(url);+ return new Uint8Array(arrayBuffer);+};++var FS_createDataFile = (...args) => FS.createDataFile(...args);++var getUniqueRunDependency = id => id;++var runDependencies = 0;++var dependenciesFulfilled = null;++var removeRunDependency = id => {+ runDependencies--;+ Module["monitorRunDependencies"]?.(runDependencies);+ if (runDependencies == 0) {+ if (dependenciesFulfilled) {+ var callback = dependenciesFulfilled;+ dependenciesFulfilled = null;+ callback();+ }+ }+};++var addRunDependency = id => {+ runDependencies++;+ Module["monitorRunDependencies"]?.(runDependencies);+};++var FS_handledByPreloadPlugin = async (byteArray, fullname) => {+ // Ensure plugins are ready.+ if (typeof Browser != "undefined") Browser.init();+ for (var plugin of preloadPlugins) {+ if (plugin["canHandle"](fullname)) {+ return plugin["handle"](byteArray, fullname);+ }+ }+ // If no plugin handled this file then return the original/unmodified+ // byteArray.+ return byteArray;+};++var FS_preloadFile = async (parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish) => {+ // TODO we should allow people to just pass in a complete filename instead+ // of parent and name being that we just join them anyways+ var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;+ var dep = getUniqueRunDependency(`cp ${fullname}`);+ // might have several active requests for the same fullname+ addRunDependency(dep);+ try {+ var byteArray = url;+ if (typeof url == "string") {+ byteArray = await asyncLoad(url);+ }+ byteArray = await FS_handledByPreloadPlugin(byteArray, fullname);+ preFinish?.();+ if (!dontCreateFile) {+ FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);+ }+ } finally {+ removeRunDependency(dep);+ }+};++var FS_createPreloadedFile = (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {+ FS_preloadFile(parent, name, url, canRead, canWrite, dontCreateFile, canOwn, preFinish).then(onload).catch(onerror);+};++var FS = {+ root: null,+ mounts: [],+ devices: {},+ streams: [],+ nextInode: 1,+ nameTable: null,+ currentPath: "/",+ initialized: false,+ ignorePermissions: true,+ filesystems: null,+ syncFSRequests: 0,+ ErrnoError: class {+ name="ErrnoError";+ // We set the `name` property to be able to identify `FS.ErrnoError`+ // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.+ // - when using PROXYFS, an error can come from an underlying FS+ // as different FS objects have their own FS.ErrnoError each,+ // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.+ // we'll use the reliable test `err.name == "ErrnoError"` instead+ constructor(errno) {+ this.errno = errno;+ }+ },+ FSStream: class {+ shared={};+ get object() {+ return this.node;+ }+ set object(val) {+ this.node = val;+ }+ get isRead() {+ return (this.flags & 2097155) !== 1;+ }+ get isWrite() {+ return (this.flags & 2097155) !== 0;+ }+ get isAppend() {+ return (this.flags & 1024);+ }+ get flags() {+ return this.shared.flags;+ }+ set flags(val) {+ this.shared.flags = val;+ }+ get position() {+ return this.shared.position;+ }+ set position(val) {+ this.shared.position = val;+ }+ },+ FSNode: class {+ node_ops={};+ stream_ops={};+ readMode=292 | 73;+ writeMode=146;+ mounted=null;+ constructor(parent, name, mode, rdev) {+ if (!parent) {+ parent = this;+ }+ this.parent = parent;+ this.mount = parent.mount;+ this.id = FS.nextInode++;+ this.name = name;+ this.mode = mode;+ this.rdev = rdev;+ this.atime = this.mtime = this.ctime = Date.now();+ }+ get read() {+ return (this.mode & this.readMode) === this.readMode;+ }+ set read(val) {+ val ? this.mode |= this.readMode : this.mode &= ~this.readMode;+ }+ get write() {+ return (this.mode & this.writeMode) === this.writeMode;+ }+ set write(val) {+ val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;+ }+ get isFolder() {+ return FS.isDir(this.mode);+ }+ get isDevice() {+ return FS.isChrdev(this.mode);+ }+ },+ lookupPath(path, opts = {}) {+ if (!path) {+ throw new FS.ErrnoError(44);+ }+ opts.follow_mount ??= true;+ if (!PATH.isAbs(path)) {+ path = FS.cwd() + "/" + path;+ }+ // limit max consecutive symlinks to 40 (SYMLOOP_MAX).+ linkloop: for (var nlinks = 0; nlinks < 40; nlinks++) {+ // split the absolute path+ var parts = path.split("/").filter(p => !!p);+ // start at the root+ var current = FS.root;+ var current_path = "/";+ for (var i = 0; i < parts.length; i++) {+ var islast = (i === parts.length - 1);+ if (islast && opts.parent) {+ // stop resolving+ break;+ }+ if (parts[i] === ".") {+ continue;+ }+ if (parts[i] === "..") {+ current_path = PATH.dirname(current_path);+ if (FS.isRoot(current)) {+ path = current_path + "/" + parts.slice(i + 1).join("/");+ // We're making progress here, don't let many consecutive ..'s+ // lead to ELOOP+ nlinks--;+ continue linkloop;+ } else {+ current = current.parent;+ }+ continue;+ }+ current_path = PATH.join2(current_path, parts[i]);+ try {+ current = FS.lookupNode(current, parts[i]);+ } catch (e) {+ // if noent_okay is true, suppress a ENOENT in the last component+ // and return an object with an undefined node. This is needed for+ // resolving symlinks in the path when creating a file.+ if ((e?.errno === 44) && islast && opts.noent_okay) {+ return {+ path: current_path+ };+ }+ throw e;+ }+ // jump to the mount's root node if this is a mountpoint+ if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {+ current = current.mounted.root;+ }+ // by default, lookupPath will not follow a symlink if it is the final path component.+ // setting opts.follow = true will override this behavior.+ if (FS.isLink(current.mode) && (!islast || opts.follow)) {+ if (!current.node_ops.readlink) {+ throw new FS.ErrnoError(52);+ }+ var link = current.node_ops.readlink(current);+ if (!PATH.isAbs(link)) {+ link = PATH.dirname(current_path) + "/" + link;+ }+ path = link + "/" + parts.slice(i + 1).join("/");+ continue linkloop;+ }+ }+ return {+ path: current_path,+ node: current+ };+ }+ throw new FS.ErrnoError(32);+ },+ getPath(node) {+ var path;+ while (true) {+ if (FS.isRoot(node)) {+ var mount = node.mount.mountpoint;+ if (!path) return mount;+ return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;+ }+ path = path ? `${node.name}/${path}` : node.name;+ node = node.parent;+ }+ },+ hashName(parentid, name) {+ var hash = 0;+ for (var i = 0; i < name.length; i++) {+ hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;+ }+ return ((parentid + hash) >>> 0) % FS.nameTable.length;+ },+ hashAddNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ node.name_next = FS.nameTable[hash];+ FS.nameTable[hash] = node;+ },+ hashRemoveNode(node) {+ var hash = FS.hashName(node.parent.id, node.name);+ if (FS.nameTable[hash] === node) {+ FS.nameTable[hash] = node.name_next;+ } else {+ var current = FS.nameTable[hash];+ while (current) {+ if (current.name_next === node) {+ current.name_next = node.name_next;+ break;+ }+ current = current.name_next;+ }+ }+ },+ lookupNode(parent, name) {+ var errCode = FS.mayLookup(parent);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ var hash = FS.hashName(parent.id, name);+ for (var node = FS.nameTable[hash]; node; node = node.name_next) {+ var nodeName = node.name;+ if (node.parent.id === parent.id && nodeName === name) {+ return node;+ }+ }+ // if we failed to find it in the cache, call into the VFS+ return FS.lookup(parent, name);+ },+ createNode(parent, name, mode, rdev) {+ var node = new FS.FSNode(parent, name, mode, rdev);+ FS.hashAddNode(node);+ return node;+ },+ destroyNode(node) {+ FS.hashRemoveNode(node);+ },+ isRoot(node) {+ return node === node.parent;+ },+ isMountpoint(node) {+ return !!node.mounted;+ },+ isFile(mode) {+ return (mode & 61440) === 32768;+ },+ isDir(mode) {+ return (mode & 61440) === 16384;+ },+ isLink(mode) {+ return (mode & 61440) === 40960;+ },+ isChrdev(mode) {+ return (mode & 61440) === 8192;+ },+ isBlkdev(mode) {+ return (mode & 61440) === 24576;+ },+ isFIFO(mode) {+ return (mode & 61440) === 4096;+ },+ isSocket(mode) {+ return (mode & 49152) === 49152;+ },+ flagsToPermissionString(flag) {+ var perms = [ "r", "w", "rw" ][flag & 3];+ if ((flag & 512)) {+ perms += "w";+ }+ return perms;+ },+ nodePermissions(node, perms) {+ if (FS.ignorePermissions) {+ return 0;+ }+ // return 0 if any user, group or owner bits are set.+ if (perms.includes("r") && !(node.mode & 292)) {+ return 2;+ }+ if (perms.includes("w") && !(node.mode & 146)) {+ return 2;+ }+ if (perms.includes("x") && !(node.mode & 73)) {+ return 2;+ }+ return 0;+ },+ mayLookup(dir) {+ if (!FS.isDir(dir.mode)) return 54;+ var errCode = FS.nodePermissions(dir, "x");+ if (errCode) return errCode;+ if (!dir.node_ops.lookup) return 2;+ return 0;+ },+ mayCreate(dir, name) {+ if (!FS.isDir(dir.mode)) {+ return 54;+ }+ try {+ var node = FS.lookupNode(dir, name);+ return 20;+ } catch (e) {}+ return FS.nodePermissions(dir, "wx");+ },+ mayDelete(dir, name, isdir) {+ var node;+ try {+ node = FS.lookupNode(dir, name);+ } catch (e) {+ return e.errno;+ }+ var errCode = FS.nodePermissions(dir, "wx");+ if (errCode) {+ return errCode;+ }+ if (isdir) {+ if (!FS.isDir(node.mode)) {+ return 54;+ }+ if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {+ return 10;+ }+ } else if (FS.isDir(node.mode)) {+ return 31;+ }+ return 0;+ },+ mayOpen(node, flags) {+ if (!node) {+ return 44;+ }+ if (FS.isLink(node.mode)) {+ return 32;+ }+ var mode = FS.flagsToPermissionString(flags);+ if (FS.isDir(node.mode)) {+ // opening for write+ // TODO: check for O_SEARCH? (== search for dir only)+ if (mode !== "r" || (flags & (512 | 64))) {+ return 31;+ }+ }+ return FS.nodePermissions(node, mode);+ },+ checkOpExists(op, err) {+ if (!op) {+ throw new FS.ErrnoError(err);+ }+ return op;+ },+ MAX_OPEN_FDS: 4096,+ nextfd() {+ for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {+ if (!FS.streams[fd]) {+ return fd;+ }+ }+ throw new FS.ErrnoError(33);+ },+ getStreamChecked(fd) {+ var stream = FS.getStream(fd);+ if (!stream) {+ throw new FS.ErrnoError(8);+ }+ return stream;+ },+ getStream: fd => FS.streams[fd],+ createStream(stream, fd = -1) {+ // clone it, so we can return an instance of FSStream+ stream = Object.assign(new FS.FSStream, stream);+ if (fd == -1) {+ fd = FS.nextfd();+ }+ stream.fd = fd;+ FS.streams[fd] = stream;+ return stream;+ },+ closeStream(fd) {+ FS.streams[fd] = null;+ },+ dupStream(origStream, fd = -1) {+ var stream = FS.createStream(origStream, fd);+ stream.stream_ops?.dup?.(stream);+ return stream;+ },+ doSetAttr(stream, node, attr) {+ var setattr = stream?.stream_ops.setattr;+ var arg = setattr ? stream : node;+ setattr ??= node.node_ops.setattr;+ FS.checkOpExists(setattr, 63);+ setattr(arg, attr);+ },+ chrdev_stream_ops: {+ open(stream) {+ var device = FS.getDevice(stream.node.rdev);+ // override node's stream ops with the device's+ stream.stream_ops = device.stream_ops;+ // forward the open call+ stream.stream_ops.open?.(stream);+ },+ llseek() {+ throw new FS.ErrnoError(70);+ }+ },+ major: dev => ((dev) >> 8),+ minor: dev => ((dev) & 255),+ makedev: (ma, mi) => ((ma) << 8 | (mi)),+ registerDevice(dev, ops) {+ FS.devices[dev] = {+ stream_ops: ops+ };+ },+ getDevice: dev => FS.devices[dev],+ getMounts(mount) {+ var mounts = [];+ var check = [ mount ];+ while (check.length) {+ var m = check.pop();+ mounts.push(m);+ check.push(...m.mounts);+ }+ return mounts;+ },+ syncfs(populate, callback) {+ if (typeof populate == "function") {+ callback = populate;+ populate = false;+ }+ FS.syncFSRequests++;+ if (FS.syncFSRequests > 1) {+ err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);+ }+ var mounts = FS.getMounts(FS.root.mount);+ var completed = 0;+ function doCallback(errCode) {+ FS.syncFSRequests--;+ return callback(errCode);+ }+ function done(errCode) {+ if (errCode) {+ if (!done.errored) {+ done.errored = true;+ return doCallback(errCode);+ }+ return;+ }+ if (++completed >= mounts.length) {+ doCallback(null);+ }+ }+ // sync all mounts+ for (var mount of mounts) {+ if (mount.type.syncfs) {+ mount.type.syncfs(mount, populate, done);+ } else {+ done(null);+ }+ }+ },+ mount(type, opts, mountpoint) {+ var root = mountpoint === "/";+ var pseudo = !mountpoint;+ var node;+ if (root && FS.root) {+ throw new FS.ErrnoError(10);+ } else if (!root && !pseudo) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ mountpoint = lookup.path;+ // use the absolute path+ node = lookup.node;+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ if (!FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ }+ var mount = {+ type,+ opts,+ mountpoint,+ mounts: []+ };+ // create a root node for the fs+ var mountRoot = type.mount(mount);+ mountRoot.mount = mount;+ mount.root = mountRoot;+ if (root) {+ FS.root = mountRoot;+ } else if (node) {+ // set as a mountpoint+ node.mounted = mount;+ // add the new mount to the current mount's children+ if (node.mount) {+ node.mount.mounts.push(mount);+ }+ }+ return mountRoot;+ },+ unmount(mountpoint) {+ var lookup = FS.lookupPath(mountpoint, {+ follow_mount: false+ });+ if (!FS.isMountpoint(lookup.node)) {+ throw new FS.ErrnoError(28);+ }+ // destroy the nodes for this mount, and all its child mounts+ var node = lookup.node;+ var mount = node.mounted;+ var mounts = FS.getMounts(mount);+ for (var [hash, current] of Object.entries(FS.nameTable)) {+ while (current) {+ var next = current.name_next;+ if (mounts.includes(current.mount)) {+ FS.destroyNode(current);+ }+ current = next;+ }+ }+ // no longer a mountpoint+ node.mounted = null;+ // remove this mount from the child mounts+ var idx = node.mount.mounts.indexOf(mount);+ node.mount.mounts.splice(idx, 1);+ },+ lookup(parent, name) {+ return parent.node_ops.lookup(parent, name);+ },+ mknod(path, mode, dev) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ if (!name) {+ throw new FS.ErrnoError(28);+ }+ if (name === "." || name === "..") {+ throw new FS.ErrnoError(20);+ }+ var errCode = FS.mayCreate(parent, name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.mknod) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.mknod(parent, name, mode, dev);+ },+ statfs(path) {+ return FS.statfsNode(FS.lookupPath(path, {+ follow: true+ }).node);+ },+ statfsStream(stream) {+ // We keep a separate statfsStream function because noderawfs overrides+ // it. In noderawfs, stream.node is sometimes null. Instead, we need to+ // look at stream.path.+ return FS.statfsNode(stream.node);+ },+ statfsNode(node) {+ // NOTE: None of the defaults here are true. We're just returning safe and+ // sane values. Currently nodefs and rawfs replace these defaults,+ // other file systems leave them alone.+ var rtn = {+ bsize: 4096,+ frsize: 4096,+ blocks: 1e6,+ bfree: 5e5,+ bavail: 5e5,+ files: FS.nextInode,+ ffree: FS.nextInode - 1,+ fsid: 42,+ flags: 2,+ namelen: 255+ };+ if (node.node_ops.statfs) {+ Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));+ }+ return rtn;+ },+ create(path, mode = 438) {+ mode &= 4095;+ mode |= 32768;+ return FS.mknod(path, mode, 0);+ },+ mkdir(path, mode = 511) {+ mode &= 511 | 512;+ mode |= 16384;+ return FS.mknod(path, mode, 0);+ },+ mkdirTree(path, mode) {+ var dirs = path.split("/");+ var d = "";+ for (var dir of dirs) {+ if (!dir) continue;+ if (d || PATH.isAbs(path)) d += "/";+ d += dir;+ try {+ FS.mkdir(d, mode);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ }+ },+ mkdev(path, mode, dev) {+ if (typeof dev == "undefined") {+ dev = mode;+ mode = 438;+ }+ mode |= 8192;+ return FS.mknod(path, mode, dev);+ },+ symlink(oldpath, newpath) {+ if (!PATH_FS.resolve(oldpath)) {+ throw new FS.ErrnoError(44);+ }+ var lookup = FS.lookupPath(newpath, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var newname = PATH.basename(newpath);+ var errCode = FS.mayCreate(parent, newname);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.symlink) {+ throw new FS.ErrnoError(63);+ }+ return parent.node_ops.symlink(parent, newname, oldpath);+ },+ rename(old_path, new_path) {+ var old_dirname = PATH.dirname(old_path);+ var new_dirname = PATH.dirname(new_path);+ var old_name = PATH.basename(old_path);+ var new_name = PATH.basename(new_path);+ // parents must exist+ var lookup, old_dir, new_dir;+ // let the errors from non existent directories percolate up+ lookup = FS.lookupPath(old_path, {+ parent: true+ });+ old_dir = lookup.node;+ lookup = FS.lookupPath(new_path, {+ parent: true+ });+ new_dir = lookup.node;+ if (!old_dir || !new_dir) throw new FS.ErrnoError(44);+ // need to be part of the same mount+ if (old_dir.mount !== new_dir.mount) {+ throw new FS.ErrnoError(75);+ }+ // source must exist+ var old_node = FS.lookupNode(old_dir, old_name);+ // old path should not be an ancestor of the new path+ var relative = PATH_FS.relative(old_path, new_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(28);+ }+ // new path should not be an ancestor of the old path+ relative = PATH_FS.relative(new_path, old_dirname);+ if (relative.charAt(0) !== ".") {+ throw new FS.ErrnoError(55);+ }+ // see if the new path already exists+ var new_node;+ try {+ new_node = FS.lookupNode(new_dir, new_name);+ } catch (e) {}+ // early out if nothing needs to change+ if (old_node === new_node) {+ return;+ }+ // we'll need to delete the old entry+ var isdir = FS.isDir(old_node.mode);+ var errCode = FS.mayDelete(old_dir, old_name, isdir);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ // need delete permissions if we'll be overwriting.+ // need create permissions if new doesn't already exist.+ errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!old_dir.node_ops.rename) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {+ throw new FS.ErrnoError(10);+ }+ // if we are going to change the parent, check write permissions+ if (new_dir !== old_dir) {+ errCode = FS.nodePermissions(old_dir, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // remove the node from the lookup hash+ FS.hashRemoveNode(old_node);+ // do the underlying fs rename+ try {+ old_dir.node_ops.rename(old_node, new_dir, new_name);+ // update old node (we do this here to avoid each backend+ // needing to)+ old_node.parent = new_dir;+ } catch (e) {+ throw e;+ } finally {+ // add the node back to the hash (in case node_ops.rename+ // changed its name)+ FS.hashAddNode(old_node);+ }+ },+ rmdir(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, true);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.rmdir) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.rmdir(parent, name);+ FS.destroyNode(node);+ },+ readdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var readdir = FS.checkOpExists(node.node_ops.readdir, 54);+ return readdir(node);+ },+ unlink(path) {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ var parent = lookup.node;+ if (!parent) {+ throw new FS.ErrnoError(44);+ }+ var name = PATH.basename(path);+ var node = FS.lookupNode(parent, name);+ var errCode = FS.mayDelete(parent, name, false);+ if (errCode) {+ // According to POSIX, we should map EISDIR to EPERM, but+ // we instead do what Linux does (and we must, as we use+ // the musl linux libc).+ throw new FS.ErrnoError(errCode);+ }+ if (!parent.node_ops.unlink) {+ throw new FS.ErrnoError(63);+ }+ if (FS.isMountpoint(node)) {+ throw new FS.ErrnoError(10);+ }+ parent.node_ops.unlink(parent, name);+ FS.destroyNode(node);+ },+ readlink(path) {+ var lookup = FS.lookupPath(path);+ var link = lookup.node;+ if (!link) {+ throw new FS.ErrnoError(44);+ }+ if (!link.node_ops.readlink) {+ throw new FS.ErrnoError(28);+ }+ return link.node_ops.readlink(link);+ },+ stat(path, dontFollow) {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ var node = lookup.node;+ var getattr = FS.checkOpExists(node.node_ops.getattr, 63);+ return getattr(node);+ },+ fstat(fd) {+ var stream = FS.getStreamChecked(fd);+ var node = stream.node;+ var getattr = stream.stream_ops.getattr;+ var arg = getattr ? stream : node;+ getattr ??= node.node_ops.getattr;+ FS.checkOpExists(getattr, 63);+ return getattr(arg);+ },+ lstat(path) {+ return FS.stat(path, true);+ },+ doChmod(stream, node, mode, dontFollow) {+ FS.doSetAttr(stream, node, {+ mode: (mode & 4095) | (node.mode & ~4095),+ ctime: Date.now(),+ dontFollow+ });+ },+ chmod(path, mode, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChmod(null, node, mode, dontFollow);+ },+ lchmod(path, mode) {+ FS.chmod(path, mode, true);+ },+ fchmod(fd, mode) {+ var stream = FS.getStreamChecked(fd);+ FS.doChmod(stream, stream.node, mode, false);+ },+ doChown(stream, node, dontFollow) {+ FS.doSetAttr(stream, node, {+ timestamp: Date.now(),+ dontFollow+ });+ },+ chown(path, uid, gid, dontFollow) {+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: !dontFollow+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doChown(null, node, dontFollow);+ },+ lchown(path, uid, gid) {+ FS.chown(path, uid, gid, true);+ },+ fchown(fd, uid, gid) {+ var stream = FS.getStreamChecked(fd);+ FS.doChown(stream, stream.node, false);+ },+ doTruncate(stream, node, len) {+ if (FS.isDir(node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!FS.isFile(node.mode)) {+ throw new FS.ErrnoError(28);+ }+ var errCode = FS.nodePermissions(node, "w");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.doSetAttr(stream, node, {+ size: len,+ timestamp: Date.now()+ });+ },+ truncate(path, len) {+ if (len < 0) {+ throw new FS.ErrnoError(28);+ }+ var node;+ if (typeof path == "string") {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ node = lookup.node;+ } else {+ node = path;+ }+ FS.doTruncate(null, node, len);+ },+ ftruncate(fd, len) {+ var stream = FS.getStreamChecked(fd);+ if (len < 0 || (stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(28);+ }+ FS.doTruncate(stream, stream.node, len);+ },+ utime(path, atime, mtime) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ var setattr = FS.checkOpExists(node.node_ops.setattr, 63);+ setattr(node, {+ atime,+ mtime+ });+ },+ open(path, flags, mode = 438) {+ if (path === "") {+ throw new FS.ErrnoError(44);+ }+ flags = FS_modeStringToFlags(flags);+ if ((flags & 64)) {+ mode = (mode & 4095) | 32768;+ } else {+ mode = 0;+ }+ var node;+ var isDirPath;+ if (typeof path == "object") {+ node = path;+ } else {+ isDirPath = path.endsWith("/");+ // noent_okay makes it so that if the final component of the path+ // doesn't exist, lookupPath returns `node: undefined`. `path` will be+ // updated to point to the target of all symlinks.+ var lookup = FS.lookupPath(path, {+ follow: !(flags & 131072),+ noent_okay: true+ });+ node = lookup.node;+ path = lookup.path;+ }+ // perhaps we need to create the node+ var created = false;+ if ((flags & 64)) {+ if (node) {+ // if O_CREAT and O_EXCL are set, error out if the node already exists+ if ((flags & 128)) {+ throw new FS.ErrnoError(20);+ }+ } else if (isDirPath) {+ throw new FS.ErrnoError(31);+ } else {+ // node doesn't exist, try to create it+ // Ignore the permission bits here to ensure we can `open` this new+ // file below. We use chmod below to apply the permissions once the+ // file is open.+ node = FS.mknod(path, mode | 511, 0);+ created = true;+ }+ }+ if (!node) {+ throw new FS.ErrnoError(44);+ }+ // can't truncate a device+ if (FS.isChrdev(node.mode)) {+ flags &= ~512;+ }+ // if asked only for a directory, then this must be one+ if ((flags & 65536) && !FS.isDir(node.mode)) {+ throw new FS.ErrnoError(54);+ }+ // check permissions, if this is not a file we just created now (it is ok to+ // create and write to a file with read-only permissions; it is read-only+ // for later use)+ if (!created) {+ var errCode = FS.mayOpen(node, flags);+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ }+ // do truncation if necessary+ if ((flags & 512) && !created) {+ FS.truncate(node, 0);+ }+ // we've already handled these, don't pass down to the underlying vfs+ flags &= ~(128 | 512 | 131072);+ // register the stream with the filesystem+ var stream = FS.createStream({+ node,+ path: FS.getPath(node),+ // we want the absolute path to the node+ flags,+ seekable: true,+ position: 0,+ stream_ops: node.stream_ops,+ // used by the file family libc calls (fopen, fwrite, ferror, etc.)+ ungotten: [],+ error: false+ });+ // call the new stream's open function+ if (stream.stream_ops.open) {+ stream.stream_ops.open(stream);+ }+ if (created) {+ FS.chmod(node, mode & 511);+ }+ return stream;+ },+ close(stream) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (stream.getdents) stream.getdents = null;+ // free readdir state+ try {+ if (stream.stream_ops.close) {+ stream.stream_ops.close(stream);+ }+ } catch (e) {+ throw e;+ } finally {+ FS.closeStream(stream.fd);+ }+ stream.fd = null;+ },+ isClosed(stream) {+ return stream.fd === null;+ },+ llseek(stream, offset, whence) {+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if (!stream.seekable || !stream.stream_ops.llseek) {+ throw new FS.ErrnoError(70);+ }+ if (whence != 0 && whence != 1 && whence != 2) {+ throw new FS.ErrnoError(28);+ }+ stream.position = stream.stream_ops.llseek(stream, offset, whence);+ stream.ungotten = [];+ return stream.position;+ },+ read(stream, buffer, offset, length, position) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.read) {+ throw new FS.ErrnoError(28);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);+ if (!seeking) stream.position += bytesRead;+ return bytesRead;+ },+ write(stream, buffer, offset, length, position, canOwn) {+ if (length < 0 || position < 0) {+ throw new FS.ErrnoError(28);+ }+ if (FS.isClosed(stream)) {+ throw new FS.ErrnoError(8);+ }+ if ((stream.flags & 2097155) === 0) {+ throw new FS.ErrnoError(8);+ }+ if (FS.isDir(stream.node.mode)) {+ throw new FS.ErrnoError(31);+ }+ if (!stream.stream_ops.write) {+ throw new FS.ErrnoError(28);+ }+ if (stream.seekable && stream.flags & 1024) {+ // seek to the end before writing in append mode+ FS.llseek(stream, 0, 2);+ }+ var seeking = typeof position != "undefined";+ if (!seeking) {+ position = stream.position;+ } else if (!stream.seekable) {+ throw new FS.ErrnoError(70);+ }+ var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);+ if (!seeking) stream.position += bytesWritten;+ return bytesWritten;+ },+ mmap(stream, length, position, prot, flags) {+ // User requests writing to file (prot & PROT_WRITE != 0).+ // Checking if we have permissions to write to the file unless+ // MAP_PRIVATE flag is set. According to POSIX spec it is possible+ // to write to file opened in read-only mode with MAP_PRIVATE flag,+ // as all modifications will be visible only in the memory of+ // the current process.+ if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {+ throw new FS.ErrnoError(2);+ }+ if ((stream.flags & 2097155) === 1) {+ throw new FS.ErrnoError(2);+ }+ if (!stream.stream_ops.mmap) {+ throw new FS.ErrnoError(43);+ }+ if (!length) {+ throw new FS.ErrnoError(28);+ }+ return stream.stream_ops.mmap(stream, length, position, prot, flags);+ },+ msync(stream, buffer, offset, length, mmapFlags) {+ if (!stream.stream_ops.msync) {+ return 0;+ }+ return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);+ },+ ioctl(stream, cmd, arg) {+ if (!stream.stream_ops.ioctl) {+ throw new FS.ErrnoError(59);+ }+ return stream.stream_ops.ioctl(stream, cmd, arg);+ },+ readFile(path, opts = {}) {+ opts.flags = opts.flags || 0;+ opts.encoding = opts.encoding || "binary";+ if (opts.encoding !== "utf8" && opts.encoding !== "binary") {+ abort(`Invalid encoding type "${opts.encoding}"`);+ }+ var stream = FS.open(path, opts.flags);+ var stat = FS.stat(path);+ var length = stat.size;+ var buf = new Uint8Array(length);+ FS.read(stream, buf, 0, length, 0);+ if (opts.encoding === "utf8") {+ buf = UTF8ArrayToString(buf);+ }+ FS.close(stream);+ return buf;+ },+ writeFile(path, data, opts = {}) {+ opts.flags = opts.flags || 577;+ var stream = FS.open(path, opts.flags, opts.mode);+ data = FS_fileDataToTypedArray(data);+ FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);+ FS.close(stream);+ },+ cwd: () => FS.currentPath,+ chdir(path) {+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ if (lookup.node === null) {+ throw new FS.ErrnoError(44);+ }+ if (!FS.isDir(lookup.node.mode)) {+ throw new FS.ErrnoError(54);+ }+ var errCode = FS.nodePermissions(lookup.node, "x");+ if (errCode) {+ throw new FS.ErrnoError(errCode);+ }+ FS.currentPath = lookup.path;+ },+ createDefaultDirectories() {+ FS.mkdir("/tmp");+ FS.mkdir("/home");+ FS.mkdir("/home/web_user");+ },+ createDefaultDevices() {+ // create /dev+ FS.mkdir("/dev");+ // setup /dev/null+ FS.registerDevice(FS.makedev(1, 3), {+ read: () => 0,+ write: (stream, buffer, offset, length, pos) => length,+ llseek: () => 0+ });+ FS.mkdev("/dev/null", FS.makedev(1, 3));+ // setup /dev/tty and /dev/tty1+ // stderr needs to print output using err() rather than out()+ // so we register a second tty just for it.+ TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);+ TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);+ FS.mkdev("/dev/tty", FS.makedev(5, 0));+ FS.mkdev("/dev/tty1", FS.makedev(6, 0));+ // setup /dev/[u]random+ // use a buffer to avoid overhead of individual crypto calls per byte+ var randomBuffer = new Uint8Array(1024), randomLeft = 0;+ var randomByte = () => {+ if (randomLeft === 0) {+ randomFill(randomBuffer);+ randomLeft = randomBuffer.byteLength;+ }+ return randomBuffer[--randomLeft];+ };+ FS.createDevice("/dev", "random", randomByte);+ FS.createDevice("/dev", "urandom", randomByte);+ // we're not going to emulate the actual shm device,+ // just create the tmp dirs that reside in it commonly+ FS.mkdir("/dev/shm");+ FS.mkdir("/dev/shm/tmp");+ },+ createSpecialDirectories() {+ // create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the+ // name of the stream for fd 6 (see test_unistd_ttyname)+ FS.mkdir("/proc");+ var proc_self = FS.mkdir("/proc/self");+ FS.mkdir("/proc/self/fd");+ FS.mount({+ mount() {+ var node = FS.createNode(proc_self, "fd", 16895, 73);+ node.stream_ops = {+ llseek: MEMFS.stream_ops.llseek+ };+ node.node_ops = {+ lookup(parent, name) {+ var fd = +name;+ var stream = FS.getStreamChecked(fd);+ var ret = {+ parent: null,+ mount: {+ mountpoint: "fake"+ },+ node_ops: {+ readlink: () => stream.path+ },+ id: fd + 1+ };+ ret.parent = ret;+ // make it look like a simple root node+ return ret;+ },+ readdir() {+ return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString());+ }+ };+ return node;+ }+ }, {}, "/proc/self/fd");+ },+ createStandardStreams(input, output, error) {+ // TODO deprecate the old functionality of a single+ // input / output callback and that utilizes FS.createDevice+ // and instead require a unique set of stream ops+ // by default, we symlink the standard streams to the+ // default tty devices. however, if the standard streams+ // have been overwritten we create a unique device for+ // them instead.+ if (input) {+ FS.createDevice("/dev", "stdin", input);+ } else {+ FS.symlink("/dev/tty", "/dev/stdin");+ }+ if (output) {+ FS.createDevice("/dev", "stdout", null, output);+ } else {+ FS.symlink("/dev/tty", "/dev/stdout");+ }+ if (error) {+ FS.createDevice("/dev", "stderr", null, error);+ } else {+ FS.symlink("/dev/tty1", "/dev/stderr");+ }+ // open default streams for the stdin, stdout and stderr devices+ var stdin = FS.open("/dev/stdin", 0);+ var stdout = FS.open("/dev/stdout", 1);+ var stderr = FS.open("/dev/stderr", 1);+ },+ staticInit() {+ FS.nameTable = new Array(4096);+ FS.mount(MEMFS, {}, "/");+ FS.createDefaultDirectories();+ FS.createDefaultDevices();+ FS.createSpecialDirectories();+ FS.filesystems = {+ "MEMFS": MEMFS+ };+ },+ init(input, output, error) {+ FS.initialized = true;+ // Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here+ input ??= Module["stdin"];+ output ??= Module["stdout"];+ error ??= Module["stderr"];+ FS.createStandardStreams(input, output, error);+ },+ quit() {+ FS.initialized = false;+ // force-flush all streams, so we get musl std streams printed out+ // close all of our streams+ for (var stream of FS.streams) {+ if (stream) {+ FS.close(stream);+ }+ }+ },+ findObject(path, dontResolveLastLink) {+ var ret = FS.analyzePath(path, dontResolveLastLink);+ if (!ret.exists) {+ return null;+ }+ return ret.object;+ },+ analyzePath(path, dontResolveLastLink) {+ // operate from within the context of the symlink's target+ try {+ var lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ path = lookup.path;+ } catch (e) {}+ var ret = {+ isRoot: false,+ exists: false,+ error: 0,+ name: null,+ path: null,+ object: null,+ parentExists: false,+ parentPath: null,+ parentObject: null+ };+ try {+ var lookup = FS.lookupPath(path, {+ parent: true+ });+ ret.parentExists = true;+ ret.parentPath = lookup.path;+ ret.parentObject = lookup.node;+ ret.name = PATH.basename(path);+ lookup = FS.lookupPath(path, {+ follow: !dontResolveLastLink+ });+ ret.exists = true;+ ret.path = lookup.path;+ ret.object = lookup.node;+ ret.name = lookup.node.name;+ ret.isRoot = lookup.path === "/";+ } catch (e) {+ ret.error = e.errno;+ }+ return ret;+ },+ createPath(parent, path, canRead, canWrite) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ var parts = path.split("/").reverse();+ while (parts.length) {+ var part = parts.pop();+ if (!part) continue;+ var current = PATH.join2(parent, part);+ try {+ FS.mkdir(current);+ } catch (e) {+ if (e.errno != 20) throw e;+ }+ parent = current;+ }+ return current;+ },+ createFile(parent, name, properties, canRead, canWrite) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(canRead, canWrite);+ return FS.create(path, mode);+ },+ createDataFile(parent, name, data, canRead, canWrite, canOwn) {+ var path = name;+ if (parent) {+ parent = typeof parent == "string" ? parent : FS.getPath(parent);+ path = name ? PATH.join2(parent, name) : parent;+ }+ var mode = FS_getMode(canRead, canWrite);+ var node = FS.create(path, mode);+ if (data) {+ data = FS_fileDataToTypedArray(data);+ // make sure we can write to the file+ FS.chmod(node, mode | 146);+ var stream = FS.open(node, 577);+ FS.write(stream, data, 0, data.length, 0, canOwn);+ FS.close(stream);+ FS.chmod(node, mode);+ }+ },+ createDevice(parent, name, input, output) {+ var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name);+ var mode = FS_getMode(!!input, !!output);+ FS.createDevice.major ??= 64;+ var dev = FS.makedev(FS.createDevice.major++, 0);+ // Create a fake device that a set of stream ops to emulate+ // the old behavior.+ FS.registerDevice(dev, {+ open(stream) {+ stream.seekable = false;+ },+ close(stream) {+ // flush any pending line data+ if (output?.buffer?.length) {+ output(10);+ }+ },+ read(stream, buffer, offset, length, pos) {+ var bytesRead = 0;+ for (var i = 0; i < length; i++) {+ var result;+ try {+ result = input();+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ if (result === undefined && bytesRead === 0) {+ throw new FS.ErrnoError(6);+ }+ if (result === null || result === undefined) break;+ bytesRead++;+ buffer[offset + i] = result;+ }+ if (bytesRead) {+ stream.node.atime = Date.now();+ }+ return bytesRead;+ },+ write(stream, buffer, offset, length, pos) {+ for (var i = 0; i < length; i++) {+ try {+ output(buffer[offset + i]);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ if (length) {+ stream.node.mtime = stream.node.ctime = Date.now();+ }+ return i;+ }+ });+ return FS.mkdev(path, mode, dev);+ },+ forceLoadFile(obj) {+ if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;+ if (globalThis.XMLHttpRequest) {+ abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");+ } else {+ // Command-line.+ try {+ obj.contents = readBinary(obj.url);+ } catch (e) {+ throw new FS.ErrnoError(29);+ }+ }+ },+ createLazyFile(parent, name, url, canRead, canWrite) {+ // Lazy chunked Uint8Array (implements get and length from Uint8Array).+ // Actual getting is abstracted away for eventual reuse.+ class LazyUint8Array {+ lengthKnown=false;+ chunks=[];+ // Loaded chunks. Index is the chunk number+ get(idx) {+ if (idx > this.length - 1 || idx < 0) {+ return undefined;+ }+ var chunkOffset = idx % this.chunkSize;+ var chunkNum = (idx / this.chunkSize) | 0;+ return this.getter(chunkNum)[chunkOffset];+ }+ setDataGetter(getter) {+ this.getter = getter;+ }+ cacheLength() {+ // Find length+ var xhr = new XMLHttpRequest;+ xhr.open("HEAD", url, false);+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ var datalength = Number(xhr.getResponseHeader("Content-length"));+ var header;+ var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";+ var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";+ var chunkSize = 1024 * 1024;+ // Chunk size in bytes+ if (!hasByteServing) chunkSize = datalength;+ // Function to get a range from the remote URL.+ var doXHR = (from, to) => {+ if (from > to) abort("invalid range (" + from + ", " + to + ") or no bytes requested!");+ if (to > datalength - 1) abort("only " + datalength + " bytes available! programmer error!");+ // TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.+ var xhr = new XMLHttpRequest;+ xhr.open("GET", url, false);+ if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);+ // Some hints to the browser that we want binary data.+ xhr.responseType = "arraybuffer";+ if (xhr.overrideMimeType) {+ xhr.overrideMimeType("text/plain; charset=x-user-defined");+ }+ xhr.send(null);+ if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) abort("Couldn't load " + url + ". Status: " + xhr.status);+ if (xhr.response !== undefined) {+ return new Uint8Array(/** @type{Array<number>} */ (xhr.response || []));+ }+ return intArrayFromString(xhr.responseText || "", true);+ };+ var lazyArray = this;+ lazyArray.setDataGetter(chunkNum => {+ var start = chunkNum * chunkSize;+ var end = (chunkNum + 1) * chunkSize - 1;+ // including this byte+ end = Math.min(end, datalength - 1);+ // if datalength-1 is selected, this is the last block+ if (typeof lazyArray.chunks[chunkNum] == "undefined") {+ lazyArray.chunks[chunkNum] = doXHR(start, end);+ }+ if (typeof lazyArray.chunks[chunkNum] == "undefined") abort("doXHR failed!");+ return lazyArray.chunks[chunkNum];+ });+ if (usesGzip || !datalength) {+ // if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length+ chunkSize = datalength = 1;+ // this will force getter(0)/doXHR do download the whole file+ datalength = this.getter(0).length;+ chunkSize = datalength;+ out("LazyFiles on gzip forces download of the whole file when length is accessed");+ }+ this._length = datalength;+ this._chunkSize = chunkSize;+ this.lengthKnown = true;+ }+ get length() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._length;+ }+ get chunkSize() {+ if (!this.lengthKnown) {+ this.cacheLength();+ }+ return this._chunkSize;+ }+ }+ if (globalThis.XMLHttpRequest) {+ if (!ENVIRONMENT_IS_WORKER) abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");+ var lazyArray = new LazyUint8Array;+ var properties = {+ isDevice: false,+ contents: lazyArray+ };+ } else {+ var properties = {+ isDevice: false,+ url+ };+ }+ var node = FS.createFile(parent, name, properties, canRead, canWrite);+ // This is a total hack, but I want to get this lazy file code out of the+ // core of MEMFS. If we want to keep this lazy file concept I feel it should+ // be its own thin LAZYFS proxying calls to MEMFS.+ if (properties.contents) {+ node.contents = properties.contents;+ } else if (properties.url) {+ node.contents = null;+ node.url = properties.url;+ }+ // Add a function that defers querying the file size until it is asked the first time.+ Object.defineProperties(node, {+ usedBytes: {+ get: function() {+ return this.contents.length;+ }+ }+ });+ // override each stream op with one that tries to force load the lazy file first+ var stream_ops = {};+ for (const [key, fn] of Object.entries(node.stream_ops)) {+ stream_ops[key] = (...args) => {+ FS.forceLoadFile(node);+ return fn(...args);+ };+ }+ function writeChunks(stream, buffer, offset, length, position) {+ var contents = stream.node.contents;+ if (position >= contents.length) return 0;+ var size = Math.min(contents.length - position, length);+ if (contents.slice) {+ // normal array+ for (var i = 0; i < size; i++) {+ buffer[offset + i] = contents[position + i];+ }+ } else {+ for (var i = 0; i < size; i++) {+ // LazyUint8Array from sync binary XHR+ buffer[offset + i] = contents.get(position + i);+ }+ }+ return size;+ }+ // use a custom read function+ stream_ops.read = (stream, buffer, offset, length, position) => {+ FS.forceLoadFile(node);+ return writeChunks(stream, buffer, offset, length, position);+ };+ // use a custom mmap function+ stream_ops.mmap = (stream, length, position, prot, flags) => {+ FS.forceLoadFile(node);+ var ptr = mmapAlloc(length);+ if (!ptr) {+ throw new FS.ErrnoError(48);+ }+ writeChunks(stream, HEAP8, ptr, length, position);+ return {+ ptr,+ allocated: true+ };+ };+ node.stream_ops = stream_ops;+ return node;+ }+};++/**+ * Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the+ * emscripten HEAP, returns a copy of that string as a Javascript String object.+ *+ * @param {number} ptr+ * @param {number=} maxBytesToRead - An optional length that specifies the+ * maximum number of bytes to read. You can omit this parameter to scan the+ * string until the first 0 byte. If maxBytesToRead is passed, and the string+ * at [ptr, ptr+maxBytesToReadr[ contains a null byte in the middle, then the+ * string will cut short at that byte index.+ * @param {boolean=} ignoreNul - If true, the function will not stop on a NUL character.+ * @return {string}+ */ var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => {+ if (!ptr) return "";+ var end = findStringEnd(HEAPU8, ptr, maxBytesToRead, ignoreNul);+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));+};++var SYSCALLS = {+ calculateAt(dirfd, path, allowEmpty) {+ if (PATH.isAbs(path)) {+ return path;+ }+ // relative path+ var dir;+ if (dirfd === -100) {+ dir = FS.cwd();+ } else {+ var dirstream = SYSCALLS.getStreamFromFD(dirfd);+ dir = dirstream.path;+ }+ if (path.length == 0) {+ if (!allowEmpty) {+ throw new FS.ErrnoError(44);+ }+ return dir;+ }+ return dir + "/" + path;+ },+ writeStat(buf, stat) {+ HEAPU32[((buf) >> 2)] = stat.dev;+ HEAPU32[(((buf) + (4)) >> 2)] = stat.mode;+ HEAPU32[(((buf) + (8)) >> 2)] = stat.nlink;+ HEAPU32[(((buf) + (12)) >> 2)] = stat.uid;+ HEAPU32[(((buf) + (16)) >> 2)] = stat.gid;+ HEAPU32[(((buf) + (20)) >> 2)] = stat.rdev;+ (tempI64 = [ stat.size >>> 0, (tempDouble = stat.size, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ HEAP32[(((buf) + (32)) >> 2)] = 4096;+ HEAP32[(((buf) + (36)) >> 2)] = stat.blocks;+ var atime = stat.atime.getTime();+ var mtime = stat.mtime.getTime();+ var ctime = stat.ctime.getTime();+ (tempI64 = [ Math.floor(atime / 1e3) >>> 0, (tempDouble = Math.floor(atime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = (atime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(mtime / 1e3) >>> 0, (tempDouble = Math.floor(mtime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (56)) >> 2)] = tempI64[0], HEAP32[(((buf) + (60)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (64)) >> 2)] = (mtime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ Math.floor(ctime / 1e3) >>> 0, (tempDouble = Math.floor(ctime / 1e3),+ (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (72)) >> 2)] = tempI64[0], HEAP32[(((buf) + (76)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (80)) >> 2)] = (ctime % 1e3) * 1e3 * 1e3;+ (tempI64 = [ stat.ino >>> 0, (tempDouble = stat.ino, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (88)) >> 2)] = tempI64[0], HEAP32[(((buf) + (92)) >> 2)] = tempI64[1]);+ return 0;+ },+ writeStatFs(buf, stats) {+ HEAPU32[(((buf) + (4)) >> 2)] = stats.bsize;+ HEAPU32[(((buf) + (60)) >> 2)] = stats.bsize;+ (tempI64 = [ stats.blocks >>> 0, (tempDouble = stats.blocks, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (8)) >> 2)] = tempI64[0], HEAP32[(((buf) + (12)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bfree >>> 0, (tempDouble = stats.bfree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (16)) >> 2)] = tempI64[0], HEAP32[(((buf) + (20)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.bavail >>> 0, (tempDouble = stats.bavail, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (24)) >> 2)] = tempI64[0], HEAP32[(((buf) + (28)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.files >>> 0, (tempDouble = stats.files, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (32)) >> 2)] = tempI64[0], HEAP32[(((buf) + (36)) >> 2)] = tempI64[1]);+ (tempI64 = [ stats.ffree >>> 0, (tempDouble = stats.ffree, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[(((buf) + (40)) >> 2)] = tempI64[0], HEAP32[(((buf) + (44)) >> 2)] = tempI64[1]);+ HEAPU32[(((buf) + (48)) >> 2)] = stats.fsid;+ HEAPU32[(((buf) + (64)) >> 2)] = stats.flags;+ // ST_NOSUID+ HEAPU32[(((buf) + (56)) >> 2)] = stats.namelen;+ },+ doMsync(addr, stream, len, flags, offset) {+ if (!FS.isFile(stream.node.mode)) {+ throw new FS.ErrnoError(43);+ }+ if (flags & 2) {+ // MAP_PRIVATE calls need not to be synced back to underlying fs+ return 0;+ }+ var buffer = HEAPU8.slice(addr, addr + len);+ FS.msync(stream, buffer, offset, len, flags);+ },+ getStreamFromFD(fd) {+ var stream = FS.getStreamChecked(fd);+ return stream;+ },+ varargs: undefined,+ getStr(ptr) {+ var ret = UTF8ToString(ptr);+ return ret;+ }+};++function ___syscall_dup(fd) {+ try {+ var old = SYSCALLS.getStreamFromFD(fd);+ return FS.dupStream(old).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_faccessat(dirfd, path, amode, flags) {+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ if (amode & ~7) {+ // need a valid mode+ return -28;+ }+ var lookup = FS.lookupPath(path, {+ follow: true+ });+ var node = lookup.node;+ if (!node) {+ return -44;+ }+ var perms = "";+ if (amode & 4) perms += "r";+ if (amode & 2) perms += "w";+ if (amode & 1) perms += "x";+ if (perms && FS.nodePermissions(node, perms)) {+ return -2;+ }+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var syscallGetVarargI = () => {+ // the `+` prepended here is necessary to convince the JSCompiler that varargs is indeed a number.+ var ret = HEAP32[((+SYSCALLS.varargs) >> 2)];+ SYSCALLS.varargs += 4;+ return ret;+};++var syscallGetVarargP = syscallGetVarargI;++function ___syscall_fcntl64(fd, cmd, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (cmd) {+ case 0:+ {+ var arg = syscallGetVarargI();+ if (arg < 0) {+ return -28;+ }+ while (FS.streams[arg]) {+ arg++;+ }+ var newStream;+ newStream = FS.dupStream(stream, arg);+ return newStream.fd;+ }++ case 1:+ case 2:+ return 0;++ // FD_CLOEXEC makes no sense for a single process.+ case 3:+ return stream.flags;++ case 4:+ {+ var arg = syscallGetVarargI();+ stream.flags |= arg;+ return 0;+ }++ case 12:+ {+ var arg = syscallGetVarargP();+ var offset = 0;+ // We're always unlocked.+ HEAP16[(((arg) + (offset)) >> 1)] = 2;+ return 0;+ }++ case 13:+ case 14:+ // Pretend that the locking is successful. These are process-level locks,+ // and Emscripten programs are a single process. If we supported linking a+ // filesystem between programs, we'd need to do more here.+ // See https://github.com/emscripten-core/emscripten/issues/23697+ return 0;+ }+ return -28;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_fstat64(fd, buf) {+ try {+ return SYSCALLS.writeStat(buf, FS.fstat(fd));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var convertI32PairToI53Checked = (lo, hi) => ((hi + 2097152) >>> 0 < 4194305 - !!lo) ? (lo >>> 0) + hi * 4294967296 : NaN;++function ___syscall_ftruncate64(fd, length_low, length_high) {+ var length = convertI32PairToI53Checked(length_low, length_high);+ try {+ if (isNaN(length)) return -61;+ FS.ftruncate(fd, length);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_ioctl(fd, op, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ switch (op) {+ case 21509:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21505:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcgets) {+ var termios = stream.tty.ops.ioctl_tcgets(stream);+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = termios.c_iflag || 0;+ HEAP32[(((argp) + (4)) >> 2)] = termios.c_oflag || 0;+ HEAP32[(((argp) + (8)) >> 2)] = termios.c_cflag || 0;+ HEAP32[(((argp) + (12)) >> 2)] = termios.c_lflag || 0;+ for (var i = 0; i < 32; i++) {+ HEAP8[(argp + i) + (17)] = termios.c_cc[i] || 0;+ }+ return 0;+ }+ return 0;+ }++ case 21510:+ case 21511:+ case 21512:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ case 21506:+ case 21507:+ case 21508:+ {+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tcsets) {+ var argp = syscallGetVarargP();+ var c_iflag = HEAP32[((argp) >> 2)];+ var c_oflag = HEAP32[(((argp) + (4)) >> 2)];+ var c_cflag = HEAP32[(((argp) + (8)) >> 2)];+ var c_lflag = HEAP32[(((argp) + (12)) >> 2)];+ var c_cc = [];+ for (var i = 0; i < 32; i++) {+ c_cc.push(HEAP8[(argp + i) + (17)]);+ }+ return stream.tty.ops.ioctl_tcsets(stream.tty, op, {+ c_iflag,+ c_oflag,+ c_cflag,+ c_lflag,+ c_cc+ });+ }+ return 0;+ }++ case 21519:+ {+ if (!stream.tty) return -59;+ var argp = syscallGetVarargP();+ HEAP32[((argp) >> 2)] = 0;+ return 0;+ }++ case 21520:+ {+ if (!stream.tty) return -59;+ return -28;+ }++ case 21537:+ case 21531:+ {+ var argp = syscallGetVarargP();+ return FS.ioctl(stream, op, argp);+ }++ case 21523:+ {+ // TODO: in theory we should write to the winsize struct that gets+ // passed in, but for now musl doesn't read anything on it+ if (!stream.tty) return -59;+ if (stream.tty.ops.ioctl_tiocgwinsz) {+ var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);+ var argp = syscallGetVarargP();+ HEAP16[((argp) >> 1)] = winsize[0];+ HEAP16[(((argp) + (2)) >> 1)] = winsize[1];+ }+ return 0;+ }++ case 21524:+ {+ // TODO: technically, this ioctl call should change the window size.+ // but, since emscripten doesn't have any concept of a terminal window+ // yet, we'll just silently throw it away as we do TIOCGWINSZ+ if (!stream.tty) return -59;+ return 0;+ }++ case 21515:+ {+ if (!stream.tty) return -59;+ return 0;+ }++ default:+ return -28;+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_lstat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.lstat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_newfstatat(dirfd, path, buf, flags) {+ try {+ path = SYSCALLS.getStr(path);+ var nofollow = flags & 256;+ var allowEmpty = flags & 4096;+ flags = flags & (~6400);+ path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);+ return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_openat(dirfd, path, flags, varargs) {+ SYSCALLS.varargs = varargs;+ try {+ path = SYSCALLS.getStr(path);+ path = SYSCALLS.calculateAt(dirfd, path);+ var mode = varargs ? syscallGetVarargI() : 0;+ return FS.open(path, flags, mode).fd;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function ___syscall_stat64(path, buf) {+ try {+ path = SYSCALLS.getStr(path);+ return SYSCALLS.writeStat(buf, FS.stat(path));+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __abort_js = () => abort("");++var __embind_register_bigint = (primitiveType, name, size, minRange, maxRange) => {};++var AsciiToString = ptr => {+ var str = "";+ while (1) {+ var ch = HEAPU8[ptr++];+ if (!ch) return str;+ str += String.fromCharCode(ch);+ }+};++var awaitingDependencies = {};++var registeredTypes = {};++var typeDependencies = {};++var BindingError = class BindingError extends Error {+ constructor(message) {+ super(message);+ this.name = "BindingError";+ }+};++var throwBindingError = message => {+ throw new BindingError(message);+};++/** @param {Object=} options */ function sharedRegisterType(rawType, registeredInstance, options = {}) {+ var name = registeredInstance.name;+ if (!rawType) {+ throwBindingError(`type "${name}" must have a positive integer typeid pointer`);+ }+ if (registeredTypes.hasOwnProperty(rawType)) {+ if (options.ignoreDuplicateRegistrations) {+ return;+ } else {+ throwBindingError(`Cannot register type '${name}' twice`);+ }+ }+ registeredTypes[rawType] = registeredInstance;+ delete typeDependencies[rawType];+ if (awaitingDependencies.hasOwnProperty(rawType)) {+ var callbacks = awaitingDependencies[rawType];+ delete awaitingDependencies[rawType];+ callbacks.forEach(cb => cb());+ }+}++/** @param {Object=} options */ function registerType(rawType, registeredInstance, options = {}) {+ return sharedRegisterType(rawType, registeredInstance, options);+}++/** @suppress {globalThis} */ var __embind_register_bool = (rawType, name, trueValue, falseValue) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: function(wt) {+ // ambiguous emscripten ABI: sometimes return values are+ // true or false, and sometimes integers (0 or 1)+ return !!wt;+ },+ toWireType: function(destructors, o) {+ return o ? trueValue : falseValue;+ },+ readValueFromPointer: function(pointer) {+ return this.fromWireType(HEAPU8[pointer]);+ },+ destructorFunction: null+ });+};++var emval_freelist = [];++var emval_handles = [ 0, 1, , 1, null, 1, true, 1, false, 1 ];++var __emval_decref = handle => {+ if (handle > 9 && 0 === --emval_handles[handle + 1]) {+ var value = emval_handles[handle];+ emval_handles[handle] = undefined;+ emval_freelist.push(handle);+ }+};++var Emval = {+ toValue: handle => {+ if (!handle) {+ throwBindingError(`Cannot use deleted val. handle = ${handle}`);+ }+ return emval_handles[handle];+ },+ toHandle: value => {+ switch (value) {+ case undefined:+ return 2;++ case null:+ return 4;++ case true:+ return 6;++ case false:+ return 8;++ default:+ {+ const handle = emval_freelist.pop() || emval_handles.length;+ emval_handles[handle] = value;+ emval_handles[handle + 1] = 1;+ return handle;+ }+ }+ }+};++/** @suppress {globalThis} */ function readPointer(pointer) {+ return this.fromWireType(HEAPU32[((pointer) >> 2)]);+}++var EmValType = {+ name: "emscripten::val",+ fromWireType: handle => {+ var rv = Emval.toValue(handle);+ __emval_decref(handle);+ return rv;+ },+ toWireType: (destructors, value) => Emval.toHandle(value),+ readValueFromPointer: readPointer,+ destructorFunction: null+};++var __embind_register_emval = rawType => registerType(rawType, EmValType);++var floatReadValueFromPointer = (name, width) => {+ switch (width) {+ case 4:+ return function(pointer) {+ return this.fromWireType(HEAPF32[((pointer) >> 2)]);+ };++ case 8:+ return function(pointer) {+ return this.fromWireType(HEAPF64[((pointer) >> 3)]);+ };++ default:+ throw new TypeError(`invalid float width (${width}): ${name}`);+ }+};++var __embind_register_float = (rawType, name, size) => {+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: value => value,+ toWireType: (destructors, value) => value,+ readValueFromPointer: floatReadValueFromPointer(name, size),+ destructorFunction: null+ });+};++var integerReadValueFromPointer = (name, width, signed) => {+ // integers are quite common, so generate very specialized functions+ switch (width) {+ case 1:+ return signed ? pointer => HEAP8[pointer] : pointer => HEAPU8[pointer];++ case 2:+ return signed ? pointer => HEAP16[((pointer) >> 1)] : pointer => HEAPU16[((pointer) >> 1)];++ case 4:+ return signed ? pointer => HEAP32[((pointer) >> 2)] : pointer => HEAPU32[((pointer) >> 2)];++ default:+ throw new TypeError(`invalid integer width (${width}): ${name}`);+ }+};++/** @suppress {globalThis} */ var __embind_register_integer = (primitiveType, name, size, minRange, maxRange) => {+ name = AsciiToString(name);+ const isUnsignedType = minRange === 0;+ let fromWireType = value => value;+ if (isUnsignedType) {+ var bitshift = 32 - 8 * size;+ fromWireType = value => (value << bitshift) >>> bitshift;+ maxRange = fromWireType(maxRange);+ }+ registerType(primitiveType, {+ name,+ fromWireType,+ toWireType: (destructors, value) => value,+ readValueFromPointer: integerReadValueFromPointer(name, size, minRange !== 0),+ destructorFunction: null+ });+};++var __embind_register_memory_view = (rawType, dataTypeIndex, name) => {+ var typeMapping = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];+ var TA = typeMapping[dataTypeIndex];+ function decodeMemoryView(handle) {+ var size = HEAPU32[((handle) >> 2)];+ var data = HEAPU32[(((handle) + (4)) >> 2)];+ return new TA(HEAP8.buffer, data, size);+ }+ name = AsciiToString(name);+ registerType(rawType, {+ name,+ fromWireType: decodeMemoryView,+ readValueFromPointer: decodeMemoryView+ }, {+ ignoreDuplicateRegistrations: true+ });+};++var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);++var __embind_register_std_string = (rawType, name) => {+ name = AsciiToString(name);+ var stdStringIsUTF8 = true;+ registerType(rawType, {+ name,+ // For some method names we use string keys here since they are part of+ // the public/external API and/or used by the runtime-generated code.+ fromWireType(value) {+ var length = HEAPU32[((value) >> 2)];+ var payload = value + 4;+ var str;+ if (stdStringIsUTF8) {+ str = UTF8ToString(payload, length, true);+ } else {+ str = "";+ for (var i = 0; i < length; ++i) {+ str += String.fromCharCode(HEAPU8[payload + i]);+ }+ }+ _free(value);+ return str;+ },+ toWireType(destructors, value) {+ if (value instanceof ArrayBuffer) {+ value = new Uint8Array(value);+ }+ var length;+ var valueIsOfTypeString = (typeof value == "string");+ // We accept `string` or array views with single byte elements+ if (!(valueIsOfTypeString || (ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1))) {+ throwBindingError("Cannot pass non-string to std::string");+ }+ if (stdStringIsUTF8 && valueIsOfTypeString) {+ length = lengthBytesUTF8(value);+ } else {+ length = value.length;+ }+ // assumes POINTER_SIZE alignment+ var base = _malloc(4 + length + 1);+ var ptr = base + 4;+ HEAPU32[((base) >> 2)] = length;+ if (valueIsOfTypeString) {+ if (stdStringIsUTF8) {+ stringToUTF8(value, ptr, length + 1);+ } else {+ for (var i = 0; i < length; ++i) {+ var charCode = value.charCodeAt(i);+ if (charCode > 255) {+ _free(base);+ throwBindingError("String has UTF-16 code units that do not fit in 8 bits");+ }+ HEAPU8[ptr + i] = charCode;+ }+ }+ } else {+ HEAPU8.set(value, ptr);+ }+ if (destructors !== null) {+ destructors.push(_free, base);+ }+ return base;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var UTF16Decoder = new TextDecoder("utf-16le");++var UTF16ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var idx = ((ptr) >> 1);+ var endIdx = findStringEnd(HEAPU16, idx, maxBytesToRead / 2, ignoreNul);+ return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx));+};++var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 2) return 0;+ maxBytesToWrite -= 2;+ // Null terminator.+ var startPtr = outPtr;+ var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length;+ for (var i = 0; i < numCharsToWrite; ++i) {+ // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.+ var codeUnit = str.charCodeAt(i);+ // possibly a lead surrogate+ HEAP16[((outPtr) >> 1)] = codeUnit;+ outPtr += 2;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP16[((outPtr) >> 1)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF16 = str => str.length * 2;++var UTF32ToString = (ptr, maxBytesToRead, ignoreNul) => {+ var str = "";+ var startIdx = ((ptr) >> 2);+ // If maxBytesToRead is not passed explicitly, it will be undefined, and this+ // will always evaluate to true. This saves on code size.+ for (var i = 0; !(i >= maxBytesToRead / 4); i++) {+ var utf32 = HEAPU32[startIdx + i];+ if (!utf32 && !ignoreNul) break;+ str += String.fromCodePoint(utf32);+ }+ return str;+};++var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {+ // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.+ maxBytesToWrite ??= 2147483647;+ if (maxBytesToWrite < 4) return 0;+ var startPtr = outPtr;+ var endPtr = startPtr + maxBytesToWrite - 4;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ HEAP32[((outPtr) >> 2)] = codePoint;+ outPtr += 4;+ if (outPtr + 4 > endPtr) break;+ }+ // Null-terminate the pointer to the HEAP.+ HEAP32[((outPtr) >> 2)] = 0;+ return outPtr - startPtr;+};++var lengthBytesUTF32 = str => {+ var len = 0;+ for (var i = 0; i < str.length; ++i) {+ var codePoint = str.codePointAt(i);+ // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.+ // We need to manually skip over the second code unit for correct iteration.+ if (codePoint > 65535) {+ i++;+ }+ len += 4;+ }+ return len;+};++var __embind_register_std_wstring = (rawType, charSize, name) => {+ name = AsciiToString(name);+ var decodeString, encodeString, lengthBytesUTF;+ if (charSize === 2) {+ decodeString = UTF16ToString;+ encodeString = stringToUTF16;+ lengthBytesUTF = lengthBytesUTF16;+ } else {+ decodeString = UTF32ToString;+ encodeString = stringToUTF32;+ lengthBytesUTF = lengthBytesUTF32;+ }+ registerType(rawType, {+ name,+ fromWireType: value => {+ // Code mostly taken from _embind_register_std_string fromWireType+ var length = HEAPU32[((value) >> 2)];+ var str = decodeString(value + 4, length * charSize, true);+ _free(value);+ return str;+ },+ toWireType: (destructors, value) => {+ if (!(typeof value == "string")) {+ throwBindingError(`Cannot pass non-string to C++ string type ${name}`);+ }+ // assumes POINTER_SIZE alignment+ var length = lengthBytesUTF(value);+ var ptr = _malloc(4 + length + charSize);+ HEAPU32[((ptr) >> 2)] = length / charSize;+ encodeString(value, ptr + 4, length + charSize);+ if (destructors !== null) {+ destructors.push(_free, ptr);+ }+ return ptr;+ },+ readValueFromPointer: readPointer,+ destructorFunction(ptr) {+ _free(ptr);+ }+ });+};++var __embind_register_void = (rawType, name) => {+ name = AsciiToString(name);+ registerType(rawType, {+ isVoid: true,+ // void return values can be optimized out sometimes+ name,+ fromWireType: () => undefined,+ // TODO: assert if anything else is given?+ toWireType: (destructors, o) => undefined+ });+};++var emval_methodCallers = [];++var emval_addMethodCaller = caller => {+ var id = emval_methodCallers.length;+ emval_methodCallers.push(caller);+ return id;+};++var getTypeName = type => {+ var ptr = ___getTypeName(type);+ var rv = AsciiToString(ptr);+ _free(ptr);+ return rv;+};++var requireRegisteredType = (rawType, humanName) => {+ var impl = registeredTypes[rawType];+ if (undefined === impl) {+ throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);+ }+ return impl;+};++var emval_lookupTypes = (argCount, argTypes) => {+ var a = new Array(argCount);+ for (var i = 0; i < argCount; ++i) {+ a[i] = requireRegisteredType(HEAPU32[(((argTypes) + (i * 4)) >> 2)], `parameter ${i}`);+ }+ return a;+};++var createNamedFunction = (name, func) => Object.defineProperty(func, "name", {+ value: name+});++var emval_returnValue = (toReturnWire, destructorsRef, handle) => {+ var destructors = [];+ var result = toReturnWire(destructors, handle);+ if (destructors.length) {+ // void, primitives and any other types w/o destructors don't need to allocate a handle+ HEAPU32[((destructorsRef) >> 2)] = Emval.toHandle(destructors);+ }+ return result;+};++var emval_symbols = {};++var getStringOrSymbol = address => {+ var symbol = emval_symbols[address];+ if (symbol === undefined) {+ return AsciiToString(address);+ }+ return symbol;+};++var __emval_create_invoker = (argCount, argTypesPtr, kind) => {+ var GenericWireTypeSize = 8;+ var [retType, ...argTypes] = emval_lookupTypes(argCount, argTypesPtr);+ var toReturnWire = retType.toWireType.bind(retType);+ var argFromPtr = argTypes.map(type => type.readValueFromPointer.bind(type));+ argCount--;+ // remove the extracted return type+ var argN = new Array(argCount);+ var invokerFunction = (handle, methodName, destructorsRef, args) => {+ var offset = 0;+ for (var i = 0; i < argCount; ++i) {+ argN[i] = argFromPtr[i](args + offset);+ offset += GenericWireTypeSize;+ }+ var rv;+ switch (kind) {+ case 0:+ rv = Emval.toValue(handle).apply(null, argN);+ break;++ case 2:+ rv = Reflect.construct(Emval.toValue(handle), argN);+ break;++ case 3:+ // no-op, just return the argument+ rv = argN[0];+ break;++ case 1:+ rv = Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);+ break;+ }+ return emval_returnValue(toReturnWire, destructorsRef, rv);+ };+ var functionName = `methodCaller<(${argTypes.map(t => t.name)}) => ${retType.name}>`;+ return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction));+};++var __emval_get_global = name => {+ if (!name) {+ return Emval.toHandle(globalThis);+ }+ name = getStringOrSymbol(name);+ return Emval.toHandle(globalThis[name]);+};++var __emval_get_property = (handle, key) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ return Emval.toHandle(handle[key]);+};++var __emval_incref = handle => {+ if (handle > 9) {+ emval_handles[handle + 1] += 1;+ }+};++var __emval_instanceof = (object, constructor) => {+ object = Emval.toValue(object);+ constructor = Emval.toValue(constructor);+ return object instanceof constructor;+};++var __emval_invoke = (caller, handle, methodName, destructorsRef, args) => emval_methodCallers[caller](handle, methodName, destructorsRef, args);++var __emval_new_cstring = v => Emval.toHandle(getStringOrSymbol(v));++var runDestructors = destructors => {+ while (destructors.length) {+ var ptr = destructors.pop();+ var del = destructors.pop();+ del(ptr);+ }+};++var __emval_run_destructors = handle => {+ var destructors = Emval.toValue(handle);+ runDestructors(destructors);+ __emval_decref(handle);+};++var __emval_set_property = (handle, key, value) => {+ handle = Emval.toValue(handle);+ key = Emval.toValue(key);+ value = Emval.toValue(value);+ handle[key] = value;+};++var __emval_typeof = handle => {+ handle = Emval.toValue(handle);+ return Emval.toHandle(typeof handle);+};++function __gmtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getUTCSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getUTCMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getUTCHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getUTCDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getUTCMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getUTCFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getUTCDay();+ var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);+ var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+}++var isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);++var MONTH_DAYS_LEAP_CUMULATIVE = [ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ];++var MONTH_DAYS_REGULAR_CUMULATIVE = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ];++var ydayFromDate = date => {+ var leap = isLeapYear(date.getFullYear());+ var monthDaysCumulative = (leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE);+ var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;+ // -1 since it's days since Jan 1+ return yday;+};++function __localtime_js(time_low, time_high, tmPtr) {+ var time = convertI32PairToI53Checked(time_low, time_high);+ var date = new Date(time * 1e3);+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getFullYear() - 1900;+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ HEAP32[(((tmPtr) + (36)) >> 2)] = -(date.getTimezoneOffset() * 60);+ // Attention: DST is in December in South, and some regions don't have DST at all.+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;+ HEAP32[(((tmPtr) + (32)) >> 2)] = dst;+}++var setTempRet0 = val => __emscripten_tempret_set(val);++var __mktime_js = function(tmPtr) {+ var ret = (() => {+ var date = new Date(HEAP32[(((tmPtr) + (20)) >> 2)] + 1900, HEAP32[(((tmPtr) + (16)) >> 2)], HEAP32[(((tmPtr) + (12)) >> 2)], HEAP32[(((tmPtr) + (8)) >> 2)], HEAP32[(((tmPtr) + (4)) >> 2)], HEAP32[((tmPtr) >> 2)], 0);+ // There's an ambiguous hour when the time goes back; the tm_isdst field is+ // used to disambiguate it. Date() basically guesses, so we fix it up if it+ // guessed wrong, or fill in tm_isdst with the guess if it's -1.+ var dst = HEAP32[(((tmPtr) + (32)) >> 2)];+ var guessedOffset = date.getTimezoneOffset();+ var start = new Date(date.getFullYear(), 0, 1);+ var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();+ var winterOffset = start.getTimezoneOffset();+ var dstOffset = Math.min(winterOffset, summerOffset);+ // DST is in December in South+ if (dst < 0) {+ // Attention: some regions don't have DST at all.+ HEAP32[(((tmPtr) + (32)) >> 2)] = Number(summerOffset != winterOffset && dstOffset == guessedOffset);+ } else if ((dst > 0) != (dstOffset == guessedOffset)) {+ var nonDstOffset = Math.max(winterOffset, summerOffset);+ var trueOffset = dst > 0 ? dstOffset : nonDstOffset;+ // Don't try setMinutes(date.getMinutes() + ...) -- it's messed up.+ date.setTime(date.getTime() + (trueOffset - guessedOffset) * 6e4);+ }+ HEAP32[(((tmPtr) + (24)) >> 2)] = date.getDay();+ var yday = ydayFromDate(date) | 0;+ HEAP32[(((tmPtr) + (28)) >> 2)] = yday;+ // To match expected behavior, update fields from date+ HEAP32[((tmPtr) >> 2)] = date.getSeconds();+ HEAP32[(((tmPtr) + (4)) >> 2)] = date.getMinutes();+ HEAP32[(((tmPtr) + (8)) >> 2)] = date.getHours();+ HEAP32[(((tmPtr) + (12)) >> 2)] = date.getDate();+ HEAP32[(((tmPtr) + (16)) >> 2)] = date.getMonth();+ HEAP32[(((tmPtr) + (20)) >> 2)] = date.getYear();+ var timeMs = date.getTime();+ if (isNaN(timeMs)) {+ return -1;+ }+ // Return time in microseconds+ return timeMs / 1e3;+ })();+ return (setTempRet0((tempDouble = ret, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0)),+ ret >>> 0);+};++function __mmap_js(len, prot, flags, fd, offset_low, offset_high, allocated, addr) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var res = FS.mmap(stream, len, offset, prot, flags);+ var ptr = res.ptr;+ HEAP32[((allocated) >> 2)] = res.allocated;+ HEAPU32[((addr) >> 2)] = ptr;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++function __munmap_js(addr, len, prot, flags, fd, offset_low, offset_high) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ if (prot & 2) {+ SYSCALLS.doMsync(addr, stream, len, flags, offset);+ }+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return -e.errno;+ }+}++var __tzset_js = (timezone, daylight, std_name, dst_name) => {+ // TODO: Use (malleable) environment variables instead of system settings.+ var currentYear = (new Date).getFullYear();+ var winter = new Date(currentYear, 0, 1);+ var summer = new Date(currentYear, 6, 1);+ var winterOffset = winter.getTimezoneOffset();+ var summerOffset = summer.getTimezoneOffset();+ // Local standard timezone offset. Local standard time is not adjusted for+ // daylight savings. This code uses the fact that getTimezoneOffset returns+ // a greater value during Standard Time versus Daylight Saving Time (DST).+ // Thus it determines the expected output during Standard Time, and it+ // compares whether the output of the given date the same (Standard) or less+ // (DST).+ var stdTimezoneOffset = Math.max(winterOffset, summerOffset);+ // timezone is specified as seconds west of UTC ("The external variable+ // `timezone` shall be set to the difference, in seconds, between+ // Coordinated Universal Time (UTC) and local standard time."), the same+ // as returned by stdTimezoneOffset.+ // See http://pubs.opengroup.org/onlinepubs/009695399/functions/tzset.html+ HEAPU32[((timezone) >> 2)] = stdTimezoneOffset * 60;+ HEAP32[((daylight) >> 2)] = Number(winterOffset != summerOffset);+ var extractZone = timezoneOffset => {+ // Why inverse sign?+ // Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset+ var sign = timezoneOffset >= 0 ? "-" : "+";+ var absOffset = Math.abs(timezoneOffset);+ var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");+ var minutes = String(absOffset % 60).padStart(2, "0");+ return `UTC${sign}${hours}${minutes}`;+ };+ var winterName = extractZone(winterOffset);+ var summerName = extractZone(summerOffset);+ if (summerOffset < winterOffset) {+ // Northern hemisphere+ stringToUTF8(winterName, std_name, 17);+ stringToUTF8(summerName, dst_name, 17);+ } else {+ stringToUTF8(winterName, dst_name, 17);+ stringToUTF8(summerName, std_name, 17);+ }+};++var _emscripten_get_now = () => performance.now();++var _emscripten_date_now = () => Date.now();++var nowIsMonotonic = 1;++var checkWasiClock = clock_id => clock_id >= 0 && clock_id <= 3;++function _clock_time_get(clk_id, ignored_precision_low, ignored_precision_high, ptime) {+ var ignored_precision = convertI32PairToI53Checked(ignored_precision_low, ignored_precision_high);+ if (!checkWasiClock(clk_id)) {+ return 28;+ }+ var now;+ // all wasi clocks but realtime are monotonic+ if (clk_id === 0) {+ now = _emscripten_date_now();+ } else if (nowIsMonotonic) {+ now = _emscripten_get_now();+ } else {+ return 52;+ }+ // "now" is in ms, and wasi times are in ns.+ var nsec = Math.round(now * 1e3 * 1e3);+ (tempI64 = [ nsec >>> 0, (tempDouble = nsec, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((ptime) >> 2)] = tempI64[0], HEAP32[(((ptime) + (4)) >> 2)] = tempI64[1]);+ return 0;+}++var readEmAsmArgsArray = [];++var readEmAsmArgs = (sigPtr, buf) => {+ readEmAsmArgsArray.length = 0;+ var ch;+ // Most arguments are i32s, so shift the buffer pointer so it is a plain+ // index into HEAP32.+ while (ch = HEAPU8[sigPtr++]) {+ // Floats are always passed as doubles, so all types except for 'i'+ // are 8 bytes and require alignment.+ var wide = (ch != 105);+ wide &= (ch != 112);+ buf += wide && (buf % 8) ? 4 : 0;+ readEmAsmArgsArray.push(// Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode.+ ch == 112 ? HEAPU32[((buf) >> 2)] : ch == 105 ? HEAP32[((buf) >> 2)] : HEAPF64[((buf) >> 3)]);+ buf += wide ? 8 : 4;+ }+ return readEmAsmArgsArray;+};++var runEmAsmFunction = (code, sigPtr, argbuf) => {+ var args = readEmAsmArgs(sigPtr, argbuf);+ return ASM_CONSTS[code](...args);+};++var _emscripten_asm_const_int = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_asm_const_ptr = (code, sigPtr, argbuf) => runEmAsmFunction(code, sigPtr, argbuf);++var _emscripten_errn = (str, len) => err(UTF8ToString(str, len));++var getHeapMax = () => // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate+// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side+// for any code that deals with heap sizes, which would require special+// casing all heap size related code to treat 0 specially.+2147483648;++var _emscripten_get_heap_max = () => getHeapMax();++var _emscripten_has_asyncify = () => 0;++var _emscripten_outn = (str, len) => out(UTF8ToString(str, len));++var UNWIND_CACHE = {};++var stringToNewUTF8 = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = _malloc(size);+ if (ret) stringToUTF8(str, ret, size);+ return ret;+};++/** @returns {number} */ var convertFrameToPC = frame => {+ var match;+ if (match = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(frame)) {+ // Wasm engines give the binary offset directly, so we use that as return address+ return +match[1];+ } else if (match = /:(\d+):\d+(?:\)|$)/.exec(frame)) {+ // If we are in js, we can use the js line number as the "return address".+ // This should work for wasm2js. We tag the high bit to distinguish this+ // from wasm addresses.+ return 2147483648 | +match[1];+ }+ // return 0 if we can't find any+ return 0;+};++var saveInUnwindCache = callstack => {+ for (var line of callstack) {+ var pc = convertFrameToPC(line);+ if (pc) {+ UNWIND_CACHE[pc] = line;+ }+ }+};++var jsStackTrace = () => (new Error).stack.toString();++var _emscripten_stack_snapshot = () => {+ var callstack = jsStackTrace().split("\n");+ if (callstack[0] == "Error") {+ callstack.shift();+ }+ saveInUnwindCache(callstack);+ // Caches the stack snapshot so that emscripten_stack_unwind_buffer() can+ // unwind from this spot.+ UNWIND_CACHE.last_addr = convertFrameToPC(callstack[3]);+ UNWIND_CACHE.last_stack = callstack;+ return UNWIND_CACHE.last_addr;+};++var _emscripten_pc_get_function = pc => {+ var frame = UNWIND_CACHE[pc];+ if (!frame) return 0;+ var name;+ var match;+ // First try to match foo.wasm.sym files explcitly. e.g.+ // at test_return_address.wasm.main (wasm://wasm/test_return_address.wasm-0012cc2a:wasm-function[26]:0x9f3+ // Then match JS symbols which don't include that module name:+ // at invokeEntryPoint (.../test_return_address.js:1500:42)+ // Finally match firefox format:+ // Object._main@http://server.com:4324:12'+ if (match = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^\s+at (.*) \(.*\)$/.exec(frame)) {+ name = match[1];+ } else if (match = /^(.+?)@/.exec(frame)) {+ name = match[1];+ } else {+ return 0;+ }+ _free(_emscripten_pc_get_function.ret ?? 0);+ _emscripten_pc_get_function.ret = stringToNewUTF8(name);+ return _emscripten_pc_get_function.ret;+};++var growMemory = size => {+ var oldHeapSize = wasmMemory.buffer.byteLength;+ var pages = ((size - oldHeapSize + 65535) / 65536) | 0;+ try {+ // round size grow request up to wasm page size (fixed 64KB per spec)+ wasmMemory.grow(pages);+ // .grow() takes a delta compared to the previous size+ updateMemoryViews();+ return 1;+ } catch (e) {}+};++var _emscripten_resize_heap = requestedSize => {+ var oldSize = HEAPU8.length;+ // With CAN_ADDRESS_2GB or MEMORY64, pointers are already unsigned.+ requestedSize >>>= 0;+ // With multithreaded builds, races can happen (another thread might increase the size+ // in between), so return a failure, and let the caller retry.+ // Memory resize rules:+ // 1. Always increase heap size to at least the requested size, rounded up+ // to next page multiple.+ // 2a. If MEMORY_GROWTH_LINEAR_STEP == -1, excessively resize the heap+ // geometrically: increase the heap size according to+ // MEMORY_GROWTH_GEOMETRIC_STEP factor (default +20%), At most+ // overreserve by MEMORY_GROWTH_GEOMETRIC_CAP bytes (default 96MB).+ // 2b. If MEMORY_GROWTH_LINEAR_STEP != -1, excessively resize the heap+ // linearly: increase the heap size by at least+ // MEMORY_GROWTH_LINEAR_STEP bytes.+ // 3. Max size for the heap is capped at 2048MB-WASM_PAGE_SIZE, or by+ // MAXIMUM_MEMORY, or by ASAN limit, depending on which is smallest+ // 4. If we were unable to allocate as much memory, it may be due to+ // over-eager decision to excessively reserve due to (3) above.+ // Hence if an allocation fails, cut down on the amount of excess+ // growth, in an attempt to succeed to perform a smaller allocation.+ // A limit is set for how much we can grow. We should not exceed that+ // (the wasm binary specifies it, so if we tried, we'd fail anyhow).+ var maxHeapSize = getHeapMax();+ if (requestedSize > maxHeapSize) {+ return false;+ }+ // Loop through potential heap size increases. If we attempt a too eager+ // reservation that fails, cut down on the attempted size and reserve a+ // smaller bump instead. (max 3 times, chosen somewhat arbitrarily)+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {+ var overGrownHeapSize = oldSize * (1 + .2 / cutDown);+ // ensure geometric growth+ // but limit overreserving (default to capping at +96MB overgrowth at most)+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));+ var replacement = growMemory(newSize);+ if (replacement) {+ return true;+ }+ }+ return false;+};++var _emscripten_stack_unwind_buffer = (addr, buffer, count) => {+ var stack;+ if (UNWIND_CACHE.last_addr == addr) {+ stack = UNWIND_CACHE.last_stack;+ } else {+ stack = jsStackTrace().split("\n");+ if (stack[0] == "Error") {+ stack.shift();+ }+ saveInUnwindCache(stack);+ }+ var offset = 3;+ while (stack[offset] && convertFrameToPC(stack[offset]) != addr) {+ ++offset;+ }+ for (var i = 0; i < count && stack[i + offset]; ++i) {+ HEAP32[(((buffer) + (i * 4)) >> 2)] = convertFrameToPC(stack[i + offset]);+ }+ return i;+};++var GLctx;++var webgl_enable_ANGLE_instanced_arrays = ctx => {+ // Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("ANGLE_instanced_arrays");+ // Because this extension is a core function in WebGL 2, assign the extension entry points in place of+ // where the core functions will reside in WebGL 2. This way the calling code can call these without+ // having to dynamically branch depending if running against WebGL 1 or WebGL 2.+ if (ext) {+ ctx["vertexAttribDivisor"] = (index, divisor) => ext["vertexAttribDivisorANGLE"](index, divisor);+ ctx["drawArraysInstanced"] = (mode, first, count, primcount) => ext["drawArraysInstancedANGLE"](mode, first, count, primcount);+ ctx["drawElementsInstanced"] = (mode, count, type, indices, primcount) => ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount);+ return 1;+ }+};++var webgl_enable_OES_vertex_array_object = ctx => {+ // Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("OES_vertex_array_object");+ if (ext) {+ ctx["createVertexArray"] = () => ext["createVertexArrayOES"]();+ ctx["deleteVertexArray"] = vao => ext["deleteVertexArrayOES"](vao);+ ctx["bindVertexArray"] = vao => ext["bindVertexArrayOES"](vao);+ ctx["isVertexArray"] = vao => ext["isVertexArrayOES"](vao);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_buffers = ctx => {+ // Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.+ var ext = ctx.getExtension("WEBGL_draw_buffers");+ if (ext) {+ ctx["drawBuffers"] = (n, bufs) => ext["drawBuffersWEBGL"](n, bufs);+ return 1;+ }+};++var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance = ctx => // Closure is expected to be allowed to minify the '.dibvbi' property, so not accessing it quoted.+!!(ctx.dibvbi = ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));++var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance = ctx => !!(ctx.mdibvbi = ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));++var webgl_enable_EXT_polygon_offset_clamp = ctx => !!(ctx.extPolygonOffsetClamp = ctx.getExtension("EXT_polygon_offset_clamp"));++var webgl_enable_EXT_clip_control = ctx => !!(ctx.extClipControl = ctx.getExtension("EXT_clip_control"));++var webgl_enable_WEBGL_polygon_mode = ctx => !!(ctx.webglPolygonMode = ctx.getExtension("WEBGL_polygon_mode"));++var webgl_enable_WEBGL_multi_draw = ctx => // Closure is expected to be allowed to minify the '.multiDrawWebgl' property, so not accessing it quoted.+!!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw"));++var getEmscriptenSupportedExtensions = ctx => {+ // Restrict the list of advertised extensions to those that we actually+ // support.+ var supportedExtensions = [ // WebGL 1 extensions+ "ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_disjoint_timer_query", "EXT_frag_depth", "EXT_shader_texture_lod", "EXT_sRGB", "OES_element_index_uint", "OES_fbo_render_mipmap", "OES_standard_derivatives", "OES_texture_float", "OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object", "WEBGL_color_buffer_float", "WEBGL_depth_texture", "WEBGL_draw_buffers", // WebGL 2 extensions+ "EXT_color_buffer_float", "EXT_conservative_depth", "EXT_disjoint_timer_query_webgl2", "EXT_texture_norm16", "NV_shader_noperspective_interpolation", "WEBGL_clip_cull_distance", // WebGL 1 and WebGL 2 extensions+ "EXT_clip_control", "EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_float_blend", "EXT_polygon_offset_clamp", "EXT_texture_compression_bptc", "EXT_texture_compression_rgtc", "EXT_texture_filter_anisotropic", "KHR_parallel_shader_compile", "OES_texture_float_linear", "WEBGL_blend_func_extended", "WEBGL_compressed_texture_astc", "WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1", "WEBGL_compressed_texture_s3tc", "WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders", "WEBGL_lose_context", "WEBGL_multi_draw", "WEBGL_polygon_mode" ];+ // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.+ return (ctx.getSupportedExtensions() || []).filter(ext => supportedExtensions.includes(ext));+};++var registerPreMainLoop = f => {+ // Does nothing unless $MainLoop is included/used.+ typeof MainLoop != "undefined" && MainLoop.preMainLoop.push(f);+};++var GL = {+ counter: 1,+ buffers: [],+ mappedBuffers: {},+ programs: [],+ framebuffers: [],+ renderbuffers: [],+ textures: [],+ shaders: [],+ vaos: [],+ contexts: [],+ offscreenCanvases: {},+ queries: [],+ samplers: [],+ transformFeedbacks: [],+ syncs: [],+ byteSizeByTypeRoot: 5120,+ byteSizeByType: [ 1, 1, 2, 2, 4, 4, 4, 2, 3, 4, 8 ],+ stringCache: {},+ stringiCache: {},+ unpackAlignment: 4,+ unpackRowLength: 0,+ recordError: errorCode => {+ if (!GL.lastError) {+ GL.lastError = errorCode;+ }+ },+ getNewId: table => {+ var ret = GL.counter++;+ for (var i = table.length; i < ret; i++) {+ table[i] = null;+ }+ // Skip over any non-null elements that might have been created by+ // glBindBuffer.+ while (table[ret]) {+ ret = GL.counter++;+ }+ return ret;+ },+ genObject: (n, buffers, createFunction, objectTable) => {+ for (var i = 0; i < n; i++) {+ var buffer = GLctx[createFunction]();+ var id = buffer && GL.getNewId(objectTable);+ if (buffer) {+ buffer.name = id;+ objectTable[id] = buffer;+ } else {+ GL.recordError(1282);+ }+ HEAP32[(((buffers) + (i * 4)) >> 2)] = id;+ }+ },+ MAX_TEMP_BUFFER_SIZE: 2097152,+ numTempVertexBuffersPerSize: 64,+ log2ceilLookup: i => 32 - Math.clz32(i === 0 ? 0 : i - 1),+ generateTempBuffers: (quads, context) => {+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ context.tempVertexBufferCounters1 = [];+ context.tempVertexBufferCounters2 = [];+ context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex + 1;+ context.tempVertexBuffers1 = [];+ context.tempVertexBuffers2 = [];+ context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex + 1;+ context.tempIndexBuffers = [];+ context.tempIndexBuffers.length = largestIndex + 1;+ for (var i = 0; i <= largestIndex; ++i) {+ context.tempIndexBuffers[i] = null;+ // Created on-demand+ context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;+ var ringbufferLength = GL.numTempVertexBuffersPerSize;+ context.tempVertexBuffers1[i] = [];+ context.tempVertexBuffers2[i] = [];+ var ringbuffer1 = context.tempVertexBuffers1[i];+ var ringbuffer2 = context.tempVertexBuffers2[i];+ ringbuffer1.length = ringbuffer2.length = ringbufferLength;+ for (var j = 0; j < ringbufferLength; ++j) {+ ringbuffer1[j] = ringbuffer2[j] = null;+ }+ }+ if (quads) {+ // GL_QUAD indexes can be precalculated+ context.tempQuadIndexBuffer = GLctx.createBuffer();+ context.GLctx.bindBuffer(34963, context.tempQuadIndexBuffer);+ var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;+ var quadIndexes = new Uint16Array(numIndexes);+ var i = 0, v = 0;+ while (1) {+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 1;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 2;+ if (i >= numIndexes) break;+ quadIndexes[i++] = v + 3;+ if (i >= numIndexes) break;+ v += 4;+ }+ context.GLctx.bufferData(34963, quadIndexes, 35044);+ context.GLctx.bindBuffer(34963, null);+ }+ },+ getTempVertexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];+ var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];+ GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx] + 1) & (GL.numTempVertexBuffersPerSize - 1);+ var vbo = ringbuffer[nextFreeBufferIndex];+ if (vbo) {+ return vbo;+ }+ var prevVBO = GLctx.getParameter(34964);+ ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();+ GLctx.bindBuffer(34962, ringbuffer[nextFreeBufferIndex]);+ GLctx.bufferData(34962, 1 << idx, 35048);+ GLctx.bindBuffer(34962, prevVBO);+ return ringbuffer[nextFreeBufferIndex];+ },+ getTempIndexBuffer: sizeBytes => {+ var idx = GL.log2ceilLookup(sizeBytes);+ var ibo = GL.currentContext.tempIndexBuffers[idx];+ if (ibo) {+ return ibo;+ }+ var prevIBO = GLctx.getParameter(34965);+ GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();+ GLctx.bindBuffer(34963, GL.currentContext.tempIndexBuffers[idx]);+ GLctx.bufferData(34963, 1 << idx, 35048);+ GLctx.bindBuffer(34963, prevIBO);+ return GL.currentContext.tempIndexBuffers[idx];+ },+ newRenderingFrameStarted: () => {+ if (!GL.currentContext) {+ return;+ }+ var vb = GL.currentContext.tempVertexBuffers1;+ GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;+ GL.currentContext.tempVertexBuffers2 = vb;+ vb = GL.currentContext.tempVertexBufferCounters1;+ GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;+ GL.currentContext.tempVertexBufferCounters2 = vb;+ var largestIndex = GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);+ for (var i = 0; i <= largestIndex; ++i) {+ GL.currentContext.tempVertexBufferCounters1[i] = 0;+ }+ },+ getSource: (shader, count, string, length) => {+ var source = "";+ for (var i = 0; i < count; ++i) {+ var len = length ? HEAPU32[(((length) + (i * 4)) >> 2)] : undefined;+ source += UTF8ToString(HEAPU32[(((string) + (i * 4)) >> 2)], len);+ }+ return source;+ },+ calcBufLength: (size, type, stride, count) => {+ if (stride > 0) {+ return count * stride;+ }+ var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];+ return size * typeSize * count;+ },+ usedTempBuffers: [],+ preDrawHandleClientVertexAttribBindings: count => {+ GL.resetBufferBinding = false;+ // TODO: initial pass to detect ranges we need to upload, might not need+ // an upload per attrib+ for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {+ var cb = GL.currentContext.clientBuffers[i];+ if (!cb.clientside || !cb.enabled) continue;+ GL.resetBufferBinding = true;+ var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);+ var buf = GL.getTempVertexBuffer(size);+ GLctx.bindBuffer(34962, buf);+ GLctx.bufferSubData(34962, 0, HEAPU8.subarray(cb.ptr, cb.ptr + size));+ cb.vertexAttribPointerAdaptor.call(GLctx, i, cb.size, cb.type, cb.normalized, cb.stride, 0);+ }+ },+ postDrawHandleClientVertexAttribBindings: () => {+ if (GL.resetBufferBinding) {+ GLctx.bindBuffer(34962, GL.buffers[GLctx.currentArrayBufferBinding]);+ }+ },+ createContext: (/** @type {HTMLCanvasElement} */ canvas, webGLContextAttributes) => {+ // BUG: Workaround Safari WebGL issue: After successfully acquiring WebGL+ // context on a canvas, calling .getContext() will always return that+ // context independent of which 'webgl' or 'webgl2'+ // context version was passed. See:+ // https://webkit.org/b/222758+ // and:+ // https://github.com/emscripten-core/emscripten/issues/13295.+ // TODO: Once the bug is fixed and shipped in Safari, adjust the Safari+ // version field in above check.+ if (!canvas.getContextSafariWebGL2Fixed) {+ canvas.getContextSafariWebGL2Fixed = canvas.getContext;+ /** @type {function(this:HTMLCanvasElement, string, (Object|null)=): (Object|null)} */ function fixedGetContext(ver, attrs) {+ var gl = canvas.getContextSafariWebGL2Fixed(ver, attrs);+ return ((ver == "webgl") == (gl instanceof WebGLRenderingContext)) ? gl : null;+ }+ canvas.getContext = fixedGetContext;+ }+ var ctx = (webGLContextAttributes.majorVersion > 1) ? canvas.getContext("webgl2", webGLContextAttributes) : canvas.getContext("webgl", webGLContextAttributes);+ if (!ctx) return 0;+ var handle = GL.registerContext(ctx, webGLContextAttributes);+ return handle;+ },+ registerContext: (ctx, webGLContextAttributes) => {+ // without pthreads a context is just an integer ID+ var handle = GL.getNewId(GL.contexts);+ var context = {+ handle,+ attributes: webGLContextAttributes,+ version: webGLContextAttributes.majorVersion,+ GLctx: ctx+ };+ // Store the created context object so that we can access the context+ // given a canvas without having to pass the parameters again.+ if (ctx.canvas) ctx.canvas.GLctxObject = context;+ GL.contexts[handle] = context;+ if (typeof webGLContextAttributes.enableExtensionsByDefault == "undefined" || webGLContextAttributes.enableExtensionsByDefault) {+ GL.initExtensions(context);+ }+ context.maxVertexAttribs = context.GLctx.getParameter(34921);+ context.clientBuffers = [];+ for (var i = 0; i < context.maxVertexAttribs; i++) {+ context.clientBuffers[i] = {+ enabled: false,+ clientside: false,+ size: 0,+ type: 0,+ normalized: 0,+ stride: 0,+ ptr: 0,+ vertexAttribPointerAdaptor: null+ };+ }+ GL.generateTempBuffers(false, context);+ return handle;+ },+ makeContextCurrent: contextHandle => {+ // Active Emscripten GL layer context object.+ GL.currentContext = GL.contexts[contextHandle];+ // Active WebGL context object.+ Module["ctx"] = GLctx = GL.currentContext?.GLctx;+ return !(contextHandle && !GLctx);+ },+ getContext: contextHandle => GL.contexts[contextHandle],+ deleteContext: contextHandle => {+ if (GL.currentContext === GL.contexts[contextHandle]) {+ GL.currentContext = null;+ }+ if (typeof JSEvents == "object") {+ // Release all JS event handlers on the DOM element that the GL context is+ // associated with since the context is now deleted.+ JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);+ }+ // Make sure the canvas object no longer refers to the context object so+ // there are no GC surprises.+ if (GL.contexts[contextHandle]?.GLctx.canvas) {+ GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined;+ }+ GL.contexts[contextHandle] = null;+ },+ initExtensions: context => {+ // If this function is called without a specific context object, init the+ // extensions of the currently active context.+ context ||= GL.currentContext;+ if (context.initExtensionsDone) return;+ context.initExtensionsDone = true;+ var GLctx = context.GLctx;+ // Detect the presence of a few extensions manually, since the GL interop+ // layer itself will need to know if they exist.+ // Extensions that are available in both WebGL 1 and WebGL 2+ webgl_enable_WEBGL_multi_draw(GLctx);+ webgl_enable_EXT_polygon_offset_clamp(GLctx);+ webgl_enable_EXT_clip_control(GLctx);+ webgl_enable_WEBGL_polygon_mode(GLctx);+ // Extensions that are only available in WebGL 1 (the calls will be no-ops+ // if called on a WebGL 2 context active)+ webgl_enable_ANGLE_instanced_arrays(GLctx);+ webgl_enable_OES_vertex_array_object(GLctx);+ webgl_enable_WEBGL_draw_buffers(GLctx);+ // Extensions that are available from WebGL >= 2 (no-op if called on a WebGL 1 context active)+ webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);+ webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);+ // On WebGL 2, EXT_disjoint_timer_query is replaced with an alternative+ // that's based on core APIs, and exposes only the queryCounterEXT()+ // entrypoint.+ if (context.version >= 2) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query_webgl2");+ }+ // However, Firefox exposes the WebGL 1 version on WebGL 2 as well and+ // thus we look for the WebGL 1 version again if the WebGL 2 version+ // isn't present. https://bugzil.la/1328882+ if (context.version < 2 || !GLctx.disjointTimerQueryExt) {+ GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");+ }+ for (var ext of getEmscriptenSupportedExtensions(GLctx)) {+ // WEBGL_lose_context, WEBGL_debug_renderer_info and WEBGL_debug_shaders+ // are not enabled by default.+ if (!ext.includes("lose_context") && !ext.includes("debug")) {+ // Call .getExtension() to enable that extension permanently.+ GLctx.getExtension(ext);+ }+ }+ }+};++var webglPowerPreferences = [ "default", "low-power", "high-performance" ];++/** @type {Object} */ var specialHTMLTargets = [ 0, globalThis.document ?? 0, globalThis.window ?? 0 ];++var findEventTarget = target => {+ // The sensible "default" target varies between events, but use window as the default+ // since DOM events mostly can default to that. Specific callback registrations+ // override their own defaults.+ if (!target) return window;+ if (typeof target == "number") target = specialHTMLTargets[target] || UTF8ToString(target);+ if (target === "#window") return window; else if (target === "#document") return document; else if (target === "#screen") return screen; else if (target === "#canvas") return Module["canvas"]; else if (typeof target == "string") return globalThis.document?.getElementById(target);+ return target;+};++var findCanvasEventTarget = target => {+ if (typeof target == "number") target = UTF8ToString(target);+ if (!target || target === "#canvas") {+ if (typeof GL != "undefined" && GL.offscreenCanvases["canvas"]) return GL.offscreenCanvases["canvas"];+ // TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.+ return Module["canvas"];+ }+ if (typeof GL != "undefined" && GL.offscreenCanvases[target]) return GL.offscreenCanvases[target];+ return findEventTarget(target);+};++var _emscripten_webgl_do_create_context = (target, attributes) => {+ var attr32 = ((attributes) >> 2);+ var powerPreference = HEAP32[attr32 + (8 >> 2)];+ var contextAttributes = {+ "alpha": !!HEAP8[attributes + 0],+ "depth": !!HEAP8[attributes + 1],+ "stencil": !!HEAP8[attributes + 2],+ "antialias": !!HEAP8[attributes + 3],+ "premultipliedAlpha": !!HEAP8[attributes + 4],+ "preserveDrawingBuffer": !!HEAP8[attributes + 5],+ "powerPreference": webglPowerPreferences[powerPreference],+ "failIfMajorPerformanceCaveat": !!HEAP8[attributes + 12],+ // The following are not predefined WebGL context attributes in the WebGL specification, so the property names can be minified by Closure.+ majorVersion: HEAP32[attr32 + (16 >> 2)],+ minorVersion: HEAP32[attr32 + (20 >> 2)],+ enableExtensionsByDefault: HEAP8[attributes + 24],+ explicitSwapControl: HEAP8[attributes + 25],+ proxyContextToMainThread: HEAP32[attr32 + (28 >> 2)],+ renderViaOffscreenBackBuffer: HEAP8[attributes + 32]+ };+ var canvas = findCanvasEventTarget(target);+ if (!canvas) {+ return 0;+ }+ if (contextAttributes.explicitSwapControl) {+ return 0;+ }+ var contextHandle = GL.createContext(canvas, contextAttributes);+ return contextHandle;+};++var _emscripten_webgl_create_context = _emscripten_webgl_do_create_context;++var _emscripten_webgl_destroy_context = contextHandle => {+ if (GL.currentContext == contextHandle) GL.currentContext = 0;+ GL.deleteContext(contextHandle);+};++var _emscripten_webgl_get_context_attributes = (c, a) => {+ if (!a) return -5;+ c = GL.contexts[c];+ if (!c) return -3;+ var t = c.GLctx?.getContextAttributes();+ if (!t) return -3;+ HEAP8[a] = t.alpha;+ HEAP8[(a) + (1)] = t.depth;+ HEAP8[(a) + (2)] = t.stencil;+ HEAP8[(a) + (3)] = t.antialias;+ HEAP8[(a) + (4)] = t.premultipliedAlpha;+ HEAP8[(a) + (5)] = t.preserveDrawingBuffer;+ var power = t["powerPreference"] && webglPowerPreferences.indexOf(t["powerPreference"]);+ HEAP32[(((a) + (8)) >> 2)] = power;+ HEAP8[(a) + (12)] = t.failIfMajorPerformanceCaveat;+ HEAP32[(((a) + (16)) >> 2)] = c.version;+ HEAP32[(((a) + (20)) >> 2)] = 0;+ HEAP8[(a) + (24)] = c.attributes.enableExtensionsByDefault;+ return 0;+};++var _emscripten_webgl_do_get_current_context = () => GL.currentContext ? GL.currentContext.handle : 0;++var _emscripten_webgl_get_current_context = _emscripten_webgl_do_get_current_context;++var _emscripten_webgl_make_context_current = contextHandle => {+ var success = GL.makeContextCurrent(contextHandle);+ return success ? 0 : -5;+};++var stackAlloc = sz => __emscripten_stack_alloc(sz);++var stringToUTF8OnStack = str => {+ var size = lengthBytesUTF8(str) + 1;+ var ret = stackAlloc(size);+ stringToUTF8(str, ret, size);+ return ret;+};++var writeI53ToI64 = (ptr, num) => {+ HEAPU32[((ptr) >> 2)] = num;+ var lower = HEAPU32[((ptr) >> 2)];+ HEAPU32[(((ptr) + (4)) >> 2)] = (num - lower) / 4294967296;+};++var readI53FromI64 = ptr => HEAPU32[((ptr) >> 2)] + HEAP32[(((ptr) + (4)) >> 2)] * 4294967296;++var wasmTableMirror = [];++var getWasmTableEntry = funcPtr => {+ var func = wasmTableMirror[funcPtr];+ if (!func) {+ /** @suppress {checkTypes} */ wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);+ }+ return func;+};++var WebGPU = {+ Internals: {+ jsObjects: [],+ jsObjectInsert: (ptr, jsObject) => {+ ptr >>>= 0;+ WebGPU.Internals.jsObjects[ptr] = jsObject;+ },+ bufferOnUnmaps: [],+ futures: [],+ futureInsert: (futureId, promise) => {}+ },+ getJsObject: ptr => {+ if (!ptr) return undefined;+ ptr >>>= 0;+ return WebGPU.Internals.jsObjects[ptr];+ },+ importJsAdapter: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateAdapter(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroup: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroup(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBindGroupLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateBindGroupLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsBuffer: (buffer, parentPtr = 0) => {+ // At the moment, we do not allow importing pending buffers.+ assert(buffer.mapState === "unmapped");+ var bufferPtr = _emwgpuImportBuffer(parentPtr);+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ return bufferPtr;+ },+ importJsCommandBuffer: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandBuffer(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsCommandEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateCommandEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsComputePipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateComputePipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsDevice: (device, parentPtr = 0) => {+ var queuePtr = _emwgpuCreateQueue(parentPtr);+ var devicePtr = _emwgpuCreateDevice(parentPtr, queuePtr);+ WebGPU.Internals.jsObjectInsert(queuePtr, device.queue);+ WebGPU.Internals.jsObjectInsert(devicePtr, device);+ return devicePtr;+ },+ importJsExternalTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateExternalTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsPipelineLayout: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreatePipelineLayout(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQuerySet: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQuerySet(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsQueue: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateQueue(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundle: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundle(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderBundleEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderBundleEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPassEncoder: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPassEncoder(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsRenderPipeline: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateRenderPipeline(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSampler: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSampler(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsShaderModule: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateShaderModule(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsSurface: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateSurface(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTexture: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTexture(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ importJsTextureView: (obj, parentPtr = 0) => {+ var ptr = _emwgpuCreateTextureView(parentPtr);+ WebGPU.Internals.jsObjects[ptr] = obj;+ return ptr;+ },+ errorCallback: (callback, type, message, userdata) => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(message);+ getWasmTableEntry(callback)(type, messagePtr, userdata);+ stackRestore(sp);+ },+ iterateExtensions: (root, handlers) => {+ for (var ptr = HEAPU32[((root) >> 2)]; ptr; ptr = HEAPU32[((ptr) >> 2)]) {+ var sType = HEAP32[(((ptr) + (4)) >> 2)];+ // This will crash if there's no handler indicating either a bogus+ // sType, or one we haven't implemented yet.+ var handler = handlers[sType](ptr);+ }+ },+ setStringView: (ptr, data, length) => {+ HEAPU32[((ptr) >> 2)] = data;+ HEAPU32[(((ptr) + (4)) >> 2)] = length;+ },+ makeStringFromStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeStringFromOptionalStringView: stringViewPtr => {+ var ptr = HEAPU32[((stringViewPtr) >> 2)];+ var length = HEAPU32[(((stringViewPtr) + (4)) >> 2)];+ // If we don't have a valid string pointer, just return undefined when+ // optional.+ if (!ptr) {+ if (length === 0) {+ return "";+ }+ return undefined;+ }+ // UTF8ToString stops at the first null terminator character in the+ // string regardless of the length.+ return UTF8ToString(ptr, length);+ },+ makeColor: ptr => ({+ "r": HEAPF64[((ptr) >> 3)],+ "g": HEAPF64[(((ptr) + (8)) >> 3)],+ "b": HEAPF64[(((ptr) + (16)) >> 3)],+ "a": HEAPF64[(((ptr) + (24)) >> 3)]+ }),+ makeExtent3D: ptr => ({+ "width": HEAPU32[((ptr) >> 2)],+ "height": HEAPU32[(((ptr) + (4)) >> 2)],+ "depthOrArrayLayers": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeOrigin3D: ptr => ({+ "x": HEAPU32[((ptr) >> 2)],+ "y": HEAPU32[(((ptr) + (4)) >> 2)],+ "z": HEAPU32[(((ptr) + (8)) >> 2)]+ }),+ makeTexelCopyTextureInfo: ptr => ({+ "texture": WebGPU.getJsObject(HEAPU32[((ptr) >> 2)]),+ "mipLevel": HEAPU32[(((ptr) + (4)) >> 2)],+ "origin": WebGPU.makeOrigin3D(ptr + 8),+ "aspect": WebGPU.TextureAspect[HEAP32[(((ptr) + (20)) >> 2)]]+ }),+ makeTexelCopyBufferLayout: ptr => {+ var bytesPerRow = HEAPU32[(((ptr) + (8)) >> 2)];+ var rowsPerImage = HEAPU32[(((ptr) + (12)) >> 2)];+ return {+ "offset": readI53FromI64(ptr),+ "bytesPerRow": bytesPerRow === 4294967295 ? undefined : bytesPerRow,+ "rowsPerImage": rowsPerImage === 4294967295 ? undefined : rowsPerImage+ };+ },+ makeTexelCopyBufferInfo: ptr => {+ var layoutPtr = ptr + 0;+ var bufferCopyView = WebGPU.makeTexelCopyBufferLayout(layoutPtr);+ bufferCopyView["buffer"] = WebGPU.getJsObject(HEAPU32[(((ptr) + (16)) >> 2)]);+ return bufferCopyView;+ },+ makePassTimestampWrites: ptr => {+ if (ptr === 0) return undefined;+ return {+ "querySet": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "beginningOfPassWriteIndex": HEAPU32[(((ptr) + (8)) >> 2)],+ "endOfPassWriteIndex": HEAPU32[(((ptr) + (12)) >> 2)]+ };+ },+ makePipelineConstants: (constantCount, constantsPtr) => {+ if (!constantCount) return;+ var constants = {};+ for (var i = 0; i < constantCount; ++i) {+ var entryPtr = constantsPtr + 24 * i;+ var key = WebGPU.makeStringFromStringView(entryPtr + 4);+ constants[key] = HEAPF64[(((entryPtr) + (16)) >> 3)];+ }+ return constants;+ },+ makePipelineLayout: layoutPtr => {+ if (!layoutPtr) return "auto";+ return WebGPU.getJsObject(layoutPtr);+ },+ makeComputeState: ptr => {+ if (!ptr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((ptr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((ptr) + (16)) >> 2)], HEAPU32[(((ptr) + (20)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(ptr + 8)+ };+ return desc;+ },+ makeComputePipelineDesc: descriptor => {+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "compute": WebGPU.makeComputeState(descriptor + 16)+ };+ return desc;+ },+ makeRenderPipelineDesc: descriptor => {+ function makePrimitiveState(psPtr) {+ if (!psPtr) return undefined;+ return {+ "topology": WebGPU.PrimitiveTopology[HEAP32[(((psPtr) + (4)) >> 2)]],+ "stripIndexFormat": WebGPU.IndexFormat[HEAP32[(((psPtr) + (8)) >> 2)]],+ "frontFace": WebGPU.FrontFace[HEAP32[(((psPtr) + (12)) >> 2)]],+ "cullMode": WebGPU.CullMode[HEAP32[(((psPtr) + (16)) >> 2)]],+ "unclippedDepth": !!(HEAPU32[(((psPtr) + (20)) >> 2)])+ };+ }+ function makeBlendComponent(bdPtr) {+ if (!bdPtr) return undefined;+ return {+ "operation": WebGPU.BlendOperation[HEAP32[((bdPtr) >> 2)]],+ "srcFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (4)) >> 2)]],+ "dstFactor": WebGPU.BlendFactor[HEAP32[(((bdPtr) + (8)) >> 2)]]+ };+ }+ function makeBlendState(bsPtr) {+ if (!bsPtr) return undefined;+ return {+ "alpha": makeBlendComponent(bsPtr + 12),+ "color": makeBlendComponent(bsPtr + 0)+ };+ }+ function makeColorState(csPtr) {+ var format = WebGPU.TextureFormat[HEAP32[(((csPtr) + (4)) >> 2)]];+ return format ? {+ "format": format,+ "blend": makeBlendState(HEAPU32[(((csPtr) + (8)) >> 2)]),+ "writeMask": HEAPU32[(((csPtr) + (16)) >> 2)]+ } : undefined;+ }+ function makeColorStates(count, csArrayPtr) {+ var states = [];+ for (var i = 0; i < count; ++i) {+ states.push(makeColorState(csArrayPtr + 24 * i));+ }+ return states;+ }+ function makeStencilStateFace(ssfPtr) {+ return {+ "compare": WebGPU.CompareFunction[HEAP32[((ssfPtr) >> 2)]],+ "failOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (4)) >> 2)]],+ "depthFailOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (8)) >> 2)]],+ "passOp": WebGPU.StencilOperation[HEAP32[(((ssfPtr) + (12)) >> 2)]]+ };+ }+ function makeDepthStencilState(dssPtr) {+ if (!dssPtr) return undefined;+ return {+ "format": WebGPU.TextureFormat[HEAP32[(((dssPtr) + (4)) >> 2)]],+ "depthWriteEnabled": !!(HEAPU32[(((dssPtr) + (8)) >> 2)]),+ "depthCompare": WebGPU.CompareFunction[HEAP32[(((dssPtr) + (12)) >> 2)]],+ "stencilFront": makeStencilStateFace(dssPtr + 16),+ "stencilBack": makeStencilStateFace(dssPtr + 32),+ "stencilReadMask": HEAPU32[(((dssPtr) + (48)) >> 2)],+ "stencilWriteMask": HEAPU32[(((dssPtr) + (52)) >> 2)],+ "depthBias": HEAP32[(((dssPtr) + (56)) >> 2)],+ "depthBiasSlopeScale": HEAPF32[(((dssPtr) + (60)) >> 2)],+ "depthBiasClamp": HEAPF32[(((dssPtr) + (64)) >> 2)]+ };+ }+ function makeVertexAttribute(vaPtr) {+ return {+ "format": WebGPU.VertexFormat[HEAP32[(((vaPtr) + (4)) >> 2)]],+ "offset": readI53FromI64((vaPtr) + (8)),+ "shaderLocation": HEAPU32[(((vaPtr) + (16)) >> 2)]+ };+ }+ function makeVertexAttributes(count, vaArrayPtr) {+ var vas = [];+ for (var i = 0; i < count; ++i) {+ vas.push(makeVertexAttribute(vaArrayPtr + i * 24));+ }+ return vas;+ }+ function makeVertexBuffer(vbPtr) {+ if (!vbPtr) return undefined;+ var stepMode = WebGPU.VertexStepMode[HEAP32[(((vbPtr) + (4)) >> 2)]];+ var attributeCount = HEAPU32[(((vbPtr) + (16)) >> 2)];+ if (!stepMode && !attributeCount) {+ return null;+ }+ return {+ "arrayStride": readI53FromI64((vbPtr) + (8)),+ "stepMode": stepMode,+ "attributes": makeVertexAttributes(attributeCount, HEAPU32[(((vbPtr) + (20)) >> 2)])+ };+ }+ function makeVertexBuffers(count, vbArrayPtr) {+ if (!count) return undefined;+ var vbs = [];+ for (var i = 0; i < count; ++i) {+ vbs.push(makeVertexBuffer(vbArrayPtr + i * 24));+ }+ return vbs;+ }+ function makeVertexState(viPtr) {+ if (!viPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((viPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((viPtr) + (16)) >> 2)], HEAPU32[(((viPtr) + (20)) >> 2)]),+ "buffers": makeVertexBuffers(HEAPU32[(((viPtr) + (24)) >> 2)], HEAPU32[(((viPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(viPtr + 8)+ };+ return desc;+ }+ function makeMultisampleState(msPtr) {+ if (!msPtr) return undefined;+ return {+ "count": HEAPU32[(((msPtr) + (4)) >> 2)],+ "mask": HEAPU32[(((msPtr) + (8)) >> 2)],+ "alphaToCoverageEnabled": !!(HEAPU32[(((msPtr) + (12)) >> 2)])+ };+ }+ function makeFragmentState(fsPtr) {+ if (!fsPtr) return undefined;+ var desc = {+ "module": WebGPU.getJsObject(HEAPU32[(((fsPtr) + (4)) >> 2)]),+ "constants": WebGPU.makePipelineConstants(HEAPU32[(((fsPtr) + (16)) >> 2)], HEAPU32[(((fsPtr) + (20)) >> 2)]),+ "targets": makeColorStates(HEAPU32[(((fsPtr) + (24)) >> 2)], HEAPU32[(((fsPtr) + (28)) >> 2)]),+ "entryPoint": WebGPU.makeStringFromOptionalStringView(fsPtr + 8)+ };+ return desc;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.makePipelineLayout(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "vertex": makeVertexState(descriptor + 16),+ "primitive": makePrimitiveState(descriptor + 48),+ "depthStencil": makeDepthStencilState(HEAPU32[(((descriptor) + (72)) >> 2)]),+ "multisample": makeMultisampleState(descriptor + 76),+ "fragment": makeFragmentState(HEAPU32[(((descriptor) + (92)) >> 2)])+ };+ return desc;+ },+ fillLimitStruct: (limits, limitsOutPtr) => {+ var nextInChainPtr = HEAPU32[((limitsOutPtr) >> 2)];+ function setLimitValueU32(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ HEAPU32[(((basePtr) + (limitOffset)) >> 2)] = limitValue;+ }+ function setLimitValueU64(name, basePtr, limitOffset, fallbackValue = 0) {+ var limitValue = limits[name] ?? fallbackValue;+ // Limits are integer-valued JS `Number`s, so they fit in 'i53'.+ writeI53ToI64((basePtr) + (limitOffset), limitValue);+ }+ setLimitValueU32("maxTextureDimension1D", limitsOutPtr, 4);+ setLimitValueU32("maxTextureDimension2D", limitsOutPtr, 8);+ setLimitValueU32("maxTextureDimension3D", limitsOutPtr, 12);+ setLimitValueU32("maxTextureArrayLayers", limitsOutPtr, 16);+ setLimitValueU32("maxBindGroups", limitsOutPtr, 20);+ setLimitValueU32("maxBindGroupsPlusVertexBuffers", limitsOutPtr, 24);+ setLimitValueU32("maxBindingsPerBindGroup", limitsOutPtr, 28);+ setLimitValueU32("maxDynamicUniformBuffersPerPipelineLayout", limitsOutPtr, 32);+ setLimitValueU32("maxDynamicStorageBuffersPerPipelineLayout", limitsOutPtr, 36);+ setLimitValueU32("maxSampledTexturesPerShaderStage", limitsOutPtr, 40);+ setLimitValueU32("maxSamplersPerShaderStage", limitsOutPtr, 44);+ setLimitValueU32("maxStorageBuffersPerShaderStage", limitsOutPtr, 48);+ setLimitValueU32("maxStorageTexturesPerShaderStage", limitsOutPtr, 52);+ setLimitValueU32("maxUniformBuffersPerShaderStage", limitsOutPtr, 56);+ setLimitValueU32("minUniformBufferOffsetAlignment", limitsOutPtr, 80);+ setLimitValueU32("minStorageBufferOffsetAlignment", limitsOutPtr, 84);+ setLimitValueU64("maxUniformBufferBindingSize", limitsOutPtr, 64);+ setLimitValueU64("maxStorageBufferBindingSize", limitsOutPtr, 72);+ setLimitValueU32("maxVertexBuffers", limitsOutPtr, 88);+ setLimitValueU64("maxBufferSize", limitsOutPtr, 96);+ setLimitValueU32("maxVertexAttributes", limitsOutPtr, 104);+ setLimitValueU32("maxVertexBufferArrayStride", limitsOutPtr, 108);+ setLimitValueU32("maxInterStageShaderVariables", limitsOutPtr, 112);+ setLimitValueU32("maxColorAttachments", limitsOutPtr, 116);+ setLimitValueU32("maxColorAttachmentBytesPerSample", limitsOutPtr, 120);+ setLimitValueU32("maxComputeWorkgroupStorageSize", limitsOutPtr, 124);+ setLimitValueU32("maxComputeInvocationsPerWorkgroup", limitsOutPtr, 128);+ setLimitValueU32("maxComputeWorkgroupSizeX", limitsOutPtr, 132);+ setLimitValueU32("maxComputeWorkgroupSizeY", limitsOutPtr, 136);+ setLimitValueU32("maxComputeWorkgroupSizeZ", limitsOutPtr, 140);+ setLimitValueU32("maxComputeWorkgroupsPerDimension", limitsOutPtr, 144);+ // Note this limit is new and won't be present in all browsers for a while. Fall back to 0.+ setLimitValueU32("maxImmediateSize", limitsOutPtr, 148);+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var compatibilityModeLimitsPtr = nextInChainPtr;+ // Note these limits are new and won't be present in all browsers for a while. Fall back to exposing the PerShaderStage limit.+ setLimitValueU32("maxStorageBuffersInVertexStage", compatibilityModeLimitsPtr, 8, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageBuffersInFragmentStage", compatibilityModeLimitsPtr, 16, limits.maxStorageBuffersPerShaderStage);+ setLimitValueU32("maxStorageTexturesInVertexStage", compatibilityModeLimitsPtr, 12, limits.maxStorageTexturesPerShaderStage);+ setLimitValueU32("maxStorageTexturesInFragmentStage", compatibilityModeLimitsPtr, 20, limits.maxStorageTexturesPerShaderStage);+ }+ },+ fillAdapterInfoStruct: (info, infoStruct) => {+ // Populate subgroup limits.+ HEAPU32[(((infoStruct) + (52)) >> 2)] = info.subgroupMinSize;+ HEAPU32[(((infoStruct) + (56)) >> 2)] = info.subgroupMaxSize;+ // Append all the strings together to condense into a single malloc.+ var strs = info.vendor + info.architecture + info.device + info.description;+ var strPtr = stringToNewUTF8(strs);+ var vendorLen = lengthBytesUTF8(info.vendor);+ WebGPU.setStringView(infoStruct + 4, strPtr, vendorLen);+ strPtr += vendorLen;+ var architectureLen = lengthBytesUTF8(info.architecture);+ WebGPU.setStringView(infoStruct + 12, strPtr, architectureLen);+ strPtr += architectureLen;+ var deviceLen = lengthBytesUTF8(info.device);+ WebGPU.setStringView(infoStruct + 20, strPtr, deviceLen);+ strPtr += deviceLen;+ var descriptionLen = lengthBytesUTF8(info.description);+ WebGPU.setStringView(infoStruct + 28, strPtr, descriptionLen);+ strPtr += descriptionLen;+ HEAP32[(((infoStruct) + (36)) >> 2)] = 2;+ var adapterType = info.isFallbackAdapter ? 3 : 4;+ HEAP32[(((infoStruct) + (40)) >> 2)] = adapterType;+ HEAPU32[(((infoStruct) + (44)) >> 2)] = 0;+ HEAPU32[(((infoStruct) + (48)) >> 2)] = 0;+ },+ AddressMode: [ , "clamp-to-edge", "repeat", "mirror-repeat" ],+ BlendFactor: [ , "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha" ],+ BlendOperation: [ , "add", "subtract", "reverse-subtract", "min", "max" ],+ BufferBindingType: [ , , "uniform", "storage", "read-only-storage" ],+ BufferMapState: [ , "unmapped", "pending", "mapped" ],+ CompareFunction: [ , "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always" ],+ CompilationInfoRequestStatus: [ , "success", "callback-cancelled" ],+ ComponentSwizzle: [ , "0", "1", "r", "g", "b", "a" ],+ CompositeAlphaMode: [ , "opaque", "premultiplied", "unpremultiplied", "inherit" ],+ CullMode: [ , "none", "front", "back" ],+ ErrorFilter: [ , "validation", "out-of-memory", "internal" ],+ FeatureLevel: [ , "compatibility", "core" ],+ FeatureName: {+ 1: "core-features-and-limits",+ 2: "depth-clip-control",+ 3: "depth32float-stencil8",+ 4: "texture-compression-bc",+ 5: "texture-compression-bc-sliced-3d",+ 6: "texture-compression-etc2",+ 7: "texture-compression-astc",+ 8: "texture-compression-astc-sliced-3d",+ 9: "timestamp-query",+ 10: "indirect-first-instance",+ 11: "shader-f16",+ 12: "rg11b10ufloat-renderable",+ 13: "bgra8unorm-storage",+ 14: "float32-filterable",+ 15: "float32-blendable",+ 16: "clip-distances",+ 17: "dual-source-blending",+ 18: "subgroups",+ 19: "texture-formats-tier1",+ 20: "texture-formats-tier2",+ 21: "primitive-index",+ 22: "texture-component-swizzle",+ 327692: "chromium-experimental-unorm16-texture-formats",+ 327729: "chromium-experimental-multi-draw-indirect"+ },+ FilterMode: [ , "nearest", "linear" ],+ FrontFace: [ , "ccw", "cw" ],+ IndexFormat: [ , "uint16", "uint32" ],+ InstanceFeatureName: [ , "timed-wait-any", "shader-source-spirv", "multiple-devices-per-adapter" ],+ LoadOp: [ , "load", "clear" ],+ MipmapFilterMode: [ , "nearest", "linear" ],+ OptionalBool: [ "false", "true" ],+ PowerPreference: [ , "low-power", "high-performance" ],+ PredefinedColorSpace: [ , "srgb", "display-p3" ],+ PrimitiveTopology: [ , "point-list", "line-list", "line-strip", "triangle-list", "triangle-strip" ],+ QueryType: [ , "occlusion", "timestamp" ],+ SamplerBindingType: [ , , "filtering", "non-filtering", "comparison" ],+ Status: [ , "success", "error" ],+ StencilOperation: [ , "keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap" ],+ StorageTextureAccess: [ , , "write-only", "read-only", "read-write" ],+ StoreOp: [ , "store", "discard" ],+ SurfaceGetCurrentTextureStatus: [ , "success-optimal", "success-suboptimal", "timeout", "outdated", "lost", "error" ],+ TextureAspect: [ , "all", "stencil-only", "depth-only" ],+ TextureDimension: [ , "1d", "2d", "3d" ],+ TextureFormat: [ , "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb" ],+ TextureSampleType: [ , , "float", "unfilterable-float", "depth", "sint", "uint" ],+ TextureViewDimension: [ , "1d", "2d", "2d-array", "cube", "cube-array", "3d" ],+ ToneMappingMode: [ , "standard", "extended" ],+ VertexFormat: [ , "uint8", "uint8x2", "uint8x4", "sint8", "sint8x2", "sint8x4", "unorm8", "unorm8x2", "unorm8x4", "snorm8", "snorm8x2", "snorm8x4", "uint16", "uint16x2", "uint16x4", "sint16", "sint16x2", "sint16x4", "unorm16", "unorm16x2", "unorm16x4", "snorm16", "snorm16x2", "snorm16x4", "float16", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", "unorm10-10-10-2", "unorm8x4-bgra" ],+ VertexStepMode: [ , "vertex", "instance" ],+ WGSLLanguageFeatureName: [ , "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", "uniform_buffer_standard_layout", "subgroup_id", "texture_and_sampler_let", "subgroup_uniformity", "texture_formats_tier1", "linear_indexing" ]+};++var _emscripten_webgpu_get_device = () => {+ if (WebGPU.preinitializedDeviceId === undefined) {+ WebGPU.preinitializedDeviceId = WebGPU.importJsDevice(Module["preinitializedWebGPUDevice"]);+ // Some users depend on this keeping the device alive, so we add an+ // additional reference when we first initialize it.+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ }+ _wgpuDeviceAddRef(WebGPU.preinitializedDeviceId);+ return WebGPU.preinitializedDeviceId;+};++var _emwgpuBufferDestroy = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (onUnmap) {+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ }+ buffer.destroy();+};++var _emwgpuBufferGetMappedRange = (bufferPtr, offset, size) => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ if (size == -1) size = undefined;+ var mapped;+ try {+ mapped = buffer.getMappedRange(offset, size);+ } catch (ex) {+ return 0;+ }+ var data = _memalign(16, mapped.byteLength);+ HEAPU8.fill(0, data, mapped.byteLength);+ WebGPU.Internals.bufferOnUnmaps[bufferPtr].push(() => {+ new Uint8Array(mapped).set(HEAPU8.subarray(data, data + mapped.byteLength));+ _free(data);+ });+ return data;+};++var _emwgpuBufferUnmap = bufferPtr => {+ var buffer = WebGPU.getJsObject(bufferPtr);+ var onUnmap = WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ if (!onUnmap) {+ // Already unmapped+ return;+ }+ for (var i = 0; i < onUnmap.length; ++i) {+ onUnmap[i]();+ }+ delete WebGPU.Internals.bufferOnUnmaps[bufferPtr];+ buffer.unmap();+};++var _emwgpuDelete = ptr => {+ delete WebGPU.Internals.jsObjects[ptr];+};++var _emwgpuDeviceCreateBuffer = (devicePtr, descriptor, bufferPtr) => {+ var mappedAtCreation = !!(HEAPU32[(((descriptor) + (32)) >> 2)]);+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "size": readI53FromI64((descriptor) + (24)),+ "mappedAtCreation": mappedAtCreation+ };+ var device = WebGPU.getJsObject(devicePtr);+ var buffer;+ try {+ buffer = device.createBuffer(desc);+ } catch (ex) {+ // The only exception should be RangeError if mapping at creation ran out of memory.+ return false;+ }+ WebGPU.Internals.jsObjectInsert(bufferPtr, buffer);+ if (mappedAtCreation) {+ WebGPU.Internals.bufferOnUnmaps[bufferPtr] = [];+ }+ return true;+};++var _emwgpuDeviceCreateComputePipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createComputePipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createComputePipelineAsync(desc).then(pipeline => {+ // createComputePipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateComputePipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createComputePipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateComputePipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateRenderPipelineAsync = function(devicePtr, futureId_low, futureId_high, descriptor, pipelinePtr) {+ var futureId = convertI32PairToI53Checked(futureId_low, futureId_high);+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ // createRenderPipelineAsync+ WebGPU.Internals.futureInsert(futureId, device.createRenderPipelineAsync(desc).then(pipeline => {+ // createRenderPipelineAsync fulfilled+ callUserCallback(() => {+ WebGPU.Internals.jsObjectInsert(pipelinePtr, pipeline);+ _emwgpuOnCreateRenderPipelineCompleted(futureId, 1, pipelinePtr, 0);+ });+ }, pipelineError => {+ // createRenderPipelineAsync rejected+ callUserCallback(() => {+ var sp = stackSave();+ var messagePtr = stringToUTF8OnStack(pipelineError.message);+ var status = pipelineError.reason === "validation" ? 3 : pipelineError.reason === "internal" ? 4 : 0;+ _emwgpuOnCreateRenderPipelineCompleted(futureId, status, pipelinePtr, messagePtr);+ stackRestore(sp);+ });+ }));+};++var _emwgpuDeviceCreateShaderModule = (devicePtr, descriptor, shaderModulePtr) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "code": ""+ };+ switch (sType) {+ case 2:+ {+ desc["code"] = WebGPU.makeStringFromStringView(nextInChainPtr + 8);+ break;+ }+ }+ var device = WebGPU.getJsObject(devicePtr);+ WebGPU.Internals.jsObjectInsert(shaderModulePtr, device.createShaderModule(desc));+};++var _emwgpuDeviceDestroy = devicePtr => {+ const device = WebGPU.getJsObject(devicePtr);+ // Remove the onuncapturederror handler which holds a pointer to the WGPUDevice.+ device.onuncapturederror = null;+ device.destroy();+};++var _emwgpuWaitAny = (futurePtr, futureCount, timeoutMSPtr) => {+ abort("TODO: Implement asyncify-free WaitAny for timeout=0");+};++var ENV = {};++var getExecutableName = () => thisProgram || "./this.program";++var getEnvStrings = () => {+ if (!getEnvStrings.strings) {+ // Default values.+ // Browser language detection #8751+ var lang = (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8";+ var env = {+ "USER": "web_user",+ "LOGNAME": "web_user",+ "PATH": "/",+ "PWD": "/",+ "HOME": "/home/web_user",+ "LANG": lang,+ "_": getExecutableName()+ };+ // Apply the user-provided values, if any.+ for (var x in ENV) {+ // x is a key in ENV; if ENV[x] is undefined, that means it was+ // explicitly set to be so. We allow user code to do that to+ // force variables with default values to remain unset.+ if (ENV[x] === undefined) delete env[x]; else env[x] = ENV[x];+ }+ var strings = [];+ for (var x in env) {+ strings.push(`${x}=${env[x]}`);+ }+ getEnvStrings.strings = strings;+ }+ return getEnvStrings.strings;+};++var _environ_get = (__environ, environ_buf) => {+ var bufSize = 0;+ var envp = 0;+ for (var string of getEnvStrings()) {+ var ptr = environ_buf + bufSize;+ HEAPU32[(((__environ) + (envp)) >> 2)] = ptr;+ bufSize += stringToUTF8(string, ptr, Infinity) + 1;+ envp += 4;+ }+ return 0;+};++var _environ_sizes_get = (penviron_count, penviron_buf_size) => {+ var strings = getEnvStrings();+ HEAPU32[((penviron_count) >> 2)] = strings.length;+ var bufSize = 0;+ for (var string of strings) {+ bufSize += lengthBytesUTF8(string) + 1;+ }+ HEAPU32[((penviron_buf_size) >> 2)] = bufSize;+ return 0;+};++function _fd_close(fd) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.close(stream);+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doReadv = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.read(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) break;+ // nothing more to read+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_read(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doReadv(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {+ var offset = convertI32PairToI53Checked(offset_low, offset_high);+ try {+ if (isNaN(offset)) return 61;+ var stream = SYSCALLS.getStreamFromFD(fd);+ FS.llseek(stream, offset, whence);+ (tempI64 = [ stream.position >>> 0, (tempDouble = stream.position, (+(Math.abs(tempDouble))) >= 1 ? (tempDouble > 0 ? (+(Math.floor((tempDouble) / 4294967296))) >>> 0 : (~~((+(Math.ceil((tempDouble - +(((~~(tempDouble))) >>> 0)) / 4294967296))))) >>> 0) : 0) ],+ HEAP32[((newOffset) >> 2)] = tempI64[0], HEAP32[(((newOffset) + (4)) >> 2)] = tempI64[1]);+ if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;+ // reset readdir state+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++/** @param {number=} offset */ var doWritev = (stream, iov, iovcnt, offset) => {+ var ret = 0;+ for (var i = 0; i < iovcnt; i++) {+ var ptr = HEAPU32[((iov) >> 2)];+ var len = HEAPU32[(((iov) + (4)) >> 2)];+ iov += 8;+ var curr = FS.write(stream, HEAP8, ptr, len, offset);+ if (curr < 0) return -1;+ ret += curr;+ if (curr < len) {+ // No more space to write.+ break;+ }+ if (typeof offset != "undefined") {+ offset += curr;+ }+ }+ return ret;+};++function _fd_write(fd, iov, iovcnt, pnum) {+ try {+ var stream = SYSCALLS.getStreamFromFD(fd);+ var num = doWritev(stream, iov, iovcnt);+ HEAPU32[((pnum) >> 2)] = num;+ return 0;+ } catch (e) {+ if (typeof FS == "undefined" || !(e.name === "ErrnoError")) throw e;+ return e.errno;+ }+}++var _emscripten_glActiveTexture = x0 => GLctx.activeTexture(x0);++var _glActiveTexture = _emscripten_glActiveTexture;++var _emscripten_glAttachShader = (program, shader) => {+ GLctx.attachShader(GL.programs[program], GL.shaders[shader]);+};++var _glAttachShader = _emscripten_glAttachShader;++var _emscripten_glBindAttribLocation = (program, index, name) => {+ GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));+};++var _glBindAttribLocation = _emscripten_glBindAttribLocation;++var _emscripten_glBindBuffer = (target, buffer) => {+ // Calling glBindBuffer with an unknown buffer will implicitly create a+ // new one. Here we bypass `GL.counter` and directly using the ID passed+ // in.+ if (buffer && !GL.buffers[buffer]) {+ var b = GLctx.createBuffer();+ b.name = buffer;+ GL.buffers[buffer] = b;+ }+ if (target == 34962) {+ GLctx.currentArrayBufferBinding = buffer;+ } else if (target == 34963) {+ GLctx.currentElementArrayBufferBinding = buffer;+ }+ if (target == 35051) {+ // In WebGL 2 glReadPixels entry point, we need to use a different WebGL 2+ // API function call when a buffer is bound to+ // GL_PIXEL_PACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelPackBufferBinding = buffer;+ } else if (target == 35052) {+ // In WebGL 2 gl(Compressed)Tex(Sub)Image[23]D entry points, we need to+ // use a different WebGL 2 API function call when a buffer is bound to+ // GL_PIXEL_UNPACK_BUFFER_BINDING point, so must keep track whether that+ // binding point is non-null to know what is the proper API function to+ // call.+ GLctx.currentPixelUnpackBufferBinding = buffer;+ }+ GLctx.bindBuffer(target, GL.buffers[buffer]);+};++var _glBindBuffer = _emscripten_glBindBuffer;++var _emscripten_glBindBufferBase = (target, index, buffer) => {+ GLctx.bindBufferBase(target, index, GL.buffers[buffer]);+};++var _glBindBufferBase = _emscripten_glBindBufferBase;++var _emscripten_glBindFramebuffer = (target, framebuffer) => {+ GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);+};++var _glBindFramebuffer = _emscripten_glBindFramebuffer;++var _emscripten_glBindTexture = (target, texture) => {+ GLctx.bindTexture(target, GL.textures[texture]);+};++var _glBindTexture = _emscripten_glBindTexture;++var _emscripten_glBindVertexArray = vao => {+ GLctx.bindVertexArray(GL.vaos[vao]);+ var ibo = GLctx.getParameter(34965);+ GLctx.currentElementArrayBufferBinding = ibo ? (ibo.name | 0) : 0;+};++var _glBindVertexArray = _emscripten_glBindVertexArray;++var _emscripten_glBlendEquation = x0 => GLctx.blendEquation(x0);++var _glBlendEquation = _emscripten_glBlendEquation;++var _emscripten_glBlendFunc = (x0, x1) => GLctx.blendFunc(x0, x1);++var _glBlendFunc = _emscripten_glBlendFunc;++var _emscripten_glBufferData = (target, size, data, usage) => {+ if (GL.currentContext.version >= 2) {+ // If size is zero, WebGL would interpret uploading the whole input+ // arraybuffer (starting from given offset), which would not make sense in+ // WebAssembly, so avoid uploading if size is zero. However we must still+ // call bufferData to establish a backing storage of zero bytes.+ if (data && size) {+ GLctx.bufferData(target, HEAPU8, usage, data, size);+ } else {+ GLctx.bufferData(target, size, usage);+ }+ return;+ }+ // N.b. here first form specifies a heap subarray, second form an integer+ // size, so the ?: code here is polymorphic. It is advised to avoid+ // randomly mixing both uses in calling code, to avoid any potential JS+ // engine JIT issues.+ GLctx.bufferData(target, data ? HEAPU8.subarray(data, data + size) : size, usage);+};++var _glBufferData = _emscripten_glBufferData;++var _emscripten_glClear = x0 => GLctx.clear(x0);++var _glClear = _emscripten_glClear;++var _emscripten_glClearColor = (x0, x1, x2, x3) => GLctx.clearColor(x0, x1, x2, x3);++var _glClearColor = _emscripten_glClearColor;++var convertI32PairToI53 = (lo, hi) => (lo >>> 0) + hi * 4294967296;++var _emscripten_glClientWaitSync = (sync, flags, timeout_low, timeout_high) => {+ // WebGL2 vs GLES3 differences: in GLES3, the timeout parameter is a uint64, where 0xFFFFFFFFFFFFFFFFULL means GL_TIMEOUT_IGNORED.+ // In JS, there's no 64-bit value types, so instead timeout is taken to be signed, and GL_TIMEOUT_IGNORED is given value -1.+ // Inherently the value accepted in the timeout is lossy, and can't take in arbitrary u64 bit pattern (but most likely doesn't matter)+ // See https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.15+ var timeout = convertI32PairToI53(timeout_low, timeout_high);+ return GLctx.clientWaitSync(GL.syncs[sync], flags, timeout);+};++var _glClientWaitSync = _emscripten_glClientWaitSync;++var _emscripten_glColorMask = (red, green, blue, alpha) => {+ GLctx.colorMask(!!red, !!green, !!blue, !!alpha);+};++var _glColorMask = _emscripten_glColorMask;++var _emscripten_glCompileShader = shader => {+ GLctx.compileShader(GL.shaders[shader]);+};++var _glCompileShader = _emscripten_glCompileShader;++var _emscripten_glCreateProgram = () => {+ var id = GL.getNewId(GL.programs);+ var program = GLctx.createProgram();+ // Store additional information needed for each shader program:+ program.name = id;+ // Lazy cache results of+ // glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH/GL_ACTIVE_ATTRIBUTE_MAX_LENGTH/GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH)+ program.maxUniformLength = program.maxAttributeLength = program.maxUniformBlockNameLength = 0;+ program.uniformIdCounter = 1;+ GL.programs[id] = program;+ return id;+};++var _glCreateProgram = _emscripten_glCreateProgram;++var _emscripten_glCreateShader = shaderType => {+ var id = GL.getNewId(GL.shaders);+ GL.shaders[id] = GLctx.createShader(shaderType);+ return id;+};++var _glCreateShader = _emscripten_glCreateShader;++var _emscripten_glDeleteBuffers = (n, buffers) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((buffers) + (i * 4)) >> 2)];+ var buffer = GL.buffers[id];+ // From spec: "glDeleteBuffers silently ignores 0's and names that do not+ // correspond to existing buffer objects."+ if (!buffer) continue;+ GLctx.deleteBuffer(buffer);+ buffer.name = 0;+ GL.buffers[id] = null;+ if (id == GLctx.currentArrayBufferBinding) GLctx.currentArrayBufferBinding = 0;+ if (id == GLctx.currentElementArrayBufferBinding) GLctx.currentElementArrayBufferBinding = 0;+ if (id == GLctx.currentPixelPackBufferBinding) GLctx.currentPixelPackBufferBinding = 0;+ if (id == GLctx.currentPixelUnpackBufferBinding) GLctx.currentPixelUnpackBufferBinding = 0;+ }+};++var _glDeleteBuffers = _emscripten_glDeleteBuffers;++var _emscripten_glDeleteFramebuffers = (n, framebuffers) => {+ for (var i = 0; i < n; ++i) {+ var id = HEAP32[(((framebuffers) + (i * 4)) >> 2)];+ var framebuffer = GL.framebuffers[id];+ if (!framebuffer) continue;+ // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".+ GLctx.deleteFramebuffer(framebuffer);+ framebuffer.name = 0;+ GL.framebuffers[id] = null;+ }+};++var _glDeleteFramebuffers = _emscripten_glDeleteFramebuffers;++var _emscripten_glDeleteProgram = id => {+ if (!id) return;+ var program = GL.programs[id];+ if (!program) {+ // glDeleteProgram actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteProgram(program);+ program.name = 0;+ GL.programs[id] = null;+};++var _glDeleteProgram = _emscripten_glDeleteProgram;++var _emscripten_glDeleteShader = id => {+ if (!id) return;+ var shader = GL.shaders[id];+ if (!shader) {+ // glDeleteShader actually signals an error when deleting a nonexisting+ // object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteShader(shader);+ GL.shaders[id] = null;+};++var _glDeleteShader = _emscripten_glDeleteShader;++var _emscripten_glDeleteSync = id => {+ if (!id) return;+ var sync = GL.syncs[id];+ if (!sync) {+ // glDeleteSync signals an error when deleting a nonexisting object, unlike some other GL delete functions.+ GL.recordError(1281);+ return;+ }+ GLctx.deleteSync(sync);+ sync.name = 0;+ GL.syncs[id] = null;+};++var _glDeleteSync = _emscripten_glDeleteSync;++var _emscripten_glDeleteTextures = (n, textures) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((textures) + (i * 4)) >> 2)];+ var texture = GL.textures[id];+ // GL spec: "glDeleteTextures silently ignores 0s and names that do not+ // correspond to existing textures".+ if (!texture) continue;+ GLctx.deleteTexture(texture);+ texture.name = 0;+ GL.textures[id] = null;+ }+};++var _glDeleteTextures = _emscripten_glDeleteTextures;++var _emscripten_glDeleteVertexArrays = (n, vaos) => {+ for (var i = 0; i < n; i++) {+ var id = HEAP32[(((vaos) + (i * 4)) >> 2)];+ GLctx.deleteVertexArray(GL.vaos[id]);+ GL.vaos[id] = null;+ }+};++var _glDeleteVertexArrays = _emscripten_glDeleteVertexArrays;++var _emscripten_glDetachShader = (program, shader) => {+ GLctx.detachShader(GL.programs[program], GL.shaders[shader]);+};++var _glDetachShader = _emscripten_glDetachShader;++var _emscripten_glDisable = x0 => GLctx.disable(x0);++var _glDisable = _emscripten_glDisable;++var _emscripten_glDisableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = false;+ GLctx.disableVertexAttribArray(index);+};++var _glDisableVertexAttribArray = _emscripten_glDisableVertexAttribArray;++var _emscripten_glDrawArrays = (mode, first, count) => {+ // bind any client-side buffers+ GL.preDrawHandleClientVertexAttribBindings(first + count);+ GLctx.drawArrays(mode, first, count);+ GL.postDrawHandleClientVertexAttribBindings();+};++var _glDrawArrays = _emscripten_glDrawArrays;++var tempFixedLengthArray = [];++var _emscripten_glDrawBuffers = (n, bufs) => {+ var bufArray = tempFixedLengthArray[n];+ for (var i = 0; i < n; i++) {+ bufArray[i] = HEAP32[(((bufs) + (i * 4)) >> 2)];+ }+ GLctx.drawBuffers(bufArray);+};++var _glDrawBuffers = _emscripten_glDrawBuffers;++var _emscripten_glEnable = x0 => GLctx.enable(x0);++var _glEnable = _emscripten_glEnable;++var _emscripten_glEnableVertexAttribArray = index => {+ var cb = GL.currentContext.clientBuffers[index];+ cb.enabled = true;+ GLctx.enableVertexAttribArray(index);+};++var _glEnableVertexAttribArray = _emscripten_glEnableVertexAttribArray;++var _emscripten_glFenceSync = (condition, flags) => {+ var sync = GLctx.fenceSync(condition, flags);+ if (sync) {+ var id = GL.getNewId(GL.syncs);+ sync.name = id;+ GL.syncs[id] = sync;+ return id;+ }+ return 0;+};++var _glFenceSync = _emscripten_glFenceSync;++var _emscripten_glFinish = () => GLctx.finish();++var _glFinish = _emscripten_glFinish;++var _emscripten_glFlush = () => GLctx.flush();++var _glFlush = _emscripten_glFlush;++var _emscripten_glFramebufferTexture2D = (target, attachment, textarget, texture, level) => {+ GLctx.framebufferTexture2D(target, attachment, textarget, GL.textures[texture], level);+};++var _glFramebufferTexture2D = _emscripten_glFramebufferTexture2D;++var _emscripten_glFramebufferTextureLayer = (target, attachment, texture, level, layer) => {+ GLctx.framebufferTextureLayer(target, attachment, GL.textures[texture], level, layer);+};++var _glFramebufferTextureLayer = _emscripten_glFramebufferTextureLayer;++var _emscripten_glGenBuffers = (n, buffers) => {+ GL.genObject(n, buffers, "createBuffer", GL.buffers);+};++var _glGenBuffers = _emscripten_glGenBuffers;++var _emscripten_glGenFramebuffers = (n, ids) => {+ GL.genObject(n, ids, "createFramebuffer", GL.framebuffers);+};++var _glGenFramebuffers = _emscripten_glGenFramebuffers;++var _emscripten_glGenTextures = (n, textures) => {+ GL.genObject(n, textures, "createTexture", GL.textures);+};++var _glGenTextures = _emscripten_glGenTextures;++var _emscripten_glGenVertexArrays = (n, arrays) => {+ GL.genObject(n, arrays, "createVertexArray", GL.vaos);+};++var _glGenVertexArrays = _emscripten_glGenVertexArrays;++var _emscripten_glGetAttribLocation = (program, name) => GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));++var _glGetAttribLocation = _emscripten_glGetAttribLocation;++var _emscripten_glGetError = () => {+ var error = GLctx.getError() || GL.lastError;+ GL.lastError = 0;+ return error;+};++var _glGetError = _emscripten_glGetError;++var webglGetExtensions = () => {+ var exts = getEmscriptenSupportedExtensions(GLctx);+ exts = exts.concat(exts.map(e => "GL_" + e));+ return exts;+};++var emscriptenWebGLGet = (name_, p, type) => {+ // Guard against user passing a null pointer.+ // Note that GLES2 spec does not say anything about how passing a null+ // pointer should be treated. Testing on desktop core GL 3, the application+ // crashes on glGetIntegerv to a null pointer, but better to report an error+ // instead of doing anything random.+ if (!p) {+ GL.recordError(1281);+ return;+ }+ var ret = undefined;+ switch (name_) {+ // Handle a few trivial GLES values+ case 36346:+ // GL_SHADER_COMPILER+ ret = 1;+ break;++ case 36344:+ // GL_SHADER_BINARY_FORMATS+ if (type != 0 && type != 1) {+ GL.recordError(1280);+ }+ // Do not write anything to the out pointer, since no binary formats are+ // supported.+ return;++ case 34814:+ // GL_NUM_PROGRAM_BINARY_FORMATS+ case 36345:+ // GL_NUM_SHADER_BINARY_FORMATS+ ret = 0;+ break;++ case 34466:+ // GL_NUM_COMPRESSED_TEXTURE_FORMATS+ // WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete+ // since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be+ // queried for length), so implement it ourselves to allow C++ GLES2+ // code to get the length.+ var formats = GLctx.getParameter(34467);+ ret = formats ? formats.length : 0;+ break;++ case 33309:+ // GL_NUM_EXTENSIONS+ if (GL.currentContext.version < 2) {+ // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context+ GL.recordError(1282);+ return;+ }+ ret = webglGetExtensions().length;+ break;++ case 33307:+ // GL_MAJOR_VERSION+ case 33308:+ // GL_MINOR_VERSION+ if (GL.currentContext.version < 2) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ ret = name_ == 33307 ? 3 : 0;+ // return version 3.0+ break;+ }+ if (ret === undefined) {+ var result = GLctx.getParameter(name_);+ switch (typeof result) {+ case "number":+ ret = result;+ break;++ case "boolean":+ ret = result ? 1 : 0;+ break;++ case "string":+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;++ case "object":+ if (result === null) {+ // null is a valid result for some (e.g., which buffer is bound -+ // perhaps nothing is bound), but otherwise can mean an invalid+ // name_, which we need to report as an error+ switch (name_) {+ case 34964:+ // ARRAY_BUFFER_BINDING+ case 35725:+ // CURRENT_PROGRAM+ case 34965:+ // ELEMENT_ARRAY_BUFFER_BINDING+ case 36006:+ // FRAMEBUFFER_BINDING or DRAW_FRAMEBUFFER_BINDING+ case 36007:+ // RENDERBUFFER_BINDING+ case 32873:+ // TEXTURE_BINDING_2D+ case 34229:+ // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES+ case 36662:+ // COPY_READ_BUFFER_BINDING or COPY_READ_BUFFER+ case 36663:+ // COPY_WRITE_BUFFER_BINDING or COPY_WRITE_BUFFER+ case 35053:+ // PIXEL_PACK_BUFFER_BINDING+ case 35055:+ // PIXEL_UNPACK_BUFFER_BINDING+ case 36010:+ // READ_FRAMEBUFFER_BINDING+ case 35097:+ // SAMPLER_BINDING+ case 35869:+ // TEXTURE_BINDING_2D_ARRAY+ case 32874:+ // TEXTURE_BINDING_3D+ case 36389:+ // TRANSFORM_FEEDBACK_BINDING+ case 35983:+ // TRANSFORM_FEEDBACK_BUFFER_BINDING+ case 35368:+ // UNIFORM_BUFFER_BINDING+ case 34068:+ {+ // TEXTURE_BINDING_CUBE_MAP+ ret = 0;+ break;+ }++ default:+ {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ return;+ }+ }+ } else if (result instanceof Float32Array || result instanceof Uint32Array || result instanceof Int32Array || result instanceof Array) {+ for (var i = 0; i < result.length; ++i) {+ switch (type) {+ case 0:+ HEAP32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 2:+ HEAPF32[(((p) + (i * 4)) >> 2)] = result[i];+ break;++ case 4:+ HEAP8[(p) + (i)] = result[i] ? 1 : 0;+ break;+ }+ }+ return;+ } else {+ try {+ ret = result.name | 0;+ } catch (e) {+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);+ return;+ }+ }+ break;++ default:+ GL.recordError(1280);+ // GL_INVALID_ENUM+ err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof (result)}!`);+ return;+ }+ }+ switch (type) {+ case 1:+ writeI53ToI64(p, ret);+ break;++ case 0:+ HEAP32[((p) >> 2)] = ret;+ break;++ case 2:+ HEAPF32[((p) >> 2)] = ret;+ break;++ case 4:+ HEAP8[p] = ret ? 1 : 0;+ break;+ }+};++var _emscripten_glGetFloatv = (name_, p) => emscriptenWebGLGet(name_, p, 2);++var _glGetFloatv = _emscripten_glGetFloatv;++var _emscripten_glGetIntegerv = (name_, p) => emscriptenWebGLGet(name_, p, 0);++var _glGetIntegerv = _emscripten_glGetIntegerv;++var _emscripten_glGetProgramiv = (program, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (program >= GL.counter) {+ GL.recordError(1281);+ return;+ }+ program = GL.programs[program];+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getProgramInfoLog(program);+ if (log === null) log = "(unknown error)";+ HEAP32[((p) >> 2)] = log.length + 1;+ } else if (pname == 35719) {+ if (!program.maxUniformLength) {+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (var i = 0; i < numActiveUniforms; ++i) {+ program.maxUniformLength = Math.max(program.maxUniformLength, GLctx.getActiveUniform(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformLength;+ } else if (pname == 35722) {+ if (!program.maxAttributeLength) {+ var numActiveAttributes = GLctx.getProgramParameter(program, 35721);+ for (var i = 0; i < numActiveAttributes; ++i) {+ program.maxAttributeLength = Math.max(program.maxAttributeLength, GLctx.getActiveAttrib(program, i).name.length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxAttributeLength;+ } else if (pname == 35381) {+ if (!program.maxUniformBlockNameLength) {+ var numActiveUniformBlocks = GLctx.getProgramParameter(program, 35382);+ for (var i = 0; i < numActiveUniformBlocks; ++i) {+ program.maxUniformBlockNameLength = Math.max(program.maxUniformBlockNameLength, GLctx.getActiveUniformBlockName(program, i).length + 1);+ }+ }+ HEAP32[((p) >> 2)] = program.maxUniformBlockNameLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getProgramParameter(program, pname);+ }+};++var _glGetProgramiv = _emscripten_glGetProgramiv;++var _emscripten_glGetShaderInfoLog = (shader, maxLength, length, infoLog) => {+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;+ if (length) HEAP32[((length) >> 2)] = numBytesWrittenExclNull;+};++var _glGetShaderInfoLog = _emscripten_glGetShaderInfoLog;++var _emscripten_glGetShaderiv = (shader, pname, p) => {+ if (!p) {+ // GLES2 specification does not specify how to behave if p is a null+ // pointer. Since calling this function does not make sense if p == null,+ // issue a GL error to notify user about it.+ GL.recordError(1281);+ return;+ }+ if (pname == 35716) {+ // GL_INFO_LOG_LENGTH+ var log = GLctx.getShaderInfoLog(GL.shaders[shader]);+ if (log === null) log = "(unknown error)";+ // The GLES2 specification says that if the shader has an empty info log,+ // a value of 0 is returned. Otherwise the log has a null char appended.+ // (An empty string is falsey, so we can just check that instead of+ // looking at log.length.)+ var logLength = log ? log.length + 1 : 0;+ HEAP32[((p) >> 2)] = logLength;+ } else if (pname == 35720) {+ // GL_SHADER_SOURCE_LENGTH+ var source = GLctx.getShaderSource(GL.shaders[shader]);+ // source may be a null, or the empty string, both of which are falsey+ // values that we report a 0 length for.+ var sourceLength = source ? source.length + 1 : 0;+ HEAP32[((p) >> 2)] = sourceLength;+ } else {+ HEAP32[((p) >> 2)] = GLctx.getShaderParameter(GL.shaders[shader], pname);+ }+};++var _glGetShaderiv = _emscripten_glGetShaderiv;++var _emscripten_glGetString = name_ => {+ var ret = GL.stringCache[name_];+ if (!ret) {+ switch (name_) {+ case 7939:+ ret = stringToNewUTF8(webglGetExtensions().join(" "));+ break;++ case 7936:+ case 7937:+ case 37445:+ case 37446:+ var s = GLctx.getParameter(name_);+ if (!s) {+ GL.recordError(1280);+ }+ ret = s ? stringToNewUTF8(s) : 0;+ break;++ case 7938:+ var webGLVersion = GLctx.getParameter(7938);+ // return GLES version string corresponding to the version of the WebGL context+ var glVersion = `OpenGL ES 2.0 (${webGLVersion})`;+ if (GL.currentContext.version >= 2) glVersion = `OpenGL ES 3.0 (${webGLVersion})`;+ ret = stringToNewUTF8(glVersion);+ break;++ case 35724:+ var glslVersion = GLctx.getParameter(35724);+ // extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'+ var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;+ var ver_num = glslVersion.match(ver_re);+ if (ver_num !== null) {+ if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + "0";+ // ensure minor version has 2 digits+ glslVersion = `OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`;+ }+ ret = stringToNewUTF8(glslVersion);+ break;++ default:+ GL.recordError(1280);+ }+ GL.stringCache[name_] = ret;+ }+ return ret;+};++var _glGetString = _emscripten_glGetString;++var _emscripten_glGetUniformBlockIndex = (program, uniformBlockName) => GLctx.getUniformBlockIndex(GL.programs[program], UTF8ToString(uniformBlockName));++var _glGetUniformBlockIndex = _emscripten_glGetUniformBlockIndex;++/** @suppress {checkTypes} */ var jstoi_q = str => parseInt(str);++/** @noinline */ var webglGetLeftBracePos = name => name.slice(-1) == "]" && name.lastIndexOf("[");++var webglPrepareUniformLocationsBeforeFirstUse = program => {+ var uniformLocsById = program.uniformLocsById, // Maps GLuint -> WebGLUniformLocation+ uniformSizeAndIdsByName = program.uniformSizeAndIdsByName, // Maps name -> [uniform array length, GLuint]+ i, j;+ // On the first time invocation of glGetUniformLocation on this shader program:+ // initialize cache data structures and discover which uniforms are arrays.+ if (!uniformLocsById) {+ // maps GLint integer locations to WebGLUniformLocations+ program.uniformLocsById = uniformLocsById = {};+ // maps integer locations back to uniform name strings, so that we can lazily fetch uniform array locations+ program.uniformArrayNamesById = {};+ var numActiveUniforms = GLctx.getProgramParameter(program, 35718);+ for (i = 0; i < numActiveUniforms; ++i) {+ var u = GLctx.getActiveUniform(program, i);+ var nm = u.name;+ var sz = u.size;+ var lb = webglGetLeftBracePos(nm);+ var arrayName = lb > 0 ? nm.slice(0, lb) : nm;+ // Assign a new location.+ var id = program.uniformIdCounter;+ program.uniformIdCounter += sz;+ // Eagerly get the location of the uniformArray[0] base element.+ // The remaining indices >0 will be left for lazy evaluation to+ // improve performance. Those may never be needed to fetch, if the+ // application fills arrays always in full starting from the first+ // element of the array.+ uniformSizeAndIdsByName[arrayName] = [ sz, id ];+ // Store placeholder integers in place that highlight that these+ // >0 index locations are array indices pending population.+ for (j = 0; j < sz; ++j) {+ uniformLocsById[id] = j;+ program.uniformArrayNamesById[id++] = arrayName;+ }+ }+ }+};++var _emscripten_glGetUniformLocation = (program, name) => {+ name = UTF8ToString(name);+ if (program = GL.programs[program]) {+ webglPrepareUniformLocationsBeforeFirstUse(program);+ var uniformLocsById = program.uniformLocsById;+ // Maps GLuint -> WebGLUniformLocation+ var arrayIndex = 0;+ var uniformBaseName = name;+ // Invariant: when populating integer IDs for uniform locations, we must+ // maintain the precondition that arrays reside in contiguous addresses,+ // i.e. for a 'vec4 colors[10];', colors[4] must be at location+ // colors[0]+4. However, user might call glGetUniformLocation(program,+ // "colors") for an array, so we cannot discover based on the user input+ // arguments whether the uniform we are dealing with is an array. The only+ // way to discover which uniforms are arrays is to enumerate over all the+ // active uniforms in the program.+ var leftBrace = webglGetLeftBracePos(name);+ // If user passed an array accessor "[index]", parse the array index off the accessor.+ if (leftBrace > 0) {+ arrayIndex = jstoi_q(name.slice(leftBrace + 1)) >>> 0;+ // "index]", coerce parseInt(']') with >>>0 to treat "foo[]" as "foo[0]" and foo[-1] as unsigned out-of-bounds.+ uniformBaseName = name.slice(0, leftBrace);+ }+ // Have we cached the location of this uniform before?+ // A pair [array length, GLint of the uniform location]+ var sizeAndId = program.uniformSizeAndIdsByName[uniformBaseName];+ // If a uniform with this name exists, and if its index is within the+ // array limits (if it's even an array), query the WebGLlocation, or+ // return an existing cached location.+ if (sizeAndId && arrayIndex < sizeAndId[0]) {+ arrayIndex += sizeAndId[1];+ // Add the base location of the uniform to the array index offset.+ if ((uniformLocsById[arrayIndex] = uniformLocsById[arrayIndex] || GLctx.getUniformLocation(program, name))) {+ return arrayIndex;+ }+ }+ } else {+ // N.b. we are currently unable to distinguish between GL program IDs that+ // never existed vs GL program IDs that have been deleted, so report+ // GL_INVALID_VALUE in both cases.+ GL.recordError(1281);+ }+ return -1;+};++var _glGetUniformLocation = _emscripten_glGetUniformLocation;++var _emscripten_glLineWidth = x0 => GLctx.lineWidth(x0);++var _glLineWidth = _emscripten_glLineWidth;++var _emscripten_glLinkProgram = program => {+ program = GL.programs[program];+ GLctx.linkProgram(program);+ // Invalidate earlier computed uniform->ID mappings, those have now become stale+ program.uniformLocsById = 0;+ // Mark as null-like so that glGetUniformLocation() knows to populate this again.+ program.uniformSizeAndIdsByName = {};+};++var _glLinkProgram = _emscripten_glLinkProgram;++var _emscripten_glPixelStorei = (pname, param) => {+ if (pname == 3317) {+ GL.unpackAlignment = param;+ } else if (pname == 3314) {+ GL.unpackRowLength = param;+ }+ GLctx.pixelStorei(pname, param);+};++var _glPixelStorei = _emscripten_glPixelStorei;++var computeUnpackAlignedImageSize = (width, height, sizePerPixel) => {+ function roundedToNextMultipleOf(x, y) {+ return (x + y - 1) & -y;+ }+ var plainRowSize = (GL.unpackRowLength || width) * sizePerPixel;+ var alignedRowSize = roundedToNextMultipleOf(plainRowSize, GL.unpackAlignment);+ return height * alignedRowSize;+};++var colorChannelsInGlTextureFormat = format => {+ // Micro-optimizations for size: map format to size by subtracting smallest+ // enum value (0x1902) from all values first. Also omit the most common+ // size value (1) from the list, which is assumed by formats not on the+ // list.+ var colorChannels = {+ // 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,+ // 0x1906 /* GL_ALPHA */ - 0x1902: 1,+ 5: 3,+ 6: 4,+ // 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,+ 8: 2,+ 29502: 3,+ 29504: 4,+ // 0x1903 /* GL_RED */ - 0x1902: 1,+ 26917: 2,+ 26918: 2,+ // 0x8D94 /* GL_RED_INTEGER */ - 0x1902: 1,+ 29846: 3,+ 29847: 4+ };+ return colorChannels[format - 6402] || 1;+};++var heapObjectForWebGLType = type => {+ // Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare+ // smaller values for the heap, for shorter generated code size.+ // Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.+ // (since most types are HEAPU16)+ type -= 5120;+ if (type == 0) return HEAP8;+ if (type == 1) return HEAPU8;+ if (type == 2) return HEAP16;+ if (type == 4) return HEAP32;+ if (type == 6) return HEAPF32;+ if (type == 5 || type == 28922 || type == 28520 || type == 30779 || type == 30782) return HEAPU32;+ return HEAPU16;+};++var toTypedArrayIndex = (pointer, heap) => pointer >>> (31 - Math.clz32(heap.BYTES_PER_ELEMENT));++var emscriptenWebGLGetTexPixelData = (type, format, width, height, pixels, internalFormat) => {+ var heap = heapObjectForWebGLType(type);+ var sizePerPixel = colorChannelsInGlTextureFormat(format) * heap.BYTES_PER_ELEMENT;+ var bytes = computeUnpackAlignedImageSize(width, height, sizePerPixel);+ return heap.subarray(toTypedArrayIndex(pixels, heap), toTypedArrayIndex(pixels + bytes, heap));+};++var _emscripten_glReadPixels = (x, y, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelPackBufferBinding) {+ GLctx.readPixels(x, y, width, height, format, type, pixels);+ return;+ }+ var heap = heapObjectForWebGLType(type);+ var target = toTypedArrayIndex(pixels, heap);+ GLctx.readPixels(x, y, width, height, format, type, heap, target);+ return;+ }+ var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format);+ if (!pixelData) {+ GL.recordError(1280);+ return;+ }+ GLctx.readPixels(x, y, width, height, format, type, pixelData);+};++var _glReadPixels = _emscripten_glReadPixels;++var _emscripten_glShaderSource = (shader, count, string, length) => {+ var source = GL.getSource(shader, count, string, length);+ GLctx.shaderSource(GL.shaders[shader], source);+};++var _glShaderSource = _emscripten_glShaderSource;++var _emscripten_glTexImage2D = (target, level, internalFormat, width, height, border, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ var index = toTypedArrayIndex(pixels, heap);+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, heap, index);+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null;+ GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixelData);+};++var _glTexImage2D = _emscripten_glTexImage2D;++var _emscripten_glTexParameterf = (x0, x1, x2) => GLctx.texParameterf(x0, x1, x2);++var _glTexParameterf = _emscripten_glTexParameterf;++var _emscripten_glTexParameterfv = (target, pname, params) => {+ var param = HEAPF32[((params) >> 2)];+ GLctx.texParameterf(target, pname, param);+};++var _glTexParameterfv = _emscripten_glTexParameterfv;++var _emscripten_glTexParameteri = (x0, x1, x2) => GLctx.texParameteri(x0, x1, x2);++var _glTexParameteri = _emscripten_glTexParameteri;++var _emscripten_glTexStorage2D = (x0, x1, x2, x3, x4) => GLctx.texStorage2D(x0, x1, x2, x3, x4);++var _glTexStorage2D = _emscripten_glTexStorage2D;++var _emscripten_glTexStorage3D = (x0, x1, x2, x3, x4, x5) => GLctx.texStorage3D(x0, x1, x2, x3, x4, x5);++var _glTexStorage3D = _emscripten_glTexStorage3D;++var _emscripten_glTexSubImage2D = (target, level, xoffset, yoffset, width, height, format, type, pixels) => {+ if (GL.currentContext.version >= 2) {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);+ return;+ }+ if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, heap, toTypedArrayIndex(pixels, heap));+ return;+ }+ }+ var pixelData = pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0) : null;+ GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);+};++var _glTexSubImage2D = _emscripten_glTexSubImage2D;++var _emscripten_glTexSubImage3D = (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels) => {+ if (GLctx.currentPixelUnpackBufferBinding) {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);+ } else if (pixels) {+ var heap = heapObjectForWebGLType(type);+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, heap, toTypedArrayIndex(pixels, heap));+ } else {+ GLctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, null);+ }+};++var _glTexSubImage3D = _emscripten_glTexSubImage3D;++var webglGetUniformLocation = location => {+ var p = GLctx.currentProgram;+ if (p) {+ var webglLoc = p.uniformLocsById[location];+ // p.uniformLocsById[location] stores either an integer, or a+ // WebGLUniformLocation.+ // If an integer, we have not yet bound the location, so do it now. The+ // integer value specifies the array index we should bind to.+ if (typeof webglLoc == "number") {+ p.uniformLocsById[location] = webglLoc = GLctx.getUniformLocation(p, p.uniformArrayNamesById[location] + (webglLoc > 0 ? `[${webglLoc}]` : ""));+ }+ // Else an already cached WebGLUniformLocation, return it.+ return webglLoc;+ } else {+ GL.recordError(1282);+ }+};++var _emscripten_glUniform1f = (location, v0) => {+ GLctx.uniform1f(webglGetUniformLocation(location), v0);+};++var _glUniform1f = _emscripten_glUniform1f;++var miniTempWebGLFloatBuffers = [];++var _emscripten_glUniform1fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform1fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count);+ return;+ }+ if (count <= 288) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; ++i) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 4) >> 2));+ }+ GLctx.uniform1fv(webglGetUniformLocation(location), view);+};++var _glUniform1fv = _emscripten_glUniform1fv;++var _emscripten_glUniform1i = (location, v0) => {+ GLctx.uniform1i(webglGetUniformLocation(location), v0);+};++var _glUniform1i = _emscripten_glUniform1i;++var _emscripten_glUniform2f = (location, v0, v1) => {+ GLctx.uniform2f(webglGetUniformLocation(location), v0, v1);+};++var _glUniform2f = _emscripten_glUniform2f;++var _emscripten_glUniform2fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform2fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 2);+ return;+ }+ if (count <= 144) {+ // avoid allocation when uploading few enough uniforms+ count *= 2;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 2) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 8) >> 2));+ }+ GLctx.uniform2fv(webglGetUniformLocation(location), view);+};++var _glUniform2fv = _emscripten_glUniform2fv;++var _emscripten_glUniform3f = (location, v0, v1, v2) => {+ GLctx.uniform3f(webglGetUniformLocation(location), v0, v1, v2);+};++var _glUniform3f = _emscripten_glUniform3f;++var _emscripten_glUniform4f = (location, v0, v1, v2, v3) => {+ GLctx.uniform4f(webglGetUniformLocation(location), v0, v1, v2, v3);+};++var _glUniform4f = _emscripten_glUniform4f;++var _emscripten_glUniform4fv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4fv(webglGetUniformLocation(location), HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[4 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 4;+ for (var i = 0; i < count; i += 4) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4fv(webglGetUniformLocation(location), view);+};++var _glUniform4fv = _emscripten_glUniform4fv;++var miniTempWebGLIntBuffers = [];++var _emscripten_glUniform4iv = (location, count, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniform4iv(webglGetUniformLocation(location), HEAP32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLIntBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAP32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAP32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAP32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAP32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAP32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniform4iv(webglGetUniformLocation(location), view);+};++var _glUniform4iv = _emscripten_glUniform4iv;++var _emscripten_glUniformBlockBinding = (program, uniformBlockIndex, uniformBlockBinding) => {+ program = GL.programs[program];+ GLctx.uniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);+};++var _glUniformBlockBinding = _emscripten_glUniformBlockBinding;++var _emscripten_glUniformMatrix2fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 4);+ return;+ }+ if (count <= 72) {+ // avoid allocation when uploading few enough uniforms+ count *= 4;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 4) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 16) >> 2));+ }+ GLctx.uniformMatrix2fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix2fv = _emscripten_glUniformMatrix2fv;++var _emscripten_glUniformMatrix3fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 9);+ return;+ }+ if (count <= 32) {+ // avoid allocation when uploading few enough uniforms+ count *= 9;+ var view = miniTempWebGLFloatBuffers[count];+ for (var i = 0; i < count; i += 9) {+ view[i] = HEAPF32[(((value) + (4 * i)) >> 2)];+ view[i + 1] = HEAPF32[(((value) + (4 * i + 4)) >> 2)];+ view[i + 2] = HEAPF32[(((value) + (4 * i + 8)) >> 2)];+ view[i + 3] = HEAPF32[(((value) + (4 * i + 12)) >> 2)];+ view[i + 4] = HEAPF32[(((value) + (4 * i + 16)) >> 2)];+ view[i + 5] = HEAPF32[(((value) + (4 * i + 20)) >> 2)];+ view[i + 6] = HEAPF32[(((value) + (4 * i + 24)) >> 2)];+ view[i + 7] = HEAPF32[(((value) + (4 * i + 28)) >> 2)];+ view[i + 8] = HEAPF32[(((value) + (4 * i + 32)) >> 2)];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 36) >> 2));+ }+ GLctx.uniformMatrix3fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix3fv = _emscripten_glUniformMatrix3fv;++var _emscripten_glUniformMatrix4fv = (location, count, transpose, value) => {+ if (GL.currentContext.version >= 2) {+ count && GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, HEAPF32, ((value) >> 2), count * 16);+ return;+ }+ if (count <= 18) {+ // avoid allocation when uploading few enough uniforms+ var view = miniTempWebGLFloatBuffers[16 * count];+ // hoist the heap out of the loop for size and for pthreads+growth.+ var heap = HEAPF32;+ value = ((value) >> 2);+ count *= 16;+ for (var i = 0; i < count; i += 16) {+ var dst = value + i;+ view[i] = heap[dst];+ view[i + 1] = heap[dst + 1];+ view[i + 2] = heap[dst + 2];+ view[i + 3] = heap[dst + 3];+ view[i + 4] = heap[dst + 4];+ view[i + 5] = heap[dst + 5];+ view[i + 6] = heap[dst + 6];+ view[i + 7] = heap[dst + 7];+ view[i + 8] = heap[dst + 8];+ view[i + 9] = heap[dst + 9];+ view[i + 10] = heap[dst + 10];+ view[i + 11] = heap[dst + 11];+ view[i + 12] = heap[dst + 12];+ view[i + 13] = heap[dst + 13];+ view[i + 14] = heap[dst + 14];+ view[i + 15] = heap[dst + 15];+ }+ } else {+ var view = HEAPF32.subarray((((value) >> 2)), ((value + count * 64) >> 2));+ }+ GLctx.uniformMatrix4fv(webglGetUniformLocation(location), !!transpose, view);+};++var _glUniformMatrix4fv = _emscripten_glUniformMatrix4fv;++var _emscripten_glUseProgram = program => {+ program = GL.programs[program];+ GLctx.useProgram(program);+ // Record the currently active program so that we can access the uniform+ // mapping table of that program.+ GLctx.currentProgram = program;+};++var _glUseProgram = _emscripten_glUseProgram;++var _emscripten_glVertexAttribPointer = (index, size, type, normalized, stride, ptr) => {+ var cb = GL.currentContext.clientBuffers[index];+ if (!GLctx.currentArrayBufferBinding) {+ cb.size = size;+ cb.type = type;+ cb.normalized = normalized;+ cb.stride = stride;+ cb.ptr = ptr;+ cb.clientside = true;+ cb.vertexAttribPointerAdaptor = function(index, size, type, normalized, stride, ptr) {+ this.vertexAttribPointer(index, size, type, normalized, stride, ptr);+ };+ return;+ }+ cb.clientside = false;+ GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);+};++var _glVertexAttribPointer = _emscripten_glVertexAttribPointer;++var _emscripten_glViewport = (x0, x1, x2, x3) => GLctx.viewport(x0, x1, x2, x3);++var _glViewport = _emscripten_glViewport;++function _mediapipe_find_canvas_event_target(canvasSelector) {+ let target = findCanvasEventTarget(canvasSelector);+ // WebGPU-on-worker uses this function to try to grab the canvas, but+ // doesn't have a DOM element to find. So as a quick patch, if the default+ // behavior is unsuccessful here then we try a webgpu canvas property+ // which is set by the user directly on the Module, much like how our old+ // pipeline used the Module.canvas property. See b/265271517 for details.+ if (Module && !target) {+ target = Module.canvasWebGpu;+ }+ return Emval.toHandle(target);+}++function _mediapipe_webgl_tex_image_drawable(drawableHandle) {+ const drawable = Emval.toValue(drawableHandle);+ GLctx.texImage2D(GLctx.TEXTURE_2D, 0, GLctx.RGBA, GLctx.RGBA, GLctx.UNSIGNED_BYTE, drawable);+}++var _random_get = (buffer, size) => randomFill(HEAPU8.subarray(buffer, buffer + size));++var _wgpuCommandEncoderBeginComputePass = (encoderPtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (12)) >> 2)])+ };+ }+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateComputePassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginComputePass(desc));+ return ptr;+};++var _wgpuCommandEncoderBeginRenderPass = (encoderPtr, descriptor) => {+ function makeColorAttachment(caPtr) {+ var viewPtr = HEAPU32[(((caPtr) + (4)) >> 2)];+ if (viewPtr === 0) {+ // Null `view` means no attachment in this slot.+ return undefined;+ }+ var depthSlice = HEAPU32[(((caPtr) + (8)) >> 2)];+ if (depthSlice == 4294967295) depthSlice = undefined;+ return {+ "view": WebGPU.getJsObject(viewPtr),+ "depthSlice": depthSlice,+ "resolveTarget": WebGPU.getJsObject(HEAPU32[(((caPtr) + (12)) >> 2)]),+ "clearValue": WebGPU.makeColor(caPtr + 24),+ "loadOp": WebGPU.LoadOp[HEAP32[(((caPtr) + (16)) >> 2)]],+ "storeOp": WebGPU.StoreOp[HEAP32[(((caPtr) + (20)) >> 2)]]+ };+ }+ function makeColorAttachments(count, caPtr) {+ var attachments = [];+ for (var i = 0; i < count; ++i) {+ attachments.push(makeColorAttachment(caPtr + 56 * i));+ }+ return attachments;+ }+ function makeDepthStencilAttachment(dsaPtr) {+ if (dsaPtr === 0) return undefined;+ return {+ "view": WebGPU.getJsObject(HEAPU32[(((dsaPtr) + (4)) >> 2)]),+ "depthClearValue": HEAPF32[(((dsaPtr) + (16)) >> 2)],+ "depthLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (8)) >> 2)]],+ "depthStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (12)) >> 2)]],+ "depthReadOnly": !!(HEAPU32[(((dsaPtr) + (20)) >> 2)]),+ "stencilClearValue": HEAPU32[(((dsaPtr) + (32)) >> 2)],+ "stencilLoadOp": WebGPU.LoadOp[HEAP32[(((dsaPtr) + (24)) >> 2)]],+ "stencilStoreOp": WebGPU.StoreOp[HEAP32[(((dsaPtr) + (28)) >> 2)]],+ "stencilReadOnly": !!(HEAPU32[(((dsaPtr) + (36)) >> 2)])+ };+ }+ function makeRenderPassDescriptor(descriptor) {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var maxDrawCount = undefined;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var renderPassMaxDrawCount = nextInChainPtr;+ // Note: The user could have passed a really huge value here, which is technically valid in+ // C but will not be allowed by WebGPU in JS because of [EnforceRange]. We intentionally+ // ignore that case because it's not useful - apps can just pick a smaller maxDrawCount.+ maxDrawCount = readI53FromI64((renderPassMaxDrawCount) + (8));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "colorAttachments": makeColorAttachments(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)]),+ "depthStencilAttachment": makeDepthStencilAttachment(HEAPU32[(((descriptor) + (20)) >> 2)]),+ "occlusionQuerySet": WebGPU.getJsObject(HEAPU32[(((descriptor) + (24)) >> 2)]),+ "timestampWrites": WebGPU.makePassTimestampWrites(HEAPU32[(((descriptor) + (28)) >> 2)]),+ "maxDrawCount": maxDrawCount+ };+ return desc;+ }+ var desc = makeRenderPassDescriptor(descriptor);+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateRenderPassEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.beginRenderPass(desc));+ return ptr;+};++var _wgpuCommandEncoderCopyBufferToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyBufferToTexture(WebGPU.makeTexelCopyBufferInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToBuffer = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToBuffer(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyBufferInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderCopyTextureToTexture = (encoderPtr, srcPtr, dstPtr, copySizePtr) => {+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var copySize = WebGPU.makeExtent3D(copySizePtr);+ commandEncoder.copyTextureToTexture(WebGPU.makeTexelCopyTextureInfo(srcPtr), WebGPU.makeTexelCopyTextureInfo(dstPtr), copySize);+};++var _wgpuCommandEncoderFinish = (encoderPtr, descriptor) => {+ // TODO: Use the descriptor.+ var commandEncoder = WebGPU.getJsObject(encoderPtr);+ var ptr = _emwgpuCreateCommandBuffer(0);+ WebGPU.Internals.jsObjectInsert(ptr, commandEncoder.finish());+ return ptr;+};++var _wgpuComputePassEncoderDispatchWorkgroups = (passPtr, x, y, z) => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.dispatchWorkgroups(x, y, z);+};++var _wgpuComputePassEncoderEnd = passPtr => {+ var pass = WebGPU.getJsObject(passPtr);+ pass.end();+};++var _wgpuComputePassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuComputePassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuComputePipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuDeviceCreateBindGroup = (devicePtr, descriptor) => {+ function makeEntry(entryPtr) {+ var bufferPtr = HEAPU32[(((entryPtr) + (8)) >> 2)];+ var samplerPtr = HEAPU32[(((entryPtr) + (32)) >> 2)];+ var textureViewPtr = HEAPU32[(((entryPtr) + (36)) >> 2)];+ var externalTexturePtr = 0;+ WebGPU.iterateExtensions(entryPtr, {+ 14: ptr => {+ externalTexturePtr = HEAPU32[(((ptr) + (8)) >> 2)];+ }+ });+ var resource;+ if (bufferPtr) {+ // Note the sentinel UINT64_MAX will be read as -1.+ var size = readI53FromI64((entryPtr) + (24));+ if (size == -1) size = undefined;+ resource = {+ "buffer": WebGPU.getJsObject(bufferPtr),+ "offset": readI53FromI64((entryPtr) + (16)),+ "size": size+ };+ } else {+ resource = WebGPU.getJsObject(samplerPtr || textureViewPtr || externalTexturePtr);+ }+ return {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "resource": resource+ };+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 40 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "layout": WebGPU.getJsObject(HEAPU32[(((descriptor) + (12)) >> 2)]),+ "entries": makeEntries(HEAPU32[(((descriptor) + (16)) >> 2)], HEAPU32[(((descriptor) + (20)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroup(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroup(desc));+ return ptr;+};++var _wgpuDeviceCreateBindGroupLayout = (devicePtr, descriptor) => {+ function makeBufferEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.BufferBindingType[typeInt],+ "hasDynamicOffset": !!(HEAPU32[(((substructPtr) + (8)) >> 2)]),+ "minBindingSize": readI53FromI64((substructPtr) + (16))+ };+ }+ function makeSamplerEntry(substructPtr) {+ var typeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!typeInt) return undefined;+ return {+ "type": WebGPU.SamplerBindingType[typeInt]+ };+ }+ function makeTextureEntry(substructPtr) {+ var sampleTypeInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!sampleTypeInt) return undefined;+ return {+ "sampleType": WebGPU.TextureSampleType[sampleTypeInt],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "multisampled": !!(HEAPU32[(((substructPtr) + (12)) >> 2)])+ };+ }+ function makeStorageTextureEntry(substructPtr) {+ var accessInt = HEAPU32[(((substructPtr) + (4)) >> 2)];+ if (!accessInt) return undefined;+ return {+ "access": WebGPU.StorageTextureAccess[accessInt],+ "format": WebGPU.TextureFormat[HEAP32[(((substructPtr) + (8)) >> 2)]],+ "viewDimension": WebGPU.TextureViewDimension[HEAP32[(((substructPtr) + (12)) >> 2)]]+ };+ }+ function makeEntry(entryPtr) {+ var entry = {+ "binding": HEAPU32[(((entryPtr) + (4)) >> 2)],+ "visibility": HEAPU32[(((entryPtr) + (8)) >> 2)],+ "buffer": makeBufferEntry(entryPtr + 24),+ "sampler": makeSamplerEntry(entryPtr + 48),+ "texture": makeTextureEntry(entryPtr + 56),+ "storageTexture": makeStorageTextureEntry(entryPtr + 72)+ };+ WebGPU.iterateExtensions(entryPtr, {+ 13: ptr => {+ entry["externalTexture"] = {};+ }+ });+ return entry;+ }+ function makeEntries(count, entriesPtrs) {+ var entries = [];+ for (var i = 0; i < count; ++i) {+ entries.push(makeEntry(entriesPtrs + 88 * i));+ }+ return entries;+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "entries": makeEntries(HEAPU32[(((descriptor) + (12)) >> 2)], HEAPU32[(((descriptor) + (16)) >> 2)])+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createBindGroupLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateCommandEncoder = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4)+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateCommandEncoder(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createCommandEncoder(desc));+ return ptr;+};++var _wgpuDeviceCreateComputePipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeComputePipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateComputePipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createComputePipeline(desc));+ return ptr;+};++var _wgpuDeviceCreatePipelineLayout = (devicePtr, descriptor) => {+ var bglCount = HEAPU32[(((descriptor) + (12)) >> 2)];+ var bglPtr = HEAPU32[(((descriptor) + (16)) >> 2)];+ var bgls = [];+ for (var i = 0; i < bglCount; ++i) {+ bgls.push(WebGPU.getJsObject(HEAPU32[(((bglPtr) + (4 * i)) >> 2)]));+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "bindGroupLayouts": bgls+ };+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreatePipelineLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createPipelineLayout(desc));+ return ptr;+};++var _wgpuDeviceCreateRenderPipeline = (devicePtr, descriptor) => {+ var desc = WebGPU.makeRenderPipelineDesc(descriptor);+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateRenderPipeline(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createRenderPipeline(desc));+ return ptr;+};++var _wgpuDeviceCreateSampler = (devicePtr, descriptor) => {+ var desc;+ if (descriptor) {+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "addressModeU": WebGPU.AddressMode[HEAP32[(((descriptor) + (12)) >> 2)]],+ "addressModeV": WebGPU.AddressMode[HEAP32[(((descriptor) + (16)) >> 2)]],+ "addressModeW": WebGPU.AddressMode[HEAP32[(((descriptor) + (20)) >> 2)]],+ "magFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (24)) >> 2)]],+ "minFilter": WebGPU.FilterMode[HEAP32[(((descriptor) + (28)) >> 2)]],+ "mipmapFilter": WebGPU.MipmapFilterMode[HEAP32[(((descriptor) + (32)) >> 2)]],+ "lodMinClamp": HEAPF32[(((descriptor) + (36)) >> 2)],+ "lodMaxClamp": HEAPF32[(((descriptor) + (40)) >> 2)],+ "compare": WebGPU.CompareFunction[HEAP32[(((descriptor) + (44)) >> 2)]],+ "maxAnisotropy": HEAPU16[(((descriptor) + (48)) >> 1)]+ };+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateSampler(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createSampler(desc));+ return ptr;+};++var _wgpuDeviceCreateTexture = (devicePtr, descriptor) => {+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ var textureBindingViewDimension;+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var textureBindingViewDimensionDescriptor = nextInChainPtr;+ textureBindingViewDimension = WebGPU.TextureViewDimension[HEAP32[(((textureBindingViewDimensionDescriptor) + (8)) >> 2)]];+ }+ var desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "size": WebGPU.makeExtent3D(descriptor + 28),+ "mipLevelCount": HEAPU32[(((descriptor) + (44)) >> 2)],+ "sampleCount": HEAPU32[(((descriptor) + (48)) >> 2)],+ "dimension": WebGPU.TextureDimension[HEAP32[(((descriptor) + (24)) >> 2)]],+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (40)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (16)) >> 2)],+ "textureBindingViewDimension": textureBindingViewDimension+ };+ var viewFormatCount = HEAPU32[(((descriptor) + (52)) >> 2)];+ if (viewFormatCount) {+ var viewFormatsPtr = HEAPU32[(((descriptor) + (56)) >> 2)];+ // viewFormatsPtr pointer to an array of TextureFormat which is an enum of size uint32_t+ desc["viewFormats"] = Array.from(HEAP32.subarray((((viewFormatsPtr) >> 2)), ((viewFormatsPtr + viewFormatCount * 4) >> 2)), format => WebGPU.TextureFormat[format]);+ }+ var device = WebGPU.getJsObject(devicePtr);+ var ptr = _emwgpuCreateTexture(0);+ WebGPU.Internals.jsObjectInsert(ptr, device.createTexture(desc));+ return ptr;+};++var _wgpuQueueSubmit = (queuePtr, commandCount, commands) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var cmds = Array.from(HEAP32.subarray((((commands) >> 2)), ((commands + commandCount * 4) >> 2)), id => WebGPU.getJsObject(id));+ queue.submit(cmds);+};++function _wgpuQueueWriteBuffer(queuePtr, bufferPtr, bufferOffset_low, bufferOffset_high, data, size) {+ var bufferOffset = convertI32PairToI53Checked(bufferOffset_low, bufferOffset_high);+ var queue = WebGPU.getJsObject(queuePtr);+ var buffer = WebGPU.getJsObject(bufferPtr);+ // There is a size limitation for ArrayBufferView. Work around by passing in a subarray+ // instead of the whole heap. crbug.com/1201109+ var subarray = HEAPU8.subarray(data, data + size);+ queue.writeBuffer(buffer, bufferOffset, subarray, 0, size);+}++var _wgpuQueueWriteTexture = (queuePtr, destinationPtr, data, dataSize, dataLayoutPtr, writeSizePtr) => {+ var queue = WebGPU.getJsObject(queuePtr);+ var destination = WebGPU.makeTexelCopyTextureInfo(destinationPtr);+ var dataLayout = WebGPU.makeTexelCopyBufferLayout(dataLayoutPtr);+ var writeSize = WebGPU.makeExtent3D(writeSizePtr);+ // This subarray isn't strictly necessary, but helps work around an issue+ // where Chromium makes a copy of the entire heap. crbug.com/1134457+ var subarray = HEAPU8.subarray(data, data + dataSize);+ queue.writeTexture(destination, subarray, dataLayout, writeSize);+};++var _wgpuRenderPassEncoderDraw = (passPtr, vertexCount, instanceCount, firstVertex, firstInstance) => {+ firstVertex >>>= 0;+ firstInstance >>>= 0;+ var pass = WebGPU.getJsObject(passPtr);+ pass.draw(vertexCount, instanceCount, firstVertex, firstInstance);+};++var _wgpuRenderPassEncoderEnd = encoderPtr => {+ var encoder = WebGPU.getJsObject(encoderPtr);+ encoder.end();+};++var _wgpuRenderPassEncoderSetBindGroup = (passPtr, groupIndex, groupPtr, dynamicOffsetCount, dynamicOffsetsPtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var group = WebGPU.getJsObject(groupPtr);+ if (dynamicOffsetCount == 0) {+ pass.setBindGroup(groupIndex, group);+ } else {+ pass.setBindGroup(groupIndex, group, HEAPU32, ((dynamicOffsetsPtr) >> 2), dynamicOffsetCount);+ }+};++var _wgpuRenderPassEncoderSetPipeline = (passPtr, pipelinePtr) => {+ var pass = WebGPU.getJsObject(passPtr);+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ pass.setPipeline(pipeline);+};++var _wgpuRenderPipelineGetBindGroupLayout = (pipelinePtr, groupIndex) => {+ var pipeline = WebGPU.getJsObject(pipelinePtr);+ var ptr = _emwgpuCreateBindGroupLayout(0);+ WebGPU.Internals.jsObjectInsert(ptr, pipeline.getBindGroupLayout(groupIndex));+ return ptr;+};++var _wgpuTextureCreateView = (texturePtr, descriptor) => {+ var desc;+ if (descriptor) {+ var swizzle;+ var nextInChainPtr = HEAPU32[((descriptor) >> 2)];+ if (nextInChainPtr !== 0) {+ var sType = HEAP32[(((nextInChainPtr) + (4)) >> 2)];+ var swizzleDescriptor = nextInChainPtr;+ var swizzlePtr = swizzleDescriptor + 8;+ var r = WebGPU.ComponentSwizzle[HEAP32[((swizzlePtr) >> 2)]] || "r";+ var g = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (4)) >> 2)]] || "g";+ var b = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (8)) >> 2)]] || "b";+ var a = WebGPU.ComponentSwizzle[HEAP32[(((swizzlePtr) + (12)) >> 2)]] || "a";+ swizzle = `${r}${g}${b}${a}`;+ }+ var mipLevelCount = HEAPU32[(((descriptor) + (24)) >> 2)];+ var arrayLayerCount = HEAPU32[(((descriptor) + (32)) >> 2)];+ desc = {+ "label": WebGPU.makeStringFromOptionalStringView(descriptor + 4),+ "format": WebGPU.TextureFormat[HEAP32[(((descriptor) + (12)) >> 2)]],+ "dimension": WebGPU.TextureViewDimension[HEAP32[(((descriptor) + (16)) >> 2)]],+ "baseMipLevel": HEAPU32[(((descriptor) + (20)) >> 2)],+ "mipLevelCount": mipLevelCount === 4294967295 ? undefined : mipLevelCount,+ "baseArrayLayer": HEAPU32[(((descriptor) + (28)) >> 2)],+ "arrayLayerCount": arrayLayerCount === 4294967295 ? undefined : arrayLayerCount,+ "aspect": WebGPU.TextureAspect[HEAP32[(((descriptor) + (36)) >> 2)]],+ "usage": HEAPU32[(((descriptor) + (40)) >> 2)],+ "swizzle": swizzle+ };+ }+ var texture = WebGPU.getJsObject(texturePtr);+ var ptr = _emwgpuCreateTextureView(0);+ WebGPU.Internals.jsObjectInsert(ptr, texture.createView(desc));+ return ptr;+};++var _wgpuTextureDestroy = texturePtr => {+ WebGPU.getJsObject(texturePtr).destroy();+};++var _wgpuTextureGetFormat = texturePtr => {+ var texture = WebGPU.getJsObject(texturePtr);+ // Should return the enum integer instead of string.+ return WebGPU.TextureFormat.indexOf(texture.format);+};++var getCFunc = ident => {+ var func = Module["_" + ident];+ // closure exported function+ return func;+};++var writeArrayToMemory = (array, buffer) => {+ HEAP8.set(array, buffer);+};++/**+ * @param {string|null=} returnType+ * @param {Array=} argTypes+ * @param {Array=} args+ * @param {Object=} opts+ */ var ccall = (ident, returnType, argTypes, args, opts) => {+ // For fast lookup of conversion functions+ var toC = {+ "string": str => {+ var ret = 0;+ if (str !== null && str !== undefined && str !== 0) {+ // null string+ ret = stringToUTF8OnStack(str);+ }+ return ret;+ },+ "array": arr => {+ var ret = stackAlloc(arr.length);+ writeArrayToMemory(arr, ret);+ return ret;+ }+ };+ function convertReturnValue(ret) {+ if (returnType === "string") {+ return UTF8ToString(ret);+ }+ if (returnType === "boolean") return Boolean(ret);+ return ret;+ }+ var func = getCFunc(ident);+ var cArgs = [];+ var stack = 0;+ if (args) {+ for (var i = 0; i < args.length; i++) {+ var converter = toC[argTypes[i]];+ if (converter) {+ if (stack === 0) stack = stackSave();+ cArgs[i] = converter(args[i]);+ } else {+ cArgs[i] = args[i];+ }+ }+ }+ var ret = func(...cArgs);+ function onDone(ret) {+ if (stack !== 0) stackRestore(stack);+ return convertReturnValue(ret);+ }+ ret = onDone(ret);+ return ret;+};++var FS_createPath = (...args) => FS.createPath(...args);++var FS_unlink = (...args) => FS.unlink(...args);++var FS_createLazyFile = (...args) => FS.createLazyFile(...args);++var FS_createDevice = (...args) => FS.createDevice(...args);++FS.createPreloadedFile = FS_createPreloadedFile;++FS.preloadFile = FS_preloadFile;++FS.staticInit();++// Signal GL rendering layer that processing of a new frame is about to+// start. This helps it optimize VBO double-buffering and reduce GPU stalls.+registerPreMainLoop(() => GL.newRenderingFrameStarted());++for (let i = 0; i < 32; ++i) tempFixedLengthArray.push(new Array(i));++var miniTempWebGLFloatBuffersStorage = new Float32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLFloatBuffers[i] = miniTempWebGLFloatBuffersStorage.subarray(0, i);+}++var miniTempWebGLIntBuffersStorage = new Int32Array(288);++// Create GL_POOL_TEMP_BUFFERS_SIZE+1 temporary buffers, for uploads of size 0 through GL_POOL_TEMP_BUFFERS_SIZE inclusive+for (/**@suppress{duplicate}*/ var i = 0; i <= 288; ++i) {+ miniTempWebGLIntBuffers[i] = miniTempWebGLIntBuffersStorage.subarray(0, i);+}++// End JS library code+// include: postlibrary.js+// This file is included after the automatically-generated JS library code+// but before the wasm module is created.+{+ // Begin ATMODULES hooks+ if (Module["preloadPlugins"]) preloadPlugins = Module["preloadPlugins"];+ if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];+ if (Module["print"]) out = Module["print"];+ if (Module["printErr"]) err = Module["printErr"];+ if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];+ // End ATMODULES hooks+ if (Module["arguments"]) arguments_ = Module["arguments"];+ if (Module["thisProgram"]) thisProgram = Module["thisProgram"];+ if (Module["preInit"]) {+ if (typeof Module["preInit"] == "function") Module["preInit"] = [ Module["preInit"] ];+ while (Module["preInit"].length > 0) {+ Module["preInit"].shift()();+ }+ }+}++// Begin runtime exports+Module["addRunDependency"] = addRunDependency;++Module["removeRunDependency"] = removeRunDependency;++Module["ccall"] = ccall;++Module["stringToNewUTF8"] = stringToNewUTF8;++Module["FS_preloadFile"] = FS_preloadFile;++Module["FS_unlink"] = FS_unlink;++Module["FS_createPath"] = FS_createPath;++Module["FS_createDevice"] = FS_createDevice;++Module["FS_createDataFile"] = FS_createDataFile;++Module["FS_createLazyFile"] = FS_createLazyFile;++// End runtime exports+// Begin JS library exports+// End JS library exports+// end include: postlibrary.js+var ASM_CONSTS = {+ 1461389: $0 => {+ const canvas = Emval.toValue($0);+ const context = canvas.getContext("webgpu");+ return WebGPU.importJsTexture(context.getCurrentTexture());+ },+ 1461532: ($0, $1, $2, $3, $4) => {+ const drawable = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const texture = WebGPU.getJsObject($2);+ const width = $3;+ const height = $4;+ device.queue.copyExternalImageToTexture({+ source: drawable+ }, {+ texture+ }, [ width, height ]);+ },+ 1461791: ($0, $1, $2, $3) => {+ const sourceExtTex = Emval.toValue($0);+ const device = WebGPU.getJsObject($1);+ const sampler = WebGPU.getJsObject($2);+ const bgLayout = WebGPU.getJsObject($3);+ const bindGroup = device.createBindGroup({+ layout: bgLayout,+ entries: [ {+ binding: 0,+ resource: sampler+ }, {+ binding: 1,+ resource: sourceExtTex+ } ]+ });+ return WebGPU.importJsBindGroup(bindGroup);+ },+ 1462161: ($0, $1) => {+ const input = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ ctx.drawImage(input, 0, 0, output.width, output.height);+ },+ 1462326: ($0, $1) => {+ const inputArray = Emval.toValue($0);+ const output = Emval.toValue($1);+ const ctx = output.getContext("2d");+ const image_data = new ImageData(inputArray, output.width, output.height);+ ctx.putImageData(image_data, 0, 0);+ },+ 1462550: ($0, $1) => {+ const input = Emval.toValue($0);+ const outputArray = Emval.toValue($1);+ const ctx = input.getContext("2d");+ const data = ctx.getImageData(0, 0, input.width, input.height);+ outputArray.set(data.data);+ },+ 1462754: () => (typeof HTMLCanvasElement !== "undefined"),+ 1462809: () => !!Module["preinitializedWebGPUDevice"],+ 1462860: () => {+ specialHTMLTargets["#canvas"] = Module.canvas;+ }+};++function BeginGlQueryTiming(calc_name, num_repetitions) {+ const gl = Module.canvas.getContext("webgl2");+ const query = gl.createQuery();+ Module.WEBGL_SHADER_CALC_METRICS = Module.WEBGL_SHADER_CALC_METRICS || {};+ Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)] = {+ query,+ repetitions: num_repetitions+ };+ Module.WEBGL_QUERY_TIMER_EXT = Module.WEBGL_QUERY_TIMER_EXT || gl.getExtension("EXT_disjoint_timer_query_webgl2");+ gl.beginQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, query);+}++function EndGlQueryTiming(calc_name) {+ const gl = Module.canvas.getContext("webgl2");+ gl.endQuery(Module.WEBGL_QUERY_TIMER_EXT.TIME_ELAPSED_EXT, Module.WEBGL_SHADER_CALC_METRICS[UTF8ToString(calc_name)].query);+}++function JsWrapImageConverter() {+ if (!Module._imageConverter) {+ Module._imageConverter = (binaryPtr, binarySize, width, height, numChannels, makeDeepCopy, outputType) => {+ const imageData = new outputType(makeDeepCopy ? Module.HEAPU8.slice(binaryPtr, binaryPtr + binarySize).buffer : Module.HEAPU8.buffer, binaryPtr, width * height * numChannels);+ return {+ data: imageData,+ width,+ height+ };+ };+ }+}++function JsOnUint8ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnFloat32ArrayImageListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, timestamp_ms);+}++function JsOnWebGLTextureListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, timestamp_ms);+}++function JsOnUint8ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Uint8Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnFloat32ArrayImageVectorListener(output_stream_name, binary_ptr, binary_size, width, height, num_channels, make_deep_copy, timestamp_ms) {+ const image = Module._imageConverter(binary_ptr, binary_size, width, height, num_channels, make_deep_copy, Float32Array);+ Module._wrapSimpleListenerOutput(output_stream_name, image, false, timestamp_ms);+}++function JsOnWebGLTextureVectorListener(output_stream_name, name, width, height, timestamp_ms) {+ Module._wrapSimpleListenerOutput(output_stream_name, {+ data: GL.textures[name],+ width,+ height+ }, false, timestamp_ms);+}++function JsOnEmptyPacketListener(output_stream_name, timestamp) {+ Module._wrapEmptyPacketListenerOutput(output_stream_name, timestamp);+}++function JsOnVectorFinishedListener(output_stream_name, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, undefined, true, timestamp);+}++function JsOnSimpleListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerBool(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerInt(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerUint(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerDouble(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, timestamp);+}++function JsOnVectorListenerFloat(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, out_data, false, timestamp);+}++function JsOnSimpleListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), timestamp);+}++function JsOnVectorListenerString(output_stream_name, out_data, timestamp) {+ Module._wrapSimpleListenerOutput(output_stream_name, UTF8ToString(out_data), false, timestamp);+}++function JsOnVectorListenerProto(output_stream_name, proto_ptr, proto_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(proto_ptr, proto_ptr + proto_size) : new Uint8Array(Module.HEAPU8.buffer, proto_ptr, proto_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, false, timestamp);+}++function JsWrapSimpleListeners() {+ if (!Module._wrapSimpleListenerOutput) {+ Module._wrapSimpleListenerOutput = (outputStreamName, ...args) => {+ if (Module.simpleListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.simpleListeners[streamName]) {+ Module.simpleListeners[streamName](...args);+ }+ }+ };+ }+ if (!Module._wrapEmptyPacketListenerOutput) {+ Module._wrapEmptyPacketListenerOutput = (outputStreamName, timestamp) => {+ if (Module.emptyPacketListeners) {+ const streamName = UTF8ToString(outputStreamName);+ if (Module.emptyPacketListeners[streamName]) {+ Module.emptyPacketListeners[streamName](timestamp);+ }+ }+ };+ }+}++function JsOnSimpleListenerBinaryArray(output_stream_name, binary_ptr, binary_size, make_deep_copy, timestamp) {+ const newProtoArray = make_deep_copy ? Module.HEAPU8.slice(binary_ptr, binary_ptr + binary_size) : new Uint8Array(Module.HEAPU8.buffer, binary_ptr, binary_size);+ Module._wrapSimpleListenerOutput(output_stream_name, newProtoArray, timestamp);+}++function mediapipe_import_external_texture(device_handle, source_handle) {+ const device = WebGPU.getJsObject(device_handle);+ const source = Emval.toValue(source_handle);+ const externalTexture = device.importExternalTexture({+ source+ });+ return Emval.toHandle(externalTexture);+}++function mediapipe_create_utility_canvas2d() {+ let canvas;+ if (typeof HTMLCanvasElement !== "undefined") {+ canvas = document.createElement("canvas");+ canvas.style.display = "none";+ } else {+ canvas = new OffscreenCanvas(0, 0);+ }+ return Emval.toHandle(canvas);+}++function GetAdapterArchitecture() {+ const device = Module["preinitializedWebGPUDevice"];+ const architecture = device.adapterInfo ? device.adapterInfo.architecture : "Unknown";+ return stringToNewUTF8(architecture);+}++function GetAdapterDescription() {+ const device = Module["preinitializedWebGPUDevice"];+ const description = device.adapterInfo ? device.adapterInfo.description : "Unknown";+ return stringToNewUTF8(description);+}++function GetAdapterDeviceName() {+ const device = Module["preinitializedWebGPUDevice"];+ const deviceName = device.adapterInfo ? device.adapterInfo.device : "Unknown";+ return stringToNewUTF8(deviceName);+}++function GetAdapterVendor() {+ const device = Module["preinitializedWebGPUDevice"];+ const vendor = device.adapterInfo ? device.adapterInfo.vendor : "Unknown";+ return stringToNewUTF8(vendor);+}++function __asyncjs__mediapipe_map_buffer_jspi(buffer_handle, data) {+ return Asyncify.handleAsync(async () => {+ const buffer = WebGPU.getJsObject(buffer_handle);+ if ("mapSync" in buffer) {+ buffer.mapSync(GPUMapMode.READ);+ } else {+ await buffer.mapAsync(GPUMapMode.READ);+ }+ const mapped = buffer.getMappedRange();+ HEAPU8.set(new Uint8Array(mapped), data);+ buffer.unmap();+ });+}++function JsWrapErrorListener(code, message) {+ if (Module.errorListener) {+ const stringMessage = UTF8ToString(message);+ Module.errorListener(code, stringMessage);+ }+}++function UseBottomLeftGpuOrigin() {+ return (Module && Module.gpuOriginForWebTexturesIsBottomLeft);+}++function custom_emscripten_dbgn(str, len) {+ if (typeof (dbg) !== "undefined") {+ dbg(UTF8ToString(str, len));+ } else {+ if (typeof (custom_dbg) === "undefined") {+ function custom_dbg(text) {+ console.warn.apply(console, arguments);+ }+ }+ custom_dbg(UTF8ToString(str, len));+ }+}++// Imports from the Wasm binary.+var _free, _malloc, _wgpuDeviceAddRef, _addBoundTextureAsImageToStream, _attachImageListener, _attachImageVectorListener, _registerModelResourcesGraphService, _bindTextureToStream, _addBoundTextureToStream, _addDoubleToInputStream, _addFloatToInputStream, _addBoolToInputStream, _addIntToInputStream, _addUintToInputStream, _addStringToInputStream, _addRawDataSpanToInputStream, _allocateBoolVector, _allocateFloatVector, _allocateDoubleVector, _allocateIntVector, _allocateUintVector, _allocateStringVector, _addBoolVectorEntry, _addFloatVectorEntry, _addDoubleVectorEntry, _addIntVectorEntry, _addUintVectorEntry, _addStringVectorEntry, _addBoolVectorToInputStream, _addFloatVectorToInputStream, _addDoubleVectorToInputStream, _addIntVectorToInputStream, _addUintVectorToInputStream, _addStringVectorToInputStream, _addFlatHashMapToInputStream, _addProtoToInputStream, _addEmptyPacketToInputStream, _addBoolToInputSidePacket, _addDoubleToInputSidePacket, _addFloatToInputSidePacket, _addIntToInputSidePacket, _addUintToInputSidePacket, _addStringToInputSidePacket, _addRawDataSpanToInputSidePacket, _addProtoToInputSidePacket, _addBoolVectorToInputSidePacket, _addDoubleVectorToInputSidePacket, _addFloatVectorToInputSidePacket, _addIntVectorToInputSidePacket, _addUintVectorToInputSidePacket, _addStringVectorToInputSidePacket, _attachBoolListener, _attachBoolVectorListener, _attachDoubleListener, _attachDoubleVectorListener, _attachFloatListener, _attachFloatVectorListener, _attachIntListener, _attachIntVectorListener, _attachUintListener, _attachUintVectorListener, _attachStringListener, _attachStringVectorListener, _attachProtoListener, _attachProtoVectorListener, _getGraphConfig, ___getTypeName, _emwgpuCreateBindGroup, _emwgpuCreateBindGroupLayout, _emwgpuCreateCommandBuffer, _emwgpuCreateCommandEncoder, _emwgpuCreateComputePassEncoder, _emwgpuCreateComputePipeline, _emwgpuCreateExternalTexture, _emwgpuCreatePipelineLayout, _emwgpuCreateQuerySet, _emwgpuCreateRenderBundle, _emwgpuCreateRenderBundleEncoder, _emwgpuCreateRenderPassEncoder, _emwgpuCreateRenderPipeline, _emwgpuCreateSampler, _emwgpuCreateSurface, _emwgpuCreateTexture, _emwgpuCreateTextureView, _emwgpuCreateAdapter, _emwgpuImportBuffer, _emwgpuCreateDevice, _emwgpuCreateQueue, _emwgpuCreateShaderModule, _emwgpuOnCreateComputePipelineCompleted, _emwgpuOnCreateRenderPipelineCompleted, _clearSubgraphs, _pushBinarySubgraph, _pushTextSubgraph, _changeBinaryGraph, _changeTextGraph, _processGl, _process, _bindTextureToCanvas, _requestShaderRefreshOnGraphChange, _waitUntilIdle, _closeGraph, _setAutoRenderToScreen, _emscripten_builtin_memalign, _memalign, __emscripten_tempret_set, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, dynCall_ji, dynCall_jii, dynCall_iiiijij, dynCall_viiji, dynCall_viji, dynCall_iiiji, dynCall_jjj, dynCall_iiiijj, dynCall_viijj, dynCall_viiijjj, dynCall_vij, dynCall_viiiji, dynCall_viijii, dynCall_vijjj, dynCall_vj, dynCall_viij, dynCall_jiji, dynCall_iiiiij, dynCall_iiiiijj, dynCall_iiiiiijj, memory, _kVersionStampBuildChangelistStr, _kVersionStampCitcSnapshotStr, _kVersionStampCitcWorkspaceIdStr, _kVersionStampSourceUriStr, _kVersionStampBuildClientStr, _kVersionStampBuildClientMintStatusStr, _kVersionStampBuildCompilerStr, _kVersionStampBuildDateTimePstStr, _kVersionStampBuildDepotPathStr, _kVersionStampBuildIdStr, _kVersionStampBuildInfoStr, _kVersionStampBuildLabelStr, _kVersionStampBuildTargetStr, _kVersionStampBuildTimestampStr, _kVersionStampBuildToolStr, _kVersionStampG3BuildTargetStr, _kVersionStampVerifiableStr, _kVersionStampBuildFdoTypeStr, _kVersionStampBuildBaselineChangelistStr, _kVersionStampBuildLtoTypeStr, _kVersionStampBuildPropellerTypeStr, _kVersionStampBuildPghoTypeStr, _kVersionStampBuildUsernameStr, _kVersionStampBuildHostnameStr, _kVersionStampBuildDirectoryStr, _kVersionStampBuildChangelistInt, _kVersionStampCitcSnapshotInt, _kVersionStampBuildClientMintStatusInt, _kVersionStampBuildTimestampInt, _kVersionStampVerifiableInt, _kVersionStampBuildCoverageEnabledInt, _kVersionStampBuildBaselineChangelistInt, _kVersionStampPrecookedTimestampStr, _kVersionStampPrecookedClientInfoStr, __indirect_function_table, wasmMemory, wasmTable;++function assignWasmExports(wasmExports) {+ _free = Module["_free"] = wasmExports["Sd"];+ _malloc = Module["_malloc"] = wasmExports["Td"];+ _wgpuDeviceAddRef = wasmExports["Ud"];+ _addBoundTextureAsImageToStream = Module["_addBoundTextureAsImageToStream"] = wasmExports["Vd"];+ _attachImageListener = Module["_attachImageListener"] = wasmExports["Wd"];+ _attachImageVectorListener = Module["_attachImageVectorListener"] = wasmExports["Xd"];+ _registerModelResourcesGraphService = Module["_registerModelResourcesGraphService"] = wasmExports["Yd"];+ _bindTextureToStream = Module["_bindTextureToStream"] = wasmExports["Zd"];+ _addBoundTextureToStream = Module["_addBoundTextureToStream"] = wasmExports["_d"];+ _addDoubleToInputStream = Module["_addDoubleToInputStream"] = wasmExports["$d"];+ _addFloatToInputStream = Module["_addFloatToInputStream"] = wasmExports["ae"];+ _addBoolToInputStream = Module["_addBoolToInputStream"] = wasmExports["be"];+ _addIntToInputStream = Module["_addIntToInputStream"] = wasmExports["ce"];+ _addUintToInputStream = Module["_addUintToInputStream"] = wasmExports["de"];+ _addStringToInputStream = Module["_addStringToInputStream"] = wasmExports["ee"];+ _addRawDataSpanToInputStream = Module["_addRawDataSpanToInputStream"] = wasmExports["fe"];+ _allocateBoolVector = Module["_allocateBoolVector"] = wasmExports["ge"];+ _allocateFloatVector = Module["_allocateFloatVector"] = wasmExports["he"];+ _allocateDoubleVector = Module["_allocateDoubleVector"] = wasmExports["ie"];+ _allocateIntVector = Module["_allocateIntVector"] = wasmExports["je"];+ _allocateUintVector = Module["_allocateUintVector"] = wasmExports["ke"];+ _allocateStringVector = Module["_allocateStringVector"] = wasmExports["le"];+ _addBoolVectorEntry = Module["_addBoolVectorEntry"] = wasmExports["me"];+ _addFloatVectorEntry = Module["_addFloatVectorEntry"] = wasmExports["ne"];+ _addDoubleVectorEntry = Module["_addDoubleVectorEntry"] = wasmExports["oe"];+ _addIntVectorEntry = Module["_addIntVectorEntry"] = wasmExports["pe"];+ _addUintVectorEntry = Module["_addUintVectorEntry"] = wasmExports["qe"];+ _addStringVectorEntry = Module["_addStringVectorEntry"] = wasmExports["re"];+ _addBoolVectorToInputStream = Module["_addBoolVectorToInputStream"] = wasmExports["se"];+ _addFloatVectorToInputStream = Module["_addFloatVectorToInputStream"] = wasmExports["te"];+ _addDoubleVectorToInputStream = Module["_addDoubleVectorToInputStream"] = wasmExports["ue"];+ _addIntVectorToInputStream = Module["_addIntVectorToInputStream"] = wasmExports["ve"];+ _addUintVectorToInputStream = Module["_addUintVectorToInputStream"] = wasmExports["we"];+ _addStringVectorToInputStream = Module["_addStringVectorToInputStream"] = wasmExports["xe"];+ _addFlatHashMapToInputStream = Module["_addFlatHashMapToInputStream"] = wasmExports["ye"];+ _addProtoToInputStream = Module["_addProtoToInputStream"] = wasmExports["ze"];+ _addEmptyPacketToInputStream = Module["_addEmptyPacketToInputStream"] = wasmExports["Ae"];+ _addBoolToInputSidePacket = Module["_addBoolToInputSidePacket"] = wasmExports["Be"];+ _addDoubleToInputSidePacket = Module["_addDoubleToInputSidePacket"] = wasmExports["Ce"];+ _addFloatToInputSidePacket = Module["_addFloatToInputSidePacket"] = wasmExports["De"];+ _addIntToInputSidePacket = Module["_addIntToInputSidePacket"] = wasmExports["Ee"];+ _addUintToInputSidePacket = Module["_addUintToInputSidePacket"] = wasmExports["Fe"];+ _addStringToInputSidePacket = Module["_addStringToInputSidePacket"] = wasmExports["Ge"];+ _addRawDataSpanToInputSidePacket = Module["_addRawDataSpanToInputSidePacket"] = wasmExports["He"];+ _addProtoToInputSidePacket = Module["_addProtoToInputSidePacket"] = wasmExports["Ie"];+ _addBoolVectorToInputSidePacket = Module["_addBoolVectorToInputSidePacket"] = wasmExports["Je"];+ _addDoubleVectorToInputSidePacket = Module["_addDoubleVectorToInputSidePacket"] = wasmExports["Ke"];+ _addFloatVectorToInputSidePacket = Module["_addFloatVectorToInputSidePacket"] = wasmExports["Le"];+ _addIntVectorToInputSidePacket = Module["_addIntVectorToInputSidePacket"] = wasmExports["Me"];+ _addUintVectorToInputSidePacket = Module["_addUintVectorToInputSidePacket"] = wasmExports["Ne"];+ _addStringVectorToInputSidePacket = Module["_addStringVectorToInputSidePacket"] = wasmExports["Oe"];+ _attachBoolListener = Module["_attachBoolListener"] = wasmExports["Pe"];+ _attachBoolVectorListener = Module["_attachBoolVectorListener"] = wasmExports["Qe"];+ _attachDoubleListener = Module["_attachDoubleListener"] = wasmExports["Re"];+ _attachDoubleVectorListener = Module["_attachDoubleVectorListener"] = wasmExports["Se"];+ _attachFloatListener = Module["_attachFloatListener"] = wasmExports["Te"];+ _attachFloatVectorListener = Module["_attachFloatVectorListener"] = wasmExports["Ue"];+ _attachIntListener = Module["_attachIntListener"] = wasmExports["Ve"];+ _attachIntVectorListener = Module["_attachIntVectorListener"] = wasmExports["We"];+ _attachUintListener = Module["_attachUintListener"] = wasmExports["Xe"];+ _attachUintVectorListener = Module["_attachUintVectorListener"] = wasmExports["Ye"];+ _attachStringListener = Module["_attachStringListener"] = wasmExports["Ze"];+ _attachStringVectorListener = Module["_attachStringVectorListener"] = wasmExports["_e"];+ _attachProtoListener = Module["_attachProtoListener"] = wasmExports["$e"];+ _attachProtoVectorListener = Module["_attachProtoVectorListener"] = wasmExports["af"];+ _getGraphConfig = Module["_getGraphConfig"] = wasmExports["bf"];+ ___getTypeName = wasmExports["cf"];+ _emwgpuCreateBindGroup = wasmExports["df"];+ _emwgpuCreateBindGroupLayout = wasmExports["ef"];+ _emwgpuCreateCommandBuffer = wasmExports["ff"];+ _emwgpuCreateCommandEncoder = wasmExports["gf"];+ _emwgpuCreateComputePassEncoder = wasmExports["hf"];+ _emwgpuCreateComputePipeline = wasmExports["jf"];+ _emwgpuCreateExternalTexture = wasmExports["kf"];+ _emwgpuCreatePipelineLayout = wasmExports["lf"];+ _emwgpuCreateQuerySet = wasmExports["mf"];+ _emwgpuCreateRenderBundle = wasmExports["nf"];+ _emwgpuCreateRenderBundleEncoder = wasmExports["of"];+ _emwgpuCreateRenderPassEncoder = wasmExports["pf"];+ _emwgpuCreateRenderPipeline = wasmExports["qf"];+ _emwgpuCreateSampler = wasmExports["rf"];+ _emwgpuCreateSurface = wasmExports["sf"];+ _emwgpuCreateTexture = wasmExports["tf"];+ _emwgpuCreateTextureView = wasmExports["uf"];+ _emwgpuCreateAdapter = wasmExports["vf"];+ _emwgpuImportBuffer = wasmExports["wf"];+ _emwgpuCreateDevice = wasmExports["xf"];+ _emwgpuCreateQueue = wasmExports["yf"];+ _emwgpuCreateShaderModule = wasmExports["zf"];+ _emwgpuOnCreateComputePipelineCompleted = wasmExports["Af"];+ _emwgpuOnCreateRenderPipelineCompleted = wasmExports["Bf"];+ _clearSubgraphs = Module["_clearSubgraphs"] = wasmExports["Cf"];+ _pushBinarySubgraph = Module["_pushBinarySubgraph"] = wasmExports["Df"];+ _pushTextSubgraph = Module["_pushTextSubgraph"] = wasmExports["Ef"];+ _changeBinaryGraph = Module["_changeBinaryGraph"] = wasmExports["Ff"];+ _changeTextGraph = Module["_changeTextGraph"] = wasmExports["Gf"];+ _processGl = Module["_processGl"] = wasmExports["Hf"];+ _process = Module["_process"] = wasmExports["If"];+ _bindTextureToCanvas = Module["_bindTextureToCanvas"] = wasmExports["Jf"];+ _requestShaderRefreshOnGraphChange = Module["_requestShaderRefreshOnGraphChange"] = wasmExports["Kf"];+ _waitUntilIdle = Module["_waitUntilIdle"] = wasmExports["Lf"];+ _closeGraph = Module["_closeGraph"] = wasmExports["Mf"];+ _setAutoRenderToScreen = Module["_setAutoRenderToScreen"] = wasmExports["Nf"];+ _emscripten_builtin_memalign = wasmExports["Of"];+ _memalign = wasmExports["Pf"];+ __emscripten_tempret_set = wasmExports["Qf"];+ __emscripten_stack_restore = wasmExports["Rf"];+ __emscripten_stack_alloc = wasmExports["Sf"];+ _emscripten_stack_get_current = wasmExports["Tf"];+ dynCall_ji = wasmExports["dynCall_ji"];+ dynCall_jii = wasmExports["dynCall_jii"];+ dynCall_iiiijij = wasmExports["dynCall_iiiijij"];+ dynCall_viiji = wasmExports["dynCall_viiji"];+ dynCall_viji = wasmExports["dynCall_viji"];+ dynCall_iiiji = wasmExports["dynCall_iiiji"];+ dynCall_jjj = wasmExports["dynCall_jjj"];+ dynCall_iiiijj = wasmExports["dynCall_iiiijj"];+ dynCall_viijj = wasmExports["dynCall_viijj"];+ dynCall_viiijjj = wasmExports["dynCall_viiijjj"];+ dynCall_vij = wasmExports["dynCall_vij"];+ dynCall_viiiji = wasmExports["dynCall_viiiji"];+ dynCall_viijii = wasmExports["dynCall_viijii"];+ dynCall_vijjj = wasmExports["dynCall_vijjj"];+ dynCall_vj = wasmExports["dynCall_vj"];+ dynCall_viij = wasmExports["dynCall_viij"];+ dynCall_jiji = wasmExports["dynCall_jiji"];+ dynCall_iiiiij = wasmExports["dynCall_iiiiij"];+ dynCall_iiiiijj = wasmExports["dynCall_iiiiijj"];+ dynCall_iiiiiijj = wasmExports["dynCall_iiiiiijj"];+ memory = wasmMemory = wasmExports["hd"];+ _kVersionStampBuildChangelistStr = Module["_kVersionStampBuildChangelistStr"] = wasmExports["jd"].value;+ _kVersionStampCitcSnapshotStr = Module["_kVersionStampCitcSnapshotStr"] = wasmExports["kd"].value;+ _kVersionStampCitcWorkspaceIdStr = Module["_kVersionStampCitcWorkspaceIdStr"] = wasmExports["ld"].value;+ _kVersionStampSourceUriStr = Module["_kVersionStampSourceUriStr"] = wasmExports["md"].value;+ _kVersionStampBuildClientStr = Module["_kVersionStampBuildClientStr"] = wasmExports["nd"].value;+ _kVersionStampBuildClientMintStatusStr = Module["_kVersionStampBuildClientMintStatusStr"] = wasmExports["od"].value;+ _kVersionStampBuildCompilerStr = Module["_kVersionStampBuildCompilerStr"] = wasmExports["pd"].value;+ _kVersionStampBuildDateTimePstStr = Module["_kVersionStampBuildDateTimePstStr"] = wasmExports["qd"].value;+ _kVersionStampBuildDepotPathStr = Module["_kVersionStampBuildDepotPathStr"] = wasmExports["rd"].value;+ _kVersionStampBuildIdStr = Module["_kVersionStampBuildIdStr"] = wasmExports["sd"].value;+ _kVersionStampBuildInfoStr = Module["_kVersionStampBuildInfoStr"] = wasmExports["td"].value;+ _kVersionStampBuildLabelStr = Module["_kVersionStampBuildLabelStr"] = wasmExports["ud"].value;+ _kVersionStampBuildTargetStr = Module["_kVersionStampBuildTargetStr"] = wasmExports["vd"].value;+ _kVersionStampBuildTimestampStr = Module["_kVersionStampBuildTimestampStr"] = wasmExports["wd"].value;+ _kVersionStampBuildToolStr = Module["_kVersionStampBuildToolStr"] = wasmExports["xd"].value;+ _kVersionStampG3BuildTargetStr = Module["_kVersionStampG3BuildTargetStr"] = wasmExports["yd"].value;+ _kVersionStampVerifiableStr = Module["_kVersionStampVerifiableStr"] = wasmExports["zd"].value;+ _kVersionStampBuildFdoTypeStr = Module["_kVersionStampBuildFdoTypeStr"] = wasmExports["Ad"].value;+ _kVersionStampBuildBaselineChangelistStr = Module["_kVersionStampBuildBaselineChangelistStr"] = wasmExports["Bd"].value;+ _kVersionStampBuildLtoTypeStr = Module["_kVersionStampBuildLtoTypeStr"] = wasmExports["Cd"].value;+ _kVersionStampBuildPropellerTypeStr = Module["_kVersionStampBuildPropellerTypeStr"] = wasmExports["Dd"].value;+ _kVersionStampBuildPghoTypeStr = Module["_kVersionStampBuildPghoTypeStr"] = wasmExports["Ed"].value;+ _kVersionStampBuildUsernameStr = Module["_kVersionStampBuildUsernameStr"] = wasmExports["Fd"].value;+ _kVersionStampBuildHostnameStr = Module["_kVersionStampBuildHostnameStr"] = wasmExports["Gd"].value;+ _kVersionStampBuildDirectoryStr = Module["_kVersionStampBuildDirectoryStr"] = wasmExports["Hd"].value;+ _kVersionStampBuildChangelistInt = Module["_kVersionStampBuildChangelistInt"] = wasmExports["Id"].value;+ _kVersionStampCitcSnapshotInt = Module["_kVersionStampCitcSnapshotInt"] = wasmExports["Jd"].value;+ _kVersionStampBuildClientMintStatusInt = Module["_kVersionStampBuildClientMintStatusInt"] = wasmExports["Kd"].value;+ _kVersionStampBuildTimestampInt = Module["_kVersionStampBuildTimestampInt"] = wasmExports["Ld"].value;+ _kVersionStampVerifiableInt = Module["_kVersionStampVerifiableInt"] = wasmExports["Md"].value;+ _kVersionStampBuildCoverageEnabledInt = Module["_kVersionStampBuildCoverageEnabledInt"] = wasmExports["Nd"].value;+ _kVersionStampBuildBaselineChangelistInt = Module["_kVersionStampBuildBaselineChangelistInt"] = wasmExports["Od"].value;+ _kVersionStampPrecookedTimestampStr = Module["_kVersionStampPrecookedTimestampStr"] = wasmExports["Pd"].value;+ _kVersionStampPrecookedClientInfoStr = Module["_kVersionStampPrecookedClientInfoStr"] = wasmExports["Qd"].value;+ __indirect_function_table = wasmTable = wasmExports["Rd"];+}++var wasmImports = {+ /** @export */ gd: BeginGlQueryTiming,+ /** @export */ fd: EndGlQueryTiming,+ /** @export */ ed: GetAdapterArchitecture,+ /** @export */ dd: GetAdapterDescription,+ /** @export */ cd: GetAdapterDeviceName,+ /** @export */ bd: GetAdapterVendor,+ /** @export */ ad: JsOnEmptyPacketListener,+ /** @export */ $c: JsOnFloat32ArrayImageListener,+ /** @export */ _c: JsOnFloat32ArrayImageVectorListener,+ /** @export */ ob: JsOnSimpleListenerBinaryArray,+ /** @export */ Zc: JsOnSimpleListenerBool,+ /** @export */ Yc: JsOnSimpleListenerDouble,+ /** @export */ Xc: JsOnSimpleListenerFloat,+ /** @export */ Wc: JsOnSimpleListenerInt,+ /** @export */ Vc: JsOnSimpleListenerString,+ /** @export */ Uc: JsOnSimpleListenerUint,+ /** @export */ Tc: JsOnUint8ArrayImageListener,+ /** @export */ Sc: JsOnUint8ArrayImageVectorListener,+ /** @export */ P: JsOnVectorFinishedListener,+ /** @export */ Rc: JsOnVectorListenerBool,+ /** @export */ Qc: JsOnVectorListenerDouble,+ /** @export */ Pc: JsOnVectorListenerFloat,+ /** @export */ Oc: JsOnVectorListenerInt,+ /** @export */ Nc: JsOnVectorListenerProto,+ /** @export */ Mc: JsOnVectorListenerString,+ /** @export */ Lc: JsOnVectorListenerUint,+ /** @export */ Kc: JsOnWebGLTextureListener,+ /** @export */ Jc: JsOnWebGLTextureVectorListener,+ /** @export */ Oa: JsWrapErrorListener,+ /** @export */ nb: JsWrapImageConverter,+ /** @export */ u: JsWrapSimpleListeners,+ /** @export */ mb: UseBottomLeftGpuOrigin,+ /** @export */ xb: __asyncjs__mediapipe_map_buffer_jspi,+ /** @export */ r: ___cxa_throw,+ /** @export */ Ic: ___syscall_dup,+ /** @export */ Hc: ___syscall_faccessat,+ /** @export */ lb: ___syscall_fcntl64,+ /** @export */ Gc: ___syscall_fstat64,+ /** @export */ Lb: ___syscall_ftruncate64,+ /** @export */ Fc: ___syscall_ioctl,+ /** @export */ Ec: ___syscall_lstat64,+ /** @export */ Dc: ___syscall_newfstatat,+ /** @export */ kb: ___syscall_openat,+ /** @export */ Cc: ___syscall_stat64,+ /** @export */ xc: __abort_js,+ /** @export */ Ib: __embind_register_bigint,+ /** @export */ wc: __embind_register_bool,+ /** @export */ vc: __embind_register_emval,+ /** @export */ ib: __embind_register_float,+ /** @export */ J: __embind_register_integer,+ /** @export */ q: __embind_register_memory_view,+ /** @export */ uc: __embind_register_std_string,+ /** @export */ La: __embind_register_std_wstring,+ /** @export */ tc: __embind_register_void,+ /** @export */ $: __emval_create_invoker,+ /** @export */ p: __emval_decref,+ /** @export */ Ka: __emval_get_global,+ /** @export */ hb: __emval_get_property,+ /** @export */ ja: __emval_incref,+ /** @export */ Ja: __emval_instanceof,+ /** @export */ _: __emval_invoke,+ /** @export */ ua: __emval_new_cstring,+ /** @export */ Z: __emval_run_destructors,+ /** @export */ gb: __emval_set_property,+ /** @export */ sc: __emval_typeof,+ /** @export */ Hb: __gmtime_js,+ /** @export */ Gb: __localtime_js,+ /** @export */ Fb: __mktime_js,+ /** @export */ Eb: __mmap_js,+ /** @export */ Db: __munmap_js,+ /** @export */ rc: __tzset_js,+ /** @export */ Kb: _clock_time_get,+ /** @export */ qc: custom_emscripten_dbgn,+ /** @export */ Y: _emscripten_asm_const_int,+ /** @export */ fb: _emscripten_asm_const_ptr,+ /** @export */ Ia: _emscripten_errn,+ /** @export */ pc: _emscripten_get_heap_max,+ /** @export */ y: _emscripten_get_now,+ /** @export */ ia: _emscripten_has_asyncify,+ /** @export */ oc: _emscripten_outn,+ /** @export */ nc: _emscripten_pc_get_function,+ /** @export */ mc: _emscripten_resize_heap,+ /** @export */ eb: _emscripten_stack_snapshot,+ /** @export */ lc: _emscripten_stack_unwind_buffer,+ /** @export */ kc: _emscripten_webgl_create_context,+ /** @export */ jc: _emscripten_webgl_destroy_context,+ /** @export */ ic: _emscripten_webgl_get_context_attributes,+ /** @export */ ha: _emscripten_webgl_get_current_context,+ /** @export */ hc: _emscripten_webgl_make_context_current,+ /** @export */ R: _emscripten_webgpu_get_device,+ /** @export */ gc: _emwgpuBufferDestroy,+ /** @export */ fc: _emwgpuBufferGetMappedRange,+ /** @export */ ec: _emwgpuBufferUnmap,+ /** @export */ x: _emwgpuDelete,+ /** @export */ dc: _emwgpuDeviceCreateBuffer,+ /** @export */ Cb: _emwgpuDeviceCreateComputePipelineAsync,+ /** @export */ Bb: _emwgpuDeviceCreateRenderPipelineAsync,+ /** @export */ cc: _emwgpuDeviceCreateShaderModule,+ /** @export */ bc: _emwgpuDeviceDestroy,+ /** @export */ ac: _emwgpuWaitAny,+ /** @export */ Bc: _environ_get,+ /** @export */ Ac: _environ_sizes_get,+ /** @export */ db: _exit,+ /** @export */ Na: _fd_close,+ /** @export */ jb: _fd_read,+ /** @export */ Jb: _fd_seek,+ /** @export */ Ma: _fd_write,+ /** @export */ b: _glActiveTexture,+ /** @export */ ta: _glAttachShader,+ /** @export */ $b: _glBindAttribLocation,+ /** @export */ c: _glBindBuffer,+ /** @export */ cb: _glBindBufferBase,+ /** @export */ t: _glBindFramebuffer,+ /** @export */ a: _glBindTexture,+ /** @export */ m: _glBindVertexArray,+ /** @export */ bb: _glBlendEquation,+ /** @export */ _b: _glBlendFunc,+ /** @export */ j: _glBufferData,+ /** @export */ I: _glClear,+ /** @export */ H: _glClearColor,+ /** @export */ da: _glClientWaitSync,+ /** @export */ ga: _glColorMask,+ /** @export */ ab: _glCompileShader,+ /** @export */ $a: _glCreateProgram,+ /** @export */ _a: _glCreateShader,+ /** @export */ o: _glDeleteBuffers,+ /** @export */ Q: _glDeleteFramebuffers,+ /** @export */ h: _glDeleteProgram,+ /** @export */ sa: _glDeleteShader,+ /** @export */ ra: _glDeleteSync,+ /** @export */ D: _glDeleteTextures,+ /** @export */ A: _glDeleteVertexArrays,+ /** @export */ Za: _glDetachShader,+ /** @export */ G: _glDisable,+ /** @export */ n: _glDisableVertexAttribArray,+ /** @export */ i: _glDrawArrays,+ /** @export */ fa: _glDrawBuffers,+ /** @export */ Zb: _glEnable,+ /** @export */ l: _glEnableVertexAttribArray,+ /** @export */ Ya: _glFenceSync,+ /** @export */ qa: _glFinish,+ /** @export */ v: _glFlush,+ /** @export */ C: _glFramebufferTexture2D,+ /** @export */ Xa: _glFramebufferTextureLayer,+ /** @export */ s: _glGenBuffers,+ /** @export */ X: _glGenFramebuffers,+ /** @export */ F: _glGenTextures,+ /** @export */ B: _glGenVertexArrays,+ /** @export */ Wa: _glGetAttribLocation,+ /** @export */ ea: _glGetError,+ /** @export */ Yb: _glGetFloatv,+ /** @export */ w: _glGetIntegerv,+ /** @export */ Xb: _glGetProgramiv,+ /** @export */ Wb: _glGetShaderInfoLog,+ /** @export */ Vb: _glGetShaderiv,+ /** @export */ O: _glGetString,+ /** @export */ Ub: _glGetUniformBlockIndex,+ /** @export */ d: _glGetUniformLocation,+ /** @export */ Tb: _glLineWidth,+ /** @export */ Va: _glLinkProgram,+ /** @export */ pa: _glPixelStorei,+ /** @export */ oa: _glReadPixels,+ /** @export */ Ua: _glShaderSource,+ /** @export */ E: _glTexImage2D,+ /** @export */ na: _glTexParameterf,+ /** @export */ Ta: _glTexParameterfv,+ /** @export */ f: _glTexParameteri,+ /** @export */ ma: _glTexStorage2D,+ /** @export */ Sb: _glTexStorage3D,+ /** @export */ W: _glTexSubImage2D,+ /** @export */ Rb: _glTexSubImage3D,+ /** @export */ N: _glUniform1f,+ /** @export */ la: _glUniform1fv,+ /** @export */ e: _glUniform1i,+ /** @export */ V: _glUniform2f,+ /** @export */ Qb: _glUniform2fv,+ /** @export */ Ha: _glUniform3f,+ /** @export */ Sa: _glUniform4f,+ /** @export */ U: _glUniform4fv,+ /** @export */ Pb: _glUniform4iv,+ /** @export */ Ob: _glUniformBlockBinding,+ /** @export */ Nb: _glUniformMatrix2fv,+ /** @export */ Mb: _glUniformMatrix3fv,+ /** @export */ Ga: _glUniformMatrix4fv,+ /** @export */ g: _glUseProgram,+ /** @export */ k: _glVertexAttribPointer,+ /** @export */ T: _glViewport,+ /** @export */ Ab: mediapipe_create_utility_canvas2d,+ /** @export */ zb: _mediapipe_find_canvas_event_target,+ /** @export */ yb: mediapipe_import_external_texture,+ /** @export */ wb: _mediapipe_webgl_tex_image_drawable,+ /** @export */ zc: _proc_exit,+ /** @export */ yc: _random_get,+ /** @export */ Fa: _wgpuCommandEncoderBeginComputePass,+ /** @export */ Ea: _wgpuCommandEncoderBeginRenderPass,+ /** @export */ vb: _wgpuCommandEncoderCopyBufferToTexture,+ /** @export */ ub: _wgpuCommandEncoderCopyTextureToBuffer,+ /** @export */ tb: _wgpuCommandEncoderCopyTextureToTexture,+ /** @export */ M: _wgpuCommandEncoderFinish,+ /** @export */ Da: _wgpuComputePassEncoderDispatchWorkgroups,+ /** @export */ Ca: _wgpuComputePassEncoderEnd,+ /** @export */ Ba: _wgpuComputePassEncoderSetBindGroup,+ /** @export */ Aa: _wgpuComputePassEncoderSetPipeline,+ /** @export */ za: _wgpuComputePipelineGetBindGroupLayout,+ /** @export */ ca: _wgpuDeviceCreateBindGroup,+ /** @export */ sb: _wgpuDeviceCreateBindGroupLayout,+ /** @export */ L: _wgpuDeviceCreateCommandEncoder,+ /** @export */ rb: _wgpuDeviceCreateComputePipeline,+ /** @export */ qb: _wgpuDeviceCreatePipelineLayout,+ /** @export */ Ra: _wgpuDeviceCreateRenderPipeline,+ /** @export */ S: _wgpuDeviceCreateSampler,+ /** @export */ ba: _wgpuDeviceCreateTexture,+ /** @export */ K: _wgpuQueueSubmit,+ /** @export */ ka: _wgpuQueueWriteBuffer,+ /** @export */ pb: _wgpuQueueWriteTexture,+ /** @export */ ya: _wgpuRenderPassEncoderDraw,+ /** @export */ xa: _wgpuRenderPassEncoderEnd,+ /** @export */ wa: _wgpuRenderPassEncoderSetBindGroup,+ /** @export */ va: _wgpuRenderPassEncoderSetPipeline,+ /** @export */ Qa: _wgpuRenderPipelineGetBindGroupLayout,+ /** @export */ z: _wgpuTextureCreateView,+ /** @export */ Pa: _wgpuTextureDestroy,+ /** @export */ aa: _wgpuTextureGetFormat+};++// include: postamble.js+// === Auto-generated postamble setup entry stuff ===+function run() {+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ preRun();+ // a preRun added a dependency, run will be called later+ if (runDependencies > 0) {+ dependenciesFulfilled = run;+ return;+ }+ function doRun() {+ // run may have just been called through dependencies being fulfilled just in this very frame,+ // or while the async setStatus time below was happening+ Module["calledRun"] = true;+ if (ABORT) return;+ initRuntime();+ readyPromiseResolve?.(Module);+ Module["onRuntimeInitialized"]?.();+ postRun();+ }+ if (Module["setStatus"]) {+ Module["setStatus"]("Running...");+ setTimeout(() => {+ setTimeout(() => Module["setStatus"](""), 1);+ doRun();+ }, 1);+ } else {+ doRun();+ }+}++var wasmExports;++// In modularize mode the generated code is within a factory function so we+// can use await here (since it's not top-level-await).+wasmExports = await (createWasm());++run();++// end include: postamble.js+// include: postamble_modularize.js+// In MODULARIZE mode we wrap the generated code in a factory function+// and return either the Module itself, or a promise of the module.+// We assign to the `moduleRtn` global here and configure closure to see+// this as an extern so it won't get minified.+if (runtimeInitialized) {+ moduleRtn = Module;+} else {+ // Set up the promise that indicates the Module is initialized+ moduleRtn = new Promise((resolve, reject) => {+ readyPromiseResolve = resolve;+ readyPromiseReject = reject;+ });+}+++ return moduleRtn;+ };+})();++// Export using a UMD style export, or ES6 exports if selected+if (typeof exports === 'object' && typeof module === 'object') {+ module.exports = ModuleFactory;+ // This default export looks redundant, but it allows TS to import this+ // commonjs style module.+ module.exports.default = ModuleFactory;+} else if (typeof define === 'function' && define['amd'])+ define([], () => ModuleFactory);+diff --git a/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.wasm b/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.wasmnew file mode 100644index 000000000..82cd2e165Binary files /dev/null and b/public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.wasm differdiff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjsindex a040018e8..0157cb821 100644--- a/scripts/build-vercel.mjs+++ b/scripts/build-vercel.mjs@@ -215,6 +215,14 @@ try {// and confirms the canonical accounts are the right kind on mainnet// (live check degrades to a warning when the RPC is unreachable).run('verify:solana', 'node scripts/verify-solana-parity.mjs'),+ // ERC-8004 EVM registry parity: the same registry addresses are hand-copied+ // across src/erc8004/abi.js, sdk/src/erc8004/abi.js, and+ // api/_lib/erc8004-chains.js. A drift sends registrations / reputation /+ // validation writes to the wrong (or zero) contract. Hard-fails on any+ // mismatch or the ValidationRegistry null-vs-address drift trap. The live+ // bytecode sweep defaults to Base mainnet + Base Sepolia (both deployed);+ // an unreachable RPC degrades to a warning so transport noise never blocks.+ run('verify:onchain', 'node scripts/verify-onchain-parity.mjs'),// MCP registry manifests: catches version drift, >100-char descriptions,// and mcpName mismatches at build time instead of on publish day.run('audit:mcp', 'node scripts/audit-mcp-manifests.mjs'),diff --git a/src/analytics.js b/src/analytics.jsindex fa7ba67e0..becb9b50a 100644--- a/src/analytics.js+++ b/src/analytics.js@@ -1,22 +1,115 @@-// Tiny PostHog identity helper.+// Analytics — PostHog identity + a typed, documented event taxonomy.//// The snippet injected by vite.config.js auto-captures pageviews, clicks and-// session replays anonymously. Without `posthog.identify()`, every visit is a-// fresh "person" keyed by session ID — funnels, cohorts and retention all-// break. Call identifyUser() once after auth resolves, resetIdentity() on-// sign-out.+// session replays anonymously. This module adds:+// 1. Identity — identifyUser() / resetIdentity() (call after auth resolves).+// 2. Event catalog — ANALYTICS_EVENTS: the single source of truth for every+// product-meaningful event name + its documented props.+// 3. track() — a validating facade. Unknown events are rejected (and+// surfaced in dev) so the taxonomy can't silently drift.+// 4. Funnels — trackFunnelStep() for ordered conversion journeys+// (landing → connect-wallet → action → success).+// 5. Errors — trackError() to capture handled boundary failures with+// context, so reliability shows up alongside behaviour.//-// All calls are no-ops when window.posthog isn't loaded (embed pages,-// blocked by adblock, ad-blocker test) so callers can fire-and-forget.+// Privacy: never pass raw wallet addresses or other PII as props — use+// shortWallet() to truncate. Every call is a no-op when window.posthog isn't+// loaded (embed pages, ad-blockers) so callers can fire-and-forget and analytics+// can never break the app.++// ─────────────────────────────────────────────────────────────────────────────+// Event taxonomy — the documented catalog. Keys are stable event names sent to+// PostHog; comments describe the props each event should carry. Group by journey.+// ─────────────────────────────────────────────────────────────────────────────++export const ANALYTICS_EVENTS = Object.freeze({+ // ── Acquisition ──────────────────────────────────────────────────────────+ /** Landing/home surfaced. props: { referrer?, utm_source?, path? } */+ LANDING_VIEWED: 'landing_viewed',+ /** A primary CTA was clicked. props: { cta: string, location: string } */+ CTA_CLICKED: 'cta_clicked',++ // ── Activation ───────────────────────────────────────────────────────────+ /** Wallet connect initiated. props: { provider?: string } */+ WALLET_CONNECT_STARTED: 'wallet_connect_started',+ /** Wallet connected. props: { provider?, wallet_short?, chain? } */+ WALLET_CONNECT_SUCCEEDED: 'wallet_connect_succeeded',+ /** Wallet connect failed. props: { provider?, reason? } */+ WALLET_CONNECT_FAILED: 'wallet_connect_failed',+ /** An agent was created. props: { agent_id?, source? } */+ AGENT_CREATED: 'agent_created',+ /** First embed/snippet generated for an agent. props: { agent_id?, embed_kind? } */+ EMBED_GENERATED: 'embed_generated',++ // ── $THREE holder funnel (ordered — see FUNNELS.three) ───────────────────+ /** $THREE token page viewed. props: { price_usd? } */+ TOKEN_PAGE_VIEWED: 'token_page_viewed',+ /** Buy/swap intent clicked. props: { source? } */+ TOKEN_BUY_CLICKED: 'token_buy_clicked',+ /** A swap quote was shown. props: { amount_usd?, out_amount? } */+ TOKEN_QUOTE_SHOWN: 'token_quote_shown',+ /** Swap submitted/confirmed by the user. props: { amount_usd? } */+ TOKEN_SWAP_CONFIRMED: 'token_swap_confirmed',+ /** Swap settled successfully. props: { amount_usd?, tx_short? } */+ TOKEN_SWAP_SUCCEEDED: 'token_swap_succeeded',++ // ── Engagement ───────────────────────────────────────────────────────────+ /** Marketplace search/filter used. props: { query_len?, filters? } */+ MARKETPLACE_SEARCHED: 'marketplace_searched',+ /** An agent profile was opened. props: { agent_id? } */+ AGENT_PROFILE_VIEWED: 'agent_profile_viewed',+ /** Visualizer/dashboard surface opened. props: { surface: string } */+ SURFACE_OPENED: 'surface_opened',++ // ── Share (this module's own instrumentation surface) ────────────────────+ /** Share card flow opened. props: { kind: string, entity_id? } */+ SHARE_CARD_OPENED: 'share_card_opened',+ /** A share action fired. props: { kind, channel: 'copy'|'download'|'native'|'x', entity_id? } */+ SHARE_CARD_ACTION: 'share_card_action',++ // ── Errors ───────────────────────────────────────────────────────────────+ /** A handled error at a boundary. props: { context, message, code?, status? } */+ ERROR_OCCURRED: 'error_occurred',+});++const _eventValues = new Set(Object.values(ANALYTICS_EVENTS));++/**+ * Ordered conversion funnels. Each is a list of event names from+ * ANALYTICS_EVENTS; trackFunnelStep() tags events with their funnel + step index+ * so PostHog funnel insights line up without per-call configuration.+ */+export const FUNNELS = Object.freeze({+ activation: [+ ANALYTICS_EVENTS.LANDING_VIEWED,+ ANALYTICS_EVENTS.WALLET_CONNECT_STARTED,+ ANALYTICS_EVENTS.WALLET_CONNECT_SUCCEEDED,+ ANALYTICS_EVENTS.AGENT_CREATED,+ ],+ three: [+ ANALYTICS_EVENTS.TOKEN_PAGE_VIEWED,+ ANALYTICS_EVENTS.TOKEN_BUY_CLICKED,+ ANALYTICS_EVENTS.TOKEN_QUOTE_SHOWN,+ ANALYTICS_EVENTS.TOKEN_SWAP_CONFIRMED,+ ANALYTICS_EVENTS.TOKEN_SWAP_SUCCEEDED,+ ],+});++// ─────────────────────────────────────────────────────────────────────────────+// PostHog plumbing+// ─────────────────────────────────────────────────────────────────────────────function ph() {if (typeof window === 'undefined') return null;if (window.__posthog_blocked) return null;const p = window.posthog;- if (!p || typeof p.identify !== 'function') return null;+ if (!p || typeof p.capture !== 'function') return null;return p;}+const _isDev =+ typeof import.meta !== 'undefined' && import.meta.env ? Boolean(import.meta.env.DEV) : false;+let _lastDistinctId = null;/**@@ -26,7 +119,7 @@ let _lastDistinctId = null;export function identifyUser(user) {if (!user?.id) return;const p = ph();- if (!p) return;+ if (!p || typeof p.identify !== 'function') return;// Avoid re-identifying on every getMe() call (most pages call it on load).if (_lastDistinctId === user.id) return;_lastDistinctId = user.id;@@ -46,7 +139,7 @@ export function identifyUser(user) {export function resetIdentity() {_lastDistinctId = null;const p = ph();- if (!p) return;+ if (!p || typeof p.reset !== 'function') return;try {p.reset();} catch {@@ -54,18 +147,118 @@ export function resetIdentity() {}}+// ─────────────────────────────────────────────────────────────────────────────+// track() — the validating facade every call site uses+// ─────────────────────────────────────────────────────────────────────────────+/**- * Capture a custom event. Use sparingly — most behavior is already auto-captured.- * Reserve for product-meaningful actions (e.g. "widget_published", "knowledge_uploaded").- * @param {string} event+ * Capture a product-meaningful event. Reserve for actions in the catalog above —+ * most behaviour is already auto-captured. Unknown event names are rejected so+ * the taxonomy can't silently drift; in dev the rejection is logged.+ *+ * @param {string} event — must be a value from ANALYTICS_EVENTS.* @param {Record<string, any>} [props]+ * @returns {boolean} whether the event was accepted + sent.*/export function track(event, props = {}) {+ if (!_eventValues.has(event)) {+ if (_isDev && typeof console !== 'undefined') {+ console.warn(+ `[analytics] rejected unknown event "${event}" — add it to ANALYTICS_EVENTS in src/analytics.js`,+ );+ }+ return false;+ }const p = ph();- if (!p) return;+ if (!p) return false;try {- p.capture(event, props);+ p.capture(event, sanitizeProps(props));+ return true;} catch {- /* swallow */+ /* swallow — analytics must never break the app */+ return false;+ }+}++/**+ * Track one step of a named conversion funnel. Stamps the event with+ * `funnel` + `funnel_step` (1-based) so funnel insights align in PostHog.+ *+ * @param {keyof typeof FUNNELS} funnel+ * @param {string} event — must belong to FUNNELS[funnel].+ * @param {Record<string, any>} [props]+ * @returns {boolean}+ */+export function trackFunnelStep(funnel, event, props = {}) {+ const steps = FUNNELS[funnel];+ if (!steps) {+ if (_isDev && typeof console !== 'undefined') {+ console.warn(`[analytics] unknown funnel "${funnel}"`);+ }+ return false;+ }+ const idx = steps.indexOf(event);+ if (idx < 0) {+ if (_isDev && typeof console !== 'undefined') {+ console.warn(`[analytics] event "${event}" is not a step of funnel "${funnel}"`);+ }+ return false;+ }+ return track(event, { ...props, funnel, funnel_step: idx + 1 });+}++/**+ * Capture a handled error at a boundary (network, user input, parse) with+ * enough context to triage without leaking internals. Errors are non-fatal to+ * the app — this is observability, not control flow.+ *+ * @param {string} context — where it happened, e.g. 'share_card.generate'.+ * @param {unknown} err — the caught error / value.+ * @param {Record<string, any>} [extra] — additional safe context.+ */+export function trackError(context, err, extra = {}) {+ const message =+ err instanceof Error ? err.message : typeof err === 'string' ? err : String(err ?? 'unknown');+ const code = err && typeof err === 'object' ? err.code : undefined;+ const status = err && typeof err === 'object' ? err.status : undefined;+ return track(ANALYTICS_EVENTS.ERROR_OCCURRED, {+ context,+ message: String(message).slice(0, 300),+ ...(code != null ? { code: String(code) } : {}),+ ...(status != null ? { status: Number(status) } : {}),+ ...extra,+ });+}++// ─────────────────────────────────────────────────────────────────────────────+// Helpers+// ─────────────────────────────────────────────────────────────────────────────++/**+ * Truncate a wallet address for analytics props so a raw public key never lands+ * in an event payload: "FeMb…Jpump".+ * @param {string} addr+ * @returns {string}+ */+export function shortWallet(addr) {+ const s = String(addr || '');+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++// Defensive: strip obvious full-length wallet/PII shapes from props so a careless+// call site can't leak a raw address. Values are kept otherwise as-is.+const _BASE58_WALLET = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const _EVM_ADDRESS = /^0x[a-fA-F0-9]{40}$/;+function sanitizeProps(props) {+ if (!props || typeof props !== 'object') return {};+ const out = {};+ for (const [k, v] of Object.entries(props)) {+ if (v == null) continue;+ if (typeof v === 'string' && (_BASE58_WALLET.test(v) || _EVM_ADDRESS.test(v))) {+ out[k] = shortWallet(v);+ } else {+ out[k] = v;+ }}+ return out;}diff --git a/src/diorama/compose.js b/src/diorama/compose.jsnew file mode 100644index 000000000..273e25f2e--- /dev/null+++ b/src/diorama/compose.js@@ -0,0 +1,226 @@+// Diorama — generation orchestration.+//+// One sentence becomes a tiny explorable 3D world in two acts:+//+// 1. COMPOSE — POST /api/diorama {action:'compose'} asks the platform's+// free-first LLM chain to decompose the sentence into a placed *plan*:+// a mood, palette, ground, island shape, and a handful of single-object+// forge prompts (each object status:'pending', no mesh yet).+//+// 2. FORGE — every object's prompt is turned into a real GLB on the EXISTING+// free text→3D lane (POST /api/forge {tier:'draft', path:'image'}). Forges+// run a few at a time so the world materializes progressively, and a failed+// object never sinks the whole world — partial worlds are real and shareable.+//+// This module owns only the orchestration + the per-browser client identity.+// The shape of a Diorama lives in ./schema.js; the controller (./main.js) drives+// the DOM from the callbacks below.++import { normalizeDiorama, MAX_PROMPT_LEN } from './schema.js';++// ── Per-browser identity ────────────────────────────────────────────────────+// A stable id so forge jobs are scoped per browser (sent as `x-forge-client`).+// Persisted in localStorage; falls back to a fresh UUID, and degrades to an+// in-memory id if storage is unavailable (private mode) so forging still works.+export const CLIENT_ID = resolveClientId();++function resolveClientId() {+ const KEY = 'dio_client';+ const fresh = () =>+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'+ ? crypto.randomUUID()+ : `dio-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ try {+ const existing = localStorage.getItem(KEY);+ if (existing) return existing;+ const id = fresh();+ localStorage.setItem(KEY, id);+ return id;+ } catch {+ return fresh();+ }+}++// ── Tuning ──────────────────────────────────────────────────────────────────+const FORGE_CONCURRENCY = 3; // objects forged at once on the free lane+const POLL_INTERVAL_MS = 2500; // how often a queued forge job is polled+const FORGE_DEADLINE_MS = 180_000; // 3 min per object before we mark it failed+const FORGE_ENDPOINT = '/api/forge';++const sleep = (ms, signal) =>+ new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(abortError());+ const t = setTimeout(() => {+ signal?.removeEventListener?.('abort', onAbort);+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(t);+ reject(abortError());+ };+ signal?.addEventListener?.('abort', onAbort, { once: true });+ });++function abortError() {+ const e = new Error('Cancelled.');+ e.name = 'AbortError';+ e.code = 'aborted';+ return e;+}++const forgeHeaders = () => ({ 'content-type': 'application/json', 'x-forge-client': CLIENT_ID });++/**+ * Compose a world from a sentence, then forge every object into a real mesh.+ *+ * @param {string} prompt the user's sentence+ * @param {Object} [opts]+ * @param {(diorama:import('./schema.js').Diorama)=>void} [opts.onPlan]+ * called once the plan returns, before any mesh exists, so the UI can+ * render the island + seeds + object chips immediately.+ * @param {(objectId:string, patch:{status:string, glbUrl?:string})=>void} [opts.onObject]+ * called as each object moves through forging → ready | failed.+ * @param {AbortSignal} [opts.signal] abort the compose + all forges.+ * @returns {Promise<import('./schema.js').Diorama>} the final, populated diorama.+ */+export async function composeWorld(prompt, { onPlan, onObject, signal } = {}) {+ const sentence = String(prompt ?? '')+ .slice(0, MAX_PROMPT_LEN)+ .trim();+ if (!sentence) {+ const e = new Error('Describe your world in a sentence.');+ e.code = 'prompt_required';+ throw e;+ }++ // ── 1. Compose the plan ──────────────────────────────────────────────────+ let payload;+ try {+ const res = await fetch('/api/diorama', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'compose', prompt: sentence }),+ signal,+ });+ payload = await res.json().catch(() => ({}));+ if (!res.ok) {+ const e = new Error(payload?.message || `The composer returned ${res.status}.`);+ e.code = payload?.error || 'compose_failed';+ throw e;+ }+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ if (err instanceof TypeError) {+ // Network boundary: fetch itself failed (offline, DNS, CORS).+ const e = new Error('Could not reach the world composer. Check your connection and try again.');+ e.code = 'network';+ throw e;+ }+ throw err;+ }++ // Normalize the untrusted plan into a guaranteed-renderable diorama.+ const { ok, diorama, errors } = normalizeDiorama(payload?.diorama);+ if (!ok || !diorama.objects.length) {+ const e = new Error('The composer could not place that world. Try a more concrete sentence.');+ e.code = 'compose_invalid';+ e.detail = errors;+ throw e;+ }+ // Plan objects start clean: pending, no mesh.+ for (const o of diorama.objects) {+ o.status = 'pending';+ o.glbUrl = null;+ }++ onPlan?.(diorama);++ // ── 2. Forge every object with bounded concurrency ───────────────────────+ const queue = diorama.objects.slice();+ const byId = new Map(diorama.objects.map((o) => [o.id, o]));++ async function worker() {+ for (;;) {+ if (signal?.aborted) throw abortError();+ const object = queue.shift();+ if (!object) return;+ const result = await forgeObject(object, { signal, onObject });+ const live = byId.get(object.id);+ if (live) {+ live.status = result.status;+ live.glbUrl = result.glbUrl ?? null;+ }+ }+ }++ const workers = Array.from({ length: Math.min(FORGE_CONCURRENCY, queue.length) }, worker);+ await Promise.all(workers);++ return diorama;+}++/**+ * Forge a single object's mesh on the free text→3D lane. Resolves with+ * `{ status:'ready', glbUrl }` on success or `{ status:'failed' }` on any+ * failure/timeout — it never throws for a forge failure (a partial world is+ * fine). It DOES propagate an AbortError so the controller can stop cleanly.+ *+ * Exported so the controller can retry one failed object in place.+ *+ * @param {import('./schema.js').DioramaObject} object+ * @param {Object} [opts]+ * @param {AbortSignal} [opts.signal]+ * @param {(objectId:string, patch:{status:string, glbUrl?:string})=>void} [opts.onObject]+ * @returns {Promise<{status:'ready'|'failed', glbUrl:string|null}>}+ */+export async function forgeObject(object, { signal, onObject } = {}) {+ onObject?.(object.id, { status: 'forging' });+ try {+ const glbUrl = await runForge(object.prompt, signal);+ if (glbUrl) {+ onObject?.(object.id, { status: 'ready', glbUrl });+ return { status: 'ready', glbUrl };+ }+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ // Any other failure is non-fatal: this object simply didn't materialize.+ }+ onObject?.(object.id, { status: 'failed' });+ return { status: 'failed', glbUrl: null };+}++// Kick a single free-lane forge and resolve to a durable GLB url (or throw).+async function runForge(prompt, signal) {+ const res = await fetch(FORGE_ENDPOINT, {+ method: 'POST',+ headers: forgeHeaders(),+ body: JSON.stringify({ prompt, tier: 'draft', path: 'image' }),+ signal,+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(data?.message || `The forge returned ${res.status}.`);+ }+ // The sync lane can return the finished mesh immediately (job_id null).+ if (data.status === 'done' && data.glb_url) return data.glb_url;+ if (data.status === 'failed') throw new Error(data.error || 'Forge failed.');+ if (!data.job_id) throw new Error('The forge did not start a job.');+ return pollForge(data.job_id, signal);+}++// Poll a queued forge job until it produces a mesh, fails, or hits the deadline.+async function pollForge(jobId, signal) {+ const deadline = Date.now() + FORGE_DEADLINE_MS;+ while (Date.now() < deadline) {+ await sleep(POLL_INTERVAL_MS, signal);+ const res = await fetch(`${FORGE_ENDPOINT}?job=${encodeURIComponent(jobId)}`, {+ headers: { 'x-forge-client': CLIENT_ID },+ signal,+ });+ const data = await res.json().catch(() => ({}));+ if (data.status === 'done' && data.glb_url) return data.glb_url;+ if (data.status === 'failed') throw new Error(data.error || 'Forge failed.');+ // queued | running → keep polling.+ }+ throw new Error('This piece took too long to forge.');+}diff --git a/src/diorama/diorama.css b/src/diorama/diorama.cssnew file mode 100644index 000000000..9bff38da2--- /dev/null+++ b/src/diorama/diorama.css@@ -0,0 +1,600 @@+/* Diorama — surface styles.+ Built on the global tokens in /style.css (--accent, --ink, --surface-*,+ --stroke*, --radius-*, --space-*, --shadow-*). Self-contained: every class+ here is namespaced under .dio so it can never bleed into other surfaces. */++.dio {+ --dio-glow: var(--accent, #7ec8ff);+ --dio-panel: var(--surface-glass, rgba(255, 255, 255, 0.04));+ --dio-stroke: var(--stroke, rgba(255, 255, 255, 0.1));+ --dio-stroke-strong: var(--stroke-strong, rgba(255, 255, 255, 0.18));+ --dio-ink: var(--ink, #eee);+ --dio-dim: var(--ink-dim, rgba(255, 255, 255, 0.62));+ max-width: 1240px;+ margin: 0 auto;+ padding: clamp(1rem, 3vw, 2.5rem) clamp(1rem, 4vw, 2rem) 5rem;+ display: flex;+ flex-direction: column;+ gap: clamp(1.5rem, 4vw, 3rem);+}++.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* ░░ Hero / composer ░░ */+.dio-hero {+ text-align: center;+ padding-top: clamp(0.5rem, 4vw, 2.5rem);+}+.dio-hero__copy {+ max-width: 720px;+ margin: 0 auto;+}+.dio-eyebrow {+ font-size: 0.75rem;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: var(--dio-dim);+ margin: 0 0 0.75rem;+}+.dio-h1 {+ font-family: var(--font-display, var(--font-body));+ font-size: clamp(2rem, 6vw, 3.4rem);+ line-height: 1.05;+ letter-spacing: -0.02em;+ margin: 0 0 0.9rem;+ background: linear-gradient(120deg, var(--dio-ink), var(--dio-glow));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+}+.dio-lede {+ font-size: clamp(1rem, 2.2vw, 1.18rem);+ line-height: 1.55;+ color: var(--dio-dim);+ margin: 0 auto 1.75rem;+ max-width: 60ch;+}++.dio-compose {+ display: flex;+ gap: 0.6rem;+ max-width: 620px;+ margin: 0 auto;+}+.dio-compose__field {+ flex: 1;+ display: block;+}+.dio-compose__input {+ width: 100%;+ box-sizing: border-box;+ padding: 0.95rem 1.1rem;+ font-size: 1.02rem;+ color: var(--dio-ink);+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke-strong);+ border-radius: var(--radius-control, 0.7rem);+ transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease;+}+.dio-compose__input::placeholder {+ color: var(--dio-dim);+}+.dio-compose__input:focus-visible {+ outline: none;+ border-color: var(--dio-glow);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--dio-glow) 28%, transparent);+}+.dio-compose__go {+ white-space: nowrap;+ padding-inline: 1.4rem;+}+.dio-compose__go[aria-busy='true'] {+ pointer-events: none;+ opacity: 0.75;+}+.dio-compose__help {+ font-size: 0.85rem;+ color: var(--dio-dim);+ margin: 0.7rem auto 0;+}++.dio-examples {+ list-style: none;+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 0.5rem;+ padding: 0;+ margin: 1.4rem auto 0;+ max-width: 700px;+}+.dio-chip {+ font-size: 0.85rem;+ color: var(--dio-dim);+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke);+ border-radius: var(--radius-pill, 999px);+ padding: 0.42rem 0.85rem;+ cursor: pointer;+ transition: color 0.16s ease, border-color 0.16s ease, transform 0.16s ease, background 0.16s ease;+}+.dio-chip:hover {+ color: var(--dio-ink);+ border-color: var(--dio-stroke-strong);+ transform: translateY(-1px);+}+.dio-chip:active {+ transform: translateY(0);+}+.dio-chip:focus-visible {+ outline: 2px solid var(--dio-glow);+ outline-offset: 2px;+}++/* ░░ Stage + side panel layout ░░ */+.dio-stage-wrap {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 320px;+ gap: 1rem;+ align-items: stretch;+}+@media (max-width: 880px) {+ .dio-stage-wrap {+ grid-template-columns: 1fr;+ }+}++.dio-stage {+ position: relative;+ aspect-ratio: 16 / 10;+ min-height: 360px;+ border-radius: var(--radius-card, 1rem);+ overflow: hidden;+ border: 1px solid var(--dio-stroke);+ background:+ radial-gradient(120% 90% at 50% 0%, color-mix(in srgb, var(--dio-glow) 12%, transparent), transparent 60%),+ linear-gradient(180deg, #0b1020, #05060c);+ box-shadow: var(--shadow-2);+ touch-action: none;+}+.dio-stage canvas {+ display: block;+ width: 100% !important;+ height: 100% !important;+}++/* Idle / loading overlay */+.dio-stage__loader {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 1.2rem;+ transition: opacity 0.5s ease;+}+.dio-stage__loader[hidden] {+ display: none;+}+.dio-stage__hint {+ color: var(--dio-dim);+ font-size: 0.95rem;+ margin: 0;+}+.dio-orb {+ position: relative;+ width: 88px;+ height: 88px;+ display: grid;+ place-items: center;+}+.dio-orb__core {+ width: 26px;+ height: 26px;+ border-radius: 50%;+ background: radial-gradient(circle at 35% 30%, #fff, var(--dio-glow));+ box-shadow: 0 0 28px color-mix(in srgb, var(--dio-glow) 70%, transparent);+ animation: dio-pulse 2.6s ease-in-out infinite;+}+.dio-orb__ring {+ position: absolute;+ inset: 0;+ border-radius: 50%;+ border: 1px solid color-mix(in srgb, var(--dio-glow) 45%, transparent);+ animation: dio-ripple 2.8s ease-out infinite;+}+.dio-orb__ring:nth-child(2) {+ animation-delay: 1.4s;+}+@keyframes dio-ripple {+ 0% {+ transform: scale(0.45);+ opacity: 0.9;+ }+ 100% {+ transform: scale(1.15);+ opacity: 0;+ }+}+@keyframes dio-pulse {+ 0%,+ 100% {+ transform: scale(1);+ opacity: 1;+ }+ 50% {+ transform: scale(1.12);+ opacity: 0.85;+ }+}++/* In-canvas HUD */+.dio-hud {+ position: absolute;+ left: 0;+ bottom: 0;+ right: 0;+ display: flex;+ flex-direction: column;+ gap: 0.15rem;+ padding: 1rem 1.1rem;+ background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.55));+ pointer-events: none;+}+.dio-hud[hidden] {+ display: none;+}+.dio-hud__title {+ font-family: var(--font-display, var(--font-body));+ font-size: 1.15rem;+ font-weight: 600;+ color: #fff;+ text-shadow: 0 1px 8px rgba(0, 0, 0, 0.6);+}+.dio-hud__meta {+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.78);+ text-transform: capitalize;+}++/* Side panel */+.dio-side {+ display: flex;+ flex-direction: column;+ gap: 0.85rem;+}+.dio-status {+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke);+ border-radius: var(--radius-md, 0.7rem);+ padding: 0.9rem 1rem;+}+.dio-status[hidden] {+ display: none;+}+.dio-status__row {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ margin-bottom: 0.6rem;+}+.dio-status__label {+ font-size: 0.9rem;+ color: var(--dio-ink);+}+.dio-status__count {+ font-size: 0.8rem;+ color: var(--dio-dim);+ font-variant-numeric: tabular-nums;+}+.dio-progress {+ height: 6px;+ border-radius: 999px;+ background: var(--dio-stroke);+ overflow: hidden;+}+.dio-progress__fill {+ height: 100%;+ width: 0%;+ border-radius: 999px;+ background: linear-gradient(90deg, var(--dio-glow), color-mix(in srgb, var(--dio-glow) 40%, #fff));+ transition: width 0.5s cubic-bezier(0.22, 1, 0.36, 1);+}++.dio-objects {+ list-style: none;+ padding: 0;+ margin: 0;+ display: flex;+ flex-direction: column;+ gap: 0.4rem;+}+.dio-objects:empty {+ display: none;+}+.dio-object {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ padding: 0.5rem 0.7rem;+ border-radius: var(--radius-md, 0.6rem);+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke);+ font-size: 0.88rem;+ color: var(--dio-ink);+ transition: border-color 0.2s ease, opacity 0.3s ease;+}+.dio-object__dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex: none;+ background: var(--dio-dim);+}+.dio-object[data-status='forging'] .dio-object__dot {+ background: var(--warn, #fbbf24);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--warn, #fbbf24) 70%, transparent);+ animation: dio-blink 1.2s ease-in-out infinite;+}+.dio-object[data-status='ready'] .dio-object__dot {+ background: var(--success, #4ade80);+}+.dio-object[data-status='failed'] .dio-object__dot {+ background: var(--danger, #f87171);+}+.dio-object[data-status='failed'] {+ border-color: color-mix(in srgb, var(--danger, #f87171) 40%, transparent);+}+.dio-object__label {+ flex: 1;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.dio-object__retry {+ font-size: 0.78rem;+ color: var(--dio-glow);+ background: none;+ border: none;+ cursor: pointer;+ padding: 0;+}+@keyframes dio-blink {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.35;+ }+}++.dio-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}+.dio-actions[hidden] {+ display: none;+}+.dio-act {+ flex: 1 1 auto;+}++/* Share panel */+.dio-share {+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke-strong);+ border-radius: var(--radius-md, 0.7rem);+ padding: 0.95rem 1rem;+ animation: dio-rise 0.4s cubic-bezier(0.22, 1, 0.36, 1);+}+.dio-share[hidden] {+ display: none;+}+.dio-share__title {+ margin: 0 0 0.7rem;+ font-weight: 600;+ color: var(--dio-ink);+}+.dio-share__link {+ display: flex;+ gap: 0.4rem;+ margin-bottom: 0.55rem;+}+.dio-share__input {+ flex: 1;+ min-width: 0;+ padding: 0.55rem 0.7rem;+ font-size: 0.82rem;+ color: var(--dio-dim);+ background: var(--bg-0, #0a0a0a);+ border: 1px solid var(--dio-stroke);+ border-radius: var(--radius-control, 0.5rem);+}+.dio-share__row {+ display: flex;+ gap: 0.4rem;+}+.dio-share__row .btn,+.dio-share__copy {+ flex: 1;+}+@keyframes dio-rise {+ from {+ opacity: 0;+ transform: translateY(8px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++/* ░░ Error state ░░ */+.dio-error {+ text-align: center;+ padding: 2.5rem 1rem;+ background: var(--dio-panel);+ border: 1px solid color-mix(in srgb, var(--danger, #f87171) 30%, var(--dio-stroke));+ border-radius: var(--radius-card, 1rem);+}+.dio-error[hidden] {+ display: none;+}+.dio-error__title {+ margin: 0 0 0.5rem;+ font-size: 1.3rem;+}+.dio-error__body {+ color: var(--dio-dim);+ margin: 0 0 1.2rem;+}++/* ░░ Gallery ░░ */+.dio-gallery__head {+ text-align: center;+ margin-bottom: 1.4rem;+}+.dio-h2 {+ font-family: var(--font-display, var(--font-body));+ font-size: clamp(1.5rem, 3.5vw, 2.1rem);+ margin: 0 0 0.4rem;+ letter-spacing: -0.01em;+}+.dio-gallery__sub {+ color: var(--dio-dim);+ margin: 0;+}+.dio-gallery__empty {+ text-align: center;+ color: var(--dio-dim);+ padding: 2.5rem 1rem;+ border: 1px dashed var(--dio-stroke);+ border-radius: var(--radius-card, 1rem);+}+.dio-gallery__empty[hidden] {+ display: none;+}+.dio-gallery__grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));+ gap: 1rem;+}+.dio-gallery__grid[aria-busy='true'] .dio-card {+ pointer-events: none;+}++/* Gallery cards (gallery.js builds these; styles live here) */+.dio-card {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 0.6rem;+ padding: 0;+ border-radius: var(--radius-card, 1rem);+ overflow: hidden;+ background: var(--dio-panel);+ border: 1px solid var(--dio-stroke);+ cursor: pointer;+ text-align: left;+ color: inherit;+ transition: border-color 0.18s ease, transform 0.18s ease, box-shadow 0.18s ease;+}+.dio-card:hover {+ border-color: var(--dio-stroke-strong);+ transform: translateY(-3px);+ box-shadow: var(--shadow-2);+}+.dio-card:focus-visible {+ outline: 2px solid var(--dio-glow);+ outline-offset: 2px;+}+.dio-card__thumb {+ aspect-ratio: 16 / 11;+ width: 100%;+ background: linear-gradient(160deg, #1a2238, #0a0e1a);+ position: relative;+}+.dio-card__thumb canvas,+.dio-card__thumb model-viewer,+.dio-card__thumb img {+ width: 100%;+ height: 100%;+ display: block;+ object-fit: cover;+}+.dio-card__body {+ padding: 0 0.85rem 0.95rem;+}+.dio-card__title {+ font-weight: 600;+ font-size: 0.98rem;+ margin: 0 0 0.2rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.dio-card__prompt {+ font-size: 0.82rem;+ color: var(--dio-dim);+ margin: 0;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.dio-card__foot {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 0.55rem;+ font-size: 0.74rem;+ color: var(--dio-dim);+}+.dio-card__mood {+ text-transform: capitalize;+}++/* Skeleton cards while the gallery loads */+.dio-card--skeleton {+ pointer-events: none;+}+.dio-card--skeleton .dio-card__thumb {+ background: linear-gradient(+ 100deg,+ var(--skeleton-base, rgba(255, 255, 255, 0.04)) 30%,+ var(--skeleton-sheen, rgba(255, 255, 255, 0.08)) 50%,+ var(--skeleton-base, rgba(255, 255, 255, 0.04)) 70%+ );+ background-size: 200% 100%;+ animation: dio-shimmer 1.4s linear infinite;+}+@keyframes dio-shimmer {+ to {+ background-position: -200% 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .dio-orb__core,+ .dio-orb__ring,+ .dio-object[data-status='forging'] .dio-object__dot,+ .dio-card--skeleton .dio-card__thumb {+ animation: none;+ }+ .dio-card:hover {+ transform: none;+ }+}diff --git a/src/diorama/main.js b/src/diorama/main.jsnew file mode 100644index 000000000..eaa8badfa--- /dev/null+++ b/src/diorama/main.js@@ -0,0 +1,749 @@+// Diorama — the create-flow controller.+//+// This is the page's only script entry: it imports the renderer, the composer,+// the gallery, and the share sheet, then wires the DOM contract documented in+// pages/diorama.html to all of them. It drives three journeys:+//+// • Compose — a sentence → a live plan → meshes forged progressively, each+// object materializing into the scene as it arrives.+// • Deep link — ?id=<uuid> loads a saved world read-only and offers a remix.+// • Save & share — persists a finished world, opens the share sheet, refreshes+// the gallery, and rewrites the URL to the new permalink.+//+// Every state in the DOM contract (idle / loading / forging / ready / empty /+// error) is designed and reachable; the controller never leaves the UI stuck.++import { createDioramaRenderer } from './renderer.js';+import { mountGallery } from './gallery.js';+import { openShare } from './share.js';+import { composeWorld, forgeObject, CLIENT_ID } from './compose.js';+import {+ forgeProgress,+ isComplete,+ MAX_PROMPT_LEN,+ MOODS,+} from './schema.js';++const MOOD_LABEL = { dawn: 'Dawn', day: 'Daytime', dusk: 'Dusk', night: 'Night' };++document.addEventListener('DOMContentLoaded', init);++function init() {+ const el = collectElements();+ if (!el.stage) return;++ const renderer = createDioramaRenderer(el.stage, {});++ /** Live controller state for the world currently on the stage. */+ const state = {+ diorama: null, // the active diorama (plan → populated)+ controller: null, // AbortController for the in-flight compose+ busy: false, // compose/forge in progress+ readOnly: false, // a deep-linked saved world (no live forging)+ };++ const gallery = mountGallery({+ listEl: el.galleryList,+ emptyEl: el.emptyState,+ onOpen: (id) => openSavedWorld(id, { scroll: true }),+ });+ gallery.reload();++ // ── DOM helpers ──────────────────────────────────────────────────────────++ const show = (node) => node && (node.hidden = false);+ const hide = (node) => node && (node.hidden = true);++ function fadeOutLoader() {+ const loader = el.stageLoader;+ if (!loader || loader.hidden) return;+ loader.classList.add('is-leaving');+ const done = () => {+ loader.hidden = true;+ loader.classList.remove('is-leaving');+ };+ // Honor the CSS transition if there is one; always settle regardless.+ loader.addEventListener('transitionend', done, { once: true });+ setTimeout(done, 600);+ }++ function setHud(diorama) {+ if (!el.hud) return;+ const mood = MOODS.includes(diorama.mood) ? diorama.mood : 'day';+ if (el.hudTitle) el.hudTitle.textContent = diorama.title || 'A little world';+ if (el.hudMeta) {+ const author = diorama.author?.handle+ ? `@${diorama.author.handle.replace(/^@/, '')}`+ : diorama.author?.wallet+ ? shortWallet(diorama.author.wallet)+ : '';+ el.hudMeta.textContent = [MOOD_LABEL[mood] || mood, author].filter(Boolean).join(' · ');+ }+ show(el.hud);+ }++ // Build the per-object status chips into #world-objects.+ function renderObjectChips(diorama) {+ if (!el.worldObjects) return;+ el.worldObjects.replaceChildren();+ for (const obj of diorama.objects) {+ el.worldObjects.append(buildChip(obj));+ }+ }++ function buildChip(obj) {+ const li = document.createElement('li');+ li.className = 'dio-object';+ li.dataset.id = obj.id;+ li.dataset.status = obj.status || 'pending';++ const dot = document.createElement('span');+ dot.className = 'dio-object__dot';+ dot.setAttribute('aria-hidden', 'true');++ const label = document.createElement('span');+ label.className = 'dio-object__label';+ label.textContent = obj.label || obj.prompt;++ li.append(dot, label);+ li.setAttribute('role', 'listitem');+ li.setAttribute('aria-label', `${obj.label || obj.prompt}: ${statusWord(obj.status)}`);+ return li;+ }++ function chipFor(id) {+ return el.worldObjects?.querySelector(`.dio-object[data-id="${cssEscape(id)}"]`) || null;+ }++ function setChipStatus(id, status) {+ const chip = chipFor(id);+ if (!chip) return;+ chip.dataset.status = status;+ const obj = state.diorama?.objects.find((o) => o.id === id);+ chip.setAttribute('aria-label', `${obj?.label || 'object'}: ${statusWord(status)}`);+ // Failed objects get an in-place retry affordance; clear it otherwise.+ const existing = chip.querySelector('.dio-object__retry');+ if (status === 'failed') {+ if (!existing) chip.append(buildRetry(id));+ } else if (existing) {+ existing.remove();+ }+ }++ function buildRetry(id) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'dio-object__retry';+ btn.textContent = 'Retry';+ btn.setAttribute('aria-label', 'Retry forging this object');+ btn.addEventListener('click', () => retryObject(id));+ return btn;+ }++ // Live progress bar + "n / total" count, driven by schema's forgeProgress.+ function updateProgress() {+ const d = state.diorama;+ if (!d) return;+ const total = d.objects.length;+ const ready = d.objects.filter((o) => o.status === 'ready').length;+ const settled = d.objects.filter((o) => o.status === 'ready' || o.status === 'failed').length;+ const pct = Math.round(forgeProgress(d) * 100);++ if (el.worldProgress) el.worldProgress.style.width = `${pct}%`;+ if (el.progressBar) el.progressBar.setAttribute('aria-valuenow', String(pct));+ if (el.worldCount) el.worldCount.textContent = `${ready} / ${total}`;++ if (el.statusLabel) {+ if (settled < total) {+ el.statusLabel.textContent = 'Forging your world…';+ } else if (ready === 0) {+ el.statusLabel.textContent = 'Hmm — nothing would forge. Try remixing.';+ } else if (ready < total) {+ el.statusLabel.textContent = `Your world is ready (${ready} of ${total} pieces).`;+ } else {+ el.statusLabel.textContent = 'Your world is ready ✨';+ }+ }+ }++ // ── Compose flow ──────────────────────────────────────────────────────────++ async function startCompose(rawPrompt) {+ const prompt = String(rawPrompt ?? '').slice(0, MAX_PROMPT_LEN).trim();+ if (!prompt) {+ el.input?.focus();+ return;+ }++ // Abort any compose already in flight (the user resubmitted).+ state.controller?.abort();+ const controller = new AbortController();+ state.controller = controller;+ state.busy = true;+ state.readOnly = false;+ state.lastPrompt = prompt;++ setComposeBusy(true);+ hide(el.errorState);+ hide(el.sharePanel);+ hide(el.worldActions);+ clearShareNote();+ show(el.worldStatus);+ if (el.statusLabel) el.statusLabel.textContent = 'Composing your world…';+ if (el.worldProgress) el.worldProgress.style.width = '0%';+ if (el.worldCount) el.worldCount.textContent = '';+ if (el.input) el.input.value = prompt;++ try {+ const diorama = await composeWorld(prompt, {+ signal: controller.signal,+ onPlan: (plan) => {+ if (controller.signal.aborted) return;+ state.diorama = plan;+ renderer.setDiorama(plan);+ fadeOutLoader();+ renderObjectChips(plan);+ setHud(plan);+ updateProgress();+ },+ onObject: (id, patch) => {+ if (controller.signal.aborted) return;+ handleObjectPatch(id, patch);+ },+ });+ if (controller.signal.aborted) return;+ state.diorama = diorama;+ finishWorld();+ } catch (err) {+ if (controller.signal.aborted || err?.name === 'AbortError') return;+ showError(err);+ } finally {+ if (state.controller === controller) {+ state.controller = null;+ state.busy = false;+ setComposeBusy(false);+ }+ }+ }++ // Apply a per-object patch from the composer: forging / ready / failed.+ async function handleObjectPatch(id, patch) {+ const obj = state.diorama?.objects.find((o) => o.id === id);+ if (!obj) return;++ if (patch.status === 'forging') {+ obj.status = 'forging';+ setChipStatus(id, 'forging');+ return;+ }+ if (patch.status === 'ready' && patch.glbUrl) {+ obj.glbUrl = patch.glbUrl;+ // Materialize the mesh into the scene, then flip the chip to ready.+ try {+ await renderer.materializeObject(id, patch.glbUrl);+ obj.status = 'ready';+ setChipStatus(id, 'ready');+ } catch {+ // The mesh forged but couldn't be placed — surface as failed so the+ // user can retry, and keep the renderer's own seed/failure state honest.+ obj.status = 'failed';+ renderer.markFailed(id);+ setChipStatus(id, 'failed');+ }+ updateProgress();+ return;+ }+ // failed (or ready without a url — treat as failed).+ obj.status = 'failed';+ obj.glbUrl = null;+ renderer.markFailed(id);+ setChipStatus(id, 'failed');+ updateProgress();+ }++ // Retry a single failed object in place on the live world.+ async function retryObject(id) {+ const obj = state.diorama?.objects.find((o) => o.id === id);+ if (!obj || state.readOnly) return;+ const chip = chipFor(id);+ const retryBtn = chip?.querySelector('.dio-object__retry');+ if (retryBtn) retryBtn.disabled = true;+ try {+ const result = await forgeObject(obj, {+ onObject: (objId, patch) => handleObjectPatch(objId, patch),+ });+ obj.status = result.status;+ obj.glbUrl = result.glbUrl;+ } catch {+ // AbortError only — the world was torn down; nothing to do.+ } finally {+ finishWorld();+ }+ }++ // Settle the world: final progress, reveal actions, start the auto-orbit.+ function finishWorld() {+ const d = state.diorama;+ if (!d) return;+ updateProgress();++ const anyReady = d.objects.some((o) => o.status === 'ready' && o.glbUrl);+ const allSettled = d.objects.every((o) => o.status === 'ready' || o.status === 'failed');++ if (anyReady) {+ show(el.worldActions);+ renderer.startAutoOrbit(true);+ wireWorldActions();+ }+ if (allSettled && isComplete(d) && el.statusLabel) {+ el.statusLabel.textContent = 'Your world is ready ✨';+ }+ }++ // ── World actions: remix / save / AR / download ────────────────────────────++ function wireWorldActions() {+ const ar = actBtn('ar');+ const dl = actBtn('download');+ const glbUrls = activeGlbUrls();++ // AR + download only make sense once there is at least one real mesh.+ if (glbUrls.length) {+ show(dl);+ if (arSupported()) show(ar);+ else hide(ar);+ } else {+ hide(dl);+ hide(ar);+ }+ }++ function activeGlbUrls() {+ try {+ const urls = renderer.getActiveGlbUrls?.();+ if (Array.isArray(urls) && urls.length) return urls;+ } catch {+ /* fall through to the diorama's own record */+ }+ return (state.diorama?.objects || [])+ .filter((o) => o.status === 'ready' && o.glbUrl)+ .map((o) => o.glbUrl);+ }++ function actBtn(name) {+ return el.worldActions?.querySelector(`[data-act="${name}"]`) || null;+ }++ function onActions(ev) {+ const btn = ev.target.closest('[data-act]');+ if (!btn || !el.worldActions?.contains(btn)) return;+ const act = btn.dataset.act;+ if (act === 'remix') remixWorld();+ else if (act === 'save') saveWorld(btn);+ else if (act === 'ar') openInRoom();+ else if (act === 'download') downloadWorld();+ }++ function remixWorld() {+ const prompt = state.diorama?.prompt || state.lastPrompt || el.input?.value;+ if (prompt) startCompose(prompt);+ }++ function downloadWorld() {+ const url = activeGlbUrls()[0];+ if (!url) return;+ const a = document.createElement('a');+ a.href = url;+ a.download = `${slug(state.diorama?.title || 'diorama')}.glb`;+ a.rel = 'noopener';+ document.body.append(a);+ a.click();+ a.remove();+ }++ // "View in your room": hand the first active mesh to a hidden <model-viewer>+ // with AR enabled (model-viewer is already loaded on the page), then trigger+ // its native AR session — mirrors the /forge AR handoff.+ function openInRoom() {+ const url = activeGlbUrls()[0];+ if (!url || !arSupported()) return;+ const mv = ensureArViewer();+ const launch = () => {+ try {+ mv.activateAR?.();+ } catch {+ /* the device declined the AR session; nothing to recover */+ }+ };+ if (mv.getAttribute('src') === url && mv.loaded) {+ launch();+ return;+ }+ mv.setAttribute('src', url);+ mv.setAttribute('alt', `3D model: ${state.diorama?.title || 'your world'}`);+ mv.addEventListener('load', launch, { once: true });+ }++ // ── Save & share ───────────────────────────────────────────────────────────++ async function saveWorld(btn) {+ const d = state.diorama;+ if (!d) return;+ btn.setAttribute('aria-busy', 'true');+ btn.disabled = true;+ clearShareNote();+ try {+ const res = await fetch('/api/diorama', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'save', diorama: d, clientKey: CLIENT_ID }),+ });+ const data = await res.json().catch(() => ({}));++ if (res.status === 503 && data.error === 'sharing_unavailable') {+ showShareNote(+ data.message || 'Sharing is not enabled on this deployment, but your world is fully yours to explore and download.',+ );+ return;+ }+ if (!res.ok || !data.id || !data.url) {+ showShareNote(data.message || 'Could not save this world. Try again in a moment.', true);+ return;+ }++ d.id = data.id;+ d.createdAt = data.createdAt || d.createdAt;+ openShare({ diorama: d, url: data.url });+ show(el.sharePanel);+ try {+ history.replaceState(null, '', `?id=${encodeURIComponent(data.id)}`);+ } catch {+ /* replaceState can throw in sandboxed frames — non-fatal */+ }+ gallery.reload();+ } catch (err) {+ const offline = err instanceof TypeError;+ showShareNote(+ offline+ ? 'Could not reach the server to save. Check your connection and try again.'+ : 'Could not save this world. Try again in a moment.',+ true,+ );+ } finally {+ btn.removeAttribute('aria-busy');+ btn.disabled = false;+ }+ }++ // An inline note in the share region for the "sharing off" / save-error states+ // — keeps the world fully usable while explaining what happened.+ function showShareNote(message, isError = false) {+ clearShareNote();+ const note = document.createElement('p');+ note.className = 'dio-share__note';+ if (isError) note.dataset.error = 'true';+ note.setAttribute('role', 'status');+ note.textContent = message;+ note.dataset.dioNote = 'true';+ (el.sharePanel?.parentElement || el.worldActions?.parentElement || el.stage).append(note);+ show(el.sharePanel?.parentElement ? el.sharePanel : note);+ }++ function clearShareNote() {+ for (const n of document.querySelectorAll('[data-dio-note="true"]')) n.remove();+ }++ // ── Deep link: load a saved world read-only ───────────────────────────────++ async function openSavedWorld(id, { scroll = false } = {}) {+ if (!id) return;+ state.controller?.abort();+ state.busy = true;+ state.readOnly = true;+ hide(el.errorState);+ hide(el.worldActions);+ hide(el.sharePanel);+ clearShareNote();+ show(el.worldStatus);+ if (el.statusLabel) el.statusLabel.textContent = 'Loading this world…';+ if (scroll) el.stage.scrollIntoView({ behavior: 'smooth', block: 'center' });++ try {+ const res = await fetch(`/api/diorama?id=${encodeURIComponent(id)}`);+ const data = await res.json().catch(() => ({}));+ if (res.status === 404) {+ showError(+ Object.assign(new Error('That world has wandered off. It may have been removed.'), {+ code: 'not_found',+ deadLink: true,+ }),+ );+ return;+ }+ if (!res.ok || !data.diorama) {+ showError(new Error(data.message || 'Could not load that world. Try again.'));+ return;+ }++ const diorama = data.diorama;+ state.diorama = diorama;+ renderer.setDiorama(diorama);+ fadeOutLoader();+ renderObjectChips(diorama);+ setHud(diorama);++ // Materialize every already-forged object; mark the rest failed.+ for (const obj of diorama.objects) {+ if (obj.status === 'ready' && obj.glbUrl) {+ setChipStatus(obj.id, 'forging');+ try {+ await renderer.materializeObject(obj.id, obj.glbUrl);+ setChipStatus(obj.id, 'ready');+ } catch {+ obj.status = 'failed';+ renderer.markFailed(obj.id);+ setChipStatus(obj.id, 'failed');+ }+ } else {+ setChipStatus(obj.id, 'failed');+ }+ }+ updateProgress();+ if (el.statusLabel) el.statusLabel.textContent = `“${diorama.title}” — spoken into being`;++ renderer.startAutoOrbit(true);+ showRemixAffordance(diorama);+ gallery.reload();+ } catch (err) {+ showError(+ err instanceof TypeError+ ? new Error('Could not reach the server. Check your connection and try again.')+ : err,+ );+ } finally {+ state.busy = false;+ state.readOnly = true;+ }+ }++ // A saved world is read-only; surface a "Remix this world" action that prefills+ // the composer with its prompt and lets the visitor spin their own version.+ function showRemixAffordance(diorama) {+ show(el.worldActions);+ // In read-only mode, only remix / AR / download apply; hide save.+ hide(actBtn('save'));+ const glbUrls = activeGlbUrls();+ const dl = actBtn('download');+ const ar = actBtn('ar');+ if (glbUrls.length) {+ show(dl);+ if (arSupported()) show(ar);+ else hide(ar);+ } else {+ hide(dl);+ hide(ar);+ }+ const remix = actBtn('remix');+ if (remix) {+ remix.textContent = '↻ Remix this world';+ if (el.input) el.input.value = diorama.prompt || '';+ state.lastPrompt = diorama.prompt || '';+ }+ }++ // ── Error state ────────────────────────────────────────────────────────────++ function showError(err) {+ hide(el.worldStatus);+ hide(el.worldActions);+ if (el.errorBody) {+ el.errorBody.textContent =+ err?.message || 'Something went wrong building that world. Try again.';+ }+ // Dead deep links get a "back to Diorama" path; everything else retries.+ if (el.retryBtn) {+ if (err?.deadLink) {+ el.retryBtn.textContent = 'Start a new world';+ } else {+ el.retryBtn.textContent = 'Try again';+ }+ }+ show(el.errorState);+ el.errorState.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }++ function onRetry() {+ hide(el.errorState);+ // A dead deep link clears the URL and returns to a clean composer.+ if (el.retryBtn?.textContent?.startsWith('Start')) {+ try {+ history.replaceState(null, '', location.pathname);+ } catch {+ /* non-fatal */+ }+ el.input?.focus();+ return;+ }+ const prompt = state.lastPrompt || el.input?.value;+ if (prompt) startCompose(prompt);+ else el.input?.focus();+ }++ // ── AR support / hidden viewer ─────────────────────────────────────────────++ function arSupported() {+ // model-viewer reports per-device AR capability via canActivateAR once the+ // custom element is defined; before then, allow it on mobile so the button+ // is offered where AR is most likely. Desktops simply won't activate.+ const mv = arViewer;+ if (mv && typeof mv.canActivateAR === 'boolean') return mv.canActivateAR;+ return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);+ }++ let arViewer = null;+ function ensureArViewer() {+ if (arViewer) return arViewer;+ const mv = document.createElement('model-viewer');+ mv.setAttribute('ar', '');+ mv.setAttribute('ar-modes', 'webxr scene-viewer quick-look');+ mv.setAttribute('camera-controls', '');+ mv.setAttribute('reveal', 'manual');+ mv.style.position = 'fixed';+ mv.style.width = '1px';+ mv.style.height = '1px';+ mv.style.left = '-9999px';+ mv.style.opacity = '0';+ mv.style.pointerEvents = 'none';+ document.body.append(mv);+ arViewer = mv;+ return mv;+ }++ // ── Compose form / examples wiring ─────────────────────────────────────────++ function setComposeBusy(busy) {+ if (!el.submit) return;+ el.submit.setAttribute('aria-busy', busy ? 'true' : 'false');+ el.submit.disabled = busy;+ if (el.input) el.input.toggleAttribute('aria-busy', busy);+ }++ el.form?.addEventListener('submit', (ev) => {+ ev.preventDefault();+ startCompose(el.input?.value);+ });++ el.examples?.addEventListener('click', (ev) => {+ const btn = ev.target.closest('button[data-prompt]');+ if (!btn) return;+ const prompt = btn.dataset.prompt || '';+ if (el.input) el.input.value = prompt;+ startCompose(prompt);+ });++ el.worldActions?.addEventListener('click', onActions);+ el.retryBtn?.addEventListener('click', onRetry);++ // ── Resize + lifecycle ─────────────────────────────────────────────────────++ const onResize = debounce(() => renderer.resize(), 150);+ window.addEventListener('resize', onResize);++ window.addEventListener(+ 'pagehide',+ () => {+ state.controller?.abort();+ window.removeEventListener('resize', onResize);+ renderer.dispose();+ },+ { once: true },+ );++ // ── Boot: deep link or idle composer ───────────────────────────────────────++ const deepId = new URLSearchParams(location.search).get('id');+ if (deepId) {+ openSavedWorld(deepId, { scroll: false });+ } else {+ // Idle: the stage loader stands, the composer waits, the gallery loads.+ el.input?.focus({ preventScroll: true });+ }+}++// ── Element lookup ────────────────────────────────────────────────────────────++function collectElements() {+ const $ = (id) => document.getElementById(id);+ const stage = $('diorama-stage');+ const hud = $('stage-hud');+ const worldStatus = $('world-status');+ const worldActions = $('world-actions');+ const errorState = $('error-state');+ return {+ stage,+ stageLoader: $('stage-loader'),+ hud,+ hudTitle: hud?.querySelector('.dio-hud__title') || null,+ hudMeta: hud?.querySelector('.dio-hud__meta') || null,+ form: $('compose-form'),+ input: $('compose-input'),+ submit: $('compose-submit'),+ examples: $('compose-examples'),+ worldStatus,+ statusLabel: worldStatus?.querySelector('.dio-status__label') || null,+ worldProgress: $('world-progress'),+ progressBar: worldStatus?.querySelector('.dio-progress') || null,+ worldCount: worldStatus?.querySelector('[data-count]') || null,+ worldObjects: $('world-objects'),+ worldActions,+ sharePanel: $('share-panel'),+ errorState,+ errorBody: errorState?.querySelector('.dio-error__body') || null,+ retryBtn: errorState?.querySelector('[data-act="retry"]') || null,+ galleryList: $('gallery-list'),+ emptyState: $('empty-state'),+ };+}++// ── Small utilities ────────────────────────────────────────────────────────────++function statusWord(status) {+ switch (status) {+ case 'ready':+ return 'forged';+ case 'forging':+ return 'forging';+ case 'failed':+ return 'failed to forge';+ default:+ return 'waiting';+ }+}++function shortWallet(w) {+ const s = String(w);+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;+}++function slug(s) {+ return (+ String(s)+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 48) || 'diorama'+ );+}++function cssEscape(value) {+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value);+ return String(value).replace(/["\\]/g, '\\$&');+}++function debounce(fn, ms) {+ let t;+ return (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), ms);+ };+}diff --git a/src/diorama/renderer.js b/src/diorama/renderer.jsnew file mode 100644index 000000000..9cdcba00f--- /dev/null+++ b/src/diorama/renderer.js@@ -0,0 +1,1526 @@+// Diorama — the Three.js renderer.+//+// One sentence becomes a tiny explorable 3D world on a floating island. This+// module owns the WebGL stage: it builds the island, sky, atmosphere, and+// lighting for a Diorama, shows each not-yet-forged object as a luminous "seed",+// and materializes forged GLB meshes onto the island with a flare-and-rise+// animation. It is the visual heart of the feature.+//+// It imports the shared data contract from ./schema.js and never redefines it.+// Boundaries (GLB load, container size) are defended; the inner render loop+// trusts itself.++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++import { MOOD_LIGHT, ISLAND_RADIUS, defaultPalette } from './schema.js';++// Decoder binaries are copied into /public/three/draco/ by the repo's+// postinstall (scripts/copy-three-decoders.mjs) — the same path every other+// loader in this codebase uses. Forged GLBs that use Draco load through this.+const DRACO_PATH = '/three/draco/';++// Geometry budget. The island is a small disc; objects normalize to ~1.4m so a+// handful read as a cohesive miniature.+const TARGET_FOOTPRINT = 1.4; // metres, before object.scale multiplier+const SURFACE_Y = 0; // the island top sits at y=0+const MATERIALIZE_MS = 700;++const prefersReducedMotion = () => {+ try {+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ } catch {+ return false;+ }+};++const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);+const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);+const clamp01 = (t) => Math.min(1, Math.max(0, t));++/** Cheap deterministic value noise (no deps) for island undulation + rim. */+function makeNoise2D(seed = 1) {+ const hash = (x, y) => {+ let h = x * 374761393 + y * 668265263 + seed * 2246822519;+ h = (h ^ (h >> 13)) * 1274126177;+ return ((h ^ (h >> 16)) >>> 0) / 4294967295;+ };+ const smooth = (t) => t * t * (3 - 2 * t);+ return (x, y) => {+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ const a = hash(xi, yi);+ const b = hash(xi + 1, yi);+ const c = hash(xi, yi + 1);+ const d = hash(xi + 1, yi + 1);+ const u = smooth(xf);+ const v = smooth(yf);+ return (a * (1 - u) + b * u) * (1 - v) + (c * (1 - u) + d * u) * v;+ };+}++/** Build a vertical gradient texture for the sky dome (top -> horizon). */+function makeSkyTexture(topHex, horizonHex) {+ const c = document.createElement('canvas');+ c.width = 4;+ c.height = 256;+ const ctx = c.getContext('2d');+ const g = ctx.createLinearGradient(0, 0, 0, 256);+ g.addColorStop(0, topHex);+ g.addColorStop(0.55, horizonHex);+ g.addColorStop(1, horizonHex);+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 4, 256);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.needsUpdate = true;+ return tex;+}++/** Soft radial alpha texture for the contact shadow + sparkle sprites. */+function makeRadialTexture(inner = 'rgba(0,0,0,0.55)', size = 128) {+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const ctx = c.getContext('2d');+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);+ g.addColorStop(0, inner);+ g.addColorStop(0.6, 'rgba(0,0,0,0.18)');+ g.addColorStop(1, 'rgba(0,0,0,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, size, size);+ const tex = new THREE.CanvasTexture(c);+ tex.needsUpdate = true;+ return tex;+}++/** Soft white glow texture (for seeds / sparkles), colored via material. */+function makeGlowTexture(size = 128) {+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const ctx = c.getContext('2d');+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);+ g.addColorStop(0, 'rgba(255,255,255,1)');+ g.addColorStop(0.25, 'rgba(255,255,255,0.85)');+ g.addColorStop(0.6, 'rgba(255,255,255,0.25)');+ g.addColorStop(1, 'rgba(255,255,255,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, size, size);+ const tex = new THREE.CanvasTexture(c);+ tex.needsUpdate = true;+ return tex;+}++/** Recursively dispose a subtree's geometries, materials, and their textures. */+function disposeObject(obj) {+ obj.traverse((node) => {+ if (node.geometry) node.geometry.dispose();+ const mat = node.material;+ if (!mat) return;+ const mats = Array.isArray(mat) ? mat : [mat];+ for (const m of mats) {+ for (const key of Object.keys(m)) {+ const val = m[key];+ if (val && val.isTexture) val.dispose();+ }+ m.dispose();+ }+ });+}++/**+ * Build the floating-island geometry. The top is a gently undulating disc; the+ * underside tapers to a point for the classic floating-rock silhouette. The rim+ * is varied by `shape`: round (smooth), craggy (noisy rim + spikier base),+ * plateau (flatter top, steeper sides).+ *+ * @returns {THREE.BufferGeometry}+ */+function buildIslandGeometry(shape, noise) {+ const radius = ISLAND_RADIUS;+ const radialSegments = 96;+ const rings = 14; // top surface rings+ const positions = [];+ const indices = [];++ const rimNoise = shape === 'craggy' ? 0.9 : shape === 'plateau' ? 0.18 : 0.32;+ const topUndulation = shape === 'plateau' ? 0.12 : 0.34;+ // Depth profile of the underside cone.+ const depth = shape === 'plateau' ? 5.4 : shape === 'craggy' ? 6.6 : 5.8;++ // --- Top surface (concentric rings, center vertex first) ---+ positions.push(0, topUndulation * 0.4, 0); // center+ for (let r = 1; r <= rings; r++) {+ const rr = r / rings;+ for (let s = 0; s < radialSegments; s++) {+ const ang = (s / radialSegments) * Math.PI * 2;+ // Rim wobble grows toward the edge.+ const edge = Math.pow(rr, 1.6);+ const wob = (noise(Math.cos(ang) * 2.2 + 7, Math.sin(ang) * 2.2 + 7) - 0.5) * rimNoise * edge;+ const radHere = rr * radius * (1 + wob * 0.16);+ const x = Math.cos(ang) * radHere;+ const z = Math.sin(ang) * radHere;+ // Surface height: gentle dome + local undulation, sinking at the rim.+ const dome = (1 - rr * rr) * topUndulation;+ const local = (noise(x * 0.5 + 3, z * 0.5 + 3) - 0.5) * topUndulation * 0.9 * (1 - edge * 0.5);+ const rimDrop = -Math.pow(rr, 3) * 0.5;+ const y = dome + local + rimDrop;+ positions.push(x, y, z);+ }+ }++ const topVertCount = positions.length / 3;+ const ringStart = (r) => 1 + (r - 1) * radialSegments; // index of first vert of ring r (1-based)++ // center fan to ring 1+ for (let s = 0; s < radialSegments; s++) {+ const a = 1 + s;+ const b = 1 + ((s + 1) % radialSegments);+ indices.push(0, b, a);+ }+ // ring-to-ring quads+ for (let r = 1; r < rings; r++) {+ const cur = ringStart(r);+ const nxt = ringStart(r + 1);+ for (let s = 0; s < radialSegments; s++) {+ const sn = (s + 1) % radialSegments;+ const a = cur + s;+ const b = cur + sn;+ const c = nxt + s;+ const d = nxt + sn;+ indices.push(a, b, c);+ indices.push(b, d, c);+ }+ }++ // --- Underside: from outer rim down to a single apex point ---+ const rimRing = ringStart(rings);+ const apexIndex = positions.length / 3;+ positions.push(0, -depth, 0);+ // underside is faceted directly from the rim ring to the apex+ for (let s = 0; s < radialSegments; s++) {+ const sn = (s + 1) % radialSegments;+ const a = rimRing + s;+ const b = rimRing + sn;+ indices.push(a, apexIndex, b);+ }+ // A couple of intermediate underside rings give the cone a bulging rocky form.+ const underRings = 4;+ const underStart = positions.length / 3;+ for (let u = 1; u <= underRings; u++) {+ const t = u / (underRings + 1);+ for (let s = 0; s < radialSegments; s++) {+ const ang = (s / radialSegments) * Math.PI * 2;+ const bulge = 1 - t;+ const rockNoise = shape === 'craggy' ? 0.5 : 0.28;+ const wob = (noise(Math.cos(ang) * 3 + 21 + u, Math.sin(ang) * 3 + 21) - 0.5) * rockNoise;+ const radHere = radius * bulge * (0.7 + wob * 0.3) * (0.5 + bulge * 0.5);+ const x = Math.cos(ang) * radHere;+ const z = Math.sin(ang) * radHere;+ const y = -depth * t;+ positions.push(x, y, z);+ }+ }+ // stitch rim -> first under ring -> ... -> apex, replacing the direct fan above+ // (we keep both; overlapping faces are fine visually for a stylized rock, but+ // to avoid z-fighting we instead stitch progressively). Rebuild underside cleanly:+ // Note: the direct rim->apex fan was a fallback; remove its faces by not relying+ // on it — stitch rings explicitly here:+ if (underRings > 0) {+ // rim -> under ring 1+ const u1 = underStart;+ for (let s = 0; s < radialSegments; s++) {+ const sn = (s + 1) % radialSegments;+ indices.push(rimRing + s, u1 + s, rimRing + sn);+ indices.push(rimRing + sn, u1 + s, u1 + sn);+ }+ for (let u = 1; u < underRings; u++) {+ const cur = underStart + (u - 1) * radialSegments;+ const nxt = underStart + u * radialSegments;+ for (let s = 0; s < radialSegments; s++) {+ const sn = (s + 1) % radialSegments;+ indices.push(cur + s, nxt + s, cur + sn);+ indices.push(cur + sn, nxt + s, nxt + sn);+ }+ }+ // last under ring -> apex+ const last = underStart + (underRings - 1) * radialSegments;+ for (let s = 0; s < radialSegments; s++) {+ const sn = (s + 1) % radialSegments;+ indices.push(last + s, apexIndex, last + sn);+ }+ }++ const geo = new THREE.BufferGeometry();+ geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));+ geo.setIndex(indices);+ geo.computeVertexNormals();+ geo.computeBoundingBox();+ geo.userData.topVertCount = topVertCount;+ geo.userData.rimRingStart = rimRing;+ return geo;+}++/** Sample the top-surface height at (x,z) so objects/seeds sit on the ground. */+function surfaceHeightAt(noise, shape, x, z) {+ const topUndulation = shape === 'plateau' ? 0.12 : 0.34;+ const r = Math.hypot(x, z);+ const rr = clamp01(r / ISLAND_RADIUS);+ const dome = (1 - rr * rr) * topUndulation;+ const local = (noise(x * 0.5 + 3, z * 0.5 + 3) - 0.5) * topUndulation * 0.9 * (1 - Math.pow(rr, 1.6) * 0.5);+ const rimDrop = -Math.pow(rr, 3) * 0.5;+ return dome + local + rimDrop;+}++/**+ * Ground material per terrain type, tinted by the palette ground colour.+ * Returns { material, accents } where accents is an optional Object3D to add.+ */+function buildGroundMaterial(ground, palette, noise, shape, getEnv) {+ const tint = new THREE.Color(palette.ground);+ const base = {+ grass: { rough: 0.95, metal: 0, sat: 1 },+ meadow: { rough: 0.92, metal: 0, sat: 1.05 },+ sand: { rough: 1, metal: 0, sat: 0.9 },+ snow: { rough: 0.7, metal: 0, sat: 0.7, emissive: 0.12 },+ stone: { rough: 1, metal: 0.02, sat: 0.8 },+ water: { rough: 0.2, metal: 0.1, sat: 1 },+ void: { rough: 1, metal: 0, sat: 0.6 },+ }[ground] || { rough: 0.95, metal: 0, sat: 1 };++ const col = tint.clone();+ // desaturate/adjust subtly per terrain+ const hsl = {};+ col.getHSL(hsl);+ col.setHSL(hsl.h, clamp01(hsl.s * base.sat), hsl.l);++ const mat = new THREE.MeshStandardMaterial({+ color: col,+ roughness: base.rough,+ metalness: base.metal,+ envMapIntensity: 0.6,+ flatShading: shape === 'craggy',+ });+ if (base.emissive) {+ mat.emissive = col.clone().multiplyScalar(0.4);+ mat.emissiveIntensity = base.emissive;+ }++ const accents = new THREE.Group();+ accents.name = 'ground-accents';++ if (ground === 'grass' || ground === 'meadow') {+ // Tiny scattered detail blades/tufts as instanced cones.+ const count = 280;+ const tuftGeo = new THREE.ConeGeometry(0.05, 0.22, 4);+ const tuftMat = mat.clone();+ const detail = col.clone();+ detail.offsetHSL(0.02, 0.05, ground === 'meadow' ? 0.04 : -0.02);+ tuftMat.color = detail;+ const inst = new THREE.InstancedMesh(tuftGeo, tuftMat, count);+ inst.castShadow = false;+ inst.receiveShadow = true;+ const m = new THREE.Matrix4();+ const q = new THREE.Quaternion();+ const sca = new THREE.Vector3();+ let placed = 0;+ for (let i = 0; i < count; i++) {+ const ang = noise(i * 1.7, 3) * Math.PI * 2;+ const rad = Math.sqrt(noise(i, 9)) * (ISLAND_RADIUS - 0.5);+ const x = Math.cos(ang) * rad;+ const z = Math.sin(ang) * rad;+ const y = surfaceHeightAt(noise, shape, x, z) + 0.1;+ const s = 0.6 + noise(i, 17) * 0.8;+ q.setFromAxisAngle(new THREE.Vector3(0, 1, 0), noise(i, 23) * Math.PI);+ sca.set(s, s, s);+ m.compose(new THREE.Vector3(x, y, z), q, sca);+ inst.setMatrixAt(placed++, m);+ }+ inst.count = placed;+ inst.instanceMatrix.needsUpdate = true;+ accents.add(inst);+ } else if (ground === 'water') {+ // A small reflective, semi-translucent inset pool.+ const poolGeo = new THREE.CircleGeometry(ISLAND_RADIUS * 0.42, 64);+ const poolMat = new THREE.MeshStandardMaterial({+ color: col,+ roughness: 0.08,+ metalness: 0.0,+ transparent: true,+ opacity: 0.78,+ envMapIntensity: 1.2,+ });+ const env = getEnv();+ if (env) poolMat.envMap = env;+ const pool = new THREE.Mesh(poolGeo, poolMat);+ pool.rotation.x = -Math.PI / 2;+ pool.position.y = SURFACE_Y + 0.04;+ pool.receiveShadow = true;+ accents.add(pool);+ } else if (ground === 'void') {+ // Dark ground with a faint field of star sparkles hugging the surface.+ const count = 160;+ const pos = new Float32Array(count * 3);+ for (let i = 0; i < count; i++) {+ const ang = noise(i, 41) * Math.PI * 2;+ const rad = Math.sqrt(noise(i, 53)) * (ISLAND_RADIUS - 0.3);+ pos[i * 3] = Math.cos(ang) * rad;+ pos[i * 3 + 1] = surfaceHeightAt(noise, shape, Math.cos(ang) * rad, Math.sin(ang) * rad) + 0.05 + noise(i, 61) * 0.2;+ pos[i * 3 + 2] = Math.sin(ang) * rad;+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));+ const pm = new THREE.PointsMaterial({+ size: 0.07,+ color: new THREE.Color(palette.accent),+ transparent: true,+ opacity: 0.9,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ map: makeGlowTexture(64),+ });+ accents.add(new THREE.Points(g, pm));+ }++ return { material: mat, accents };+}++/**+ * Create the diorama renderer bound to a container element.+ * @param {HTMLElement} container+ * @param {object} [opts]+ */+export function createDioramaRenderer(container, opts = {}) {+ if (!container) throw new Error('createDioramaRenderer(container): container is required');++ const reduced = prefersReducedMotion();++ // --- core three objects ---+ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);+ camera.position.set(9, 7, 11);++ const renderer = new THREE.WebGLRenderer({+ antialias: true,+ alpha: true,+ powerPreference: 'high-performance',+ preserveDrawingBuffer: Boolean(opts.preserveDrawingBuffer),+ });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = opts.exposure ?? 1.0;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.domElement.style.display = 'block';+ renderer.domElement.style.width = '100%';+ renderer.domElement.style.height = '100%';+ renderer.domElement.setAttribute('aria-hidden', 'true');+ container.appendChild(renderer.domElement);++ // PMREM environment from RoomEnvironment for crisp PBR reflections.+ const pmrem = new THREE.PMREMGenerator(renderer);+ pmrem.compileEquirectangularShader();+ const envRT = pmrem.fromScene(new RoomEnvironment(), 0.04);+ scene.environment = envRT.texture;+ const getEnv = () => envRT.texture;++ // shared GLB loader (Draco-enabled)+ const dracoLoader = new DRACOLoader().setDecoderPath(DRACO_PATH);+ const gltfLoader = new GLTFLoader();+ gltfLoader.setDRACOLoader(dracoLoader);++ // controls+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.06;+ controls.minDistance = 6;+ controls.maxDistance = 30;+ controls.minPolarAngle = 0.15;+ controls.maxPolarAngle = Math.PI * 0.49; // never go under the island+ controls.target.set(0, 0.8, 0);+ controls.enablePan = false;++ // shared resources reused across builds+ const glowTex = makeGlowTexture(128);+ const radialTex = makeRadialTexture('rgba(0,0,0,0.5)', 128);++ // scene groups (rebuilt by setDiorama)+ const worldGroup = new THREE.Group();+ scene.add(worldGroup);++ // lights (created once, retuned per mood)+ const sun = new THREE.DirectionalLight(0xffffff, 1);+ sun.castShadow = true;+ sun.shadow.mapSize.set(1024, 1024);+ sun.shadow.bias = -0.0006;+ sun.shadow.normalBias = 0.02;+ sun.shadow.camera.near = 1;+ sun.shadow.camera.far = 60;+ sun.shadow.camera.left = -ISLAND_RADIUS * 1.6;+ sun.shadow.camera.right = ISLAND_RADIUS * 1.6;+ sun.shadow.camera.top = ISLAND_RADIUS * 1.6;+ sun.shadow.camera.bottom = -ISLAND_RADIUS * 1.6;+ scene.add(sun);+ scene.add(sun.target);++ const hemi = new THREE.HemisphereLight(0xffffff, 0x404040, 0.6);+ scene.add(hemi);+ const ambient = new THREE.AmbientLight(0xffffff, 0.2);+ scene.add(ambient);++ // per-diorama state+ let current = null; // normalized diorama+ let noise = makeNoise2D(1);+ let islandMesh = null;+ let skyMesh = null;+ let starField = null;+ let contactShadow = null;+ const seeds = new Map(); // objectId -> { group, status }+ const placed = new Map(); // objectId -> { group, glbUrl }+ const animations = []; // active timeline tweens+ const disposables = []; // textures/materials created per-build++ // --- camera framing ---+ const _box = new THREE.Box3();+ const _sphere = new THREE.Sphere();+ function computeContentSphere() {+ _box.makeEmpty();+ let any = false;+ worldGroup.traverse((n) => {+ if (n.isMesh || n.isPoints) {+ if (n.name === 'sky-dome') return;+ n.updateWorldMatrix(true, false);+ _box.expandByObject(n);+ any = true;+ }+ });+ if (!any) {+ _sphere.center.set(0, 0.8, 0);+ _sphere.radius = ISLAND_RADIUS;+ return _sphere;+ }+ _box.getBoundingSphere(_sphere);+ // keep the focus near the top surface, not the long underside cone+ _sphere.center.y = Math.max(_sphere.center.y, 0.4);+ _sphere.radius = Math.max(_sphere.radius * 0.7, ISLAND_RADIUS * 0.9);+ return _sphere;+ }++ let frameTween = null;+ function frameCamera(animated = true) {+ const sph = computeContentSphere();+ const fov = (camera.fov * Math.PI) / 180;+ const dist = (sph.radius / Math.sin(fov / 2)) * 1.05;+ const dir = new THREE.Vector3(0.62, 0.5, 0.78).normalize();+ const targetPos = sph.center.clone().add(dir.multiplyScalar(dist));+ const targetLook = sph.center.clone();+ targetLook.y = Math.max(targetLook.y, 0.6);++ if (!animated || reduced) {+ camera.position.copy(targetPos);+ controls.target.copy(targetLook);+ controls.update();+ return;+ }+ const fromPos = camera.position.clone();+ const fromTarget = controls.target.clone();+ frameTween = {+ t: 0,+ dur: 850,+ tick(dt) {+ this.t += dt;+ const k = easeInOutCubic(clamp01(this.t / this.dur));+ camera.position.lerpVectors(fromPos, targetPos, k);+ controls.target.lerpVectors(fromTarget, targetLook, k);+ return this.t >= this.dur;+ },+ };+ }++ // --- seeds ---+ function makeSeed(obj) {+ const group = new THREE.Group();+ const accent = new THREE.Color(current ? current.palette.accent : '#ffe08a');+ const core = new THREE.Mesh(+ new THREE.IcosahedronGeometry(0.14, 2),+ new THREE.MeshStandardMaterial({+ color: accent,+ emissive: accent,+ emissiveIntensity: 1.6,+ roughness: 0.4,+ metalness: 0,+ }),+ );+ core.castShadow = false;+ group.add(core);++ // glow sprite+ const glowMat = new THREE.SpriteMaterial({+ map: glowTex,+ color: accent,+ transparent: true,+ opacity: 0.85,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ const glow = new THREE.Sprite(glowMat);+ glow.scale.setScalar(0.9);+ group.add(glow);++ // a small point light so the seed actually casts color onto the ground+ const pl = new THREE.PointLight(accent, 1.2, 2.4, 2);+ pl.position.set(0, 0.05, 0);+ group.add(pl);++ const y = surfaceHeightAt(noise, current ? current.island : 'round', obj.position[0], obj.position[2]);+ group.position.set(obj.position[0], y + 0.45 + (obj.position[1] || 0), obj.position[2]);+ group.userData = { core, glow, pl, glowMat, status: obj.status, base: group.position.y };+ return group;+ }++ function setSeedStatus(group, status) {+ group.userData.status = status;+ const accent = new THREE.Color(current ? current.palette.accent : '#ffe08a');+ if (status === 'failed') {+ const dim = new THREE.Color('#6b6b78');+ group.userData.core.material.color.copy(dim);+ group.userData.core.material.emissive.copy(dim);+ group.userData.core.material.emissiveIntensity = 0.25;+ group.userData.glowMat.color.copy(dim);+ group.userData.glowMat.opacity = 0.25;+ group.userData.pl.intensity = 0.15;+ group.userData.pl.color.copy(dim);+ } else {+ group.userData.core.material.color.copy(accent);+ group.userData.core.material.emissive.copy(accent);+ group.userData.core.material.emissiveIntensity = status === 'forging' ? 2.4 : 1.6;+ group.userData.glowMat.color.copy(accent);+ group.userData.pl.color.copy(accent);+ }+ }++ // --- starfield (night) ---+ function buildStars(palette) {+ const count = 600;+ const pos = new Float32Array(count * 3);+ const R = 60;+ for (let i = 0; i < count; i++) {+ // upper hemisphere shell+ const u = Math.random();+ const v = Math.random() * 0.5 + 0.05;+ const theta = u * Math.PI * 2;+ const phi = Math.acos(1 - 2 * v);+ pos[i * 3] = R * Math.sin(phi) * Math.cos(theta);+ pos[i * 3 + 1] = Math.abs(R * Math.cos(phi)) + 4;+ pos[i * 3 + 2] = R * Math.sin(phi) * Math.sin(theta);+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));+ const m = new THREE.PointsMaterial({+ size: 0.5,+ sizeAttenuation: true,+ color: new THREE.Color(palette.accent).lerp(new THREE.Color('#ffffff'), 0.5),+ transparent: true,+ opacity: 0.9,+ depthWrite: false,+ map: glowTex,+ blending: THREE.AdditiveBlending,+ });+ const pts = new THREE.Points(g, m);+ pts.name = 'stars';+ disposables.push(g, m);+ return pts;+ }++ // --- build / reset the whole world ---+ function clearWorld() {+ for (const a of animations.splice(0)) {+ /* drop tweens */ void a;+ }+ frameTween = null;+ seeds.clear();+ placed.clear();+ while (worldGroup.children.length) {+ const child = worldGroup.children[0];+ worldGroup.remove(child);+ disposeObject(child);+ }+ for (const d of disposables.splice(0)) {+ if (d && d.dispose) d.dispose();+ }+ }++ function setDiorama(diorama) {+ const d = diorama && diorama.objects ? diorama : { ...normalizedFallback() };+ current = d;+ const palette = d.palette || defaultPalette(d.mood);+ const moodKey = MOOD_LIGHT[d.mood] ? d.mood : 'day';+ const ml = MOOD_LIGHT[moodKey];++ // stable noise seed from id/prompt so re-renders match+ const seedNum = hashString(d.id || d.prompt || 'diorama');+ noise = makeNoise2D((seedNum % 9973) + 1);++ clearWorld();++ // --- sky dome (vertical gradient, painted on inside of a large sphere) ---+ const skyTex = makeSkyTexture(palette.sky[0], palette.sky[1]);+ disposables.push(skyTex);+ const skyMat = new THREE.MeshBasicMaterial({+ map: skyTex,+ side: THREE.BackSide,+ depthWrite: false,+ fog: false,+ });+ skyMesh = new THREE.Mesh(new THREE.SphereGeometry(90, 32, 16), skyMat);+ skyMesh.name = 'sky-dome';+ worldGroup.add(skyMesh);+ // also set scene.background so screenshots/AR backdrop read the horizon tone+ scene.background = new THREE.Color(palette.sky[1]);++ // --- fog ---+ const fogColor = new THREE.Color(palette.fog);+ const fogDensity = 0.006 + ml.fog * 0.9;+ scene.fog = new THREE.FogExp2(fogColor, fogDensity);++ // --- island ---+ const islandGeo = buildIslandGeometry(d.island, noise);+ const { material: groundMat, accents } = buildGroundMaterial(d.ground, palette, noise, d.island, getEnv);+ // underside rocky material as a second material via vertex-based? Keep single+ // material but darken using a subtle gradient won't work without uv; instead+ // add a separate underside-tint via a darker overlay mesh would z-fight.+ // Simpler + clean: rely on lighting + the cone shape; tint underside darker+ // through vertex colors.+ applyUndersideVertexColors(islandGeo, groundMat);+ islandMesh = new THREE.Mesh(islandGeo, groundMat);+ islandMesh.castShadow = true;+ islandMesh.receiveShadow = true;+ islandMesh.frustumCulled = true;+ worldGroup.add(islandMesh);+ worldGroup.add(accents);+ disposables.push(islandGeo, groundMat);++ // --- contact shadow blob under the island ---+ const shadowMat = new THREE.MeshBasicMaterial({+ map: radialTex,+ transparent: true,+ opacity: 0.45,+ depthWrite: false,+ color: 0x000000,+ fog: false,+ });+ contactShadow = new THREE.Mesh(new THREE.PlaneGeometry(ISLAND_RADIUS * 3.4, ISLAND_RADIUS * 3.4), shadowMat);+ contactShadow.rotation.x = -Math.PI / 2;+ contactShadow.position.y = -7.6;+ contactShadow.name = 'contact-shadow';+ worldGroup.add(contactShadow);+ disposables.push(shadowMat);++ // --- stars at night ---+ if (moodKey === 'night') {+ starField = buildStars(palette);+ worldGroup.add(starField);+ } else {+ starField = null;+ }++ // --- lights retuned for mood + palette accent ---+ const accentColor = new THREE.Color(palette.accent);+ const sunColor = new THREE.Color(0xffffff).lerp(accentColor, 0.45);+ sun.color.copy(sunColor);+ sun.intensity = ml.sunIntensity * 1.4;+ // position the sun from elevation (0..1 -> angle), azimuth fixed for hero look+ const elev = THREE.MathUtils.clamp(ml.sunElevation, -0.2, 1) * (Math.PI / 2);+ const az = Math.PI * 0.25;+ const sunDist = 24;+ sun.position.set(+ Math.cos(elev) * Math.cos(az) * sunDist,+ Math.max(2, Math.sin(elev) * sunDist + 6),+ Math.cos(elev) * Math.sin(az) * sunDist,+ );+ sun.target.position.set(0, 0, 0);++ hemi.color.copy(new THREE.Color(palette.sky[0]));+ hemi.groundColor.copy(new THREE.Color(palette.ground).multiplyScalar(0.6));+ hemi.intensity = ml.ambient * 0.9;+ ambient.intensity = ml.ambient * 0.35;+ ambient.color.copy(fogColor).lerp(new THREE.Color('#ffffff'), 0.4);++ // --- seeds for every object ---+ for (const obj of d.objects) {+ const seed = makeSeed(obj);+ worldGroup.add(seed);+ seeds.set(obj.id, seed);+ if (obj.status === 'failed') setSeedStatus(seed, 'failed');+ else setSeedStatus(seed, obj.status === 'forging' ? 'forging' : 'pending');+ }++ frameCamera(false);+ needsRender = true;+ return api;+ }++ // --- materialize a forged GLB ---+ function fitGltfScene(root, objScale) {+ const box = new THREE.Box3().setFromObject(root);+ if (box.isEmpty()) return root;+ const size = new THREE.Vector3();+ const center = new THREE.Vector3();+ box.getSize(size);+ box.getCenter(center);+ const footprint = Math.max(size.x, size.z) || Math.max(size.x, size.y, size.z) || 1;+ const norm = (TARGET_FOOTPRINT / footprint) * (objScale || 1);++ const wrapper = new THREE.Group();+ // recenter horizontally to origin, drop base to y=0+ root.position.x -= center.x;+ root.position.z -= center.z;+ root.position.y -= box.min.y;+ wrapper.add(root);+ wrapper.scale.setScalar(norm);++ root.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = true;+ n.frustumCulled = true;+ if (n.material) {+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) {+ m.envMapIntensity = m.envMapIntensity ?? 1;+ if (m.map) m.map.colorSpace = THREE.SRGBColorSpace;+ m.needsUpdate = true;+ }+ }+ }+ });+ return wrapper;+ }++ function materializeObject(objectId, glbUrl) {+ return new Promise((resolve, reject) => {+ const obj = current && current.objects.find((o) => o.id === objectId);+ if (!obj) {+ reject(new Error(`materializeObject: unknown object "${objectId}"`));+ return;+ }+ const seed = seeds.get(objectId);+ if (seed) setSeedStatus(seed, 'forging');++ gltfLoader.load(+ glbUrl,+ (gltf) => {+ try {+ const fitted = fitGltfScene(gltf.scene, obj.scale);+ const y = surfaceHeightAt(noise, current.island, obj.position[0], obj.position[2]);+ fitted.position.set(obj.position[0], y + (obj.position[1] || 0), obj.position[2]);+ fitted.rotation.y = obj.rotationY || 0;+ fitted.userData.glbUrl = glbUrl;+ fitted.userData.objectId = objectId;++ // remove any previously placed mesh for this object+ const prev = placed.get(objectId);+ if (prev && prev.group.parent) {+ worldGroup.remove(prev.group);+ disposeObject(prev.group);+ }+ worldGroup.add(fitted);+ placed.set(objectId, { group: fitted, glbUrl });++ playMaterialize(seed, fitted, obj);+ needsRender = true;+ resolve(fitted);+ } catch (err) {+ reject(err instanceof Error ? err : new Error(String(err)));+ }+ },+ undefined,+ (err) => {+ if (seed) setSeedStatus(seed, 'failed');+ needsRender = true;+ reject(err instanceof Error ? err : new Error(`Failed to load GLB: ${glbUrl}`));+ },+ );+ });+ }++ function playMaterialize(seed, fitted, obj) {+ const accent = new THREE.Color(current.palette.accent);++ if (reduced) {+ // snap in, hide the seed+ if (seed) {+ worldGroup.remove(seed);+ seeds.delete(obj.id);+ }+ fitted.scale.multiplyScalar(1);+ return;+ }++ // expanding ring sprite at the seed location+ const ringMat = new THREE.SpriteMaterial({+ map: glowTex,+ color: accent,+ transparent: true,+ opacity: 0.9,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ const ring = new THREE.Sprite(ringMat);+ ring.position.copy(fitted.position);+ ring.position.y += 0.3;+ ring.scale.setScalar(0.2);+ worldGroup.add(ring);++ // sparkle burst+ const sparkCount = 14;+ const sparkPos = new Float32Array(sparkCount * 3);+ const sparkVel = [];+ for (let i = 0; i < sparkCount; i++) {+ sparkPos[i * 3] = 0;+ sparkPos[i * 3 + 1] = 0;+ sparkPos[i * 3 + 2] = 0;+ const a = Math.random() * Math.PI * 2;+ const up = 0.4 + Math.random() * 0.9;+ sparkVel.push(new THREE.Vector3(Math.cos(a) * (0.4 + Math.random() * 0.6), up, Math.sin(a) * (0.4 + Math.random() * 0.6)));+ }+ const sparkGeo = new THREE.BufferGeometry();+ sparkGeo.setAttribute('position', new THREE.BufferAttribute(sparkPos, 3));+ const sparkMat = new THREE.PointsMaterial({+ size: 0.18,+ color: accent,+ transparent: true,+ opacity: 1,+ depthWrite: false,+ map: glowTex,+ blending: THREE.AdditiveBlending,+ });+ const sparks = new THREE.Points(sparkGeo, sparkMat);+ sparks.position.copy(fitted.position);+ sparks.position.y += 0.3;+ worldGroup.add(sparks);++ // mesh emerges: from below + small + transparent -> in place+ const finalScale = fitted.scale.clone();+ const startScale = finalScale.clone().multiplyScalar(0.25);+ const finalY = fitted.position.y;+ const startY = finalY - 0.6;+ fitted.scale.copy(startScale);+ fitted.position.y = startY;+ setMeshOpacity(fitted, 0);++ // seed flare then fade+ const seedStartIntensity = seed ? seed.userData.core.material.emissiveIntensity : 0;++ const tween = {+ t: 0,+ dur: MATERIALIZE_MS,+ done: false,+ tick(dt) {+ this.t += dt;+ const raw = clamp01(this.t / this.dur);+ const k = easeOutCubic(raw);++ // mesh rise + scale + fade+ fitted.scale.lerpVectors(startScale, finalScale, k);+ fitted.position.y = startY + (finalY - startY) * k;+ setMeshOpacity(fitted, k);++ // seed flares early then collapses+ if (seed) {+ const flare = raw < 0.35 ? 1 + (raw / 0.35) * 2.5 : Math.max(0, 1 - (raw - 0.35) / 0.4);+ seed.userData.core.material.emissiveIntensity = seedStartIntensity * flare + flare * 2;+ seed.userData.glowMat.opacity = 0.85 * flare;+ const ss = 1 + (raw < 0.35 ? raw * 2 : 0);+ seed.userData.core.scale.setScalar(Math.max(0.001, ss * (1 - raw)));+ seed.userData.pl.intensity = 1.2 * flare;+ }++ // ring expands + fades+ ring.scale.setScalar(0.2 + raw * 3.2);+ ringMat.opacity = 0.9 * (1 - raw);++ // sparks fly out + gravity, fade+ const sp = sparkGeo.attributes.position;+ for (let i = 0; i < sparkCount; i++) {+ const v = sparkVel[i];+ sp.array[i * 3] = v.x * raw * 1.4;+ sp.array[i * 3 + 1] = v.y * raw * 1.4 - raw * raw * 0.8;+ sp.array[i * 3 + 2] = v.z * raw * 1.4;+ }+ sp.needsUpdate = true;+ sparkMat.opacity = 1 - raw;++ if (raw >= 1) {+ this.done = true;+ setMeshOpacity(fitted, 1, true); // restore original material opacity+ fitted.scale.copy(finalScale);+ fitted.position.y = finalY;+ // remove seed + fx+ if (seed) {+ worldGroup.remove(seed);+ disposeObject(seed);+ seeds.delete(obj.id);+ }+ worldGroup.remove(ring);+ ringMat.map = null;+ ringMat.dispose();+ worldGroup.remove(sparks);+ sparkGeo.dispose();+ sparkMat.dispose();+ }+ return this.done;+ },+ };+ animations.push(tween);+ needsRender = true;+ }++ function markFailed(objectId) {+ const seed = seeds.get(objectId);+ if (seed) {+ setSeedStatus(seed, 'failed');+ needsRender = true;+ }+ if (current) {+ const obj = current.objects.find((o) => o.id === objectId);+ if (obj) obj.status = 'failed';+ }+ return api;+ }++ // --- auto orbit ---+ let autoOrbit = false;+ let userInteracting = false;+ let lastInteraction = performance.now();+ const onPointerDown = () => {+ userInteracting = true;+ lastInteraction = performance.now();+ };+ const onPointerUp = () => {+ userInteracting = false;+ lastInteraction = performance.now();+ };+ controls.addEventListener('start', onPointerDown);+ controls.addEventListener('end', onPointerUp);++ function startAutoOrbit(on) {+ autoOrbit = Boolean(on) && !reduced;+ lastInteraction = performance.now();+ needsRender = true;+ return api;+ }++ // --- render loop, gated by visibility ---+ let rafId = 0;+ let running = false;+ let visible = true;+ let needsRender = true;+ let lastTime = performance.now();++ function loop(now) {+ rafId = requestAnimationFrame(loop);+ const dt = Math.min(64, now - lastTime);+ lastTime = now;++ if (!visible || document.hidden) {+ needsRender = true; // force a fresh frame when we resume+ return;+ }++ let active = false;++ // frame tween+ if (frameTween) {+ if (frameTween.tick(dt)) frameTween = null;+ active = true;+ }++ // materialize tweens+ if (animations.length) {+ for (let i = animations.length - 1; i >= 0; i--) {+ if (animations[i].tick(dt)) animations.splice(i, 1);+ }+ active = true;+ }++ // idle pulse on forging seeds + gentle seed bob+ const tsec = now / 1000;+ if (seeds.size) {+ for (const seed of seeds.values()) {+ const ud = seed.userData;+ const bob = Math.sin(tsec * 1.6 + seed.position.x) * 0.05;+ seed.position.y = ud.base + bob;+ if (ud.status === 'forging') {+ const pulse = 0.5 + 0.5 * Math.sin(tsec * 3.4);+ ud.glowMat.opacity = 0.6 + pulse * 0.35;+ ud.core.material.emissiveIntensity = 1.8 + pulse * 1.4;+ ud.pl.intensity = 0.9 + pulse * 0.9;+ } else if (ud.status === 'pending') {+ ud.glowMat.opacity = 0.55 + 0.2 * Math.sin(tsec * 1.5 + seed.position.z);+ }+ }+ active = true;+ }++ // water shimmer+ if (current && current.ground === 'water') active = true;++ // auto orbit+ if (autoOrbit && !userInteracting && now - lastInteraction > 3000) {+ const sph = computeContentSphere();+ controls.target.lerp(new THREE.Vector3(sph.center.x, Math.max(sph.center.y, 0.6), sph.center.z), 0.02);+ // rotate camera around target+ const offset = camera.position.clone().sub(controls.target);+ const ang = 0.00018 * dt;+ const cos = Math.cos(ang);+ const sin = Math.sin(ang);+ const nx = offset.x * cos - offset.z * sin;+ const nz = offset.x * sin + offset.z * cos;+ offset.x = nx;+ offset.z = nz;+ camera.position.copy(controls.target).add(offset);+ active = true;+ }++ const damped = controls.update();+ if (damped || active || needsRender) {+ renderer.render(scene, camera);+ needsRender = false;+ }+ }++ function start() {+ if (running) return;+ running = true;+ lastTime = performance.now();+ rafId = requestAnimationFrame(loop);+ }+ function stop() {+ running = false;+ if (rafId) cancelAnimationFrame(rafId);+ rafId = 0;+ }++ // --- resize ---+ function resize() {+ const w = container.clientWidth || container.offsetWidth || 0;+ const h = container.clientHeight || container.offsetHeight || 0;+ if (w === 0 || h === 0) return;+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ renderer.setSize(w, h, false);+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ needsRender = true;+ }++ let hadFirstSize = false;+ const resizeObserver = new ResizeObserver(() => {+ const w = container.clientWidth;+ const h = container.clientHeight;+ if (w > 0 && h > 0) {+ resize();+ if (!hadFirstSize) {+ hadFirstSize = true;+ start();+ if (current) frameCamera(false);+ }+ }+ });+ resizeObserver.observe(container);++ // visibility gating+ const intersectionObserver = new IntersectionObserver(+ (entries) => {+ for (const e of entries) visible = e.isIntersecting;+ needsRender = true;+ },+ { threshold: 0.01 },+ );+ intersectionObserver.observe(container);++ const onVisibility = () => {+ needsRender = true;+ };+ document.addEventListener('visibilitychange', onVisibility);++ // kick off immediately if the container already has a size+ if (container.clientWidth > 0 && container.clientHeight > 0) {+ resize();+ hadFirstSize = true;+ start();+ }++ // --- public api ---+ function getActiveGlbUrls() {+ return Array.from(placed.values()).map((p) => p.glbUrl).filter(Boolean);+ }++ function frame() {+ frameCamera(true);+ needsRender = true;+ return api;+ }++ let disposed = false;+ function dispose() {+ if (disposed) return;+ disposed = true;+ stop();+ resizeObserver.disconnect();+ intersectionObserver.disconnect();+ document.removeEventListener('visibilitychange', onVisibility);+ controls.removeEventListener('start', onPointerDown);+ controls.removeEventListener('end', onPointerUp);+ controls.dispose();++ clearWorld();+ scene.remove(worldGroup);++ glowTex.dispose();+ radialTex.dispose();+ envRT.texture.dispose();+ pmrem.dispose();+ dracoLoader.dispose();++ if (scene.background && scene.background.isTexture) scene.background.dispose();+ scene.environment = null;++ renderer.dispose();+ if (renderer.domElement.parentNode === container) container.removeChild(renderer.domElement);+ renderer.forceContextLoss();+ }++ const api = {+ setDiorama,+ materializeObject,+ markFailed,+ frame,+ startAutoOrbit,+ getActiveGlbUrls,+ resize,+ dispose,+ // escape hatches the integrator may want+ get scene() {+ return scene;+ },+ get camera() {+ return camera;+ },+ get renderer() {+ return renderer;+ },+ };+ return api;+}++// --- helpers shared by both exports ---++function hashString(s) {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++function normalizedFallback() {+ const p = defaultPalette('day');+ return {+ id: 'fallback',+ prompt: '',+ title: '',+ mood: 'day',+ palette: p,+ ground: 'grass',+ island: 'round',+ objects: [],+ };+}++/** Darken underside vertices so the rocky base reads distinct from the top. */+function applyUndersideVertexColors(geo, material) {+ const pos = geo.attributes.position;+ const colors = new Float32Array(pos.count * 3);+ const base = new THREE.Color(material.color.getHex());+ const dark = base.clone().multiplyScalar(0.32);+ const c = new THREE.Color();+ for (let i = 0; i < pos.count; i++) {+ const y = pos.getY(i);+ // y >= ~ -0.6 is top surface; below blends to dark rock+ const t = clamp01((-y) / 4); // 0 at top, 1 deep+ c.copy(base).lerp(dark, t);+ colors[i * 3] = c.r;+ colors[i * 3 + 1] = c.g;+ colors[i * 3 + 2] = c.b;+ }+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));+ material.vertexColors = true;+ material.color.set(0xffffff); // let vertex colors drive it+ material.needsUpdate = true;+}++/** Set opacity across a fitted GLB subtree; remembers originals on first call. */+function setMeshOpacity(root, k, restore = false) {+ root.traverse((n) => {+ if (!n.isMesh || !n.material) return;+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) {+ if (m.userData.__baseOpacity === undefined) {+ m.userData.__baseOpacity = m.opacity;+ m.userData.__baseTransparent = m.transparent;+ }+ if (restore) {+ m.opacity = m.userData.__baseOpacity;+ m.transparent = m.userData.__baseTransparent;+ m.depthWrite = m.userData.__baseTransparent ? m.depthWrite : true;+ } else {+ m.transparent = true;+ m.opacity = m.userData.__baseOpacity * k;+ }+ m.needsUpdate = false;+ }+ });+}++/**+ * One-shot thumbnail render of a saved diorama into a canvas. Owns its own+ * scene/renderer/loader. Renders the island + mood sky always; loads the first+ * available forged GLB (or all of them, capped) so the preview is never blank.+ * Returns a dispose function the caller invokes when the thumbnail is gone.+ *+ * @param {HTMLCanvasElement} canvas+ * @param {object} diorama+ * @returns {Promise<() => void>}+ */+export async function renderThumbnail(canvas, diorama) {+ if (!canvas) throw new Error('renderThumbnail(canvas): canvas is required');+ const d = diorama && diorama.objects ? diorama : normalizedFallback();+ const palette = d.palette || defaultPalette(d.mood);+ const moodKey = MOOD_LIGHT[d.mood] ? d.mood : 'day';+ const ml = MOOD_LIGHT[moodKey];++ const width = canvas.width || canvas.clientWidth || 320;+ const height = canvas.height || canvas.clientHeight || 200;++ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.setSize(width, height, false);+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.0;+ renderer.outputColorSpace = THREE.SRGBColorSpace;++ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(40, width / height, 0.1, 200);++ const pmrem = new THREE.PMREMGenerator(renderer);+ const envRT = pmrem.fromScene(new RoomEnvironment(), 0.04);+ scene.environment = envRT.texture;++ const noise = makeNoise2D((hashString(d.id || d.prompt || 'diorama') % 9973) + 1);+ const created = []; // geometries/materials/textures to dispose+ const loaders = [];++ // sky+ const skyTex = makeSkyTexture(palette.sky[0], palette.sky[1]);+ const skyMat = new THREE.MeshBasicMaterial({ map: skyTex, side: THREE.BackSide, depthWrite: false, fog: false });+ const sky = new THREE.Mesh(new THREE.SphereGeometry(90, 24, 12), skyMat);+ scene.add(sky);+ scene.background = new THREE.Color(palette.sky[1]);+ created.push(skyTex, skyMat, sky.geometry);++ scene.fog = new THREE.FogExp2(new THREE.Color(palette.fog), 0.006 + ml.fog * 0.9);++ // island+ const islandGeo = buildIslandGeometry(d.island, noise);+ const { material: groundMat, accents } = buildGroundMaterial(d.ground, palette, noise, d.island, () => envRT.texture);+ applyUndersideVertexColors(islandGeo, groundMat);+ const island = new THREE.Mesh(islandGeo, groundMat);+ island.castShadow = true;+ island.receiveShadow = true;+ scene.add(island);+ scene.add(accents);+ created.push(islandGeo, groundMat);++ // contact shadow+ const radialTex = makeRadialTexture('rgba(0,0,0,0.5)', 128);+ const shadowMat = new THREE.MeshBasicMaterial({ map: radialTex, transparent: true, opacity: 0.45, depthWrite: false, color: 0x000000, fog: false });+ const contact = new THREE.Mesh(new THREE.PlaneGeometry(ISLAND_RADIUS * 3.4, ISLAND_RADIUS * 3.4), shadowMat);+ contact.rotation.x = -Math.PI / 2;+ contact.position.y = -7.6;+ scene.add(contact);+ created.push(radialTex, shadowMat, contact.geometry);++ // lights+ const accentColor = new THREE.Color(palette.accent);+ const sun = new THREE.DirectionalLight(new THREE.Color(0xffffff).lerp(accentColor, 0.45), ml.sunIntensity * 1.4);+ sun.castShadow = true;+ sun.shadow.mapSize.set(1024, 1024);+ sun.shadow.bias = -0.0006;+ sun.shadow.normalBias = 0.02;+ sun.shadow.camera.left = -ISLAND_RADIUS * 1.6;+ sun.shadow.camera.right = ISLAND_RADIUS * 1.6;+ sun.shadow.camera.top = ISLAND_RADIUS * 1.6;+ sun.shadow.camera.bottom = -ISLAND_RADIUS * 1.6;+ sun.shadow.camera.far = 60;+ const elev = THREE.MathUtils.clamp(ml.sunElevation, -0.2, 1) * (Math.PI / 2);+ sun.position.set(Math.cos(elev) * Math.cos(Math.PI * 0.25) * 24, Math.max(2, Math.sin(elev) * 24 + 6), Math.cos(elev) * Math.sin(Math.PI * 0.25) * 24);+ scene.add(sun);+ scene.add(sun.target);+ const hemi = new THREE.HemisphereLight(new THREE.Color(palette.sky[0]), new THREE.Color(palette.ground).multiplyScalar(0.6), ml.ambient * 0.9);+ scene.add(hemi);+ const ambient = new THREE.AmbientLight(new THREE.Color(palette.fog).lerp(new THREE.Color('#ffffff'), 0.4), ml.ambient * 0.35);+ scene.add(ambient);++ if (moodKey === 'night') {+ const count = 300;+ const posArr = new Float32Array(count * 3);+ const R = 60;+ for (let i = 0; i < count; i++) {+ const u = Math.random();+ const v = Math.random() * 0.5 + 0.05;+ const theta = u * Math.PI * 2;+ const phi = Math.acos(1 - 2 * v);+ posArr[i * 3] = R * Math.sin(phi) * Math.cos(theta);+ posArr[i * 3 + 1] = Math.abs(R * Math.cos(phi)) + 4;+ posArr[i * 3 + 2] = R * Math.sin(phi) * Math.sin(theta);+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(posArr, 3));+ const glowTex = makeGlowTexture(64);+ const m = new THREE.PointsMaterial({ size: 0.5, color: new THREE.Color(palette.accent).lerp(new THREE.Color('#ffffff'), 0.5), transparent: true, opacity: 0.9, depthWrite: false, map: glowTex, blending: THREE.AdditiveBlending });+ const stars = new THREE.Points(g, m);+ scene.add(stars);+ created.push(g, m, glowTex);+ }++ // seeds for any unforged objects (so it reads as a populated little world)+ const glowTex = makeGlowTexture(96);+ created.push(glowTex);+ for (const obj of d.objects) {+ if (obj.glbUrl) continue;+ const y = surfaceHeightAt(noise, d.island, obj.position[0], obj.position[2]);+ const spriteMat = new THREE.SpriteMaterial({ map: glowTex, color: accentColor, transparent: true, opacity: 0.8, depthWrite: false, blending: THREE.AdditiveBlending });+ const sprite = new THREE.Sprite(spriteMat);+ sprite.scale.setScalar(0.8 * (obj.scale || 1));+ sprite.position.set(obj.position[0], y + 0.45, obj.position[2]);+ scene.add(sprite);+ created.push(spriteMat);+ }++ // load forged GLBs (capped), defensively — a failure must not blank the thumb+ const dracoLoader = new DRACOLoader().setDecoderPath(DRACO_PATH);+ const gltfLoader = new GLTFLoader();+ gltfLoader.setDRACOLoader(dracoLoader);+ loaders.push(dracoLoader);++ const forged = d.objects.filter((o) => o.glbUrl).slice(0, 8);+ const placedGroups = [];+ await Promise.all(+ forged.map(+ (obj) =>+ new Promise((resolve) => {+ gltfLoader.load(+ obj.glbUrl,+ (gltf) => {+ try {+ const root = gltf.scene;+ const box = new THREE.Box3().setFromObject(root);+ if (!box.isEmpty()) {+ const size = new THREE.Vector3();+ const center = new THREE.Vector3();+ box.getSize(size);+ box.getCenter(center);+ const footprint = Math.max(size.x, size.z) || 1;+ const norm = (TARGET_FOOTPRINT / footprint) * (obj.scale || 1);+ const wrapper = new THREE.Group();+ root.position.x -= center.x;+ root.position.z -= center.z;+ root.position.y -= box.min.y;+ wrapper.add(root);+ wrapper.scale.setScalar(norm);+ const y = surfaceHeightAt(noise, d.island, obj.position[0], obj.position[2]);+ wrapper.position.set(obj.position[0], y, obj.position[2]);+ wrapper.rotation.y = obj.rotationY || 0;+ root.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = true;+ if (n.material) {+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const mm of mats) {+ if (mm.map) mm.map.colorSpace = THREE.SRGBColorSpace;+ }+ }+ }+ });+ scene.add(wrapper);+ placedGroups.push(wrapper);+ }+ } catch {+ /* skip this mesh; thumbnail still renders the island */+ }+ resolve();+ },+ undefined,+ () => resolve(), // ignore load failure for a thumbnail+ );+ }),+ ),+ );++ // frame to a 3/4 hero angle+ const box = new THREE.Box3();+ box.makeEmpty();+ box.expandByObject(island);+ for (const g of placedGroups) box.expandByObject(g);+ const sphere = new THREE.Sphere();+ box.getBoundingSphere(sphere);+ sphere.center.y = Math.max(0.4, sphere.center.y * 0.4);+ sphere.radius = Math.max(sphere.radius * 0.62, ISLAND_RADIUS * 0.9);+ const fov = (camera.fov * Math.PI) / 180;+ const dist = (sphere.radius / Math.sin(fov / 2)) * 1.05;+ const dir = new THREE.Vector3(0.62, 0.5, 0.78).normalize();+ camera.position.copy(sphere.center).add(dir.multiplyScalar(dist));+ camera.lookAt(sphere.center.x, Math.max(sphere.center.y, 0.6), sphere.center.z);+ sun.target.position.set(0, 0, 0);+ sun.target.updateMatrixWorld();++ // render a few frames so env/shadows settle+ renderer.render(scene, camera);+ renderer.render(scene, camera);++ let disposed = false;+ return function disposeThumbnail() {+ if (disposed) return;+ disposed = true;+ for (const g of placedGroups) {+ scene.remove(g);+ disposeObject(g);+ }+ scene.traverse((n) => {+ if (n === island) return;+ });+ disposeObject(island);+ disposeObject(accents);+ for (const r of created) {+ if (r && r.dispose) r.dispose();+ }+ for (const l of loaders) {+ if (l && l.dispose) l.dispose();+ }+ envRT.texture.dispose();+ pmrem.dispose();+ if (scene.background && scene.background.isTexture) scene.background.dispose();+ renderer.dispose();+ renderer.forceContextLoss();+ };+}diff --git a/src/erc8004/abi.js b/src/erc8004/abi.jsindex 0079b6564..eb10a0638 100644--- a/src/erc8004/abi.js+++ b/src/erc8004/abi.js@@ -55,13 +55,27 @@ export const IDENTITY_REGISTRY_ABI = ['event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',];+// Mirrors contracts/src/ReputationRegistry.sol exactly (the deployed bytecode):+// submitFeedback(uint256, int8 score, string uri) — score is signed, [-100,100]+// getReputation(uint256) → (int256 avgX100, uint256 count) — pre-averaged ×100; divide for display+// FeedbackSubmitted(agentId, from, int8 score, string uri) — `from`, not `submitter`+// The earlier `submitReputation` / `(uint256 totalScore, uint256 count)` shape+// did NOT match the contract: ethers mis-decoded a signed average as a raw total+// and the write selector reverted. Kept byte-identical with sdk/src/erc8004/abi.js.export const REPUTATION_REGISTRY_ABI = [- 'function submitReputation(uint256 agentId, uint8 score, string comment) external',- 'function getReputation(uint256 agentId) external view returns (uint256 totalScore, uint256 count)',+ 'function submitFeedback(uint256 agentId, int8 score, string uri) external',+ 'function getReputation(uint256 agentId) external view returns (int256 avgX100, uint256 count)',+ 'function getFeedbackCount(uint256 agentId) external view returns (uint256)',+ 'function getFeedback(uint256 agentId, uint256 index) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri))',+ 'function getFeedbackRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri)[])',+ 'function hasReviewed(uint256 agentId, address reviewer) external view returns (bool)','function stakeReputation(uint256 agentId, uint8 score, string comment) external payable',+ 'function withdrawStake(uint256 agentId) external','function getTotalStake(uint256 agentId) external view returns (uint256)',- 'event ReputationSubmitted(uint256 indexed agentId, address indexed submitter, uint8 score, string comment)',+ 'function getStake(uint256 agentId, address staker) external view returns (uint256)',+ 'event FeedbackSubmitted(uint256 indexed agentId, address indexed from, int8 score, string uri)','event ReputationStaked(uint256 indexed agentId, address indexed staker, uint8 score, uint256 value)',+ 'event StakeWithdrawn(uint256 indexed agentId, address indexed staker, uint256 value)',];/**diff --git a/src/erc8004/reputation.js b/src/erc8004/reputation.jsindex b70c9a831..99de8f442 100644--- a/src/erc8004/reputation.js+++ b/src/erc8004/reputation.js@@ -1,9 +1,17 @@/*** ReputationRegistry helpers — submit and query agent feedback.*- * Matches the canonical ERC-8004 reputation contract:- * submitReputation(uint256 agentId, uint8 score, string comment)- * getReputation(uint256 agentId) → (uint256 totalScore, uint256 count)+ * Matches the deployed ERC-8004 reputation contract+ * (contracts/src/ReputationRegistry.sol) exactly:+ * submitFeedback(uint256 agentId, int8 score, string uri)+ * getReputation(uint256 agentId) → (int256 avgX100, uint256 count)+ * getTotalStake(uint256 agentId) → uint256+ * FeedbackSubmitted(agentId, from, int8 score, string uri)+ *+ * `getReputation` returns the average already multiplied by 100 (so callers can+ * divide client-side without precision loss). Never re-divide by `count` — that+ * is what the contract already did. `score` is a signed int8 in [-100, 100]; the+ * star UIs pass 1-5, which is a valid subset.*/import { Contract } from 'ethers';@@ -18,43 +26,42 @@ function getContract(chainId, runner) {}/**- * Submit a reputation score about an agent.+ * Submit reputation feedback about an agent.* @param {object} opts* @param {number|bigint} opts.agentId- * @param {number} opts.score Integer 0-255 (typically 1-5 or 1-100)- * @param {string} [opts.comment=''] Free-form comment+ * @param {number} opts.score Signed int8 in [-100, 100] (star UIs pass 1-5)+ * @param {string} [opts.comment=''] Optional public on-chain comment / ipfs:// URI* @param {import('ethers').Signer} opts.signer* @param {number} [opts.chainId]* @returns {Promise<string>} tx hash*/-export async function submitReputation({ agentId, score, comment = '', signer, chainId }) {- if (!Number.isInteger(score) || score < 0 || score > 255) {- throw new Error('score must be a uint8 (0-255)');+export async function submitFeedback({ agentId, score, comment = '', signer, chainId }) {+ if (!Number.isInteger(score) || score < -100 || score > 100) {+ throw new Error('score must be an int8 in [-100, 100]');}const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);const contract = getContract(resolvedChainId, signer);- const tx = await contract.submitReputation(agentId, score, comment);+ const tx = await contract.submitFeedback(agentId, score, comment);await tx.wait();return tx.hash;}-// Back-compat alias — the canonical contract calls it submitReputation.-export const submitFeedback = submitReputation;+// Back-compat alias — the prior client API called this submitReputation.+export const submitReputation = submitFeedback;/*** Read aggregated reputation.- * @returns {Promise<{total: number, count: number, average: number}>}- * average is 0 when no reviews have been submitted.+ * @returns {Promise<{average: number, count: number}>}+ * `average` is the on-chain avgX100 divided by 100 (so 4.2 reads as 4.2),+ * 0 when no reviews have been submitted.*/export async function getReputation({ agentId, runner, chainId }) {const contract = getContract(chainId, runner);- const [totalScore, count] = await contract.getReputation(agentId);+ const [avgX100, count] = await contract.getReputation(agentId);const n = Number(count);- const t = Number(totalScore);return {- total: t,count: n,- average: n === 0 ? 0 : t / n,+ average: n === 0 ? 0 : Number(avgX100) / 100,};}@@ -90,18 +97,18 @@ export async function getTotalStake({ agentId, runner, chainId }) {}/**- * Enumerate past reviews by querying the ReputationSubmitted event log.+ * Enumerate past reviews by querying the FeedbackSubmitted event log.* Optional — only useful if an indexer/provider supports filtered log queries.*/export async function getRecentReviews({ agentId, runner, chainId, fromBlock = 0 }) {const contract = getContract(chainId, runner);- const filter = contract.filters.ReputationSubmitted(agentId);+ const filter = contract.filters.FeedbackSubmitted(agentId);const events = await contract.queryFilter(filter, fromBlock);return events.map((ev) => ({agentId: Number(ev.args.agentId),- from: ev.args.submitter,+ from: ev.args.from,score: Number(ev.args.score),- comment: ev.args.comment,+ comment: ev.args.uri,blockNumber: ev.blockNumber,txHash: ev.transactionHash,}));diff --git a/src/irl.js b/src/irl.jsindex 1b95cbf5a..9a93abc01 100644--- a/src/irl.js+++ b/src/irl.js@@ -897,7 +897,7 @@ if (avatarBtn) {// (−Z = north, matching gpsToWorld), the avatar holds its real-world bearing for// every viewer, and the stored pose is a genuine compass heading. Page-relative// devices keep the delta fallback and are tagged `:rel` for A3 down-weighting.-let lastDevAlpha = 0, lastDevBeta = 90;+let lastDevAlpha = 0, lastDevBeta = 90, lastDevGamma = 0;let devOrientBaseAlpha = null; // null = inactivelet devOrientBaseBeta = null;let devOrientBaseCamYaw = 0;@@ -935,9 +935,14 @@ function onDeviceOrientation(e) {if (isFiniteReading(e.alpha, e.beta)) {lastDevAlpha = e.alpha;lastDevBeta = e.beta;+ // gamma (left↔right tilt) only matters when the screen is landscape, where it+ // becomes the pitch axis. Hold the last value if a frame omits it.+ if (Number.isFinite(e.gamma)) lastDevGamma = e.gamma;}const a = lastDevAlpha;- const b = lastDevBeta;+ // Portrait-equivalent pitch: in landscape the user's look-up/down rides gamma,+ // not beta, so fold the screen angle in before the baseline-delta math (task-02).+ const b = screenPitchDeg(lastDevBeta, lastDevGamma, currentScreenAngle());const compass = readCompassHeading(e);if (compass !== null) {lastCompassHeading = compass;@@ -1079,7 +1084,9 @@ async function setLocked(next) {// on the page-relative fallback path. The pitch baseline is used by both// paths; the yaw baseline only by the delta fallback.devOrientBaseAlpha = lastDevAlpha;- devOrientBaseBeta = lastDevBeta;+ // Same screen-corrected pitch source as the per-frame path, so the first+ // delta after locking is 0 regardless of how the device is held (task-02).+ devOrientBaseBeta = screenPitchDeg(lastDevBeta, lastDevGamma, currentScreenAngle());devOrientBaseCamYaw = cameraYaw;devOrientBaseCamPitch = cameraPitch;// iOS compass + a live GPS fix: snap the first locked frame to the true@@ -1388,6 +1395,147 @@ function discoveryOrigin() {};}+// ── H4 / L4 — Approximate placement (how a pin the user PLACES is stored) ─────+// Distinct from discovery precision (which governs the nearby READ): placement+// precision governs the coordinate we WRITE. 'precise' stores the agent exactly+// where chosen; 'approximate' stores a point fuzzed within PLACEMENT_FUZZ_RADIUS_M+// so the exact standing spot is never recorded. The first-placement consent sheet+// (maybeConfirmPlacement) sets it; the choice is remembered across sessions.+const PLACEMENT_KIND_KEY = 'irl_placement_kind';+const PLACEMENT_CONSENT_KEY = 'irl_placement_consented_v1';+const PLACEMENT_FUZZ_RADIUS_M = 30;++function getPlacementKind() {+ try { return localStorage.getItem(PLACEMENT_KIND_KEY) === 'approximate' ? 'approximate' : 'precise'; }+ catch { return 'precise'; }+}+function setPlacementKind(v) {+ try { localStorage.setItem(PLACEMENT_KIND_KEY, v === 'approximate' ? 'approximate' : 'precise'); } catch {}+}+function hasPlacementConsent() {+ try { return localStorage.getItem(PLACEMENT_CONSENT_KEY) === '1'; } catch { return false; }+}+function markPlacementConsented() {+ try { localStorage.setItem(PLACEMENT_CONSENT_KEY, '1'); } catch {}+}++// Offset a coordinate by a uniformly-distributed random point inside a disc of+// `radiusM` metres (not a square — a square biases the corners). sqrt(rand) gives a+// uniform areal distribution; the bearing is uniform. Returns a fresh {lat,lng} so a+// caller can fuzz once at commit and store the result, keeping the true spot local.+function fuzzCoord(lat, lng, radiusM) {+ const r = radiusM * Math.sqrt(Math.random());+ const theta = Math.random() * Math.PI * 2;+ const dNorth = r * Math.cos(theta);+ const dEast = r * Math.sin(theta);+ const mLat = 110540;+ const mLng = 111320 * Math.cos(lat * Math.PI / 180) || 1;+ return { lat: lat + dNorth / mLat, lng: lng + dEast / mLng };+}++// Apply the active placement kind to a coordinate at commit time. In approximate+// mode it returns the fuzzed point + the metadata the pin-create call sends+// (placement_kind + fuzz_radius_m); precise mode returns the coordinate untouched.+function applyPlacementKind(lat, lng) {+ if (getPlacementKind() !== 'approximate') {+ return { lat, lng, placementKind: 'precise', fuzzRadiusM: 0 };+ }+ const fuzzed = fuzzCoord(lat, lng, PLACEMENT_FUZZ_RADIUS_M);+ return { lat: fuzzed.lat, lng: fuzzed.lng, placementKind: 'approximate', fuzzRadiusM: PLACEMENT_FUZZ_RADIUS_M };+}++// H3 — Proof-of-presence. The nearby read is bound to a genuine fix: we mint a+// short-lived, server-signed token from our REAL geolocation and attach it+// (x-irl-fix) to every loadNearbyPins call, so the server only answers for where+// we actually are. Invisible to the user — they already granted location. We+// re-mint on a coarse cell change (~150 m of travel) or on a 401 fix_required.+let _fixToken = null;+let _fixCell = null; // the ~110 m cell key the current token was minted for+let _fixExpiresAt = 0; // performance.now()-relative ms when the cached token lapses+let _fixMintInflight = null;+// Re-mint a hair before the server clock would reject the token, so a poll or a pin+// create never races the boundary and eats a 401.+const FIX_EXPIRY_SKEW_MS = 8000;++// A coarse cell key for the origin we send to the read — 3 decimals ≈ 110 m, the+// granularity the server token anchors at. When this changes we re-mint.+function fixCellKey(origin) {+ if (!origin || !Number.isFinite(origin.lat) || !Number.isFinite(origin.lng)) return null;+ return `${origin.lat.toFixed(3)},${origin.lng.toFixed(3)}`;+}++// True when the cached token is still good for the current cell AND hasn't lapsed.+// A cell change (the user walked ~150 m) or an imminent expiry both force a re-mint.+function fixTokenFresh(cell) {+ return !!_fixToken && cell === _fixCell && Date.now() < _fixExpiresAt;+}++// Mint (or re-mint) a fix token for the current discovery origin. De-duped so a+// burst of GPS callbacks issues one request; cached until the cell changes OR the+// server-supplied expires_in lapses. On a dev/preview server with IRL_FIX_SECRET+// unset the read ignores the token, so a mint failure there is harmless — we simply+// poll without one.+async function ensureFixToken(force = false) {+ const origin = discoveryOrigin();+ const cell = fixCellKey(origin);+ if (!cell) return null;+ if (!force && fixTokenFresh(cell)) return _fixToken;+ if (_fixMintInflight) return _fixMintInflight;+ _fixMintInflight = (async () => {+ try {+ const r = await fetch('/api/irl/fix-token', {+ method: 'POST',+ credentials: 'include',+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ deviceToken: _deviceToken, lat: origin.lat, lng: origin.lng, accuracy: gpsState.accuracy }),+ });+ if (!r.ok) return null;+ // `expires_in` is the token TTL in seconds (the server's exp expressed as a+ // relative lifetime); cache the absolute lapse moment so a long-idle session+ // re-mints rather than re-using a stale token the server now rejects.+ const { token, expires_in } = await r.json();+ if (token) {+ _fixToken = token;+ _fixCell = cell;+ const ttlMs = Number.isFinite(expires_in) ? expires_in * 1000 : 180000;+ _fixExpiresAt = Date.now() + Math.max(0, ttlMs - FIX_EXPIRY_SKEW_MS);+ }+ return _fixToken;+ } catch {+ return null;+ } finally {+ _fixMintInflight = null;+ }+ })();+ return _fixMintInflight;+}++// Headers for a request that proves presence: device id + a guaranteed-fresh fix+// token. Awaits a mint when the cache is cold/expired so a pin create or nearby read+// is never sent without proof when one is obtainable. Falls back to device-only+// headers when no fix is available yet (dev/preview, or location off) so the call+// still goes out rather than dead-ending.+async function presenceHeaders(extra = {}) {+ let token = _fixToken;+ const cell = fixCellKey(discoveryOrigin());+ if (cell && !fixTokenFresh(cell)) token = await ensureFixToken();+ return deviceHeaders(token ? { 'x-irl-fix': token, ...extra } : { ...extra });+}++// The nearby read returned 401 fix_required (proof-of-presence enforced and our+// token is missing/expired/out-of-area). Re-mint from the current fix and let the+// next ~10 s poll cycle pick it up — or, if location is unavailable, surface the+// existing designed permission/no-fix state rather than a blank screen.+async function handleFixRequired(_resp) {+ const token = await ensureFixToken(true);+ if (!token) {+ // Couldn't mint — almost always because we don't have a usable fix. Flag the+ // badge so the user sees a retrying state instead of an empty world.+ _nearbyError = true;+ updateNearbyBadge();+ }+}+// Honour the OS "reduce motion" setting for the spawn/despawn transitions below —// scale in/out for everyone else, instant for users who asked for less animation.function prefersReducedMotion() {@@ -1427,6 +1575,11 @@ function onGPSPosition(pos) {// and the poll runs the whole session even if that socket never connects.if (!wasReady) startPinSync();+ // H3: keep a fresh proof-of-presence token for the nearby read. ensureFixToken+ // is a no-op unless our coarse cell changed, so this fires a mint on the first+ // fix and then only every ~150 m of travel — invisible, and cheap. Fire-and-forget.+ ensureFixToken();+// A lock was requested before the first fix — finish anchoring now that we// have real coordinates, rather than dropping the agent at a default origin.if (_pendingGpsLock && avatarLocked && arActive) {@@ -2665,9 +2818,11 @@ async function loadNearbyPins() {// debounce CLIENT-side (pinBandAction) so consumer GPS jitter can't pop it in and out.const _o = discoveryOrigin();try {+ // presenceHeaders awaits a mint when the cached token is cold or lapsed, so the+ // read is never sent with a stale token that the server would 401 on.const r = await fetch(`/api/irl/pins?lat=${_o.lat}&lng=${_o.lng}&radius=${NEARBY_READ_RADIUS}`,- { headers: deviceHeaders(_fixToken ? { 'x-irl-fix': _fixToken } : {}) },+ { headers: await presenceHeaders() },);if (r.status === 401) { return handleFixRequired(r); }if (!r.ok) { _nearbyError = true; updateNearbyBadge(); return; }@@ -4556,14 +4711,64 @@ function applyBand(pin, band) {}}-// ── Resize ────────────────────────────────────────────────────────────────-function resize() {- renderer.setSize(window.innerWidth, window.innerHeight, false);- camera.aspect = window.innerWidth / window.innerHeight;- camera.updateProjectionMatrix();+// ── Viewport / orientation change ───────────────────────────────────────────+// One funnel for resize, orientationchange, and screen.orientation's change event+// (feature-detected — iOS support varies). It re-applies the active perf tier's+// pixel ratio + render size, the new aspect, AND re-derives the camera FOV from+// the rear-camera sensor against the now-current viewport — so rotating+// portrait↔landscape holds the avatar's real-world scale instead of leaving it at+// the orientation AR opened in (task-02). iOS Safari's dynamic toolbar fires+// `resize` on every scroll frame, so the work is debounced to a single rAF and+// skipped entirely when the viewport dimensions did not actually change.+let _lastViewW = window.innerWidth;+let _lastViewH = window.innerHeight;+let _viewportRaf = 0;+function onViewportChanged() {+ if (_viewportRaf) return;+ _viewportRaf = requestAnimationFrame(() => {+ _viewportRaf = 0;+ const w = window.innerWidth, h = window.innerHeight;+ if (w === _lastViewW && h === _lastViewH) return; // toolbar jitter with no real change+ _lastViewW = w; _lastViewH = h;+ // setPixelRatio first so setSize allocates the drawing buffer at the right DPR.+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, budget.pixelRatio));+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ applyCameraFov(); // no-op when AR is off; re-derives + refreshes projection otherwise+ rebaselineGyroForScreenAngle();+ });+}+// `screen.orientation.angle` for the landscape gyro-frame correction. Falls back+// to the legacy `window.orientation` (older iOS) and finally 0 (assume portrait).+function currentScreenAngle() {+ const a = window.screen?.orientation?.angle;+ if (Number.isFinite(a)) return a;+ const legacy = window.orientation;+ if (Number.isFinite(legacy)) return ((legacy % 360) + 360) % 360;+ return 0;+}+// When the screen rotates mid-lock the pitch axis switches (beta↔gamma), so the+// relative integrator baselines — captured under the previous angle — no longer+// describe the current pose and the view would snap. Re-pin them to the live pose+// at the new angle so rotation is seamless (the absolute-yaw path is unaffected;+// it tracks the compass directly). No-op when not locked in AR.+let _lastGyroScreenAngle = currentScreenAngle();+function rebaselineGyroForScreenAngle() {+ const angle = currentScreenAngle();+ if (angle === _lastGyroScreenAngle) return;+ _lastGyroScreenAngle = angle;+ if (!avatarLocked || !arActive || devOrientBaseAlpha === null) return;+ devOrientBaseAlpha = lastDevAlpha;+ devOrientBaseBeta = screenPitchDeg(lastDevBeta, lastDevGamma, angle);+ devOrientBaseCamYaw = cameraYaw;+ devOrientBaseCamPitch = cameraPitch;+}+window.addEventListener('resize', onViewportChanged);+window.addEventListener('orientationchange', onViewportChanged);+if (window.screen?.orientation?.addEventListener) {+ window.screen.orientation.addEventListener('change', onViewportChanged);}-window.addEventListener('resize', resize);-window.addEventListener('orientationchange', resize);// ── Main loop ─────────────────────────────────────────────────────────────const clock = new Timer();diff --git a/src/irl/privacy-center.js b/src/irl/privacy-center.jsindex 5fdf13537..2f39618fc 100644--- a/src/irl/privacy-center.js+++ b/src/irl/privacy-center.js@@ -10,8 +10,46 @@const PRECISION_KEY = 'irl_discovery_precision'; // 'precise' | 'approximate'const DISCLOSED_KEY = 'irl_location_disclosed_v1';+const DEVICE_KEY = 'irl_device_token'; // shared with src/irl.js (H2 identity)const STYLE_ID = 'irlpc-styles';+// The anonymous device token is a BEARER credential (H2): presenting it reads a+// device's pin history + inbox. It rides the `x-irl-device` REQUEST HEADER — never+// a URL — so it can't leak through access logs, history, or a Referer header. The+// session cookie (credentials: 'include') authenticates a signed-in caller; both+// arms are accepted by api/irl/privacy.js, which scopes every query to the owner.+function deviceToken() {+ try { return localStorage.getItem(DEVICE_KEY) || ''; } catch { return ''; }+}++function privacyHeaders(extra = {}) {+ const tok = deviceToken();+ return tok ? { 'x-irl-device': tok, ...extra } : { ...extra };+}++// Talk to api/irl/privacy.js. Token in the header, body for mutations, never a+// query string. Throws a plain-language Error on a non-2xx so the UI renders a+// designed error state rather than a silent failure.+async function privacyApi(method, { query = '', body } = {}) {+ const init = { method, credentials: 'include', headers: privacyHeaders() };+ if (body !== undefined) {+ init.headers = privacyHeaders({ 'content-type': 'application/json' });+ init.body = JSON.stringify(body);+ }+ let resp;+ try {+ resp = await fetch(`/api/irl/privacy${query}`, init);+ } catch {+ throw new Error('Network error — check your connection and try again.');+ }+ let data = null;+ try { data = await resp.json(); } catch { /* empty/non-JSON body */ }+ if (!resp.ok) {+ throw new Error(data?.error || `Request failed (${resp.status}).`);+ }+ return data;+}+// ── Discovery precision (single source of truth) ────────────────────────────export function getDiscoveryPrecision() {try { return localStorage.getItem(PRECISION_KEY) === 'approximate' ? 'approximate' : 'precise'; }@@ -87,6 +125,61 @@ function ensureStyles() {.irlpc-learn .ar{font-size:14px}/* First-run disclosure reuses the sheet shell with a tighter body */.irlpc-discl .irlpc-sec{border-top:none}+/* ── My data panel ──────────────────────────────────────────────────────── */+.irlpc-stats{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:4px}+.irlpc-stat{background:#11151f;border:1px solid #232838;border-radius:11px;padding:11px 12px}+.irlpc-stat .n{font:700 19px/1 system-ui,sans-serif;color:#eef1f7}+.irlpc-stat .l{font:500 11px/1.2 system-ui,sans-serif;color:#8b93a7;margin-top:4px}+.irlpc-stored{list-style:none;margin:10px 0 0;padding:0}+.irlpc-stored li{position:relative;padding:0 0 6px 16px;font:400 12px/1.45 system-ui,sans-serif;color:#aeb6c8}+.irlpc-stored li::before{content:'•';position:absolute;left:3px;color:#4f7cff}+.irlpc-pin{display:flex;align-items:center;gap:10px;padding:10px 0;border-top:1px solid #161b27}+.irlpc-pin:first-child{border-top:none}+.irlpc-pin .pmeta{flex:1;min-width:0}+.irlpc-pin .pname{font:600 13px/1.3 system-ui,sans-serif;color:#eef1f7;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.irlpc-pin .psub{font:400 11px/1.3 system-ui,sans-serif;color:#7b8398;margin-top:2px}+.irlpc-pin.hidden .pname{color:#8b93a7}+.irlpc-tag{display:inline-block;margin-left:6px;font:600 9.5px/1.4 system-ui,sans-serif;letter-spacing:.04em;+ text-transform:uppercase;color:#cda13a;background:#2a2410;border:1px solid #4a3f17;border-radius:5px;padding:1px 5px;vertical-align:middle}+.irlpc-pinbtn{appearance:none;border:1px solid #2a3042;background:#161b27;color:#aeb6c8;border-radius:8px;cursor:pointer;+ font:600 11.5px system-ui,sans-serif;padding:7px 10px;transition:background .15s,color .15s,border-color .15s;flex-shrink:0}+.irlpc-pinbtn:hover,.irlpc-pinbtn:focus-visible{background:#1f2636;color:#eef1f7;outline:none;border-color:#3a4258}+.irlpc-pinbtn:focus-visible{outline:2px solid #4f7cff;outline-offset:2px}+.irlpc-pinbtn.danger{color:#ff8a8a;border-color:#4a2630}+.irlpc-pinbtn.danger:hover,.irlpc-pinbtn.danger:focus-visible{background:#2a1620;color:#ffb3b3}+.irlpc-actbtn{display:flex;align-items:center;justify-content:center;gap:7px;width:100%;appearance:none;cursor:pointer;+ border-radius:11px;padding:12px;font:600 13.5px system-ui,sans-serif;transition:background .15s,border-color .15s;margin-top:8px}+.irlpc-actbtn.ghost{background:#11151f;border:1px solid #232838;color:#eef1f7}+.irlpc-actbtn.ghost:hover{background:#1a2032}+.irlpc-actbtn.danger{background:#1c1014;border:1px solid #4a2630;color:#ff9a9a}+.irlpc-actbtn.danger:hover{background:#2a1620;border-color:#6a3340;color:#ffb3b3}+.irlpc-actbtn:disabled{opacity:.5;cursor:not-allowed}+.irlpc-empty{text-align:center;padding:22px 12px;color:#8b93a7;font:400 13px/1.5 system-ui,sans-serif}+.irlpc-empty .e-ic{font-size:26px;display:block;margin-bottom:8px}+.irlpc-skel{height:64px;border-radius:11px;background:linear-gradient(90deg,#11151f 25%,#171c28 50%,#11151f 75%);+ background-size:200% 100%;animation:irlpc-shimmer 1.3s infinite;margin-bottom:8px}+@keyframes irlpc-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}+.irlpc-err{background:#1c1014;border:1px solid #4a2630;border-radius:11px;padding:12px 14px;color:#ffb3b3;+ font:500 12.5px/1.45 system-ui,sans-serif;display:flex;flex-direction:column;gap:9px}+.irlpc-err button{align-self:flex-start;appearance:none;background:#2a1620;border:1px solid #6a3340;color:#ffd1d1;+ border-radius:8px;padding:7px 12px;font:600 12px system-ui,sans-serif;cursor:pointer}+.irlpc-toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%) translateY(8px);z-index:10003;opacity:0;+ background:#11331c;border:1px solid #1f6b3a;color:#c8ffd9;border-radius:11px;padding:11px 16px;+ font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);transition:opacity .2s,transform .2s;pointer-events:none}+.irlpc-toast.show{opacity:1;transform:translateX(-50%) translateY(0)}+.irlpc-toast.err{background:#331114;border-color:#6b1f24;color:#ffd1d1}+/* Typed-confirm modal */+.irlpc-confirm h4{margin:0 0 8px;font:700 15px/1.3 system-ui,sans-serif;color:#eef1f7;text-transform:none;letter-spacing:0}+.irlpc-confirm p{margin:0 0 12px;font:400 13px/1.5 system-ui,sans-serif;color:#aeb6c8}+.irlpc-confirm code{background:#11151f;border:1px solid #232838;border-radius:5px;padding:1px 6px;color:#ffd1d1;font:600 12px ui-monospace,monospace}+.irlpc-confirm input{width:100%;box-sizing:border-box;background:#0a0d14;border:1px solid #2a3042;border-radius:9px;+ padding:11px 12px;color:#eef1f7;font:500 14px system-ui,sans-serif;margin-bottom:12px}+.irlpc-confirm input:focus{outline:2px solid #ff8a8a;outline-offset:1px;border-color:#ff8a8a}+.irlpc-confirm .row{display:flex;gap:9px}+.irlpc-confirm .row button{flex:1;appearance:none;border-radius:10px;padding:12px;font:600 13.5px system-ui,sans-serif;cursor:pointer}+.irlpc-confirm .cancel{background:#161b27;border:1px solid #232838;color:#eef1f7}+.irlpc-confirm .go{background:#7a1f2a;border:1px solid #a13340;color:#fff}+.irlpc-confirm .go:disabled{opacity:.45;cursor:not-allowed}`;document.head.appendChild(el);}@@ -209,6 +302,298 @@ export function openPrivacyCenter({ getGhost, setGhost, onManagePins } = {}) {});}+// ── Toast (success / error confirmation) ────────────────────────────────────+function toast(msg, kind = 'ok') {+ if (typeof document === 'undefined') return;+ const t = document.createElement('div');+ t.className = `irlpc-toast ${kind === 'err' ? 'err' : ''}`.trim();+ t.setAttribute('role', 'status');+ t.textContent = msg;+ document.body.appendChild(t);+ requestAnimationFrame(() => t.classList.add('show'));+ setTimeout(() => {+ t.classList.remove('show');+ setTimeout(() => t.remove(), 240);+ }, 2600);+}++// ── Typed-confirm modal for the two irreversible actions ────────────────────+// The user must type the exact word to arm the destructive button — no accidental+// "remove everything." Resolves true only on a confirmed go.+function typedConfirm({ title, body, word, goLabel }) {+ return new Promise((resolve) => {+ let done = false;+ const finish = (ok) => { if (done) return; done = true; close(); resolve(ok); };+ const close = modal((sheet) => {+ sheet.classList.add('irlpc-confirm');+ sheet.setAttribute('aria-label', title);+ sheet.innerHTML = `+ <div class="irlpc-sec">+ <h4>${esc(title)}</h4>+ <p>${body}</p>+ <input type="text" autocomplete="off" autocapitalize="none" spellcheck="false"+ aria-label="Type ${esc(word)} to confirm" placeholder="Type ${esc(word)} to confirm" data-field />+ <div class="row">+ <button class="cancel" type="button" data-cancel>Cancel</button>+ <button class="go" type="button" data-go disabled>${esc(goLabel)}</button>+ </div>+ </div>`;+ const field = sheet.querySelector('[data-field]');+ const go = sheet.querySelector('[data-go]');+ field.addEventListener('input', () => {+ go.disabled = field.value.trim().toLowerCase() !== word.toLowerCase();+ });+ field.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && !go.disabled) finish(true);+ });+ go.addEventListener('click', () => finish(true));+ sheet.querySelector('[data-cancel]').addEventListener('click', () => finish(false));+ setTimeout(() => field.focus(), 60);+ }, { onClose: () => finish(false) });+ });+}++// ── "Privacy & my data" — the H5 control surface ────────────────────────────+// Renders the caller's real data summary (api/irl/privacy GET), a per-pin+// Unpublish/Republish + Delete, Download, and the two destructive actions behind+// a typed confirm. Every state — loading, empty, error, populated — is designed.+export function openMyDataPanel({ onChanged } = {}) {+ modal((sheet, close) => {+ sheet.setAttribute('aria-label', 'Privacy and my data');+ const head = `+ <div class="irlpc-head">+ <div class="irlpc-title">Privacy & my data</div>+ <button class="irlpc-x" type="button" data-close aria-label="Close">×</button>+ </div>`;++ const renderLoading = () => {+ sheet.innerHTML = `${head}+ <div class="irlpc-sec"><div class="irlpc-skel"></div><div class="irlpc-skel"></div><div class="irlpc-skel"></div></div>`;+ sheet.querySelector('[data-close]')?.addEventListener('click', close);+ };++ const renderError = (message) => {+ sheet.innerHTML = `${head}+ <div class="irlpc-sec">+ <div class="irlpc-err">+ <span>${esc(message)}</span>+ <button type="button" data-retry>Try again</button>+ </div>+ </div>`;+ sheet.querySelector('[data-close]')?.addEventListener('click', close);+ sheet.querySelector('[data-retry]')?.addEventListener('click', load);+ };++ const fmtDate = (iso) => {+ if (!iso) return '';+ try { return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }); }+ catch { return ''; }+ };++ async function load() {+ renderLoading();+ let data;+ try {+ data = await privacyApi('GET');+ } catch (e) {+ renderError(e.message || 'Could not load your data.');+ return;+ }+ renderSummary(data.summary || {});+ }++ function renderSummary(s) {+ const pins = s.pins || {};+ const ix = s.interactions || {};+ const ret = s.retention || {};+ const stored = Array.isArray(s.stored) ? s.stored : [];+ const totalPins = pins.total || 0;++ if (totalPins === 0 && (ix.onYourPins || 0) === 0 && (ix.youLeftElsewhere || 0) === 0) {+ sheet.innerHTML = `${head}+ <div class="irlpc-sec">+ <div class="irlpc-empty">+ <span class="e-ic">🫧</span>+ We hold no location data for this ${s.account === 'signed-in' ? 'account' : 'device'}.+ Place an agent in /irl and it’ll show up here — yours to manage or remove anytime.+ </div>+ </div>+ <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Done</button></div>`;+ sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));+ return;+ }++ const expiryNote = ret.nextPinExpiry+ ? `Your next anonymous pin expires ${fmtDate(ret.nextPinExpiry)}.`+ : (pins.permanent ? 'Your pins are permanent until you remove them.' : '');++ sheet.innerHTML = `${head}+ <div class="irlpc-sec">+ <h4>What we hold</h4>+ <div class="irlpc-stats">+ <div class="irlpc-stat"><div class="n">${totalPins}</div><div class="l">placed agent${totalPins === 1 ? '' : 's'}${pins.unpublished ? ` · ${pins.unpublished} hidden` : ''}</div></div>+ <div class="irlpc-stat"><div class="n">${ix.onYourPins || 0}</div><div class="l">encounters on your agents</div></div>+ <div class="irlpc-stat"><div class="n">${ix.youLeftElsewhere || 0}</div><div class="l">taps you left elsewhere</div></div>+ <div class="irlpc-stat"><div class="n">${pins.permanent || 0}</div><div class="l">permanent · ${pins.expiring || 0} auto-expiring</div></div>+ </div>+ ${expiryNote ? `<div class="irlpc-note">${esc(expiryNote)} Encounters auto-delete after ${ret.interactionsExpireInDays || 180} days.</div>` : ''}+ <ul class="irlpc-stored">${stored.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>+ </div>+ <div class="irlpc-sec" data-pins-sec>+ <h4>Your placed agents</h4>+ <div data-pins><div class="irlpc-skel"></div></div>+ </div>+ <div class="irlpc-sec">+ <h4>Export & erase</h4>+ <button class="irlpc-actbtn ghost" type="button" data-export>⬇ Download my data (JSON)</button>+ <button class="irlpc-actbtn danger" type="button" data-del-all>Remove all my pins</button>+ <button class="irlpc-actbtn danger" type="button" data-forget>Forget this device</button>+ <div class="irlpc-note">“Forget this device” erases every pin and every tap tied to this device, everywhere — instantly and permanently.</div>+ </div>+ <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Done</button></div>`;++ sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));+ loadPins();++ sheet.querySelector('[data-export]')?.addEventListener('click', onExport);+ sheet.querySelector('[data-del-all]')?.addEventListener('click', () => onDestructive('all'));+ sheet.querySelector('[data-forget]')?.addEventListener('click', () => onDestructive('device'));+ }++ async function loadPins() {+ const host = sheet.querySelector('[data-pins]');+ if (!host) return;+ let data;+ try {+ data = await privacyApi('GET', { query: '?export=1' });+ } catch (e) {+ host.innerHTML = `<div class="irlpc-err"><span>${esc(e.message || 'Could not load your pins.')}</span></div>`;+ return;+ }+ const pins = Array.isArray(data?.pins) ? data.pins : [];+ if (!pins.length) {+ host.innerHTML = `<div class="irlpc-empty">No placed agents on this ${data.account === 'signed-in' ? 'account' : 'device'} yet.</div>`;+ return;+ }+ host.innerHTML = pins.map((p) => renderPinRow(p)).join('');+ host.querySelectorAll('[data-pin]').forEach((rowEl) => wirePinRow(rowEl));+ }++ function renderPinRow(p) {+ const hidden = !!p.hidden_at;+ const name = p.avatar_name || p.caption || 'Placed agent';+ const sub = fmtDate(p.placed_at) + (p.expires_at ? ` · expires ${fmtDate(p.expires_at)}` : ' · permanent');+ return `+ <div class="irlpc-pin ${hidden ? 'hidden' : ''}" data-pin="${esc(p.id)}" data-hidden="${hidden}">+ <div class="pmeta">+ <div class="pname">${esc(name)}${hidden ? '<span class="irlpc-tag">hidden</span>' : ''}</div>+ <div class="psub">${esc(sub)}</div>+ </div>+ <button class="irlpc-pinbtn" type="button" data-toggle>${hidden ? 'Republish' : 'Unpublish'}</button>+ <button class="irlpc-pinbtn danger" type="button" data-del>Delete</button>+ </div>`;+ }++ function wirePinRow(rowEl) {+ const id = rowEl.getAttribute('data-pin');+ const toggleBtn = rowEl.querySelector('[data-toggle]');+ const delBtn = rowEl.querySelector('[data-del]');++ toggleBtn?.addEventListener('click', async () => {+ const hidden = rowEl.getAttribute('data-hidden') === 'true';+ const action = hidden ? 'republish' : 'unpublish';+ toggleBtn.disabled = true; toggleBtn.textContent = '…';+ try {+ const r = await privacyApi('PATCH', { body: { pinId: id, action } });+ const nowHidden = !!r?.hidden;+ rowEl.setAttribute('data-hidden', String(nowHidden));+ rowEl.classList.toggle('hidden', nowHidden);+ toggleBtn.textContent = nowHidden ? 'Republish' : 'Unpublish';+ const nameEl = rowEl.querySelector('.pname');+ const tag = nameEl.querySelector('.irlpc-tag');+ if (nowHidden && !tag) nameEl.insertAdjacentHTML('beforeend', '<span class="irlpc-tag">hidden</span>');+ if (!nowHidden && tag) tag.remove();+ toast(nowHidden ? 'Pin hidden from everyone' : 'Pin is visible again');+ onChanged?.();+ } catch (e) {+ toast(e.message || 'Could not update the pin', 'err');+ toggleBtn.textContent = hidden ? 'Republish' : 'Unpublish';+ } finally {+ toggleBtn.disabled = false;+ }+ });++ delBtn?.addEventListener('click', async () => {+ delBtn.disabled = true; toggleBtn && (toggleBtn.disabled = true);+ try {+ const r = await privacyApi('DELETE', { body: { scope: 'pin', pinId: id } });+ rowEl.style.transition = 'opacity .2s, height .2s';+ rowEl.style.opacity = '0';+ setTimeout(() => {+ rowEl.remove();+ const host = sheet.querySelector('[data-pins]');+ if (host && !host.querySelector('[data-pin]')) {+ host.innerHTML = '<div class="irlpc-empty">No placed agents left on this device.</div>';+ }+ }, 200);+ toast(`Deleted${r?.deletedInteractions ? ` (and ${r.deletedInteractions} encounter${r.deletedInteractions === 1 ? '' : 's'})` : ''}`);+ onChanged?.();+ } catch (e) {+ toast(e.message || 'Could not delete the pin', 'err');+ delBtn.disabled = false; toggleBtn && (toggleBtn.disabled = false);+ }+ });+ }++ async function onExport() {+ const btn = sheet.querySelector('[data-export]');+ if (btn) { btn.disabled = true; }+ try {+ const data = await privacyApi('GET', { query: '?export=1' });+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'irl-my-data.json';+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+ toast('Your data is downloading');+ } catch (e) {+ toast(e.message || 'Export failed', 'err');+ } finally {+ if (btn) btn.disabled = false;+ }+ }++ async function onDestructive(scope) {+ const isDevice = scope === 'device';+ const ok = await typedConfirm({+ title: isDevice ? 'Forget this device?' : 'Remove all your pins?',+ body: isDevice+ ? 'This permanently deletes every agent you placed and every tap or message this device left anywhere. It cannot be undone.'+ : 'This permanently deletes every agent you placed and the encounters on them. It cannot be undone.',+ word: isDevice ? 'forget' : 'delete',+ goLabel: isDevice ? 'Forget device' : 'Remove all',+ });+ if (!ok) return;+ try {+ const r = await privacyApi('DELETE', { body: { scope } });+ const n = r?.deletedPins || 0;+ const ic = r?.deletedInteractions || 0;+ toast(`Removed ${n} pin${n === 1 ? '' : 's'}${ic ? ` and ${ic} encounter${ic === 1 ? '' : 's'}` : ''}`);+ onChanged?.();+ load(); // refresh — the summary should now read empty+ } catch (e) {+ toast(e.message || 'Could not complete that', 'err');+ }+ }++ load();+ });+}+// ── First-run disclosure (shown once, the first time location is granted) ────export function maybeShowFirstRunDisclosure() {let already = false;diff --git a/src/mirror/avatar-stage.js b/src/mirror/avatar-stage.jsnew file mode 100644index 000000000..a6956dbe3--- /dev/null+++ b/src/mirror/avatar-stage.js@@ -0,0 +1,562 @@+/**+ * AvatarStage — the cinematic 3D render surface for /mirror ("Become your agent").+ *+ * Loads a GLB avatar, lights it like a portrait studio, and drives its face ++ * head from the FaceFrame stream produced by FaceTracker (MediaPipe). The+ * mapping is name-for-name: MediaPipe FaceLandmarker emits ARKit blendshape+ * names (jawOpen, eyeBlinkLeft, mouthSmileLeft, browInnerUp, eyeLookInLeft …)+ * and the avatars we ship carry morph targets with those exact names, so a+ * smile becomes a smile with no guesswork. A small alias table extends support+ * to rigs that only carry the combined morphs (eyesClosed / mouthSmile /+ * mouthOpen) so user-supplied avatars still emote.+ *+ * Head pose (pitch/yaw/roll in radians) is split across the Neck and Head bones+ * for a natural turn, damped and clamped so the avatar never snaps or breaks+ * its neck. When no face is present the avatar stays alive: slow breathing,+ * gentle head sway, and the occasional blink.+ *+ * The class owns nothing but its <canvas> and the WebGL context. It exposes a+ * single applyFace(frame) entry point, plus background / mirror / head-tracking+ * controls and snapshot access for the recorder. No DOM scaffolding, no CSS.+ *+ * @module mirror/avatar-stage+ */++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';++// Bone names seen across the riggers that target three.ws (ReadyPlayerMe,+// Avaturn, Mixamo, VRoid, Rigify). Matched case-insensitively.+const HEAD_BONE_NAMES = [+ 'head', 'mixamorig:head', 'mixamorighead', 'cc_base_head', 'bip01_head',+ 'j_bip_c_head', 'head_01', 'headbone', 'def-spine.006', 'def-head', 'org-head',+];+const NECK_BONE_NAMES = [+ 'neck', 'mixamorig:neck', 'mixamorigneck', 'cc_base_neckTwist01', 'cc_base_neck',+ 'bip01_neck', 'j_bip_c_neck', 'neck_01', 'neckbone', 'def-spine.004', 'org-neck',+];+const SPINE_BONE_NAMES = [+ 'spine2', 'spine1', 'spine', 'mixamorig:spine2', 'mixamorigspine2',+ 'cc_base_spine02', 'j_bip_c_spine', 'def-spine.003', 'chest', 'upperchest',+];++// Avatars that only carry combined morphs still emote: feed the granular ARKit+// channel into the combined target. left/right pairs average so a one-sided+// smile reads correctly. Keys + values are lower-cased.+const MORPH_ALIASES = {+ eyeblinkleft: ['eyesclosed', 'blink', 'blink_left', 'eyeblink_l'],+ eyeblinkright: ['eyesclosed', 'blink', 'blink_right', 'eyeblink_r'],+ mouthsmileleft: ['mouthsmile', 'smile'],+ mouthsmileright: ['mouthsmile', 'smile'],+ jawopen: ['mouthopen', 'mouth_open', 'aa', 'viseme_aa', 'a'],+ mouthfunnel: ['mouth_o', 'viseme_o', 'o'],+ mouthpucker: ['viseme_u', 'u'],+ eyelookupleft: ['eyeslookup'],+ eyelookupright: ['eyeslookup'],+ eyelookdownleft: ['eyeslookdown'],+ eyelookdownright: ['eyeslookdown'],+};++// Head rotation clamps (radians). Keeps motion expressive but anatomical.+const YAW_LIMIT = 0.62;+const PITCH_LIMIT = 0.5;+const ROLL_LIMIT = 0.42;++export class AvatarStage {+ /**+ * @param {HTMLCanvasElement} canvas+ * @param {object} [opts]+ * @param {number} [opts.expressiveness=1.15] global gain on blendshape weights+ * @param {number} [opts.headGain=1.0] global gain on head rotation+ */+ constructor(canvas, opts = {}) {+ this.canvas = canvas;+ this.expressiveness = opts.expressiveness ?? 1.15;+ this.headGain = opts.headGain ?? 1.0;++ this._mirror = true;+ this._headTracking = true;+ this._faceActive = false;+ this._lastFaceTs = 0;+ this._disposed = false;+ this._running = false;++ // Smoothed state.+ this._morphState = new Map(); // morph key -> current weight+ this._headTarget = { pitch: 0, yaw: 0, roll: 0 };+ this._headCurrent = { pitch: 0, yaw: 0, roll: 0 };++ // Synthetic idle blink scheduling.+ this._nextBlink = 1.5;+ this._blinkPhase = -1; // -1 idle, else 0..1 progress+ this._clock = new THREE.Clock();++ this._model = null;+ this._morphTargets = new Map(); // lower morph name -> [{mesh, index}]+ this._headBone = null;+ this._neckBone = null;+ this._spineBone = null;+ this._restRot = new WeakMap(); // bone -> THREE.Euler base rotation++ this._scratchEuler = new THREE.Euler();+ this._scratchQuat = new THREE.Quaternion();++ this._initRenderer();+ this._initScene();+ this._onResize = this._onResize.bind(this);+ window.addEventListener('resize', this._onResize);+ this._resizeObserver = new ResizeObserver(this._onResize);+ this._resizeObserver.observe(canvas.parentElement || canvas);+ }++ _initRenderer() {+ const renderer = new THREE.WebGLRenderer({+ canvas: this.canvas,+ antialias: true,+ alpha: true,+ preserveDrawingBuffer: true, // needed for PNG snapshots+ 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;+ this.renderer = renderer;+ }++ _initScene() {+ const scene = new THREE.Scene();+ this.scene = scene;++ const pmrem = new THREE.PMREMGenerator(this.renderer);+ this._envRT = pmrem.fromScene(new RoomEnvironment(), 0.04);+ scene.environment = this._envRT.texture;+ pmrem.dispose();++ const camera = new THREE.PerspectiveCamera(28, 1, 0.1, 100);+ camera.position.set(0, 1.55, 1.35);+ this.camera = camera;++ // Portrait three-point lighting.+ const key = new THREE.DirectionalLight(0xfff4e6, 2.1);+ key.position.set(1.4, 2.4, 2.0);+ key.castShadow = true;+ key.shadow.mapSize.set(1024, 1024);+ key.shadow.camera.near = 0.5;+ key.shadow.camera.far = 8;+ key.shadow.bias = -0.0004;+ scene.add(key);++ const fill = new THREE.DirectionalLight(0xbfd4ff, 0.7);+ fill.position.set(-2.0, 1.4, 1.2);+ scene.add(fill);++ const rim = new THREE.DirectionalLight(0xffffff, 1.6);+ rim.position.set(-0.8, 2.0, -2.4);+ scene.add(rim);++ scene.add(new THREE.AmbientLight(0xffffff, 0.25));++ // Soft contact shadow catcher.+ const shadowMat = new THREE.ShadowMaterial({ opacity: 0.25 });+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(12, 12), shadowMat);+ ground.rotation.x = -Math.PI / 2;+ ground.position.y = 0;+ ground.receiveShadow = true;+ scene.add(ground);+ this._ground = ground;++ this._buildLoaders();+ this.setBackground('studio');+ }++ _buildLoaders() {+ const draco = new DRACOLoader().setDecoderPath('/three/draco/gltf/');+ const ktx2 = new KTX2Loader()+ .setTranscoderPath('/three/basis/')+ .detectSupport(this.renderer);+ const loader = new GLTFLoader()+ .setDRACOLoader(draco)+ .setKTX2Loader(ktx2)+ .setMeshoptDecoder(MeshoptDecoder);+ this._loader = loader;+ this._draco = draco;+ this._ktx2 = ktx2;+ }++ /**+ * Load (or hot-swap) a GLB avatar by URL.+ * @param {string} url+ * @returns {Promise<{morphCount:number, hasHead:boolean}>}+ */+ async loadAvatar(url) {+ const gltf = await this._loader.loadAsync(url);+ this._teardownModel();++ const model = gltf.scene || gltf.scenes?.[0];+ if (!model) throw new Error('GLB contains no scene');+ model.traverse((o) => {+ if (o.isMesh || o.isSkinnedMesh) {+ o.castShadow = true;+ o.frustumCulled = false; // morphed heads can escape their static bounds+ if (o.material) o.material.envMapIntensity = 1.0;+ }+ });++ this._scanRig(model);+ this.scene.add(model);+ this._model = model;+ this._frameOnFace(model);+ return {+ morphCount: this._morphTargets.size,+ hasHead: !!this._headBone,+ };+ }++ _scanRig(root) {+ this._morphTargets = new Map();+ this._headBone = this._neckBone = this._spineBone = null;+ this._morphState.clear();++ const lc = (s) => String(s).toLowerCase();+ root.traverse((node) => {+ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {+ for (const [name, idx] of Object.entries(node.morphTargetDictionary)) {+ const key = lc(name);+ if (!this._morphTargets.has(key)) this._morphTargets.set(key, []);+ this._morphTargets.get(key).push({ mesh: node, index: idx });+ }+ }+ if (node.isBone || node.type === 'Bone') {+ const name = lc(node.name);+ if (!this._headBone && HEAD_BONE_NAMES.includes(name)) this._headBone = node;+ if (!this._neckBone && NECK_BONE_NAMES.includes(name)) this._neckBone = node;+ if (!this._spineBone && SPINE_BONE_NAMES.includes(name)) this._spineBone = node;+ }+ });++ for (const bone of [this._headBone, this._neckBone, this._spineBone]) {+ if (bone) this._restRot.set(bone, bone.rotation.clone());+ }+ }++ // Frame the camera on the avatar's head / upper body.+ _frameOnFace(model) {+ const box = new THREE.Box3().setFromObject(model);+ const size = new THREE.Vector3();+ const center = new THREE.Vector3();+ box.getSize(size);+ box.getCenter(center);++ // Drop the model so its feet sit on y=0 for the shadow catcher.+ model.position.y -= box.min.y;+ box.translate(new THREE.Vector3(0, -box.min.y, 0));++ // Aim at the head: use the head bone world position when available,+ // else estimate near the top of the bounding box.+ let headY;+ if (this._headBone) {+ const wp = new THREE.Vector3();+ this._headBone.getWorldPosition(wp);+ headY = wp.y + size.y * 0.04;+ } else {+ headY = box.min.y + size.y * 0.92;+ }+ const target = new THREE.Vector3(0, headY, 0);++ // Distance scales with head size so tall and short rigs both frame well.+ const dist = THREE.MathUtils.clamp(size.y * 0.55, 0.55, 1.6);+ this.camera.position.set(0, headY + size.y * 0.02, dist);+ this.camera.near = 0.05;+ this.camera.far = 100;+ this.camera.updateProjectionMatrix();+ this.camera.lookAt(target);+ this._cameraTarget = target;++ if (!this._controls) {+ const controls = new OrbitControls(this.camera, this.canvas);+ controls.enablePan = false;+ controls.enableZoom = true;+ controls.minDistance = 0.4;+ controls.maxDistance = 3.2;+ controls.minPolarAngle = Math.PI * 0.28;+ controls.maxPolarAngle = Math.PI * 0.62;+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;+ controls.rotateSpeed = 0.5;+ this._controls = controls;+ }+ this._controls.target.copy(target);+ this._controls.update();+ }++ _teardownModel() {+ if (!this._model) return;+ this.scene.remove(this._model);+ this._model.traverse((o) => {+ if (o.geometry) o.geometry.dispose();+ if (o.material) {+ const mats = Array.isArray(o.material) ? o.material : [o.material];+ for (const m of mats) {+ for (const k of Object.keys(m)) {+ if (m[k] && m[k].isTexture) m[k].dispose();+ }+ m.dispose();+ }+ }+ });+ this._model = null;+ }++ /**+ * Apply a FaceFrame from the tracker. Safe to call before a model loads.+ * @param {{present:boolean, blendshapes:Object, head:?{pitch:number,yaw:number,roll:number}, ts:number}} frame+ */+ applyFace(frame) {+ if (!frame) return;+ this._faceActive = !!frame.present;+ if (frame.present) this._lastFaceTs = performance.now();++ if (frame.present && frame.blendshapes) {+ const mirror = this._mirror;+ for (const [rawName, rawVal] of Object.entries(frame.blendshapes)) {+ let name = rawName;+ let val = rawVal;+ // In mirror mode swap left/right channels so the avatar mirrors+ // the user like a reflection rather than aping them.+ if (mirror) name = this._swapSide(name);+ this._setMorphTarget(name, val * this.expressiveness);+ }+ }++ if (frame.present && frame.head && this._headTracking) {+ let { pitch, yaw, roll } = frame.head;+ if (this._mirror) { yaw = -yaw; roll = -roll; }+ this._headTarget.pitch = THREE.MathUtils.clamp(pitch * this.headGain, -PITCH_LIMIT, PITCH_LIMIT);+ this._headTarget.yaw = THREE.MathUtils.clamp(yaw * this.headGain, -YAW_LIMIT, YAW_LIMIT);+ this._headTarget.roll = THREE.MathUtils.clamp(roll * this.headGain, -ROLL_LIMIT, ROLL_LIMIT);+ }+ }++ _swapSide(name) {+ if (name.endsWith('Left')) return name.slice(0, -4) + 'Right';+ if (name.endsWith('Right')) return name.slice(0, -5) + 'Left';+ return name;+ }++ // Record a desired weight for a blendshape against every morph it maps to+ // (direct name match + aliases). Actual easing happens in the render loop.+ _setMorphTarget(arkitName, weight) {+ const key = arkitName.toLowerCase();+ const w = Math.max(0, Math.min(1, weight));+ this._stageMorph(key, w);+ const aliases = MORPH_ALIASES[key];+ if (aliases) for (const a of aliases) this._stageMorph(a, w, true);+ }++ _stageMorph(key, w, isAlias = false) {+ if (!this._morphTargets.has(key)) return;+ // For aliases, take the max so two granular channels feeding one combined+ // morph don't cancel each other between calls within a frame.+ const prev = this._pendingMorph.get(key);+ if (isAlias && prev != null) this._pendingMorph.set(key, Math.max(prev, w));+ else this._pendingMorph.set(key, w);+ }++ setMirror(on) { this._mirror = !!on; }+ setHeadTracking(on) {+ this._headTracking = !!on;+ if (!on) { this._headTarget.pitch = this._headTarget.yaw = this._headTarget.roll = 0; }+ }+ setExpressiveness(v) { this.expressiveness = Math.max(0, Math.min(2.5, v)); }++ /**+ * Background presets. 'transparent' lets a CSS layer show through (and+ * records with alpha); the others paint an in-scene backdrop so snapshots+ * and recordings include the background.+ * @param {'studio'|'noir'|'aurora'|'transparent'} preset+ */+ setBackground(preset) {+ this._bgPreset = preset;+ if (preset === 'transparent') {+ this.scene.background = null;+ this.renderer.setClearColor(0x000000, 0);+ return;+ }+ const grad = this._gradientTexture(preset);+ this.scene.background = grad;+ this.renderer.setClearColor(0x000000, 1);+ }++ _gradientTexture(preset) {+ const stops = {+ studio: ['#1a1d27', '#0b0c10', '#050507'],+ noir: ['#15151a', '#0a0a0c', '#000000'],+ aurora: ['#16313a', '#101a2c', '#08070f'],+ }[preset] || ['#1a1d27', '#0b0c10', '#050507'];+ const c = document.createElement('canvas');+ c.width = 16; c.height = 256;+ const ctx = c.getContext('2d');+ const g = ctx.createLinearGradient(0, 0, 0, 256);+ g.addColorStop(0, stops[0]);+ g.addColorStop(0.55, stops[1]);+ g.addColorStop(1, stops[2]);+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 16, 256);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ return tex;+ }++ start() {+ if (this._running || this._disposed) return;+ this._running = true;+ this._pendingMorph = this._pendingMorph || new Map();+ this._clock.start();+ const tick = () => {+ if (!this._running) return;+ this._raf = requestAnimationFrame(tick);+ this._update(this._clock.getDelta());+ this._controls?.update();+ this.renderer.render(this.scene, this.camera);+ };+ this._raf = requestAnimationFrame(tick);+ }++ stop() {+ this._running = false;+ if (this._raf) cancelAnimationFrame(this._raf);+ this._raf = null;+ }++ _update(dt) {+ dt = Math.min(dt, 0.05);+ const now = performance.now();+ const faceFresh = this._faceActive && now - this._lastFaceTs < 400;++ this._pendingMorph = this._pendingMorph || new Map();++ // When the face is lost, relax all driven morphs toward 0.+ if (!faceFresh) this._pendingMorph.clear();++ // Idle life: breathing + sway + synthetic blink when untracked.+ if (!faceFresh) this._driveIdle(dt);++ // Ease every known morph toward its pending (or zero) target.+ const ease = 1 - Math.pow(0.001, dt); // ~frame-rate independent snappy ease+ for (const [key, bindings] of this._morphTargets) {+ const target = this._pendingMorph.get(key) ?? 0;+ const cur = this._morphState.get(key) ?? 0;+ const next = cur + (target - cur) * Math.min(1, ease * 1.6);+ if (Math.abs(next - cur) < 1e-4 && next === 0) {+ if (cur !== 0) this._writeMorph(bindings, 0);+ this._morphState.set(key, 0);+ continue;+ }+ this._morphState.set(key, next);+ this._writeMorph(bindings, next);+ }++ // Head pose easing + application.+ this._driveHead(dt, faceFresh);+ }++ _writeMorph(bindings, value) {+ for (const b of bindings) b.mesh.morphTargetInfluences[b.index] = value;+ }++ _driveIdle(dt) {+ this._t = (this._t || 0) + dt;+ const t = this._t;+ // Breathing through the spine, gentle and slow (~14 breaths/min).+ const breath = Math.sin(t * 1.45) * 0.5 + 0.5;+ if (this._spineBone) {+ const rest = this._restRot.get(this._spineBone);+ this._spineBone.rotation.x = rest.x + (breath - 0.5) * 0.018;+ }+ // Drifting head sway target.+ this._headTarget.yaw = Math.sin(t * 0.35) * 0.12;+ this._headTarget.pitch = Math.sin(t * 0.27 + 1.0) * 0.05;+ this._headTarget.roll = Math.sin(t * 0.22) * 0.04;++ // Synthetic blink.+ this._nextBlink -= dt;+ if (this._blinkPhase < 0 && this._nextBlink <= 0) {+ this._blinkPhase = 0;+ this._nextBlink = 2.2 + Math.random() * 3.2;+ }+ if (this._blinkPhase >= 0) {+ this._blinkPhase += dt / 0.16; // ~160ms blink+ const p = this._blinkPhase;+ const v = p < 0.5 ? p * 2 : Math.max(0, 2 - p * 2);+ this._stageMorph('eyeblinkleft', v);+ this._stageMorph('eyeblinkright', v);+ this._stageMorph('eyesclosed', v);+ if (p >= 1) this._blinkPhase = -1;+ }+ }++ _driveHead(dt, faceFresh) {+ const ease = Math.min(1, (1 - Math.pow(0.002, dt)) * (faceFresh ? 1.8 : 1.0));+ const c = this._headCurrent;+ c.pitch += (this._headTarget.pitch - c.pitch) * ease;+ c.yaw += (this._headTarget.yaw - c.yaw) * ease;+ c.roll += (this._headTarget.roll - c.roll) * ease;++ // Split rotation across neck + head for a believable turn.+ this._applyBoneRot(this._neckBone, c.pitch * 0.45, c.yaw * 0.4, c.roll * 0.4);+ this._applyBoneRot(this._headBone, c.pitch * 0.6, c.yaw * 0.62, c.roll * 0.62);+ }++ _applyBoneRot(bone, px, py, pz) {+ if (!bone) return;+ const rest = this._restRot.get(bone);+ if (!rest) return;+ this._scratchEuler.set(rest.x + px, rest.y + py, rest.z + pz, 'XYZ');+ bone.quaternion.setFromEuler(this._scratchEuler);+ }++ /** @returns {Promise<Blob>} PNG of the current frame. */+ snapshotPNG() {+ // Force a fresh render so the buffer is current before reading it.+ this.renderer.render(this.scene, this.camera);+ return new Promise((resolve, reject) => {+ this.canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error('snapshot failed'))),+ 'image/png',+ );+ });+ }++ get isFaceActive() { return this._faceActive && performance.now() - this._lastFaceTs < 400; }++ _onResize() {+ const parent = this.canvas.parentElement || this.canvas;+ const w = parent.clientWidth || window.innerWidth;+ const h = parent.clientHeight || window.innerHeight;+ if (!w || !h) return;+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ dispose() {+ this._disposed = true;+ this.stop();+ window.removeEventListener('resize', this._onResize);+ this._resizeObserver?.disconnect();+ this._teardownModel();+ this._controls?.dispose();+ this._draco?.dispose();+ this._ktx2?.dispose();+ this._envRT?.dispose();+ this.renderer.dispose();+ }+}diff --git a/src/mirror/face-tracker.js b/src/mirror/face-tracker.jsnew file mode 100644index 000000000..b2fffc52f--- /dev/null+++ b/src/mirror/face-tracker.js@@ -0,0 +1,596 @@+/**+ * FaceTracker — webcam → live face landmarks for the "become your agent" mirror.+ *+ * Wraps Google MediaPipe FaceLandmarker (`@mediapipe/tasks-vision`) into a tiny,+ * dependency-light driver that turns a user's webcam feed into a stream of+ * normalized {@link FaceFrame}s: ARKit-style blendshape weights plus a decoded+ * head pose (pitch / yaw / roll). A consuming module maps those onto a 3D avatar+ * each frame so the user's face drives the model in real time.+ *+ * Design notes+ * ------------+ * - VIDEO running mode, one face, blendshapes + facial transformation matrices on.+ * - The detection loop prefers `requestVideoFrameCallback` (fires once per decoded+ * video frame, no wasted work) and falls back to `requestAnimationFrame`.+ * - MediaPipe's `detectForVideo` throws if the timestamp is not strictly+ * monotonically increasing and processes nothing useful if you feed it the same+ * video frame twice — so we track `lastVideoTime` (skip unchanged frames) and a+ * `lastTimestamp` watermark (force-bump the timestamp we pass so it always rises).+ * - Head pose is decoded from the 4x4 column-major facial transformation matrix via+ * THREE: Matrix4 → decompose → Euler('YXZ'). yaw=y, pitch=x, roll=z (radians).+ * - Light exponential smoothing on blendshapes + angles keeps the avatar from+ * jittering; the consumer smooths again, so this stays intentionally gentle.+ * - Assets (WASM fileset + .task model) are vendored locally and served from+ * `${localBasePath}` (default `/vendor/mediapipe`). If local load fails we retry+ * once from the pinned official CDN before surfacing a 'model-load' error.+ *+ * The module is pure: it creates no DOM, injects no CSS, and touches no globals.+ * Its only side effect is on the <video> element handed to {@link FaceTracker#start}.+ *+ * @example+ * const tracker = new FaceTracker({ smoothing: 0.5 });+ * tracker.onStatus = (s) => console.log('status', s);+ * tracker.onError = (e) => console.error(e.code, e.message);+ * tracker.onFrame = (frame) => {+ * if (!frame.present) return;+ * avatar.applyBlendshapes(frame.blendshapes);+ * avatar.applyHead(frame.head);+ * };+ * await tracker.init();+ * await tracker.start(document.querySelector('video'));+ * // …later…+ * tracker.stop();+ * tracker.dispose();+ *+ * @typedef {Object} FaceFrame+ * @property {boolean} present True if a face was detected this frame.+ * @property {Object<string, number>} blendshapes ARKit blendshape name → 0..1 weight. Empty when no face.+ * @property {{pitch:number, yaw:number, roll:number}|null} head Head pose in radians, or null when no face.+ * @property {number} ts `performance.now()` timestamp of the frame.+ */++import { FilesetResolver, FaceLandmarker } from '@mediapipe/tasks-vision';+import * as THREE from 'three';++/** Official pinned CDN fallbacks (must match the installed library version). */+const CDN_WASM = 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';+const CDN_MODEL =+ 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';++/**+ * Wrap a value in an Error carrying a stable `.code`, preserving the original+ * message/cause when one is supplied.+ *+ * @param {string} code+ * @param {string} message+ * @param {unknown} [cause]+ * @returns {Error & { code: string }}+ */+function trackerError(code, message, cause) {+ const err = /** @type {Error & { code: string }} */ (+ new Error(cause instanceof Error ? `${message}: ${cause.message}` : message)+ );+ err.code = code;+ if (cause !== undefined) err.cause = cause;+ return err;+}++/** Linear interpolation. */+function lerp(a, b, t) {+ return a + (b - a) * t;+}++export class FaceTracker {+ /**+ * @param {Object} [opts]+ * @param {string} [opts.localBasePath='/vendor/mediapipe'] Base path for the vendored WASM dir + model.+ * @param {number} [opts.smoothing=0.5] 0..1 smoothing factor (0 = none/instant, 1 = frozen). Light values feel best.+ */+ constructor(opts = {}) {+ this._localBasePath = (opts.localBasePath ?? '/vendor/mediapipe').replace(/\/+$/, '');+ // Clamp smoothing to a sane range; this is the per-frame lerp blend toward the new value.+ const s = Number.isFinite(opts.smoothing) ? opts.smoothing : 0.5;+ this._smoothing = Math.min(0.95, Math.max(0, s));++ /** @type {FaceLandmarker|null} */+ this._landmarker = null;+ /** @type {Promise<void>|null} Guards concurrent init() calls. */+ this._initPromise = null;++ /** @type {HTMLVideoElement|null} */+ this._video = null;+ /** @type {MediaStream|null} */+ this._stream = null;+ this._running = false;++ // Loop bookkeeping.+ this._rafId = 0;+ this._rvfcId = 0;+ this._useRvfc = false;+ this._lastVideoTime = -1; // last video currentTime we actually ran detection on+ this._lastTimestamp = -1; // monotonic watermark for detectForVideo()++ // Smoothing caches.+ /** @type {Object<string, number>} */+ this._smoothedShapes = {};+ /** @type {{pitch:number, yaw:number, roll:number}|null} */+ this._smoothedHead = null;+ this._wasPresent = false;++ // Reused THREE scratch objects (avoid per-frame allocation).+ this._mat4 = new THREE.Matrix4();+ this._pos = new THREE.Vector3();+ this._quat = new THREE.Quaternion();+ this._scale = new THREE.Vector3();+ this._euler = new THREE.Euler(0, 0, 0, 'YXZ');++ // Consumer-assignable callbacks. Default to no-ops so calls are always safe.+ /** @type {(frame: FaceFrame) => void} */+ this.onFrame = () => {};+ /** @type {(status: 'idle'|'loading-model'|'requesting-camera'|'running'|'stopped'|'no-face') => void} */+ this.onStatus = () => {};+ /** @type {(err: Error & { code: string }) => void} */+ this.onError = () => {};++ this._status = 'idle';+ }++ /** @returns {boolean} Whether the detection loop is currently active. */+ get running() {+ return this._running;+ }++ /** @returns {HTMLVideoElement|null} The bound video element, or null before start(). */+ get videoElement() {+ return this._video;+ }++ /**+ * Load the MediaPipe fileset + create the FaceLandmarker. Idempotent: repeated+ * calls share the same in-flight promise and resolve once the landmarker exists.+ *+ * @returns {Promise<void>}+ */+ async init() {+ if (this._landmarker) return;+ if (this._initPromise) return this._initPromise;++ this._initPromise = this._loadLandmarker().catch((err) => {+ // Reset so a later init() can retry from scratch.+ this._initPromise = null;+ throw err;+ });+ return this._initPromise;+ }++ /**+ * Build the FaceLandmarker, trying local vendored assets first and falling+ * back once to the pinned CDN. Emits 'loading-model' while working.+ *+ * @private+ * @returns {Promise<void>}+ */+ async _loadLandmarker() {+ this._setStatus('loading-model');++ const localWasm = `${this._localBasePath}/wasm`;+ const localModel = `${this._localBasePath}/face_landmarker.task`;++ try {+ this._landmarker = await this._createLandmarker(localWasm, localModel);+ } catch (localErr) {+ console.warn(+ '[FaceTracker] Local MediaPipe assets failed to load, falling back to CDN.',+ localErr+ );+ try {+ this._landmarker = await this._createLandmarker(CDN_WASM, CDN_MODEL);+ } catch (cdnErr) {+ const err = trackerError(+ 'model-load',+ 'Failed to load the face tracking model from local assets and the CDN fallback',+ cdnErr+ );+ this._emitError(err);+ throw err;+ }+ }+ }++ /**+ * Resolve the WASM fileset and create a VIDEO-mode FaceLandmarker.+ *+ * @private+ * @param {string} wasmPath+ * @param {string} modelPath+ * @returns {Promise<FaceLandmarker>}+ */+ async _createLandmarker(wasmPath, modelPath) {+ const fileset = await FilesetResolver.forVisionTasks(wasmPath);+ return FaceLandmarker.createFromOptions(fileset, {+ baseOptions: { modelAssetPath: modelPath },+ runningMode: 'VIDEO',+ numFaces: 1,+ outputFaceBlendshapes: true,+ outputFacialTransformationMatrixes: true,+ });+ }++ /**+ * Open the webcam, attach it to `videoEl`, start playback, and begin the+ * per-frame detection loop. Calls {@link FaceTracker#init} first if needed.+ *+ * @param {HTMLVideoElement} videoEl+ * @returns {Promise<MediaStream>} The active camera stream.+ */+ async start(videoEl) {+ if (!videoEl) {+ throw trackerError('runtime', 'start() requires a <video> element');+ }+ if (this._running) {+ // Already running on this element — hand back the live stream.+ if (this._video === videoEl && this._stream) return this._stream;+ // Switching elements: tear down the old loop/stream cleanly first.+ this.stop();+ }++ if (+ typeof navigator === 'undefined' ||+ !navigator.mediaDevices ||+ typeof navigator.mediaDevices.getUserMedia !== 'function'+ ) {+ const err = trackerError('unsupported', 'getUserMedia is not available in this browser');+ this._emitError(err);+ throw err;+ }++ try {+ await this.init();+ } catch (err) {+ // init() already emitted a typed error; re-surface to the caller.+ throw err;+ }++ this._video = videoEl;+ this._setStatus('requesting-camera');++ let stream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({+ video: {+ facingMode: 'user',+ width: { ideal: 640 },+ height: { ideal: 480 },+ },+ audio: false,+ });+ } catch (camErr) {+ const err = this._mapCameraError(camErr);+ this._video = null;+ this._emitError(err);+ throw err;+ }++ this._stream = stream;++ try {+ videoEl.srcObject = stream;+ videoEl.muted = true;+ videoEl.playsInline = true;+ await this._playVideo(videoEl);+ } catch (playErr) {+ // Couldn't bind/play — release the camera so we don't leak the device.+ this._releaseStream();+ this._video = null;+ const err = trackerError('runtime', 'Failed to start webcam playback', playErr);+ this._emitError(err);+ throw err;+ }++ this._running = true;+ this._lastVideoTime = -1;+ this._lastTimestamp = -1;+ this._resetSmoothing();+ this._useRvfc = typeof videoEl.requestVideoFrameCallback === 'function';+ this._setStatus('running');+ this._scheduleNext();++ return stream;+ }++ /**+ * Play the video element, tolerating the AbortError that fires when play()+ * is interrupted by a fast stop().+ *+ * @private+ * @param {HTMLVideoElement} videoEl+ * @returns {Promise<void>}+ */+ async _playVideo(videoEl) {+ try {+ await videoEl.play();+ } catch (err) {+ if (err && err.name === 'AbortError') return;+ throw err;+ }+ }++ /**+ * Stop the detection loop and release the camera. Safe to call repeatedly and+ * when never started. Leaves the FaceLandmarker alive so start() can resume;+ * use {@link FaceTracker#dispose} to free it.+ */+ stop() {+ const wasActive = this._running || !!this._stream || !!this._video;++ this._running = false;+ this._cancelLoop();+ this._releaseStream();++ if (this._video) {+ try {+ this._video.srcObject = null;+ } catch {+ /* element may already be detached from the DOM */+ }+ this._video = null;+ }++ this._lastVideoTime = -1;+ this._lastTimestamp = -1;+ this._resetSmoothing();++ if (wasActive) this._setStatus('stopped');+ }++ /**+ * Fully release MediaPipe resources. After dispose() you must call init()+ * again before start(). Calls stop() first.+ */+ dispose() {+ this.stop();+ if (this._landmarker) {+ try {+ this._landmarker.close();+ } catch (err) {+ console.warn('[FaceTracker] Error closing FaceLandmarker.', err);+ }+ this._landmarker = null;+ }+ this._initPromise = null;+ }++ /**+ * Cancel any pending rAF / rVFC callback.+ * @private+ */+ _cancelLoop() {+ if (this._rafId) {+ cancelAnimationFrame(this._rafId);+ this._rafId = 0;+ }+ if (this._rvfcId && this._video && typeof this._video.cancelVideoFrameCallback === 'function') {+ try {+ this._video.cancelVideoFrameCallback(this._rvfcId);+ } catch {+ /* element gone; nothing to cancel */+ }+ }+ this._rvfcId = 0;+ }++ /**+ * Stop and detach all tracks of the active stream.+ * @private+ */+ _releaseStream() {+ if (this._stream) {+ for (const track of this._stream.getTracks()) {+ try {+ track.stop();+ } catch {+ /* already stopped */+ }+ }+ this._stream = null;+ }+ }++ /**+ * Schedule the next loop tick using rVFC when available, else rAF.+ * @private+ */+ _scheduleNext() {+ if (!this._running || !this._video) return;+ const tick = () => this._onTick();+ if (this._useRvfc && typeof this._video.requestVideoFrameCallback === 'function') {+ this._rvfcId = this._video.requestVideoFrameCallback(tick);+ } else {+ this._rafId = requestAnimationFrame(tick);+ }+ }++ /**+ * One detection step: run MediaPipe on the current video frame (if it's new+ * and decodable), normalize the result, and emit a FaceFrame.+ * @private+ */+ _onTick() {+ if (!this._running || !this._video || !this._landmarker) return;++ const video = this._video;++ try {+ // readyState >= 2 (HAVE_CURRENT_DATA) means there's a frame to read.+ if (video.readyState >= 2 && video.videoWidth > 0) {+ const now = performance.now();+ // Skip if the decoded frame hasn't advanced — feeding the same frame+ // wastes work and an unchanged timestamp makes MediaPipe throw.+ if (video.currentTime !== this._lastVideoTime) {+ this._lastVideoTime = video.currentTime;+ // Guarantee a strictly increasing timestamp for detectForVideo().+ const ts = now > this._lastTimestamp ? now : this._lastTimestamp + 1;+ this._lastTimestamp = ts;++ const result = this._landmarker.detectForVideo(video, ts);+ this._emitFrame(result, now);+ }+ }+ } catch (err) {+ // A runtime detection failure shouldn't kill the loop silently, but we+ // also don't want to spam — surface once, then keep trying next frame.+ this._emitError(trackerError('runtime', 'Face detection failed for a frame', err));+ }++ this._scheduleNext();+ }++ /**+ * Convert a MediaPipe FaceLandmarkerResult into a smoothed FaceFrame and emit it.+ *+ * @private+ * @param {import('@mediapipe/tasks-vision').FaceLandmarkerResult} result+ * @param {number} ts+ */+ _emitFrame(result, ts) {+ const blendList = result.faceBlendshapes && result.faceBlendshapes[0];+ const matrix = result.facialTransformationMatrixes && result.facialTransformationMatrixes[0];+ const present = !!(blendList && blendList.categories && blendList.categories.length);++ if (!present) {+ if (this._wasPresent || this._status === 'running') this._setStatus('no-face');+ this._wasPresent = false;+ this._resetSmoothing();+ this.onFrame({ present: false, blendshapes: {}, head: null, ts });+ return;+ }++ if (!this._wasPresent && this._status === 'no-face') this._setStatus('running');+ this._wasPresent = true;++ const blendshapes = this._smoothBlendshapes(blendList.categories);+ const head = matrix && matrix.data ? this._smoothHead(this._decodeHead(matrix.data)) : null;++ this.onFrame({ present: true, blendshapes, head, ts });+ }++ /**+ * Map MediaPipe blendshape categories → { arkitName: weight }, dropping the+ * `_neutral` channel, and apply light exponential smoothing against the cache.+ *+ * @private+ * @param {Array<{categoryName: string, score: number}>} categories+ * @returns {Object<string, number>}+ */+ _smoothBlendshapes(categories) {+ const t = 1 - this._smoothing; // blend toward the new value+ /** @type {Object<string, number>} */+ const out = {};+ for (const c of categories) {+ const name = c.categoryName;+ if (!name || name === '_neutral') continue;+ const prev = this._smoothedShapes[name];+ const value = prev === undefined ? c.score : lerp(prev, c.score, t);+ this._smoothedShapes[name] = value;+ out[name] = value;+ }+ return out;+ }++ /**+ * Decode head pitch/yaw/roll (radians) from a 4x4 column-major transform matrix.+ *+ * @private+ * @param {Float32Array|number[]} data length-16 column-major matrix+ * @returns {{pitch:number, yaw:number, roll:number}}+ */+ _decodeHead(data) {+ this._mat4.fromArray(data);+ this._mat4.decompose(this._pos, this._quat, this._scale);+ this._euler.setFromQuaternion(this._quat, 'YXZ');+ return { pitch: this._euler.x, yaw: this._euler.y, roll: this._euler.z };+ }++ /**+ * Smooth head angles against the cache.+ *+ * @private+ * @param {{pitch:number, yaw:number, roll:number}} head+ * @returns {{pitch:number, yaw:number, roll:number}}+ */+ _smoothHead(head) {+ const t = 1 - this._smoothing;+ if (!this._smoothedHead) {+ this._smoothedHead = { ...head };+ } else {+ this._smoothedHead = {+ pitch: lerp(this._smoothedHead.pitch, head.pitch, t),+ yaw: lerp(this._smoothedHead.yaw, head.yaw, t),+ roll: lerp(this._smoothedHead.roll, head.roll, t),+ };+ }+ return { ...this._smoothedHead };+ }++ /**+ * Clear smoothing caches so a fresh session / re-acquired face starts clean.+ * @private+ */+ _resetSmoothing() {+ this._smoothedShapes = {};+ this._smoothedHead = null;+ }++ /**+ * Translate a getUserMedia rejection into a typed FaceTracker error.+ *+ * @private+ * @param {unknown} camErr+ * @returns {Error & { code: string }}+ */+ _mapCameraError(camErr) {+ const name = camErr && /** @type {{ name?: string }} */ (camErr).name;+ switch (name) {+ case 'NotAllowedError':+ case 'SecurityError':+ case 'PermissionDeniedError':+ return trackerError('camera-denied', 'Camera permission was denied', camErr);+ case 'NotFoundError':+ case 'DevicesNotFoundError':+ case 'OverconstrainedError':+ return trackerError('camera-missing', 'No suitable camera was found', camErr);+ default:+ return trackerError('runtime', 'Could not access the camera', camErr);+ }+ }++ /**+ * Emit a status transition (deduped) through onStatus.+ *+ * @private+ * @param {'idle'|'loading-model'|'requesting-camera'|'running'|'stopped'|'no-face'} status+ */+ _setStatus(status) {+ if (this._status === status) return;+ this._status = status;+ try {+ this.onStatus(status);+ } catch (err) {+ console.warn('[FaceTracker] onStatus handler threw.', err);+ }+ }++ /**+ * Emit a typed error through onError, guarding against a throwing handler.+ *+ * @private+ * @param {Error & { code: string }} err+ */+ _emitError(err) {+ try {+ this.onError(err);+ } catch (handlerErr) {+ console.warn('[FaceTracker] onError handler threw.', handlerErr);+ }+ }+}diff --git a/src/mirror/recorder.js b/src/mirror/recorder.jsnew file mode 100644index 000000000..aff9697d9--- /dev/null+++ b/src/mirror/recorder.js@@ -0,0 +1,425 @@+/**+ * Recorder — real-time capture, download, and share for the Mirror page.+ *+ * The Mirror page draws a 3D avatar to a <canvas> that is driven by the user's+ * webcam in real time. This module turns that live canvas into two artifacts a+ * user can keep or post:+ *+ * 1. A short video clip — MediaRecorder over canvas.captureStream(fps),+ * optionally muxing a supplied mic/voice audio+ * track, auto-stopping at maxDurationMs.+ * 2. A still PNG snapshot — canvas.toBlob('image/png').+ *+ * Plus the plumbing to act on those artifacts: a real browser download (object+ * URL + temporary anchor, URL revoked after) and a share-to-X intent window.+ *+ * Everything here is genuine: real MediaRecorder, real canvas.captureStream,+ * real canvas.toBlob. The only timers in this file track *actual* elapsed wall+ * time (the max-duration cutoff and the onTick UI clock) — there is no+ * simulated progress, no setTimeout-faked loading.+ *+ * State machine (surfaced through `onState`):+ *+ * idle ──start()──▶ recording ──stop()/auto──▶ stopping ──blob──▶ ready+ * ▲ │ │+ * └──────cancel()───────┘ next start() ─────────┘+ *+ * Usage:+ *+ * const rec = new Recorder({ fps: 30, maxDurationMs: 15000 });+ * rec.onState = (s) => updateButton(s);+ * rec.onTick = (ms) => updateTimer(ms);+ * rec.start(canvas, { audioStream: micStream }); // micStream optional+ * // ...later...+ * const blob = await rec.stop();+ * if (blob) downloadBlob(blob, suggestedFilename('three-ws-mirror', 'webm'));+ *+ * // Still image + share:+ * const png = await snapshotPNG(canvas);+ * downloadBlob(png, suggestedFilename('three-ws-mirror', 'png'));+ * shareToX({ text: 'My avatar on three.ws', url: 'https://three.ws', hashtags: ['threews'] });+ *+ * Pure module: no DOM scaffolding beyond the throwaway <a> used for download+ * and window.open for share. No CSS. ES module, named exports.+ */++// MediaRecorder mimeTypes we'll try, best-first. The first one the browser+// reports as supported wins.+const MIME_CANDIDATES = [+ 'video/webm;codecs=vp9',+ 'video/webm;codecs=vp8',+ 'video/webm',+ 'video/mp4',+];++// How often onTick fires while recording (~4x/sec).+const TICK_INTERVAL_MS = 250;++/**+ * Picks the best MediaRecorder mimeType the current browser supports.+ * @returns {string} a supported mimeType, or '' to let the browser choose.+ */+function pickMimeType() {+ if (typeof MediaRecorder === 'undefined' ||+ typeof MediaRecorder.isTypeSupported !== 'function') {+ return '';+ }+ for (const mime of MIME_CANDIDATES) {+ if (MediaRecorder.isTypeSupported(mime)) return mime;+ }+ return '';+}++/**+ * True when this environment can actually record a canvas.+ * @returns {boolean}+ */+function detectSupport() {+ if (typeof MediaRecorder === 'undefined') return false;+ if (typeof HTMLCanvasElement === 'undefined') return false;+ if (typeof HTMLCanvasElement.prototype.captureStream !== 'function') return false;+ return true;+}++export class Recorder {+ /**+ * @param {{ fps?: number, maxDurationMs?: number }} [opts]+ */+ constructor(opts = {}) {+ this.fps = Number.isFinite(opts.fps) && opts.fps > 0 ? opts.fps : 30;+ this.maxDurationMs = Number.isFinite(opts.maxDurationMs) && opts.maxDurationMs > 0+ ? opts.maxDurationMs+ : 30000;++ // Assignable callbacks — default to no-ops so callers can skip either.+ this.onState = () => {};+ this.onTick = () => {};++ this._state = 'idle';+ this._recorder = null;+ this._stream = null;+ this._chunks = [];+ this._mimeType = '';+ this._startedAt = 0;++ this._maxTimer = null;+ this._tickTimer = null;++ // Pending stop() promise resolver, set while a stop is in flight.+ this._stopResolve = null;+ }++ /** @returns {string} current state: 'idle'|'recording'|'stopping'|'ready' */+ get state() {+ return this._state;+ }++ /** @returns {boolean} true while actively recording. */+ get recording() {+ return this._state === 'recording';+ }++ /** @returns {boolean} whether recording is possible in this environment. */+ get supported() {+ return detectSupport();+ }++ /**+ * Begin recording the given canvas.+ *+ * @param {HTMLCanvasElement} canvas+ * @param {{ audioStream?: MediaStream }} [opts] optional mic/voice stream to mux.+ * @throws {Error} when unsupported, given a bad canvas, or already recording.+ */+ start(canvas, opts = {}) {+ if (!this.supported) {+ throw new Error('Recording is not supported in this browser (MediaRecorder or canvas.captureStream unavailable).');+ }+ if (!canvas || typeof canvas.captureStream !== 'function') {+ throw new Error('Recorder.start requires an HTMLCanvasElement with captureStream support.');+ }+ if (this._state === 'recording' || this._state === 'stopping') {+ throw new Error('Recorder is already running. Stop or cancel before starting again.');+ }++ // Clean any leftover state from a prior 'ready' cycle.+ this._teardownTimers();+ this._chunks = [];+ this._stopResolve = null;++ const videoStream = canvas.captureStream(this.fps);+ const videoTracks = videoStream.getVideoTracks();++ let stream = videoStream;+ const audioStream = opts.audioStream;+ if (audioStream && typeof audioStream.getAudioTracks === 'function') {+ const audioTracks = audioStream.getAudioTracks();+ if (audioTracks.length > 0) {+ stream = new MediaStream([...videoTracks, ...audioTracks]);+ }+ }++ this._mimeType = pickMimeType();+ const recorderOptions = this._mimeType ? { mimeType: this._mimeType } : undefined;++ let recorder;+ try {+ recorder = new MediaRecorder(stream, recorderOptions);+ } catch (err) {+ // Fall back to default options if the chosen mimeType was rejected.+ recorder = new MediaRecorder(stream);+ this._mimeType = '';+ }++ // Honor whatever the recorder actually committed to, when exposed.+ if (recorder.mimeType) this._mimeType = recorder.mimeType;++ recorder.ondataavailable = (event) => {+ if (event.data && event.data.size > 0) {+ this._chunks.push(event.data);+ }+ };+ recorder.onstop = () => this._finalize();+ recorder.onerror = () => {+ // A recorder error mid-capture: salvage whatever chunks exist by+ // finalizing rather than leaving the caller hanging.+ this._finalize();+ };++ this._stream = stream;+ this._recorder = recorder;+ this._startedAt = Date.now();++ // requestData cadence isn't required — onstop flushes a final chunk —+ // but a timeslice guarantees periodic chunks for long clips.+ recorder.start(1000);++ this._setState('recording');++ this._tickTimer = setInterval(() => {+ this.onTick(Date.now() - this._startedAt);+ }, TICK_INTERVAL_MS);++ this._maxTimer = setTimeout(() => {+ this._maxTimer = null;+ // Auto-stop at the duration cap; ignore the returned promise here,+ // any pending stop() awaiter is still resolved through _finalize.+ this.stop();+ }, this.maxDurationMs);+ }++ /**+ * Stop recording and resolve to the assembled Blob.+ * Safe to call when not recording — resolves null.+ *+ * @returns {Promise<Blob|null>}+ */+ stop() {+ if (this._state !== 'recording') {+ return Promise.resolve(null);+ }++ this._setState('stopping');+ this._teardownTimers();++ return new Promise((resolve) => {+ this._stopResolve = resolve;+ try {+ if (this._recorder && this._recorder.state !== 'inactive') {+ this._recorder.stop();+ } else {+ this._finalize();+ }+ } catch (err) {+ // If stop() throws, still finalize so the awaiter resolves.+ this._finalize();+ }+ });+ }++ /**+ * Discard an in-progress recording without producing a blob.+ * Resolves any pending stop() awaiter with null and returns to 'idle'.+ */+ cancel() {+ const wasActive = this._state === 'recording' || this._state === 'stopping';+ this._teardownTimers();++ const recorder = this._recorder;+ if (recorder) {+ recorder.ondataavailable = null;+ recorder.onstop = null;+ recorder.onerror = null;+ try {+ if (recorder.state !== 'inactive') recorder.stop();+ } catch (err) {+ // Already inactive or detached — nothing to recover.+ }+ }++ this._releaseStream();+ this._recorder = null;+ this._chunks = [];+ this._mimeType = '';++ const resolve = this._stopResolve;+ this._stopResolve = null;++ if (wasActive) this._setState('idle');+ if (resolve) resolve(null);+ }++ // --- internals ---------------------------------------------------------++ /**+ * Assemble collected chunks into a Blob, settle pending stop(), and move to+ * 'ready'. Idempotent: guarded so a recorder error + onstop don't double-fire.+ */+ _finalize() {+ if (this._state !== 'stopping' && this._state !== 'recording') {+ // Already finalized or cancelled.+ return;+ }++ this._teardownTimers();++ const type = this._mimeType || 'video/webm';+ const blob = this._chunks.length > 0+ ? new Blob(this._chunks, { type })+ : null;++ this._chunks = [];+ this._releaseStream();+ this._recorder = null;++ const resolve = this._stopResolve;+ this._stopResolve = null;++ this._setState('ready');+ if (resolve) resolve(blob);+ }++ /** Stop and release the captured stream's tracks. */+ _releaseStream() {+ if (this._stream) {+ for (const track of this._stream.getTracks()) {+ try {+ track.stop();+ } catch (err) {+ // Track already ended.+ }+ }+ this._stream = null;+ }+ }++ /** Clear both the max-duration cutoff and the onTick interval. */+ _teardownTimers() {+ if (this._maxTimer !== null) {+ clearTimeout(this._maxTimer);+ this._maxTimer = null;+ }+ if (this._tickTimer !== null) {+ clearInterval(this._tickTimer);+ this._tickTimer = null;+ }+ }++ /**+ * @param {'idle'|'recording'|'stopping'|'ready'} next+ */+ _setState(next) {+ if (this._state === next) return;+ this._state = next;+ this.onState(next);+ }+}++/**+ * Capture a still PNG of the canvas.+ *+ * @param {HTMLCanvasElement} canvas+ * @returns {Promise<Blob>} a PNG blob.+ */+export function snapshotPNG(canvas) {+ return new Promise((resolve, reject) => {+ if (!canvas || typeof canvas.toBlob !== 'function') {+ reject(new Error('snapshotPNG requires an HTMLCanvasElement with toBlob support.'));+ return;+ }+ try {+ canvas.toBlob((blob) => {+ if (blob) {+ resolve(blob);+ } else {+ reject(new Error('Failed to encode canvas to PNG (toBlob returned null).'));+ }+ }, 'image/png');+ } catch (err) {+ // canvas.toBlob throws SecurityError on a tainted (cross-origin) canvas.+ reject(err instanceof Error ? err : new Error(String(err)));+ }+ });+}++/**+ * Trigger a browser download of a blob via a temporary object URL + anchor.+ * The object URL is revoked after the click to avoid leaking memory.+ *+ * @param {Blob} blob+ * @param {string} filename+ */+export function downloadBlob(blob, filename) {+ if (!blob) {+ throw new Error('downloadBlob requires a Blob.');+ }+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = filename || 'download';+ anchor.rel = 'noopener';+ anchor.style.display = 'none';+ document.body.appendChild(anchor);+ anchor.click();+ document.body.removeChild(anchor);+ // Revoke on the next tick so the navigation has committed.+ setTimeout(() => URL.revokeObjectURL(url), 0);+}++/**+ * Open X's tweet-intent composer in a new tab, pre-filled with the supplied copy.+ * The caller supplies all text — nothing is defaulted on their behalf.+ *+ * @param {{ text?: string, url?: string, hashtags?: string[] }} params+ * @returns {Window|null} the opened window, or null if the browser blocked it.+ */+export function shareToX({ text, url, hashtags } = {}) {+ const params = new URLSearchParams();+ if (text) params.set('text', text);+ if (url) params.set('url', url);+ if (Array.isArray(hashtags) && hashtags.length > 0) {+ // X expects bare, comma-joined tags (no leading '#').+ const tags = hashtags+ .map((tag) => String(tag).replace(/^#/, '').trim())+ .filter(Boolean);+ if (tags.length > 0) params.set('hashtags', tags.join(','));+ }+ const intentUrl = `https://twitter.com/intent/tweet?${params.toString()}`;+ return window.open(intentUrl, '_blank', 'noopener');+}++/**+ * Build a timestamped filename using local time.+ *+ * @param {string} [prefix='three-ws-mirror']+ * @param {string} [ext='webm']+ * @returns {string} e.g. "three-ws-mirror-20260619-143005.webm"+ */+export function suggestedFilename(prefix = 'three-ws-mirror', ext = 'webm') {+ const now = new Date();+ const pad = (n) => String(n).padStart(2, '0');+ const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;+ const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;+ const cleanExt = String(ext).replace(/^\./, '');+ return `${prefix}-${date}-${time}.${cleanExt}`;+}diff --git a/src/pulse-scene.js b/src/pulse-scene.jsnew file mode 100644index 000000000..517c56813--- /dev/null+++ b/src/pulse-scene.js@@ -0,0 +1,971 @@+// PULSE — a cinematic 3D visualization of the whole three.ws agent economy.+//+// The $THREE core sits at the gravitational center; every agent orbits it as a+// glowing node, pulled inward by reputation and value. Real economy events+// (launches, buybacks, payments, graduations) fire as eased streaks of light+// flowing between an agent and the core.+//+// This module owns ONLY the WebGL scene. The page (pages/pulse.html) and the+// controller (src/pulse.js) drive it through the API exported below:+//+// const scene = createPulseScene(canvas, opts);+// scene.setData({ three, agents }); // (re)build from real data+// scene.pulse({ type, agentId, amountUsdc }); // one event streak+// scene.focusAgent(id | null); // fly camera to a node / overview+// scene.getAgentAtPointer(x, y); // raycast → agent id | null+// scene.resize();+// scene.setReducedMotion(bool);+// scene.dispose();+//+// Conventions (renderer setup, reduced-motion, render-on-demand, dispose+// discipline) mirror src/galaxy.js.++import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';++const PREFERS_REDUCED_MOTION =+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;++// ── Palette ──────────────────────────────────────────────────────────────────+// Dark, premium, Linear/Stripe-grade. Reputation ramps from a dim ember red+// (low trust) through teal to a bright gold-white (high trust). The $THREE core+// glows in the platform's signature green.+const PALETTE = {+ core: new THREE.Color('#3be08a'), // $THREE green — the gravitational center+ coreHalo: new THREE.Color('#7af7b8'),+ repLow: new THREE.Color('#ff5a5f'), // low reputation — dim ember+ repMid: new THREE.Color('#26c6da'), // mid reputation — cyan+ repHigh: new THREE.Color('#ffd86b'), // high reputation — bright gold+ rugged: new THREE.Color('#6b3a3a'), // rugged agents read as cold/ashen+ link: new THREE.Color('#1f3b52'),+ // Event hues+ event: {+ payment: new THREE.Color('#22d3ee'), // cyan — value flows to core+ buyback: new THREE.Color('#3be08a'), // $THREE green — buyback pressure+ launch: new THREE.Color('#a78bfa'), // violet — new creation emits outward+ graduation: new THREE.Color('#fff6e0'), // white-hot — a milestone+ },+};++// Map reputation 0..1 onto the ramp.+function reputationColor(rep, rugged) {+ const out = new THREE.Color();+ if (rugged) return out.copy(PALETTE.rugged);+ const r = Math.max(0, Math.min(1, rep || 0));+ if (r < 0.5) out.copy(PALETTE.repLow).lerp(PALETTE.repMid, r / 0.5);+ else out.copy(PALETTE.repMid).lerp(PALETTE.repHigh, (r - 0.5) / 0.5);+ return out;+}++const MAX_PARTICLES = 120; // hard cap on concurrent event streaks+const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);+const easeOut = (t) => 1 - Math.pow(1 - t, 3);++// ── Sprite textures (generated once, reused) ─────────────────────────────────+// Soft radial-gradient glow used for agent nodes and the core halo.+function makeGlowTexture(size = 128) {+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const ctx = c.getContext('2d');+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);+ g.addColorStop(0.0, 'rgba(255,255,255,1)');+ g.addColorStop(0.18, 'rgba(255,255,255,0.85)');+ g.addColorStop(0.45, 'rgba(255,255,255,0.32)');+ g.addColorStop(1.0, 'rgba(255,255,255,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, size, size);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.needsUpdate = true;+ return tex;+}++// A tighter, hotter spark for event streaks.+function makeSparkTexture(size = 64) {+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const ctx = c.getContext('2d');+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);+ g.addColorStop(0.0, 'rgba(255,255,255,1)');+ g.addColorStop(0.35, 'rgba(255,255,255,0.55)');+ g.addColorStop(1.0, 'rgba(255,255,255,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, size, size);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.needsUpdate = true;+ return tex;+}++export function createPulseScene(canvas, opts = {}) {+ if (!(canvas instanceof HTMLCanvasElement)) {+ throw new TypeError('createPulseScene: a canvas element is required');+ }++ let reducedMotion = PREFERS_REDUCED_MOTION || !!opts.reducedMotion;++ // ── Renderer / scene / camera (galaxy.js conventions) ──────────────────────+ const renderer = new THREE.WebGLRenderer({+ canvas,+ antialias: true,+ alpha: true,+ powerPreference: 'high-performance',+ });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.15;+ renderer.setClearColor(0x000000, 0);++ const scene = new THREE.Scene();+ scene.fog = new THREE.FogExp2(0x05070d, 0.0016);++ const camera = new THREE.PerspectiveCamera(56, 1, 0.1, 6000);+ camera.position.set(0, 60, 520);++ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;+ controls.enablePan = false;+ controls.minDistance = 80;+ controls.maxDistance = 1400;+ controls.rotateSpeed = 0.55;+ controls.zoomSpeed = 0.8;+ controls.autoRotate = !reducedMotion;+ controls.autoRotateSpeed = 0.28;++ const clock = new THREE.Clock();+ const raycaster = new THREE.Raycaster();+ const pointer = new THREE.Vector2();++ // ── Shared, single-allocation resources ────────────────────────────────────+ const glowTex = makeGlowTexture();+ const sparkTex = makeSparkTexture();++ // ── State ──────────────────────────────────────────────────────────────────+ const state = {+ agents: [], // array of normalized agent records (with position + screen radius)+ idToIndex: new Map(),+ nodes: null, // THREE.Points cloud of agent nodes+ nodeGeom: null,+ nodeMat: null,+ links: null, // faint connection lines agent → core+ linkGeom: null,+ linkMat: null,+ coreGroup: null,+ coreMesh: null,+ coreMat: null,+ coreHalo: null,+ coreHaloMat: null,+ ambient: null, // ambient depth particle field+ ambientMat: null,+ starfield: null,+ starMat: null,+ };++ // Camera fly-to tween (galaxy.js style).+ const fly = {+ active: false,+ t: 0,+ dur: 0.9,+ fromPos: new THREE.Vector3(),+ toPos: new THREE.Vector3(),+ fromTgt: new THREE.Vector3(),+ toTgt: new THREE.Vector3(),+ };++ // Idle auto-rotate resumes a few seconds after the user stops interacting.+ let idleTimer = 0;+ function scheduleIdle() {+ clearTimeout(idleTimer);+ if (reducedMotion) return;+ idleTimer = setTimeout(() => {+ controls.autoRotate = true;+ }, 3500);+ }+ controls.addEventListener('start', () => {+ controls.autoRotate = false;+ clearTimeout(idleTimer);+ });+ controls.addEventListener('end', scheduleIdle);++ // ── Background: starfield + ambient depth field ────────────────────────────+ function buildBackground() {+ // Distant starfield shell — purely decorative parallax.+ const N = 1600;+ const pos = new Float32Array(N * 3);+ for (let i = 0; i < N; i++) {+ const r = 1400 + Math.random() * 2800;+ const th = Math.random() * Math.PI * 2;+ const ph = Math.acos(2 * Math.random() - 1);+ pos[i * 3] = r * Math.sin(ph) * Math.cos(th);+ pos[i * 3 + 1] = r * Math.sin(ph) * Math.sin(th);+ pos[i * 3 + 2] = r * Math.cos(ph);+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));+ state.starMat = new THREE.PointsMaterial({+ color: 0x9fb4d6,+ size: 1.5,+ sizeAttenuation: false,+ transparent: true,+ opacity: 0.5,+ depthWrite: false,+ });+ state.starfield = new THREE.Points(g, state.starMat);+ state.starfield.frustumCulled = false;+ scene.add(state.starfield);++ // Ambient dust nearer the core gives the economy field a sense of volume.+ const M = 900;+ const apos = new Float32Array(M * 3);+ for (let i = 0; i < M; i++) {+ const r = 120 + Math.random() * 620;+ const th = Math.random() * Math.PI * 2;+ const ph = Math.acos(2 * Math.random() - 1);+ apos[i * 3] = r * Math.sin(ph) * Math.cos(th);+ apos[i * 3 + 1] = (r * Math.sin(ph) * Math.sin(th)) * 0.55; // flatten into a disk+ apos[i * 3 + 2] = r * Math.cos(ph);+ }+ const ag = new THREE.BufferGeometry();+ ag.setAttribute('position', new THREE.BufferAttribute(apos, 3));+ state.ambientMat = new THREE.PointsMaterial({+ color: 0x2e6f8e,+ size: 2.0,+ map: glowTex,+ sizeAttenuation: true,+ transparent: true,+ opacity: 0.28,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ state.ambient = new THREE.Points(ag, state.ambientMat);+ state.ambient.frustumCulled = false;+ scene.add(state.ambient);+ }++ // ── The $THREE core ────────────────────────────────────────────────────────+ function buildCore() {+ const group = new THREE.Group();++ // Emissive faceted gem — reads as a charged, premium centerpiece.+ const geo = new THREE.IcosahedronGeometry(22, 1);+ const mat = new THREE.MeshStandardMaterial({+ color: PALETTE.core,+ emissive: PALETTE.core,+ emissiveIntensity: 1.6,+ metalness: 0.3,+ roughness: 0.25,+ flatShading: true,+ });+ const mesh = new THREE.Mesh(geo, mat);+ group.add(mesh);++ // Inner wireframe shell adds detail without postprocessing.+ const wireGeo = new THREE.IcosahedronGeometry(26, 1);+ const wireMat = new THREE.MeshBasicMaterial({+ color: PALETTE.coreHalo,+ wireframe: true,+ transparent: true,+ opacity: 0.18,+ blending: THREE.AdditiveBlending,+ depthWrite: false,+ });+ const wire = new THREE.Mesh(wireGeo, wireMat);+ group.add(wire);++ // Soft additive halo sprite — the "bloom" without postprocessing cost.+ const haloMat = new THREE.SpriteMaterial({+ map: glowTex,+ color: PALETTE.coreHalo,+ transparent: true,+ opacity: 0.9,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ const halo = new THREE.Sprite(haloMat);+ halo.scale.setScalar(170);+ group.add(halo);++ // Two point lights so the gem and nearby nodes catch real shading.+ const keyLight = new THREE.PointLight(PALETTE.coreHalo.getHex(), 3.2, 1200, 1.4);+ group.add(keyLight);++ scene.add(group);+ scene.add(new THREE.AmbientLight(0x3a4a66, 0.6));++ state.coreGroup = group;+ state.coreMesh = mesh;+ state.coreMat = mat;+ state.coreHalo = halo;+ state.coreHaloMat = haloMat;+ // Track auxiliary disposables on the group's userData for clean teardown.+ group.userData.disposables = [geo, mat, wireGeo, wireMat, haloMat];+ }++ // ── Agent nodes ────────────────────────────────────────────────────────────+ // Position each agent in an orbital shell: higher reputation/value pulls the+ // node closer to the core and makes it brighter; node size scales with value+ // and launch activity. Layout is deterministic per agent id so re-renders are+ // stable, with a golden-angle spiral spreading nodes evenly over a sphere.+ function layoutAgents(agents) {+ const GOLDEN = Math.PI * (3 - Math.sqrt(5));+ const maxValue = Math.max(1, ...agents.map((a) => a.value_usdc || 0));+ const maxLaunch = Math.max(1, ...agents.map((a) => a.launches || 0));++ return agents.map((a, i) => {+ const rep = Math.max(0, Math.min(1, a.reputation || 0));+ const valueNorm = Math.log1p(a.value_usdc || 0) / Math.log1p(maxValue);+ const launchNorm = Math.log1p(a.launches || 0) / Math.log1p(maxLaunch);++ // Pull-in: blend reputation and value. 1 = hugs the core, 0 = far rim.+ const pull = 0.6 * rep + 0.4 * valueNorm;+ const radius = 110 + (560 - 110) * (1 - pull);++ // Even spherical distribution via Fibonacci sphere, flattened into a+ // gentle disk so the economy reads as an accretion field, not a ball.+ const y = 1 - (i / Math.max(1, agents.length - 1)) * 2; // 1 → -1+ const ringR = Math.sqrt(Math.max(0, 1 - y * y));+ const theta = GOLDEN * i;+ const pos = new THREE.Vector3(+ radius * ringR * Math.cos(theta),+ radius * y * 0.6,+ radius * ringR * Math.sin(theta),+ );++ // Node size scales with value + launches; graduated agents get a bump.+ const size = 6 + 22 * (0.55 * valueNorm + 0.45 * launchNorm) + (a.graduated ? 6 : 0);++ // Brightness rides reputation; rugged agents are dimmed regardless.+ const brightness = a.rugged ? 0.22 : 0.45 + 0.55 * rep;++ return {+ id: a.id,+ name: a.name || 'Agent',+ avatar_url: a.avatar_url || null,+ launches: a.launches || 0,+ value_usdc: a.value_usdc || 0,+ reputation: rep,+ graduated: !!a.graduated,+ rugged: !!a.rugged,+ best_ath_multiple: a.best_ath_multiple || 0,+ position: pos,+ size,+ brightness,+ color: reputationColor(rep, a.rugged),+ };+ });+ }++ function buildNodes(agents) {+ const n = agents.length;+ const positions = new Float32Array(n * 3);+ const colors = new Float32Array(n * 3);+ const sizes = new Float32Array(n);+ const seeds = new Float32Array(n);+ const bright = new Float32Array(n);++ state.idToIndex.clear();+ agents.forEach((a, i) => {+ state.idToIndex.set(a.id, i);+ positions[i * 3] = a.position.x;+ positions[i * 3 + 1] = a.position.y;+ positions[i * 3 + 2] = a.position.z;+ colors[i * 3] = a.color.r;+ colors[i * 3 + 1] = a.color.g;+ colors[i * 3 + 2] = a.color.b;+ sizes[i] = a.size;+ seeds[i] = Math.random();+ bright[i] = a.brightness;+ });++ const geom = new THREE.BufferGeometry();+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));+ geom.setAttribute('aColor', new THREE.BufferAttribute(colors, 3));+ geom.setAttribute('aSize', new THREE.BufferAttribute(sizes, 1));+ geom.setAttribute('aSeed', new THREE.BufferAttribute(seeds, 1));+ geom.setAttribute('aBright', new THREE.BufferAttribute(bright, 1));++ const mat = new THREE.ShaderMaterial({+ uniforms: {+ uTime: { value: 0 },+ uPixelRatio: { value: Math.min(window.devicePixelRatio || 1, 2) },+ uTwinkle: { value: reducedMotion ? 0 : 1 },+ uFocus: { value: -1 }, // index of focused node, or -1+ uTex: { value: glowTex },+ },+ vertexShader: NODE_VERT,+ fragmentShader: NODE_FRAG,+ transparent: true,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });++ const points = new THREE.Points(geom, mat);+ points.frustumCulled = false;+ scene.add(points);++ state.nodes = points;+ state.nodeGeom = geom;+ state.nodeMat = mat;++ // Raycast against points; threshold scaled to node footprint.+ raycaster.params.Points.threshold = 14;+ }++ // Faint lines tying each agent back to the core — the economy's connective tissue.+ function buildLinks(agents) {+ const n = agents.length;+ const positions = new Float32Array(n * 2 * 3);+ const alphas = new Float32Array(n * 2);+ agents.forEach((a, i) => {+ positions[i * 6 + 0] = 0;+ positions[i * 6 + 1] = 0;+ positions[i * 6 + 2] = 0;+ positions[i * 6 + 3] = a.position.x;+ positions[i * 6 + 4] = a.position.y;+ positions[i * 6 + 5] = a.position.z;+ // Brighter, more reputable agents get a slightly more visible tether.+ const al = 0.05 + 0.22 * a.brightness;+ alphas[i * 2] = al * 0.4; // near core+ alphas[i * 2 + 1] = al; // at node+ });+ const geom = new THREE.BufferGeometry();+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));+ geom.setAttribute('aAlpha', new THREE.BufferAttribute(alphas, 1));+ const mat = new THREE.ShaderMaterial({+ uniforms: { uColor: { value: PALETTE.link.clone() } },+ vertexShader: LINK_VERT,+ fragmentShader: LINK_FRAG,+ transparent: true,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ const lines = new THREE.LineSegments(geom, mat);+ lines.frustumCulled = false;+ scene.add(lines);+ state.links = lines;+ state.linkGeom = geom;+ state.linkMat = mat;+ }++ // ── Event particle pool ────────────────────────────────────────────────────+ // One additive Points cloud holds the whole pool. Inactive particles live at+ // the origin with zero alpha; pulse() activates a slot and tick() advances it.+ const particles = {+ points: null,+ geom: null,+ mat: null,+ count: MAX_PARTICLES,+ // Per-particle simulation state (parallel arrays).+ active: new Uint8Array(MAX_PARTICLES),+ t: new Float32Array(MAX_PARTICLES),+ dur: new Float32Array(MAX_PARTICLES),+ from: [],+ to: [],+ baseSize: new Float32Array(MAX_PARTICLES),+ cursor: 0,+ };++ function buildParticles() {+ const N = particles.count;+ for (let i = 0; i < N; i++) {+ particles.from[i] = new THREE.Vector3();+ particles.to[i] = new THREE.Vector3();+ }+ const positions = new Float32Array(N * 3);+ const colors = new Float32Array(N * 3);+ const sizes = new Float32Array(N);+ const alphas = new Float32Array(N);+ const geom = new THREE.BufferGeometry();+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));+ geom.setAttribute('aColor', new THREE.BufferAttribute(colors, 3));+ geom.setAttribute('aSize', new THREE.BufferAttribute(sizes, 1));+ geom.setAttribute('aAlpha', new THREE.BufferAttribute(alphas, 1));+ const mat = new THREE.ShaderMaterial({+ uniforms: {+ uPixelRatio: { value: Math.min(window.devicePixelRatio || 1, 2) },+ uTex: { value: sparkTex },+ },+ vertexShader: PARTICLE_VERT,+ fragmentShader: PARTICLE_FRAG,+ transparent: true,+ depthWrite: false,+ blending: THREE.AdditiveBlending,+ });+ const pts = new THREE.Points(geom, mat);+ pts.frustumCulled = false;+ scene.add(pts);+ particles.points = pts;+ particles.geom = geom;+ particles.mat = mat;+ }++ // Find the next free slot; if the pool is saturated, recycle the oldest+ // (round-robin) so we never allocate beyond the cap.+ function acquireParticle() {+ const N = particles.count;+ for (let k = 0; k < N; k++) {+ const i = (particles.cursor + k) % N;+ if (!particles.active[i]) {+ particles.cursor = (i + 1) % N;+ return i;+ }+ }+ const i = particles.cursor;+ particles.cursor = (i + 1) % N;+ return i;+ }++ function emitParticle(from, to, color, dur, size) {+ const i = acquireParticle();+ particles.active[i] = 1;+ particles.t[i] = 0;+ particles.dur[i] = dur;+ particles.from[i].copy(from);+ particles.to[i].copy(to);+ particles.baseSize[i] = size;+ const col = particles.geom.getAttribute('aColor');+ col.setXYZ(i, color.r, color.g, color.b);+ col.needsUpdate = true;+ }++ function updateParticles(dt) {+ if (!particles.points) return;+ const posAttr = particles.geom.getAttribute('position');+ const sizeAttr = particles.geom.getAttribute('aSize');+ const alphaAttr = particles.geom.getAttribute('aAlpha');+ const N = particles.count;+ const tmp = updateParticles._tmp || (updateParticles._tmp = new THREE.Vector3());+ const ctrl = updateParticles._ctrl || (updateParticles._ctrl = new THREE.Vector3());+ let live = 0;+ for (let i = 0; i < N; i++) {+ if (!particles.active[i]) {+ alphaAttr.setX(i, 0);+ continue;+ }+ live++;+ particles.t[i] += dt / particles.dur[i];+ const t = particles.t[i];+ if (t >= 1) {+ particles.active[i] = 0;+ alphaAttr.setX(i, 0);+ continue;+ }+ const e = easeInOut(t);+ // Curve the streak: lift it out of the straight chord toward the core+ // plane so flows arc gracefully rather than slicing through center.+ const from = particles.from[i];+ const to = particles.to[i];+ ctrl.copy(from).add(to).multiplyScalar(0.5);+ ctrl.multiplyScalar(0.62); // bend toward the core+ ctrl.y += from.length() * 0.18;+ // Quadratic Bézier(from, ctrl, to).+ const mt = 1 - e;+ tmp.copy(from).multiplyScalar(mt * mt);+ tmp.addScaledVector(ctrl, 2 * mt * e);+ tmp.addScaledVector(to, e * e);+ posAttr.setXYZ(i, tmp.x, tmp.y, tmp.z);+ // Fade in fast, linger, fade out; pulse the size near arrival.+ const fade = Math.sin(Math.PI * easeOut(t));+ alphaAttr.setX(i, fade);+ sizeAttr.setX(i, particles.baseSize[i] * (0.7 + 0.6 * fade));+ }+ posAttr.needsUpdate = true;+ sizeAttr.needsUpdate = true;+ alphaAttr.needsUpdate = true;+ return live;+ }++ // ── Camera moves (galaxy.js style) ─────────────────────────────────────────+ function flyTo(toPos, toTgt, dur = 0.9) {+ fly.fromPos.copy(camera.position);+ fly.fromTgt.copy(controls.target);+ fly.toPos.copy(toPos);+ fly.toTgt.copy(toTgt);+ fly.dur = Math.max(0.001, dur);+ fly.t = 0;+ fly.active = true;+ controls.autoRotate = false;+ }+ // Glide closer to a target along the current view direction.+ function flyToTarget(target, dist) {+ const dir = new THREE.Vector3().subVectors(camera.position, controls.target);+ if (dir.lengthSq() < 1e-6) dir.set(0, 0.2, 1);+ dir.normalize().multiplyScalar(dist);+ flyTo(new THREE.Vector3().addVectors(target, dir), target.clone(), 0.9);+ }++ // ── Render loop (render-on-demand via setAnimationLoop; paused when hidden) ─+ let running = true;+ function tick() {+ if (!running) return;+ const dt = Math.min(0.05, clock.getDelta());+ const t = clock.getElapsed();++ if (state.nodeMat) state.nodeMat.uniforms.uTime.value = t;++ // Core breathing: subtle scale + emissive pulse (still under reduced motion,+ // but very gentle).+ if (state.coreGroup) {+ const breathe = reducedMotion ? 0 : 0.06 * Math.sin(t * 1.4);+ state.coreGroup.scale.setScalar(1 + breathe);+ if (!reducedMotion) state.coreMesh.rotation.y += dt * 0.18;+ if (state.coreMat) state.coreMat.emissiveIntensity = 1.5 + (reducedMotion ? 0 : 0.4 * (0.5 + 0.5 * Math.sin(t * 1.4)));+ if (state.coreHalo) state.coreHalo.scale.setScalar(170 * (1 + breathe * 1.4));+ }+ if (state.ambient && !reducedMotion) state.ambient.rotation.y += dt * 0.01;++ updateParticles(dt);++ if (fly.active) {+ fly.t = Math.min(1, fly.t + dt / fly.dur);+ const e = easeInOut(fly.t);+ camera.position.lerpVectors(fly.fromPos, fly.toPos, e);+ controls.target.lerpVectors(fly.fromTgt, fly.toTgt, e);+ if (fly.t >= 1) {+ fly.active = false;+ scheduleIdle();+ }+ }++ controls.update();+ renderer.render(scene, camera);+ }++ // Pause the loop when the tab is hidden to save battery/GPU.+ function onVisibility() {+ if (document.hidden) {+ renderer.setAnimationLoop(null);+ } else if (running) {+ clock.getDelta(); // discard the gap so animations don't jump+ renderer.setAnimationLoop(tick);+ }+ }+ document.addEventListener('visibilitychange', onVisibility);++ // ── Public API ─────────────────────────────────────────────────────────────+ function setData({ three, agents } = {}) {+ disposeSceneContent();+ state.three = three || { symbol: '$THREE' };++ const list = Array.isArray(agents) ? agents.filter((a) => a && a.id != null) : [];+ state.agents = layoutAgents(list);++ buildCore();+ if (state.agents.length) {+ buildLinks(state.agents);+ buildNodes(state.agents);+ }+ buildParticles();++ // Frame the whole field on first build.+ flyTo(new THREE.Vector3(0, 90, 640), new THREE.Vector3(0, 0, 0), 0.001);+ dbg.agentCount = state.agents.length;+ dbg.ready = true;+ }++ function pulse(event = {}) {+ if (!particles.points) return;+ const type = event.type || 'payment';+ const color = PALETTE.event[type] || PALETTE.event.payment;+ const core = new THREE.Vector3(0, 0, 0);++ // Resolve the agent endpoint; fall back to a random node so a streak still+ // fires for events with no agent attached (keeps the field alive).+ let node = null;+ if (event.agentId != null && state.idToIndex.has(event.agentId)) {+ node = state.agents[state.idToIndex.get(event.agentId)];+ } else if (state.agents.length) {+ node = state.agents[(Math.random() * state.agents.length) | 0];+ }+ const nodePos = node ? node.position : new THREE.Vector3(0, 120, 0);++ // Streak size scales gently with amount; graduations/buybacks read bigger.+ const amt = Math.max(0, event.amountUsdc || 0);+ const amtBoost = amt ? Math.min(1, Math.log1p(amt) / Math.log1p(5000)) : 0;+ let size = 18 + 26 * amtBoost;+ let dur = 1.1;++ // Direction & character per event type.+ switch (type) {+ case 'launch':+ // New creation emits OUTWARD from the agent into the field.+ emitParticle(nodePos, outwardPoint(nodePos), color, 1.0, size);+ break;+ case 'graduation':+ // A milestone: a bright burst flowing core ↔ node, slightly larger.+ size += 12;+ dur = 1.4;+ emitParticle(nodePos, core, color, dur, size);+ emitParticle(core, nodePos, color, dur * 0.9, size * 0.7);+ break;+ case 'buyback':+ // Value flows IN to the $THREE core (buyback pressure).+ emitParticle(nodePos, core, color, 1.2, size);+ break;+ case 'payment':+ default:+ // Payments flow IN to the core as well, cyan-tinted.+ emitParticle(nodePos, core, color, dur, size);+ break;+ }+ dbg.pulseCount++;+ }++ // A point flung outward from a node, away from the core, for launch streaks.+ function outwardPoint(nodePos) {+ const dir = nodePos.clone();+ if (dir.lengthSq() < 1e-6) dir.set(0, 1, 0);+ dir.normalize();+ return nodePos.clone().addScaledVector(dir, 140 + Math.random() * 120);+ }++ function focusAgent(id) {+ if (id == null || !state.idToIndex.has(id)) {+ // Return to overview.+ if (state.nodeMat) state.nodeMat.uniforms.uFocus.value = -1;+ flyTo(new THREE.Vector3(0, 90, 640), new THREE.Vector3(0, 0, 0), 1.1);+ return;+ }+ const idx = state.idToIndex.get(id);+ const a = state.agents[idx];+ if (state.nodeMat) state.nodeMat.uniforms.uFocus.value = idx;+ flyToTarget(a.position, 130);+ }++ function getAgentAtPointer(clientX, clientY) {+ if (!state.nodes) return null;+ const rect = renderer.domElement.getBoundingClientRect();+ if (rect.width === 0 || rect.height === 0) return null;+ pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;+ pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;+ raycaster.setFromCamera(pointer, camera);+ const hits = raycaster.intersectObject(state.nodes, false);+ if (!hits.length) return null;+ const a = state.agents[hits[0].index];+ return a ? a.id : null;+ }++ function resize() {+ const parent = renderer.domElement.parentElement;+ const w = (parent && parent.clientWidth) || renderer.domElement.clientWidth || window.innerWidth;+ const h = (parent && parent.clientHeight) || renderer.domElement.clientHeight || window.innerHeight;+ if (!w || !h) return;+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ }++ function setReducedMotion(bool) {+ reducedMotion = !!bool;+ controls.autoRotate = !reducedMotion;+ if (reducedMotion) {+ clearTimeout(idleTimer);+ controls.autoRotate = false;+ } else {+ scheduleIdle();+ }+ if (state.nodeMat) state.nodeMat.uniforms.uTwinkle.value = reducedMotion ? 0 : 1;+ }++ // ── Teardown ───────────────────────────────────────────────────────────────+ // Dispose scene content (nodes, links, core, particles) without killing the+ // renderer — used by setData() for safe rebuilds and by dispose().+ function disposeSceneContent() {+ const drop = (obj, ...extra) => {+ if (!obj) return;+ scene.remove(obj);+ obj.geometry?.dispose?.();+ if (obj.material) {+ if (Array.isArray(obj.material)) obj.material.forEach((m) => m.dispose());+ else obj.material.dispose();+ }+ for (const d of extra) d?.dispose?.();+ };++ drop(state.nodes);+ state.nodes = state.nodeGeom = state.nodeMat = null;+ drop(state.links);+ state.links = state.linkGeom = state.linkMat = null;+ drop(particles.points);+ particles.points = particles.geom = particles.mat = null;+ particles.active.fill(0);++ if (state.coreGroup) {+ scene.remove(state.coreGroup);+ for (const d of state.coreGroup.userData.disposables || []) d?.dispose?.();+ state.coreGroup.traverse((o) => {+ o.geometry?.dispose?.();+ if (o.material && !Array.isArray(o.material)) o.material.dispose?.();+ });+ state.coreGroup = state.coreMesh = state.coreMat = null;+ state.coreHalo = state.coreHaloMat = null;+ }+ // Strip ambient lights added alongside the core so they don't accumulate.+ for (const o of [...scene.children]) {+ if (o.isAmbientLight) scene.remove(o);+ }+ }++ function dispose() {+ running = false;+ try {+ clearTimeout(idleTimer);+ renderer.setAnimationLoop(null);+ document.removeEventListener('visibilitychange', onVisibility);+ controls.dispose();++ disposeSceneContent();++ drop(state.starfield);+ state.starfield = state.starMat = null;+ drop(state.ambient);+ state.ambient = state.ambientMat = null;++ glowTex.dispose();+ sparkTex.dispose();+ renderer.dispose();+ } catch {+ /* best-effort teardown */+ }+ if (window.__pulseScene === controller) delete window.__pulseScene;++ function drop(obj) {+ if (!obj) return;+ scene.remove(obj);+ obj.geometry?.dispose?.();+ obj.material?.dispose?.();+ }+ }++ // ── Boot the loop ──────────────────────────────────────────────────────────+ buildBackground();+ resize();+ renderer.setAnimationLoop(tick);++ // Public debug/verification surface.+ const dbg = {+ ready: false,+ agentCount: 0,+ pulseCount: 0,+ get particlesLive() {+ let n = 0;+ for (let i = 0; i < particles.count; i++) n += particles.active[i];+ return n;+ },+ camera,+ scene,+ focus: (id) => focusAgent(id),+ emit: (type, agentId, amountUsdc) => pulse({ type, agentId, amountUsdc }),+ };++ const controller = {+ setData,+ pulse,+ focusAgent,+ getAgentAtPointer,+ resize,+ setReducedMotion,+ dispose,+ debug: dbg,+ };++ // Tiny debug handle for browser-console verification.+ window.__pulseScene = controller;++ return controller;+}++// ── Shaders ────────────────────────────────────────────────────────────────────+// Agent nodes: soft additive glow, gentle twinkle, size attenuates with distance,+// focused node pulses brighter.+const NODE_VERT = /* glsl */ `+ attribute vec3 aColor;+ attribute float aSize;+ attribute float aSeed;+ attribute float aBright;+ uniform float uTime;+ uniform float uPixelRatio;+ uniform float uTwinkle;+ uniform float uFocus;+ varying vec3 vColor;+ varying float vBright;+ void main() {+ vColor = aColor;+ vBright = aBright;+ vec4 mv = modelViewMatrix * vec4(position, 1.0);+ float size = aSize;+ size *= 1.0 + uTwinkle * 0.14 * sin(uTime * 1.5 + aSeed * 6.2831);+ // Focused node pulses larger/brighter.+ float focused = step(0.5, 1.0 - abs(float(gl_VertexID) - uFocus));+ size *= mix(1.0, 1.9 + 0.5 * sin(uTime * 4.0), focused);+ vBright += focused * 0.6;+ float dist = max(-mv.z, 1.0);+ gl_PointSize = clamp(size * (320.0 / dist), 1.0, 80.0) * uPixelRatio;+ gl_Position = projectionMatrix * mv;+ }+`;+const NODE_FRAG = /* glsl */ `+ precision mediump float;+ uniform sampler2D uTex;+ varying vec3 vColor;+ varying float vBright;+ void main() {+ vec4 tex = texture2D(uTex, gl_PointCoord);+ float a = tex.a;+ if (a < 0.01) discard;+ // Hot white core fading to the agent's reputation color at the edges.+ vec3 col = mix(vColor, vec3(1.0), pow(a, 2.5) * 0.6);+ gl_FragColor = vec4(col * (0.5 + vBright), a);+ }+`;++// Connection tethers: per-vertex alpha so the line fades from core to node.+const LINK_VERT = /* glsl */ `+ attribute float aAlpha;+ varying float vAlpha;+ void main() {+ vAlpha = aAlpha;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+`;+const LINK_FRAG = /* glsl */ `+ precision mediump float;+ uniform vec3 uColor;+ varying float vAlpha;+ void main() {+ gl_FragColor = vec4(uColor, vAlpha);+ }+`;++// Event streaks: textured additive sparks; per-particle color/size/alpha.+const PARTICLE_VERT = /* glsl */ `+ attribute vec3 aColor;+ attribute float aSize;+ attribute float aAlpha;+ uniform float uPixelRatio;+ varying vec3 vColor;+ varying float vAlpha;+ void main() {+ vColor = aColor;+ vAlpha = aAlpha;+ vec4 mv = modelViewMatrix * vec4(position, 1.0);+ float dist = max(-mv.z, 1.0);+ gl_PointSize = clamp(aSize * (340.0 / dist), 1.0, 110.0) * uPixelRatio;+ gl_Position = projectionMatrix * mv;+ }+`;+const PARTICLE_FRAG = /* glsl */ `+ precision mediump float;+ uniform sampler2D uTex;+ varying vec3 vColor;+ varying float vAlpha;+ void main() {+ if (vAlpha < 0.01) discard;+ vec4 tex = texture2D(uTex, gl_PointCoord);+ float a = tex.a * vAlpha;+ vec3 col = mix(vColor, vec3(1.0), pow(tex.a, 3.0) * 0.7);+ gl_FragColor = vec4(col, a);+ }+`;diff --git a/src/walk-embed-events.js b/src/walk-embed-events.jsnew file mode 100644index 000000000..f98d137b3--- /dev/null+++ b/src/walk-embed-events.js@@ -0,0 +1,190 @@+// walk-embed-events.js — the bi-directional postMessage contract between a host+// page and the three.ws walk-embed iframe.+//+// This is the single source of truth for the event protocol. Both sides of the+// boundary import (or, for the standalone SDK, mirror) the constants and helpers+// here so the wire format can never drift between the iframe and the host.+//+// ── Envelope ───────────────────────────────────────────────────────────────+// Every message is a plain object:+// {+// channel: 'three-walk', // namespace guard — ignore anything else+// v: 1, // protocol version+// type: 'walk:moved', // see INBOUND / OUTBOUND below+// id?: '<correlation id>', // echoes a command id on its result event+// ...payload // type-specific fields+// }+// The legacy flat `{ type: 'walk:*' }` shape (no channel/version) is still+// accepted on the inbound side for backward compatibility with embeds shipped+// before this module existed — see isWalkMessage().+//+// ── Handshake ──────────────────────────────────────────────────────────────+// iframe → host : walk:loaded (once, when the avatar is ready)+// host → iframe: walk:ping (optional) → iframe replies walk:loaded again+// A host that mounts the iframe after it has already loaded can fire walk:ping+// to re-trigger the ready event instead of racing the initial walk:loaded.++export const CHANNEL = 'three-walk';+export const PROTOCOL_VERSION = 1;++// Commands a host sends INTO the iframe.+export const INBOUND = Object.freeze({+ PING: 'walk:ping',+ MOVE: 'walk:move', // { x, y, run? } analog vector, OR { dir, meters? } discrete+ GESTURE: 'walk:gesture', // { gesture: 'wave' | 'jump' | 'idle' | 'walk' | 'run' }+ SAY: 'walk:say', // { text, durationMs? }+ SET_ENVIRONMENT: 'walk:setEnvironment', // { env }+ SET_AVATAR: 'walk:setAvatar', // { id }+ SET_CONFIG: 'walk:config', // { speed? }+ RESET: 'walk:reset',+});++// Events the iframe emits OUT to the host.+export const OUTBOUND = Object.freeze({+ LOADED: 'walk:loaded', // { avatar }+ MOVED: 'walk:moved', // { x, z, yaw, motion }+ SPOKE: 'walk:spoke', // { text }+ GESTURE: 'walk:gestured', // { gesture }+ ENVIRONMENT: 'walk:environment', // { env }+ AVATAR_CHANGED: 'walk:avatarChanged', // { id }+ ERROR: 'walk:error', // { error, code? }+});++// ── Legacy aliases ───────────────────────────────────────────────────────────+// Older embeds spoke walk:ready / walk:position / walk:narrate / walk:setEnv /+// walk:setMotion. We accept those names on input and (for the two outbound ones+// hosts may already listen for) also emit them, so no existing integration+// breaks when this contract lands.+const INBOUND_ALIASES = Object.freeze({+ 'walk:setEnv': INBOUND.SET_ENVIRONMENT,+ 'walk:setMotion': INBOUND.GESTURE,+ 'walk:narrate': INBOUND.SAY,+ 'walk:resetPose': INBOUND.RESET,+});++const ALL_INBOUND = new Set([...Object.values(INBOUND), ...Object.keys(INBOUND_ALIASES)]);+const ALL_OUTBOUND = new Set(Object.values(OUTBOUND));+const ALL_TYPES = new Set([...ALL_INBOUND, ...ALL_OUTBOUND, 'walk:ready', 'walk:position', 'walk:narrateEnd']);++// ── Origin allow-listing ─────────────────────────────────────────────────────+// The walk embed is designed to be dropped onto ANY origin (it ships+// `frame-ancestors *`), so the host page's origin can be anything. We therefore+// cannot allow-list the host. What we DO validate is the message *source*: the+// iframe only accepts messages whose source window is its own parent, and the+// host SDK only accepts messages whose source is the iframe it mounted. That+// source check (done by the caller) is the real authentication; the optional+// `allowedOrigins` list below is a belt-and-suspenders filter a security-+// conscious integrator can opt into when they know the embed's exact origin.+export function makeOriginAllowList(origins) {+ if (!origins || origins === '*') return () => true;+ const set = new Set((Array.isArray(origins) ? origins : [origins]).map(normalizeOrigin));+ return (origin) => origin === 'null' /* sandboxed/file iframe */ || set.has(normalizeOrigin(origin));+}++function normalizeOrigin(o) {+ try {+ return new URL(o).origin;+ } catch {+ return String(o || '');+ }+}++// ── Envelope helpers ──────────────────────────────────────────────────────────+export function makeMessage(type, payload = {}, { id } = {}) {+ const msg = { channel: CHANNEL, v: PROTOCOL_VERSION, type, ...payload };+ if (id) msg.id = id;+ return msg;+}++// Is this a message we should handle at all? Accepts the new channelled+// envelope AND the legacy flat `walk:*` shape so old hosts keep working.+export function isWalkMessage(data) {+ if (!data || typeof data !== 'object') return false;+ if (data.channel === CHANNEL) return typeof data.type === 'string';+ // Legacy: any object whose `type` is a known walk event.+ return typeof data.type === 'string' && ALL_TYPES.has(data.type);+}++// Normalize an inbound command to its canonical type, resolving legacy aliases.+export function canonicalInboundType(type) {+ if (INBOUND_ALIASES[type]) return INBOUND_ALIASES[type];+ return ALL_INBOUND.has(type) ? type : null;+}++// ── Inbound command validation (runs inside the iframe) ──────────────────────+// Returns { type, payload } on success or { error } describing the rejection.+// Trusts nothing: clamps numbers, bounds strings, rejects unknown shapes. This+// is the boundary between the untrusted host page and the embed's runtime.+const ENV_IDS = new Set(['studio', 'void', 'beach', 'sunset', 'night', 'grid']);+const GESTURES = new Set(['idle', 'walk', 'run', 'wave', 'jump']);+const DIRECTIONS = new Set(['forward', 'back', 'left', 'right']);+const SAY_MAX = 280;++export function validateInbound(raw) {+ const type = canonicalInboundType(raw?.type);+ if (!type) return { error: `unknown command: ${raw?.type}` };+ const id = typeof raw.id === 'string' ? raw.id.slice(0, 64) : undefined;++ switch (type) {+ case INBOUND.PING:+ case INBOUND.RESET:+ return { type, id, payload: {} };++ case INBOUND.MOVE: {+ // Two accepted shapes: analog { x, y, run } or discrete { dir, meters }.+ if (typeof raw.dir === 'string') {+ if (!DIRECTIONS.has(raw.dir)) return { error: `move.dir must be one of ${[...DIRECTIONS].join('/')}` };+ const meters = clamp(num(raw.meters, 1), 0, 12);+ return { type, id, payload: { dir: raw.dir, meters } };+ }+ const x = clamp(num(raw.x, 0), -1, 1);+ const y = clamp(num(raw.y, 0), -1, 1);+ const run = raw.run === true;+ return { type, id, payload: { x, y, run } };+ }++ case INBOUND.GESTURE: {+ const g = raw.gesture ?? raw.motion; // legacy walk:setMotion used `motion`+ if (!GESTURES.has(g)) return { error: `gesture must be one of ${[...GESTURES].join('/')}` };+ return { type, id, payload: { gesture: g } };+ }++ case INBOUND.SAY: {+ const text = typeof raw.text === 'string' ? raw.text.slice(0, SAY_MAX) : '';+ if (!text.trim()) return { error: 'say.text required' };+ const durationMs = raw.durationMs == null ? undefined : clamp(num(raw.durationMs, 0), 800, 20000);+ return { type, id, payload: { text, durationMs } };+ }++ case INBOUND.SET_ENVIRONMENT: {+ const e = String(raw.env || '').toLowerCase();+ if (!ENV_IDS.has(e)) return { error: `env must be one of ${[...ENV_IDS].join('/')}` };+ return { type, id, payload: { env: e } };+ }++ case INBOUND.SET_AVATAR: {+ const avatarId = typeof raw.id === 'string' ? raw.id : (typeof raw.avatar === 'string' ? raw.avatar : '');+ // `id` here is the avatar id, which doubles as the correlation id slot —+ // keep them separate: avatar id can be a URL/uuid, correlation id is short.+ if (!avatarId || avatarId.length > 2048) return { error: 'setAvatar.id required' };+ return { type, id: undefined, payload: { id: avatarId } };+ }++ case INBOUND.SET_CONFIG: {+ const payload = {};+ if (raw.speed != null) payload.speed = clamp(num(raw.speed, 1), 0.3, 3);+ return { type, id, payload };+ }++ default:+ return { error: `unhandled command: ${type}` };+ }+}++function num(v, fallback) {+ const n = typeof v === 'number' ? v : Number(v);+ return Number.isFinite(n) ? n : fallback;+}+function clamp(n, lo, hi) {+ return Math.min(hi, Math.max(lo, n));+}diff --git a/src/walk-embed.js b/src/walk-embed.jsindex cb911b31b..4bda8fa51 100644--- a/src/walk-embed.js+++ b/src/walk-embed.js@@ -38,6 +38,16 @@ import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';import { log } from './shared/log.js';+import {+ CHANNEL,+ PROTOCOL_VERSION,+ INBOUND,+ OUTBOUND,+ makeMessage,+ makeOriginAllowList,+ isWalkMessage,+ validateInbound,+} from './walk-embed-events.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';@@ -85,6 +95,11 @@ const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';const CLIP_IDLE = 'idle';const CLIP_WALK = 'av-walk-feminine';const CLIP_RUN = 'av-walk-feminine'; // no separate run clip; timeScale handles pace difference+// One-shot gesture clips, driven by the `walk:gesture` host command. Mapped to+// real manifest clip names; playOnce settles back to idle when each finishes.+const GESTURE_CLIPS = { wave: 'wave', jump: 'av-superhero-jump' };+// Clip names the embed must have resident for locomotion + gestures.+const REQUIRED_CLIPS = new Set([CLIP_IDLE, CLIP_WALK, CLIP_RUN, ...Object.values(GESTURE_CLIPS)]);const WALK_SPEED = 1.6;const RUN_SPEED = 4.0;@@ -126,14 +141,27 @@ function setStatus(text, { error = false, sticky = false } = {}) {}// ── postMessage bridge to host page ──────────────────────────────────────-// The host frame learns about embed lifecycle + avatar position via-// window.postMessage. We post to window.parent only when it's a different-// window (i.e. we're actually inside an iframe). Direct page loads still-// work — they just don't emit messages.+// The host frame learns about embed lifecycle + avatar position via the typed+// walk-embed-events contract (src/walk-embed-events.js). We post to window.parent+// only when it's a different window (i.e. we're actually inside an iframe).+// Direct page loads still work — they just don't emit messages.+//+// `?targetOrigin=` lets a security-conscious host pin the exact origin we post+// to; default '*' keeps the embed droppable on any site (it ships+// frame-ancestors *). The inbound source check below is the real authentication.const INSIDE_IFRAME = window.parent && window.parent !== window;-function postToHost(payload) {+const TARGET_ORIGIN = params.get('targetOrigin') || '*';+const isOriginAllowed = makeOriginAllowList(params.get('allowOrigins')?.split(',').map((s) => s.trim()).filter(Boolean) || '*');++// Emit a typed outbound event. `legacy` (optional) is the pre-contract message+// shape we still emit alongside the new one so integrations written against+// walk:ready / walk:position keep receiving events during the transition.+function emit(type, payload = {}, legacy = null) {if (!INSIDE_IFRAME) return;- try { window.parent.postMessage(payload, '*'); } catch {}+ try {+ window.parent.postMessage(makeMessage(type, payload), TARGET_ORIGIN);+ if (legacy) window.parent.postMessage(legacy, TARGET_ORIGIN);+ } catch {}}// ── Renderer / scene ──────────────────────────────────────────────────────@@ -284,9 +312,25 @@ const input = {keys: { forward: 0, back: 0, left: 0, right: 0, run: false },joy: { x: 0, y: 0, active: false },autoplay: { active: false, t: 0 },+ // Programmatic vector, set by the `walk:move` host command (analog form).+ // Persists until the host sends move {x:0,y:0} or any live input overrides it.+ cmd: { x: 0, y: 0, run: false, active: false },+ // Scripted discrete move ({ dir, meters }) — walks a fixed distance then stops.+ // `remaining` counts down in metres each frame; `vx/vy` is the unit heading.+ scripted: { remaining: 0, vx: 0, vy: 0, run: false },_speedMultiplier: 1.0,};+// Map a discrete direction to a camera-relative input vector. forward/back use+// the y axis (joystick up = forward), left/right the x axis — same convention+// readMoveInput already resolves against the camera heading.+const DIR_VECTORS = {+ forward: { vx: 0, vy: 1 },+ back: { vx: 0, vy: -1 },+ left: { vx: -1, vy: 0 },+ right: { vx: 1, vy: 0 },+};+if (CONTROLS === 'keyboard' || CONTROLS === 'joystick') {window.addEventListener('keydown', (e) => {switch (e.code) {@@ -378,11 +422,9 @@ async function loadAvatar() {if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`);return r.json();});- const needed = manifest.filter((d) =>- d.name === CLIP_IDLE || d.name === CLIP_WALK || d.name === CLIP_RUN,- );- if (needed.length === 0) {- throw new Error('Animation manifest missing idle/walking/running clips');+ const needed = manifest.filter((d) => REQUIRED_CLIPS.has(d.name));+ if (!needed.some((d) => d.name === CLIP_IDLE) || !needed.some((d) => d.name === CLIP_WALK)) {+ throw new Error('Animation manifest missing idle/walking clips');}animationManager.setAnimationDefs(needed);await animationManager.loadAll();@@ -396,7 +438,7 @@ async function loadAvatar() {}setStatus('walk it');- postToHost({ type: 'walk:ready', avatar: avatarUrl });+ emit(OUTBOUND.LOADED, { avatar: avatarUrl }, { type: 'walk:ready', avatar: avatarUrl });}// ── Resize ────────────────────────────────────────────────────────────────@@ -418,12 +460,24 @@ const moveRight = new Vector3();const upY = new Vector3(0, 1, 0);function readMoveInput(dt) {- if (input.joy.active) return { ix: input.joy.x, iy: input.joy.y };+ // Live input always wins and cancels any programmatic drive so a human can+ // grab control mid-script.+ if (input.joy.active) { input.scripted.remaining = 0; input.cmd.active = false; return { ix: input.joy.x, iy: input.joy.y, run: false }; }if (CONTROLS !== 'none') {const ix = input.keys.right - input.keys.left;const iy = input.keys.forward - input.keys.back;- if (ix || iy) return { ix, iy };+ if (ix || iy) { input.scripted.remaining = 0; input.cmd.active = false; return { ix, iy, run: input.keys.run }; }+ }+ // Scripted discrete move: walk a fixed distance then stop. Decrement by the+ // per-frame distance the loop will actually travel (speed × dt) so `meters`+ // maps to real world distance regardless of frame rate.+ if (input.scripted.remaining > 0) {+ const pace = (input.scripted.run ? RUN_SPEED : WALK_SPEED) * (input._speedMultiplier || 1.0);+ input.scripted.remaining = Math.max(0, input.scripted.remaining - pace * dt);+ return { ix: input.scripted.vx, iy: input.scripted.vy, run: input.scripted.run };}+ // Held analog vector from `walk:move`.+ if (input.cmd.active) return { ix: input.cmd.x, iy: input.cmd.y, run: input.cmd.run };if (input.autoplay.active) {// Lazy "walk in a slow circle" pattern — readable, non-distracting,// and keeps the avatar within the visible ground disc no matter how@@ -526,13 +580,13 @@ function tick() {) {lastBroadcastX = avatarRig.position.x;lastBroadcastZ = avatarRig.position.z;- postToHost({- type: 'walk:position',+ const pos = {x: avatarRig.position.x,z: avatarRig.position.z,yaw: avatarYaw,motion: currentMotion,- });+ };+ emit(OUTBOUND.MOVED, pos, { type: 'walk:position', ...pos });}renderer.render(scene, camera);diff --git a/src/widgets/passport.js b/src/widgets/passport.jsindex 644f9f878..7898c6d5c 100644--- a/src/widgets/passport.js+++ b/src/widgets/passport.js@@ -179,10 +179,11 @@ async function _refresh(state, panel) {const symbol = symbolRes.status === 'fulfilled' ? symbolRes.value : '';let reputationData = null;if (repRes.status === 'fulfilled' && repRes.value) {- const [total, count] = repRes.value;+ // getReputation returns (avgX100, count) — already averaged ×100 on-chain.+ // Divide for display; never re-divide by count.+ const [avgX100, count] = repRes.value;const n = Number(count);- const t = Number(total);- reputationData = { total: t, count: n, average: n === 0 ? 0 : t / n };+ reputationData = { count: n, average: n === 0 ? 0 : Number(avgX100) / 100 };}let feedback = [];diff --git a/tests/onchain-parity.test.js b/tests/onchain-parity.test.jsnew file mode 100644index 000000000..9d248e54c--- /dev/null+++ b/tests/onchain-parity.test.js@@ -0,0 +1,105 @@+// Guards the ERC-8004 EVM registry address surface. The same registry addresses+// are hand-duplicated across three sources that can silently drift:+// 1. src/erc8004/abi.js — REGISTRY_DEPLOYMENTS (browser/client)+// 2. sdk/src/erc8004/abi.js — REGISTRY_DEPLOYMENTS (published SDK)+// 3. api/_lib/erc8004-chains.js — CHAINS[].registry + .validationRegistry+//+// A drift sends registrations / reputation / validation writes to the wrong (or+// zero) contract. The same parity check gates the Vercel build+// (scripts/build-vercel.mjs phase 1, `verify:onchain`); running it here means+// `npm test` catches a drift before a push. The live bytecode sweep is exercised+// by the CLI (`npm run verify:onchain`), not here — unit tests stay offline and+// deterministic.++import { describe, it, expect, beforeAll } from 'vitest';+import {+ loadSources,+ checkParity,+ resolveLiveChains,+} from '../scripts/verify-onchain-parity.mjs';++let sources;+beforeAll(async () => {+ ({ sources } = await loadSources());+});++describe('onchain parity · the three sources agree today', () => {+ it('loadSources returns all three registry sources', () => {+ expect(Object.keys(sources).sort()).toEqual([+ 'api/_lib/erc8004-chains.js',+ 'sdk/src/erc8004/abi.js',+ 'src/erc8004/abi.js',+ ]);+ });++ it('checkParity reports zero problems on the real repo', () => {+ const { problems } = checkParity(sources);+ expect(problems).toEqual([]);+ });++ it('produces a merged map of real (non-null) addresses for the live sweep', () => {+ const { merged } = checkParity(sources);+ // Base mainnet (8453) + Base Sepolia (84532) are the build-gate live targets.+ expect(merged[8453]?.identityRegistry).toMatch(/^0x[0-9a-fA-F]{40}$/);+ expect(merged[8453]?.reputationRegistry).toMatch(/^0x[0-9a-fA-F]{40}$/);+ expect(merged[84532]?.validationRegistry).toMatch(/^0x[0-9a-fA-F]{40}$/);+ // ValidationRegistry is not yet on mainnet — it must be absent, not zero.+ expect(merged[8453]?.validationRegistry).toBeUndefined();+ });+});++describe('onchain parity · detects injected drift', () => {+ it('catches a mismatched address across two sources', () => {+ const drifted = structuredClone(sources);+ drifted['src/erc8004/abi.js'][8453] = {+ ...drifted['src/erc8004/abi.js'][8453],+ identityRegistry: '0x000000000000000000000000000000000000dEaD',+ };+ const { problems } = checkParity(drifted);+ expect(problems.length).toBeGreaterThan(0);+ expect(problems.some((p) => p.type === 'mismatch' && p.kind === 'identityRegistry')).toBe(+ true,+ );+ });++ it('catches the ValidationRegistry null-vs-address drift trap', () => {+ const drifted = structuredClone(sources);+ // Give mainnet Base a validationRegistry in src but leave sdk null — the+ // exact trap the guard exists to catch (one source live, another absent).+ drifted['src/erc8004/abi.js'][8453] = {+ ...drifted['src/erc8004/abi.js'][8453],+ validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB4272',+ };+ const { problems } = checkParity(drifted);+ expect(problems.some((p) => p.type === 'drift-trap' && p.kind === 'validationRegistry')).toBe(+ true,+ );+ });++ it('catches a chainId present in one source but missing from another', () => {+ const drifted = structuredClone(sources);+ delete drifted['sdk/src/erc8004/abi.js'][8453];+ const { problems } = checkParity(drifted);+ expect(problems.some((p) => p.type === 'chain-set' && p.chainId === 8453)).toBe(true);+ });+});++describe('onchain parity · live-chain selection', () => {+ const ALL = [1, 8453, 84532, 42161];++ it('defaults to Base mainnet + Base Sepolia', () => {+ expect(resolveLiveChains({}, ALL)).toEqual([8453, 84532]);+ });++ it('"none" disables the live sweep', () => {+ expect(resolveLiveChains({ VERIFY_ONCHAIN_CHAINS: 'none' }, ALL)).toEqual([]);+ });++ it('"all" sweeps every known chain', () => {+ expect(resolveLiveChains({ VERIFY_ONCHAIN_CHAINS: 'all' }, ALL)).toEqual(ALL);+ });++ it('parses an explicit comma list', () => {+ expect(resolveLiveChains({ VERIFY_ONCHAIN_CHAINS: '1, 42161' }, ALL)).toEqual([1, 42161]);+ });+});diff --git a/vercel.json b/vercel.jsonindex e96ef8046..9525dac7e 100644--- a/vercel.json+++ b/vercel.json@@ -187,6 +187,12 @@"api/irl/report.js": {"maxDuration": 15},+ "api/irl/fix-token.js": {+ "maxDuration": 10+ },+ "api/irl/privacy.js": {+ "maxDuration": 20+ },"api/**/*.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 30@@ -2034,6 +2040,14 @@"src": "/api/irl/report","dest": "/api/irl/report.js"},+ {+ "src": "/api/irl/fix-token",+ "dest": "/api/irl/fix-token.js"+ },+ {+ "src": "/api/irl/privacy",+ "dest": "/api/irl/privacy.js"+ },{"src": "/api/copy/executions","dest": "/api/copy/executions.js"@@ -2494,6 +2508,10 @@"src": "/api/og/agent","dest": "/api/og/agent.js"},+ {+ "src": "/api/og/three-token-badge",+ "dest": "/api/og/three-token-badge.js"+ },{"src": "/agent/([^/]+)/edit","dest": "/agent-edit.html"diff --git a/vite.config.js b/vite.config.jsindex 6c0a0fbee..d1eb75513 100644--- a/vite.config.js+++ b/vite.config.js@@ -314,6 +314,8 @@ const appConfig = {'create-review': resolve(__dirname, 'pages/create-review.html'),'import-rpm': resolve(__dirname, 'pages/import-rpm.html'),marketplace: resolve(__dirname, 'pages/marketplace.html'),+ 'marketplace-analytics': resolve(__dirname, 'pages/marketplace-analytics.html'),+ collection: resolve(__dirname, 'pages/collection.html'),'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),'create-video': resolve(__dirname, 'pages/create/video.html'),