Skip to content

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

feat: add manage permissions panel and delegation toolkit

swarmsyycd29bb766d75
diff --git a/.env.example b/.env.example
index c07acb559..965e7ba04 100644
--- a/.env.example
+++ b/.env.example
@@ -67,7 +67,30 @@ VITE_AVATURN_DEVELOPER_ID=
# Unset or "none" → API returns 501 regen_unconfigured.
AVATAR_REGEN_PROVIDER=none
-# IPFS pinning — used by POST /api/pinning/pin before on-chain registration.
+# ── ERC-7710 Delegation Relayer (POST /api/permissions/redeem) ───────────────
+# Enable the server-side relayer endpoint (default: false).
+PERMISSIONS_RELAYER_ENABLED=false
+
+# Hex private key of the relayer EOA that pays gas for redeemDelegations.
+# This is NOT the user's key — only the agent's server-side relayer.
+# Generate: node -e "const {Wallet} = require('ethers'); const w = Wallet.createRandom(); console.log(w.privateKey, w.address)"
+# NEVER commit a real value. Rotate via Vercel env vars.
+AGENT_RELAYER_KEY=0x...
+
+# EIP-55 checksummed address derived from AGENT_RELAYER_KEY — fund with testnet ETH.
+AGENT_RELAYER_ADDRESS=0x...
+
+# Per-chain RPC URLs for DelegationManager calls.
+# Pattern: RPC_URL_<CHAINID>. Override the default public RPCs with Alchemy/Infura for production.
+RPC_URL_84532=https://sepolia.base.org # Base Sepolia (primary dev chain)
+RPC_URL_11155111=https://rpc.sepolia.org # Ethereum Sepolia
+
+# Per-chain DelegationManager contract address overrides (optional).
+# Defaults are from MetaMask Delegation Toolkit v1. Override if you deploy a custom instance.
+# DELEGATION_MANAGER_ADDRESS_84532=0x...
+# DELEGATION_MANAGER_ADDRESS_11155111=0x...
+
+# ── IPFS pinning — used by POST /api/pinning/pin before on-chain registration.
# Pinata (preferred): get JWT from https://app.pinata.cloud/keys
PINATA_JWT=
# Web3.Storage (fallback): get token from https://web3.storage/tokens
diff --git a/CLAUDE.md b/CLAUDE.md
index fdc2c9fc9..ca1043e50 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,171 +1,65 @@
# CLAUDE.md
-Root guidance for agents working in this repo. Read this first. Then read the scoped CLAUDE.md closest to the code you're touching.
+Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
----
-
-## How to work here
+**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
-1. **Move on your own.** You have broad permissions (see [.claude/settings.json](.claude/settings.json)). Don't ask before running builds, tests, formatters, git commits, or reads — just do them. Ask only before destructive ops, on-chain broadcasts, or production deploys.
-2. **Work hard, then verify.** Don't stop at "the build passed." Open the URL, click the thing, check the network tab, tail the log. If you can't actually test the change (e.g., no browser), say so — don't fake confidence.
-3. **Be intelligent about scope.** If a one-line fix needs a 200-line refactor to be safe, say so and ask. If the task is underspecified, pick the most useful interpretation and say which one.
-4. **Don't delete the user's work.** Unfamiliar files / branches / comments may be in-progress. Investigate before removing. Deny list in [.claude/settings.json](.claude/settings.json) blocks the worst footguns (`rm -rf`, `git reset --hard`, `git push --force`, `forge script --broadcast`, etc.) — don't try to bypass them.
-5. **One command to check yourself:** `npm run verify` (prettier + build). Run before reporting done.
+## 1. Think Before Coding
----
+**Don't assume. Don't hide confusion. Surface tradeoffs.**
-## What this repo is
+Before implementing:
+- State your assumptions explicitly. If uncertain, ask.
+- If multiple interpretations exist, present them - don't pick silently.
+- If a simpler approach exists, say so. Push back when warranted.
+- If something is unclear, stop. Name what's confusing. Ask.
-**3D Agent** is a browser-native glTF/GLB viewer that grew a full embodied-agent platform on top of it. Two halves, one codebase:
+## 2. Simplicity First
-- **Viewer** — client-side three.js app that renders glTF 2.0 / GLB with Draco, KTX2, Meshopt. 100% in-browser.
-- **Agent platform** — persona + memory + skills + wallet identity + ERC-8004 on-chain registration. LLM brain in `src/runtime/`, embodied rendering in `src/agent-avatar.js`, protocol bus in `src/agent-protocol.js`.
+**Minimum code that solves the problem. Nothing speculative.**
-Live at <https://3dagent.vercel.app>. Backend is Vercel serverless (`api/`) + Neon Postgres + Cloudflare R2 + Upstash Redis. Contracts are Foundry / Solidity 0.8.24.
+- No features beyond what was asked.
+- No abstractions for single-use code.
+- No "flexibility" or "configurability" that wasn't requested.
+- No error handling for impossible scenarios.
+- If you write 200 lines and it could be 50, rewrite it.
----
+Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
-## Directory map — where things live
+## 3. Surgical Changes
-| Path | What it is | Scoped doc |
-| ------------------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
-| [src/](src/) | Browser app — viewer + agent runtime + web component | [src/CLAUDE.md](src/CLAUDE.md) |
-| [api/](api/) | Vercel serverless endpoints (auth, avatars, OAuth, MCP, agents) | [api/CLAUDE.md](api/CLAUDE.md) |
-| [contracts/](contracts/) | Foundry project — ERC-8004 registries (Solidity) | [contracts/CLAUDE.md](contracts/CLAUDE.md) |
-| [specs/](specs/) | Format specs: `AGENT_MANIFEST.md`, `SKILL_SPEC.md`, `EMBED_SPEC.md`, `MEMORY_SPEC.md` | — |
-| [docs/](docs/) | User-facing docs: `ARCHITECTURE.md`, `API.md`, `DEPLOYMENT.md`, `DEVELOPMENT.md`, `WIDGETS.md`, `MCP.md` | — |
-| [prompts/](prompts/) | Build prompts organized by priority band — see [prompts/INDEX.md](prompts/INDEX.md) | — |
-| [public/](public/) | Static assets, separate HTML pages (`login.html`, `dashboard/`, `studio/`, `widgets-gallery/`) | — |
-| [sdk/](sdk/) | `@3dagent/sdk` — public TS client (separate npm package) | — |
-| [scripts/](scripts/) | One-off node scripts (schema apply, icon gen, animation fetchers) | — |
-| [.github/skills/](.github/skills/) | GitHub Copilot `SKILL.md` bundles (viewer, features, validation, deploy) | — |
-| [.github/prompts/](.github/prompts/) | Copilot prompt library for one-shot features | — |
-
-Top-level HTML entry points: `index.html` (app), `features.html`, `embed.html`, `agent-home.html`, `agent-embed.html`. Additional routes served from `public/` — wiring is in [vite.config.js](vite.config.js) `vercel-rewrites` plugin, mirrored in [vercel.json](vercel.json).
-
----
+**Touch only what you must. Clean up only your own mess.**
-## Current priorities (don't freelance)
+When editing existing code:
+- Don't "improve" adjacent code, comments, or formatting.
+- Don't refactor things that aren't broken.
+- Match existing style, even if you'd do it differently.
+- If you notice unrelated dead code, mention it - don't delete it.
-Work follows the six-band priority stack in [prompts/INDEX.md](prompts/INDEX.md):
+When your changes create orphans:
+- Remove imports/variables/functions that YOUR changes made unused.
+- Don't remove pre-existing dead code unless asked.
-1. **Wallet auth** (SIWE / Privy / WalletConnect)
-2. **Selfie → agent** (photo → rigged avatar)
-3. **Edit avatars** (material, mesh, regenerate)
-4. **View + embed** polish
-5. **Portable embed** (Claude.ai artifact + LobeHub plugin)
-6. **On-chain deployment** (ERC-8004)
+The test: Every changed line should trace directly to the user's request.
-If the task isn't in a band or isn't listed in INDEX.md, **ask before doing it.** Bands 1 and 2 block most downstream work — don't start band 4+ if band 1 is broken.
+## 4. Goal-Driven Execution
-Side lanes explicitly deprioritized: `pretext/`, `scalability/`, `widget-studio/` polish, CLI tool, AR quick-look, screenshot export. Don't open those without direction.
+**Define success criteria. Loop until verified.**
----
+Transform tasks into verifiable goals:
+- "Add validation" → "Write tests for invalid inputs, then make them pass"
+- "Fix the bug" → "Write a test that reproduces it, then make it pass"
+- "Refactor X" → "Ensure tests pass before and after"
-## Commands
-
-```bash
-npm install # install deps
-npm run dev # Vite dev server on :3000 (app build)
-npm run dev:lib # library build watch (dist-lib/agent-3d.js)
-npm run build # production build → dist/
-npm run build:lib # library build → dist-lib/
-npm run build:all # both
-npm run deploy # build + vercel --prod
-npx prettier --write <file> # format (tabs, 4-wide, single quotes, 100 cols)
-node --check <file.js> # syntax check — run this on every JS you modify
-
-# Contracts (cd contracts/)
-forge build && forge test # always before a deploy
-forge script script/Deploy.s.sol --rpc-url base_sepolia # dry-run
+For multi-step tasks, state a brief plan:
+```
+1. [Step] → verify: [check]
+2. [Step] → verify: [check]
+3. [Step] → verify: [check]
```
-No test suite is configured (`npm test` exits 0). Verification = `node --check` + `npm run build` + manual smoke at `localhost:3000`. Say so explicitly when you can't browser-test a UI change — don't claim a UI works just because the build passed.
-
----
-
-## Conventions
-
-| Topic | Rule |
-| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
-| Modules | **ESM only.** No CommonJS in `src/` or `api/`. |
-| Formatting | Prettier: **tabs**, 4-wide, single quotes, 100-col print width, `bracketSpacing`. Run `npx prettier --write` before committing. |
-| Typing | **No TypeScript** in the main app. JSDoc for public APIs. (SDK in `sdk/` may use TS — check locally.) |
-| Templating | **vhtml JSX** — string-based, no virtual DOM. Files end in `.jsx`. `jsxFactory: 'vhtml'`. |
-| Naming | CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` for private. |
-| State | Classes over factories where there's state. `EventTarget` for buses. |
-| SQL | Always tagged-template via `sql\`...\`` from [api/\_lib/db.js](api/_lib/db.js). Never concat. |
-| HTTP responses | Use `json()` / `error()` / `wrap()` from [api/\_lib/http.js](api/_lib/http.js). Never `res.end(JSON.stringify(...))`. |
-| Auth | Use `getSessionUser` / `authenticateBearer` from [api/\_lib/auth.js](api/_lib/auth.js). Never hand-roll JWT. |
-| Tool result shape | `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`. |
-| Errors | `error(res, status, code, message)` — OAuth-style string codes. See `api/CLAUDE.md`. |
-
----
-
-## Ground rules for agents
-
-1. **One task, one PR.** If you notice an unrelated bug, write it in your report; don't fix it.
-2. **Edit existing files before creating new ones.** No new top-level docs (`README.md`, `CLAUDE.md`, design docs) unless the task explicitly asks for them.
-3. **No new runtime deps** unless the task says so. The bundle is a user-facing concern.
-4. **Cite exact paths + line numbers** when referencing code. Don't invent APIs — read the file first.
-5. **Trust but verify** — `node --check` and `npm run build` any modified JS. Report both outputs.
-6. **Files off-limits per task** — respect `Files off-limits` sections in `prompts/*/` if present. Parallel tasks may be editing them.
-7. **On-chain = immutable.** Any change to contract ABI, storage layout, or deployed address requires explicit user approval. See [contracts/CLAUDE.md](contracts/CLAUDE.md).
-8. **Never `forge script --broadcast`** without approval.
-9. **Secrets live in `.env.local` / Vercel**, never in code. See [.env.example](.env.example) for the full list.
-10. **Reporting block at the end of every task:** files changed, commands run + their output, what you skipped, unrelated bugs observed.
-
----
-
-## Architectural invariants — don't violate these
-
-- **Viewer doesn't know about agents.** The agent layer wraps the viewer via `runtime/scene.js` (`SceneController`). Never import agent code from `viewer.js`.
-- **All cross-module agent events flow through [src/agent-protocol.js](src/agent-protocol.js).** Don't add direct module-to-module coupling; emit typed events (`ACTION_TYPES`).
-- **The Empathy Layer is a continuous weighted blend**, not an emotion FSM. See [src/CLAUDE.md](src/CLAUDE.md) for the decay + stimulus rules.
-- **Manifest `_baseURI`** must end with `/` for relative resolution to work.
-- **Skills default to `owned-only` trust** — manifest `author` must match `ownerAddress`. Mismatch → skill load throws.
-- **Avatar `.glb` uploads must be verified via `headObject()`** before registering in the `avatars` table (blocks R2-bypass attacks).
-- **MCP endpoints emit to `usage_events`** and respect `hasScope()`. Adding a tool without those = rejected.
-- **`window.VIEWER` is a debug global only.** Never rely on it in production code paths — use closures / DI.
-
----
-
-## Anti-patterns (these will get reverted)
-
-- `res.end(JSON.stringify(...))` — use `json(res, ...)`.
-- Instantiating a new Postgres `Pool` / `neon()` — import `sql` from `api/_lib/db.js`.
-- Hand-rolled JWT extraction — use `authenticateBearer()`.
-- String-concat SQL — tagged templates only.
-- Inline CORS — use `cors(req, res, ...)`.
-- Missing rate-limit on a public endpoint — use `limits.*` presets.
-- Adding a discrete "emotion state" to the avatar — break the continuous blend.
-- New top-level markdown file (README, design doc, "PLAN.md") without user asking.
-- Adding TypeScript to the main app.
-- Importing agent modules from the viewer half.
-- Writing a new routing layer instead of extending the URL-hash params in [src/app.js](src/app.js).
-- Long multi-paragraph comments / docstrings explaining _what_ code does. Keep it tight.
-
----
-
-## Common gotchas
-
-- **Avatar creator** wraps the Ready Player Me iframe. Configure subdomain via `VITE_RPM_SUBDOMAIN`; defaults to `demo.readyplayer.me`. See [src/avatar-creator.js](src/avatar-creator.js).
-- **`npm run dev` port 3000** — if taken, kill the other process; don't silently change the port.
-- **SpeechRecognition** silently no-ops if unavailable — check `window.SpeechRecognition || window.webkitSpeechRecognition`.
-- **Morph traversal runs every frame, every mesh.** Cheap on Mixamo avatars, expensive on scene-scale models.
-- **`memory.recall()` is substring search** — no embeddings yet. Don't assume semantic.
-- **`protocol.emit()` has no rate limit** — a runaway skill loop will cascade. Guard in the handler.
-- **ERC-8004 addresses are CREATE2-deterministic** — same bytes on every chain. Check `REGISTRY_DEPLOYMENTS` in [src/erc8004/abi.js](src/erc8004/abi.js) before hardcoding anything.
-- **Contract ABIs are hand-maintained ethers v6 human-readable strings** in `src/erc8004/abi.js`. No codegen. Sol change → abi.js edit.
+Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
---
-## If you're stuck
-
-- Unknown API — check `api/CLAUDE.md` and `api/_lib/` exports.
-- Unknown viewer/agent pattern — check `src/CLAUDE.md` and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
-- Unknown on-chain behavior — check `contracts/CLAUDE.md` and [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md).
-- Unknown skill shape — check [specs/SKILL_SPEC.md](specs/SKILL_SPEC.md).
-- Unknown embed attribute — check [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md).
-- Which prompt to run next — check [prompts/INDEX.md](prompts/INDEX.md).
-- Can't find something — `rg`/Grep first, then ask. Don't invent it.
+**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
\ No newline at end of file
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 004ce678a..ecb5ed5b2 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -103,4 +103,36 @@ export const env = {
get MAINNET_RPC_URL() {
return opt('MAINNET_RPC_URL');
},
+
+ // ── ERC-7710 Delegation Relayer ──────────────────────────────────────────
+ // Private key of the server-held EOA that pays gas for redeemDelegations.
+ // NEVER log this value. Rotate via Vercel env; derive AGENT_RELAYER_ADDRESS
+ // from the key using: node -e "require('ethers').Wallet.createRandom().address"
+ get AGENT_RELAYER_KEY() {
+ return req('AGENT_RELAYER_KEY');
+ },
+
+ // Derived: checksummed address of the relayer EOA. Fund with testnet ETH.
+ // Optional — can be computed from AGENT_RELAYER_KEY; provided here for ops convenience.
+ get AGENT_RELAYER_ADDRESS() {
+ return opt('AGENT_RELAYER_ADDRESS');
+ },
+
+ // Feature flag. Set to "true" to enable POST /api/permissions/redeem.
+ // Defaults to false so the endpoint is opt-in per environment.
+ get PERMISSIONS_RELAYER_ENABLED() {
+ return opt('PERMISSIONS_RELAYER_ENABLED', 'false') === 'true';
+ },
+
+ // Per-chain RPC URLs for on-chain delegation calls.
+ // Pattern: RPC_URL_<CHAINID> e.g. RPC_URL_84532 for Base Sepolia.
+ // Falls back to public RPC nodes when unset; set Alchemy/Infura URLs for production.
+ getRpcUrl(chainId) {
+ return (
+ opt(`RPC_URL_${chainId}`) ||
+ (chainId === 84532 ? opt('BASE_SEPOLIA_RPC_URL') : null) ||
+ (chainId === 11155111 ? opt('SEPOLIA_RPC_URL') : null) ||
+ null
+ );
+ },
};
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 983af633d..fe681095d 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -93,12 +93,19 @@ export const limits = {
limit: Math.max(1, Math.min(1000, perMin || 10)),
window: '1 m',
}).limit(agentId),
+ // Gas-spending endpoints: 10 redeems per 5 minutes per IP
+ strict: (key) => getLimiter('permissions:redeem:strict', { limit: 10, window: '5 m' }).limit(key),
pinUser: (userId) => getLimiter('pin:user', { limit: 30, window: '1 h' }).limit(userId),
pinStatusIp: (ip) => getLimiter('pin:status:ip', { limit: 60, window: '1 m' }).limit(ip),
agentByAddress: (ip) =>
getLimiter('agents:by-address', { limit: 120, window: '1 m' }).limit(ip),
walletLink: (userId) => getLimiter('wallet:link', { limit: 10, window: '10 m' }).limit(userId),
agentSuggest: (ip) => getLimiter('agents:suggest', { limit: 120, window: '1 m' }).limit(ip),
+ read: (ip) => getLimiter('permissions:read', { limit: 300, window: '1 m' }).limit(ip),
+ permissionsGrant: (userId) =>
+ getLimiter('permissions:grant', { limit: 10, window: '1 h' }).limit(userId),
+ permissionsRevoke: (userId) =>
+ getLimiter('permissions:revoke', { limit: 20, window: '1 h' }).limit(userId),
};
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
diff --git a/api/cron/index-delegations.js b/api/cron/index-delegations.js
new file mode 100644
index 000000000..4045891a5
--- /dev/null
+++ b/api/cron/index-delegations.js
@@ -0,0 +1,208 @@
+/**
+ * Delegation event indexer — polls each supported chain for DelegationDisabled
+ * and DelegationRedeemed events, reconciles against agent_delegations, and
+ * updates status / redemption_count / last_redeemed_at.
+ *
+ * Also sweeps expired rows (expires_at < NOW()) in a single idempotent UPDATE.
+ *
+ * Runs on Vercel Cron every 5 minutes (see vercel.json). Also callable manually
+ * via `POST /api/cron/index-delegations` with `Authorization: Bearer $CRON_SECRET`.
+ *
+ * Protocol-bus note: a future enhancement can emit a lightweight DB NOTIFY after
+ * a revoke sync so that task-13's runtime cache (src/runtime/delegation-redeem.js)
+ * invalidates without waiting for the next cron tick. Today the cache TTL covers
+ * the gap. Plumbing: NOTIFY would fire here → a LISTEN connection in a persistent
+ * worker picks it up → invalidates the in-memory delegation map keyed by agentId.
+ */
+
+import { id as keccakId } from 'ethers';
+import { sql } from '../_lib/db.js';
+import { cors, error, json, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';
+
+const DISABLED_TOPIC = keccakId('DelegationDisabled(address,bytes32)');
+const REDEEMED_TOPIC = keccakId('DelegationRedeemed(address,bytes32)');
+
+// Max blocks per eth_getLogs call. Public RPCs 429 above ~2000.
+const BLOCK_CAP = 2000;
+const RPC_TIMEOUT_MS = 10_000;
+
+// Approximate blocks per day, used only to seed the cursor on first run.
+const BLOCKS_PER_DAY = {
+ 84532: 43200, // Base Sepolia ~2 s/block
+ 11155111: 7200, // Sepolia ~12 s/block
+};
+
+// Public RPC fallbacks — override per chain via env RPC_<chainId>.
+const PUBLIC_RPC = {
+ 84532: 'https://sepolia.base.org',
+ 11155111: 'https://rpc.sepolia.org',
+};
+
+function rpcUrl(chainId) {
+ return process.env[`RPC_${chainId}`] ?? PUBLIC_RPC[chainId] ?? null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const started = Date.now();
+ const report = { chains: [], expiredSwept: 0, errors: [] };
+
+ // Index each chain independently — one chain's RPC failure must not abort others.
+ for (const [chainIdStr, contract] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {
+ const chainId = Number(chainIdStr);
+ const t0 = Date.now();
+ try {
+ const r = await indexChain(chainId, contract);
+ const summary = { chainId, ...r, elapsedMs: Date.now() - t0 };
+ report.chains.push(summary);
+ console.error(JSON.stringify({ stage: 'index-delegations', ...summary }));
+ } catch (err) {
+ const entry = { chainId, error: err.message || String(err) };
+ report.errors.push(entry);
+ console.error(JSON.stringify({ stage: 'index-delegations', ...entry }));
+ }
+ }
+
+ // Expiry sweep — idempotent, catches expirations missed between grant and indexer.
+ try {
+ const swept = await sql`
+ UPDATE agent_delegations
+ SET status = 'expired'
+ WHERE status = 'active' AND expires_at < NOW()
+ RETURNING id
+ `;
+ report.expiredSwept = swept.length;
+ } catch (err) {
+ report.errors.push({ stage: 'expiry-sweep', error: err.message || String(err) });
+ console.error(JSON.stringify({ stage: 'expiry-sweep', error: err.message }));
+ }
+
+ // Emit summary to usage_events (best-effort — non-fatal if table shape differs).
+ try {
+ await sql`
+ INSERT INTO usage_events (kind, tool, status, latency_ms)
+ VALUES ('permissions.indexer.tick', 'index-delegations', 'ok', ${Date.now() - started})
+ `;
+ } catch { /* non-fatal */ }
+
+ return json(res, 200, report);
+});
+
+// ─── Chain indexer ────────────────────────────────────────────────────────────
+
+async function indexChain(chainId, contract) {
+ const url = rpcUrl(chainId);
+ if (!url) throw new Error(`no RPC URL configured for chain ${chainId}`);
+
+ const latestHex = await rpc(url, 'eth_blockNumber', []);
+ const latestBlock = parseInt(latestHex, 16);
+
+ const [cursor] = await sql`
+ SELECT last_indexed_block FROM indexer_state
+ WHERE contract = ${contract.toLowerCase()} AND chain_id = ${chainId}
+ `;
+ const initialFrom = cursor
+ ? Number(cursor.last_indexed_block) + 1
+ : Math.max(0, latestBlock - (BLOCKS_PER_DAY[chainId] ?? 7200));
+
+ let fromBlock = initialFrom;
+ let toBlock = latestBlock; // updated each iteration; reflects final processed range
+ let revokedCount = 0;
+ let redeemedCount = 0;
+
+ while (fromBlock <= latestBlock) {
+ toBlock = Math.min(fromBlock + BLOCK_CAP - 1, latestBlock);
+
+ const logs = await rpc(url, 'eth_getLogs', [
+ {
+ address: contract,
+ topics: [[DISABLED_TOPIC, REDEEMED_TOPIC]],
+ fromBlock: '0x' + fromBlock.toString(16),
+ toBlock: '0x' + toBlock.toString(16),
+ },
+ ]);
+
+ if (logs.length > 0) {
+ // Fetch block timestamps only for blocks that have events.
+ const uniqueBlocks = [...new Set(logs.map((l) => l.blockNumber))];
+ const blockTs = {};
+ for (const bn of uniqueBlocks) {
+ const block = await rpc(url, 'eth_getBlockByNumber', [bn, false]);
+ blockTs[bn] = new Date(parseInt(block.timestamp, 16) * 1000).toISOString();
+ }
+
+ for (const log of logs) {
+ // topics[2] is the bytes32 delegationHash (indexed param, 0x-prefixed, 64 hex chars).
+ const delegationHash = log.topics[2];
+ const ts = blockTs[log.blockNumber];
+
+ if (log.topics[0] === DISABLED_TOPIC) {
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET status = 'revoked',
+ revoked_at = ${ts}::timestamptz,
+ tx_hash_revoke = ${log.transactionHash}
+ WHERE delegation_hash = ${delegationHash} AND status = 'active'
+ RETURNING id
+ `;
+ revokedCount += rows.length;
+ } else {
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET redemption_count = redemption_count + 1,
+ last_redeemed_at = ${ts}::timestamptz
+ WHERE delegation_hash = ${delegationHash}
+ RETURNING id
+ `;
+ redeemedCount += rows.length;
+ }
+ }
+ }
+
+ // Advance cursor after each batch so a timeout preserves partial progress.
+ await sql`
+ INSERT INTO indexer_state (contract, chain_id, last_indexed_block, updated_at)
+ VALUES (${contract.toLowerCase()}, ${chainId}, ${toBlock}, NOW())
+ ON CONFLICT (contract, chain_id) DO UPDATE SET
+ last_indexed_block = GREATEST(indexer_state.last_indexed_block, excluded.last_indexed_block),
+ updated_at = NOW()
+ `;
+
+ fromBlock = toBlock + 1;
+ }
+
+ return { fromBlock: initialFrom, toBlock, revokedCount, redeemedCount };
+}
+
+// ─── RPC helper ──────────────────────────────────────────────────────────────
+
+async function rpc(url, method, params) {
+ const ac = new AbortController();
+ const t = setTimeout(() => ac.abort(), RPC_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: ac.signal,
+ });
+ if (!res.ok) throw new Error(`RPC HTTP ${res.status} from ${url}`);
+ const data = await res.json();
+ if (data.error) {
+ throw new Error(`RPC ${method} error: ${data.error.message ?? JSON.stringify(data.error)}`);
+ }
+ return data.result;
+ } finally {
+ clearTimeout(t);
+ }
+}
diff --git a/api/cron/run-dca.js b/api/cron/run-dca.js
new file mode 100644
index 000000000..88e45dc4b
--- /dev/null
+++ b/api/cron/run-dca.js
@@ -0,0 +1,317 @@
+// GET /api/cron/run-dca
+// Hourly cron: executes pending DCA strategies via Uniswap V3 SwapRouter.
+// Scheduled in vercel.json: "0 * * * *"
+
+import { createPublicClient, http, encodeFunctionData, parseAbi } from 'viem';
+import { baseSepolia, base } from 'viem/chains';
+
+import { sql } from '../_lib/db.js';
+import { env } from '../_lib/env.js';
+import { json, error, wrap } from '../_lib/http.js';
+
+// ── Chain config ──────────────────────────────────────────────────────────────
+
+const CHAIN_CONFIG = {
+ 84532: {
+ chain: baseSepolia,
+ swap_router: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
+ quoter_v2: '0xC5290058841028F1614F3A6F0F5816cAd0df5E27',
+ },
+ 8453: {
+ chain: base,
+ swap_router: '0x2626664c2603336E57B271c5C0b26F421741e481',
+ quoter_v2: '0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a',
+ },
+};
+
+// ── ABIs (minimal) ────────────────────────────────────────────────────────────
+
+const QUOTER_V2_ABI = parseAbi([
+ 'function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)',
+]);
+
+const SWAP_ROUTER_ABI = parseAbi([
+ 'function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) external payable returns (uint256 amountOut)',
+]);
+
+const ERC20_ABI = parseAbi([
+ 'function approve(address spender, uint256 amount) external returns (bool)',
+]);
+
+// Uniswap V3 standard fee tier — 0.3% pool is the most liquid USDC/WETH tier
+const FEE_TIER = 3000;
+
+// ── RPC client factory ────────────────────────────────────────────────────────
+
+function getViemClient(chainId) {
+ const cfg = CHAIN_CONFIG[chainId];
+ if (!cfg) throw new Error(`Unsupported chainId: ${chainId}`);
+ const rpcUrl = env.getRpcUrl(chainId);
+ return createPublicClient({
+ chain: cfg.chain,
+ transport: rpcUrl ? http(rpcUrl) : http(),
+ });
+}
+
+// ── Quote with divergence check ───────────────────────────────────────────────
+
+/**
+ * Fetch a quote twice 15s apart; abort if they diverge by more than 0.5%.
+ * Returns { amountOut, divergenceBps } or throws if divergence exceeds limit.
+ */
+async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amountIn) {
+ const params = {
+ tokenIn,
+ tokenOut,
+ amountIn: BigInt(amountIn),
+ fee: FEE_TIER,
+ sqrtPriceLimitX96: 0n,
+ };
+
+ // First quote
+ const [q1] = await client.readContract({
+ address: quoterAddress,
+ abi: QUOTER_V2_ABI,
+ functionName: 'quoteExactInputSingle',
+ args: [params],
+ });
+
+ // Wait 15s then quote again
+ await new Promise((r) => setTimeout(r, 15_000));
+
+ const [q2] = await client.readContract({
+ address: quoterAddress,
+ abi: QUOTER_V2_ABI,
+ functionName: 'quoteExactInputSingle',
+ args: [params],
+ });
+
+ // Divergence in basis points: |q2-q1| / q1 * 10000
+ const divergenceBps =
+ q1 === 0n ? 0 : Number(((q2 > q1 ? q2 - q1 : q1 - q2) * 10000n) / q1);
+
+ if (divergenceBps > 50) {
+ throw Object.assign(
+ new Error(`Quote divergence ${divergenceBps}bps exceeds 50bps limit — aborting`),
+ { code: 'quote_divergence', divergenceBps },
+ );
+ }
+
+ // Use the more conservative (lower) of the two quotes
+ const amountOut = q1 < q2 ? q1 : q2;
+ return { amountOut, divergenceBps };
+}
+
+// ── Calldata builders ─────────────────────────────────────────────────────────
+
+function buildApproveCalldata(spender, amount) {
+ return encodeFunctionData({
+ abi: ERC20_ABI,
+ functionName: 'approve',
+ args: [spender, BigInt(amount)],
+ });
+}
+
+function buildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum) {
+ return encodeFunctionData({
+ abi: SWAP_ROUTER_ABI,
+ functionName: 'exactInputSingle',
+ args: [
+ {
+ tokenIn,
+ tokenOut,
+ fee: FEE_TIER,
+ recipient,
+ amountIn: BigInt(amountIn),
+ amountOutMinimum: BigInt(amountOutMinimum),
+ sqrtPriceLimitX96: 0n,
+ },
+ ],
+ });
+}
+
+// ── Relayer redemption ────────────────────────────────────────────────────────
+
+async function redeemViaRelayer(delegationId, calls) {
+ const relayerUrl = `${env.APP_ORIGIN}/api/permissions/redeem`;
+ const res = await fetch(relayerUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ // Cron uses the shared relayer bearer token set in env
+ authorization: `Bearer ${env.CRON_SECRET}`,
+ },
+ body: JSON.stringify({ id: delegationId, calls }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({ message: res.statusText }));
+ throw Object.assign(
+ new Error(body.error_description || body.message || `Relayer ${res.status}`),
+ { code: body.error || 'relayer_error', status: res.status },
+ );
+ }
+ return res.json();
+}
+
+// ── onPeriod — process one strategy ──────────────────────────────────────────
+
+async function onPeriod(strategy) {
+ const {
+ id: strategyId,
+ delegation_id: delegationId,
+ chain_id: chainId,
+ token_in: tokenIn,
+ token_out: tokenOut,
+ amount_per_execution: amountIn,
+ slippage_bps: slippageBps,
+ } = strategy;
+
+ const cfg = CHAIN_CONFIG[chainId];
+ if (!cfg) throw Object.assign(new Error(`No config for chainId ${chainId}`), { code: 'unsupported_chain' });
+
+ const client = getViemClient(chainId);
+
+ // Get verified quote
+ const { amountOut, divergenceBps } = await getVerifiedQuote(
+ client,
+ cfg.quoter_v2,
+ tokenIn,
+ tokenOut,
+ amountIn,
+ );
+
+ // Apply slippage: amountOutMinimum = amountOut * (10000 - slippageBps) / 10000
+ const amountOutMinimum = (amountOut * BigInt(10000 - slippageBps)) / 10000n;
+
+ // Resolve recipient — use the delegator address from the delegation row
+ const [delegationRow] = await sql`
+ SELECT delegator_address FROM agent_delegations
+ WHERE id = ${delegationId} AND status = 'active'
+ LIMIT 1
+ `;
+ if (!delegationRow) {
+ throw Object.assign(new Error('Delegation not found or no longer active'), { code: 'delegation_gone' });
+ }
+ const recipient = delegationRow.delegator_address;
+
+ // Build calls: [approve USDC → SwapRouter, exactInputSingle]
+ const calls = [
+ {
+ to: tokenIn,
+ value: '0',
+ data: buildApproveCalldata(cfg.swap_router, amountIn),
+ },
+ {
+ to: cfg.swap_router,
+ value: '0',
+ data: buildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum),
+ },
+ ];
+
+ // Submit via relayer
+ const result = await redeemViaRelayer(delegationId, calls);
+
+ return { txHash: result.txHash, quoteAmountOut: amountOut.toString(), divergenceBps };
+}
+
+// ── Cron handler ──────────────────────────────────────────────────────────────
+
+export default wrap(async (req, res) => {
+ // Vercel cron passes Authorization: Bearer $CRON_SECRET
+ const cronSecret = env.CRON_SECRET;
+ if (cronSecret) {
+ const auth = req.headers.authorization || '';
+ if (auth !== `Bearer ${cronSecret}`) {
+ return error(res, 401, 'unauthorized', 'invalid cron secret');
+ }
+ }
+
+ // Fetch all due active strategies
+ const strategies = await sql`
+ SELECT
+ s.id, s.delegation_id, s.chain_id,
+ s.token_in, s.token_out, s.amount_per_execution,
+ s.period_seconds, s.slippage_bps, s.agent_id,
+ ad.status AS delegation_status, ad.expires_at AS delegation_expires_at
+ FROM dca_strategies s
+ JOIN agent_delegations ad ON ad.id = s.delegation_id
+ WHERE s.status = 'active'
+ AND s.next_execution_at <= NOW()
+ ORDER BY s.next_execution_at ASC
+ LIMIT 50
+ `;
+
+ const results = [];
+ for (const strategy of strategies) {
+ const execRow = {
+ strategy_id: strategy.id,
+ chain_id: strategy.chain_id,
+ amount_in: strategy.amount_per_execution,
+ slippage_bps_used: strategy.slippage_bps,
+ status: 'pending',
+ };
+
+ // Check delegation is still alive before spending gas on a quote
+ if (strategy.delegation_status !== 'active') {
+ await sql`
+ UPDATE dca_strategies SET status = 'paused' WHERE id = ${strategy.id}
+ `;
+ execRow.status = 'aborted';
+ execRow.error = `Delegation ${strategy.delegation_status}`;
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`;
+ results.push({ id: strategy.id, skipped: true, reason: execRow.error });
+ continue;
+ }
+
+ if (new Date(strategy.delegation_expires_at) <= new Date()) {
+ await sql`
+ UPDATE dca_strategies SET status = 'expired' WHERE id = ${strategy.id}
+ `;
+ execRow.status = 'aborted';
+ execRow.error = 'Delegation expired';
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`;
+ results.push({ id: strategy.id, skipped: true, reason: execRow.error });
+ continue;
+ }
+
+ try {
+ const { txHash, quoteAmountOut, divergenceBps } = await onPeriod(strategy);
+
+ execRow.tx_hash = txHash;
+ execRow.quote_amount_out = quoteAmountOut;
+ execRow.quote_divergence_bps = divergenceBps;
+ execRow.status = 'success';
+
+ const nextExecAt = new Date(
+ Date.now() + strategy.period_seconds * 1000,
+ ).toISOString();
+
+ await sql`
+ UPDATE dca_strategies
+ SET last_execution_at = NOW(), next_execution_at = ${nextExecAt}
+ WHERE id = ${strategy.id}
+ `;
+
+ results.push({ id: strategy.id, txHash, quoteAmountOut });
+ } catch (err) {
+ execRow.status = err.code === 'quote_divergence' ? 'aborted' : 'failed';
+ execRow.error = err.message;
+ execRow.quote_divergence_bps = err.divergenceBps ?? null;
+
+ console.error('[cron/run-dca] strategy', strategy.id, err.code, err.message);
+ results.push({ id: strategy.id, error: err.message, code: err.code });
+ }
+
+ // Insert execution record regardless of outcome
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ console.error('[cron/run-dca] failed to insert execution row', e.message),
+ );
+ }
+
+ return json(res, 200, {
+ ok: true,
+ processed: strategies.length,
+ results,
+ });
+});
diff --git a/api/cron/run-subscriptions.js b/api/cron/run-subscriptions.js
new file mode 100644
index 000000000..5be393f08
--- /dev/null
+++ b/api/cron/run-subscriptions.js
@@ -0,0 +1,152 @@
+/**
+ * Hourly cron — process due subscription charges.
+ *
+ * Selects agent_subscriptions WHERE status='active' AND next_charge_at <= NOW(),
+ * verifies the backing delegation is still active, calls the skill's onPeriod
+ * handler (imported dynamically from public/skills/subscription/skill.js), then
+ * either advances next_charge_at on success or flips status to 'paused' on failure.
+ *
+ * Idempotent: re-running within the same period is a no-op because next_charge_at
+ * is only reached once per period.
+ *
+ * Scheduled via vercel.json crons — "0 * * * *" (every hour on the hour).
+ */
+
+import { sql } from '../_lib/db.js';
+import { cors, error, json, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+
+// USDC contract addresses by chain ID.
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
+};
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ // Auth: Vercel Cron header OR explicit Bearer $CRON_SECRET.
+ const auth = req.headers['authorization'] ?? '';
+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
+ const fromVercelCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromVercelCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const origin = env.APP_ORIGIN;
+ const relayerToken = env.CRON_SECRET ?? '';
+
+ const report = { processed: 0, charged: 0, skipped: 0, paused: 0, errors: [] };
+
+ // Load the skill's onPeriod handler once per invocation.
+ const { onPeriod } = await import('../../public/skills/subscription/skill.js');
+
+ // Select all active subscriptions whose charge window has arrived.
+ const rows = await sql`
+ SELECT
+ s.id,
+ s.user_id,
+ s.agent_id,
+ s.delegation_id,
+ s.period_seconds,
+ s.amount_per_period,
+ s.next_charge_at,
+ d.status AS delegation_status,
+ d.expires_at AS delegation_expires_at,
+ d.chain_id,
+ ai.wallet_address AS owner_address
+ FROM agent_subscriptions s
+ JOIN agent_delegations d ON d.id = s.delegation_id
+ JOIN agent_identities ai ON ai.id = s.agent_id
+ WHERE s.status = 'active'
+ AND s.next_charge_at <= NOW()
+ `;
+
+ for (const row of rows) {
+ report.processed++;
+
+ // Guard: delegation must still be active.
+ if (row.delegation_status !== 'active') {
+ await _pause(row.id, `delegation_${row.delegation_status}`);
+ report.paused++;
+ report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });
+ continue;
+ }
+
+ // Guard: delegation must not be expired.
+ if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {
+ await _pause(row.id, 'delegation_expired');
+ report.paused++;
+ report.errors.push({ id: row.id, reason: 'delegation_expired' });
+ continue;
+ }
+
+ const usdcAddress = USDC_BY_CHAIN[row.chain_id];
+ if (!usdcAddress) {
+ await _pause(row.id, `chain_${row.chain_id}_unsupported`);
+ report.skipped++;
+ report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });
+ continue;
+ }
+
+ let result;
+ try {
+ result = await onPeriod({
+ agent: {
+ agentId: row.agent_id,
+ chainId: row.chain_id,
+ ownerAddress: row.owner_address,
+ usdcAddress,
+ relayerToken,
+ origin,
+ },
+ subscription: {
+ id: row.id,
+ delegationId: row.delegation_id,
+ amountPerPeriod: row.amount_per_period,
+ },
+ });
+ } catch (err) {
+ await _pause(row.id, (err.message ?? 'unknown').slice(0, 500));
+ report.paused++;
+ report.errors.push({ id: row.id, reason: err.message ?? 'unknown' });
+ continue;
+ }
+
+ if (result.ok) {
+ // Advance next_charge_at by exactly one period to enforce idempotency.
+ const nextChargeAt = new Date(
+ Date.parse(row.next_charge_at) + row.period_seconds * 1000,
+ );
+ await sql`
+ UPDATE agent_subscriptions
+ SET last_charge_at = NOW(),
+ next_charge_at = ${nextChargeAt.toISOString()},
+ last_error = NULL
+ WHERE id = ${row.id}
+ `;
+
+ // Emit usage event — non-fatal if the table schema differs.
+ await sql`
+ INSERT INTO usage_events (user_id, kind, tool, status)
+ VALUES (${row.user_id}, 'subscription_charge', 'subscription', 'success')
+ `.catch(() => null);
+
+ report.charged++;
+ } else {
+ await _pause(row.id, `${result.code ?? ''}: ${result.message ?? ''}`.slice(0, 500));
+ report.paused++;
+ report.errors.push({ id: row.id, code: result.code, message: result.message });
+ }
+ }
+
+ return json(res, 200, report);
+});
+
+async function _pause(id, lastError) {
+ await sql`
+ UPDATE agent_subscriptions
+ SET status = 'paused', last_error = ${lastError}
+ WHERE id = ${id}
+ `;
+}
diff --git a/api/dca-strategies.js b/api/dca-strategies.js
new file mode 100644
index 000000000..72a1664da
--- /dev/null
+++ b/api/dca-strategies.js
@@ -0,0 +1,190 @@
+// POST/GET/DELETE /api/dca-strategies
+// Manages DCA strategy records. Strategies are executed by api/cron/run-dca.js.
+
+import { z } from 'zod';
+import { sql } from './_lib/db.js';
+import { getSessionUser } from './_lib/auth.js';
+import { cors, json, error, wrap, readJson, method } from './_lib/http.js';
+import { parse } from './_lib/validate.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+
+// Whitelisted token-out symbols — extend this as new pools become liquid enough
+const ALLOWED_TOKEN_OUT_SYMBOLS = new Set(['WETH', 'cbBTC', 'USDT']);
+
+// Max slippage enforced server-side in addition to the UI cap
+const MAX_SLIPPAGE_BPS = 500;
+
+const weiString = z.string().regex(/^\d+$/, 'must be a decimal integer string');
+const ethAddress = z
+ .string()
+ .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 0x-prefixed 40-character hex address');
+
+const createSchema = z.object({
+ agent_id: z.string().uuid(),
+ delegation_id: z.string().uuid(),
+ chain_id: z.number().int().positive().default(84532),
+ token_in: ethAddress,
+ token_out: ethAddress,
+ token_out_symbol: z.string().min(1).max(10),
+ amount_per_execution: weiString,
+ period_seconds: z.number().int().refine((v) => v === 86400 || v === 604800, {
+ message: 'period_seconds must be 86400 (daily) or 604800 (weekly)',
+ }),
+ slippage_bps: z.number().int().min(1).max(MAX_SLIPPAGE_BPS).default(50),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const url = new URL(req.url, 'http://x');
+
+ // ── DELETE /api/dca-strategies/:id ─────────────────────────────────────────
+ if (req.method === 'DELETE') {
+ const strategyId = url.pathname.split('/').pop();
+ if (!strategyId || strategyId === 'dca-strategies') {
+ return error(res, 400, 'missing_param', 'strategy id required in path');
+ }
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // Verify ownership via agent_id → user_id chain
+ const [row] = await sql`
+ SELECT s.id
+ FROM dca_strategies s
+ JOIN agent_identities a ON a.id = s.agent_id
+ WHERE s.id = ${strategyId}
+ AND a.user_id = ${session.id}
+ AND s.status = 'active'
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'strategy not found or already cancelled');
+
+ await sql`
+ UPDATE dca_strategies
+ SET status = 'cancelled', cancelled_at = NOW()
+ WHERE id = ${strategyId}
+ `;
+ return json(res, 200, { ok: true });
+ }
+
+ // ── GET /api/dca-strategies?agent_id=… ────────────────────────────────────
+ if (req.method === 'GET') {
+ const agentId = url.searchParams.get('agent_id');
+ if (!agentId) return error(res, 400, 'missing_param', 'agent_id is required');
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // Confirm session user owns this agent
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${session.id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const strategies = await sql`
+ SELECT
+ s.id, s.chain_id, s.token_in, s.token_out, s.token_out_symbol,
+ s.amount_per_execution, s.period_seconds, s.slippage_bps,
+ s.status, s.next_execution_at, s.last_execution_at, s.created_at,
+ (
+ SELECT json_build_object(
+ 'tx_hash', e.tx_hash,
+ 'amount_in', e.amount_in,
+ 'amount_out', e.amount_out,
+ 'status', e.status,
+ 'executed_at', e.executed_at
+ )
+ FROM dca_executions e
+ WHERE e.strategy_id = s.id
+ ORDER BY e.executed_at DESC
+ LIMIT 1
+ ) AS last_execution
+ FROM dca_strategies s
+ WHERE s.agent_id = ${agentId}
+ ORDER BY s.created_at DESC
+ `;
+ return json(res, 200, { ok: true, data: strategies });
+ }
+
+ // ── POST /api/dca-strategies ───────────────────────────────────────────────
+ if (!method(req, res, ['POST'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = parse(createSchema, await readJson(req));
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'validation_error', err.message);
+ }
+
+ if (!ALLOWED_TOKEN_OUT_SYMBOLS.has(body.token_out_symbol)) {
+ return error(res, 400, 'validation_error', `token_out_symbol must be one of: ${[...ALLOWED_TOKEN_OUT_SYMBOLS].join(', ')}`);
+ }
+
+ // Confirm session user owns the agent
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${body.agent_id} AND user_id = ${session.id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ // Confirm delegation exists and is active, and belongs to this agent
+ const [delegation] = await sql`
+ SELECT id, status, expires_at
+ FROM agent_delegations
+ WHERE id = ${body.delegation_id}
+ AND agent_id = ${body.agent_id}
+ AND status = 'active'
+ LIMIT 1
+ `;
+ if (!delegation) {
+ return error(res, 404, 'not_found', 'active delegation not found for this agent');
+ }
+ if (new Date(delegation.expires_at) <= new Date()) {
+ return error(res, 409, 'delegation_expired', 'delegation has already expired');
+ }
+
+ // Prevent duplicate active strategies for the same agent + token pair
+ const [existing] = await sql`
+ SELECT id FROM dca_strategies
+ WHERE agent_id = ${body.agent_id}
+ AND token_in = ${body.token_in}
+ AND token_out = ${body.token_out}
+ AND status = 'active'
+ LIMIT 1
+ `;
+ if (existing) {
+ return error(res, 409, 'conflict', 'an active strategy already exists for this token pair — cancel it first');
+ }
+
+ const nextExecAt = new Date(Date.now() + body.period_seconds * 1000).toISOString();
+
+ const [created] = await sql`
+ INSERT INTO dca_strategies (
+ agent_id, delegation_id, chain_id,
+ token_in, token_out, token_out_symbol,
+ amount_per_execution, period_seconds, slippage_bps,
+ next_execution_at
+ ) VALUES (
+ ${body.agent_id}, ${body.delegation_id}, ${body.chain_id},
+ ${body.token_in}, ${body.token_out}, ${body.token_out_symbol},
+ ${body.amount_per_execution}, ${body.period_seconds}, ${body.slippage_bps},
+ ${nextExecAt}
+ )
+ RETURNING id, status, next_execution_at, created_at
+ `;
+
+ return json(res, 201, { ok: true, ...created });
+});
diff --git a/api/permissions/grant.js b/api/permissions/grant.js
new file mode 100644
index 000000000..93c1915a5
--- /dev/null
+++ b/api/permissions/grant.js
@@ -0,0 +1,235 @@
+// POST /api/permissions/grant
+// Accepts a signed ERC-7710 delegation, verifies it, and persists it.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { recordEvent } from '../_lib/usage.js';
+import { SERVER_CHAIN_META } from '../_lib/onchain.js';
+import { z } from 'zod';
+import { ethers } from 'ethers';
+import {
+ DELEGATION_MANAGER_DEPLOYMENTS,
+ EIP712_DOMAIN,
+ DELEGATION_TYPES,
+} from '../../src/erc7710/abi.js';
+import { isDelegationValid, PermissionError } from '../../src/permissions/toolkit.js';
+
+const ROOT_AUTHORITY =
+ '0x0000000000000000000000000000000000000000000000000000000000000000';
+
+const hexAddr = z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address');
+const hexBytes = z.string().regex(/^0x([0-9a-fA-F]{2})*$/, 'must be 0x-prefixed hex bytes');
+const hexBytes32 = z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 32-byte hex value');
+
+const caveatSchema = z.object({
+ enforcer: hexAddr,
+ terms: hexBytes.default('0x'),
+ args: hexBytes.default('0x'),
+});
+
+const delegationSchema = z.object({
+ delegator: hexAddr,
+ delegate: hexAddr,
+ authority: hexBytes32.optional(),
+ caveats: z.array(caveatSchema).default([]),
+ salt: z.union([
+ z.string().regex(/^(0x[0-9a-fA-F]+|\d+)$/, 'salt must be a decimal or 0x-prefixed hex integer'),
+ z.number().int().nonnegative(),
+ ]),
+ signature: hexBytes,
+ hash: hexBytes32,
+});
+
+const scopeSchema = z.object({
+ token: z.string().min(1),
+ maxAmount: z.string().min(1),
+ period: z.enum(['daily', 'weekly', 'once']),
+ targets: z.array(hexAddr).min(1),
+ expiry: z.number().int().positive(),
+});
+
+const bodySchema = z.object({
+ agentId: z.string().uuid(),
+ chainId: z.number().int().positive(),
+ delegation: delegationSchema,
+ scope: scopeSchema,
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.permissionsGrant(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = await readJson(req);
+ const parsed = bodySchema.safeParse(raw);
+ if (!parsed.success) {
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
+ return error(res, 400, 'validation_error', msg);
+ }
+ const { agentId, chainId, delegation, scope } = parsed.data;
+
+ // chainId must be a supported DelegationManager deployment
+ if (!(chainId in DELEGATION_MANAGER_DEPLOYMENTS)) {
+ return error(res, 400, 'chain_not_supported', `chainId ${chainId} is not supported`);
+ }
+
+ // Owner gate: agent must exist and belong to the authenticated user
+ const [agent] = await sql`
+ select id, user_id from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== user.id) return error(res, 403, 'not_owner', 'you do not own this agent');
+
+ // Wallet linkage: delegation.delegator must be a wallet linked to the authenticated user
+ const delegatorLower = delegation.delegator.toLowerCase();
+ const [linkedWallet] = await sql`
+ select address from user_wallets
+ where user_id = ${user.id} and address = ${delegatorLower}
+ limit 1
+ `;
+ if (!linkedWallet) {
+ return error(res, 409, 'wallet_not_linked', 'delegation.delegator is not linked to your account');
+ }
+
+ // Signature verification — two steps:
+ // 1. Re-derive the EIP-712 hash from delegation fields and compare with delegation.hash
+ // (prevents chain-hop replay: different contract address → different hash).
+ // 2. Recover the signer from the signature and verify it matches delegation.delegator.
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
+ const eip712Domain = EIP712_DOMAIN({ chainId, verifyingContract: managerAddr });
+ let derivedHash;
+ try {
+ const structValue = {
+ delegate: delegation.delegate,
+ delegator: delegation.delegator,
+ authority: delegation.authority || ROOT_AUTHORITY,
+ caveats: delegation.caveats.map((c) => ({
+ enforcer: c.enforcer,
+ terms: c.terms,
+ args: c.args,
+ })),
+ salt: BigInt(delegation.salt),
+ };
+
+ derivedHash = ethers.TypedDataEncoder.hash(eip712Domain, DELEGATION_TYPES, structValue);
+
+ if (derivedHash.toLowerCase() !== delegation.hash.toLowerCase()) {
+ return error(res, 400, 'hash_mismatch', 'delegation.hash does not match the delegation fields');
+ }
+
+ const recovered = ethers.verifyTypedData(
+ eip712Domain,
+ DELEGATION_TYPES,
+ structValue,
+ delegation.signature,
+ );
+ if (recovered.toLowerCase() !== delegatorLower) {
+ return error(res, 400, 'signature_invalid', 'signature does not match delegation.delegator');
+ }
+ } catch (err) {
+ if (err instanceof PermissionError) {
+ return error(res, 400, err.code || 'signature_invalid', err.message);
+ }
+ return error(res, 400, 'signature_invalid', err.message || 'invalid delegation signature');
+ }
+
+ // On-chain revocation check (isDelegationValid from task 04)
+ const rpcUrl = SERVER_CHAIN_META[chainId]?.rpc;
+ const validity = await isDelegationValid({ hash: delegation.hash, chainId, rpcUrl }).catch(
+ (err) => {
+ if (err instanceof PermissionError) return { valid: false, reason: err.code };
+ console.warn('[grant] isDelegationValid error', err?.message);
+ return { valid: true }; // RPC unavailable; proceed and rely on indexer for revocation
+ },
+ );
+ if (!validity.valid) {
+ return error(res, 400, validity.reason || 'signature_invalid', 'delegation is not valid on-chain');
+ }
+
+ // Scope sanity checks
+ const nowSec = Math.floor(Date.now() / 1000);
+ if (scope.expiry <= nowSec + 60) {
+ return error(res, 400, 'validation_error', 'scope.expiry must be at least 60 seconds in the future');
+ }
+ if (scope.expiry > nowSec + 365 * 24 * 3600) {
+ return error(res, 400, 'validation_error', 'scope.expiry must be within 365 days');
+ }
+ let maxAmountBig;
+ try {
+ maxAmountBig = BigInt(scope.maxAmount);
+ } catch {
+ return error(res, 400, 'validation_error', 'scope.maxAmount must be a numeric string');
+ }
+ if (maxAmountBig <= 0n) {
+ return error(res, 400, 'validation_error', 'scope.maxAmount must be positive');
+ }
+ let targets;
+ try {
+ targets = scope.targets.map((t) => ethers.getAddress(t));
+ } catch {
+ return error(res, 400, 'validation_error', 'scope.targets contains an invalid address');
+ }
+
+ const delegationHash = derivedHash;
+ const expiresAt = new Date(scope.expiry * 1000).toISOString();
+ const delegatorAddr = ethers.getAddress(delegation.delegator);
+ const delegateAddr = ethers.getAddress(delegation.delegate);
+
+ const delegationJson = {
+ delegator: delegation.delegator,
+ delegate: delegation.delegate,
+ authority: delegation.authority || ROOT_AUTHORITY,
+ caveats: delegation.caveats,
+ salt: String(delegation.salt),
+ // signature stored as part of the envelope; not logged separately
+ signature: delegation.signature,
+ hash: delegationHash,
+ };
+ const scopeJson = { ...scope, targets };
+
+ // Persist — delegation_hash is UNIQUE; on conflict return 409
+ const rows = await sql`
+ insert into agent_delegations (
+ agent_id, chain_id, delegator_address, delegate_address,
+ delegation_hash, delegation_json, scope, expires_at
+ )
+ values (
+ ${agentId},
+ ${chainId},
+ ${delegatorAddr.toLowerCase()},
+ ${delegateAddr.toLowerCase()},
+ ${delegationHash},
+ ${JSON.stringify(delegationJson)}::jsonb,
+ ${JSON.stringify(scopeJson)}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (delegation_hash) do nothing
+ returning id
+ `;
+
+ if (!rows || rows.length === 0) {
+ const [existing] = await sql`
+ select id from agent_delegations where delegation_hash = ${delegationHash} limit 1
+ `;
+ return error(res, 409, 'duplicate_delegation', 'this delegation has already been granted', {
+ id: existing?.id,
+ });
+ }
+
+ const { id } = rows[0];
+
+ recordEvent({ userId: user.id, agentId, kind: 'permissions.grant' });
+
+ return json(res, 200, { ok: true, id, delegationHash, expiresAt });
+});
diff --git a/api/permissions/list.js b/api/permissions/list.js
new file mode 100644
index 000000000..76eba9570
--- /dev/null
+++ b/api/permissions/list.js
@@ -0,0 +1,128 @@
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, error, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const PUBLIC_CACHE = 'public, max-age=30, s-maxage=60';
+
+const VALID_STATUSES = new Set(['active', 'revoked', 'expired', 'all']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || null;
+ const delegator = url.searchParams.get('delegator') || null;
+
+ if (!agentId && !delegator) {
+ return error(res, 400, 'missing_filter', 'agentId or delegator query param is required');
+ }
+
+ const statusParam = url.searchParams.get('status') || 'active';
+ if (!VALID_STATUSES.has(statusParam)) {
+ return error(res, 400, 'validation_error', 'status must be active, revoked, expired, or all');
+ }
+
+ const chainIdParam = url.searchParams.get('chainId');
+ const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
+ if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ }
+
+ const limitParam = Math.min(200, Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)));
+ const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10));
+
+ // agentId-only path: public, no auth required
+ if (agentId && !delegator) {
+ const rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE agent_id = ${agentId}
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+
+ const delegations = rows.map(toPublicShape);
+ const body = { ok: true, delegations };
+ if (rows.length === limitParam) body.nextOffset = offset + limitParam;
+
+ return json(res, 200, body, { 'cache-control': PUBLIC_CACHE });
+ }
+
+ // delegator path (or both provided): session required
+ const session = await getSessionUser(req, res);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) {
+ return error(res, 401, 'unauthorized', 'sign in required to list delegations by delegator');
+ }
+ const userId = session?.id ?? bearer?.userId;
+
+ // Verify the session user owns this delegator address
+ const targetDelegator = delegator || null;
+ if (targetDelegator) {
+ const [wallet] = await sql`
+ SELECT 1 FROM user_wallets
+ WHERE user_id = ${userId}
+ AND lower(address) = lower(${targetDelegator})
+ LIMIT 1
+ `;
+ if (!wallet) {
+ return error(res, 403, 'forbidden', 'delegator address does not belong to your account');
+ }
+ }
+
+ const whereAgentId = agentId;
+ const rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ delegation_json, scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE (${whereAgentId}::uuid IS NULL OR agent_id = ${whereAgentId}::uuid)
+ AND (${targetDelegator}::text IS NULL OR lower(delegator_address) = lower(${targetDelegator}::text))
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+
+ const delegations = rows.map(toAuthShape);
+ const body = { ok: true, delegations };
+ if (rows.length === limitParam) body.nextOffset = offset + limitParam;
+
+ return json(res, 200, body);
+});
+
+function toPublicShape(row) {
+ return {
+ id: row.id,
+ chainId: row.chain_id,
+ delegator: row.delegator_address,
+ delegate: row.delegate_address,
+ delegationHash: row.delegation_hash,
+ scope: row.scope,
+ status: row.status,
+ expiresAt: row.expires_at,
+ createdAt: row.created_at,
+ lastRedeemedAt: row.last_redeemed_at,
+ redemptionCount: row.redemption_count,
+ };
+}
+
+function toAuthShape(row) {
+ return {
+ ...toPublicShape(row),
+ delegationJson: row.delegation_json,
+ };
+}
diff --git a/api/permissions/metadata.js b/api/permissions/metadata.js
new file mode 100644
index 000000000..78ad4adc8
--- /dev/null
+++ b/api/permissions/metadata.js
@@ -0,0 +1,122 @@
+import { createHash } from 'node:crypto';
+import { sql } from '../_lib/db.js';
+import { json, error, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+// Populated by task 03 (src/erc7710/abi.js). Until that ships, unknown chains get null.
+let DELEGATION_MANAGER_DEPLOYMENTS = {};
+try {
+ const mod = await import('../../src/erc7710/abi.js');
+ DELEGATION_MANAGER_DEPLOYMENTS = mod.DELEGATION_MANAGER_DEPLOYMENTS ?? {};
+} catch {
+ // abi.js not yet present — delegationManager will be null
+}
+
+function corsHeaders(res) {
+ res.setHeader('access-control-allow-origin', '*');
+ res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
+ res.setHeader('access-control-allow-headers', 'content-type');
+ res.setHeader('access-control-max-age', '86400');
+}
+
+export default wrap(async (req, res) => {
+ if (req.method === 'OPTIONS') {
+ corsHeaders(res);
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ corsHeaders(res);
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId');
+ if (!agentId) return error(res, 400, 'missing_param', 'agentId is required');
+
+ const chainIdParam = url.searchParams.get('chainId');
+ const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
+ if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ }
+
+ // Verify agent exists
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) {
+ return json(res, 404, { ok: false, error: 'agent_not_found' });
+ }
+
+ const rows = await sql`
+ SELECT
+ chain_id, delegator_address, delegate_address, delegation_hash,
+ delegation_json, scope, expires_at, created_at, revoked_at
+ FROM agent_delegations
+ WHERE agent_id = ${agentId}
+ AND status = 'active'
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY expires_at DESC
+ `;
+
+ const delegations = rows.map((r) => ({
+ chainId: r.chain_id,
+ delegator: r.delegator_address,
+ delegate: r.delegate_address,
+ hash: r.delegation_hash,
+ scope: r.scope,
+ expiresAt: r.expires_at,
+ createdAt: r.created_at,
+ envelope: r.delegation_json,
+ }));
+
+ // delegationManager: use the filtered chain if provided, otherwise first delegation's chain
+ const resolveChain = chainId ?? (rows[0]?.chain_id ?? null);
+ const delegationManager = resolveChain
+ ? (DELEGATION_MANAGER_DEPLOYMENTS[resolveChain] ?? null)
+ : null;
+
+ // Last-Modified: max of created_at and revoked_at across returned rows
+ let lastModified = null;
+ for (const r of rows) {
+ const candidates = [r.created_at, r.revoked_at].filter(Boolean);
+ for (const d of candidates) {
+ if (!lastModified || d > lastModified) lastModified = d;
+ }
+ }
+
+ const body = {
+ ok: true,
+ agentId,
+ spec: 'erc-7715/0.1',
+ delegationManager,
+ delegations,
+ };
+
+ const bodyStr = JSON.stringify(body);
+ const etag = `"${createHash('sha256').update(bodyStr).digest('hex').slice(0, 32)}"`;
+
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');
+ res.setHeader('etag', etag);
+ if (lastModified) res.setHeader('last-modified', new Date(lastModified).toUTCString());
+
+ // ETag short-circuit
+ if (req.headers['if-none-match'] === etag) {
+ res.statusCode = 304;
+ res.end();
+ return;
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(bodyStr);
+});
diff --git a/api/permissions/redeem.js b/api/permissions/redeem.js
new file mode 100644
index 000000000..728cd6fcd
--- /dev/null
+++ b/api/permissions/redeem.js
@@ -0,0 +1,339 @@
+// POST /api/permissions/redeem
+// Server-side delegation relayer: pays gas on behalf of the agent's smart account.
+// Auth: agent bearer token with scope `permissions:redeem`.
+// Feature-flagged via PERMISSIONS_RELAYER_ENABLED env var (default: false).
+
+import { Wallet, JsonRpcProvider, getAddress, isAddress } from 'ethers';
+import { z } from 'zod';
+
+import { sql } from '../_lib/db.js';
+import { authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, error, wrap, readJson, method } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { env } from '../_lib/env.js';
+import { recordEvent } from '../_lib/usage.js';
+import { redeemDelegation, PermissionError } from '../../src/permissions/toolkit.js';
+
+// ── Idempotency cache (in-memory, 10-minute TTL) ───────────────────────────
+const idempotencyCache = new Map();
+const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
+
+function idempotencyGet(key) {
+ const entry = idempotencyCache.get(key);
+ if (!entry) return null;
+ if (Date.now() > entry.expiresAt) {
+ idempotencyCache.delete(key);
+ return null;
+ }
+ return entry.result;
+}
+
+function idempotencySet(key, result) {
+ // Purge expired entries opportunistically.
+ const now = Date.now();
+ for (const [k, v] of idempotencyCache) {
+ if (now > v.expiresAt) idempotencyCache.delete(k);
+ }
+ idempotencyCache.set(key, { result, expiresAt: now + IDEMPOTENCY_TTL_MS });
+}
+
+// ── Validation schemas ─────────────────────────────────────────────────────
+const hexData = z.string().regex(/^0x[0-9a-fA-F]*$/, 'must be 0x-prefixed hex');
+const weiValue = z.string().regex(/^\d+$/, 'value must be a decimal integer string');
+
+const callSchema = z.object({
+ to: z.string().refine((v) => isAddress(v), 'to must be a valid EIP-55 address'),
+ value: weiValue.default('0'),
+ data: hexData.default('0x'),
+});
+
+const bodySchema = z.object({
+ id: z.string().uuid(),
+ calls: z.array(callSchema).min(1).max(4),
+});
+
+// ── ERC-20 selector helpers ────────────────────────────────────────────────
+const TRANSFER_SELECTOR = '0xa9059cbb';
+const TRANSFER_FROM_SELECTOR = '0x23b872dd';
+
+// Decode token amount from ERC-20 transfer/transferFrom calldata.
+// Param slots (0-indexed) start at hex[8 + n*64]. Returns null if unrecognised.
+function decodeErc20AmountFixed(data) {
+ if (!data || data.length < 10) return null;
+ const hex = data.startsWith('0x') ? data.slice(2) : data;
+ const sel = '0x' + hex.slice(0, 8).toLowerCase();
+ try {
+ if (sel === TRANSFER_SELECTOR && hex.length >= 8 + 64 + 64) {
+ // slot 1 (0-indexed) = amount
+ return BigInt('0x' + hex.slice(8 + 64, 8 + 64 + 64));
+ }
+ if (sel === TRANSFER_FROM_SELECTOR && hex.length >= 8 + 64 + 64 + 64) {
+ // slot 2 (0-indexed) = amount
+ return BigInt('0x' + hex.slice(8 + 64 + 64, 8 + 64 + 64 + 64));
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+// ── Period window helper ───────────────────────────────────────────────────
+function periodStart(period) {
+ const now = new Date();
+ if (period === 'daily') {
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
+ }
+ if (period === 'weekly') {
+ const day = now.getUTCDay(); // 0=Sun
+ const diff = day === 0 ? -6 : 1 - day; // back to Monday
+ const monday = new Date(now);
+ monday.setUTCDate(now.getUTCDate() + diff);
+ monday.setUTCHours(0, 0, 0, 0);
+ return monday;
+ }
+ // 'once' or unknown: entire history counts
+ return new Date(0);
+}
+
+// ── RPC URL resolution ─────────────────────────────────────────────────────
+function getRpcUrl(chainId) {
+ return (
+ process.env[`RPC_URL_${chainId}`] ||
+ // Shared fallback names that might already exist in the project
+ (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||
+ (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||
+ null
+ );
+}
+
+// ── Handler ────────────────────────────────────────────────────────────────
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Feature flag — 503 when disabled
+ if (!env.PERMISSIONS_RELAYER_ENABLED) {
+ return error(res, 503, 'feature_disabled', 'relayer not enabled on this deployment');
+ }
+
+ // Rate limit — strict bucket since each request costs gas
+ const ip = clientIp(req);
+ const rl = await limits.strict(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // Auth — agent bearer only (no user sessions on this machine endpoint)
+ const token = extractBearer(req);
+ const bearer = await authenticateBearer(token);
+ if (!bearer) return error(res, 401, 'unauthorized', 'valid bearer token required');
+ if (!hasScope(bearer.scope, 'permissions:redeem')) {
+ return error(res, 403, 'insufficient_scope', "token must include 'permissions:redeem' scope");
+ }
+
+ // Idempotency-Key check (before parsing body — key is in header)
+ const idempotencyKey = req.headers['idempotency-key'] || null;
+
+ // Parse body
+ let body;
+ try {
+ body = parse(bodySchema, await readJson(req));
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'validation_error', err.message);
+ }
+ const { id, calls } = body;
+
+ // Idempotency-Key early return
+ if (idempotencyKey) {
+ const cached = idempotencyGet(`${id}:${idempotencyKey}`);
+ if (cached) return json(res, 200, cached);
+ }
+
+ // Load delegation row
+ const [row] = await sql`
+ SELECT id, agent_id, chain_id, delegation_hash, delegation_json, scope,
+ status, expires_at, redemption_count, last_redeemed_at
+ FROM agent_delegations
+ WHERE id = ${id}
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
+
+ // Check status
+ if (row.status === 'revoked') {
+ return error(res, 409, 'delegation_revoked', 'delegation has been revoked');
+ }
+
+ // Check expiry; auto-flip status if expired
+ const now = new Date();
+ if (new Date(row.expires_at) <= now) {
+ // Side-effect: mark as expired without blocking
+ sql`UPDATE agent_delegations SET status = 'expired' WHERE id = ${id}`.catch(() => {});
+ return error(res, 409, 'delegation_expired', 'delegation has expired');
+ }
+
+ if (row.status !== 'active') {
+ return error(res, 409, 'delegation_expired', `delegation status is '${row.status}'`);
+ }
+
+ const scope = row.scope;
+ const chainId = row.chain_id;
+
+ // ── Server-side scope checks (cheap, prevent paying gas on doomed tx) ────
+
+ // 1. Target allow-list
+ const allowedTargets = new Set((scope.targets || []).map((t) => t.toLowerCase()));
+ for (const call of calls) {
+ if (!allowedTargets.has(call.to.toLowerCase())) {
+ return error(res, 403, 'target_not_allowed', `call target ${call.to} is not in scope.targets`);
+ }
+ }
+
+ // 2. Native ETH: reject non-zero value if token is ERC-20
+ const isNative = scope.token === 'native';
+ if (!isNative) {
+ for (const call of calls) {
+ if (BigInt(call.value) > 0n) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'non-zero ETH value not allowed for ERC-20 scoped delegation',
+ );
+ }
+ }
+ }
+
+ // 3. Amount cap: compute period spend from usage_events history
+ const maxAmount = BigInt(scope.maxAmount || '0');
+ const pStart = periodStart(scope.period || 'daily');
+
+ if (isNative) {
+ // Sum ETH values in this request
+ const requestAmount = calls.reduce((s, c) => s + BigInt(c.value), 0n);
+
+ // Query period history
+ const [histRow] = await sql`
+ SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
+ FROM usage_events
+ WHERE kind = 'permissions.redeem'
+ AND meta->>'delegation_id' = ${id}
+ AND created_at >= ${pStart.toISOString()}
+ `;
+ const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
+
+ if (requestAmount + historicalSpend > maxAmount) {
+ return error(res, 403, 'scope_exceeded', 'ETH spend would exceed scope.maxAmount for this period', {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ });
+ }
+ } else {
+ // ERC-20: decode transfer amounts from call data
+ let requestAmount = 0n;
+ for (const call of calls) {
+ const decoded = decodeErc20AmountFixed(call.data);
+ if (decoded === null) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ `call to ${call.to} does not look like an ERC-20 transfer or transferFrom`,
+ );
+ }
+ requestAmount += decoded;
+ }
+
+ const [histRow] = await sql`
+ SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
+ FROM usage_events
+ WHERE kind = 'permissions.redeem'
+ AND meta->>'delegation_id' = ${id}
+ AND created_at >= ${pStart.toISOString()}
+ `;
+ const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
+
+ if (requestAmount + historicalSpend > maxAmount) {
+ return error(res, 403, 'scope_exceeded', 'token spend would exceed scope.maxAmount for this period', {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ });
+ }
+ }
+
+ // ── Build signer ───────────────────────────────────────────────────────
+ const rpcUrl = getRpcUrl(chainId);
+ if (!rpcUrl) {
+ return error(res, 502, 'rpc_error', `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`);
+ }
+
+ let signer;
+ try {
+ const provider = new JsonRpcProvider(rpcUrl);
+ // AGENT_RELAYER_KEY is never logged — only use it to construct the Wallet
+ signer = new Wallet(env.AGENT_RELAYER_KEY, provider);
+ } catch {
+ return error(res, 500, 'internal_error', 'failed to initialise relayer signer');
+ }
+
+ // ── Submit on-chain ────────────────────────────────────────────────────
+ let txHash, receipt;
+ try {
+ ({ txHash, receipt } = await redeemDelegation({
+ delegation: row.delegation_json,
+ delegationHash: row.delegation_hash,
+ calls,
+ signer,
+ chainId,
+ }));
+ } catch (err) {
+ if (err instanceof PermissionError && err.code === 'delegation_revoked') {
+ // Auto-sync status in DB
+ sql`UPDATE agent_delegations SET status = 'revoked' WHERE id = ${id}`.catch(() => {});
+ return error(res, 409, 'delegation_revoked', err.message);
+ }
+ // RPC or provider error
+ console.error('[permissions/redeem] on-chain error', err?.code, err?.message);
+ return error(res, 502, 'rpc_error', err?.message || 'on-chain call failed');
+ }
+
+ // ── Update DB ──────────────────────────────────────────────────────────
+ await sql`
+ UPDATE agent_delegations
+ SET redemption_count = redemption_count + 1,
+ last_redeemed_at = NOW()
+ WHERE id = ${id}
+ `;
+
+ // Compute amount redeemed for usage tracking
+ const redeemAmount = isNative
+ ? calls.reduce((s, c) => s + BigInt(c.value), 0n).toString()
+ : calls.reduce((s, c) => {
+ const a = decodeErc20AmountFixed(c.data);
+ return s + (a ?? 0n);
+ }, 0n).toString();
+
+ recordEvent({
+ userId: bearer.userId,
+ apiKeyId: bearer.apiKeyId ?? null,
+ agentId: row.agent_id,
+ kind: 'permissions.redeem',
+ status: 'ok',
+ meta: {
+ delegation_id: id,
+ chain_id: chainId,
+ tx_hash: txHash,
+ gas_used: receipt.gasUsed,
+ amount: redeemAmount,
+ },
+ });
+
+ const result = { ok: true, txHash, receipt };
+
+ if (idempotencyKey) {
+ idempotencySet(`${id}:${idempotencyKey}`, result);
+ }
+
+ return json(res, 200, result);
+});
diff --git a/api/permissions/revoke.js b/api/permissions/revoke.js
new file mode 100644
index 000000000..a942b63d1
--- /dev/null
+++ b/api/permissions/revoke.js
@@ -0,0 +1,125 @@
+// POST /api/permissions/revoke
+// Mirrors an on-chain DelegationManager.disableDelegation() call into the DB.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, method, readJson, wrap, error, json } from '../_lib/http.js';
+import { limits } from '../_lib/rate-limit.js';
+import { recordEvent } from '../_lib/usage.js';
+import { SERVER_CHAIN_META } from '../_lib/onchain.js';
+import {
+ DELEGATION_MANAGER_ABI,
+ DELEGATION_MANAGER_DEPLOYMENTS,
+} from '../../src/erc7710/abi.js';
+import { z } from 'zod';
+import { JsonRpcProvider, Contract, Interface } from 'ethers';
+
+const bodySchema = z.object({
+ id: z.string().uuid(),
+ txHash: z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 66-char 0x-prefixed hex string'),
+});
+
+const iface = new Interface(DELEGATION_MANAGER_ABI);
+const DISABLED_TOPIC = iface.getEvent('DelegationDisabled').topicHash;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.permissionsRevoke(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = await readJson(req);
+ const parsed = bodySchema.safeParse(raw);
+ if (!parsed.success) {
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
+ return error(res, 400, 'validation_error', msg);
+ }
+ const { id, txHash } = parsed.data;
+
+ // Lookup delegation + agent owner in one join
+ const [row] = await sql`
+ SELECT d.*, a.user_id AS agent_owner_user_id
+ FROM agent_delegations d
+ JOIN agent_identities a ON a.id = d.agent_id AND a.deleted_at IS NULL
+ WHERE d.id = ${id}
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
+
+ // Authorization: agent owner OR the delegator wallet linked to this user
+ const isAgentOwner = row.agent_owner_user_id === user.id;
+ let isDelegator = false;
+ if (!isAgentOwner) {
+ const [wallet] = await sql`
+ SELECT address FROM user_wallets
+ WHERE user_id = ${user.id} AND address = ${row.delegator_address}
+ LIMIT 1
+ `;
+ isDelegator = !!wallet;
+ }
+ if (!isAgentOwner && !isDelegator) {
+ return error(res, 403, 'forbidden', 'you are not authorized to revoke this delegation');
+ }
+
+ // Build a read-only provider for the delegation's chain
+ const chainMeta = SERVER_CHAIN_META[row.chain_id];
+ if (!chainMeta) {
+ return error(res, 400, 'chain_not_supported', `chainId ${row.chain_id} is not supported`);
+ }
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[row.chain_id];
+ if (!managerAddr) {
+ return error(res, 400, 'chain_not_supported', `no DelegationManager for chainId ${row.chain_id}`);
+ }
+
+ const provider = new JsonRpcProvider(chainMeta.rpc, row.chain_id, { staticNetwork: true });
+
+ // Fetch receipt (up to 3 attempts with short back-off for propagation lag)
+ let receipt = null;
+ for (let attempt = 0; attempt < 3 && !receipt; attempt++) {
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 800));
+ receipt = await provider.getTransactionReceipt(txHash).catch(() => null);
+ }
+ if (!receipt) return error(res, 400, 'tx_not_found', 'transaction receipt not found');
+
+ // Decode DelegationDisabled event: (address indexed delegationManager, bytes32 indexed delegationHash)
+ // topics[0] = event sig, topics[1] = delegationManager, topics[2] = delegationHash
+ const disabledLog = receipt.logs.find((log) => log.topics[0] === DISABLED_TOPIC);
+ if (!disabledLog) {
+ return error(res, 400, 'tx_mismatch', 'transaction contains no DelegationDisabled event');
+ }
+
+ const loggedHash = disabledLog.topics[2]; // bytes32 indexed — raw topic IS the value
+ if (loggedHash.toLowerCase() !== row.delegation_hash.toLowerCase()) {
+ return error(res, 400, 'tx_mismatch', 'transaction revoked a different delegation hash');
+ }
+
+ // Second confirmation: call disabledDelegations(hash) on-chain
+ const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, provider);
+ const isDisabled = await manager.disabledDelegations(row.delegation_hash).catch(() => null);
+ if (!isDisabled) {
+ return error(res, 400, 'not_yet_disabled', 'delegation is not yet marked disabled on-chain');
+ }
+
+ // Flip status active → revoked; 0 rows = already revoked / never active
+ const updated = await sql`
+ UPDATE agent_delegations
+ SET status = 'revoked', revoked_at = NOW(), tx_hash_revoke = ${txHash}
+ WHERE id = ${id} AND status = 'active'
+ RETURNING revoked_at
+ `;
+ if (!updated || updated.length === 0) {
+ return error(res, 409, 'already_revoked', 'delegation is already revoked or expired');
+ }
+
+ const revokedAt = updated[0].revoked_at;
+
+ recordEvent({ userId: user.id, agentId: row.agent_id, kind: 'permissions.revoke' });
+
+ return json(res, 200, { ok: true, status: 'revoked', revokedAt });
+});
diff --git a/api/permissions/verify.js b/api/permissions/verify.js
new file mode 100644
index 000000000..2943710c5
--- /dev/null
+++ b/api/permissions/verify.js
@@ -0,0 +1,128 @@
+import { createHash } from 'node:crypto';
+import { Contract, JsonRpcProvider } from 'ethers';
+import { sql } from '../_lib/db.js';
+import { error, wrap } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import {
+ DELEGATION_MANAGER_DEPLOYMENTS,
+ DELEGATION_MANAGER_ABI,
+} from '../../src/erc7710/abi.js';
+
+const HASH_RE = /^0x[0-9a-fA-F]{64}$/;
+const CACHE_VALID = 'public, max-age=30, s-maxage=60';
+const CACHE_INVALID = 'public, max-age=300, s-maxage=600';
+
+export default wrap(async (req, res) => {
+ res.setHeader('access-control-allow-origin', '*');
+ res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
+ res.setHeader('access-control-allow-headers', 'content-type');
+ res.setHeader('access-control-max-age', '86400');
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const hash = url.searchParams.get('hash');
+ const chainIdRaw = url.searchParams.get('chainId');
+
+ if (!hash) return error(res, 400, 'validation_error', 'hash query param is required');
+ if (!HASH_RE.test(hash))
+ return error(res, 400, 'validation_error', 'hash must be 0x + 64 hex chars');
+ if (!chainIdRaw) return error(res, 400, 'validation_error', 'chainId query param is required');
+
+ const chainId = parseInt(chainIdRaw, 10);
+ if (Number.isNaN(chainId) || chainId <= 0)
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ if (!DELEGATION_MANAGER_DEPLOYMENTS[chainId])
+ return error(res, 400, 'validation_error', `chainId ${chainId} is not supported`);
+
+ const checkedAt = new Date().toISOString();
+
+ const [row] = await sql`
+ SELECT status, expires_at
+ FROM agent_delegations
+ WHERE delegation_hash = ${hash} AND chain_id = ${chainId}
+ LIMIT 1
+ `;
+
+ if (row?.status === 'revoked') {
+ return respond(res, { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash }, CACHE_INVALID);
+ }
+
+ if (row?.status === 'expired' || (row?.expires_at && new Date(row.expires_at) <= new Date())) {
+ return respond(res, { ok: true, valid: false, reason: 'delegation_expired', checkedAt, chainId, hash }, CACHE_INVALID);
+ }
+
+ // On-chain check — 5 s timeout
+ let disabled;
+ try {
+ disabled = await withTimeout(checkDisabled(hash, chainId), 5000);
+ } catch (err) {
+ console.error('[verify] rpc error', err);
+ res.statusCode = 502;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(JSON.stringify({ ok: false, error: 'rpc_error', message: err.message }));
+ return;
+ }
+
+ if (disabled) {
+ // Self-heal: if DB still tracks it as active, flip to revoked without blocking the response.
+ if (row?.status === 'active') {
+ console.log(`[verify] self-heal queued for ${hash}`);
+ queueMicrotask(() => {
+ sql`
+ UPDATE agent_delegations
+ SET status = 'revoked', revoked_at = NOW()
+ WHERE delegation_hash = ${hash} AND status = 'active'
+ `.catch((e) => console.error('[verify] self-heal failed', e));
+ });
+ }
+ return respond(res, { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash }, CACHE_INVALID);
+ }
+
+ const body = { ok: true, valid: true, checkedAt, chainId, hash };
+ if (!row) body.reason = 'unknown_to_platform';
+ return respond(res, body, CACHE_VALID);
+});
+
+async function checkDisabled(hash, chainId) {
+ const rpcUrl = process.env[`RPC_URL_${chainId}`];
+ if (!rpcUrl) throw new Error(`no RPC configured for chainId ${chainId}`);
+ const provider = new JsonRpcProvider(rpcUrl);
+ const manager = new Contract(
+ DELEGATION_MANAGER_DEPLOYMENTS[chainId],
+ DELEGATION_MANAGER_ABI,
+ provider,
+ );
+ return manager.isDelegationDisabled(hash);
+}
+
+function withTimeout(promise, ms) {
+ return Promise.race([
+ promise,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`RPC timeout after ${ms}ms`)), ms),
+ ),
+ ]);
+}
+
+function respond(res, body, cacheControl) {
+ const str = JSON.stringify(body);
+ const etag = `"${createHash('sha256').update(str).digest('hex').slice(0, 16)}"`;
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', cacheControl);
+ res.setHeader('etag', etag);
+ res.end(str);
+}
diff --git a/api/subscriptions.js b/api/subscriptions.js
new file mode 100644
index 000000000..e0248d4eb
--- /dev/null
+++ b/api/subscriptions.js
@@ -0,0 +1,118 @@
+/**
+ * /api/subscriptions — manage recurring subscription records.
+ *
+ * POST — create a subscription (viewer has already granted a delegation)
+ * GET — list subscriptions for the authenticated user
+ * DELETE — soft-cancel a subscription (?id=<uuid>); does NOT revoke the delegation
+ */
+
+import { sql } from './_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { z } from 'zod';
+import { parse } from './_lib/validate.js';
+
+const postSchema = z.object({
+ agentId: z.string().uuid(),
+ delegationId: z.string().uuid(),
+ periodSeconds: z.number().int().positive(),
+ amountPerPeriod: z.string().regex(/^\d+$/, 'amountPerPeriod must be a base-unit integer string'),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // ── POST: create subscription ─────────────────────────────────────────────
+
+ if (req.method === 'POST') {
+ let body;
+ try {
+ body = parse(postSchema, await readJson(req));
+ } catch (err) {
+ return error(res, err.status ?? 400, err.code ?? 'validation_error', err.message);
+ }
+ const { agentId, delegationId, periodSeconds, amountPerPeriod } = body;
+
+ // Verify the agent belongs to this user.
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 403, 'forbidden', 'agent not found or not owned by you');
+
+ // Verify the delegation is active and belongs to this agent.
+ const [delegation] = await sql`
+ SELECT id FROM agent_delegations
+ WHERE id = ${delegationId} AND agent_id = ${agentId} AND status = 'active'
+ `;
+ if (!delegation) return error(res, 400, 'validation_error', 'delegation not found or not active');
+
+ // Idempotency: return existing active subscription rather than duplicating.
+ const [existing] = await sql`
+ SELECT id, status, next_charge_at
+ FROM agent_subscriptions
+ WHERE agent_id = ${agentId} AND delegation_id = ${delegationId} AND status = 'active'
+ `;
+ if (existing) return json(res, 200, { data: existing });
+
+ const nextChargeAt = new Date(Date.now() + periodSeconds * 1000);
+ const [row] = await sql`
+ INSERT INTO agent_subscriptions
+ (user_id, agent_id, delegation_id, period_seconds, amount_per_period, next_charge_at)
+ VALUES
+ (${userId}, ${agentId}, ${delegationId}, ${periodSeconds}, ${amountPerPeriod}, ${nextChargeAt.toISOString()})
+ RETURNING id, status, next_charge_at, created_at
+ `;
+ return json(res, 201, { data: row });
+ }
+
+ // ── GET: list subscriptions for authenticated user ────────────────────────
+
+ if (req.method === 'GET') {
+ const agentId = req.query?.agentId ?? null;
+
+ const rows = agentId
+ ? await sql`
+ SELECT id, agent_id, delegation_id, period_seconds, amount_per_period,
+ next_charge_at, last_charge_at, status, last_error, created_at, canceled_at
+ FROM agent_subscriptions
+ WHERE user_id = ${userId} AND agent_id = ${agentId}
+ ORDER BY created_at DESC
+ `
+ : await sql`
+ SELECT id, agent_id, delegation_id, period_seconds, amount_per_period,
+ next_charge_at, last_charge_at, status, last_error, created_at, canceled_at
+ FROM agent_subscriptions
+ WHERE user_id = ${userId}
+ ORDER BY created_at DESC
+ `;
+
+ return json(res, 200, { data: rows });
+ }
+
+ // ── DELETE: soft-cancel ───────────────────────────────────────────────────
+
+ if (req.method === 'DELETE') {
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'validation_error', 'id query param is required');
+
+ const [row] = await sql`
+ UPDATE agent_subscriptions
+ SET status = 'canceled', canceled_at = NOW()
+ WHERE id = ${id} AND user_id = ${userId} AND status != 'canceled'
+ RETURNING id, status, canceled_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'subscription not found or already canceled');
+ return json(res, 200, { data: row });
+ }
+});
diff --git a/dist-lib/agent-3d.js b/dist-lib/agent-3d.js
index 95873ecbd..24bff7ed3 100644
--- a/dist-lib/agent-3d.js
+++ b/dist-lib/agent-3d.js
@@ -1,4 +1,4 @@
-const va = { ROTATE: 0, DOLLY: 1, PAN: 2 }, ga = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, sy = 0, Op = 1, ry = 2, m0 = 1, ay = 2, es = 3, bs = 0, Wn = 1, Oi = 2, Gs = 0, Ca = 1, Qp = 2, Gp = 3, Hp = 4, oy = 5, pr = 100, cy = 101, ly = 102, hy = 103, uy = 104, dy = 200, fy = 201, py = 202, Ay = 203, fd = 204, pd = 205, gy = 206, my = 207, xy = 208, by = 209, Ey = 210, yy = 211, _y = 212, wy = 213, vy = 214, Ad = 0, gd = 1, md = 2, Da = 3, xd = 4, bd = 5, Ed = 6, yd = 7, fh = 0, Cy = 1, Iy = 2, Hs = 0, _d = 1, Sy = 2, My = 3, x0 = 4, By = 5, Ty = 6, Ry = 7, zp = "attached", Fy = "detached", b0 = 300, Br = 301, La = 302, kl = 303, wd = 304, ph = 306, Ws = 1e3, ni = 1001, Ul = 1002, qn = 1003, E0 = 1004, _o = 1005, Xt = 1006, Sl = 1007, ui = 1008, un = 1009, y0 = 1010, _0 = 1011, Go = 1012, Of = 1013, Tr = 1014, fn = 1015, Gn = 1016, Qf = 1017, Gf = 1018, Ho = 1020, w0 = 35902, v0 = 1021, C0 = 1022, pn = 1023, zo = 1026, Vo = 1027, cs = 1028, Hf = 1029, Er = 1030, zf = 1031, Vf = 1033, Ml = 33776, To = 33777, Bl = 33778, Ro = 33779, Ol = 35840, vd = 35841, Ql = 35842, Cd = 35843, Gl = 36196, Hl = 37492, zl = 37496, Wo = 37808, Id = 37809, Sd = 37810, Md = 37811, qo = 37812, Bd = 37813, Td = 37814, Rd = 37815, Fd = 37816, Nd = 37817, Dd = 37818, Ld = 37819, Pd = 37820, kd = 37821, Fo = 36492, Ud = 36494, Vl = 36495, I0 = 36283, Od = 36284, Qd = 36285, Gd = 36286, S0 = 2200, M0 = 2201, Ny = 2202, Ko = 2300, jo = 2301, zh = 2302, ma = 2400, xa = 2401, Wl = 2402, Wf = 2500, Dy = 2501, Ly = 0, B0 = 1, Hd = 2, Py = 3200, ky = 3201, Ah = 0, Uy = 1, Ci = "", _t = "srgb", An = "srgb-linear", ql = "linear", Rt = "srgb", qr = 7680, Vp = 519, Oy = 512, Qy = 513, Gy = 514, T0 = 515, Hy = 516, zy = 517, Vy = 518, Wy = 519, zd = 35044, Wp = "300 es", ls = 2e3, Kl = 2001;
+const va = { ROTATE: 0, DOLLY: 1, PAN: 2 }, ga = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, iy = 0, Op = 1, sy = 2, g0 = 1, ry = 2, es = 3, bs = 0, Wn = 1, Oi = 2, Gs = 0, Ca = 1, Qp = 2, Gp = 3, Hp = 4, ay = 5, pr = 100, oy = 101, cy = 102, ly = 103, hy = 104, uy = 200, dy = 201, fy = 202, py = 203, fd = 204, pd = 205, Ay = 206, gy = 207, my = 208, xy = 209, by = 210, Ey = 211, yy = 212, _y = 213, wy = 214, Ad = 0, gd = 1, md = 2, Da = 3, xd = 4, bd = 5, Ed = 6, yd = 7, fh = 0, vy = 1, Cy = 2, Hs = 0, _d = 1, Iy = 2, Sy = 3, m0 = 4, My = 5, By = 6, Ty = 7, zp = "attached", Ry = "detached", x0 = 300, Br = 301, La = 302, kl = 303, wd = 304, ph = 306, Ws = 1e3, ni = 1001, Ul = 1002, qn = 1003, b0 = 1004, _o = 1005, Xt = 1006, Sl = 1007, ui = 1008, un = 1009, E0 = 1010, y0 = 1011, Go = 1012, Of = 1013, Tr = 1014, fn = 1015, Gn = 1016, Qf = 1017, Gf = 1018, Ho = 1020, _0 = 35902, w0 = 1021, v0 = 1022, pn = 1023, zo = 1026, Vo = 1027, cs = 1028, Hf = 1029, Er = 1030, zf = 1031, Vf = 1033, Ml = 33776, To = 33777, Bl = 33778, Ro = 33779, Ol = 35840, vd = 35841, Ql = 35842, Cd = 35843, Gl = 36196, Hl = 37492, zl = 37496, Wo = 37808, Id = 37809, Sd = 37810, Md = 37811, qo = 37812, Bd = 37813, Td = 37814, Rd = 37815, Fd = 37816, Nd = 37817, Dd = 37818, Ld = 37819, Pd = 37820, kd = 37821, Fo = 36492, Ud = 36494, Vl = 36495, C0 = 36283, Od = 36284, Qd = 36285, Gd = 36286, I0 = 2200, S0 = 2201, Fy = 2202, Ko = 2300, jo = 2301, zh = 2302, ma = 2400, xa = 2401, Wl = 2402, Wf = 2500, Ny = 2501, Dy = 0, M0 = 1, Hd = 2, Ly = 3200, Py = 3201, Ah = 0, ky = 1, Ci = "", _t = "srgb", An = "srgb-linear", ql = "linear", Rt = "srgb", qr = 7680, Vp = 519, Uy = 512, Oy = 513, Qy = 514, B0 = 515, Gy = 516, Hy = 517, zy = 518, Vy = 519, zd = 35044, Wp = "300 es", ls = 2e3, Kl = 2001;
class Js {
/**
* Adds the given event listener to the given event type.
@@ -68,57 +68,57 @@ function ot(i, e, t) {
function qf(i, e) {
return (i % e + e) % e;
}
-function qy(i, e, t, n, s) {
+function Wy(i, e, t, n, s) {
return n + (i - e) * (s - n) / (t - e);
}
-function Ky(i, e, t) {
+function qy(i, e, t) {
return i !== e ? (t - i) / (e - i) : 0;
}
function Do(i, e, t) {
return (1 - t) * i + t * e;
}
-function jy(i, e, t, n) {
+function Ky(i, e, t, n) {
return Do(i, e, 1 - Math.exp(-t * n));
}
-function Xy(i, e = 1) {
+function jy(i, e = 1) {
return e - Math.abs(qf(i, e * 2) - e);
}
-function Yy(i, e, t) {
+function Xy(i, e, t) {
return i <= e ? 0 : i >= t ? 1 : (i = (i - e) / (t - e), i * i * (3 - 2 * i));
}
-function Jy(i, e, t) {
+function Yy(i, e, t) {
return i <= e ? 0 : i >= t ? 1 : (i = (i - e) / (t - e), i * i * i * (i * (i * 6 - 15) + 10));
}
-function Zy(i, e) {
+function Jy(i, e) {
return i + Math.floor(Math.random() * (e - i + 1));
}
-function $y(i, e) {
+function Zy(i, e) {
return i + Math.random() * (e - i);
}
-function e_(i) {
+function $y(i) {
return i * (0.5 - Math.random());
}
-function t_(i) {
+function e_(i) {
i !== void 0 && (qp = i);
let e = qp += 1831565813;
return e = Math.imul(e ^ e >>> 15, e | 1), e ^= e + Math.imul(e ^ e >>> 7, e | 61), ((e ^ e >>> 14) >>> 0) / 4294967296;
}
-function n_(i) {
+function t_(i) {
return i * No;
}
-function i_(i) {
+function n_(i) {
return i * Pa;
}
-function s_(i) {
+function i_(i) {
return (i & i - 1) === 0 && i !== 0;
}
-function r_(i) {
+function s_(i) {
return Math.pow(2, Math.ceil(Math.log(i) / Math.LN2));
}
-function a_(i) {
+function r_(i) {
return Math.pow(2, Math.floor(Math.log(i) / Math.LN2));
}
-function o_(i, e, t, n, s) {
+function a_(i, e, t, n, s) {
const r = Math.cos, a = Math.sin, o = r(t / 2), c = a(t / 2), l = r((e + n) / 2), h = a((e + n) / 2), u = r((e - n) / 2), d = a((e - n) / 2), f = r((n - e) / 2), p = a((n - e) / 2);
switch (s) {
case "XYX":
@@ -230,7 +230,7 @@ const Cn = {
* @param {number} b2 - Maximum value for range B.
* @return {number} The mapped value.
*/
- mapLinear: qy,
+ mapLinear: Wy,
/**
* Returns the percentage in the closed interval `[0, 1]` of the given value
* between the start and end point.
@@ -242,7 +242,7 @@ const Cn = {
* @param {number} value - A value between start and end.
* @return {number} The interpolation factor.
*/
- inverseLerp: Ky,
+ inverseLerp: qy,
/**
* Returns a value linearly interpolated from two known points based on the given interval -
* `t = 0` will return `x` and `t = 1` will return `y`.
@@ -269,7 +269,7 @@ const Cn = {
* @param {number} dt - Delta time in seconds.
* @return {number} The interpolated value.
*/
- damp: jy,
+ damp: Ky,
/**
* Returns a value that alternates between `0` and the given `length` parameter.
*
@@ -279,7 +279,7 @@ const Cn = {
* @param {number} [length=1] - The positive value the function will pingpong to.
* @return {number} The alternated value.
*/
- pingpong: Xy,
+ pingpong: jy,
/**
* Returns a value in the range `[0,1]` that represents the percentage that `x` has
* moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
@@ -294,7 +294,7 @@ const Cn = {
* @param {number} max - The max value. Any x value above max will be `1`.
* @return {number} The alternated value.
*/
- smoothstep: Yy,
+ smoothstep: Xy,
/**
* A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
* that has zero 1st and 2nd order derivatives at x=0 and x=1.
@@ -306,7 +306,7 @@ const Cn = {
* @param {number} max - The max value. Any x value above max will be `1`.
* @return {number} The alternated value.
*/
- smootherstep: Jy,
+ smootherstep: Yy,
/**
* Returns a random integer from `<low, high>` interval.
*
@@ -316,7 +316,7 @@ const Cn = {
* @param {number} high - The upper value boundary
* @return {number} A random integer.
*/
- randInt: Zy,
+ randInt: Jy,
/**
* Returns a random float from `<low, high>` interval.
*
@@ -326,7 +326,7 @@ const Cn = {
* @param {number} high - The upper value boundary
* @return {number} A random float.
*/
- randFloat: $y,
+ randFloat: Zy,
/**
* Returns a random integer from `<-range/2, range/2>` interval.
*
@@ -335,7 +335,7 @@ const Cn = {
* @param {number} range - Defines the value range.
* @return {number} A random float.
*/
- randFloatSpread: e_,
+ randFloatSpread: $y,
/**
* Returns a deterministic pseudo-random float in the interval `[0, 1]`.
*
@@ -344,7 +344,7 @@ const Cn = {
* @param {number} [s] - The integer seed.
* @return {number} A random float.
*/
- seededRandom: t_,
+ seededRandom: e_,
/**
* Converts degrees to radians.
*
@@ -353,7 +353,7 @@ const Cn = {
* @param {number} degrees - A value in degrees.
* @return {number} The converted value in radians.
*/
- degToRad: n_,
+ degToRad: t_,
/**
* Converts radians to degrees.
*
@@ -362,7 +362,7 @@ const Cn = {
* @param {number} radians - A value in radians.
* @return {number} The converted value in degrees.
*/
- radToDeg: i_,
+ radToDeg: n_,
/**
* Returns `true` if the given number is a power of two.
*
@@ -371,7 +371,7 @@ const Cn = {
* @param {number} value - The value to check.
* @return {boolean} Whether the given number is a power of two or not.
*/
- isPowerOfTwo: s_,
+ isPowerOfTwo: i_,
/**
* Returns the smallest power of two that is greater than or equal to the given number.
*
@@ -380,7 +380,7 @@ const Cn = {
* @param {number} value - The value to find a POT for.
* @return {number} The smallest power of two that is greater than or equal to the given number.
*/
- ceilPowerOfTwo: r_,
+ ceilPowerOfTwo: s_,
/**
* Returns the largest power of two that is less than or equal to the given number.
*
@@ -389,7 +389,7 @@ const Cn = {
* @param {number} value - The value to find a POT for.
* @return {number} The largest power of two that is less than or equal to the given number.
*/
- floorPowerOfTwo: a_,
+ floorPowerOfTwo: r_,
/**
* Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
* defined by the given angles and order.
@@ -405,7 +405,7 @@ const Cn = {
* @param {number} c - The rotation applied to the third axis, in radians.
* @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
*/
- setQuaternionFromProperEuler: o_,
+ setQuaternionFromProperEuler: a_,
/**
* Normalizes the given value according to the given typed array.
*
@@ -1337,7 +1337,7 @@ class at {
}
}
const Vh = /* @__PURE__ */ new at();
-function R0(i) {
+function T0(i) {
for (let e = i.length - 1; e >= 0; --e)
if (i[e] >= 65535) return !0;
return !1;
@@ -1345,7 +1345,7 @@ function R0(i) {
function Xo(i) {
return document.createElementNS("http://www.w3.org/1999/xhtml", i);
}
-function c_() {
+function o_() {
const i = Xo("canvas");
return i.style.display = "block", i;
}
@@ -1353,7 +1353,7 @@ const Kp = {};
function Tl(i) {
i in Kp || (Kp[i] = !0, console.warn(i));
}
-function l_(i, e, t) {
+function c_(i, e, t) {
return new Promise(function(n, s) {
function r() {
switch (i.clientWaitSync(e, i.SYNC_FLUSH_COMMANDS_BIT, 0)) {
@@ -1370,11 +1370,11 @@ function l_(i, e, t) {
setTimeout(r, t);
});
}
-function h_(i) {
+function l_(i) {
const e = i.elements;
e[2] = 0.5 * e[2] + 0.5 * e[3], e[6] = 0.5 * e[6] + 0.5 * e[7], e[10] = 0.5 * e[10] + 0.5 * e[11], e[14] = 0.5 * e[14] + 0.5 * e[15];
}
-function u_(i) {
+function h_(i) {
const e = i.elements;
e[11] === -1 ? (e[10] = -e[10] - 1, e[14] = -e[14]) : (e[10] = -e[10], e[14] = -e[14] + 1);
}
@@ -1399,7 +1399,7 @@ const jp = /* @__PURE__ */ new at().set(
-0.203977,
1.0569715
);
-function d_() {
+function u_() {
const i = {
enabled: !0,
workingColorSpace: An,
@@ -1476,7 +1476,7 @@ function d_() {
}
}), i;
}
-const rt = /* @__PURE__ */ d_();
+const rt = /* @__PURE__ */ u_();
function ps(i) {
return i < 0.04045 ? i * 0.0773993808 : Math.pow(i * 0.9478672986 + 0.0521327014, 2.4);
}
@@ -1484,7 +1484,7 @@ function Ia(i) {
return i < 31308e-7 ? i * 12.92 : 1.055 * Math.pow(i, 0.41666) - 0.055;
}
let Kr;
-class f_ {
+class d_ {
/**
* Returns a data URI containing a representation of the given image.
*
@@ -1534,7 +1534,7 @@ class f_ {
return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e;
}
}
-let p_ = 0;
+let f_ = 0;
class Kf {
/**
* Constructs a new video texture.
@@ -1542,7 +1542,7 @@ class Kf {
* @param {any} [data=null] - The data definition of a texture.
*/
constructor(e = null) {
- this.isSource = !0, Object.defineProperty(this, "id", { value: p_++ }), this.uuid = Bi(), this.data = e, this.dataReady = !0, this.version = 0;
+ this.isSource = !0, Object.defineProperty(this, "id", { value: f_++ }), this.uuid = Bi(), this.data = e, this.dataReady = !0, this.version = 0;
}
/**
* When the property is set to `true`, the engine allocates the memory
@@ -1585,14 +1585,14 @@ class Kf {
}
}
function Wh(i) {
- return typeof HTMLImageElement < "u" && i instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && i instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && i instanceof ImageBitmap ? f_.getDataURL(i) : i.data ? {
+ return typeof HTMLImageElement < "u" && i instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && i instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && i instanceof ImageBitmap ? d_.getDataURL(i) : i.data ? {
data: Array.from(i.data),
width: i.width,
height: i.height,
type: i.data.constructor.name
} : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
}
-let A_ = 0;
+let p_ = 0;
class an extends Js {
/**
* Constructs a new texture.
@@ -1609,7 +1609,7 @@ class an extends Js {
* @param {string} [colorSpace=NoColorSpace] - The color space.
*/
constructor(e = an.DEFAULT_IMAGE, t = an.DEFAULT_MAPPING, n = ni, s = ni, r = Xt, a = ui, o = pn, c = un, l = an.DEFAULT_ANISOTROPY, h = Ci) {
- super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: A_++ }), this.uuid = Bi(), this.name = "", this.source = new Kf(e), this.mipmaps = [], this.mapping = t, this.channel = 0, this.wrapS = n, this.wrapT = s, this.magFilter = r, this.minFilter = a, this.anisotropy = l, this.format = o, this.internalFormat = null, this.type = c, this.offset = new Ze(0, 0), this.repeat = new Ze(1, 1), this.center = new Ze(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new at(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = h, this.userData = {}, this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isTextureArray = !1, this.pmremVersion = 0;
+ super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: p_++ }), this.uuid = Bi(), this.name = "", this.source = new Kf(e), this.mipmaps = [], this.mapping = t, this.channel = 0, this.wrapS = n, this.wrapT = s, this.magFilter = r, this.minFilter = a, this.anisotropy = l, this.format = o, this.internalFormat = null, this.type = c, this.offset = new Ze(0, 0), this.repeat = new Ze(1, 1), this.center = new Ze(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new at(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = h, this.userData = {}, this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isTextureArray = !1, this.pmremVersion = 0;
}
/**
* The image object holding the texture data.
@@ -1703,7 +1703,7 @@ class an extends Js {
* @return {Vector2} The transformed uv vector.
*/
transformUv(e) {
- if (this.mapping !== b0) return e;
+ if (this.mapping !== x0) return e;
if (e.applyMatrix3(this.matrix), e.x < 0 || e.x > 1)
switch (this.wrapS) {
case Ws:
@@ -1755,7 +1755,7 @@ class an extends Js {
}
}
an.DEFAULT_IMAGE = null;
-an.DEFAULT_MAPPING = b0;
+an.DEFAULT_MAPPING = x0;
an.DEFAULT_ANISOTROPY = 1;
class mt {
/**
@@ -2302,7 +2302,7 @@ class mt {
yield this.x, yield this.y, yield this.z, yield this.w;
}
}
-class g_ extends Js {
+class A_ extends Js {
/**
* Render target options.
*
@@ -2432,7 +2432,7 @@ class g_ extends Js {
this.dispatchEvent({ type: "dispose" });
}
}
-class Rr extends g_ {
+class Rr extends A_ {
/**
* Constructs a new 3D render target.
*
@@ -2444,7 +2444,7 @@ class Rr extends g_ {
super(e, t, n), this.isWebGLRenderTarget = !0;
}
}
-class F0 extends an {
+class R0 extends an {
/**
* Constructs a new data array texture.
*
@@ -2475,7 +2475,7 @@ class F0 extends an {
this.layerUpdates.clear();
}
}
-class N0 extends an {
+class F0 extends an {
/**
* Constructs a new data array texture.
*
@@ -4097,7 +4097,7 @@ function Kh(i, e, t, n, s) {
}
return !0;
}
-const m_ = /* @__PURE__ */ new zi(), ro = /* @__PURE__ */ new G(), jh = /* @__PURE__ */ new G();
+const g_ = /* @__PURE__ */ new zi(), ro = /* @__PURE__ */ new G(), jh = /* @__PURE__ */ new G();
class Vi {
/**
* Constructs a new sphere.
@@ -4130,7 +4130,7 @@ class Vi {
*/
setFromPoints(e, t) {
const n = this.center;
- t !== void 0 ? n.copy(t) : m_.setFromPoints(e).getCenter(n);
+ t !== void 0 ? n.copy(t) : g_.setFromPoints(e).getCenter(n);
let s = 0;
for (let r = 0, a = e.length; r < a; r++)
s = Math.max(s, n.distanceToSquared(e[r]));
@@ -4799,7 +4799,7 @@ class Ne {
* @return {Matrix4} A reference to this matrix.
*/
makeRotationFromQuaternion(e) {
- return this.compose(x_, e, b_);
+ return this.compose(m_, e, x_);
}
/**
* Sets the rotation component of the transformation matrix, looking from `eye` towards
@@ -5259,7 +5259,7 @@ class Ne {
return e[t] = n[0], e[t + 1] = n[1], e[t + 2] = n[2], e[t + 3] = n[3], e[t + 4] = n[4], e[t + 5] = n[5], e[t + 6] = n[6], e[t + 7] = n[7], e[t + 8] = n[8], e[t + 9] = n[9], e[t + 10] = n[10], e[t + 11] = n[11], e[t + 12] = n[12], e[t + 13] = n[13], e[t + 14] = n[14], e[t + 15] = n[15], e;
}
}
-const Jr = /* @__PURE__ */ new G(), xi = /* @__PURE__ */ new Ne(), x_ = /* @__PURE__ */ new G(0, 0, 0), b_ = /* @__PURE__ */ new G(1, 1, 1), Ss = /* @__PURE__ */ new G(), Fc = /* @__PURE__ */ new G(), Zn = /* @__PURE__ */ new G(), Jp = /* @__PURE__ */ new Ne(), Zp = /* @__PURE__ */ new Jt();
+const Jr = /* @__PURE__ */ new G(), xi = /* @__PURE__ */ new Ne(), m_ = /* @__PURE__ */ new G(0, 0, 0), x_ = /* @__PURE__ */ new G(1, 1, 1), Ss = /* @__PURE__ */ new G(), Fc = /* @__PURE__ */ new G(), Zn = /* @__PURE__ */ new G(), Jp = /* @__PURE__ */ new Ne(), Zp = /* @__PURE__ */ new Jt();
class dn {
/**
* Constructs a new euler instance.
@@ -5458,7 +5458,7 @@ class dn {
}
}
dn.DEFAULT_ORDER = "XYZ";
-class D0 {
+class N0 {
/**
* Constructs a new layers instance, with membership
* initially set to layer `0`.
@@ -5530,14 +5530,14 @@ class D0 {
return (this.mask & (1 << e | 0)) !== 0;
}
}
-let E_ = 0;
-const $p = /* @__PURE__ */ new G(), Zr = /* @__PURE__ */ new Jt(), Yi = /* @__PURE__ */ new Ne(), Nc = /* @__PURE__ */ new G(), ao = /* @__PURE__ */ new G(), y_ = /* @__PURE__ */ new G(), __ = /* @__PURE__ */ new Jt(), eA = /* @__PURE__ */ new G(1, 0, 0), tA = /* @__PURE__ */ new G(0, 1, 0), nA = /* @__PURE__ */ new G(0, 0, 1), iA = { type: "added" }, w_ = { type: "removed" }, $r = { type: "childadded", child: null }, Zh = { type: "childremoved", child: null };
+let b_ = 0;
+const $p = /* @__PURE__ */ new G(), Zr = /* @__PURE__ */ new Jt(), Yi = /* @__PURE__ */ new Ne(), Nc = /* @__PURE__ */ new G(), ao = /* @__PURE__ */ new G(), E_ = /* @__PURE__ */ new G(), y_ = /* @__PURE__ */ new Jt(), eA = /* @__PURE__ */ new G(1, 0, 0), tA = /* @__PURE__ */ new G(0, 1, 0), nA = /* @__PURE__ */ new G(0, 0, 1), iA = { type: "added" }, __ = { type: "removed" }, $r = { type: "childadded", child: null }, Zh = { type: "childremoved", child: null };
class Tt extends Js {
/**
* Constructs a new 3D object.
*/
constructor() {
- super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: E_++ }), this.uuid = Bi(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Tt.DEFAULT_UP.clone();
+ super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: b_++ }), this.uuid = Bi(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Tt.DEFAULT_UP.clone();
const e = new G(), t = new dn(), n = new Jt(), s = new G(1, 1, 1);
function r() {
n.setFromEuler(t, !1);
@@ -5611,7 +5611,7 @@ class Tt extends Js {
normalMatrix: {
value: new at()
}
- }), this.matrix = new Ne(), this.matrixWorld = new Ne(), this.matrixAutoUpdate = Tt.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new D0(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
+ }), this.matrix = new Ne(), this.matrixWorld = new Ne(), this.matrixAutoUpdate = Tt.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new N0(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
}
/**
* A callback that is executed immediately before a 3D object is rendered to a shadow map.
@@ -5865,7 +5865,7 @@ class Tt extends Js {
return this;
}
const t = this.children.indexOf(e);
- return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent(w_), Zh.child = e, this.dispatchEvent(Zh), Zh.child = null), this;
+ return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent(__), Zh.child = e, this.dispatchEvent(Zh), Zh.child = null), this;
}
/**
* Removes this 3D object from its current parent.
@@ -5968,7 +5968,7 @@ class Tt extends Js {
* @return {Quaternion} The 3D object's rotation in world space.
*/
getWorldQuaternion(e) {
- return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(ao, e, y_), e;
+ return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(ao, e, E_), e;
}
/**
* Returns a vector representing the scale of the 3D object in world space.
@@ -5977,7 +5977,7 @@ class Tt extends Js {
* @return {Vector3} The 3D object's scale in world space.
*/
getWorldScale(e) {
- return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(ao, __, e), e;
+ return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(ao, y_, e), e;
}
/**
* Returns a vector representing the ("look") direction of the 3D object in world space.
@@ -6488,7 +6488,7 @@ class Si {
return e.a.equals(this.a) && e.b.equals(this.b) && e.c.equals(this.c);
}
}
-const L0 = {
+const D0 = {
aliceblue: 15792383,
antiquewhite: 16444375,
aqua: 65535,
@@ -6801,7 +6801,7 @@ let Le = class {
* @return {Color} A reference to this color.
*/
setColorName(e, t = _t) {
- const n = L0[e.toLowerCase()];
+ const n = D0[e.toLowerCase()];
return n !== void 0 ? this.setHex(n, t) : console.warn("THREE.Color: Unknown color " + e), this;
}
/**
@@ -7110,14 +7110,14 @@ let Le = class {
}
};
const Fn = /* @__PURE__ */ new Le();
-Le.NAMES = L0;
-let v_ = 0;
+Le.NAMES = D0;
+let w_ = 0;
class di extends Js {
/**
* Constructs a new material.
*/
constructor() {
- super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: v_++ }), this.uuid = Bi(), this.name = "", this.type = "Material", this.blending = Ca, this.side = bs, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = fd, this.blendDst = pd, this.blendEquation = pr, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new Le(0, 0, 0), this.blendAlpha = 0, this.depthFunc = Da, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = Vp, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = qr, this.stencilZFail = qr, this.stencilZPass = qr, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
+ super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: w_++ }), this.uuid = Bi(), this.name = "", this.type = "Material", this.blending = Ca, this.side = bs, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = fd, this.blendDst = pd, this.blendEquation = pr, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new Le(0, 0, 0), this.blendAlpha = 0, this.depthFunc = Da, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = Vp, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = qr, this.stencilZFail = qr, this.stencilZPass = qr, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
}
/**
* Sets the alpha value to be used when running an alpha test. The material
@@ -7295,8 +7295,8 @@ class Os extends di {
return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this;
}
}
-const rs = /* @__PURE__ */ C_();
-function C_() {
+const rs = /* @__PURE__ */ v_();
+function v_() {
const i = new ArrayBuffer(4), e = new Float32Array(i), t = new Uint32Array(i), n = new Uint32Array(512), s = new Uint32Array(512);
for (let c = 0; c < 256; ++c) {
const l = c - 127;
@@ -7329,12 +7329,12 @@ function C_() {
offsetTable: o
};
}
-function I_(i) {
+function C_(i) {
Math.abs(i) > 65504 && console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."), i = ot(i, -65504, 65504), rs.floatView[0] = i;
const e = rs.uint32View[0], t = e >> 23 & 511;
return rs.baseTable[t] + ((e & 8388607) >> rs.shiftTable[t]);
}
-function S_(i) {
+function I_(i) {
const e = i >> 10;
return rs.uint32View[0] = rs.mantissaTable[rs.offsetTable[e] + (i & 1023)] + rs.exponentTable[e], rs.floatView[0];
}
@@ -7347,7 +7347,7 @@ class rA {
* @return {number} The FP16 value.
*/
static toHalfFloat(e) {
- return I_(e);
+ return C_(e);
}
/**
* Returns a single precision floating point value (FP32) from the given half
@@ -7357,11 +7357,11 @@ class rA {
* @return {number} The FP32 value.
*/
static fromHalfFloat(e) {
- return S_(e);
+ return I_(e);
}
}
const nn = /* @__PURE__ */ new G(), Lc = /* @__PURE__ */ new Ze();
-let M_ = 0;
+let S_ = 0;
class Bn {
/**
* Constructs a new buffer attribute.
@@ -7373,7 +7373,7 @@ class Bn {
constructor(e, t, n = !1) {
if (Array.isArray(e))
throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
- this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: M_++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e !== void 0 ? e.length / t : 0, this.normalized = n, this.usage = zd, this.updateRanges = [], this.gpuType = fn, this.version = 0;
+ this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: S_++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e !== void 0 ? e.length / t : 0, this.normalized = n, this.usage = zd, this.updateRanges = [], this.gpuType = fn, this.version = 0;
}
/**
* A callback function that is executed after the renderer has transferred the attribute
@@ -7696,7 +7696,7 @@ class jf extends Bn {
super(new Uint16Array(e), t, n);
}
}
-class P0 extends Bn {
+class L0 extends Bn {
/**
* Constructs a new buffer attribute.
*
@@ -7720,14 +7720,14 @@ class en extends Bn {
super(new Float32Array(e), t, n);
}
}
-let B_ = 0;
+let M_ = 0;
const si = /* @__PURE__ */ new Ne(), ou = /* @__PURE__ */ new Tt(), na = /* @__PURE__ */ new G(), $n = /* @__PURE__ */ new zi(), oo = /* @__PURE__ */ new zi(), yn = /* @__PURE__ */ new G();
class Tn extends Js {
/**
* Constructs a new geometry.
*/
constructor() {
- super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: B_++ }), this.uuid = Bi(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {};
+ super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: M_++ }), this.uuid = Bi(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {};
}
/**
* Returns the index of this geometry.
@@ -7744,7 +7744,7 @@ class Tn extends Js {
* @return {BufferGeometry} A reference to this instance.
*/
setIndex(e) {
- return Array.isArray(e) ? this.index = new (R0(e) ? P0 : jf)(e, 1) : this.index = e, this;
+ return Array.isArray(e) ? this.index = new (T0(e) ? L0 : jf)(e, 1) : this.index = e, this;
}
/**
* Sets the given indirect attribute to this geometry.
@@ -8354,7 +8354,7 @@ class Zt extends Tt {
}
}
}
-function T_(i, e, t, n, s, r, a, o) {
+function B_(i, e, t, n, s, r, a, o) {
let c;
if (e.side === Wn ? c = n.intersectTriangle(a, r, s, !0, o) : c = n.intersectTriangle(s, r, a, e.side === bs, o), c === null) return null;
Gc.copy(o), Gc.applyMatrix4(i.matrixWorld);
@@ -8367,7 +8367,7 @@ function T_(i, e, t, n, s, r, a, o) {
}
function Hc(i, e, t, n, s, r, a, o, c, l) {
i.getVertexPosition(o, kc), i.getVertexPosition(c, Uc), i.getVertexPosition(l, Oc);
- const h = T_(i, e, t, n, kc, Uc, Oc, cA);
+ const h = B_(i, e, t, n, kc, Uc, Oc, cA);
if (h) {
const u = new G();
Si.getBarycoord(cA, kc, Uc, Oc, u), s && (h.uv = Si.getInterpolatedAttribute(s, o, c, l, u, new Ze())), r && (h.uv1 = Si.getInterpolatedAttribute(r, o, c, l, u, new Ze())), a && (h.normal = Si.getInterpolatedAttribute(a, o, c, l, u, new G()), h.normal.dot(n.direction) > 0 && h.normal.multiplyScalar(-1));
@@ -8460,20 +8460,20 @@ function kn(i) {
}
return e;
}
-function R_(i) {
+function T_(i) {
const e = [];
for (let t = 0; t < i.length; t++)
e.push(i[t].clone());
return e;
}
-function k0(i) {
+function P0(i) {
const e = i.getRenderTarget();
return e === null ? i.outputColorSpace : e.isXRRenderTarget === !0 ? e.texture.colorSpace : rt.workingColorSpace;
}
-const F_ = { clone: ka, merge: kn };
-var N_ = `void main() {
+const R_ = { clone: ka, merge: kn };
+var F_ = `void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
-}`, D_ = `void main() {
+}`, N_ = `void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;
class qs extends di {
@@ -8487,7 +8487,7 @@ class qs extends di {
* by {@link Color#set}.
*/
constructor(e) {
- super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = N_, this.fragmentShader = D_, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
+ super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = F_, this.fragmentShader = N_, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
clipCullDistance: !1,
// set to use vertex shader clipping
multiDraw: !1
@@ -8499,7 +8499,7 @@ class qs extends di {
}, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, e !== void 0 && this.setValues(e);
}
copy(e) {
- return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = ka(e.uniforms), this.uniformsGroups = R_(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this;
+ return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = ka(e.uniforms), this.uniformsGroups = T_(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this;
}
toJSON(e) {
const t = super.toJSON(e);
@@ -8538,7 +8538,7 @@ class qs extends di {
return Object.keys(n).length > 0 && (t.extensions = n), t;
}
}
-class U0 extends Tt {
+class k0 extends Tt {
/**
* Constructs a new camera.
*/
@@ -8571,7 +8571,7 @@ class U0 extends Tt {
}
}
const Bs = /* @__PURE__ */ new G(), lA = /* @__PURE__ */ new Ze(), hA = /* @__PURE__ */ new Ze();
-class In extends U0 {
+class In extends k0 {
/**
* Constructs a new perspective camera.
*
@@ -8738,7 +8738,7 @@ class In extends U0 {
}
}
const ia = -90, sa = 1;
-class L_ extends Tt {
+class D_ extends Tt {
/**
* Constructs a new cube camera.
*
@@ -8793,7 +8793,7 @@ class L_ extends Tt {
n.texture.generateMipmaps = !1, e.setRenderTarget(n, 0, s), e.render(t, r), e.setRenderTarget(n, 1, s), e.render(t, a), e.setRenderTarget(n, 2, s), e.render(t, o), e.setRenderTarget(n, 3, s), e.render(t, c), e.setRenderTarget(n, 4, s), e.render(t, l), n.texture.generateMipmaps = m, e.setRenderTarget(n, 5, s), e.render(t, h), e.setRenderTarget(u, d, f), e.xr.enabled = p, n.texture.needsPMREMUpdate = !0;
}
}
-class O0 extends an {
+class U0 extends an {
/**
* Constructs a new cube texture.
*
@@ -8823,7 +8823,7 @@ class O0 extends an {
this.image = e;
}
}
-class P_ extends Rr {
+class L_ extends Rr {
/**
* Constructs a new cube render target.
*
@@ -8833,7 +8833,7 @@ class P_ extends Rr {
constructor(e = 1, t = {}) {
super(e, e, t), this.isWebGLCubeRenderTarget = !0;
const n = { width: e, height: e, depth: 1 }, s = [n, n, n, n, n, n];
- this.texture = new O0(s, t.mapping, t.wrapS, t.wrapT, t.magFilter, t.minFilter, t.format, t.type, t.anisotropy, t.colorSpace), this.texture.isRenderTargetTexture = !0, this.texture.generateMipmaps = t.generateMipmaps !== void 0 ? t.generateMipmaps : !1, this.texture.minFilter = t.minFilter !== void 0 ? t.minFilter : Xt;
+ this.texture = new U0(s, t.mapping, t.wrapS, t.wrapT, t.magFilter, t.minFilter, t.format, t.type, t.anisotropy, t.colorSpace), this.texture.isRenderTargetTexture = !0, this.texture.generateMipmaps = t.generateMipmaps !== void 0 ? t.generateMipmaps : !1, this.texture.minFilter = t.minFilter !== void 0 ? t.minFilter : Xt;
}
/**
* Converts the given equirectangular texture to a cube map.
@@ -8901,7 +8901,7 @@ class P_ extends Rr {
});
r.uniforms.tEquirect.value = t;
const a = new Zt(s, r), o = t.minFilter;
- return t.minFilter === ui && (t.minFilter = Xt), new L_(1, 10, this).update(e, a), t.minFilter = o, a.geometry.dispose(), a.material.dispose(), this;
+ return t.minFilter === ui && (t.minFilter = Xt), new D_(1, 10, this).update(e, a), t.minFilter = o, a.geometry.dispose(), a.material.dispose(), this;
}
/**
* Clears this cube render target.
@@ -8923,7 +8923,7 @@ class hs extends Tt {
super(), this.isGroup = !0, this.type = "Group";
}
}
-const k_ = { type: "move" };
+const P_ = { type: "move" };
class lu {
/**
* Constructs a new XR controller.
@@ -9021,7 +9021,7 @@ class lu {
}));
} else
c !== null && e.gripSpace && (r = t.getPose(e.gripSpace, n), r !== null && (c.matrix.fromArray(r.transform.matrix), c.matrix.decompose(c.position, c.rotation, c.scale), c.matrixWorldNeedsUpdate = !0, r.linearVelocity ? (c.hasLinearVelocity = !0, c.linearVelocity.copy(r.linearVelocity)) : c.hasLinearVelocity = !1, r.angularVelocity ? (c.hasAngularVelocity = !0, c.angularVelocity.copy(r.angularVelocity)) : c.hasAngularVelocity = !1));
- o !== null && (s = t.getPose(e.targetRaySpace, n), s === null && r !== null && (s = r), s !== null && (o.matrix.fromArray(s.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(s.linearVelocity)) : o.hasLinearVelocity = !1, s.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(s.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(k_)));
+ o !== null && (s = t.getPose(e.targetRaySpace, n), s === null && r !== null && (s = r), s !== null && (o.matrix.fromArray(s.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(s.linearVelocity)) : o.hasLinearVelocity = !1, s.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(s.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(P_)));
}
return o !== null && (o.visible = s !== null), c !== null && (c.visible = r !== null), l !== null && (l.visible = a !== null), this;
}
@@ -9056,7 +9056,7 @@ class Vd extends Tt {
return this.fog !== null && (t.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (t.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (t.object.backgroundIntensity = this.backgroundIntensity), t.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (t.object.environmentIntensity = this.environmentIntensity), t.object.environmentRotation = this.environmentRotation.toArray(), t;
}
}
-class U_ {
+class k_ {
/**
* Constructs a new interleaved buffer.
*
@@ -9448,8 +9448,8 @@ class Xf {
};
}
}
-const uA = /* @__PURE__ */ new G(), dA = /* @__PURE__ */ new mt(), fA = /* @__PURE__ */ new mt(), O_ = /* @__PURE__ */ new G(), pA = /* @__PURE__ */ new Ne(), zc = /* @__PURE__ */ new G(), hu = /* @__PURE__ */ new Vi(), AA = /* @__PURE__ */ new Ne(), uu = /* @__PURE__ */ new dc();
-class Q0 extends Zt {
+const uA = /* @__PURE__ */ new G(), dA = /* @__PURE__ */ new mt(), fA = /* @__PURE__ */ new mt(), U_ = /* @__PURE__ */ new G(), pA = /* @__PURE__ */ new Ne(), zc = /* @__PURE__ */ new G(), hu = /* @__PURE__ */ new Vi(), AA = /* @__PURE__ */ new Ne(), uu = /* @__PURE__ */ new dc();
+class O0 extends Zt {
/**
* Constructs a new skinned mesh.
*
@@ -9524,7 +9524,7 @@ class Q0 extends Zt {
}
}
updateMatrixWorld(e) {
- super.updateMatrixWorld(e), this.bindMode === zp ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === Fy ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
+ super.updateMatrixWorld(e), this.bindMode === zp ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === Ry ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
}
/**
* Applies the bone transform associated with the given index to the given
@@ -9542,7 +9542,7 @@ class Q0 extends Zt {
const a = fA.getComponent(r);
if (a !== 0) {
const o = dA.getComponent(r);
- pA.multiplyMatrices(n.bones[o].matrixWorld, n.boneInverses[o]), t.addScaledVector(O_.copy(uA).applyMatrix4(pA), a);
+ pA.multiplyMatrices(n.bones[o].matrixWorld, n.boneInverses[o]), t.addScaledVector(U_.copy(uA).applyMatrix4(pA), a);
}
}
return t.applyMatrix4(this.bindMatrixInverse);
@@ -9577,7 +9577,7 @@ class gh extends an {
super(null, a, o, c, l, h, s, r, u, d), this.isDataTexture = !0, this.image = { data: e, width: t, height: n }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
}
}
-const gA = /* @__PURE__ */ new Ne(), Q_ = /* @__PURE__ */ new Ne();
+const gA = /* @__PURE__ */ new Ne(), O_ = /* @__PURE__ */ new Ne();
class mh {
/**
* Constructs a new skeleton.
@@ -9634,7 +9634,7 @@ class mh {
update() {
const e = this.bones, t = this.boneInverses, n = this.boneMatrices, s = this.boneTexture;
for (let r = 0, a = e.length; r < a; r++) {
- const o = e[r] ? e[r].matrixWorld : Q_;
+ const o = e[r] ? e[r].matrixWorld : O_;
gA.multiplyMatrices(o, t[r]), gA.toArray(n, r * 16);
}
s !== null && (s.needsUpdate = !0);
@@ -9744,8 +9744,8 @@ class Wd extends Bn {
return e.meshPerAttribute = this.meshPerAttribute, e.isInstancedBufferAttribute = !0, e;
}
}
-const ra = /* @__PURE__ */ new Ne(), mA = /* @__PURE__ */ new Ne(), Vc = [], xA = /* @__PURE__ */ new zi(), G_ = /* @__PURE__ */ new Ne(), co = /* @__PURE__ */ new Zt(), lo = /* @__PURE__ */ new Vi();
-class G0 extends Zt {
+const ra = /* @__PURE__ */ new Ne(), mA = /* @__PURE__ */ new Ne(), Vc = [], xA = /* @__PURE__ */ new zi(), Q_ = /* @__PURE__ */ new Ne(), co = /* @__PURE__ */ new Zt(), lo = /* @__PURE__ */ new Vi();
+class Q0 extends Zt {
/**
* Constructs a new instanced mesh.
*
@@ -9756,7 +9756,7 @@ class G0 extends Zt {
constructor(e, t, n) {
super(e, t), this.isInstancedMesh = !0, this.instanceMatrix = new Wd(new Float32Array(n * 16), 16), this.instanceColor = null, this.morphTexture = null, this.count = n, this.boundingBox = null, this.boundingSphere = null;
for (let s = 0; s < n; s++)
- this.setMatrixAt(s, G_);
+ this.setMatrixAt(s, Q_);
}
/**
* Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
@@ -9872,7 +9872,7 @@ class G0 extends Zt {
this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null);
}
}
-const du = /* @__PURE__ */ new G(), H_ = /* @__PURE__ */ new G(), z_ = /* @__PURE__ */ new at();
+const du = /* @__PURE__ */ new G(), G_ = /* @__PURE__ */ new G(), H_ = /* @__PURE__ */ new at();
class Us {
/**
* Constructs a new plane.
@@ -9928,7 +9928,7 @@ class Us {
* @return {Plane} A reference to this plane.
*/
setFromCoplanarPoints(e, t, n) {
- const s = du.subVectors(n, t).cross(H_.subVectors(e, t)).normalize();
+ const s = du.subVectors(n, t).cross(G_.subVectors(e, t)).normalize();
return this.setFromNormalAndCoplanarPoint(s, e), this;
}
/**
@@ -10052,7 +10052,7 @@ class Us {
* @return {Plane} A reference to this plane.
*/
applyMatrix4(e, t) {
- const n = t || z_.getNormalMatrix(e), s = this.coplanarPoint(du).applyMatrix4(e), r = this.normal.applyMatrix3(n).normalize();
+ const n = t || H_.getNormalMatrix(e), s = this.coplanarPoint(du).applyMatrix4(e), r = this.normal.applyMatrix3(n).normalize();
return this.constant = -s.dot(r), this;
}
/**
@@ -10359,7 +10359,7 @@ class bh extends xh {
return this;
}
}
-class V_ extends xh {
+class z_ extends xh {
/**
* Constructs a new line loop.
*
@@ -10388,7 +10388,7 @@ class Jf extends di {
}
}
const wA = /* @__PURE__ */ new Ne(), qd = /* @__PURE__ */ new dc(), jc = /* @__PURE__ */ new Vi(), Xc = /* @__PURE__ */ new G();
-class W_ extends Tt {
+class V_ extends Tt {
/**
* Constructs a new point cloud.
*
@@ -10483,7 +10483,7 @@ class Eh extends an {
super(null, a, o, c, l, h, s, r, u, d), this.isCompressedTexture = !0, this.image = { width: t, height: n }, this.mipmaps = e, this.flipY = !1, this.generateMipmaps = !1;
}
}
-class q_ extends Eh {
+class W_ extends Eh {
/**
* Constructs a new compressed array texture.
*
@@ -10517,7 +10517,7 @@ class q_ extends Eh {
this.layerUpdates.clear();
}
}
-class K_ extends Eh {
+class q_ extends Eh {
/**
* Constructs a new compressed texture.
*
@@ -10529,7 +10529,7 @@ class K_ extends Eh {
super(void 0, e[0].width, e[0].height, t, n, Br), this.isCompressedCubeTexture = !0, this.isCubeTexture = !0, this.image = e;
}
}
-class H0 extends an {
+class G0 extends an {
/**
* Constructs a new depth texture.
*
@@ -10557,7 +10557,7 @@ class H0 extends an {
return this.compareFunction !== null && (t.compareFunction = this.compareFunction), t;
}
}
-class j_ {
+class K_ {
/**
* Constructs a new curve.
*/
@@ -10791,13 +10791,13 @@ class j_ {
return this.arcLengthDivisions = e.arcLengthDivisions, this;
}
}
-function X_(i, e, t = 2) {
+function j_(i, e, t = 2) {
const n = e && e.length, s = n ? e[0] * t : i.length;
- let r = z0(i, 0, s, t, !0);
+ let r = H0(i, 0, s, t, !0);
const a = [];
if (!r || r.next === r.prev) return a;
let o, c, l;
- if (n && (r = ew(i, e, r, t)), i.length > 80 * t) {
+ if (n && (r = $_(i, e, r, t)), i.length > 80 * t) {
o = 1 / 0, c = 1 / 0;
let h = -1 / 0, u = -1 / 0;
for (let d = t; d < s; d += t) {
@@ -10808,9 +10808,9 @@ function X_(i, e, t = 2) {
}
return Yo(r, a, t, o, c, l, 0), a;
}
-function z0(i, e, t, n, s) {
+function H0(i, e, t, n, s) {
let r;
- if (s === uw(i, e, t, n) > 0)
+ if (s === hw(i, e, t, n) > 0)
for (let a = e; a < t; a += n) r = CA(a / n | 0, i[a], i[a + 1], r);
else
for (let a = t - n; a >= e; a -= n) r = CA(a / n | 0, i[a], i[a + 1], r);
@@ -10831,21 +10831,21 @@ function Fr(i, e) {
}
function Yo(i, e, t, n, s, r, a) {
if (!i) return;
- !a && r && rw(i, n, s, r);
+ !a && r && sw(i, n, s, r);
let o = i;
for (; i.prev !== i.next; ) {
const c = i.prev, l = i.next;
- if (r ? J_(i, n, s, r) : Y_(i)) {
+ if (r ? Y_(i, n, s, r) : X_(i)) {
e.push(c.i, i.i, l.i), Zo(i), i = l.next, o = l.next;
continue;
}
if (i = l, i === o) {
- a ? a === 1 ? (i = Z_(Fr(i), e), Yo(i, e, t, n, s, r, 2)) : a === 2 && $_(i, e, t, n, s, r) : Yo(Fr(i), e, t, n, s, r, 1);
+ a ? a === 1 ? (i = J_(Fr(i), e), Yo(i, e, t, n, s, r, 2)) : a === 2 && Z_(i, e, t, n, s, r) : Yo(Fr(i), e, t, n, s, r, 1);
break;
}
}
}
-function Y_(i) {
+function X_(i) {
const e = i.prev, t = i, n = i.next;
if (Wt(e, t, n) >= 0) return !1;
const s = e.x, r = t.x, a = n.x, o = e.y, c = t.y, l = n.y, h = Math.min(s, r, a), u = Math.min(o, c, l), d = Math.max(s, r, a), f = Math.max(o, c, l);
@@ -10856,7 +10856,7 @@ function Y_(i) {
}
return !0;
}
-function J_(i, e, t, n) {
+function Y_(i, e, t, n) {
const s = i.prev, r = i, a = i.next;
if (Wt(s, r, a) >= 0) return !1;
const o = s.x, c = r.x, l = a.x, h = s.y, u = r.y, d = a.y, f = Math.min(o, c, l), p = Math.min(h, u, d), m = Math.max(o, c, l), g = Math.max(h, u, d), A = Kd(f, p, e, t, n), _ = Kd(m, g, e, t, n);
@@ -10875,21 +10875,21 @@ function J_(i, e, t, n) {
}
return !0;
}
-function Z_(i, e) {
+function J_(i, e) {
let t = i;
do {
const n = t.prev, s = t.next.next;
- !Ua(n, s) && W0(n, t, t.next, s) && Jo(n, s) && Jo(s, n) && (e.push(n.i, t.i, s.i), Zo(t), Zo(t.next), t = i = s), t = t.next;
+ !Ua(n, s) && V0(n, t, t.next, s) && Jo(n, s) && Jo(s, n) && (e.push(n.i, t.i, s.i), Zo(t), Zo(t.next), t = i = s), t = t.next;
} while (t !== i);
return Fr(t);
}
-function $_(i, e, t, n, s, r) {
+function Z_(i, e, t, n, s, r) {
let a = i;
do {
let o = a.next.next;
for (; o !== a.prev; ) {
- if (a.i !== o.i && cw(a, o)) {
- let c = q0(a, o);
+ if (a.i !== o.i && ow(a, o)) {
+ let c = W0(a, o);
a = Fr(a, a.next), c = Fr(c, c.next), Yo(a, e, t, n, s, r, 0), Yo(c, e, t, n, s, r, 0);
return;
}
@@ -10898,18 +10898,18 @@ function $_(i, e, t, n, s, r) {
a = a.next;
} while (a !== i);
}
-function ew(i, e, t, n) {
+function $_(i, e, t, n) {
const s = [];
for (let r = 0, a = e.length; r < a; r++) {
- const o = e[r] * n, c = r < a - 1 ? e[r + 1] * n : i.length, l = z0(i, o, c, n, !1);
- l === l.next && (l.steiner = !0), s.push(ow(l));
+ const o = e[r] * n, c = r < a - 1 ? e[r + 1] * n : i.length, l = H0(i, o, c, n, !1);
+ l === l.next && (l.steiner = !0), s.push(aw(l));
}
- s.sort(tw);
+ s.sort(ew);
for (let r = 0; r < s.length; r++)
- t = nw(s[r], t);
+ t = tw(s[r], t);
return t;
}
-function tw(i, e) {
+function ew(i, e) {
let t = i.x - e.x;
if (t === 0 && (t = i.y - e.y, t === 0)) {
const n = (i.next.y - i.y) / (i.next.x - i.x), s = (e.next.y - e.y) / (e.next.x - e.x);
@@ -10917,14 +10917,14 @@ function tw(i, e) {
}
return t;
}
-function nw(i, e) {
- const t = iw(i, e);
+function tw(i, e) {
+ const t = nw(i, e);
if (!t)
return e;
- const n = q0(t, i);
+ const n = W0(t, i);
return Fr(n, n.next), Fr(t, t.next);
}
-function iw(i, e) {
+function nw(i, e) {
let t = e;
const n = i.x, s = i.y;
let r = -1 / 0, a;
@@ -10943,25 +10943,25 @@ function iw(i, e) {
let h = 1 / 0;
t = a;
do {
- if (n >= t.x && t.x >= c && n !== t.x && V0(s < l ? n : r, s, c, l, s < l ? r : n, s, t.x, t.y)) {
+ if (n >= t.x && t.x >= c && n !== t.x && z0(s < l ? n : r, s, c, l, s < l ? r : n, s, t.x, t.y)) {
const u = Math.abs(s - t.y) / (n - t.x);
- Jo(t, i) && (u < h || u === h && (t.x > a.x || t.x === a.x && sw(a, t))) && (a = t, h = u);
+ Jo(t, i) && (u < h || u === h && (t.x > a.x || t.x === a.x && iw(a, t))) && (a = t, h = u);
}
t = t.next;
} while (t !== o);
return a;
}
-function sw(i, e) {
+function iw(i, e) {
return Wt(i.prev, i, e.prev) < 0 && Wt(e.next, i, i.next) < 0;
}
-function rw(i, e, t, n) {
+function sw(i, e, t, n) {
let s = i;
do
s.z === 0 && (s.z = Kd(s.x, s.y, e, t, n)), s.prevZ = s.prev, s.nextZ = s.next, s = s.next;
while (s !== i);
- s.prevZ.nextZ = null, s.prevZ = null, aw(s);
+ s.prevZ.nextZ = null, s.prevZ = null, rw(s);
}
-function aw(i) {
+function rw(i) {
let e, t = 1;
do {
let n = i, s;
@@ -10984,22 +10984,22 @@ function aw(i) {
function Kd(i, e, t, n, s) {
return i = (i - t) * s | 0, e = (e - n) * s | 0, i = (i | i << 8) & 16711935, i = (i | i << 4) & 252645135, i = (i | i << 2) & 858993459, i = (i | i << 1) & 1431655765, e = (e | e << 8) & 16711935, e = (e | e << 4) & 252645135, e = (e | e << 2) & 858993459, e = (e | e << 1) & 1431655765, i | e << 1;
}
-function ow(i) {
+function aw(i) {
let e = i, t = i;
do
(e.x < t.x || e.x === t.x && e.y < t.y) && (t = e), e = e.next;
while (e !== i);
return t;
}
-function V0(i, e, t, n, s, r, a, o) {
+function z0(i, e, t, n, s, r, a, o) {
return (s - a) * (e - o) >= (i - a) * (r - o) && (i - a) * (n - o) >= (t - a) * (e - o) && (t - a) * (r - o) >= (s - a) * (n - o);
}
function wo(i, e, t, n, s, r, a, o) {
- return !(i === a && e === o) && V0(i, e, t, n, s, r, a, o);
+ return !(i === a && e === o) && z0(i, e, t, n, s, r, a, o);
}
-function cw(i, e) {
- return i.next.i !== e.i && i.prev.i !== e.i && !lw(i, e) && // dones't intersect other edges
- (Jo(i, e) && Jo(e, i) && hw(i, e) && // locally visible
+function ow(i, e) {
+ return i.next.i !== e.i && i.prev.i !== e.i && !cw(i, e) && // dones't intersect other edges
+ (Jo(i, e) && Jo(e, i) && lw(i, e) && // locally visible
(Wt(i.prev, i, e.prev) || Wt(i, e.prev, e)) || // does not create opposite-facing sectors
Ua(i, e) && Wt(i.prev, i, i.next) > 0 && Wt(e.prev, e, e.next) > 0);
}
@@ -11009,7 +11009,7 @@ function Wt(i, e, t) {
function Ua(i, e) {
return i.x === e.x && i.y === e.y;
}
-function W0(i, e, t, n) {
+function V0(i, e, t, n) {
const s = Jc(Wt(i, e, t)), r = Jc(Wt(i, e, n)), a = Jc(Wt(t, n, i)), o = Jc(Wt(t, n, e));
return !!(s !== r && a !== o || s === 0 && Yc(i, t, e) || r === 0 && Yc(i, n, e) || a === 0 && Yc(t, i, n) || o === 0 && Yc(t, e, n));
}
@@ -11019,10 +11019,10 @@ function Yc(i, e, t) {
function Jc(i) {
return i > 0 ? 1 : i < 0 ? -1 : 0;
}
-function lw(i, e) {
+function cw(i, e) {
let t = i;
do {
- if (t.i !== i.i && t.next.i !== i.i && t.i !== e.i && t.next.i !== e.i && W0(t, t.next, i, e)) return !0;
+ if (t.i !== i.i && t.next.i !== i.i && t.i !== e.i && t.next.i !== e.i && V0(t, t.next, i, e)) return !0;
t = t.next;
} while (t !== i);
return !1;
@@ -11030,7 +11030,7 @@ function lw(i, e) {
function Jo(i, e) {
return Wt(i.prev, i, i.next) < 0 ? Wt(i, e, i.next) >= 0 && Wt(i, i.prev, e) >= 0 : Wt(i, e, i.prev) < 0 || Wt(i, i.next, e) < 0;
}
-function hw(i, e) {
+function lw(i, e) {
let t = i, n = !1;
const s = (i.x + e.x) / 2, r = (i.y + e.y) / 2;
do
@@ -11038,7 +11038,7 @@ function hw(i, e) {
while (t !== i);
return n;
}
-function q0(i, e) {
+function W0(i, e) {
const t = jd(i.i, i.x, i.y), n = jd(e.i, e.x, e.y), s = i.next, r = e.prev;
return i.next = e, e.prev = i, t.next = s, s.prev = t, n.next = t, t.prev = n, r.next = n, n.prev = r, n;
}
@@ -11068,13 +11068,13 @@ function jd(i, e, t) {
// indicates whether this is a steiner point
};
}
-function uw(i, e, t, n) {
+function hw(i, e, t, n) {
let s = 0;
for (let r = e, a = t - n; r < t; r += n)
s += (i[a] - i[r]) * (i[r + 1] + i[a + 1]), a = r;
return s;
}
-class dw {
+class uw {
/**
* Triangulates the given shape definition by returning an array of triangles.
*
@@ -11085,7 +11085,7 @@ class dw {
* representing vertex indices.
*/
static triangulate(e, t, n = 2) {
- return X_(e, t, n);
+ return j_(e, t, n);
}
}
class Zf {
@@ -11125,7 +11125,7 @@ class Zf {
t.forEach(IA);
for (let c = 0; c < t.length; c++)
s.push(a), a += t[c].length, SA(n, t[c]);
- const o = dw.triangulate(n, s);
+ const o = uw.triangulate(n, s);
for (let c = 0; c < o.length; c += 3)
r.push(o.slice(c, c + 3));
return r;
@@ -11331,7 +11331,7 @@ class Zc extends di {
return super.copy(e), this.color.copy(e.color), this.specular.copy(e.specular), this.shininess = e.shininess, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
}
}
-class fw extends di {
+class dw extends di {
/**
* Constructs a new mesh lambert material.
*
@@ -11348,7 +11348,7 @@ class fw extends di {
return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
}
}
-class pw extends di {
+class fw extends di {
/**
* Constructs a new mesh depth material.
*
@@ -11359,13 +11359,13 @@ class pw extends di {
* by {@link Color#set}.
*/
constructor(e) {
- super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = Py, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e);
+ super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = Ly, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e);
}
copy(e) {
return super.copy(e), this.depthPacking = e.depthPacking, this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this;
}
}
-class Aw extends di {
+class pw extends di {
/**
* Constructs a new mesh distance material.
*
@@ -11385,10 +11385,10 @@ class Aw extends di {
function $c(i, e) {
return !i || i.constructor === e ? i : typeof e.BYTES_PER_ELEMENT == "number" ? new e(i) : Array.prototype.slice.call(i);
}
-function gw(i) {
+function Aw(i) {
return ArrayBuffer.isView(i) && !(i instanceof DataView);
}
-function mw(i) {
+function gw(i) {
function e(s, r) {
return i[s] - i[r];
}
@@ -11405,7 +11405,7 @@ function MA(i, e, t) {
}
return s;
}
-function K0(i, e, t, n) {
+function q0(i, e, t, n) {
let s = 1, r = i[0];
for (; r !== void 0 && r[n] === void 0; )
r = i[s++];
@@ -11534,7 +11534,7 @@ class fc {
intervalChanged_() {
}
}
-class xw extends fc {
+class mw extends fc {
/**
* Constructs a new cubic interpolant.
*
@@ -11584,7 +11584,7 @@ class xw extends fc {
return r;
}
}
-class j0 extends fc {
+class K0 extends fc {
/**
* Constructs a new linear interpolant.
*
@@ -11603,7 +11603,7 @@ class j0 extends fc {
return r;
}
}
-class bw extends fc {
+class xw extends fc {
/**
* Constructs a new discrete interpolant.
*
@@ -11664,7 +11664,7 @@ class Ti {
* @return {DiscreteInterpolant} The new interpolant.
*/
InterpolantFactoryMethodDiscrete(e) {
- return new bw(this.times, this.values, this.getValueSize(), e);
+ return new xw(this.times, this.values, this.getValueSize(), e);
}
/**
* Factory method for creating a new linear interpolant.
@@ -11674,7 +11674,7 @@ class Ti {
* @return {LinearInterpolant} The new interpolant.
*/
InterpolantFactoryMethodLinear(e) {
- return new j0(this.times, this.values, this.getValueSize(), e);
+ return new K0(this.times, this.values, this.getValueSize(), e);
}
/**
* Factory method for creating a new smooth interpolant.
@@ -11684,7 +11684,7 @@ class Ti {
* @return {CubicInterpolant} The new interpolant.
*/
InterpolantFactoryMethodSmooth(e) {
- return new xw(this.times, this.values, this.getValueSize(), e);
+ return new mw(this.times, this.values, this.getValueSize(), e);
}
/**
* Defines the interpolation factor method for this keyframe track.
@@ -11816,7 +11816,7 @@ class Ti {
}
a = c;
}
- if (s !== void 0 && gw(s))
+ if (s !== void 0 && Aw(s))
for (let o = 0, c = s.length; o !== c; ++o) {
const l = s[o];
if (isNaN(l)) {
@@ -11903,7 +11903,7 @@ ja.prototype.ValueBufferType = Array;
ja.prototype.DefaultInterpolation = Ko;
ja.prototype.InterpolantFactoryMethodLinear = void 0;
ja.prototype.InterpolantFactoryMethodSmooth = void 0;
-class X0 extends Ti {
+class j0 extends Ti {
/**
* Constructs a new color keyframe track.
*
@@ -11916,7 +11916,7 @@ class X0 extends Ti {
super(e, t, n, s);
}
}
-X0.prototype.ValueTypeName = "color";
+j0.prototype.ValueTypeName = "color";
class Nr extends Ti {
/**
* Constructs a new number keyframe track.
@@ -11931,7 +11931,7 @@ class Nr extends Ti {
}
}
Nr.prototype.ValueTypeName = "number";
-class Ew extends fc {
+class bw extends fc {
/**
* Constructs a new SLERP interpolant.
*
@@ -11971,7 +11971,7 @@ class Ks extends Ti {
* @return {QuaternionLinearInterpolant} The new interpolant.
*/
InterpolantFactoryMethodLinear(e) {
- return new Ew(this.times, this.values, this.getValueSize(), e);
+ return new bw(this.times, this.values, this.getValueSize(), e);
}
}
Ks.prototype.ValueTypeName = "quaternion";
@@ -12038,7 +12038,7 @@ class Jl {
static parse(e) {
const t = [], n = e.tracks, s = 1 / (e.fps || 1);
for (let a = 0, o = n.length; a !== o; ++a)
- t.push(_w(n[a]).scale(s));
+ t.push(yw(n[a]).scale(s));
const r = new this(e.name, e.duration, t, e.blendMode);
return r.uuid = e.uuid, r;
}
@@ -12084,7 +12084,7 @@ class Jl {
o,
(o + 1) % r
), l.push(0, 1, 0);
- const h = mw(c);
+ const h = gw(c);
c = MA(c, 1, h), l = MA(l, 1, h), !s && c[0] === 0 && (c.push(r), l.push(l[0])), a.push(
new Nr(
".morphTargetInfluences[" + t[o].name + "]",
@@ -12159,7 +12159,7 @@ class Jl {
const n = function(u, d, f, p, m) {
if (f.length !== 0) {
const g = [], A = [];
- K0(f, g, A, p), g.length !== 0 && m.push(new u(d, g, A));
+ q0(f, g, A, p), g.length !== 0 && m.push(new u(d, g, A));
}
}, s = [], r = e.name || "default", a = e.fps || 30, o = e.blendMode;
let c = e.length || -1;
@@ -12275,7 +12275,7 @@ class Jl {
return this.constructor.toJSON(this);
}
}
-function yw(i) {
+function Ew(i) {
switch (i.toLowerCase()) {
case "scalar":
case "double":
@@ -12289,7 +12289,7 @@ function yw(i) {
case "vector4":
return Dr;
case "color":
- return X0;
+ return j0;
case "quaternion":
return Ks;
case "bool":
@@ -12300,13 +12300,13 @@ function yw(i) {
}
throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + i);
}
-function _w(i) {
+function yw(i) {
if (i.type === void 0)
throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");
- const e = yw(i.type);
+ const e = Ew(i.type);
if (i.times === void 0) {
const t = [], n = [];
- K0(i.keys, t, n, "value"), i.times = t, i.values = n;
+ q0(i.keys, t, n, "value"), i.times = t, i.values = n;
}
return e.parse !== void 0 ? e.parse(i) : new e(i.name, i.times, i.values, i.interpolation);
}
@@ -12366,7 +12366,7 @@ const us = {
this.files = {};
}
};
-class Y0 {
+class X0 {
/**
* Constructs a new loading manager.
*
@@ -12403,7 +12403,7 @@ class Y0 {
};
}
}
-const ww = /* @__PURE__ */ new Y0();
+const _w = /* @__PURE__ */ new X0();
class pi {
/**
* Constructs a new loader.
@@ -12411,7 +12411,7 @@ class pi {
* @param {LoadingManager} [manager] - The loading manager.
*/
constructor(e) {
- this.manager = e !== void 0 ? e : ww, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {};
+ this.manager = e !== void 0 ? e : _w, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {};
}
/**
* This method needs to be implemented by all concrete loaders. It holds the
@@ -12498,7 +12498,7 @@ class pi {
}
pi.DEFAULT_MATERIAL_NAME = "__DEFAULT";
const $i = {};
-class vw extends Error {
+class ww extends Error {
constructor(e, t) {
super(e), this.response = t;
}
@@ -12576,7 +12576,7 @@ class As extends pi {
});
return new Response(g);
} else
- throw new vw(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`, l);
+ throw new ww(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`, l);
}).then((l) => {
switch (c) {
case "arraybuffer":
@@ -12636,7 +12636,7 @@ class As extends pi {
return this.mimeType = e, this;
}
}
-class Cw extends pi {
+class vw extends pi {
/**
* Constructs a new image loader.
*
@@ -12677,7 +12677,7 @@ class Cw extends pi {
return o.addEventListener("load", c, !1), o.addEventListener("error", l, !1), e.slice(0, 5) !== "data:" && this.crossOrigin !== void 0 && (o.crossOrigin = this.crossOrigin), r.manager.itemStart(e), o.src = e, o;
}
}
-class Iw extends pi {
+class Cw extends pi {
/**
* Constructs a new data texture loader.
*
@@ -12716,7 +12716,7 @@ class Iw extends pi {
}, n, s), a;
}
}
-class J0 extends pi {
+class Y0 extends pi {
/**
* Constructs a new texture loader.
*
@@ -12738,7 +12738,7 @@ class J0 extends pi {
* @return {Texture} The texture.
*/
load(e, t, n, s) {
- const r = new an(), a = new Cw(this.manager);
+ const r = new an(), a = new vw(this.manager);
return a.setCrossOrigin(this.crossOrigin), a.setPath(this.path), a.load(e, function(o) {
r.image = o, r.needsUpdate = !0, t !== void 0 && t(r);
}, n, s), r;
@@ -12768,7 +12768,7 @@ class pc extends Tt {
return t.object.color = this.color.getHex(), t.object.intensity = this.intensity, this.groundColor !== void 0 && (t.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (t.object.distance = this.distance), this.angle !== void 0 && (t.object.angle = this.angle), this.decay !== void 0 && (t.object.decay = this.decay), this.penumbra !== void 0 && (t.object.penumbra = this.penumbra), this.shadow !== void 0 && (t.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (t.object.target = this.target.uuid), t;
}
}
-class Sw extends pc {
+class Iw extends pc {
/**
* Constructs a new hemisphere light.
*
@@ -12890,7 +12890,7 @@ class $f {
return this.intensity !== 1 && (e.intensity = this.intensity), this.bias !== 0 && (e.bias = this.bias), this.normalBias !== 0 && (e.normalBias = this.normalBias), this.radius !== 1 && (e.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (e.mapSize = this.mapSize.toArray()), e.camera = this.camera.toJSON(!1).object, delete e.camera.matrix, e;
}
}
-class Mw extends $f {
+class Sw extends $f {
/**
* Constructs a new spot light shadow.
*/
@@ -12905,7 +12905,7 @@ class Mw extends $f {
return super.copy(e), this.focus = e.focus, this;
}
}
-class Z0 extends pc {
+class J0 extends pc {
/**
* Constructs a new spot light.
*
@@ -12917,7 +12917,7 @@ class Z0 extends pc {
* @param {number} [decay=2] - The amount the light dims along the distance of the light.
*/
constructor(e, t, n = 0, s = Math.PI / 3, r = 0, a = 2) {
- super(e, t), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(Tt.DEFAULT_UP), this.updateMatrix(), this.target = new Tt(), this.distance = n, this.angle = s, this.penumbra = r, this.decay = a, this.map = null, this.shadow = new Mw();
+ super(e, t), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(Tt.DEFAULT_UP), this.updateMatrix(), this.target = new Tt(), this.distance = n, this.angle = s, this.penumbra = r, this.decay = a, this.map = null, this.shadow = new Sw();
}
/**
* The light's power. Power is the luminous power of the light measured in lumens (lm).
@@ -12939,7 +12939,7 @@ class Z0 extends pc {
}
}
const RA = /* @__PURE__ */ new Ne(), uo = /* @__PURE__ */ new G(), Au = /* @__PURE__ */ new G();
-class Bw extends $f {
+class Mw extends $f {
/**
* Constructs a new point light shadow.
*/
@@ -13006,7 +13006,7 @@ class Zl extends pc {
* @param {number} [decay=2] - The amount the light dims along the distance of the light.
*/
constructor(e, t, n = 0, s = 2) {
- super(e, t), this.isPointLight = !0, this.type = "PointLight", this.distance = n, this.decay = s, this.shadow = new Bw();
+ super(e, t), this.isPointLight = !0, this.type = "PointLight", this.distance = n, this.decay = s, this.shadow = new Mw();
}
/**
* The light's power. Power is the luminous power of the light measured in lumens (lm).
@@ -13027,7 +13027,7 @@ class Zl extends pc {
return super.copy(e, t), this.distance = e.distance, this.decay = e.decay, this.shadow = e.shadow.clone(), this;
}
}
-class ep extends U0 {
+class ep extends k0 {
/**
* Constructs a new orthographic camera.
*
@@ -13091,7 +13091,7 @@ class ep extends U0 {
return t.object.zoom = this.zoom, t.object.left = this.left, t.object.right = this.right, t.object.top = this.top, t.object.bottom = this.bottom, t.object.near = this.near, t.object.far = this.far, this.view !== null && (t.object.view = Object.assign({}, this.view)), t;
}
}
-class Tw extends $f {
+class Bw extends $f {
/**
* Constructs a new directional light shadow.
*/
@@ -13107,7 +13107,7 @@ class tp extends pc {
* @param {number} [intensity=1] - The light's strength/intensity.
*/
constructor(e, t) {
- super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(Tt.DEFAULT_UP), this.updateMatrix(), this.target = new Tt(), this.shadow = new Tw();
+ super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(Tt.DEFAULT_UP), this.updateMatrix(), this.target = new Tt(), this.shadow = new Bw();
}
dispose() {
this.shadow.dispose();
@@ -13116,7 +13116,7 @@ class tp extends pc {
return super.copy(e), this.target = e.target.clone(), this.shadow = e.shadow.clone(), this;
}
}
-class $0 extends pc {
+class Z0 extends pc {
/**
* Constructs a new ambient light.
*
@@ -13151,7 +13151,7 @@ class Cr {
return typeof e != "string" || e === "" ? "" : (/^https?:\/\//i.test(t) && /^\//.test(e) && (t = t.replace(/(^https?:\/\/[^\/]+).*/i, "$1")), /^(https?:)?\/\//i.test(e) || /^data:.*,.*$/i.test(e) || /^blob:.*$/i.test(e) ? e : t + e);
}
}
-class Rw extends pi {
+class Tw extends pi {
/**
* Constructs a new image bitmap loader.
*
@@ -13209,7 +13209,7 @@ class Rw extends pi {
us.add(e, c), r.manager.itemStart(e);
}
}
-class Fw extends In {
+class Rw extends In {
/**
* Constructs a new array camera.
*
@@ -13219,7 +13219,7 @@ class Fw extends In {
super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = e;
}
}
-class Nw {
+class Fw {
/**
* Constructs a new property mixer.
*
@@ -13354,10 +13354,10 @@ class Nw {
}
}
}
-const np = "\\[\\]\\.:\\/", Dw = new RegExp("[" + np + "]", "g"), ip = "[^" + np + "]", Lw = "[^" + np.replace("\\.", "") + "]", Pw = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", ip), kw = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", Lw), Uw = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", ip), Ow = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", ip), Qw = new RegExp(
- "^" + Pw + kw + Uw + Ow + "$"
-), Gw = ["material", "materials", "bones", "map"];
-class Hw {
+const np = "\\[\\]\\.:\\/", Nw = new RegExp("[" + np + "]", "g"), ip = "[^" + np + "]", Dw = "[^" + np.replace("\\.", "") + "]", Lw = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", ip), Pw = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", Dw), kw = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", ip), Uw = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", ip), Ow = new RegExp(
+ "^" + Lw + Pw + kw + Uw + "$"
+), Qw = ["material", "materials", "bones", "map"];
+class Gw {
constructor(e, t, n) {
const s = n || yt.parseTrackName(t);
this._targetGroup = e, this._bindings = e.subscribe_(t, s);
@@ -13414,7 +13414,7 @@ class yt {
* @return {string} The sanitized node name.
*/
static sanitizeNodeName(e) {
- return e.replace(/\s/g, "_").replace(Dw, "");
+ return e.replace(/\s/g, "_").replace(Nw, "");
}
/**
* Parses the given track name (an object path to an animated property) and
@@ -13435,7 +13435,7 @@ class yt {
* @return {Object} The parsed track name as an object.
*/
static parseTrackName(e) {
- const t = Qw.exec(e);
+ const t = Ow.exec(e);
if (t === null)
throw new Error("PropertyBinding: Cannot parse trackName: " + e);
const n = {
@@ -13449,7 +13449,7 @@ class yt {
}, s = n.nodeName && n.nodeName.lastIndexOf(".");
if (s !== void 0 && s !== -1) {
const r = n.nodeName.substring(s + 1);
- Gw.indexOf(r) !== -1 && (n.nodeName = n.nodeName.substring(0, s), n.objectName = r);
+ Qw.indexOf(r) !== -1 && (n.nodeName = n.nodeName.substring(0, s), n.objectName = r);
}
if (n.propertyName === null || n.propertyName.length === 0)
throw new Error("PropertyBinding: can not parse propertyName from trackName: " + e);
@@ -13661,7 +13661,7 @@ class yt {
this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
}
}
-yt.Composite = Hw;
+yt.Composite = Gw;
yt.prototype.BindingType = {
Direct: 0,
EntireArray: 1,
@@ -13705,7 +13705,7 @@ yt.prototype.SetterByBindingTypeAndVersioning = [
yt.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
]
];
-class zw {
+class Hw {
/**
* Constructs a new animation action.
*
@@ -13724,7 +13724,7 @@ class zw {
const h = r[l].createInterpolant(null);
o[l] = h, h.settings = c;
}
- this._interpolantSettings = c, this._interpolants = o, this._propertyBindings = new Array(a), this._cacheIndex = null, this._byClipCacheIndex = null, this._timeScaleInterpolant = null, this._weightInterpolant = null, this.loop = M0, this._loopCount = -1, this._startTime = null, this.time = 0, this.timeScale = 1, this._effectiveTimeScale = 1, this.weight = 1, this._effectiveWeight = 1, this.repetitions = 1 / 0, this.paused = !1, this.enabled = !0, this.clampWhenFinished = !1, this.zeroSlopeAtStart = !0, this.zeroSlopeAtEnd = !0;
+ this._interpolantSettings = c, this._interpolants = o, this._propertyBindings = new Array(a), this._cacheIndex = null, this._byClipCacheIndex = null, this._timeScaleInterpolant = null, this._weightInterpolant = null, this.loop = S0, this._loopCount = -1, this._startTime = null, this.time = 0, this.timeScale = 1, this._effectiveTimeScale = 1, this.weight = 1, this._effectiveWeight = 1, this.repetitions = 1 / 0, this.paused = !1, this.enabled = !0, this.clampWhenFinished = !1, this.zeroSlopeAtStart = !0, this.zeroSlopeAtEnd = !0;
}
/**
* Starts the playback of the animation.
@@ -13975,7 +13975,7 @@ class zw {
if (o > 0) {
const c = this._interpolants, l = this._propertyBindings;
switch (this.blendMode) {
- case Dy:
+ case Ny:
for (let h = 0, u = c.length; h !== u; ++h)
c[h].evaluate(a), l[h].accumulateAdditive(o);
break;
@@ -14013,10 +14013,10 @@ class zw {
_updateTime(e) {
const t = this._clip.duration, n = this.loop;
let s = this.time + e, r = this._loopCount;
- const a = n === Ny;
+ const a = n === Fy;
if (e === 0)
return r === -1 ? s : a && (r & 1) === 1 ? t - s : s;
- if (n === S0) {
+ if (n === I0) {
r === -1 && (this._loopCount = 0, this._setEndings(!0, !0, !1));
e: {
if (s >= t)
@@ -14075,8 +14075,8 @@ class zw {
return o[0] = r, c[0] = t, o[1] = r + e, c[1] = n, this;
}
}
-const Vw = new Float32Array(1);
-class ex extends Js {
+const zw = new Float32Array(1);
+class $0 extends Js {
/**
* Constructs a new animation mixer.
*
@@ -14100,7 +14100,7 @@ class ex extends Js {
continue;
}
const m = t && t._propertyBindings[u].binding.parsedPath;
- p = new Nw(
+ p = new Fw(
yt.create(n, f, m),
d.ValueTypeName,
d.getValueSize()
@@ -14231,11 +14231,11 @@ class ex extends Js {
_lendControlInterpolant() {
const e = this._controlInterpolants, t = this._nActiveControlInterpolants++;
let n = e[t];
- return n === void 0 && (n = new j0(
+ return n === void 0 && (n = new K0(
new Float32Array(2),
new Float32Array(2),
1,
- Vw
+ zw
), n.__cacheIndex = t, e[t] = n), n;
}
_takeBackControlInterpolant(e) {
@@ -14266,7 +14266,7 @@ class ex extends Js {
l = c.knownActions[0], a === null && (a = l._clip);
}
if (a === null) return null;
- const h = new zw(this, a, t, n);
+ const h = new Hw(this, a, t, n);
return this._bindAction(h, l), this._addInactiveAction(h, o, r), h;
}
/**
@@ -14457,7 +14457,7 @@ class FA {
}
}
const Ts = /* @__PURE__ */ new G(), el = /* @__PURE__ */ new Ne(), gu = /* @__PURE__ */ new Ne();
-class Ww extends bh {
+class Vw extends bh {
/**
* Constructs a new hemisphere light helper.
*
@@ -14465,7 +14465,7 @@ class Ww extends bh {
* can be used if it represents a hierarchy of bones (see {@link Bone}).
*/
constructor(e) {
- const t = tx(e), n = new Tn(), s = [], r = [], a = new Le(0, 0, 1), o = new Le(0, 1, 0);
+ const t = ex(e), n = new Tn(), s = [], r = [], a = new Le(0, 0, 1), o = new Le(0, 1, 0);
for (let l = 0; l < t.length; l++) {
const h = t[l];
h.parent && h.parent.isBone && (s.push(0, 0, 0), s.push(0, 0, 0), r.push(a.r, a.g, a.b), r.push(o.r, o.g, o.b));
@@ -14491,14 +14491,14 @@ class Ww extends bh {
this.geometry.dispose(), this.material.dispose();
}
}
-function tx(i) {
+function ex(i) {
const e = [];
i.isBone === !0 && e.push(i);
for (let t = 0; t < i.children.length; t++)
- e.push(...tx(i.children[t]));
+ e.push(...ex(i.children[t]));
return e;
}
-class qw extends bh {
+class Ww extends bh {
/**
* Constructs a new grid helper.
*
@@ -14598,7 +14598,7 @@ class NA extends bh {
this.geometry.dispose(), this.material.dispose();
}
}
-class Kw extends Js {
+class qw extends Js {
/**
* Constructs a new controls instance.
*
@@ -14642,10 +14642,10 @@ class Kw extends Js {
}
}
function DA(i, e, t, n) {
- const s = jw(n);
+ const s = Kw(n);
switch (t) {
// https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
- case v0:
+ case w0:
return i * e;
case cs:
return i * e / s.components * s.byteLength;
@@ -14655,7 +14655,7 @@ function DA(i, e, t, n) {
return i * e * 2 / s.components * s.byteLength;
case zf:
return i * e * 2 / s.components * s.byteLength;
- case C0:
+ case v0:
return i * e * 3 / s.components * s.byteLength;
case pn:
return i * e * 4 / s.components * s.byteLength;
@@ -14716,7 +14716,7 @@ function DA(i, e, t, n) {
case Vl:
return Math.ceil(i / 4) * Math.ceil(e / 4) * 16;
// https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
- case I0:
+ case C0:
case Od:
return Math.ceil(i / 4) * Math.ceil(e / 4) * 8;
case Qd:
@@ -14727,13 +14727,13 @@ function DA(i, e, t, n) {
`Unable to determine texture byte length for ${t} format.`
);
}
-function jw(i) {
+function Kw(i) {
switch (i) {
case un:
- case y0:
+ case E0:
return { byteLength: 1, components: 1 };
case Go:
- case _0:
+ case y0:
case Gn:
return { byteLength: 2, components: 1 };
case Qf:
@@ -14743,7 +14743,7 @@ function jw(i) {
case Of:
case fn:
return { byteLength: 4, components: 1 };
- case w0:
+ case _0:
return { byteLength: 4, components: 3 };
}
throw new Error(`Unknown texture type ${i}.`);
@@ -14752,7 +14752,7 @@ typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEv
revision: "176"
} }));
typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = "176");
-function nx() {
+function tx() {
let i = null, e = !1, t = null, n = null;
function s(r, a) {
t(r, a), n = i.requestAnimationFrame(s);
@@ -14772,7 +14772,7 @@ function nx() {
}
};
}
-function Xw(i) {
+function jw(i) {
const e = /* @__PURE__ */ new WeakMap();
function t(o, c) {
const l = o.array, h = o.usage, u = l.byteLength, d = i.createBuffer();
@@ -14867,9 +14867,9 @@ function Xw(i) {
update: a
};
}
-var Yw = `#ifdef USE_ALPHAHASH
+var Xw = `#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
-#endif`, Jw = `#ifdef USE_ALPHAHASH
+#endif`, Yw = `#ifdef USE_ALPHAHASH
const float ALPHA_HASH_SCALE = 0.05;
float hash2D( vec2 value ) {
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
@@ -14904,20 +14904,20 @@ var Yw = `#ifdef USE_ALPHAHASH
: cases.z;
return clamp( threshold , 1.0e-6, 1.0 );
}
-#endif`, Zw = `#ifdef USE_ALPHAMAP
+#endif`, Jw = `#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
-#endif`, $w = `#ifdef USE_ALPHAMAP
+#endif`, Zw = `#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
-#endif`, ev = `#ifdef USE_ALPHATEST
+#endif`, $w = `#ifdef USE_ALPHATEST
#ifdef ALPHA_TO_COVERAGE
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
if ( diffuseColor.a == 0.0 ) discard;
#else
if ( diffuseColor.a < alphaTest ) discard;
#endif
-#endif`, tv = `#ifdef USE_ALPHATEST
+#endif`, ev = `#ifdef USE_ALPHATEST
uniform float alphaTest;
-#endif`, nv = `#ifdef USE_AOMAP
+#endif`, tv = `#ifdef USE_AOMAP
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
reflectedLight.indirectDiffuse *= ambientOcclusion;
#if defined( USE_CLEARCOAT )
@@ -14930,10 +14930,10 @@ var Yw = `#ifdef USE_ALPHAHASH
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
#endif
-#endif`, iv = `#ifdef USE_AOMAP
+#endif`, nv = `#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
-#endif`, sv = `#ifdef USE_BATCHING
+#endif`, iv = `#ifdef USE_BATCHING
#if ! defined( GL_ANGLE_multi_draw )
#define gl_DrawID _gl_DrawID
uniform int _gl_DrawID;
@@ -14967,15 +14967,15 @@ var Yw = `#ifdef USE_ALPHAHASH
int y = j / size;
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
}
-#endif`, rv = `#ifdef USE_BATCHING
+#endif`, sv = `#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
-#endif`, av = `vec3 transformed = vec3( position );
+#endif`, rv = `vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
-#endif`, ov = `vec3 objectNormal = vec3( normal );
+#endif`, av = `vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
-#endif`, cv = `float G_BlinnPhong_Implicit( ) {
+#endif`, ov = `float G_BlinnPhong_Implicit( ) {
return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
@@ -14989,7 +14989,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
float G = G_BlinnPhong_Implicit( );
float D = D_BlinnPhong( shininess, dotNH );
return F * ( G * D );
-} // validated`, lv = `#ifdef USE_IRIDESCENCE
+} // validated`, cv = `#ifdef USE_IRIDESCENCE
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
@@ -15052,7 +15052,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
}
return max( I, vec3( 0.0 ) );
}
-#endif`, hv = `#ifdef USE_BUMPMAP
+#endif`, lv = `#ifdef USE_BUMPMAP
uniform sampler2D bumpMap;
uniform float bumpScale;
vec2 dHdxy_fwd() {
@@ -15073,7 +15073,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
-#endif`, uv = `#if NUM_CLIPPING_PLANES > 0
+#endif`, hv = `#if NUM_CLIPPING_PLANES > 0
vec4 plane;
#ifdef ALPHA_TO_COVERAGE
float distanceToPlane, distanceGradient;
@@ -15119,26 +15119,26 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
if ( clipped ) discard;
#endif
#endif
-#endif`, dv = `#if NUM_CLIPPING_PLANES > 0
+#endif`, uv = `#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
-#endif`, fv = `#if NUM_CLIPPING_PLANES > 0
+#endif`, dv = `#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
-#endif`, pv = `#if NUM_CLIPPING_PLANES > 0
+#endif`, fv = `#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
-#endif`, Av = `#if defined( USE_COLOR_ALPHA )
+#endif`, pv = `#if defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#elif defined( USE_COLOR )
diffuseColor.rgb *= vColor;
-#endif`, gv = `#if defined( USE_COLOR_ALPHA )
+#endif`, Av = `#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR )
varying vec3 vColor;
-#endif`, mv = `#if defined( USE_COLOR_ALPHA )
+#endif`, gv = `#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec3 vColor;
-#endif`, xv = `#if defined( USE_COLOR_ALPHA )
+#endif`, mv = `#if defined( USE_COLOR_ALPHA )
vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
vColor = vec3( 1.0 );
@@ -15152,7 +15152,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
#ifdef USE_BATCHING_COLOR
vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
vColor.xyz *= batchingColor.xyz;
-#endif`, bv = `#define PI 3.141592653589793
+#endif`, xv = `#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
@@ -15226,7 +15226,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
-} // validated`, Ev = `#ifdef ENVMAP_TYPE_CUBE_UV
+} // validated`, bv = `#ifdef ENVMAP_TYPE_CUBE_UV
#define cubeUV_minMipLevel 4.0
#define cubeUV_minTileSize 16.0
float getFace( vec3 direction ) {
@@ -15319,7 +15319,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
return vec4( mix( color0, color1, mipF ), 1.0 );
}
}
-#endif`, yv = `vec3 transformedNormal = objectNormal;
+#endif`, Ev = `vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
vec3 transformedTangent = objectTangent;
#endif
@@ -15348,21 +15348,21 @@ transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
transformedTangent = - transformedTangent;
#endif
-#endif`, _v = `#ifdef USE_DISPLACEMENTMAP
+#endif`, yv = `#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
-#endif`, wv = `#ifdef USE_DISPLACEMENTMAP
+#endif`, _v = `#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
-#endif`, vv = `#ifdef USE_EMISSIVEMAP
+#endif`, wv = `#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
-#endif`, Cv = `#ifdef USE_EMISSIVEMAP
+#endif`, vv = `#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
-#endif`, Iv = "gl_FragColor = linearToOutputTexel( gl_FragColor );", Sv = `vec4 LinearTransferOETF( in vec4 value ) {
+#endif`, Cv = "gl_FragColor = linearToOutputTexel( gl_FragColor );", Iv = `vec4 LinearTransferOETF( in vec4 value ) {
return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
@@ -15370,7 +15370,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) {
}
vec4 sRGBTransferOETF( in vec4 value ) {
return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
-}`, Mv = `#ifdef USE_ENVMAP
+}`, Sv = `#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vec3 cameraToFrag;
if ( isOrthographic ) {
@@ -15399,7 +15399,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
#elif defined( ENVMAP_BLENDING_ADD )
outgoingLight += envColor.xyz * specularStrength * reflectivity;
#endif
-#endif`, Bv = `#ifdef USE_ENVMAP
+#endif`, Mv = `#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform float flipEnvMap;
uniform mat3 envMapRotation;
@@ -15409,7 +15409,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
uniform sampler2D envMap;
#endif
-#endif`, Tv = `#ifdef USE_ENVMAP
+#endif`, Bv = `#ifdef USE_ENVMAP
uniform float reflectivity;
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
@@ -15420,7 +15420,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
#else
varying vec3 vReflect;
#endif
-#endif`, Rv = `#ifdef USE_ENVMAP
+#endif`, Tv = `#ifdef USE_ENVMAP
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
@@ -15431,7 +15431,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
varying vec3 vReflect;
uniform float refractionRatio;
#endif
-#endif`, Fv = `#ifdef USE_ENVMAP
+#endif`, Rv = `#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vWorldPosition = worldPosition.xyz;
#else
@@ -15448,18 +15448,18 @@ vec4 sRGBTransferOETF( in vec4 value ) {
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
-#endif`, Nv = `#ifdef USE_FOG
+#endif`, Fv = `#ifdef USE_FOG
vFogDepth = - mvPosition.z;
-#endif`, Dv = `#ifdef USE_FOG
+#endif`, Nv = `#ifdef USE_FOG
varying float vFogDepth;
-#endif`, Lv = `#ifdef USE_FOG
+#endif`, Dv = `#ifdef USE_FOG
#ifdef FOG_EXP2
float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
#else
float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
#endif
gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
-#endif`, Pv = `#ifdef USE_FOG
+#endif`, Lv = `#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
@@ -15468,7 +15468,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
uniform float fogNear;
uniform float fogFar;
#endif
-#endif`, kv = `#ifdef USE_GRADIENTMAP
+#endif`, Pv = `#ifdef USE_GRADIENTMAP
uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
@@ -15480,12 +15480,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
vec2 fw = fwidth( coord ) * 0.5;
return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
#endif
-}`, Uv = `#ifdef USE_LIGHTMAP
+}`, kv = `#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
-#endif`, Ov = `LambertMaterial material;
+#endif`, Uv = `LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
-material.specularStrength = specularStrength;`, Qv = `varying vec3 vViewPosition;
+material.specularStrength = specularStrength;`, Ov = `varying vec3 vViewPosition;
struct LambertMaterial {
vec3 diffuseColor;
float specularStrength;
@@ -15499,7 +15499,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Lambert
-#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`, Gv = `uniform bool receiveShadow;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`, Qv = `uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
uniform vec3 lightProbe[ 9 ];
@@ -15615,7 +15615,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi
vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
return irradiance;
}
-#endif`, Hv = `#ifdef USE_ENVMAP
+#endif`, Gv = `#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
@@ -15648,8 +15648,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi
#endif
}
#endif
-#endif`, zv = `ToonMaterial material;
-material.diffuseColor = diffuseColor.rgb;`, Vv = `varying vec3 vViewPosition;
+#endif`, Hv = `ToonMaterial material;
+material.diffuseColor = diffuseColor.rgb;`, zv = `varying vec3 vViewPosition;
struct ToonMaterial {
vec3 diffuseColor;
};
@@ -15661,11 +15661,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Toon
-#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`, Wv = `BlinnPhongMaterial material;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`, Vv = `BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
-material.specularStrength = specularStrength;`, qv = `varying vec3 vViewPosition;
+material.specularStrength = specularStrength;`, Wv = `varying vec3 vViewPosition;
struct BlinnPhongMaterial {
vec3 diffuseColor;
vec3 specularColor;
@@ -15682,7 +15682,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_BlinnPhong
-#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`, Kv = `PhysicalMaterial material;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`, qv = `PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
@@ -15768,7 +15768,7 @@ material.roughness = min( material.roughness, 1.0 );
material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
-#endif`, jv = `struct PhysicalMaterial {
+#endif`, Kv = `struct PhysicalMaterial {
vec3 diffuseColor;
float roughness;
vec3 specularColor;
@@ -16069,7 +16069,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia
#define RE_IndirectSpecular RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
-}`, Xv = `
+}`, jv = `
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
@@ -16184,7 +16184,7 @@ IncidentLight directLight;
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
-#endif`, Yv = `#if defined( RE_IndirectDiffuse )
+#endif`, Xv = `#if defined( RE_IndirectDiffuse )
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
@@ -16203,32 +16203,32 @@ IncidentLight directLight;
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
#endif
-#endif`, Jv = `#if defined( RE_IndirectDiffuse )
+#endif`, Yv = `#if defined( RE_IndirectDiffuse )
RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
-#endif`, Zv = `#if defined( USE_LOGDEPTHBUF )
+#endif`, Jv = `#if defined( USE_LOGDEPTHBUF )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
-#endif`, $v = `#if defined( USE_LOGDEPTHBUF )
+#endif`, Zv = `#if defined( USE_LOGDEPTHBUF )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
-#endif`, eC = `#ifdef USE_LOGDEPTHBUF
+#endif`, $v = `#ifdef USE_LOGDEPTHBUF
varying float vFragDepth;
varying float vIsPerspective;
-#endif`, tC = `#ifdef USE_LOGDEPTHBUF
+#endif`, eC = `#ifdef USE_LOGDEPTHBUF
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
-#endif`, nC = `#ifdef USE_MAP
+#endif`, tC = `#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
-#endif`, iC = `#ifdef USE_MAP
+#endif`, nC = `#ifdef USE_MAP
uniform sampler2D map;
-#endif`, sC = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
+#endif`, iC = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
#if defined( USE_POINTS_UV )
vec2 uv = vUv;
#else
@@ -16240,7 +16240,7 @@ IncidentLight directLight;
#endif
#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, uv ).g;
-#endif`, rC = `#if defined( USE_POINTS_UV )
+#endif`, sC = `#if defined( USE_POINTS_UV )
varying vec2 vUv;
#else
#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
@@ -16252,19 +16252,19 @@ IncidentLight directLight;
#endif
#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
-#endif`, aC = `float metalnessFactor = metalness;
+#endif`, rC = `float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
-#endif`, oC = `#ifdef USE_METALNESSMAP
+#endif`, aC = `#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
-#endif`, cC = `#ifdef USE_INSTANCING_MORPH
+#endif`, oC = `#ifdef USE_INSTANCING_MORPH
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
}
-#endif`, lC = `#if defined( USE_MORPHCOLORS )
+#endif`, cC = `#if defined( USE_MORPHCOLORS )
vColor *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
#if defined( USE_COLOR_ALPHA )
@@ -16273,12 +16273,12 @@ IncidentLight directLight;
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
#endif
}
-#endif`, hC = `#ifdef USE_MORPHNORMALS
+#endif`, lC = `#ifdef USE_MORPHNORMALS
objectNormal *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
}
-#endif`, uC = `#ifdef USE_MORPHTARGETS
+#endif`, hC = `#ifdef USE_MORPHTARGETS
#ifndef USE_INSTANCING_MORPH
uniform float morphTargetBaseInfluence;
uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
@@ -16292,12 +16292,12 @@ IncidentLight directLight;
ivec3 morphUV = ivec3( x, y, morphTargetIndex );
return texelFetch( morphTargetsTexture, morphUV, 0 );
}
-#endif`, dC = `#ifdef USE_MORPHTARGETS
+#endif`, uC = `#ifdef USE_MORPHTARGETS
transformed *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
}
-#endif`, fC = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
+#endif`, dC = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
vec3 fdx = dFdx( vViewPosition );
vec3 fdy = dFdy( vViewPosition );
@@ -16338,7 +16338,7 @@ IncidentLight directLight;
tbn2[1] *= faceDirection;
#endif
#endif
-vec3 nonPerturbedNormal = normal;`, pC = `#ifdef USE_NORMALMAP_OBJECTSPACE
+vec3 nonPerturbedNormal = normal;`, fC = `#ifdef USE_NORMALMAP_OBJECTSPACE
normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#ifdef FLIP_SIDED
normal = - normal;
@@ -16353,25 +16353,25 @@ vec3 nonPerturbedNormal = normal;`, pC = `#ifdef USE_NORMALMAP_OBJECTSPACE
normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
-#endif`, AC = `#ifndef FLAT_SHADED
+#endif`, pC = `#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
-#endif`, gC = `#ifndef FLAT_SHADED
+#endif`, AC = `#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
-#endif`, mC = `#ifndef FLAT_SHADED
+#endif`, gC = `#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#endif
-#endif`, xC = `#ifdef USE_NORMALMAP
+#endif`, mC = `#ifdef USE_NORMALMAP
uniform sampler2D normalMap;
uniform vec2 normalScale;
#endif
@@ -16393,13 +16393,13 @@ vec3 nonPerturbedNormal = normal;`, pC = `#ifdef USE_NORMALMAP_OBJECTSPACE
float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
return mat3( T * scale, B * scale, N );
}
-#endif`, bC = `#ifdef USE_CLEARCOAT
+#endif`, xC = `#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
-#endif`, EC = `#ifdef USE_CLEARCOAT_NORMALMAP
+#endif`, bC = `#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
-#endif`, yC = `#ifdef USE_CLEARCOATMAP
+#endif`, EC = `#ifdef USE_CLEARCOATMAP
uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
@@ -16408,18 +16408,18 @@ vec3 nonPerturbedNormal = normal;`, pC = `#ifdef USE_NORMALMAP_OBJECTSPACE
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform sampler2D clearcoatRoughnessMap;
-#endif`, _C = `#ifdef USE_IRIDESCENCEMAP
+#endif`, yC = `#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
-#endif`, wC = `#ifdef OPAQUE
+#endif`, _C = `#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
-gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, vC = `vec3 packNormalToRGB( const in vec3 normal ) {
+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, wC = `vec3 packNormalToRGB( const in vec3 normal ) {
return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
@@ -16488,9 +16488,9 @@ float viewZToPerspectiveDepth( const in float viewZ, const in float near, const
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
return ( near * far ) / ( ( far - near ) * depth - far );
-}`, CC = `#ifdef PREMULTIPLIED_ALPHA
+}`, vC = `#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
-#endif`, IC = `vec4 mvPosition = vec4( transformed, 1.0 );
+#endif`, CC = `vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
mvPosition = batchingMatrix * mvPosition;
#endif
@@ -16498,22 +16498,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const
mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
-gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
+gl_Position = projectionMatrix * mvPosition;`, IC = `#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
-#endif`, MC = `#ifdef DITHERING
+#endif`, SC = `#ifdef DITHERING
vec3 dithering( vec3 color ) {
float grid_position = rand( gl_FragCoord.xy );
vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
return color + dither_shift_RGB;
}
-#endif`, BC = `float roughnessFactor = roughness;
+#endif`, MC = `float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
-#endif`, TC = `#ifdef USE_ROUGHNESSMAP
+#endif`, BC = `#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
-#endif`, RC = `#if NUM_SPOT_LIGHT_COORDS > 0
+#endif`, TC = `#if NUM_SPOT_LIGHT_COORDS > 0
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
@@ -16699,7 +16699,7 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
}
return mix( 1.0, shadow, shadowIntensity );
}
-#endif`, FC = `#if NUM_SPOT_LIGHT_COORDS > 0
+#endif`, RC = `#if NUM_SPOT_LIGHT_COORDS > 0
uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
@@ -16740,7 +16740,7 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
-#endif`, NC = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
+#endif`, FC = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
vec4 shadowWorldPosition;
#endif
@@ -16772,7 +16772,7 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
-#endif`, DC = `float getShadowMask() {
+#endif`, NC = `float getShadowMask() {
float shadow = 1.0;
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
@@ -16804,12 +16804,12 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
#endif
#endif
return shadow;
-}`, LC = `#ifdef USE_SKINNING
+}`, DC = `#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
-#endif`, PC = `#ifdef USE_SKINNING
+#endif`, LC = `#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
uniform highp sampler2D boneTexture;
@@ -16824,7 +16824,7 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
-#endif`, kC = `#ifdef USE_SKINNING
+#endif`, PC = `#ifdef USE_SKINNING
vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
vec4 skinned = vec4( 0.0 );
skinned += boneMatX * skinVertex * skinWeight.x;
@@ -16832,7 +16832,7 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
skinned += boneMatZ * skinVertex * skinWeight.z;
skinned += boneMatW * skinVertex * skinWeight.w;
transformed = ( bindMatrixInverse * skinned ).xyz;
-#endif`, UC = `#ifdef USE_SKINNING
+#endif`, kC = `#ifdef USE_SKINNING
mat4 skinMatrix = mat4( 0.0 );
skinMatrix += skinWeight.x * boneMatX;
skinMatrix += skinWeight.y * boneMatY;
@@ -16843,17 +16843,17 @@ gl_Position = projectionMatrix * mvPosition;`, SC = `#ifdef DITHERING
#ifdef USE_TANGENT
objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
#endif
-#endif`, OC = `float specularStrength;
+#endif`, UC = `float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
-#endif`, QC = `#ifdef USE_SPECULARMAP
+#endif`, OC = `#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
-#endif`, GC = `#if defined( TONE_MAPPING )
+#endif`, QC = `#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
-#endif`, HC = `#ifndef saturate
+#endif`, GC = `#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
@@ -16950,7 +16950,7 @@ vec3 NeutralToneMapping( vec3 color ) {
float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
return mix( color, vec3( newPeak ), g );
}
-vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSMISSION
+vec3 CustomToneMapping( vec3 color ) { return color; }`, HC = `#ifdef USE_TRANSMISSION
material.transmission = transmission;
material.transmissionAlpha = 1.0;
material.thickness = thickness;
@@ -16971,7 +16971,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
material.attenuationColor, material.attenuationDistance );
material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
-#endif`, VC = `#ifdef USE_TRANSMISSION
+#endif`, zC = `#ifdef USE_TRANSMISSION
uniform float transmission;
uniform float thickness;
uniform float attenuationDistance;
@@ -17097,7 +17097,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
}
-#endif`, WC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`, VC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
@@ -17167,7 +17167,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
-#endif`, qC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`, WC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
@@ -17261,7 +17261,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
-#endif`, KC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`, qC = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
@@ -17332,7 +17332,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
#endif
#ifdef USE_THICKNESSMAP
vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
-#endif`, jC = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
+#endif`, KC = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
vec4 worldPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
worldPosition = batchingMatrix * worldPosition;
@@ -17342,12 +17342,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`, zC = `#ifdef USE_TRANSM
#endif
worldPosition = modelMatrix * worldPosition;
#endif`;
-const XC = `varying vec2 vUv;
+const jC = `varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
-}`, YC = `uniform sampler2D t2D;
+}`, XC = `uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
@@ -17359,14 +17359,14 @@ void main() {
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
-}`, JC = `varying vec3 vWorldDirection;
+}`, YC = `varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
-}`, ZC = `#ifdef ENVMAP_TYPE_CUBE
+}`, JC = `#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
uniform sampler2D envMap;
@@ -17389,14 +17389,14 @@ void main() {
gl_FragColor = texColor;
#include <tonemapping_fragment>
#include <colorspace_fragment>
-}`, $C = `varying vec3 vWorldDirection;
+}`, ZC = `varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
-}`, eI = `uniform samplerCube tCube;
+}`, $C = `uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
@@ -17406,7 +17406,7 @@ void main() {
gl_FragColor.a *= opacity;
#include <tonemapping_fragment>
#include <colorspace_fragment>
-}`, tI = `#include <common>
+}`, eI = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
@@ -17433,7 +17433,7 @@ void main() {
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
vHighPrecisionZW = gl_Position.zw;
-}`, nI = `#if DEPTH_PACKING == 3200
+}`, tI = `#if DEPTH_PACKING == 3200
uniform float opacity;
#endif
#include <common>
@@ -17467,7 +17467,7 @@ void main() {
#elif DEPTH_PACKING == 3203
gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
#endif
-}`, iI = `#define DISTANCE
+}`, nI = `#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
@@ -17494,7 +17494,7 @@ void main() {
#include <worldpos_vertex>
#include <clipping_planes_vertex>
vWorldPosition = worldPosition.xyz;
-}`, sI = `#define DISTANCE
+}`, iI = `#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
@@ -17518,13 +17518,13 @@ void main () {
dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
dist = saturate( dist );
gl_FragColor = packDepthToRGBA( dist );
-}`, rI = `varying vec3 vWorldDirection;
+}`, sI = `varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
-}`, aI = `uniform sampler2D tEquirect;
+}`, rI = `uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
@@ -17533,7 +17533,7 @@ void main() {
gl_FragColor = texture2D( tEquirect, sampleUV );
#include <tonemapping_fragment>
#include <colorspace_fragment>
-}`, oI = `uniform float scale;
+}`, aI = `uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
@@ -17555,7 +17555,7 @@ void main() {
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
-}`, cI = `uniform vec3 diffuse;
+}`, oI = `uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
@@ -17583,7 +17583,7 @@ void main() {
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
-}`, lI = `#include <common>
+}`, cI = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
@@ -17615,7 +17615,7 @@ void main() {
#include <worldpos_vertex>
#include <envmap_vertex>
#include <fog_vertex>
-}`, hI = `uniform vec3 diffuse;
+}`, lI = `uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
varying vec3 vNormal;
@@ -17663,7 +17663,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, uI = `#define LAMBERT
+}`, hI = `#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
@@ -17702,7 +17702,7 @@ void main() {
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
-}`, dI = `#define LAMBERT
+}`, uI = `#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
@@ -17759,7 +17759,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, fI = `#define MATCAP
+}`, dI = `#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
@@ -17793,7 +17793,7 @@ void main() {
#include <clipping_planes_vertex>
#include <fog_vertex>
vViewPosition = - mvPosition.xyz;
-}`, pI = `#define MATCAP
+}`, fI = `#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
@@ -17839,7 +17839,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, AI = `#define NORMAL
+}`, pI = `#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
#endif
@@ -17872,7 +17872,7 @@ void main() {
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
vViewPosition = - mvPosition.xyz;
#endif
-}`, gI = `#define NORMAL
+}`, AI = `#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
varying vec3 vViewPosition;
@@ -17894,7 +17894,7 @@ void main() {
#ifdef OPAQUE
gl_FragColor.a = 1.0;
#endif
-}`, mI = `#define PHONG
+}`, gI = `#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
@@ -17933,7 +17933,7 @@ void main() {
#include <envmap_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
-}`, xI = `#define PHONG
+}`, mI = `#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
@@ -17992,7 +17992,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, bI = `#define STANDARD
+}`, xI = `#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
varying vec3 vWorldPosition;
@@ -18035,7 +18035,7 @@ void main() {
#ifdef USE_TRANSMISSION
vWorldPosition = worldPosition.xyz;
#endif
-}`, EI = `#define STANDARD
+}`, bI = `#define STANDARD
#ifdef PHYSICAL
#define IOR
#define USE_SPECULAR
@@ -18160,7 +18160,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, yI = `#define TOON
+}`, EI = `#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
@@ -18197,7 +18197,7 @@ void main() {
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
-}`, _I = `#define TOON
+}`, yI = `#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
@@ -18250,7 +18250,7 @@ void main() {
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
#include <dithering_fragment>
-}`, wI = `uniform float size;
+}`, _I = `uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
@@ -18281,7 +18281,7 @@ void main() {
#include <clipping_planes_vertex>
#include <worldpos_vertex>
#include <fog_vertex>
-}`, vI = `uniform vec3 diffuse;
+}`, wI = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
@@ -18306,7 +18306,7 @@ void main() {
#include <colorspace_fragment>
#include <fog_fragment>
#include <premultiplied_alpha_fragment>
-}`, CI = `#include <common>
+}`, vI = `#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
@@ -18329,7 +18329,7 @@ void main() {
#include <worldpos_vertex>
#include <shadowmap_vertex>
#include <fog_vertex>
-}`, II = `uniform vec3 color;
+}`, CI = `uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
@@ -18345,7 +18345,7 @@ void main() {
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
-}`, SI = `uniform float rotation;
+}`, II = `uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
@@ -18369,7 +18369,7 @@ void main() {
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#include <fog_vertex>
-}`, MI = `uniform vec3 diffuse;
+}`, SI = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
@@ -18395,147 +18395,147 @@ void main() {
#include <colorspace_fragment>
#include <fog_fragment>
}`, lt = {
- alphahash_fragment: Yw,
- alphahash_pars_fragment: Jw,
- alphamap_fragment: Zw,
- alphamap_pars_fragment: $w,
- alphatest_fragment: ev,
- alphatest_pars_fragment: tv,
- aomap_fragment: nv,
- aomap_pars_fragment: iv,
- batching_pars_vertex: sv,
- batching_vertex: rv,
- begin_vertex: av,
- beginnormal_vertex: ov,
- bsdfs: cv,
- iridescence_fragment: lv,
- bumpmap_pars_fragment: hv,
- clipping_planes_fragment: uv,
- clipping_planes_pars_fragment: dv,
- clipping_planes_pars_vertex: fv,
- clipping_planes_vertex: pv,
- color_fragment: Av,
- color_pars_fragment: gv,
- color_pars_vertex: mv,
- color_vertex: xv,
- common: bv,
- cube_uv_reflection_fragment: Ev,
- defaultnormal_vertex: yv,
- displacementmap_pars_vertex: _v,
- displacementmap_vertex: wv,
- emissivemap_fragment: vv,
- emissivemap_pars_fragment: Cv,
- colorspace_fragment: Iv,
- colorspace_pars_fragment: Sv,
- envmap_fragment: Mv,
- envmap_common_pars_fragment: Bv,
- envmap_pars_fragment: Tv,
- envmap_pars_vertex: Rv,
- envmap_physical_pars_fragment: Hv,
- envmap_vertex: Fv,
- fog_vertex: Nv,
- fog_pars_vertex: Dv,
- fog_fragment: Lv,
- fog_pars_fragment: Pv,
- gradientmap_pars_fragment: kv,
- lightmap_pars_fragment: Uv,
- lights_lambert_fragment: Ov,
- lights_lambert_pars_fragment: Qv,
- lights_pars_begin: Gv,
- lights_toon_fragment: zv,
- lights_toon_pars_fragment: Vv,
- lights_phong_fragment: Wv,
- lights_phong_pars_fragment: qv,
- lights_physical_fragment: Kv,
- lights_physical_pars_fragment: jv,
- lights_fragment_begin: Xv,
- lights_fragment_maps: Yv,
- lights_fragment_end: Jv,
- logdepthbuf_fragment: Zv,
- logdepthbuf_pars_fragment: $v,
- logdepthbuf_pars_vertex: eC,
- logdepthbuf_vertex: tC,
- map_fragment: nC,
- map_pars_fragment: iC,
- map_particle_fragment: sC,
- map_particle_pars_fragment: rC,
- metalnessmap_fragment: aC,
- metalnessmap_pars_fragment: oC,
- morphinstance_vertex: cC,
- morphcolor_vertex: lC,
- morphnormal_vertex: hC,
- morphtarget_pars_vertex: uC,
- morphtarget_vertex: dC,
- normal_fragment_begin: fC,
- normal_fragment_maps: pC,
- normal_pars_fragment: AC,
- normal_pars_vertex: gC,
- normal_vertex: mC,
- normalmap_pars_fragment: xC,
- clearcoat_normal_fragment_begin: bC,
- clearcoat_normal_fragment_maps: EC,
- clearcoat_pars_fragment: yC,
- iridescence_pars_fragment: _C,
- opaque_fragment: wC,
- packing: vC,
- premultiplied_alpha_fragment: CC,
- project_vertex: IC,
- dithering_fragment: SC,
- dithering_pars_fragment: MC,
- roughnessmap_fragment: BC,
- roughnessmap_pars_fragment: TC,
- shadowmap_pars_fragment: RC,
- shadowmap_pars_vertex: FC,
- shadowmap_vertex: NC,
- shadowmask_pars_fragment: DC,
- skinbase_vertex: LC,
- skinning_pars_vertex: PC,
- skinning_vertex: kC,
- skinnormal_vertex: UC,
- specularmap_fragment: OC,
- specularmap_pars_fragment: QC,
- tonemapping_fragment: GC,
- tonemapping_pars_fragment: HC,
- transmission_fragment: zC,
- transmission_pars_fragment: VC,
- uv_pars_fragment: WC,
- uv_pars_vertex: qC,
- uv_vertex: KC,
- worldpos_vertex: jC,
- background_vert: XC,
- background_frag: YC,
- backgroundCube_vert: JC,
- backgroundCube_frag: ZC,
- cube_vert: $C,
- cube_frag: eI,
- depth_vert: tI,
- depth_frag: nI,
- distanceRGBA_vert: iI,
- distanceRGBA_frag: sI,
- equirect_vert: rI,
- equirect_frag: aI,
- linedashed_vert: oI,
- linedashed_frag: cI,
- meshbasic_vert: lI,
- meshbasic_frag: hI,
- meshlambert_vert: uI,
- meshlambert_frag: dI,
- meshmatcap_vert: fI,
- meshmatcap_frag: pI,
- meshnormal_vert: AI,
- meshnormal_frag: gI,
- meshphong_vert: mI,
- meshphong_frag: xI,
- meshphysical_vert: bI,
- meshphysical_frag: EI,
- meshtoon_vert: yI,
- meshtoon_frag: _I,
- points_vert: wI,
- points_frag: vI,
- shadow_vert: CI,
- shadow_frag: II,
- sprite_vert: SI,
- sprite_frag: MI
+ alphahash_fragment: Xw,
+ alphahash_pars_fragment: Yw,
+ alphamap_fragment: Jw,
+ alphamap_pars_fragment: Zw,
+ alphatest_fragment: $w,
+ alphatest_pars_fragment: ev,
+ aomap_fragment: tv,
+ aomap_pars_fragment: nv,
+ batching_pars_vertex: iv,
+ batching_vertex: sv,
+ begin_vertex: rv,
+ beginnormal_vertex: av,
+ bsdfs: ov,
+ iridescence_fragment: cv,
+ bumpmap_pars_fragment: lv,
+ clipping_planes_fragment: hv,
+ clipping_planes_pars_fragment: uv,
+ clipping_planes_pars_vertex: dv,
+ clipping_planes_vertex: fv,
+ color_fragment: pv,
+ color_pars_fragment: Av,
+ color_pars_vertex: gv,
+ color_vertex: mv,
+ common: xv,
+ cube_uv_reflection_fragment: bv,
+ defaultnormal_vertex: Ev,
+ displacementmap_pars_vertex: yv,
+ displacementmap_vertex: _v,
+ emissivemap_fragment: wv,
+ emissivemap_pars_fragment: vv,
+ colorspace_fragment: Cv,
+ colorspace_pars_fragment: Iv,
+ envmap_fragment: Sv,
+ envmap_common_pars_fragment: Mv,
+ envmap_pars_fragment: Bv,
+ envmap_pars_vertex: Tv,
+ envmap_physical_pars_fragment: Gv,
+ envmap_vertex: Rv,
+ fog_vertex: Fv,
+ fog_pars_vertex: Nv,
+ fog_fragment: Dv,
+ fog_pars_fragment: Lv,
+ gradientmap_pars_fragment: Pv,
+ lightmap_pars_fragment: kv,
+ lights_lambert_fragment: Uv,
+ lights_lambert_pars_fragment: Ov,
+ lights_pars_begin: Qv,
+ lights_toon_fragment: Hv,
+ lights_toon_pars_fragment: zv,
+ lights_phong_fragment: Vv,
+ lights_phong_pars_fragment: Wv,
+ lights_physical_fragment: qv,
+ lights_physical_pars_fragment: Kv,
+ lights_fragment_begin: jv,
+ lights_fragment_maps: Xv,
+ lights_fragment_end: Yv,
+ logdepthbuf_fragment: Jv,
+ logdepthbuf_pars_fragment: Zv,
+ logdepthbuf_pars_vertex: $v,
+ logdepthbuf_vertex: eC,
+ map_fragment: tC,
+ map_pars_fragment: nC,
+ map_particle_fragment: iC,
+ map_particle_pars_fragment: sC,
+ metalnessmap_fragment: rC,
+ metalnessmap_pars_fragment: aC,
+ morphinstance_vertex: oC,
+ morphcolor_vertex: cC,
+ morphnormal_vertex: lC,
+ morphtarget_pars_vertex: hC,
+ morphtarget_vertex: uC,
+ normal_fragment_begin: dC,
+ normal_fragment_maps: fC,
+ normal_pars_fragment: pC,
+ normal_pars_vertex: AC,
+ normal_vertex: gC,
+ normalmap_pars_fragment: mC,
+ clearcoat_normal_fragment_begin: xC,
+ clearcoat_normal_fragment_maps: bC,
+ clearcoat_pars_fragment: EC,
+ iridescence_pars_fragment: yC,
+ opaque_fragment: _C,
+ packing: wC,
+ premultiplied_alpha_fragment: vC,
+ project_vertex: CC,
+ dithering_fragment: IC,
+ dithering_pars_fragment: SC,
+ roughnessmap_fragment: MC,
+ roughnessmap_pars_fragment: BC,
+ shadowmap_pars_fragment: TC,
+ shadowmap_pars_vertex: RC,
+ shadowmap_vertex: FC,
+ shadowmask_pars_fragment: NC,
+ skinbase_vertex: DC,
+ skinning_pars_vertex: LC,
+ skinning_vertex: PC,
+ skinnormal_vertex: kC,
+ specularmap_fragment: UC,
+ specularmap_pars_fragment: OC,
+ tonemapping_fragment: QC,
+ tonemapping_pars_fragment: GC,
+ transmission_fragment: HC,
+ transmission_pars_fragment: zC,
+ uv_pars_fragment: VC,
+ uv_pars_vertex: WC,
+ uv_vertex: qC,
+ worldpos_vertex: KC,
+ background_vert: jC,
+ background_frag: XC,
+ backgroundCube_vert: YC,
+ backgroundCube_frag: JC,
+ cube_vert: ZC,
+ cube_frag: $C,
+ depth_vert: eI,
+ depth_frag: tI,
+ distanceRGBA_vert: nI,
+ distanceRGBA_frag: iI,
+ equirect_vert: sI,
+ equirect_frag: rI,
+ linedashed_vert: aI,
+ linedashed_frag: oI,
+ meshbasic_vert: cI,
+ meshbasic_frag: lI,
+ meshlambert_vert: hI,
+ meshlambert_frag: uI,
+ meshmatcap_vert: dI,
+ meshmatcap_frag: fI,
+ meshnormal_vert: pI,
+ meshnormal_frag: AI,
+ meshphong_vert: gI,
+ meshphong_frag: mI,
+ meshphysical_vert: xI,
+ meshphysical_frag: bI,
+ meshtoon_vert: EI,
+ meshtoon_frag: yI,
+ points_vert: _I,
+ points_frag: wI,
+ shadow_vert: vI,
+ shadow_frag: CI,
+ sprite_vert: II,
+ sprite_frag: SI
}, we = {
common: {
diffuse: { value: /* @__PURE__ */ new Le(16777215) },
@@ -18974,8 +18974,8 @@ Ui.physical = {
vertexShader: lt.meshphysical_vert,
fragmentShader: lt.meshphysical_frag
};
-const tl = { r: 0, b: 0, g: 0 }, ar = /* @__PURE__ */ new dn(), BI = /* @__PURE__ */ new Ne();
-function TI(i, e, t, n, s, r, a) {
+const tl = { r: 0, b: 0, g: 0 }, ar = /* @__PURE__ */ new dn(), MI = /* @__PURE__ */ new Ne();
+function BI(i, e, t, n, s, r, a) {
const o = new Le(0);
let c = r === !0 ? 0 : 1, l, h, u = null, d = 0, f = null;
function p(x) {
@@ -19010,7 +19010,7 @@ function TI(i, e, t, n, s, r, a) {
get: function() {
return this.uniforms.envMap.value;
}
- }), s.update(h)), ar.copy(E.backgroundRotation), ar.x *= -1, ar.y *= -1, ar.z *= -1, S.isCubeTexture && S.isRenderTargetTexture === !1 && (ar.y *= -1, ar.z *= -1), h.material.uniforms.envMap.value = S, h.material.uniforms.flipEnvMap.value = S.isCubeTexture && S.isRenderTargetTexture === !1 ? -1 : 1, h.material.uniforms.backgroundBlurriness.value = E.backgroundBlurriness, h.material.uniforms.backgroundIntensity.value = E.backgroundIntensity, h.material.uniforms.backgroundRotation.value.setFromMatrix4(BI.makeRotationFromEuler(ar)), h.material.toneMapped = rt.getTransfer(S.colorSpace) !== Rt, (u !== S || d !== S.version || f !== i.toneMapping) && (h.material.needsUpdate = !0, u = S, d = S.version, f = i.toneMapping), h.layers.enableAll(), x.unshift(h, h.geometry, h.material, 0, 0, null)) : S && S.isTexture && (l === void 0 && (l = new Zt(
+ }), s.update(h)), ar.copy(E.backgroundRotation), ar.x *= -1, ar.y *= -1, ar.z *= -1, S.isCubeTexture && S.isRenderTargetTexture === !1 && (ar.y *= -1, ar.z *= -1), h.material.uniforms.envMap.value = S, h.material.uniforms.flipEnvMap.value = S.isCubeTexture && S.isRenderTargetTexture === !1 ? -1 : 1, h.material.uniforms.backgroundBlurriness.value = E.backgroundBlurriness, h.material.uniforms.backgroundIntensity.value = E.backgroundIntensity, h.material.uniforms.backgroundRotation.value.setFromMatrix4(MI.makeRotationFromEuler(ar)), h.material.toneMapped = rt.getTransfer(S.colorSpace) !== Rt, (u !== S || d !== S.version || f !== i.toneMapping) && (h.material.needsUpdate = !0, u = S, d = S.version, f = i.toneMapping), h.layers.enableAll(), x.unshift(h, h.geometry, h.material, 0, 0, null)) : S && S.isTexture && (l === void 0 && (l = new Zt(
new yh(2, 2),
new qs({
name: "BackgroundMaterial",
@@ -19030,7 +19030,7 @@ function TI(i, e, t, n, s, r, a) {
}), s.update(l)), l.material.uniforms.t2D.value = S, l.material.uniforms.backgroundIntensity.value = E.backgroundIntensity, l.material.toneMapped = rt.getTransfer(S.colorSpace) !== Rt, S.matrixAutoUpdate === !0 && S.updateMatrix(), l.material.uniforms.uvTransform.value.copy(S.matrix), (u !== S || d !== S.version || f !== i.toneMapping) && (l.material.needsUpdate = !0, u = S, d = S.version, f = i.toneMapping), l.layers.enableAll(), x.unshift(l, l.geometry, l.material, 0, 0, null));
}
function A(x, E) {
- x.getRGB(tl, k0(i)), n.buffers.color.setClear(tl.r, tl.g, tl.b, E, a);
+ x.getRGB(tl, P0(i)), n.buffers.color.setClear(tl.r, tl.g, tl.b, E, a);
}
function _() {
h !== void 0 && (h.geometry.dispose(), h.material.dispose(), h = void 0), l !== void 0 && (l.geometry.dispose(), l.material.dispose(), l = void 0);
@@ -19053,7 +19053,7 @@ function TI(i, e, t, n, s, r, a) {
dispose: _
};
}
-function RI(i, e) {
+function TI(i, e) {
const t = i.getParameter(i.MAX_VERTEX_ATTRIBS), n = {}, s = d(null);
let r = s, a = !1;
function o(v, F, K, q, $) {
@@ -19266,7 +19266,7 @@ function RI(i, e) {
disableUnusedAttributes: _
};
}
-function FI(i, e, t) {
+function RI(i, e, t) {
let n;
function s(l) {
n = l;
@@ -19301,7 +19301,7 @@ function FI(i, e, t) {
}
this.setMode = s, this.render = r, this.renderInstances = a, this.renderMultiDraw = o, this.renderMultiDrawInstances = c;
}
-function NI(i, e, t, n) {
+function FI(i, e, t, n) {
let s;
function r() {
if (s !== void 0) return s;
@@ -19354,7 +19354,7 @@ function NI(i, e, t, n) {
maxSamples: w
};
}
-function DI(i) {
+function NI(i) {
const e = this;
let t = null, n = 0, s = !1, r = !1;
const a = new Us(), o = new at(), c = { value: null, needsUpdate: !1 };
@@ -19400,7 +19400,7 @@ function DI(i) {
return e.numPlanes = m, e.numIntersection = 0, g;
}
}
-function LI(i) {
+function DI(i) {
let e = /* @__PURE__ */ new WeakMap();
function t(a, o) {
return o === kl ? a.mapping = Br : o === wd && (a.mapping = La), a;
@@ -19415,7 +19415,7 @@ function LI(i) {
} else {
const c = a.image;
if (c && c.height > 0) {
- const l = new P_(c.height);
+ const l = new L_(c.height);
return l.fromEquirectangularTexture(i, a), e.set(a, l), a.addEventListener("dispose", s), t(l.texture, a.mapping);
} else
return null;
@@ -19450,7 +19450,7 @@ const dr = (1 + Math.sqrt(5)) / 2, aa = 1 / dr, kA = [
/* @__PURE__ */ new G(1, 1, -1),
/* @__PURE__ */ new G(-1, 1, 1),
/* @__PURE__ */ new G(1, 1, 1)
-], PI = /* @__PURE__ */ new G();
+], LI = /* @__PURE__ */ new G();
class Xd {
/**
* Constructs a new PMREM generator.
@@ -19478,7 +19478,7 @@ class Xd {
fromScene(e, t = 0, n = 0.1, s = 100, r = {}) {
const {
size: a = 256,
- position: o = PI
+ position: o = LI
} = r;
xu = this._renderer.getRenderTarget(), bu = this._renderer.getActiveCubeFace(), Eu = this._renderer.getActiveMipmapLevel(), yu = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a);
const c = this._allocateTargets();
@@ -19560,7 +19560,7 @@ class Xd {
if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== e || this._pingPongRenderTarget.height !== t) {
this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = UA(e, t, n);
const { _lodMax: r } = this;
- ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = kI(r)), this._blurMaterial = UI(r, e, t);
+ ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = PI(r)), this._blurMaterial = kI(r, e, t);
}
return s;
}
@@ -19662,7 +19662,7 @@ class Xd {
nl(t, S, w, 3 * E, 2 * E), c.setRenderTarget(t), c.render(u, mu);
}
}
-function kI(i) {
+function PI(i) {
const e = [], t = [], n = [];
let s = i;
const r = i - ba + 1 + LA.length;
@@ -19709,7 +19709,7 @@ function UA(i, e, t) {
function nl(i, e, t, n, s) {
i.viewport.set(e, t, n, s), i.scissor.set(e, t, n, s);
}
-function UI(i, e, t) {
+function kI(i, e, t) {
const n = new Float32Array(Ar), s = new G(0, 1, 0);
return new qs({
name: "SphericalGaussianBlur",
@@ -19927,7 +19927,7 @@ function sp() {
`
);
}
-function OI(i) {
+function UI(i) {
let e = /* @__PURE__ */ new WeakMap(), t = null;
function n(o) {
if (o && o.isTexture) {
@@ -19968,7 +19968,7 @@ function OI(i) {
dispose: a
};
}
-function QI(i) {
+function OI(i) {
const e = {};
function t(n) {
if (e[n] !== void 0)
@@ -20005,7 +20005,7 @@ function QI(i) {
}
};
}
-function GI(i, e, t, n) {
+function QI(i, e, t, n) {
const s = {}, r = /* @__PURE__ */ new WeakMap();
function a(u) {
const d = u.target;
@@ -20043,7 +20043,7 @@ function GI(i, e, t, n) {
}
} else
return;
- const g = new (R0(d) ? P0 : jf)(d, 1);
+ const g = new (T0(d) ? L0 : jf)(d, 1);
g.version = m;
const A = r.get(u);
A && e.remove(A), r.set(u, g);
@@ -20063,7 +20063,7 @@ function GI(i, e, t, n) {
getWireframeAttribute: h
};
}
-function HI(i, e, t) {
+function GI(i, e, t) {
let n;
function s(d) {
n = d;
@@ -20102,7 +20102,7 @@ function HI(i, e, t) {
}
this.setMode = s, this.setIndex = o, this.render = c, this.renderInstances = l, this.renderMultiDraw = h, this.renderMultiDrawInstances = u;
}
-function zI(i) {
+function HI(i) {
const e = {
geometries: 0,
textures: 0
@@ -20147,7 +20147,7 @@ function zI(i) {
update: n
};
}
-function VI(i, e, t) {
+function zI(i, e, t) {
const n = /* @__PURE__ */ new WeakMap(), s = new mt();
function r(a, o, c) {
const l = a.morphTargetInfluences, h = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, u = h !== void 0 ? h.length : 0;
@@ -20162,7 +20162,7 @@ function VI(i, e, t) {
f === !0 && (x = 1), p === !0 && (x = 2), m === !0 && (x = 3);
let E = o.attributes.position.count * x, S = 1;
E > e.maxTextureSize && (S = Math.ceil(E / e.maxTextureSize), E = e.maxTextureSize);
- const w = new Float32Array(E * S * 4 * u), I = new F0(w, E, S, u);
+ const w = new Float32Array(E * S * 4 * u), I = new R0(w, E, S, u);
I.type = fn, I.needsUpdate = !0;
const T = x * 4;
for (let v = 0; v < u; v++) {
@@ -20193,7 +20193,7 @@ function VI(i, e, t) {
update: r
};
}
-function WI(i, e, t, n) {
+function VI(i, e, t, n) {
let s = /* @__PURE__ */ new WeakMap();
function r(c) {
const l = n.render.frame, h = c.geometry, u = e.get(c, h);
@@ -20215,7 +20215,7 @@ function WI(i, e, t, n) {
dispose: a
};
}
-const ix = /* @__PURE__ */ new an(), GA = /* @__PURE__ */ new H0(1, 1), sx = /* @__PURE__ */ new F0(), rx = /* @__PURE__ */ new N0(), ax = /* @__PURE__ */ new O0(), HA = [], zA = [], VA = new Float32Array(16), WA = new Float32Array(9), qA = new Float32Array(4);
+const nx = /* @__PURE__ */ new an(), GA = /* @__PURE__ */ new G0(1, 1), ix = /* @__PURE__ */ new R0(), sx = /* @__PURE__ */ new F0(), rx = /* @__PURE__ */ new U0(), HA = [], zA = [], VA = new Float32Array(16), WA = new Float32Array(9), qA = new Float32Array(4);
function Ya(i, e, t) {
const n = i[0];
if (n <= 0 || n > 0) return i;
@@ -20245,11 +20245,11 @@ function _h(i, e) {
t[n] = i.allocateTextureUnit();
return t;
}
-function qI(i, e) {
+function WI(i, e) {
const t = this.cache;
t[0] !== e && (i.uniform1f(this.addr, e), t[0] = e);
}
-function KI(i, e) {
+function qI(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y) && (i.uniform2f(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
@@ -20258,7 +20258,7 @@ function KI(i, e) {
i.uniform2fv(this.addr, e), mn(t, e);
}
}
-function jI(i, e) {
+function KI(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (i.uniform3f(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
@@ -20269,7 +20269,7 @@ function jI(i, e) {
i.uniform3fv(this.addr, e), mn(t, e);
}
}
-function XI(i, e) {
+function jI(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (i.uniform4f(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
@@ -20278,7 +20278,7 @@ function XI(i, e) {
i.uniform4fv(this.addr, e), mn(t, e);
}
}
-function YI(i, e) {
+function XI(i, e) {
const t = this.cache, n = e.elements;
if (n === void 0) {
if (gn(t, e)) return;
@@ -20288,7 +20288,7 @@ function YI(i, e) {
qA.set(n), i.uniformMatrix2fv(this.addr, !1, qA), mn(t, n);
}
}
-function JI(i, e) {
+function YI(i, e) {
const t = this.cache, n = e.elements;
if (n === void 0) {
if (gn(t, e)) return;
@@ -20298,7 +20298,7 @@ function JI(i, e) {
WA.set(n), i.uniformMatrix3fv(this.addr, !1, WA), mn(t, n);
}
}
-function ZI(i, e) {
+function JI(i, e) {
const t = this.cache, n = e.elements;
if (n === void 0) {
if (gn(t, e)) return;
@@ -20308,11 +20308,11 @@ function ZI(i, e) {
VA.set(n), i.uniformMatrix4fv(this.addr, !1, VA), mn(t, n);
}
}
-function $I(i, e) {
+function ZI(i, e) {
const t = this.cache;
t[0] !== e && (i.uniform1i(this.addr, e), t[0] = e);
}
-function eS(i, e) {
+function $I(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y) && (i.uniform2i(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
@@ -20321,7 +20321,7 @@ function eS(i, e) {
i.uniform2iv(this.addr, e), mn(t, e);
}
}
-function tS(i, e) {
+function eS(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (i.uniform3i(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
@@ -20330,7 +20330,7 @@ function tS(i, e) {
i.uniform3iv(this.addr, e), mn(t, e);
}
}
-function nS(i, e) {
+function tS(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (i.uniform4i(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
@@ -20339,11 +20339,11 @@ function nS(i, e) {
i.uniform4iv(this.addr, e), mn(t, e);
}
}
-function iS(i, e) {
+function nS(i, e) {
const t = this.cache;
t[0] !== e && (i.uniform1ui(this.addr, e), t[0] = e);
}
-function sS(i, e) {
+function iS(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y) && (i.uniform2ui(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y);
@@ -20352,7 +20352,7 @@ function sS(i, e) {
i.uniform2uiv(this.addr, e), mn(t, e);
}
}
-function rS(i, e) {
+function sS(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (i.uniform3ui(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z);
@@ -20361,7 +20361,7 @@ function rS(i, e) {
i.uniform3uiv(this.addr, e), mn(t, e);
}
}
-function aS(i, e) {
+function rS(i, e) {
const t = this.cache;
if (e.x !== void 0)
(t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (i.uniform4ui(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w);
@@ -20370,74 +20370,74 @@ function aS(i, e) {
i.uniform4uiv(this.addr, e), mn(t, e);
}
}
-function oS(i, e, t) {
+function aS(i, e, t) {
const n = this.cache, s = t.allocateTextureUnit();
n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s);
let r;
- this.type === i.SAMPLER_2D_SHADOW ? (GA.compareFunction = T0, r = GA) : r = ix, t.setTexture2D(e || r, s);
+ this.type === i.SAMPLER_2D_SHADOW ? (GA.compareFunction = B0, r = GA) : r = nx, t.setTexture2D(e || r, s);
}
-function cS(i, e, t) {
+function oS(i, e, t) {
const n = this.cache, s = t.allocateTextureUnit();
- n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTexture3D(e || rx, s);
+ n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTexture3D(e || sx, s);
}
-function lS(i, e, t) {
+function cS(i, e, t) {
const n = this.cache, s = t.allocateTextureUnit();
- n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTextureCube(e || ax, s);
+ n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTextureCube(e || rx, s);
}
-function hS(i, e, t) {
+function lS(i, e, t) {
const n = this.cache, s = t.allocateTextureUnit();
- n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTexture2DArray(e || sx, s);
+ n[0] !== s && (i.uniform1i(this.addr, s), n[0] = s), t.setTexture2DArray(e || ix, s);
}
-function uS(i) {
+function hS(i) {
switch (i) {
case 5126:
- return qI;
+ return WI;
// FLOAT
case 35664:
- return KI;
+ return qI;
// _VEC2
case 35665:
- return jI;
+ return KI;
// _VEC3
case 35666:
- return XI;
+ return jI;
// _VEC4
case 35674:
- return YI;
+ return XI;
// _MAT2
case 35675:
- return JI;
+ return YI;
// _MAT3
case 35676:
- return ZI;
+ return JI;
// _MAT4
case 5124:
case 35670:
- return $I;
+ return ZI;
// INT, BOOL
case 35667:
case 35671:
- return eS;
+ return $I;
// _VEC2
case 35668:
case 35672:
- return tS;
+ return eS;
// _VEC3
case 35669:
case 35673:
- return nS;
+ return tS;
// _VEC4
case 5125:
- return iS;
+ return nS;
// UINT
case 36294:
- return sS;
+ return iS;
// _VEC2
case 36295:
- return rS;
+ return sS;
// _VEC3
case 36296:
- return aS;
+ return rS;
// _VEC4
case 35678:
// SAMPLER_2D
@@ -20448,13 +20448,13 @@ function uS(i) {
case 36306:
// UNSIGNED_INT_SAMPLER_2D
case 35682:
- return oS;
+ return aS;
case 35679:
// SAMPLER_3D
case 36299:
// INT_SAMPLER_3D
case 36307:
- return cS;
+ return oS;
case 35680:
// SAMPLER_CUBE
case 36300:
@@ -20462,7 +20462,7 @@ function uS(i) {
case 36308:
// UNSIGNED_INT_SAMPLER_CUBE
case 36293:
- return lS;
+ return cS;
case 36289:
// SAMPLER_2D_ARRAY
case 36303:
@@ -20470,134 +20470,134 @@ function uS(i) {
case 36311:
// UNSIGNED_INT_SAMPLER_2D_ARRAY
case 36292:
- return hS;
+ return lS;
}
}
-function dS(i, e) {
+function uS(i, e) {
i.uniform1fv(this.addr, e);
}
-function fS(i, e) {
+function dS(i, e) {
const t = Ya(e, this.size, 2);
i.uniform2fv(this.addr, t);
}
-function pS(i, e) {
+function fS(i, e) {
const t = Ya(e, this.size, 3);
i.uniform3fv(this.addr, t);
}
-function AS(i, e) {
+function pS(i, e) {
const t = Ya(e, this.size, 4);
i.uniform4fv(this.addr, t);
}
-function gS(i, e) {
+function AS(i, e) {
const t = Ya(e, this.size, 4);
i.uniformMatrix2fv(this.addr, !1, t);
}
-function mS(i, e) {
+function gS(i, e) {
const t = Ya(e, this.size, 9);
i.uniformMatrix3fv(this.addr, !1, t);
}
-function xS(i, e) {
+function mS(i, e) {
const t = Ya(e, this.size, 16);
i.uniformMatrix4fv(this.addr, !1, t);
}
-function bS(i, e) {
+function xS(i, e) {
i.uniform1iv(this.addr, e);
}
-function ES(i, e) {
+function bS(i, e) {
i.uniform2iv(this.addr, e);
}
-function yS(i, e) {
+function ES(i, e) {
i.uniform3iv(this.addr, e);
}
-function _S(i, e) {
+function yS(i, e) {
i.uniform4iv(this.addr, e);
}
-function wS(i, e) {
+function _S(i, e) {
i.uniform1uiv(this.addr, e);
}
-function vS(i, e) {
+function wS(i, e) {
i.uniform2uiv(this.addr, e);
}
-function CS(i, e) {
+function vS(i, e) {
i.uniform3uiv(this.addr, e);
}
-function IS(i, e) {
+function CS(i, e) {
i.uniform4uiv(this.addr, e);
}
-function SS(i, e, t) {
+function IS(i, e, t) {
const n = this.cache, s = e.length, r = _h(t, s);
gn(n, r) || (i.uniform1iv(this.addr, r), mn(n, r));
for (let a = 0; a !== s; ++a)
- t.setTexture2D(e[a] || ix, r[a]);
+ t.setTexture2D(e[a] || nx, r[a]);
}
-function MS(i, e, t) {
+function SS(i, e, t) {
const n = this.cache, s = e.length, r = _h(t, s);
gn(n, r) || (i.uniform1iv(this.addr, r), mn(n, r));
for (let a = 0; a !== s; ++a)
- t.setTexture3D(e[a] || rx, r[a]);
+ t.setTexture3D(e[a] || sx, r[a]);
}
-function BS(i, e, t) {
+function MS(i, e, t) {
const n = this.cache, s = e.length, r = _h(t, s);
gn(n, r) || (i.uniform1iv(this.addr, r), mn(n, r));
for (let a = 0; a !== s; ++a)
- t.setTextureCube(e[a] || ax, r[a]);
+ t.setTextureCube(e[a] || rx, r[a]);
}
-function TS(i, e, t) {
+function BS(i, e, t) {
const n = this.cache, s = e.length, r = _h(t, s);
gn(n, r) || (i.uniform1iv(this.addr, r), mn(n, r));
for (let a = 0; a !== s; ++a)
- t.setTexture2DArray(e[a] || sx, r[a]);
+ t.setTexture2DArray(e[a] || ix, r[a]);
}
-function RS(i) {
+function TS(i) {
switch (i) {
case 5126:
- return dS;
+ return uS;
// FLOAT
case 35664:
- return fS;
+ return dS;
// _VEC2
case 35665:
- return pS;
+ return fS;
// _VEC3
case 35666:
- return AS;
+ return pS;
// _VEC4
case 35674:
- return gS;
+ return AS;
// _MAT2
case 35675:
- return mS;
+ return gS;
// _MAT3
case 35676:
- return xS;
+ return mS;
// _MAT4
case 5124:
case 35670:
- return bS;
+ return xS;
// INT, BOOL
case 35667:
case 35671:
- return ES;
+ return bS;
// _VEC2
case 35668:
case 35672:
- return yS;
+ return ES;
// _VEC3
case 35669:
case 35673:
- return _S;
+ return yS;
// _VEC4
case 5125:
- return wS;
+ return _S;
// UINT
case 36294:
- return vS;
+ return wS;
// _VEC2
case 36295:
- return CS;
+ return vS;
// _VEC3
case 36296:
- return IS;
+ return CS;
// _VEC4
case 35678:
// SAMPLER_2D
@@ -20608,13 +20608,13 @@ function RS(i) {
case 36306:
// UNSIGNED_INT_SAMPLER_2D
case 35682:
- return SS;
+ return IS;
case 35679:
// SAMPLER_3D
case 36299:
// INT_SAMPLER_3D
case 36307:
- return MS;
+ return SS;
case 35680:
// SAMPLER_CUBE
case 36300:
@@ -20622,7 +20622,7 @@ function RS(i) {
case 36308:
// UNSIGNED_INT_SAMPLER_CUBE
case 36293:
- return BS;
+ return MS;
case 36289:
// SAMPLER_2D_ARRAY
case 36303:
@@ -20630,20 +20630,20 @@ function RS(i) {
case 36311:
// UNSIGNED_INT_SAMPLER_2D_ARRAY
case 36292:
- return TS;
+ return BS;
}
}
-class FS {
+class RS {
constructor(e, t, n) {
- this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.setValue = uS(t.type);
+ this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.setValue = hS(t.type);
}
}
-class NS {
+class FS {
constructor(e, t, n) {
- this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = RS(t.type);
+ this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = TS(t.type);
}
}
-class DS {
+class NS {
constructor(e) {
this.id = e, this.seq = [], this.map = {};
}
@@ -20659,18 +20659,18 @@ const _u = /(\w+)(\])?(\[|\.)?/g;
function KA(i, e) {
i.seq.push(e), i.map[e.id] = e;
}
-function LS(i, e, t) {
+function DS(i, e, t) {
const n = i.name, s = n.length;
for (_u.lastIndex = 0; ; ) {
const r = _u.exec(n), a = _u.lastIndex;
let o = r[1];
const c = r[2] === "]", l = r[3];
if (c && (o = o | 0), l === void 0 || l === "[" && a + 2 === s) {
- KA(t, l === void 0 ? new FS(o, i, e) : new NS(o, i, e));
+ KA(t, l === void 0 ? new RS(o, i, e) : new FS(o, i, e));
break;
} else {
let u = t.map[o];
- u === void 0 && (u = new DS(o), KA(t, u)), t = u;
+ u === void 0 && (u = new NS(o), KA(t, u)), t = u;
}
}
}
@@ -20680,7 +20680,7 @@ class Rl {
const n = e.getProgramParameter(t, e.ACTIVE_UNIFORMS);
for (let s = 0; s < n; ++s) {
const r = e.getActiveUniform(t, s), a = e.getUniformLocation(t, r.name);
- LS(r, a, this);
+ DS(r, a, this);
}
}
setValue(e, t, n, s) {
@@ -20710,9 +20710,9 @@ function jA(i, e, t) {
const n = i.createShader(e);
return i.shaderSource(n, t), i.compileShader(n), n;
}
-const PS = 37297;
-let kS = 0;
-function US(i, e) {
+const LS = 37297;
+let PS = 0;
+function kS(i, e) {
const t = i.split(`
`), n = [], s = Math.max(e - 6, 0), r = Math.min(e + 6, t.length);
for (let a = s; a < r; a++) {
@@ -20723,7 +20723,7 @@ function US(i, e) {
`);
}
const XA = /* @__PURE__ */ new at();
-function OS(i) {
+function US(i) {
rt._getMatrix(XA, rt.workingColorSpace, i);
const e = `mat3( ${XA.elements.map((t) => t.toFixed(4))} )`;
switch (rt.getTransfer(i)) {
@@ -20745,12 +20745,12 @@ function YA(i, e, t) {
` + s + `
-` + US(i.getShaderSource(e), a);
+` + kS(i.getShaderSource(e), a);
} else
return s;
}
-function QS(i, e) {
- const t = OS(e);
+function OS(i, e) {
+ const t = US(e);
return [
`vec4 ${i}( vec4 value ) {`,
` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,
@@ -20758,28 +20758,28 @@ function QS(i, e) {
].join(`
`);
}
-function GS(i, e) {
+function QS(i, e) {
let t;
switch (e) {
case _d:
t = "Linear";
break;
- case Sy:
+ case Iy:
t = "Reinhard";
break;
- case My:
+ case Sy:
t = "Cineon";
break;
- case x0:
+ case m0:
t = "ACESFilmic";
break;
- case Ty:
+ case By:
t = "AgX";
break;
- case Ry:
+ case Ty:
t = "Neutral";
break;
- case By:
+ case My:
t = "Custom";
break;
default:
@@ -20788,7 +20788,7 @@ function GS(i, e) {
return "vec3 " + i + "( vec3 color ) { return " + t + "ToneMapping( color ); }";
}
const il = /* @__PURE__ */ new G();
-function HS() {
+function GS() {
rt.getLuminanceCoefficients(il);
const i = il.x.toFixed(4), e = il.y.toFixed(4), t = il.z.toFixed(4);
return [
@@ -20799,14 +20799,14 @@ function HS() {
].join(`
`);
}
-function zS(i) {
+function HS(i) {
return [
i.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "",
i.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""
].filter(vo).join(`
`);
}
-function VS(i) {
+function zS(i) {
const e = [];
for (const t in i) {
const n = i[t];
@@ -20815,7 +20815,7 @@ function VS(i) {
return e.join(`
`);
}
-function WS(i, e) {
+function VS(i, e) {
const t = {}, n = i.getProgramParameter(e, i.ACTIVE_ATTRIBUTES);
for (let s = 0; s < n; s++) {
const r = i.getActiveAttrib(e, s), a = r.name;
@@ -20838,15 +20838,15 @@ function JA(i, e) {
function ZA(i, e) {
return i.replace(/NUM_CLIPPING_PLANES/g, e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, e.numClippingPlanes - e.numClipIntersection);
}
-const qS = /^[ \t]*#include +<([\w\d./]+)>/gm;
+const WS = /^[ \t]*#include +<([\w\d./]+)>/gm;
function Yd(i) {
- return i.replace(qS, jS);
+ return i.replace(WS, KS);
}
-const KS = /* @__PURE__ */ new Map();
-function jS(i, e) {
+const qS = /* @__PURE__ */ new Map();
+function KS(i, e) {
let t = lt[e];
if (t === void 0) {
- const n = KS.get(e);
+ const n = qS.get(e);
if (n !== void 0)
t = lt[n], console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', e, n);
else
@@ -20854,11 +20854,11 @@ function jS(i, e) {
}
return Yd(t);
}
-const XS = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
+const jS = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
function $A(i) {
- return i.replace(XS, YS);
+ return i.replace(jS, XS);
}
-function YS(i, e, t, n) {
+function XS(i, e, t, n) {
let s = "";
for (let r = parseInt(e); r < parseInt(t); r++)
s += n.replace(/\[\s*i\s*\]/g, "[ " + r + " ]").replace(/UNROLLED_LOOP_INDEX/g, r);
@@ -20888,11 +20888,11 @@ function eg(i) {
#define MEDIUM_PRECISION` : i.precision === "lowp" && (e += `
#define LOW_PRECISION`), e;
}
-function JS(i) {
+function YS(i) {
let e = "SHADOWMAP_TYPE_BASIC";
- return i.shadowMapType === m0 ? e = "SHADOWMAP_TYPE_PCF" : i.shadowMapType === ay ? e = "SHADOWMAP_TYPE_PCF_SOFT" : i.shadowMapType === es && (e = "SHADOWMAP_TYPE_VSM"), e;
+ return i.shadowMapType === g0 ? e = "SHADOWMAP_TYPE_PCF" : i.shadowMapType === ry ? e = "SHADOWMAP_TYPE_PCF_SOFT" : i.shadowMapType === es && (e = "SHADOWMAP_TYPE_VSM"), e;
}
-function ZS(i) {
+function JS(i) {
let e = "ENVMAP_TYPE_CUBE";
if (i.envMap)
switch (i.envMapMode) {
@@ -20906,36 +20906,36 @@ function ZS(i) {
}
return e;
}
-function $S(i) {
+function ZS(i) {
let e = "ENVMAP_MODE_REFLECTION";
return i.envMap && i.envMapMode === La && (e = "ENVMAP_MODE_REFRACTION"), e;
}
-function e1(i) {
+function $S(i) {
let e = "ENVMAP_BLENDING_NONE";
if (i.envMap)
switch (i.combine) {
case fh:
e = "ENVMAP_BLENDING_MULTIPLY";
break;
- case Cy:
+ case vy:
e = "ENVMAP_BLENDING_MIX";
break;
- case Iy:
+ case Cy:
e = "ENVMAP_BLENDING_ADD";
break;
}
return e;
}
-function t1(i) {
+function e1(i) {
const e = i.envMapCubeUVHeight;
if (e === null) return null;
const t = Math.log2(e) - 2, n = 1 / e;
return { texelWidth: 1 / (3 * Math.max(Math.pow(2, t), 112)), texelHeight: n, maxMip: t };
}
-function n1(i, e, t, n) {
+function t1(i, e, t, n) {
const s = i.getContext(), r = t.defines;
let a = t.vertexShader, o = t.fragmentShader;
- const c = JS(t), l = ZS(t), h = $S(t), u = e1(t), d = t1(t), f = zS(t), p = VS(r), m = s.createProgram();
+ const c = YS(t), l = JS(t), h = ZS(t), u = $S(t), d = e1(t), f = HS(t), p = zS(r), m = s.createProgram();
let g, A, _ = t.glslVersion ? "#version " + t.glslVersion + `
` : "";
t.isRawShaderMaterial ? (g = [
@@ -21156,13 +21156,13 @@ function n1(i, e, t, n) {
t.toneMapping !== Hs ? "#define TONE_MAPPING" : "",
t.toneMapping !== Hs ? lt.tonemapping_pars_fragment : "",
// this code is required here because it is used by the toneMapping() function defined below
- t.toneMapping !== Hs ? GS("toneMapping", t.toneMapping) : "",
+ t.toneMapping !== Hs ? QS("toneMapping", t.toneMapping) : "",
t.dithering ? "#define DITHERING" : "",
t.opaque ? "#define OPAQUE" : "",
lt.colorspace_pars_fragment,
// this code is required here because it is used by the various encoding/decoding function defined below
- QS("linearToOutputTexel", t.outputColorSpace),
- HS(),
+ OS("linearToOutputTexel", t.outputColorSpace),
+ GS(),
t.useDepthPacking ? "#define DEPTH_PACKING " + t.depthPacking : "",
`
`
@@ -21228,7 +21228,7 @@ Program Info Log: ` + K + `
}
});
}
- s.deleteShader(S), s.deleteShader(w), T = new Rl(s, m), C = WS(s, m);
+ s.deleteShader(S), s.deleteShader(w), T = new Rl(s, m), C = VS(s, m);
}
let T;
this.getUniforms = function() {
@@ -21240,13 +21240,13 @@ Program Info Log: ` + K + `
};
let v = t.rendererExtensionParallelShaderCompile === !1;
return this.isReady = function() {
- return v === !1 && (v = s.getProgramParameter(m, PS)), v;
+ return v === !1 && (v = s.getProgramParameter(m, LS)), v;
}, this.destroy = function() {
n.releaseStatesOfProgram(this), s.deleteProgram(m), this.program = void 0;
- }, this.type = t.shaderType, this.name = t.shaderName, this.id = kS++, this.cacheKey = e, this.usedTimes = 1, this.program = m, this.vertexShader = S, this.fragmentShader = w, this;
+ }, this.type = t.shaderType, this.name = t.shaderName, this.id = PS++, this.cacheKey = e, this.usedTimes = 1, this.program = m, this.vertexShader = S, this.fragmentShader = w, this;
}
-let i1 = 0;
-class s1 {
+let n1 = 0;
+class i1 {
constructor() {
this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map();
}
@@ -21277,16 +21277,16 @@ class s1 {
_getShaderStage(e) {
const t = this.shaderCache;
let n = t.get(e);
- return n === void 0 && (n = new r1(e), t.set(e, n)), n;
+ return n === void 0 && (n = new s1(e), t.set(e, n)), n;
}
}
-class r1 {
+class s1 {
constructor(e) {
- this.id = i1++, this.code = e, this.usedTimes = 0;
+ this.id = n1++, this.code = e, this.usedTimes = 0;
}
}
-function a1(i, e, t, n, s, r, a) {
- const o = new D0(), c = new s1(), l = /* @__PURE__ */ new Set(), h = [], u = s.logarithmicDepthBuffer, d = s.vertexTextures;
+function r1(i, e, t, n, s, r, a) {
+ const o = new N0(), c = new i1(), l = /* @__PURE__ */ new Set(), h = [], u = s.logarithmicDepthBuffer, d = s.vertexTextures;
let f = s.precision;
const p = {
MeshDepthMaterial: "depth",
@@ -21354,7 +21354,7 @@ function a1(i, e, t, n, s, r, a) {
normalMap: gt,
displacementMap: d && We,
emissiveMap: Dt,
- normalMapObjectSpace: gt && C.normalMapType === Uy,
+ normalMapObjectSpace: gt && C.normalMapType === ky,
normalMapTangentSpace: gt && C.normalMapType === Ah,
metalnessMap: ze,
roughnessMap: L,
@@ -21475,7 +21475,7 @@ function a1(i, e, t, n, s, r, a) {
let F;
if (v) {
const K = Ui[v];
- F = F_.clone(K.uniforms);
+ F = R_.clone(K.uniforms);
} else
F = C.uniforms;
return F;
@@ -21489,7 +21489,7 @@ function a1(i, e, t, n, s, r, a) {
break;
}
}
- return F === void 0 && (F = new n1(i, v, C, r), h.push(F)), F;
+ return F === void 0 && (F = new t1(i, v, C, r), h.push(F)), F;
}
function w(C) {
if (--C.usedTimes === 0) {
@@ -21515,7 +21515,7 @@ function a1(i, e, t, n, s, r, a) {
dispose: T
};
}
-function o1() {
+function a1() {
let i = /* @__PURE__ */ new WeakMap();
function e(a) {
return i.has(a);
@@ -21541,7 +21541,7 @@ function o1() {
dispose: r
};
}
-function c1(i, e) {
+function o1(i, e) {
return i.groupOrder !== e.groupOrder ? i.groupOrder - e.groupOrder : i.renderOrder !== e.renderOrder ? i.renderOrder - e.renderOrder : i.material.id !== e.material.id ? i.material.id - e.material.id : i.z !== e.z ? i.z - e.z : i.id - e.id;
}
function tg(i, e) {
@@ -21576,7 +21576,7 @@ function ng() {
f.transmission > 0 ? n.unshift(A) : f.transparent === !0 ? s.unshift(A) : t.unshift(A);
}
function l(u, d) {
- t.length > 1 && t.sort(u || c1), n.length > 1 && n.sort(d || tg), s.length > 1 && s.sort(d || tg);
+ t.length > 1 && t.sort(u || o1), n.length > 1 && n.sort(d || tg), s.length > 1 && s.sort(d || tg);
}
function h() {
for (let u = e, d = i.length; u < d; u++) {
@@ -21596,7 +21596,7 @@ function ng() {
sort: l
};
}
-function l1() {
+function c1() {
let i = /* @__PURE__ */ new WeakMap();
function e(n, s) {
const r = i.get(n);
@@ -21611,7 +21611,7 @@ function l1() {
dispose: t
};
}
-function h1() {
+function l1() {
const i = {};
return {
get: function(e) {
@@ -21664,7 +21664,7 @@ function h1() {
}
};
}
-function u1() {
+function h1() {
const i = {};
return {
get: function(e) {
@@ -21706,12 +21706,12 @@ function u1() {
}
};
}
-let d1 = 0;
-function f1(i, e) {
+let u1 = 0;
+function d1(i, e) {
return (e.castShadow ? 2 : 0) - (i.castShadow ? 2 : 0) + (e.map ? 1 : 0) - (i.map ? 1 : 0);
}
-function p1(i) {
- const e = new h1(), t = u1(), n = {
+function f1(i) {
+ const e = new l1(), t = h1(), n = {
version: 0,
hash: {
directionalLength: -1,
@@ -21753,7 +21753,7 @@ function p1(i) {
let h = 0, u = 0, d = 0;
for (let C = 0; C < 9; C++) n.probe[C].set(0, 0, 0);
let f = 0, p = 0, m = 0, g = 0, A = 0, _ = 0, x = 0, E = 0, S = 0, w = 0, I = 0;
- l.sort(f1);
+ l.sort(d1);
for (let C = 0, v = l.length; C < v; C++) {
const F = l[C], K = F.color, q = F.intensity, $ = F.distance, D = F.shadow && F.shadow.map ? F.shadow.map.texture : null;
if (F.isAmbientLight)
@@ -21795,7 +21795,7 @@ function p1(i) {
}
g > 0 && (i.has("OES_texture_float_linear") === !0 ? (n.rectAreaLTC1 = we.LTC_FLOAT_1, n.rectAreaLTC2 = we.LTC_FLOAT_2) : (n.rectAreaLTC1 = we.LTC_HALF_1, n.rectAreaLTC2 = we.LTC_HALF_2)), n.ambient[0] = h, n.ambient[1] = u, n.ambient[2] = d;
const T = n.hash;
- (T.directionalLength !== f || T.pointLength !== p || T.spotLength !== m || T.rectAreaLength !== g || T.hemiLength !== A || T.numDirectionalShadows !== _ || T.numPointShadows !== x || T.numSpotShadows !== E || T.numSpotMaps !== S || T.numLightProbes !== I) && (n.directional.length = f, n.spot.length = m, n.rectArea.length = g, n.point.length = p, n.hemi.length = A, n.directionalShadow.length = _, n.directionalShadowMap.length = _, n.pointShadow.length = x, n.pointShadowMap.length = x, n.spotShadow.length = E, n.spotShadowMap.length = E, n.directionalShadowMatrix.length = _, n.pointShadowMatrix.length = x, n.spotLightMatrix.length = E + S - w, n.spotLightMap.length = S, n.numSpotLightShadowsWithMaps = w, n.numLightProbes = I, T.directionalLength = f, T.pointLength = p, T.spotLength = m, T.rectAreaLength = g, T.hemiLength = A, T.numDirectionalShadows = _, T.numPointShadows = x, T.numSpotShadows = E, T.numSpotMaps = S, T.numLightProbes = I, n.version = d1++);
+ (T.directionalLength !== f || T.pointLength !== p || T.spotLength !== m || T.rectAreaLength !== g || T.hemiLength !== A || T.numDirectionalShadows !== _ || T.numPointShadows !== x || T.numSpotShadows !== E || T.numSpotMaps !== S || T.numLightProbes !== I) && (n.directional.length = f, n.spot.length = m, n.rectArea.length = g, n.point.length = p, n.hemi.length = A, n.directionalShadow.length = _, n.directionalShadowMap.length = _, n.pointShadow.length = x, n.pointShadowMap.length = x, n.spotShadow.length = E, n.spotShadowMap.length = E, n.directionalShadowMatrix.length = _, n.pointShadowMatrix.length = x, n.spotLightMatrix.length = E + S - w, n.spotLightMap.length = S, n.numSpotLightShadowsWithMaps = w, n.numLightProbes = I, T.directionalLength = f, T.pointLength = p, T.spotLength = m, T.rectAreaLength = g, T.hemiLength = A, T.numDirectionalShadows = _, T.numPointShadows = x, T.numSpotShadows = E, T.numSpotMaps = S, T.numLightProbes = I, n.version = u1++);
}
function c(l, h) {
let u = 0, d = 0, f = 0, p = 0, m = 0;
@@ -21827,7 +21827,7 @@ function p1(i) {
};
}
function ig(i) {
- const e = new p1(i), t = [], n = [];
+ const e = new f1(i), t = [], n = [];
function s(h) {
l.camera = h, t.length = 0, n.length = 0;
}
@@ -21859,7 +21859,7 @@ function ig(i) {
pushShadow: a
};
}
-function A1(i) {
+function p1(i) {
let e = /* @__PURE__ */ new WeakMap();
function t(s, r = 0) {
const a = e.get(s);
@@ -21874,9 +21874,9 @@ function A1(i) {
dispose: n
};
}
-const g1 = `void main() {
+const A1 = `void main() {
gl_Position = vec4( position, 1.0 );
-}`, m1 = `uniform sampler2D shadow_pass;
+}`, g1 = `uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
@@ -21903,9 +21903,9 @@ void main() {
float std_dev = sqrt( squared_mean - mean * mean );
gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;
-function x1(i, e, t) {
+function m1(i, e, t) {
let n = new Yf();
- const s = new Ze(), r = new Ze(), a = new mt(), o = new pw({ depthPacking: ky }), c = new Aw(), l = {}, h = t.maxTextureSize, u = { [bs]: Wn, [Wn]: bs, [Oi]: Oi }, d = new qs({
+ const s = new Ze(), r = new Ze(), a = new mt(), o = new fw({ depthPacking: Py }), c = new pw(), l = {}, h = t.maxTextureSize, u = { [bs]: Wn, [Wn]: bs, [Oi]: Oi }, d = new qs({
defines: {
VSM_SAMPLES: 8
},
@@ -21914,8 +21914,8 @@ function x1(i, e, t) {
resolution: { value: new Ze() },
radius: { value: 4 }
},
- vertexShader: g1,
- fragmentShader: m1
+ vertexShader: A1,
+ fragmentShader: g1
}), f = d.clone();
f.defines.HORIZONTAL_PASS = 1;
const p = new Tn();
@@ -21927,7 +21927,7 @@ function x1(i, e, t) {
)
);
const m = new Zt(p, d), g = this;
- this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = m0;
+ this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = g0;
let A = this.type;
this.render = function(w, I, T) {
if (g.enabled === !1 || g.autoUpdate === !1 && g.needsUpdate === !1 || w.length === 0) return;
@@ -22015,7 +22015,7 @@ function x1(i, e, t) {
}
}
}
-const b1 = {
+const x1 = {
[Ad]: gd,
[md]: Ed,
[xd]: yd,
@@ -22025,7 +22025,7 @@ const b1 = {
[yd]: xd,
[bd]: Da
};
-function E1(i, e) {
+function b1(i, e) {
function t() {
let W = !1;
const ne = new mt();
@@ -22067,7 +22067,7 @@ function E1(i, e) {
re !== Ce && !W && (i.depthMask(Ce), re = Ce);
},
setFunc: function(Ce) {
- if (ne && (Ce = b1[Ce]), de !== Ce) {
+ if (ne && (Ce = x1[Ce]), de !== Ce) {
switch (Ce) {
case Ad:
i.depthFunc(i.NEVER);
@@ -22181,33 +22181,33 @@ function E1(i, e) {
}
const ht = {
[pr]: i.FUNC_ADD,
- [cy]: i.FUNC_SUBTRACT,
- [ly]: i.FUNC_REVERSE_SUBTRACT
+ [oy]: i.FUNC_SUBTRACT,
+ [cy]: i.FUNC_REVERSE_SUBTRACT
};
- ht[hy] = i.MIN, ht[uy] = i.MAX;
+ ht[ly] = i.MIN, ht[hy] = i.MAX;
const $e = {
- [dy]: i.ZERO,
- [fy]: i.ONE,
- [py]: i.SRC_COLOR,
+ [uy]: i.ZERO,
+ [dy]: i.ONE,
+ [fy]: i.SRC_COLOR,
[fd]: i.SRC_ALPHA,
- [Ey]: i.SRC_ALPHA_SATURATE,
- [xy]: i.DST_COLOR,
- [gy]: i.DST_ALPHA,
- [Ay]: i.ONE_MINUS_SRC_COLOR,
+ [by]: i.SRC_ALPHA_SATURATE,
+ [my]: i.DST_COLOR,
+ [Ay]: i.DST_ALPHA,
+ [py]: i.ONE_MINUS_SRC_COLOR,
[pd]: i.ONE_MINUS_SRC_ALPHA,
- [by]: i.ONE_MINUS_DST_COLOR,
- [my]: i.ONE_MINUS_DST_ALPHA,
- [yy]: i.CONSTANT_COLOR,
- [_y]: i.ONE_MINUS_CONSTANT_COLOR,
- [wy]: i.CONSTANT_ALPHA,
- [vy]: i.ONE_MINUS_CONSTANT_ALPHA
+ [xy]: i.ONE_MINUS_DST_COLOR,
+ [gy]: i.ONE_MINUS_DST_ALPHA,
+ [Ey]: i.CONSTANT_COLOR,
+ [yy]: i.ONE_MINUS_CONSTANT_COLOR,
+ [_y]: i.CONSTANT_ALPHA,
+ [wy]: i.ONE_MINUS_CONSTANT_ALPHA
};
function H(W, ne, re, de, Se, Ce, it, Qt, bn, Ct) {
if (W === Gs) {
m === !0 && (Ue(i.BLEND), m = !1);
return;
}
- if (m === !1 && (be(i.BLEND), m = !0), W !== oy) {
+ if (m === !1 && (be(i.BLEND), m = !0), W !== ay) {
if (W !== g || Ct !== C) {
if ((A !== pr || E !== pr) && (i.blendEquation(i.FUNC_ADD), A = pr, E = pr), Ct)
switch (W) {
@@ -22262,7 +22262,7 @@ function E1(i, e) {
v !== W && (W ? i.frontFace(i.CW) : i.frontFace(i.CCW), v = W);
}
function gt(W) {
- W !== sy ? (be(i.CULL_FACE), W !== F && (W === Op ? i.cullFace(i.BACK) : W === ry ? i.cullFace(i.FRONT) : i.cullFace(i.FRONT_AND_BACK))) : Ue(i.CULL_FACE), F = W;
+ W !== iy ? (be(i.CULL_FACE), W !== F && (W === Op ? i.cullFace(i.BACK) : W === sy ? i.cullFace(i.FRONT) : i.cullFace(i.FRONT_AND_BACK))) : Ue(i.CULL_FACE), F = W;
}
function We(W) {
W !== K && (O && i.lineWidth(W), K = W);
@@ -22412,7 +22412,7 @@ function E1(i, e) {
reset: nt
};
}
-function y1(i, e, t, n, s, r, a) {
+function E1(i, e, t, n, s, r, a) {
const o = e.has("WEBGL_multisampled_render_to_texture") ? e.get("WEBGL_multisampled_render_to_texture") : null, c = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), l = new Ze(), h = /* @__PURE__ */ new WeakMap();
let u;
const d = /* @__PURE__ */ new WeakMap();
@@ -22576,20 +22576,20 @@ function y1(i, e, t, n, s, r, a) {
[Ul]: i.MIRRORED_REPEAT
}, ee = {
[qn]: i.NEAREST,
- [E0]: i.NEAREST_MIPMAP_NEAREST,
+ [b0]: i.NEAREST_MIPMAP_NEAREST,
[_o]: i.NEAREST_MIPMAP_LINEAR,
[Xt]: i.LINEAR,
[Sl]: i.LINEAR_MIPMAP_NEAREST,
[ui]: i.LINEAR_MIPMAP_LINEAR
}, ae = {
- [Oy]: i.NEVER,
- [Wy]: i.ALWAYS,
- [Qy]: i.LESS,
- [T0]: i.LEQUAL,
- [Gy]: i.EQUAL,
- [Vy]: i.GEQUAL,
- [Hy]: i.GREATER,
- [zy]: i.NOTEQUAL
+ [Uy]: i.NEVER,
+ [Vy]: i.ALWAYS,
+ [Oy]: i.LESS,
+ [B0]: i.LEQUAL,
+ [Qy]: i.EQUAL,
+ [zy]: i.GEQUAL,
+ [Gy]: i.GREATER,
+ [Hy]: i.NOTEQUAL
};
function _e(L, M) {
if (M.type === fn && e.has("OES_texture_float_linear") === !1 && (M.magFilter === Xt || M.magFilter === Sl || M.magFilter === _o || M.magFilter === ui || M.minFilter === Xt || M.minFilter === Sl || M.minFilter === _o || M.minFilter === ui) && console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), i.texParameteri(L, i.TEXTURE_WRAP_S, J[M.wrapS]), i.texParameteri(L, i.TEXTURE_WRAP_T, J[M.wrapT]), (L === i.TEXTURE_3D || L === i.TEXTURE_2D_ARRAY) && i.texParameteri(L, i.TEXTURE_WRAP_R, J[M.wrapR]), i.texParameteri(L, i.TEXTURE_MAG_FILTER, ee[M.magFilter]), i.texParameteri(L, i.TEXTURE_MIN_FILTER, ee[M.minFilter]), M.compareFunction && (i.texParameteri(L, i.TEXTURE_COMPARE_MODE, i.COMPARE_REF_TO_TEXTURE), i.texParameteri(L, i.TEXTURE_COMPARE_FUNC, ae[M.compareFunction])), e.has("EXT_texture_filter_anisotropic") === !0) {
@@ -22974,23 +22974,23 @@ function y1(i, e, t, n, s, r, a) {
}
this.allocateTextureUnit = q, this.resetTextureUnits = K, this.setTexture2D = D, this.setTexture2DArray = O, this.setTexture3D = Y, this.setTextureCube = Q, this.rebindTextures = He, this.setupRenderTarget = St, this.updateRenderTargetMipmap = ht, this.updateMultisampleRenderTarget = xn, this.setupDepthRenderbuffer = et, this.setupFrameBufferTexture = xe, this.useMultisampledRTT = gt;
}
-function _1(i, e) {
+function y1(i, e) {
function t(n, s = Ci) {
let r;
const a = rt.getTransfer(s);
if (n === un) return i.UNSIGNED_BYTE;
if (n === Qf) return i.UNSIGNED_SHORT_4_4_4_4;
if (n === Gf) return i.UNSIGNED_SHORT_5_5_5_1;
- if (n === w0) return i.UNSIGNED_INT_5_9_9_9_REV;
- if (n === y0) return i.BYTE;
- if (n === _0) return i.SHORT;
+ if (n === _0) return i.UNSIGNED_INT_5_9_9_9_REV;
+ if (n === E0) return i.BYTE;
+ if (n === y0) return i.SHORT;
if (n === Go) return i.UNSIGNED_SHORT;
if (n === Of) return i.INT;
if (n === Tr) return i.UNSIGNED_INT;
if (n === fn) return i.FLOAT;
if (n === Gn) return i.HALF_FLOAT;
- if (n === v0) return i.ALPHA;
- if (n === C0) return i.RGB;
+ if (n === w0) return i.ALPHA;
+ if (n === v0) return i.RGB;
if (n === pn) return i.RGBA;
if (n === zo) return i.DEPTH_COMPONENT;
if (n === Vo) return i.DEPTH_STENCIL;
@@ -23054,7 +23054,7 @@ function _1(i, e) {
if (n === Vl) return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
} else
return null;
- if (n === I0 || n === Od || n === Qd || n === Gd)
+ if (n === C0 || n === Od || n === Qd || n === Gd)
if (r = e.get("EXT_texture_compression_rgtc"), r !== null) {
if (n === Fo) return r.COMPRESSED_RED_RGTC1_EXT;
if (n === Od) return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;
@@ -23066,12 +23066,12 @@ function _1(i, e) {
}
return { convert: t };
}
-const w1 = `
+const _1 = `
void main() {
gl_Position = vec4( position, 1.0 );
-}`, v1 = `
+}`, w1 = `
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;
@@ -23091,7 +23091,7 @@ void main() {
}
}`;
-class C1 {
+class v1 {
/**
* Constructs a new depth sensing module.
*/
@@ -23120,8 +23120,8 @@ class C1 {
getMesh(e) {
if (this.texture !== null && this.mesh === null) {
const t = e.cameras[0].viewport, n = new qs({
- vertexShader: w1,
- fragmentShader: v1,
+ vertexShader: _1,
+ fragmentShader: w1,
uniforms: {
depthColor: { value: this.texture },
depthWidth: { value: t.z },
@@ -23147,7 +23147,7 @@ class C1 {
return this.texture;
}
}
-class I1 extends Js {
+class C1 extends Js {
/**
* Constructs a new WebGL renderer.
*
@@ -23158,7 +23158,7 @@ class I1 extends Js {
super();
const n = this;
let s = null, r = 1, a = null, o = "local-floor", c = 1, l = null, h = null, u = null, d = null, f = null, p = null;
- const m = new C1(), g = t.getContextAttributes();
+ const m = new v1(), g = t.getContextAttributes();
let A = null, _ = null;
const x = [], E = [], S = new Ze();
let w = null;
@@ -23166,7 +23166,7 @@ class I1 extends Js {
I.viewport = new mt();
const T = new In();
T.viewport = new mt();
- const C = [I, T], v = new Fw();
+ const C = [I, T], v = new Rw();
let F = null, K = null;
this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(se) {
let me = x[se];
@@ -23225,7 +23225,7 @@ class I1 extends Js {
{
format: pn,
type: un,
- depthTexture: new H0(d.textureWidth, d.textureHeight, be, void 0, void 0, void 0, void 0, void 0, void 0, xe),
+ depthTexture: new G0(d.textureWidth, d.textureHeight, be, void 0, void 0, void 0, void 0, void 0, void 0, xe),
stencilBuffer: g.stencil,
colorSpace: e.outputColorSpace,
samples: g.antialias ? 4 : 0,
@@ -23362,20 +23362,20 @@ class I1 extends Js {
}
ae && ae(se, me), me.detectedPlanes && n.dispatchEvent({ type: "planesdetected", data: me }), p = null;
}
- const Me = new nx();
+ const Me = new tx();
Me.setAnimationLoop(_e), this.setAnimationLoop = function(se) {
ae = se;
}, this.dispose = function() {
};
}
}
-const or = /* @__PURE__ */ new dn(), S1 = /* @__PURE__ */ new Ne();
-function M1(i, e) {
+const or = /* @__PURE__ */ new dn(), I1 = /* @__PURE__ */ new Ne();
+function S1(i, e) {
function t(g, A) {
g.matrixAutoUpdate === !0 && g.updateMatrix(), A.value.copy(g.matrix);
}
function n(g, A) {
- A.color.getRGB(g.fogColor.value, k0(i)), A.isFog ? (g.fogNear.value = A.near, g.fogFar.value = A.far) : A.isFogExp2 && (g.fogDensity.value = A.density);
+ A.color.getRGB(g.fogColor.value, P0(i)), A.isFog ? (g.fogNear.value = A.near, g.fogFar.value = A.far) : A.isFogExp2 && (g.fogDensity.value = A.density);
}
function s(g, A, _, x, E) {
A.isMeshBasicMaterial || A.isMeshLambertMaterial ? r(g, A) : A.isMeshToonMaterial ? (r(g, A), u(g, A)) : A.isMeshPhongMaterial ? (r(g, A), h(g, A)) : A.isMeshStandardMaterial ? (r(g, A), d(g, A), A.isMeshPhysicalMaterial && f(g, A, E)) : A.isMeshMatcapMaterial ? (r(g, A), p(g, A)) : A.isMeshDepthMaterial ? r(g, A) : A.isMeshDistanceMaterial ? (r(g, A), m(g, A)) : A.isMeshNormalMaterial ? r(g, A) : A.isLineBasicMaterial ? (a(g, A), A.isLineDashedMaterial && o(g, A)) : A.isPointsMaterial ? c(g, A, _, x) : A.isSpriteMaterial ? l(g, A) : A.isShadowMaterial ? (g.color.value.copy(A.color), g.opacity.value = A.opacity) : A.isShaderMaterial && (A.uniformsNeedUpdate = !1);
@@ -23383,7 +23383,7 @@ function M1(i, e) {
function r(g, A) {
g.opacity.value = A.opacity, A.color && g.diffuse.value.copy(A.color), A.emissive && g.emissive.value.copy(A.emissive).multiplyScalar(A.emissiveIntensity), A.map && (g.map.value = A.map, t(A.map, g.mapTransform)), A.alphaMap && (g.alphaMap.value = A.alphaMap, t(A.alphaMap, g.alphaMapTransform)), A.bumpMap && (g.bumpMap.value = A.bumpMap, t(A.bumpMap, g.bumpMapTransform), g.bumpScale.value = A.bumpScale, A.side === Wn && (g.bumpScale.value *= -1)), A.normalMap && (g.normalMap.value = A.normalMap, t(A.normalMap, g.normalMapTransform), g.normalScale.value.copy(A.normalScale), A.side === Wn && g.normalScale.value.negate()), A.displacementMap && (g.displacementMap.value = A.displacementMap, t(A.displacementMap, g.displacementMapTransform), g.displacementScale.value = A.displacementScale, g.displacementBias.value = A.displacementBias), A.emissiveMap && (g.emissiveMap.value = A.emissiveMap, t(A.emissiveMap, g.emissiveMapTransform)), A.specularMap && (g.specularMap.value = A.specularMap, t(A.specularMap, g.specularMapTransform)), A.alphaTest > 0 && (g.alphaTest.value = A.alphaTest);
const _ = e.get(A), x = _.envMap, E = _.envMapRotation;
- x && (g.envMap.value = x, or.copy(E), or.x *= -1, or.y *= -1, or.z *= -1, x.isCubeTexture && x.isRenderTargetTexture === !1 && (or.y *= -1, or.z *= -1), g.envMapRotation.value.setFromMatrix4(S1.makeRotationFromEuler(or)), g.flipEnvMap.value = x.isCubeTexture && x.isRenderTargetTexture === !1 ? -1 : 1, g.reflectivity.value = A.reflectivity, g.ior.value = A.ior, g.refractionRatio.value = A.refractionRatio), A.lightMap && (g.lightMap.value = A.lightMap, g.lightMapIntensity.value = A.lightMapIntensity, t(A.lightMap, g.lightMapTransform)), A.aoMap && (g.aoMap.value = A.aoMap, g.aoMapIntensity.value = A.aoMapIntensity, t(A.aoMap, g.aoMapTransform));
+ x && (g.envMap.value = x, or.copy(E), or.x *= -1, or.y *= -1, or.z *= -1, x.isCubeTexture && x.isRenderTargetTexture === !1 && (or.y *= -1, or.z *= -1), g.envMapRotation.value.setFromMatrix4(I1.makeRotationFromEuler(or)), g.flipEnvMap.value = x.isCubeTexture && x.isRenderTargetTexture === !1 ? -1 : 1, g.reflectivity.value = A.reflectivity, g.ior.value = A.ior, g.refractionRatio.value = A.refractionRatio), A.lightMap && (g.lightMap.value = A.lightMap, g.lightMapIntensity.value = A.lightMapIntensity, t(A.lightMap, g.lightMapTransform)), A.aoMap && (g.aoMap.value = A.aoMap, g.aoMapIntensity.value = A.aoMapIntensity, t(A.aoMap, g.aoMapTransform));
}
function a(g, A) {
g.diffuse.value.copy(A.color), g.opacity.value = A.opacity, A.map && (g.map.value = A.map, t(A.map, g.mapTransform));
@@ -23421,7 +23421,7 @@ function M1(i, e) {
refreshMaterialUniforms: s
};
}
-function B1(i, e, t, n) {
+function M1(i, e, t, n) {
let s = {}, r = {}, a = [];
const o = i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);
function c(_, x) {
@@ -23533,7 +23533,7 @@ class sg {
*/
constructor(e = {}) {
const {
- canvas: t = c_(),
+ canvas: t = o_(),
context: n = null,
depth: s = !0,
stencil: r = !1,
@@ -23610,10 +23610,10 @@ class sg {
}
let pt, gt, We, Dt, ze, L, M, Z, le, pe, oe, Qe, ve, qe, Je, Ee, Re, Oe, Ge, Be, tt, Ke, nt, W;
function ne() {
- pt = new QI(H), pt.init(), Ke = new _1(H, pt), gt = new NI(H, pt, e, Ke), We = new E1(H, pt), gt.reverseDepthBuffer && d && We.buffers.depth.setReversed(!0), Dt = new zI(H), ze = new o1(), L = new y1(H, pt, We, ze, gt, Ke, Dt), M = new LI(E), Z = new OI(E), le = new Xw(H), nt = new RI(H, le), pe = new GI(H, le, Dt, nt), oe = new WI(H, pe, le, Dt), Ge = new VI(H, gt, L), Ee = new DI(ze), Qe = new a1(E, M, Z, pt, gt, nt, Ee), ve = new M1(E, ze), qe = new l1(), Je = new A1(pt), Oe = new TI(E, M, Z, We, oe, f, c), Re = new x1(E, oe, gt), W = new B1(H, Dt, gt, We), Be = new FI(H, pt, Dt), tt = new HI(H, pt, Dt), Dt.programs = Qe.programs, E.capabilities = gt, E.extensions = pt, E.properties = ze, E.renderLists = qe, E.shadowMap = Re, E.state = We, E.info = Dt;
+ pt = new OI(H), pt.init(), Ke = new y1(H, pt), gt = new FI(H, pt, e, Ke), We = new b1(H, pt), gt.reverseDepthBuffer && d && We.buffers.depth.setReversed(!0), Dt = new HI(H), ze = new a1(), L = new E1(H, pt, We, ze, gt, Ke, Dt), M = new DI(E), Z = new UI(E), le = new jw(H), nt = new TI(H, le), pe = new QI(H, le, Dt, nt), oe = new VI(H, pe, le, Dt), Ge = new zI(H, gt, L), Ee = new NI(ze), Qe = new r1(E, M, Z, pt, gt, nt, Ee), ve = new S1(E, ze), qe = new c1(), Je = new p1(pt), Oe = new BI(E, M, Z, We, oe, f, c), Re = new m1(E, oe, gt), W = new M1(H, Dt, gt, We), Be = new RI(H, pt, Dt), tt = new GI(H, pt, Dt), Dt.programs = Qe.programs, E.capabilities = gt, E.extensions = pt, E.properties = ze, E.renderLists = qe, E.shadowMap = Re, E.state = We, E.info = Dt;
}
ne();
- const re = new I1(E, H);
+ const re = new C1(E, H);
this.xr = re, this.getContext = function() {
return H;
}, this.getContextAttributes = function() {
@@ -23802,7 +23802,7 @@ class sg {
function vc() {
qi.start();
}
- const qi = new nx();
+ const qi = new tx();
qi.setAnimationLoop(gi), typeof self < "u" && qi.setContext(self), this.setAnimationLoop = function(y) {
Jn = y, re.setAnimationLoop(y), y === null ? qi.stop() : qi.start();
}, re.addEventListener("sessionstart", wc), re.addEventListener("sessionend", vc), this.render = function(y, R) {
@@ -23955,7 +23955,7 @@ class sg {
let on = !1, wt = !1, xt = !1;
const Xe = It.getUniforms(), qt = Fe.uniforms;
if (We.useProgram(It.program) && (on = !0, wt = !0, xt = !0), U.id !== C && (C = U.id, wt = !0), on || v !== y) {
- We.buffers.depth.getReversed() ? (be.copy(y.projectionMatrix), h_(be), u_(be), Xe.setValue(H, "projectionMatrix", be)) : Xe.setValue(H, "projectionMatrix", y.projectionMatrix), Xe.setValue(H, "viewMatrix", y.matrixWorldInverse);
+ We.buffers.depth.getReversed() ? (be.copy(y.projectionMatrix), l_(be), h_(be), Xe.setValue(H, "projectionMatrix", be)) : Xe.setValue(H, "projectionMatrix", y.projectionMatrix), Xe.setValue(H, "viewMatrix", y.matrixWorldInverse);
const cn = Xe.map.cameraPosition;
cn !== void 0 && cn.setValue(H, et.setFromMatrixPosition(y.matrixWorld)), gt.logarithmicDepthBuffer && Xe.setValue(
H,
@@ -24076,7 +24076,7 @@ class sg {
const Ae = T !== null ? ze.get(T).__webglFramebuffer : null;
We.bindFramebuffer(H.FRAMEBUFFER, Ae);
const ye = H.fenceSync(H.SYNC_GPU_COMMANDS_COMPLETE, 0);
- return H.flush(), await l_(H, ye, 4), H.bindBuffer(H.PIXEL_PACK_BUFFER, fe), H.getBufferSubData(H.PIXEL_PACK_BUFFER, 0, z), H.deleteBuffer(fe), H.deleteSync(ye), z;
+ return H.flush(), await c_(H, ye, 4), H.bindBuffer(H.PIXEL_PACK_BUFFER, fe), H.getBufferSubData(H.PIXEL_PACK_BUFFER, 0, z), H.deleteBuffer(fe), H.deleteSync(ye), z;
} else
throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
}, this.copyFramebufferToTexture = function(y, R = null, N = 0) {
@@ -24206,9 +24206,9 @@ Lo.Panel = function(i, e, t) {
};
};
function rg(i, e) {
- if (e === Ly)
+ if (e === Dy)
return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."), i;
- if (e === Hd || e === B0) {
+ if (e === Hd || e === M0) {
let t = i.getIndex();
if (t === null) {
const a = [], o = i.getAttribute("position");
@@ -24240,15 +24240,17 @@ class rp extends pi {
*/
constructor(e) {
super(e), this.dracoLoader = null, this.ktx2Loader = null, this.meshoptDecoder = null, this.pluginCallbacks = [], this.register(function(t) {
+ return new N1(t);
+ }), this.register(function(t) {
return new D1(t);
}), this.register(function(t) {
- return new L1(t);
+ return new z1(t);
}), this.register(function(t) {
return new V1(t);
}), this.register(function(t) {
return new W1(t);
}), this.register(function(t) {
- return new q1(t);
+ return new P1(t);
}), this.register(function(t) {
return new k1(t);
}), this.register(function(t) {
@@ -24256,23 +24258,21 @@ class rp extends pi {
}), this.register(function(t) {
return new O1(t);
}), this.register(function(t) {
- return new Q1(t);
+ return new F1(t);
}), this.register(function(t) {
- return new N1(t);
+ return new Q1(t);
}), this.register(function(t) {
- return new G1(t);
+ return new L1(t);
}), this.register(function(t) {
- return new P1(t);
+ return new H1(t);
}), this.register(function(t) {
- return new z1(t);
+ return new G1(t);
}), this.register(function(t) {
- return new H1(t);
+ return new T1(t);
}), this.register(function(t) {
- return new R1(t);
+ return new q1(t);
}), this.register(function(t) {
return new K1(t);
- }), this.register(function(t) {
- return new j1(t);
});
}
/**
@@ -24372,9 +24372,9 @@ class rp extends pi {
if (typeof e == "string")
r = JSON.parse(e);
else if (e instanceof ArrayBuffer)
- if (c.decode(new Uint8Array(e, 0, 4)) === ox) {
+ if (c.decode(new Uint8Array(e, 0, 4)) === ax) {
try {
- a[At.KHR_BINARY_GLTF] = new X1(e);
+ a[At.KHR_BINARY_GLTF] = new j1(e);
} catch (u) {
s && s(u);
return;
@@ -24388,7 +24388,7 @@ class rp extends pi {
s && s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));
return;
}
- const l = new cM(r, {
+ const l = new oM(r, {
path: t || this.resourcePath || "",
crossOrigin: this.crossOrigin,
requestHeader: this.requestHeader,
@@ -24406,16 +24406,16 @@ class rp extends pi {
const u = r.extensionsUsed[h], d = r.extensionsRequired || [];
switch (u) {
case At.KHR_MATERIALS_UNLIT:
- a[u] = new F1();
+ a[u] = new R1();
break;
case At.KHR_DRACO_MESH_COMPRESSION:
- a[u] = new Y1(r, this.dracoLoader);
+ a[u] = new X1(r, this.dracoLoader);
break;
case At.KHR_TEXTURE_TRANSFORM:
- a[u] = new J1();
+ a[u] = new Y1();
break;
case At.KHR_MESH_QUANTIZATION:
- a[u] = new Z1();
+ a[u] = new J1();
break;
default:
d.indexOf(u) >= 0 && o[u] === void 0 && console.warn('THREE.GLTFLoader: Unknown extension "' + u + '".');
@@ -24438,7 +24438,7 @@ class rp extends pi {
});
}
}
-function T1() {
+function B1() {
let i = {};
return {
get: function(e) {
@@ -24479,7 +24479,7 @@ const At = {
EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression",
EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing"
};
-class R1 {
+class T1 {
constructor(e) {
this.parser = e, this.name = At.KHR_LIGHTS_PUNCTUAL, this.cache = { refs: {}, uses: {} };
}
@@ -24507,7 +24507,7 @@ class R1 {
l = new Zl(h), l.distance = u;
break;
case "spot":
- l = new Z0(h), l.distance = u, c.spot = c.spot || {}, c.spot.innerConeAngle = c.spot.innerConeAngle !== void 0 ? c.spot.innerConeAngle : 0, c.spot.outerConeAngle = c.spot.outerConeAngle !== void 0 ? c.spot.outerConeAngle : Math.PI / 4, l.angle = c.spot.outerConeAngle, l.penumbra = 1 - c.spot.innerConeAngle / c.spot.outerConeAngle, l.target.position.set(0, 0, -1), l.add(l.target);
+ l = new J0(h), l.distance = u, c.spot = c.spot || {}, c.spot.innerConeAngle = c.spot.innerConeAngle !== void 0 ? c.spot.innerConeAngle : 0, c.spot.outerConeAngle = c.spot.outerConeAngle !== void 0 ? c.spot.outerConeAngle : Math.PI / 4, l.angle = c.spot.outerConeAngle, l.penumbra = 1 - c.spot.innerConeAngle / c.spot.outerConeAngle, l.target.position.set(0, 0, -1), l.add(l.target);
break;
default:
throw new Error("THREE.GLTFLoader: Unexpected light type: " + c.type);
@@ -24525,7 +24525,7 @@ class R1 {
});
}
}
-class F1 {
+class R1 {
constructor() {
this.name = At.KHR_MATERIALS_UNLIT;
}
@@ -24546,7 +24546,7 @@ class F1 {
return Promise.all(s);
}
}
-class N1 {
+class F1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_EMISSIVE_STRENGTH;
}
@@ -24558,7 +24558,7 @@ class N1 {
return r !== void 0 && (t.emissiveIntensity = r), Promise.resolve();
}
}
-class D1 {
+class N1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_CLEARCOAT;
}
@@ -24578,7 +24578,7 @@ class D1 {
return Promise.all(r);
}
}
-class L1 {
+class D1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_DISPERSION;
}
@@ -24594,7 +24594,7 @@ class L1 {
return t.dispersion = r.dispersion !== void 0 ? r.dispersion : 0, Promise.resolve();
}
}
-class P1 {
+class L1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_IRIDESCENCE;
}
@@ -24610,7 +24610,7 @@ class P1 {
return a.iridescenceFactor !== void 0 && (t.iridescence = a.iridescenceFactor), a.iridescenceTexture !== void 0 && r.push(n.assignTexture(t, "iridescenceMap", a.iridescenceTexture)), a.iridescenceIor !== void 0 && (t.iridescenceIOR = a.iridescenceIor), t.iridescenceThicknessRange === void 0 && (t.iridescenceThicknessRange = [100, 400]), a.iridescenceThicknessMinimum !== void 0 && (t.iridescenceThicknessRange[0] = a.iridescenceThicknessMinimum), a.iridescenceThicknessMaximum !== void 0 && (t.iridescenceThicknessRange[1] = a.iridescenceThicknessMaximum), a.iridescenceThicknessTexture !== void 0 && r.push(n.assignTexture(t, "iridescenceThicknessMap", a.iridescenceThicknessTexture)), Promise.all(r);
}
}
-class k1 {
+class P1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_SHEEN;
}
@@ -24632,7 +24632,7 @@ class k1 {
return a.sheenRoughnessFactor !== void 0 && (t.sheenRoughness = a.sheenRoughnessFactor), a.sheenColorTexture !== void 0 && r.push(n.assignTexture(t, "sheenColorMap", a.sheenColorTexture, _t)), a.sheenRoughnessTexture !== void 0 && r.push(n.assignTexture(t, "sheenRoughnessMap", a.sheenRoughnessTexture)), Promise.all(r);
}
}
-class U1 {
+class k1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_TRANSMISSION;
}
@@ -24648,7 +24648,7 @@ class U1 {
return a.transmissionFactor !== void 0 && (t.transmission = a.transmissionFactor), a.transmissionTexture !== void 0 && r.push(n.assignTexture(t, "transmissionMap", a.transmissionTexture)), Promise.all(r);
}
}
-class O1 {
+class U1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_VOLUME;
}
@@ -24666,7 +24666,7 @@ class O1 {
return t.attenuationColor = new Le().setRGB(o[0], o[1], o[2], An), Promise.all(r);
}
}
-class Q1 {
+class O1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_IOR;
}
@@ -24682,7 +24682,7 @@ class Q1 {
return t.ior = r.ior !== void 0 ? r.ior : 1.5, Promise.resolve();
}
}
-class G1 {
+class Q1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_SPECULAR;
}
@@ -24700,7 +24700,7 @@ class G1 {
return t.specularColor = new Le().setRGB(o[0], o[1], o[2], An), a.specularColorTexture !== void 0 && r.push(n.assignTexture(t, "specularColorMap", a.specularColorTexture, _t)), Promise.all(r);
}
}
-class H1 {
+class G1 {
constructor(e) {
this.parser = e, this.name = At.EXT_MATERIALS_BUMP;
}
@@ -24716,7 +24716,7 @@ class H1 {
return t.bumpScale = a.bumpFactor !== void 0 ? a.bumpFactor : 1, a.bumpTexture !== void 0 && r.push(n.assignTexture(t, "bumpMap", a.bumpTexture)), Promise.all(r);
}
}
-class z1 {
+class H1 {
constructor(e) {
this.parser = e, this.name = At.KHR_MATERIALS_ANISOTROPY;
}
@@ -24732,7 +24732,7 @@ class z1 {
return a.anisotropyStrength !== void 0 && (t.anisotropy = a.anisotropyStrength), a.anisotropyRotation !== void 0 && (t.anisotropyRotation = a.anisotropyRotation), a.anisotropyTexture !== void 0 && r.push(n.assignTexture(t, "anisotropyMap", a.anisotropyTexture)), Promise.all(r);
}
}
-class V1 {
+class z1 {
constructor(e) {
this.parser = e, this.name = At.KHR_TEXTURE_BASISU;
}
@@ -24749,7 +24749,7 @@ class V1 {
return t.loadTextureImage(e, r.source, a);
}
}
-class W1 {
+class V1 {
constructor(e) {
this.parser = e, this.name = At.EXT_TEXTURE_WEBP;
}
@@ -24766,7 +24766,7 @@ class W1 {
return n.loadTextureImage(e, a.source, c);
}
}
-class q1 {
+class W1 {
constructor(e) {
this.parser = e, this.name = At.EXT_TEXTURE_AVIF;
}
@@ -24783,7 +24783,7 @@ class q1 {
return n.loadTextureImage(e, a.source, c);
}
}
-class K1 {
+class q1 {
constructor(e) {
this.name = At.EXT_MESHOPT_COMPRESSION, this.parser = e;
}
@@ -24809,7 +24809,7 @@ class K1 {
return null;
}
}
-class j1 {
+class K1 {
constructor(e) {
this.name = At.EXT_MESH_GPU_INSTANCING, this.parser = e;
}
@@ -24827,7 +24827,7 @@ class j1 {
return o.length < 1 ? null : (o.push(this.parser.createNodeMesh(e)), Promise.all(o).then((l) => {
const h = l.pop(), u = h.isGroup ? h.children : [h], d = l[0].count, f = [];
for (const p of u) {
- const m = new Ne(), g = new G(), A = new Jt(), _ = new G(1, 1, 1), x = new G0(p.geometry, p.material, d);
+ const m = new Ne(), g = new G(), A = new Jt(), _ = new G(1, 1, 1), x = new Q0(p.geometry, p.material, d);
for (let E = 0; E < d; E++)
c.TRANSLATION && g.fromBufferAttribute(c.TRANSLATION, E), c.ROTATION && A.fromBufferAttribute(c.ROTATION, E), c.SCALE && _.fromBufferAttribute(c.SCALE, E), x.setMatrixAt(E, m.compose(g, A, _));
for (const E in c)
@@ -24841,8 +24841,8 @@ class j1 {
}));
}
}
-const ox = "glTF", fo = 12, ag = { JSON: 1313821514, BIN: 5130562 };
-class X1 {
+const ax = "glTF", fo = 12, ag = { JSON: 1313821514, BIN: 5130562 };
+class j1 {
constructor(e) {
this.name = At.KHR_BINARY_GLTF, this.content = null, this.body = null;
const t = new DataView(e, 0, fo), n = new TextDecoder();
@@ -24850,7 +24850,7 @@ class X1 {
magic: n.decode(new Uint8Array(e.slice(0, 4))),
version: t.getUint32(4, !0),
length: t.getUint32(8, !0)
- }, this.header.magic !== ox)
+ }, this.header.magic !== ax)
throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");
if (this.header.version < 2)
throw new Error("THREE.GLTFLoader: Legacy binary file detected.");
@@ -24873,7 +24873,7 @@ class X1 {
throw new Error("THREE.GLTFLoader: JSON content not found.");
}
}
-class Y1 {
+class X1 {
constructor(e, t) {
if (!t)
throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");
@@ -24905,7 +24905,7 @@ class Y1 {
});
}
}
-class J1 {
+class Y1 {
constructor() {
this.name = At.KHR_TEXTURE_TRANSFORM;
}
@@ -24913,12 +24913,12 @@ class J1 {
return (t.texCoord === void 0 || t.texCoord === e.channel) && t.offset === void 0 && t.rotation === void 0 && t.scale === void 0 || (e = e.clone(), t.texCoord !== void 0 && (e.channel = t.texCoord), t.offset !== void 0 && e.offset.fromArray(t.offset), t.rotation !== void 0 && (e.rotation = t.rotation), t.scale !== void 0 && e.repeat.fromArray(t.scale), e.needsUpdate = !0), e;
}
}
-class Z1 {
+class J1 {
constructor() {
this.name = At.KHR_MESH_QUANTIZATION;
}
}
-class cx extends fc {
+class ox extends fc {
constructor(e, t, n, s) {
super(e, t, n, s);
}
@@ -24937,11 +24937,11 @@ class cx extends fc {
return r;
}
}
-const $1 = new Jt();
-class eM extends cx {
+const Z1 = new Jt();
+class $1 extends ox {
interpolate_(e, t, n, s) {
const r = super.interpolate_(e, t, n, s);
- return $1.fromArray(r).normalize().toArray(r), r;
+ return Z1.fromArray(r).normalize().toArray(r), r;
}
}
const ai = {
@@ -24962,7 +24962,7 @@ const ai = {
}, og = {
9728: qn,
9729: Xt,
- 9984: E0,
+ 9984: b0,
9985: Sl,
9986: _o,
9987: ui
@@ -24994,7 +24994,7 @@ const ai = {
translation: "position",
rotation: "quaternion",
weights: "morphTargetInfluences"
-}, tM = {
+}, eM = {
CUBICSPLINE: void 0,
// We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
// keyframe track will be initialized with a default interpolation type, then modified.
@@ -25005,7 +25005,7 @@ const ai = {
MASK: "MASK",
BLEND: "BLEND"
};
-function nM(i) {
+function tM(i) {
return i.DefaultMaterial === void 0 && (i.DefaultMaterial = new $o({
color: 16777215,
emissive: 0,
@@ -25023,7 +25023,7 @@ function cr(i, e, t) {
function ns(i, e) {
e.extras !== void 0 && (typeof e.extras == "object" ? Object.assign(i.userData, e.extras) : console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + e.extras));
}
-function iM(i, e, t) {
+function nM(i, e, t) {
let n = !1, s = !1, r = !1;
for (let l = 0, h = e.length; l < h; l++) {
const u = e[l];
@@ -25055,7 +25055,7 @@ function iM(i, e, t) {
return n && (i.morphAttributes.position = h), s && (i.morphAttributes.normal = u), r && (i.morphAttributes.color = d), i.morphTargetsRelative = !0, i;
});
}
-function sM(i, e) {
+function iM(i, e) {
if (i.updateMorphTargets(), e.weights !== void 0)
for (let t = 0, n = e.weights.length; t < n; t++)
i.morphTargetInfluences[t] = e.weights[t];
@@ -25069,7 +25069,7 @@ function sM(i, e) {
console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.");
}
}
-function rM(i) {
+function sM(i) {
let e;
const t = i.extensions && i.extensions[At.KHR_DRACO_MESH_COMPRESSION];
if (t ? e = "draco:" + t.bufferView + ":" + t.indices + ":" + Cu(t.attributes) : e = i.indices + ":" + Cu(i.attributes) + ":" + i.mode, i.targets !== void 0)
@@ -25098,13 +25098,13 @@ function Zd(i) {
throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.");
}
}
-function aM(i) {
+function rM(i) {
return i.search(/\.jpe?g($|\?)/i) > 0 || i.search(/^data\:image\/jpeg/) === 0 ? "image/jpeg" : i.search(/\.webp($|\?)/i) > 0 || i.search(/^data\:image\/webp/) === 0 ? "image/webp" : i.search(/\.ktx2($|\?)/i) > 0 || i.search(/^data\:image\/ktx2/) === 0 ? "image/ktx2" : "image/png";
}
-const oM = new Ne();
-class cM {
+const aM = new Ne();
+class oM {
constructor(e = {}, t = {}) {
- this.json = e, this.extensions = {}, this.plugins = {}, this.options = t, this.cache = new T1(), this.associations = /* @__PURE__ */ new Map(), this.primitiveCache = {}, this.nodeCache = {}, this.meshCache = { refs: {}, uses: {} }, this.cameraCache = { refs: {}, uses: {} }, this.lightCache = { refs: {}, uses: {} }, this.sourceCache = {}, this.textureCache = {}, this.nodeNamesUsed = {};
+ this.json = e, this.extensions = {}, this.plugins = {}, this.options = t, this.cache = new B1(), this.associations = /* @__PURE__ */ new Map(), this.primitiveCache = {}, this.nodeCache = {}, this.meshCache = { refs: {}, uses: {} }, this.cameraCache = { refs: {}, uses: {} }, this.lightCache = { refs: {}, uses: {} }, this.sourceCache = {}, this.textureCache = {}, this.nodeNamesUsed = {};
let n = !1, s = -1, r = !1, a = -1;
if (typeof navigator < "u") {
const o = navigator.userAgent;
@@ -25112,7 +25112,7 @@ class cM {
const c = o.match(/Version\/(\d+)/);
s = n && c ? parseInt(c[1], 10) : -1, r = o.indexOf("Firefox") > -1, a = r ? o.match(/Firefox\/([0-9]+)\./)[1] : -1;
}
- typeof createImageBitmap > "u" || n && s < 17 || r && a < 98 ? this.textureLoader = new J0(this.options.manager) : this.textureLoader = new Rw(this.options.manager), this.textureLoader.setCrossOrigin(this.options.crossOrigin), this.textureLoader.setRequestHeader(this.options.requestHeader), this.fileLoader = new As(this.options.manager), this.fileLoader.setResponseType("arraybuffer"), this.options.crossOrigin === "use-credentials" && this.fileLoader.setWithCredentials(!0);
+ typeof createImageBitmap > "u" || n && s < 17 || r && a < 98 ? this.textureLoader = new Y0(this.options.manager) : this.textureLoader = new Tw(this.options.manager), this.textureLoader.setCrossOrigin(this.options.crossOrigin), this.textureLoader.setRequestHeader(this.options.requestHeader), this.fileLoader = new As(this.options.manager), this.fileLoader.setResponseType("arraybuffer"), this.options.crossOrigin === "use-credentials" && this.fileLoader.setWithCredentials(!0);
}
setExtensions(e) {
this.extensions = e;
@@ -25362,7 +25362,7 @@ class cM {
if (f && f !== u) {
const A = Math.floor(d / f), _ = "InterleavedBuffer:" + s.bufferView + ":" + s.componentType + ":" + A + ":" + s.count;
let x = t.cache.get(_);
- x || (m = new l(o, A * f, s.count * f / h), x = new U_(m, f / h), t.cache.add(_, x)), g = new Xf(x, c, d % f / h, p);
+ x || (m = new l(o, A * f, s.count * f / h), x = new k_(m, f / h), t.cache.add(_, x)), g = new Xf(x, c, d % f / h, p);
} else
o === null ? m = new l(s.count * c) : m = new l(o, d, s.count * c), g = new Bn(m, c, p);
if (s.sparse !== void 0) {
@@ -25429,7 +25429,7 @@ class cM {
}), t.load(Cr.resolveURL(u, r.path), p, void 0, f);
});
}).then(function(u) {
- return l === !0 && o.revokeObjectURL(c), ns(u, a), u.userData.mimeType = a.mimeType || aM(a.uri), u;
+ return l === !0 && o.revokeObjectURL(c), ns(u, a), u.userData.mimeType = a.mimeType || rM(a.uri), u;
}).catch(function(u) {
throw console.error("THREE.GLTFLoader: Couldn't load texture", c), u;
});
@@ -25563,7 +25563,7 @@ class cM {
}
const a = [];
for (let o = 0, c = e.length; o < c; o++) {
- const l = e[o], h = rM(l), u = s[h];
+ const l = e[o], h = sM(l), u = s[h];
if (u)
a.push(u.promise);
else {
@@ -25583,7 +25583,7 @@ class cM {
loadMesh(e) {
const t = this, n = this.json, s = this.extensions, r = n.meshes[e], a = r.primitives, o = [];
for (let c = 0, l = a.length; c < l; c++) {
- const h = a[c].material === void 0 ? nM(this.cache) : this.getDependency("material", a[c].material);
+ const h = a[c].material === void 0 ? tM(this.cache) : this.getDependency("material", a[c].material);
o.push(h);
}
return o.push(t.loadGeometries(a)), Promise.all(o).then(function(c) {
@@ -25593,18 +25593,18 @@ class cM {
let A;
const _ = l[f];
if (g.mode === ai.TRIANGLES || g.mode === ai.TRIANGLE_STRIP || g.mode === ai.TRIANGLE_FAN || g.mode === void 0)
- A = r.isSkinnedMesh === !0 ? new Q0(m, _) : new Zt(m, _), A.isSkinnedMesh === !0 && A.normalizeSkinWeights(), g.mode === ai.TRIANGLE_STRIP ? A.geometry = rg(A.geometry, B0) : g.mode === ai.TRIANGLE_FAN && (A.geometry = rg(A.geometry, Hd));
+ A = r.isSkinnedMesh === !0 ? new O0(m, _) : new Zt(m, _), A.isSkinnedMesh === !0 && A.normalizeSkinWeights(), g.mode === ai.TRIANGLE_STRIP ? A.geometry = rg(A.geometry, M0) : g.mode === ai.TRIANGLE_FAN && (A.geometry = rg(A.geometry, Hd));
else if (g.mode === ai.LINES)
A = new bh(m, _);
else if (g.mode === ai.LINE_STRIP)
A = new xh(m, _);
else if (g.mode === ai.LINE_LOOP)
- A = new V_(m, _);
+ A = new z_(m, _);
else if (g.mode === ai.POINTS)
- A = new W_(m, _);
+ A = new V_(m, _);
else
throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + g.mode);
- Object.keys(A.geometry.morphAttributes).length > 0 && sM(A, r), A.name = t.createUniqueName(r.name || "mesh_" + e), ns(A, r), g.extensions && cr(s, A, g), t.assignFinalMaterial(A), u.push(A);
+ Object.keys(A.geometry.morphAttributes).length > 0 && iM(A, r), A.name = t.createUniqueName(r.name || "mesh_" + e), ns(A, r), g.extensions && cr(s, A, g), t.assignFinalMaterial(A), u.push(A);
}
for (let f = 0, p = u.length; f < p; f++)
t.associations.set(u[f], {
@@ -25724,7 +25724,7 @@ class cM {
]).then(function(l) {
const h = l[0], u = l[1], d = l[2];
d !== null && h.traverse(function(f) {
- f.isSkinnedMesh && f.bind(d, oM);
+ f.isSkinnedMesh && f.bind(d, aM);
});
for (let f = 0, p = u.length; f < p; f++)
h.add(u[f]);
@@ -25808,7 +25808,7 @@ class cM {
n.itemSize === 1 ? l = Nr : l = Dr;
break;
}
- const h = s.interpolation !== void 0 ? tM[s.interpolation] : jo, u = this._getArrayFromAccessor(n);
+ const h = s.interpolation !== void 0 ? eM[s.interpolation] : jo, u = this._getArrayFromAccessor(n);
for (let d = 0, f = c.length; d < f; d++) {
const p = new l(
c[d] + "." + Rs[r.path],
@@ -25832,12 +25832,12 @@ class cM {
}
_createCubicSplineTrackInterpolant(e) {
e.createInterpolant = function(n) {
- const s = this instanceof Ks ? eM : cx;
+ const s = this instanceof Ks ? $1 : ox;
return new s(this.times, this.values, this.getValueSize() / 3, n);
}, e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = !0;
}
}
-function lM(i, e, t) {
+function cM(i, e, t) {
const n = e.attributes, s = new zi();
if (n.POSITION !== void 0) {
const o = t.json.accessors[n.POSITION], c = o.min, l = o.max;
@@ -25895,11 +25895,11 @@ function lg(i, e, t) {
});
s.push(a);
}
- return rt.workingColorSpace !== An && "COLOR_0" in n && console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${rt.workingColorSpace}" not supported.`), ns(i, e), lM(i, e, t), Promise.all(s).then(function() {
- return e.targets !== void 0 ? iM(i, e.targets, t) : i;
+ return rt.workingColorSpace !== An && "COLOR_0" in n && console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${rt.workingColorSpace}" not supported.`), ns(i, e), cM(i, e, t), Promise.all(s).then(function() {
+ return e.targets !== void 0 ? nM(i, e.targets, t) : i;
});
}
-var hM = (function() {
+var lM = (function() {
var i = "b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb", e = "b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdxekkcbhlaHceGmdkdnakTmbavcjdfazfhiavazfpbdbhYcbhXinaiavcj;cbfaXfgopblbgLcep9TaLpxeeeeeeeeeeeeeeeegQp9op9Hp9rgLaoakfpblbg8Acep9Ta8AaQp9op9Hp9rg8ApmbzeHdOiAlCvXoQrLgEaoamfpblbg3cep9Ta3aQp9op9Hp9rg3aoaxfpblbg5cep9Ta5aQp9op9Hp9rg5pmbzeHdOiAlCvXoQrLg8EpmbezHdiOAlvCXorQLgQaQpmbedibedibedibediaYp9UgYp9AdbbaiadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaEa8EpmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwKDYq8AkEx3m5P8Es8FgLa3a5pmwKDYq8AkEx3m5P8Es8Fg8ApmbezHdiOAlvCXorQLgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfhiaXczfgXak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb", t = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]), n = new Uint8Array([32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115]);
if (typeof WebAssembly != "object")
return {
@@ -25995,7 +25995,7 @@ var hM = (function() {
}
};
})();
-const hg = { type: "change" }, ap = { type: "start" }, lx = { type: "end" }, sl = new dc(), ug = new Us(), uM = Math.cos(70 * Cn.DEG2RAD), ln = new G(), Kn = 2 * Math.PI, Ft = {
+const hg = { type: "change" }, ap = { type: "start" }, cx = { type: "end" }, sl = new dc(), ug = new Us(), hM = Math.cos(70 * Cn.DEG2RAD), ln = new G(), Kn = 2 * Math.PI, Ft = {
NONE: -1,
ROTATE: 0,
DOLLY: 1,
@@ -26005,7 +26005,7 @@ const hg = { type: "change" }, ap = { type: "start" }, lx = { type: "end" }, sl
TOUCH_DOLLY_PAN: 5,
TOUCH_DOLLY_ROTATE: 6
}, Iu = 1e-6;
-class dM extends Kw {
+class uM extends qw {
/**
* Constructs a new controls instance.
*
@@ -26013,7 +26013,7 @@ class dM extends Kw {
* @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
*/
constructor(e, t = null) {
- super(e, t), this.state = Ft.NONE, this.target = new G(), this.cursor = new G(), this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.minTargetRadius = 0, this.maxTargetRadius = 1 / 0, this.minPolarAngle = 0, this.maxPolarAngle = Math.PI, this.minAzimuthAngle = -1 / 0, this.maxAzimuthAngle = 1 / 0, this.enableDamping = !1, this.dampingFactor = 0.05, this.enableZoom = !0, this.zoomSpeed = 1, this.enableRotate = !0, this.rotateSpeed = 1, this.keyRotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !0, this.keyPanSpeed = 7, this.zoomToCursor = !1, this.autoRotate = !1, this.autoRotateSpeed = 2, this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }, this.mouseButtons = { LEFT: va.ROTATE, MIDDLE: va.DOLLY, RIGHT: va.PAN }, this.touches = { ONE: ga.ROTATE, TWO: ga.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new G(), this._lastQuaternion = new Jt(), this._lastTargetPosition = new G(), this._quat = new Jt().setFromUnitVectors(e.up, new G(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new FA(), this._sphericalDelta = new FA(), this._scale = 1, this._panOffset = new G(), this._rotateStart = new Ze(), this._rotateEnd = new Ze(), this._rotateDelta = new Ze(), this._panStart = new Ze(), this._panEnd = new Ze(), this._panDelta = new Ze(), this._dollyStart = new Ze(), this._dollyEnd = new Ze(), this._dollyDelta = new Ze(), this._dollyDirection = new G(), this._mouse = new Ze(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = pM.bind(this), this._onPointerDown = fM.bind(this), this._onPointerUp = AM.bind(this), this._onContextMenu = _M.bind(this), this._onMouseWheel = xM.bind(this), this._onKeyDown = bM.bind(this), this._onTouchStart = EM.bind(this), this._onTouchMove = yM.bind(this), this._onMouseDown = gM.bind(this), this._onMouseMove = mM.bind(this), this._interceptControlDown = wM.bind(this), this._interceptControlUp = vM.bind(this), this.domElement !== null && this.connect(this.domElement), this.update();
+ super(e, t), this.state = Ft.NONE, this.target = new G(), this.cursor = new G(), this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.minTargetRadius = 0, this.maxTargetRadius = 1 / 0, this.minPolarAngle = 0, this.maxPolarAngle = Math.PI, this.minAzimuthAngle = -1 / 0, this.maxAzimuthAngle = 1 / 0, this.enableDamping = !1, this.dampingFactor = 0.05, this.enableZoom = !0, this.zoomSpeed = 1, this.enableRotate = !0, this.rotateSpeed = 1, this.keyRotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !0, this.keyPanSpeed = 7, this.zoomToCursor = !1, this.autoRotate = !1, this.autoRotateSpeed = 2, this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }, this.mouseButtons = { LEFT: va.ROTATE, MIDDLE: va.DOLLY, RIGHT: va.PAN }, this.touches = { ONE: ga.ROTATE, TWO: ga.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new G(), this._lastQuaternion = new Jt(), this._lastTargetPosition = new G(), this._quat = new Jt().setFromUnitVectors(e.up, new G(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new FA(), this._sphericalDelta = new FA(), this._scale = 1, this._panOffset = new G(), this._rotateStart = new Ze(), this._rotateEnd = new Ze(), this._rotateDelta = new Ze(), this._panStart = new Ze(), this._panEnd = new Ze(), this._panDelta = new Ze(), this._dollyStart = new Ze(), this._dollyEnd = new Ze(), this._dollyDelta = new Ze(), this._dollyDirection = new G(), this._mouse = new Ze(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = fM.bind(this), this._onPointerDown = dM.bind(this), this._onPointerUp = pM.bind(this), this._onContextMenu = yM.bind(this), this._onMouseWheel = mM.bind(this), this._onKeyDown = xM.bind(this), this._onTouchStart = bM.bind(this), this._onTouchMove = EM.bind(this), this._onMouseDown = AM.bind(this), this._onMouseMove = gM.bind(this), this._interceptControlDown = _M.bind(this), this._interceptControlUp = wM.bind(this), this.domElement !== null && this.connect(this.domElement), this.update();
}
connect(e) {
super.connect(e), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerUp), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.getRootNode().addEventListener("keydown", this._interceptControlDown, { passive: !0, capture: !0 }), this.domElement.style.touchAction = "none";
@@ -26104,7 +26104,7 @@ class dM extends Kw {
l.unproject(this.object), this.object.position.sub(l).add(o), this.object.updateMatrixWorld(), a = ln.length();
} else
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."), this.zoomToCursor = !1;
- a !== null && (this.screenSpacePanning ? this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position) : (sl.origin.copy(this.object.position), sl.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(sl.direction)) < uM ? this.object.lookAt(this.target) : (ug.setFromNormalAndCoplanarPoint(this.object.up, this.target), sl.intersectPlane(ug, this.target))));
+ a !== null && (this.screenSpacePanning ? this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position) : (sl.origin.copy(this.object.position), sl.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(sl.direction)) < hM ? this.object.lookAt(this.target) : (ug.setFromNormalAndCoplanarPoint(this.object.up, this.target), sl.intersectPlane(ug, this.target))));
} else if (this.object.isOrthographicCamera) {
const a = this.object.zoom;
this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), a !== this.object.zoom && (this.object.updateProjectionMatrix(), r = !0);
@@ -26301,16 +26301,16 @@ class dM extends Kw {
return e.ctrlKey && !this._controlActive && (n.deltaY *= 10), n;
}
}
-function fM(i) {
+function dM(i) {
this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(i.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(i) && (this._addPointer(i), i.pointerType === "touch" ? this._onTouchStart(i) : this._onMouseDown(i)));
}
-function pM(i) {
+function fM(i) {
this.enabled !== !1 && (i.pointerType === "touch" ? this._onTouchMove(i) : this._onMouseMove(i));
}
-function AM(i) {
+function pM(i) {
switch (this._removePointer(i), this._pointers.length) {
case 0:
- this.domElement.releasePointerCapture(i.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(lx), this.state = Ft.NONE;
+ this.domElement.releasePointerCapture(i.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(cx), this.state = Ft.NONE;
break;
case 1:
const e = this._pointers[0], t = this._pointerPositions[e];
@@ -26318,7 +26318,7 @@ function AM(i) {
break;
}
}
-function gM(i) {
+function AM(i) {
let e;
switch (i.button) {
case 0:
@@ -26361,7 +26361,7 @@ function gM(i) {
}
this.state !== Ft.NONE && this.dispatchEvent(ap);
}
-function mM(i) {
+function gM(i) {
switch (this.state) {
case Ft.ROTATE:
if (this.enableRotate === !1) return;
@@ -26377,13 +26377,13 @@ function mM(i) {
break;
}
}
-function xM(i) {
- this.enabled === !1 || this.enableZoom === !1 || this.state !== Ft.NONE || (i.preventDefault(), this.dispatchEvent(ap), this._handleMouseWheel(this._customWheelEvent(i)), this.dispatchEvent(lx));
+function mM(i) {
+ this.enabled === !1 || this.enableZoom === !1 || this.state !== Ft.NONE || (i.preventDefault(), this.dispatchEvent(ap), this._handleMouseWheel(this._customWheelEvent(i)), this.dispatchEvent(cx));
}
-function bM(i) {
+function xM(i) {
this.enabled !== !1 && this._handleKeyDown(i);
}
-function EM(i) {
+function bM(i) {
switch (this._trackPointer(i), this._pointers.length) {
case 1:
switch (this.touches.ONE) {
@@ -26418,7 +26418,7 @@ function EM(i) {
}
this.state !== Ft.NONE && this.dispatchEvent(ap);
}
-function yM(i) {
+function EM(i) {
switch (this._trackPointer(i), this.state) {
case Ft.TOUCH_ROTATE:
if (this.enableRotate === !1) return;
@@ -26440,16 +26440,16 @@ function yM(i) {
this.state = Ft.NONE;
}
}
-function _M(i) {
+function yM(i) {
this.enabled !== !1 && i.preventDefault();
}
-function wM(i) {
+function _M(i) {
i.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
-function vM(i) {
+function wM(i) {
i.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
-class CM extends Vd {
+class vM extends Vd {
constructor() {
super();
const e = new qa();
@@ -26458,7 +26458,7 @@ class CM extends Vd {
s.position.set(0.418, 16.199, 0.3), this.add(s);
const r = new Zt(e, t);
r.position.set(-0.757, 13.219, 0.717), r.scale.set(31.713, 28.305, 28.591), this.add(r);
- const a = new G0(e, n, 6), o = new Tt();
+ const a = new Q0(e, n, 6), o = new Tt();
o.position.set(-10.906, 2.009, 1.846), o.rotation.set(0, -0.195, 0), o.scale.set(2.328, 7.905, 4.651), o.updateMatrix(), a.setMatrixAt(0, o.matrix), o.position.set(-5.607, -0.754, -0.758), o.rotation.set(0, 0.994, 0), o.scale.set(1.97, 1.534, 3.955), o.updateMatrix(), a.setMatrixAt(1, o.matrix), o.position.set(6.167, 0.857, 7.803), o.rotation.set(0, 0.561, 0), o.scale.set(3.927, 6.285, 3.687), o.updateMatrix(), a.setMatrixAt(2, o.matrix), o.position.set(-2.017, 0.018, 6.124), o.rotation.set(0, 0.333, 0), o.scale.set(2.002, 4.566, 2.064), o.updateMatrix(), a.setMatrixAt(3, o.matrix), o.position.set(2.291, -0.756, -2.621), o.rotation.set(0, -0.286, 0), o.scale.set(1.546, 1.552, 1.496), o.updateMatrix(), a.setMatrixAt(4, o.matrix), o.position.set(-2.193, -0.369, -5.547), o.rotation.set(0, 0.516, 0), o.scale.set(3.875, 3.487, 2.986), o.updateMatrix(), a.setMatrixAt(5, o.matrix), this.add(a);
const c = new Zt(e, oa(50));
c.position.set(-16.116, 14.37, 8.208), c.scale.set(0.1, 2.428, 2.739), this.add(c);
@@ -26490,7 +26490,7 @@ function oa(i) {
const e = new Os();
return e.color.setScalar(i), e;
}
-function IM(i) {
+function CM(i) {
if (!(typeof window > "u")) {
var e = document.createElement("style");
return e.setAttribute("type", "text/css"), e.innerHTML = i, document.head.appendChild(e), i;
@@ -26616,7 +26616,7 @@ var dg = Array.prototype.forEach, po = Array.prototype.slice, ue = {
isFunction: function(e) {
return e instanceof Function;
}
-}, SM = [
+}, IM = [
{
litmus: ue.isString,
conversions: {
@@ -26796,7 +26796,7 @@ var dg = Array.prototype.forEach, po = Array.prototype.slice, ue = {
], Ao = void 0, rl = void 0, $d = function() {
rl = !1;
var e = arguments.length > 1 ? ue.toArray(arguments) : arguments[0];
- return ue.each(SM, function(t) {
+ return ue.each(IM, function(t) {
if (t.litmus(e))
return ue.each(t.conversions, function(n, s) {
if (Ao = n.read(e), rl === !1 && Ao !== !1)
@@ -26838,7 +26838,7 @@ var dg = Array.prototype.forEach, po = Array.prototype.slice, ue = {
hex_with_component: function(e, t, n) {
return n << (fg = t * 8) | e & ~(255 << fg);
}
-}, MM = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(i) {
+}, SM = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(i) {
return typeof i;
} : function(i) {
return i && typeof Symbol == "function" && i.constructor === Symbol && i !== Symbol.prototype ? "symbol" : typeof i;
@@ -26998,21 +26998,21 @@ var Gr = (function() {
return this.initialValue !== this.getValue();
}
}]), i;
-})(), BM = {
+})(), MM = {
HTMLEvents: ["change"],
MouseEvents: ["click", "mousemove", "mousedown", "mouseup", "mouseover"],
KeyboardEvents: ["keydown"]
-}, hx = {};
-ue.each(BM, function(i, e) {
+}, lx = {};
+ue.each(MM, function(i, e) {
ue.each(i, function(t) {
- hx[t] = e;
+ lx[t] = e;
});
});
-var TM = /(\d+(\.\d+)?)px/;
+var BM = /(\d+(\.\d+)?)px/;
function Di(i) {
if (i === "0" || ue.isUndefined(i))
return 0;
- var e = i.match(TM);
+ var e = i.match(BM);
return ue.isNull(e) ? 0 : parseFloat(e[1]);
}
var te = {
@@ -27027,7 +27027,7 @@ var te = {
ue.isUndefined(r) && (r = !0), ue.isUndefined(s) && (s = !0), e.style.position = "absolute", r && (e.style.left = 0, e.style.right = 0), s && (e.style.top = 0, e.style.bottom = 0);
},
fakeEvent: function(e, t, n, s) {
- var r = n || {}, a = hx[t];
+ var r = n || {}, a = lx[t];
if (!a)
throw new Error("Event type " + t + " not supported.");
var o = document.createEvent(a);
@@ -27124,7 +27124,7 @@ var te = {
isActive: function(e) {
return e === document.activeElement && (e.type || e.href);
}
-}, ux = (function(i) {
+}, hx = (function(i) {
Zs(e, i);
function e(t, n) {
Ri(this, e);
@@ -27147,7 +27147,7 @@ var te = {
return this.getValue() === !0 ? (this.__checkbox.setAttribute("checked", "checked"), this.__checkbox.checked = !0, this.__prev = !0) : (this.__checkbox.checked = !1, this.__prev = !1), js(e.prototype.__proto__ || Object.getPrototypeOf(e.prototype), "updateDisplay", this).call(this);
}
}]), e;
-})(Gr), RM = (function(i) {
+})(Gr), TM = (function(i) {
Zs(e, i);
function e(t, n, s) {
Ri(this, e);
@@ -27178,7 +27178,7 @@ var te = {
return te.isActive(this.__select) ? this : (this.__select.value = this.getValue(), js(e.prototype.__proto__ || Object.getPrototypeOf(e.prototype), "updateDisplay", this).call(this));
}
}]), e;
-})(Gr), FM = (function(i) {
+})(Gr), RM = (function(i) {
Zs(e, i);
function e(t, n) {
Ri(this, e);
@@ -27204,7 +27204,7 @@ function pg(i) {
var e = i.toString();
return e.indexOf(".") > -1 ? e.length - e.indexOf(".") - 1 : 0;
}
-var dx = (function(i) {
+var ux = (function(i) {
Zs(e, i);
function e(t, n, s) {
Ri(this, e);
@@ -27234,7 +27234,7 @@ var dx = (function(i) {
}
}]), e;
})(Gr);
-function NM(i, e) {
+function FM(i, e) {
var t = Math.pow(10, e);
return Math.round(i * t) / t;
}
@@ -27272,10 +27272,10 @@ var eh = (function(i) {
return Fi(e, [{
key: "updateDisplay",
value: function() {
- return this.__input.value = this.__truncationSuspended ? this.getValue() : NM(this.getValue(), this.__precision), js(e.prototype.__proto__ || Object.getPrototypeOf(e.prototype), "updateDisplay", this).call(this);
+ return this.__input.value = this.__truncationSuspended ? this.getValue() : FM(this.getValue(), this.__precision), js(e.prototype.__proto__ || Object.getPrototypeOf(e.prototype), "updateDisplay", this).call(this);
}
}]), e;
-})(dx);
+})(ux);
function Ag(i, e, t, n, s) {
return n + (s - n) * ((i - e) / (t - e));
}
@@ -27315,7 +27315,7 @@ var ef = (function(i) {
return this.__foreground.style.width = n * 100 + "%", js(e.prototype.__proto__ || Object.getPrototypeOf(e.prototype), "updateDisplay", this).call(this);
}
}]), e;
-})(dx), fx = (function(i) {
+})(ux), dx = (function(i) {
Zs(e, i);
function e(t, n, s) {
Ri(this, e);
@@ -27388,7 +27388,7 @@ var ef = (function(i) {
position: "absolute",
top: "3px",
right: "3px"
- }), LM(s.__hue_field), ue.extend(s.__input.style, {
+ }), DM(s.__hue_field), ue.extend(s.__input.style, {
outline: "none",
textAlign: "center",
color: "#fff",
@@ -27453,16 +27453,16 @@ var ef = (function(i) {
});
}
}]), e;
-})(Gr), DM = ["-moz-", "-o-", "-webkit-", "-ms-", ""];
+})(Gr), NM = ["-moz-", "-o-", "-webkit-", "-ms-", ""];
function gg(i, e, t, n) {
- i.style.background = "", ue.each(DM, function(s) {
+ i.style.background = "", ue.each(NM, function(s) {
i.style.cssText += "background: " + s + "linear-gradient(" + e + ", " + t + " 0%, " + n + " 100%); ";
});
}
-function LM(i) {
+function DM(i) {
i.style.background = "", i.style.cssText += "background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);", i.style.cssText += "background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", i.style.cssText += "background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", i.style.cssText += "background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", i.style.cssText += "background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);";
}
-var PM = {
+var LM = {
load: function(e, t) {
var n = t || document, s = n.createElement("link");
s.type = "text/css", s.rel = "stylesheet", s.href = e, n.getElementsByTagName("head")[0].appendChild(s);
@@ -27476,7 +27476,7 @@ var PM = {
} catch {
}
}
-}, kM = `<div id="dg-save" class="dg dialogue">
+}, PM = `<div id="dg-save" class="dg dialogue">
Here's the new load parameter for your <code>GUI</code>'s constructor:
@@ -27496,14 +27496,14 @@ var PM = {
</div>
-</div>`, UM = function(e, t) {
+</div>`, kM = function(e, t) {
var n = e[t];
- return ue.isArray(arguments[2]) || ue.isObject(arguments[2]) ? new RM(e, t, arguments[2]) : ue.isNumber(n) ? ue.isNumber(arguments[2]) && ue.isNumber(arguments[3]) ? ue.isNumber(arguments[4]) ? new ef(e, t, arguments[2], arguments[3], arguments[4]) : new ef(e, t, arguments[2], arguments[3]) : ue.isNumber(arguments[4]) ? new eh(e, t, { min: arguments[2], max: arguments[3], step: arguments[4] }) : new eh(e, t, { min: arguments[2], max: arguments[3] }) : ue.isString(n) ? new FM(e, t) : ue.isFunction(n) ? new fx(e, t, "") : ue.isBoolean(n) ? new ux(e, t) : null;
+ return ue.isArray(arguments[2]) || ue.isObject(arguments[2]) ? new TM(e, t, arguments[2]) : ue.isNumber(n) ? ue.isNumber(arguments[2]) && ue.isNumber(arguments[3]) ? ue.isNumber(arguments[4]) ? new ef(e, t, arguments[2], arguments[3], arguments[4]) : new ef(e, t, arguments[2], arguments[3]) : ue.isNumber(arguments[4]) ? new eh(e, t, { min: arguments[2], max: arguments[3], step: arguments[4] }) : new eh(e, t, { min: arguments[2], max: arguments[3] }) : ue.isString(n) ? new RM(e, t) : ue.isFunction(n) ? new dx(e, t, "") : ue.isBoolean(n) ? new hx(e, t) : null;
};
-function OM(i) {
+function UM(i) {
setTimeout(i, 1e3 / 60);
}
-var QM = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || OM, GM = (function() {
+var OM = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || UM, QM = (function() {
function i() {
Ri(this, i), this.backgroundElement = document.createElement("div"), ue.extend(this.backgroundElement.style, {
backgroundColor: "rgba(0,0,0,0.8)",
@@ -27549,16 +27549,16 @@ var QM = window.requestAnimationFrame || window.webkitRequestAnimationFrame || w
this.domElement.style.left = window.innerWidth / 2 - te.getWidth(this.domElement) / 2 + "px", this.domElement.style.top = window.innerHeight / 2 - te.getHeight(this.domElement) / 2 + "px";
}
}]), i;
-})(), HM = IM(`.dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}
+})(), GM = CM(`.dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}
`);
-PM.inject(HM);
+LM.inject(GM);
var mg = "dg", xg = 72, bg = 20, ec = "Default", Co = (function() {
try {
return !!window.localStorage;
} catch {
return !1;
}
-})(), Po = void 0, Eg = !0, fa = void 0, Su = !1, px = [], kt = function i(e) {
+})(), Po = void 0, Eg = !0, fa = void 0, Su = !1, fx = [], kt = function i(e) {
var t = this, n = e || {};
this.domElement = document.createElement("div"), this.__ul = document.createElement("ul"), this.domElement.appendChild(this.__ul), te.addClass(this.domElement, mg), this.__folders = {}, this.__controllers = [], this.__rememberedObjects = [], this.__rememberedObjectIndecesToControllers = [], this.__listening = [], n = ue.defaults(n, {
closeOnTop: !1,
@@ -27567,7 +27567,7 @@ var mg = "dg", xg = 72, bg = 20, ec = "Default", Co = (function() {
}), n = ue.defaults(n, {
resizable: n.autoPlace,
hideable: n.autoPlace
- }), ue.isUndefined(n.load) ? n.load = { preset: ec } : n.preset && (n.load.preset = n.preset), ue.isUndefined(n.parent) && n.hideable && px.push(this), n.resizable = ue.isUndefined(n.parent) && n.resizable, n.autoPlace && ue.isUndefined(n.scrollable) && (n.scrollable = !0);
+ }), ue.isUndefined(n.load) ? n.load = { preset: ec } : n.preset && (n.load.preset = n.preset), ue.isUndefined(n.parent) && n.hideable && fx.push(this), n.resizable = ue.isUndefined(n.parent) && n.resizable, n.autoPlace && ue.isUndefined(n.scrollable) && (n.scrollable = !0);
var s = Co && localStorage.getItem(pa(this, "isLocal")) === "true", r = void 0, a = void 0;
if (Object.defineProperties(
this,
@@ -27597,7 +27597,7 @@ var mg = "dg", xg = 72, bg = 20, ec = "Default", Co = (function() {
return t.parent ? t.getRoot().preset : n.load.preset;
},
set: function(d) {
- t.parent ? t.getRoot().preset = d : n.load.preset = d, qM(this), t.revert();
+ t.parent ? t.getRoot().preset = d : n.load.preset = d, WM(this), t.revert();
}
},
width: {
@@ -27658,7 +27658,7 @@ var mg = "dg", xg = 72, bg = 20, ec = "Default", Co = (function() {
}
n.autoPlace && (ue.isUndefined(n.parent) && (Eg && (fa = document.createElement("div"), te.addClass(fa, mg), te.addClass(fa, i.CLASS_AUTO_PLACE_CONTAINER), document.body.appendChild(fa), Eg = !1), fa.appendChild(this.domElement), te.addClass(this.domElement, i.CLASS_AUTO_PLACE)), this.parent || rf(t, n.width)), this.__resizeHandler = function() {
t.onResizeDebounced();
- }, te.bind(window, "resize", this.__resizeHandler), te.bind(this.__ul, "webkitTransitionEnd", this.__resizeHandler), te.bind(this.__ul, "transitionend", this.__resizeHandler), te.bind(this.__ul, "oTransitionEnd", this.__resizeHandler), this.onResize(), n.resizable && WM(this), r = function() {
+ }, te.bind(window, "resize", this.__resizeHandler), te.bind(this.__ul, "webkitTransitionEnd", this.__resizeHandler), te.bind(this.__ul, "transitionend", this.__resizeHandler), te.bind(this.__ul, "oTransitionEnd", this.__resizeHandler), this.onResize(), n.resizable && VM(this), r = function() {
Co && localStorage.getItem(pa(t, "isLocal")) === "true" && localStorage.setItem(pa(t, "gui"), JSON.stringify(t.getSaveObject()));
}, this.saveToLocalStorageIfPossible = r;
function h() {
@@ -27670,7 +27670,7 @@ var mg = "dg", xg = 72, bg = 20, ec = "Default", Co = (function() {
n.parent || h();
};
kt.toggleHide = function() {
- Su = !Su, ue.each(px, function(i) {
+ Su = !Su, ue.each(fx, function(i) {
i.domElement.style.display = Su ? "none" : "";
});
};
@@ -27767,11 +27767,11 @@ ue.extend(
this.onResize();
}, 50),
remember: function() {
- if (ue.isUndefined(Po) && (Po = new GM(), Po.domElement.innerHTML = kM), this.parent)
+ if (ue.isUndefined(Po) && (Po = new QM(), Po.domElement.innerHTML = PM), this.parent)
throw new Error("You can only call remember on a top level GUI.");
var e = this;
ue.each(Array.prototype.slice.call(arguments), function(t) {
- e.__rememberedObjects.length === 0 && VM(e), e.__rememberedObjects.indexOf(t) === -1 && e.__rememberedObjects.push(t);
+ e.__rememberedObjects.length === 0 && zM(e), e.__rememberedObjects.indexOf(t) === -1 && e.__rememberedObjects.push(t);
}), this.autoPlace && rf(this, this.width);
},
getRoot: function() {
@@ -27793,14 +27793,14 @@ ue.extend(
},
revert: function(e) {
ue.each(this.__controllers, function(t) {
- this.getRoot().load.remembered ? Ax(e || this.getRoot(), t) : t.setValue(t.initialValue), t.__onFinishChange && t.__onFinishChange.call(t, t.getValue());
+ this.getRoot().load.remembered ? px(e || this.getRoot(), t) : t.setValue(t.initialValue), t.__onFinishChange && t.__onFinishChange.call(t, t.getValue());
}, this), ue.each(this.__folders, function(t) {
t.revert(t);
}), e || nf(this.getRoot(), !1);
},
listen: function(e) {
var t = this.__listening.length === 0;
- this.__listening.push(e), t && gx(this.__listening);
+ this.__listening.push(e), t && Ax(this.__listening);
},
updateDisplay: function() {
ue.each(this.__controllers, function(e) {
@@ -27822,7 +27822,7 @@ function nf(i, e) {
var t = i.__preset_select[i.__preset_select.selectedIndex];
e ? t.innerHTML = t.value + "*" : t.innerHTML = t.value;
}
-function zM(i, e, t) {
+function HM(i, e, t) {
if (t.__li = e, t.__gui = i, ue.extend(t, {
options: function(a) {
if (arguments.length > 1) {
@@ -27872,11 +27872,11 @@ function zM(i, e, t) {
return a;
};
t.min = ue.compose(s, t.min), t.max = ue.compose(s, t.max);
- } else t instanceof ux ? (te.bind(e, "click", function() {
+ } else t instanceof hx ? (te.bind(e, "click", function() {
te.fakeEvent(t.__checkbox, "click");
}), te.bind(t.__checkbox, "click", function(r) {
r.stopPropagation();
- })) : t instanceof fx ? (te.bind(e, "click", function() {
+ })) : t instanceof dx ? (te.bind(e, "click", function() {
te.fakeEvent(t.__button, "click");
}), te.bind(e, "mouseover", function() {
te.addClass(t.__button, "hover");
@@ -27889,7 +27889,7 @@ function zM(i, e, t) {
return i.getRoot().__preset_select && t.isModified() && nf(i.getRoot(), !0), r;
}, t.setValue);
}
-function Ax(i, e) {
+function px(i, e) {
var t = i.getRoot(), n = t.__rememberedObjects.indexOf(e.object);
if (n !== -1) {
var s = t.__rememberedObjectIndecesToControllers[n];
@@ -27916,15 +27916,15 @@ function ko(i, e, t, n) {
s = new tf(e, t);
else {
var r = [e, t].concat(n.factoryArgs);
- s = UM.apply(i, r);
+ s = kM.apply(i, r);
}
- n.before instanceof Gr && (n.before = n.before.__li), Ax(i, s), te.addClass(s.domElement, "c");
+ n.before instanceof Gr && (n.before = n.before.__li), px(i, s), te.addClass(s.domElement, "c");
var a = document.createElement("span");
te.addClass(a, "property-name"), a.innerHTML = s.property;
var o = document.createElement("div");
o.appendChild(a), o.appendChild(s.domElement);
var c = lp(i, o, n.before);
- return te.addClass(c, kt.CLASS_CONTROLLER_ROW), s instanceof tf ? te.addClass(c, "color") : te.addClass(c, MM(s.getValue())), zM(i, c, s), i.__controllers.push(s), s;
+ return te.addClass(c, kt.CLASS_CONTROLLER_ROW), s instanceof tf ? te.addClass(c, "color") : te.addClass(c, SM(s.getValue())), HM(i, c, s), i.__controllers.push(s), s;
}
function pa(i, e) {
return document.location.href + "." + e;
@@ -27936,7 +27936,7 @@ function sf(i, e, t) {
function _g(i, e) {
e.style.display = i.useLocalStorage ? "block" : "none";
}
-function VM(i) {
+function zM(i) {
var e = i.__save_row = document.createElement("li");
te.addClass(i.domElement, "has-save"), i.__ul.insertBefore(e, i.__ul.firstChild), te.addClass(e, "save-row");
var t = document.createElement("span");
@@ -27974,7 +27974,7 @@ function VM(i) {
i.revert();
});
}
-function WM(i) {
+function VM(i) {
var e = void 0;
i.__resize_handle = document.createElement("div"), ue.extend(i.__resize_handle.style, {
width: "6px",
@@ -28006,18 +28006,18 @@ function al(i, e) {
}), t[s] = r;
}), t;
}
-function qM(i) {
+function WM(i) {
for (var e = 0; e < i.__preset_select.length; e++)
i.__preset_select[e].value === i.preset && (i.__preset_select.selectedIndex = e);
}
-function gx(i) {
- i.length !== 0 && QM.call(window, function() {
- gx(i);
+function Ax(i) {
+ i.length !== 0 && OM.call(window, function() {
+ Ax(i);
}), ue.each(i, function(e) {
e.updateDisplay();
});
}
-var KM = kt;
+var qM = kt;
const ol = [
{
id: "",
@@ -28042,7 +28042,7 @@ const ol = [
path: "https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr",
format: ".exr"
}
-], jM = [
+], KM = [
"BN",
"BN",
"BN",
@@ -29015,9 +29015,9 @@ const ol = [
[1048574, 1048575, "BN"],
[1114110, 1114111, "BN"]
];
-function XM(i) {
+function jM(i) {
if (i <= 255)
- return jM[i];
+ return KM[i];
let e = 0, t = wg.length - 1;
for (; e <= t; ) {
const n = e + t >> 1, s = wg[n];
@@ -29033,7 +29033,7 @@ function XM(i) {
}
return "L";
}
-function YM(i) {
+function XM(i) {
const e = i.length;
if (e === 0)
return null;
@@ -29046,7 +29046,7 @@ function YM(i) {
const p = i.charCodeAt(l + 1);
p >= 56320 && p <= 57343 && (u = (h - 55296 << 10) + (p - 56320) + 65536, d = 2);
}
- const f = XM(u);
+ const f = jM(u);
(f === "R" || f === "AL" || f === "AN") && (n = !0);
for (let p = 0; p < d; p++)
t[l + p] = f;
@@ -29120,8 +29120,8 @@ function YM(i) {
}
return r;
}
-function JM(i, e) {
- const t = YM(i);
+function YM(i, e) {
+ const t = XM(i);
if (t === null)
return null;
const n = new Int8Array(e.length);
@@ -29129,30 +29129,30 @@ function JM(i, e) {
n[s] = t[e[s]];
return n;
}
-const ZM = /[ \t\n\r\f]+/g, $M = /[\t\n\r\f]| {2,}|^ | $/;
-function eB(i) {
+const JM = /[ \t\n\r\f]+/g, ZM = /[\t\n\r\f]| {2,}|^ | $/;
+function $M(i) {
const e = i ?? "normal";
return e === "pre-wrap" ? { mode: e, preserveOrdinarySpaces: !0, preserveHardBreaks: !0 } : { mode: e, preserveOrdinarySpaces: !1, preserveHardBreaks: !1 };
}
-function tB(i) {
- if (!$M.test(i))
+function eB(i) {
+ if (!ZM.test(i))
return i;
- let e = i.replace(ZM, " ");
+ let e = i.replace(JM, " ");
return e.charCodeAt(0) === 32 && (e = e.slice(1)), e.length > 0 && e.charCodeAt(e.length - 1) === 32 && (e = e.slice(0, -1)), e;
}
-function nB(i) {
+function tB(i) {
return /[\r\f]/.test(i) ? i.replace(/\r\n/g, `
`).replace(/[\r\f]/g, `
`) : i.replace(/\r\n/g, `
`);
}
-let Mu = null, iB;
-function sB() {
- return Mu === null && (Mu = new Intl.Segmenter(iB, { granularity: "word" })), Mu;
+let Mu = null, nB;
+function iB() {
+ return Mu === null && (Mu = new Intl.Segmenter(nB, { granularity: "word" })), Mu;
}
-const rB = new RegExp("\\p{Script=Arabic}", "u"), wh = new RegExp("\\p{M}", "u"), mx = new RegExp("\\p{Nd}", "u");
+const sB = new RegExp("\\p{Script=Arabic}", "u"), wh = new RegExp("\\p{M}", "u"), gx = new RegExp("\\p{Nd}", "u");
function vg(i) {
- return rB.test(i);
+ return sB.test(i);
}
function Cg(i) {
return i >= 19968 && i <= 40959 || i >= 13312 && i <= 19903 || i >= 131072 && i <= 173791 || i >= 173824 && i <= 177983 || i >= 177984 && i <= 178207 || i >= 178208 && i <= 183983 || i >= 183984 && i <= 191471 || i >= 191472 && i <= 192093 || i >= 194560 && i <= 195103 || i >= 196608 && i <= 201551 || i >= 201552 && i <= 205743 || i >= 205744 && i <= 210041 || i >= 63744 && i <= 64255 || i >= 12288 && i <= 12351 || i >= 12352 && i <= 12447 || i >= 12448 && i <= 12543 || i >= 44032 && i <= 55215 || i >= 65280 && i <= 65519;
@@ -29177,25 +29177,25 @@ function Lr(i) {
}
return !1;
}
-function aB(i) {
+function rB(i) {
const e = Ch(i);
return e !== null && (hp.has(e) || Pr.has(e));
}
-const oB = /* @__PURE__ */ new Set([
+const aB = /* @__PURE__ */ new Set([
" ",
" ",
"⁠",
"\uFEFF"
]);
-function cB(i) {
+function oB(i) {
return Lr(i);
}
-function lB(i) {
+function cB(i) {
const e = Ch(i);
- return e !== null && oB.has(e);
+ return e !== null && aB.has(e);
}
-function hB(i) {
- return !aB(i) && !lB(i);
+function lB(i) {
+ return !rB(i) && !cB(i);
}
const hp = /* @__PURE__ */ new Set([
",",
@@ -29273,14 +29273,14 @@ const hp = /* @__PURE__ */ new Set([
"»",
"›",
"…"
-]), uB = /* @__PURE__ */ new Set([
+]), hB = /* @__PURE__ */ new Set([
":",
".",
"،",
"؛"
-]), dB = /* @__PURE__ */ new Set([
+]), uB = /* @__PURE__ */ new Set([
"၏"
-]), fB = /* @__PURE__ */ new Set([
+]), dB = /* @__PURE__ */ new Set([
"”",
"’",
"»",
@@ -29293,7 +29293,7 @@ const hp = /* @__PURE__ */ new Set([
"〕",
")"
]);
-function pB(i) {
+function fB(i) {
if (dp(i))
return !0;
let e = !1;
@@ -29307,13 +29307,13 @@ function pB(i) {
}
return e;
}
-function AB(i) {
+function pB(i) {
for (const e of i)
if (!hp.has(e) && !Pr.has(e))
return !1;
return i.length > 0;
}
-function gB(i) {
+function AB(i) {
if (dp(i))
return !0;
for (const e of i)
@@ -29333,7 +29333,7 @@ function dp(i) {
}
return e;
}
-function xx(i, e) {
+function mx(i, e) {
const t = e - 1;
if (t <= 0)
return Math.max(t, 0);
@@ -29349,10 +29349,10 @@ function xx(i, e) {
function Ch(i) {
if (i.length === 0)
return null;
- const e = xx(i, i.length);
+ const e = mx(i, i.length);
return i.slice(e);
}
-function mB(i) {
+function gB(i) {
const e = Array.from(i);
let t = e.length;
for (; t > 0; ) {
@@ -29372,7 +29372,7 @@ function mB(i) {
tail: e.slice(t).join("")
};
}
-function xB(i, e, t) {
+function mB(i, e, t) {
return t === "text" && !e && i.length === 1 && i !== "-" && i !== "—" ? i : null;
}
function Ig(i, e, t, n) {
@@ -29386,13 +29386,13 @@ function Ig(i, e, t, n) {
return i[n] = o, o;
}
function Sg(i, e) {
- return i && e !== null && uB.has(e);
+ return i && e !== null && hB.has(e);
}
-function bB(i) {
+function xB(i) {
const e = Ch(i);
- return e !== null && dB.has(e);
+ return e !== null && uB.has(e);
}
-function EB(i) {
+function bB(i) {
if (i.length < 2 || i[0] !== " ")
return null;
const e = i.slice(1);
@@ -29401,8 +29401,8 @@ function EB(i) {
function af(i) {
let e = i.length;
for (; e > 0; ) {
- const t = xx(i, e), n = i.slice(t, e);
- if (fB.has(n))
+ const t = mx(i, e), n = i.slice(t, e);
+ if (dB.has(n))
return !0;
if (!Pr.has(n))
return !1;
@@ -29410,7 +29410,7 @@ function af(i) {
}
return !1;
}
-function yB(i, e) {
+function EB(i, e) {
if (e.preserveOrdinarySpaces || e.preserveHardBreaks) {
if (i === " ")
return "preserved-space";
@@ -29422,23 +29422,23 @@ function yB(i, e) {
}
return i === " " ? "space" : i === " " || i === " " || i === "⁠" || i === "\uFEFF" ? "glue" : i === "​" ? "zero-width-break" : i === "­" ? "soft-hyphen" : "text";
}
-const _B = /[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;
+const yB = /[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;
function fi(i) {
return i.length === 1 ? i[0] : i.join("");
}
-function wB(i, e) {
+function _B(i, e) {
const t = [];
for (let n = i.length - 1; n >= 0; n--)
t.push(i[n]);
return t.push(e), fi(t);
}
-function vB(i, e, t, n) {
- if (!_B.test(i))
+function wB(i, e, t, n) {
+ if (!yB.test(i))
return [{ text: i, isWordLike: e, kind: "text", start: t }];
const s = [];
let r = null, a = [], o = t, c = !1, l = 0;
for (const h of i) {
- const u = yB(h, n), d = u === "text" && e;
+ const u = EB(h, n), d = u === "text" && e;
if (r !== null && u === r && d === c) {
a.push(h), l += h.length;
continue;
@@ -29460,18 +29460,18 @@ function vB(i, e, t, n) {
function of(i) {
return i === "space" || i === "preserved-space" || i === "zero-width-break" || i === "hard-break";
}
-const CB = /^[A-Za-z][A-Za-z0-9+.-]*:$/;
-function IB(i, e) {
+const vB = /^[A-Za-z][A-Za-z0-9+.-]*:$/;
+function CB(i, e) {
const t = i.texts[e];
- return t.startsWith("www.") ? !0 : CB.test(t) && e + 1 < i.len && i.kinds[e + 1] === "text" && i.texts[e + 1] === "//";
+ return t.startsWith("www.") ? !0 : vB.test(t) && e + 1 < i.len && i.kinds[e + 1] === "text" && i.texts[e + 1] === "//";
}
-function SB(i) {
+function IB(i) {
return i.includes("?") && (i.includes("://") || i.startsWith("www."));
}
-function MB(i) {
+function SB(i) {
const e = i.texts.slice(), t = i.isWordLike.slice(), n = i.kinds.slice(), s = i.starts.slice();
for (let a = 0; a < i.len; a++) {
- if (n[a] !== "text" || !IB(i, a))
+ if (n[a] !== "text" || !CB(i, a))
continue;
const o = [e[a]];
let c = a + 1;
@@ -29496,11 +29496,11 @@ function MB(i) {
starts: s
};
}
-function BB(i) {
+function MB(i) {
const e = [], t = [], n = [], s = [];
for (let r = 0; r < i.len; r++) {
const a = i.texts[r];
- if (e.push(a), t.push(i.isWordLike[r]), n.push(i.kinds[r]), s.push(i.starts[r]), !SB(a))
+ if (e.push(a), t.push(i.isWordLike[r]), n.push(i.kinds[r]), s.push(i.starts[r]), !IB(a))
continue;
const o = r + 1;
if (o >= i.len || of(i.kinds[o]))
@@ -29519,7 +29519,7 @@ function BB(i) {
starts: s
};
}
-const TB = /* @__PURE__ */ new Set([
+const BB = /* @__PURE__ */ new Set([
":",
"-",
"/",
@@ -29530,9 +29530,9 @@ const TB = /* @__PURE__ */ new Set([
"–",
"—"
]), Mg = /^[A-Za-z0-9_]+[,:;]*$/, Bg = /[,:;]+$/;
-function bx(i) {
+function xx(i) {
for (const e of i)
- if (mx.test(e))
+ if (gx.test(e))
return !0;
return !1;
}
@@ -29540,15 +29540,15 @@ function th(i) {
if (i.length === 0)
return !1;
for (const e of i)
- if (!(mx.test(e) || TB.has(e)))
+ if (!(gx.test(e) || BB.has(e)))
return !1;
return !0;
}
-function RB(i) {
+function TB(i) {
const e = [], t = [], n = [], s = [];
for (let r = 0; r < i.len; r++) {
const a = i.texts[r], o = i.kinds[r];
- if (o === "text" && th(a) && bx(a)) {
+ if (o === "text" && th(a) && xx(a)) {
const c = [a];
let l = r + 1;
for (; l < i.len && i.kinds[l] === "text" && th(i.texts[l]); )
@@ -29566,7 +29566,7 @@ function RB(i) {
starts: s
};
}
-function FB(i) {
+function RB(i) {
const e = [], t = [], n = [], s = [];
for (let r = 0; r < i.len; r++) {
const a = i.texts[r], o = i.kinds[r], c = i.isWordLike[r];
@@ -29590,7 +29590,7 @@ function FB(i) {
starts: s
};
}
-function NB(i) {
+function FB(i) {
const e = [], t = [], n = [], s = [];
for (let r = 0; r < i.len; r++) {
const a = i.texts[r];
@@ -29601,7 +29601,7 @@ function NB(i) {
const h = o[l];
if (!c)
break;
- (h.length === 0 || !bx(h) || !th(h)) && (c = !1);
+ (h.length === 0 || !xx(h) || !th(h)) && (c = !1);
}
if (c) {
let l = 0;
@@ -29622,7 +29622,7 @@ function NB(i) {
starts: s
};
}
-function DB(i) {
+function NB(i) {
const e = [], t = [], n = [], s = [];
let r = 0;
for (; r < i.len; ) {
@@ -29663,12 +29663,12 @@ function DB(i) {
starts: s
};
}
-function LB(i) {
+function DB(i) {
const e = i.texts.slice(), t = i.isWordLike.slice(), n = i.kinds.slice(), s = i.starts.slice();
for (let r = 0; r < e.length - 1; r++) {
if (n[r] !== "text" || n[r + 1] !== "text" || !Lr(e[r]) || !Lr(e[r + 1]))
continue;
- const a = mB(e[r]);
+ const a = gB(e[r]);
a !== null && (e[r] = a.head, e[r + 1] = a.tail + e[r + 1], s[r + 1] = s[r] + a.head.length);
}
return {
@@ -29680,18 +29680,18 @@ function LB(i) {
};
}
function Tg(i, e, t) {
- const n = sB();
+ const n = iB();
let s = 0;
const r = [], a = [], o = [], c = [], l = [], h = [], u = [], d = [], f = [], p = [], m = [], g = [];
for (const w of n.segment(i))
- for (const I of vB(w.segment, w.isWordLike ?? !1, w.index, t)) {
+ for (const I of wB(w.segment, w.isWordLike ?? !1, w.index, t)) {
let O = function() {
h[D] !== null && (a[D] = [
Ig(r, h, u, D)
], h[D] = null), a[D].push(I.text), o[D] = o[D] || I.isWordLike, d[D] = d[D] || v, f[D] = f[D] || F, p[D] = q, m[D] = $, g[D] = Sg(f[D], K);
};
- const T = I.kind === "text", C = xB(I.text, I.isWordLike, I.kind), v = Lr(I.text), F = vg(I.text), K = Ch(I.text), q = af(I.text), $ = bB(I.text), D = s - 1;
- e.carryCJKAfterClosingQuote && T && s > 0 && c[D] === "text" && v && d[D] && p[D] || T && s > 0 && c[D] === "text" && AB(I.text) && d[D] || T && s > 0 && c[D] === "text" && m[D] ? O() : T && s > 0 && c[D] === "text" && I.isWordLike && F && g[D] ? (O(), o[D] = !0) : C !== null && s > 0 && c[D] === "text" && h[D] === C ? u[D] = (u[D] ?? 1) + 1 : T && !I.isWordLike && s > 0 && c[D] === "text" && (pB(I.text) || I.text === "-" && o[D]) ? O() : (r[s] = I.text, a[s] = [I.text], o[s] = I.isWordLike, c[s] = I.kind, l[s] = I.start, h[s] = C, u[s] = C === null ? 0 : 1, d[s] = v, f[s] = F, p[s] = q, m[s] = $, g[s] = Sg(F, K), s++);
+ const T = I.kind === "text", C = mB(I.text, I.isWordLike, I.kind), v = Lr(I.text), F = vg(I.text), K = Ch(I.text), q = af(I.text), $ = xB(I.text), D = s - 1;
+ e.carryCJKAfterClosingQuote && T && s > 0 && c[D] === "text" && v && d[D] && p[D] || T && s > 0 && c[D] === "text" && pB(I.text) && d[D] || T && s > 0 && c[D] === "text" && m[D] ? O() : T && s > 0 && c[D] === "text" && I.isWordLike && F && g[D] ? (O(), o[D] = !0) : C !== null && s > 0 && c[D] === "text" && h[D] === C ? u[D] = (u[D] ?? 1) + 1 : T && !I.isWordLike && s > 0 && c[D] === "text" && (fB(I.text) || I.text === "-" && o[D]) ? O() : (r[s] = I.text, a[s] = [I.text], o[s] = I.isWordLike, c[s] = I.kind, l[s] = I.start, h[s] = C, u[s] = C === null ? 0 : 1, d[s] = v, f[s] = F, p[s] = q, m[s] = $, g[s] = Sg(F, K), s++);
}
for (let w = 0; w < s; w++) {
if (h[w] !== null) {
@@ -29707,7 +29707,7 @@ function Tg(i, e, t) {
for (let w = s - 1; w >= 0; w--) {
const I = r[w];
if (I.length !== 0) {
- if (c[w] === "text" && !o[w] && gB(I) && _ >= 0 && c[_] === "text") {
+ if (c[w] === "text" && !o[w] && AB(I) && _ >= 0 && c[_] === "text") {
const T = A[_] ?? [];
T.push(I), A[_] = T, l[_] = l[w], r[w] = "";
continue;
@@ -29717,7 +29717,7 @@ function Tg(i, e, t) {
}
for (let w = 0; w < s; w++) {
const I = A[w];
- I != null && (r[w] = wB(I, r[w]));
+ I != null && (r[w] = _B(I, r[w]));
}
let x = 0;
for (let w = 0; w < s; w++) {
@@ -29725,20 +29725,20 @@ function Tg(i, e, t) {
I.length !== 0 && (x !== w && (r[x] = I, o[x] = o[w], c[x] = c[w], l[x] = l[w]), x++);
}
r.length = x, o.length = x, c.length = x, l.length = x;
- const E = DB({
+ const E = NB({
len: x,
texts: r,
isWordLike: o,
kinds: c,
starts: l
- }), S = LB(FB(NB(RB(BB(MB(E))))));
+ }), S = DB(RB(FB(TB(MB(SB(E))))));
for (let w = 0; w < S.len - 1; w++) {
- const I = EB(S.texts[w]);
+ const I = bB(S.texts[w]);
I !== null && (S.kinds[w] !== "space" && S.kinds[w] !== "preserved-space" || S.kinds[w + 1] !== "text" || !vg(S.texts[w + 1]) || (S.texts[w] = I.space, S.isWordLike[w] = !1, S.kinds[w] = S.kinds[w] === "preserved-space" ? "preserved-space" : "space", S.texts[w + 1] = I.marks + S.texts[w + 1], S.starts[w + 1] = S.starts[w] + I.space.length));
}
return S;
}
-function PB(i, e) {
+function LB(i, e) {
if (i.len === 0)
return [];
if (!e.preserveHardBreaks)
@@ -29761,7 +29761,7 @@ function PB(i, e) {
consumedEndSegmentIndex: i.len
}), t;
}
-function kB(i) {
+function PB(i) {
if (i.len <= 1)
return i;
const e = [], t = [], n = [], s = [];
@@ -29772,7 +29772,7 @@ function kB(i) {
for (let u = 0; u < i.len; u++) {
const d = i.texts[u], f = i.kinds[u], p = i.isWordLike[u], m = i.starts[u];
if (f === "text") {
- const g = cB(d), A = hB(d);
+ const g = oB(d), A = lB(d);
if (r !== null && c && l) {
r.push(d), a = a || p, c = c || g, l = A;
continue;
@@ -29790,8 +29790,8 @@ function kB(i) {
starts: s
};
}
-function UB(i, e, t = "normal", n = "normal") {
- const s = eB(t), r = s.mode === "pre-wrap" ? nB(i) : tB(i);
+function kB(i, e, t = "normal", n = "normal") {
+ const s = $M(t), r = s.mode === "pre-wrap" ? tB(i) : eB(i);
if (r.length === 0)
return {
normalized: r,
@@ -29802,17 +29802,17 @@ function UB(i, e, t = "normal", n = "normal") {
kinds: [],
starts: []
};
- const a = n === "keep-all" ? kB(Tg(r, e, s)) : Tg(r, e, s);
+ const a = n === "keep-all" ? PB(Tg(r, e, s)) : Tg(r, e, s);
return {
normalized: r,
- chunks: PB(a, s),
+ chunks: LB(a, s),
...a
};
}
let ca = null;
const Rg = /* @__PURE__ */ new Map();
let la = null;
-const OB = 96, QB = new RegExp("\\p{Emoji_Presentation}", "u"), GB = /[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;
+const UB = 96, OB = new RegExp("\\p{Emoji_Presentation}", "u"), QB = /[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;
let Bu = null;
const Fg = /* @__PURE__ */ new Map();
function fp() {
@@ -29824,7 +29824,7 @@ function fp() {
return ca = document.createElement("canvas").getContext("2d"), ca;
throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.");
}
-function HB(i) {
+function GB(i) {
let e = Rg.get(i);
return e || (e = /* @__PURE__ */ new Map(), Rg.set(i, e)), e;
}
@@ -29853,20 +29853,20 @@ function Ja() {
preferEarlySoftHyphenBreak: t
}, la;
}
-function zB(i) {
+function HB(i) {
const e = i.match(/(\d+(?:\.\d+)?)\s*px/);
return e ? parseFloat(e[1]) : 16;
}
-function Ex() {
+function bx() {
return Bu === null && (Bu = new Intl.Segmenter(void 0, { granularity: "grapheme" })), Bu;
}
-function VB(i) {
- return QB.test(i) || i.includes("️");
+function zB(i) {
+ return OB.test(i) || i.includes("️");
}
-function WB(i) {
- return GB.test(i);
+function VB(i) {
+ return QB.test(i);
}
-function qB(i, e) {
+function WB(i, e) {
let t = Fg.get(i);
if (t !== void 0)
return t;
@@ -29881,23 +29881,23 @@ function qB(i, e) {
}
return Fg.set(i, t), t;
}
-function KB(i) {
+function qB(i) {
let e = 0;
- const t = Ex();
+ const t = bx();
for (const n of t.segment(i))
- VB(n.segment) && e++;
+ zB(n.segment) && e++;
return e;
}
-function jB(i, e) {
- return e.emojiCount === void 0 && (e.emojiCount = KB(i)), e.emojiCount;
+function KB(i, e) {
+ return e.emojiCount === void 0 && (e.emojiCount = qB(i)), e.emojiCount;
}
function yr(i, e, t) {
- return t === 0 ? e.width : e.width - jB(i, e) * t;
+ return t === 0 ? e.width : e.width - KB(i, e) * t;
}
-function XB(i, e, t, n, s) {
+function jB(i, e, t, n, s) {
if (e.breakableFitAdvances !== void 0)
return e.breakableFitAdvances;
- const r = Ex(), a = [];
+ const r = bx(), a = [];
for (const h of r.segment(i))
a.push(h.segment);
if (a.length <= 1)
@@ -29910,7 +29910,7 @@ function XB(i, e, t, n, s) {
}
return e.breakableFitAdvances = h, e.breakableFitAdvances;
}
- if (s === "pair-context" || a.length > OB) {
+ if (s === "pair-context" || a.length > UB) {
const h = [];
let u = null, d = 0;
for (const f of a) {
@@ -29934,13 +29934,13 @@ function XB(i, e, t, n, s) {
}
return e.breakableFitAdvances = o, e.breakableFitAdvances;
}
-function YB(i, e) {
+function XB(i, e) {
const t = fp();
t.font = i;
- const n = HB(i), s = zB(i), r = e ? qB(i, s) : 0;
+ const n = GB(i), s = HB(i), r = e ? WB(i, s) : 0;
return { cache: n, fontSize: s, emojiCorrection: r };
}
-function JB(i, e) {
+function YB(i, e) {
for (; e < i.widths.length; ) {
const t = i.kinds[e];
if (t !== "space" && t !== "zero-width-break" && t !== "soft-hyphen")
@@ -29949,13 +29949,13 @@ function JB(i, e) {
}
return e;
}
-function yx(i, e) {
+function Ex(i, e) {
if (e <= 0)
return 0;
const t = i % e;
return Math.abs(t) <= 1e-6 ? e : e - t;
}
-function _x(i, e, t, n, s) {
+function yx(i, e, t, n, s) {
let r = 0, a = e;
for (; r < i.length; ) {
const o = a + i[r];
@@ -29965,7 +29965,7 @@ function _x(i, e, t, n, s) {
}
return { fitCount: r, fittedWidth: a };
}
-function ZB(i, e) {
+function JB(i, e) {
let t = 0, n = i.chunks.length;
for (; t < n; ) {
const s = Math.floor((t + n) / 2);
@@ -29973,7 +29973,7 @@ function ZB(i, e) {
}
return t < i.chunks.length ? t : -1;
}
-function wx(i, e, t) {
+function _x(i, e, t) {
let n = t.segmentIndex;
if (t.graphemeIndex > 0)
return e;
@@ -29991,21 +29991,21 @@ function wx(i, e, t) {
function pp(i, e) {
if (e.segmentIndex >= i.widths.length)
return -1;
- const t = ZB(i, e.segmentIndex);
- return t < 0 ? -1 : wx(i, t, e);
+ const t = JB(i, e.segmentIndex);
+ return t < 0 ? -1 : _x(i, t, e);
}
-function $B(i, e, t) {
+function ZB(i, e, t) {
if (t.segmentIndex >= i.widths.length)
return -1;
let n = e;
for (; n < i.chunks.length && t.segmentIndex >= i.chunks[n].consumedEndSegmentIndex; )
n++;
- return n >= i.chunks.length ? -1 : wx(i, n, t);
+ return n >= i.chunks.length ? -1 : _x(i, n, t);
}
-function eT(i, e) {
- return i.simpleLineWalkFastPath ? vx(i, e) : Ap(i, e);
+function $B(i, e) {
+ return i.simpleLineWalkFastPath ? wx(i, e) : Ap(i, e);
}
-function vx(i, e, t) {
+function wx(i, e, t) {
const { widths: n, kinds: s, breakableFitAdvances: r } = i;
if (n.length === 0)
return 0;
@@ -30045,7 +30045,7 @@ function vx(i, e, t) {
u && p === C && m === F.length && (p = C + 1, m = 0);
}
let T = 0;
- for (; T < n.length && !(!u && (T = JB(i, T), T >= n.length)); ) {
+ for (; T < n.length && !(!u && (T = YB(i, T), T >= n.length)); ) {
const C = n[T], v = s[T], F = v === "space" || v === "preserved-space" || v === "tab" || v === "zero-width-break" || v === "soft-hyphen";
if (!u) {
C > e && r[T] !== null ? I(T, 0) : E(T, C), F && (g = T + 1, A = h - C), T++;
@@ -30077,7 +30077,7 @@ function vx(i, e, t) {
}
function Ap(i, e, t) {
if (i.simpleLineWalkFastPath)
- return vx(i, e, t);
+ return wx(i, e, t);
const { widths: n, lineEndFitAdvances: s, lineEndPaintAdvances: r, kinds: a, breakableFitAdvances: o, discretionaryHyphenWidth: c, tabStopAdvance: l, chunks: h } = i;
if (n.length === 0 || h.length === 0)
return 0;
@@ -30128,7 +30128,7 @@ function Ap(i, e, t) {
const J = o[Q];
if (J == null)
return !1;
- const { fitCount: ee, fittedWidth: ae } = _x(J, m, e, d, c);
+ const { fitCount: ee, fittedWidth: ae } = yx(J, m, e, d, c);
return ee === 0 ? !1 : (m = ae, x = Q, E = ee, C(), ee === J.length ? (x = Q + 1, E = 0, !0) : (v(Q, ee, ae + c), D(Q, ee), !0));
}
function Y(Q) {
@@ -30149,7 +30149,7 @@ function Ap(i, e, t) {
g = !1, m = 0, A = J.startSegmentIndex, _ = 0, x = J.startSegmentIndex, E = 0, C();
let ee = J.startSegmentIndex;
for (; ee < J.endSegmentIndex; ) {
- const ae = a[ee], _e = ae === "space" || ae === "preserved-space" || ae === "tab" || ae === "zero-width-break" || ae === "soft-hyphen", Me = ae === "tab" ? yx(m, l) : n[ee];
+ const ae = a[ee], _e = ae === "space" || ae === "preserved-space" || ae === "tab" || ae === "zero-width-break" || ae === "soft-hyphen", Me = ae === "tab" ? Ex(m, l) : n[ee];
if (ae === "soft-hyphen") {
g && (x = ee + 1, E = 0, S = ee + 1, w = m + c, I = m + c, T = ae), ee++;
continue;
@@ -30247,7 +30247,7 @@ function gp(i, e, t, n) {
return null;
const O = l[D] ?? null;
if (O !== null) {
- const { fitCount: Y, fittedWidth: Q } = _x(O, m, n, f, h);
+ const { fitCount: Y, fittedWidth: Q } = yx(O, m, n, f, h);
if (Y === O.length)
return m = Q, A = D + 1, _ = 0, I(), null;
if (Y > 0)
@@ -30256,7 +30256,7 @@ function gp(i, e, t, n) {
return E <= p ? T(x, 0, S) : null;
}
for (let D = e.segmentIndex; D < s.endSegmentIndex; D++) {
- const O = c[D], Y = O === "space" || O === "preserved-space" || O === "tab" || O === "zero-width-break" || O === "soft-hyphen", Q = D === e.segmentIndex ? e.graphemeIndex : 0, J = O === "tab" ? yx(m, u) : r[D];
+ const O = c[D], Y = O === "space" || O === "preserved-space" || O === "tab" || O === "zero-width-break" || O === "soft-hyphen", Q = D === e.segmentIndex ? e.graphemeIndex : 0, J = O === "tab" ? Ex(m, u) : r[D];
if (O === "soft-hyphen" && Q === 0) {
g && (A = D + 1, _ = 0, x = D + 1, E = m + h, S = m + h, w = O);
continue;
@@ -30300,7 +30300,7 @@ function gp(i, e, t, n) {
}
return x === s.consumedEndSegmentIndex && _ === 0 ? T(s.consumedEndSegmentIndex, 0, S) : T(s.consumedEndSegmentIndex, 0, m);
}
-function Cx(i, e, t) {
+function vx(i, e, t) {
const { widths: n, kinds: s, breakableFitAdvances: r } = i, o = Ja().lineFitEpsilon, c = t + o;
let l = 0, h = !1, u = e.segmentIndex, d = e.graphemeIndex, f = -1, p = 0;
for (let m = e.segmentIndex; m < n.length; m++) {
@@ -30334,7 +30334,7 @@ function cf(i, e, t) {
}, s = pp(i, n);
if (s < 0)
return null;
- const r = n.segmentIndex, a = n.graphemeIndex, o = i.simpleLineWalkFastPath ? Cx(i, n, t) : gp(i, n, s, t);
+ const r = n.segmentIndex, a = n.graphemeIndex, o = i.simpleLineWalkFastPath ? vx(i, n, t) : gp(i, n, s, t);
return o === null ? null : {
startSegmentIndex: r,
startGraphemeIndex: a,
@@ -30343,11 +30343,11 @@ function cf(i, e, t) {
width: o
};
}
-function tT(i, e, t) {
+function eT(i, e, t) {
const n = pp(i, e);
- return n < 0 ? null : i.simpleLineWalkFastPath ? Cx(i, e, t) : gp(i, e, n, t);
+ return n < 0 ? null : i.simpleLineWalkFastPath ? vx(i, e, t) : gp(i, e, n, t);
}
-function nT(i, e) {
+function tT(i, e) {
if (i.widths.length === 0)
return {
lineCount: 0,
@@ -30367,7 +30367,7 @@ function nT(i, e) {
lineCount: n,
maxLineWidth: s
};
- n++, a > s && (s = a), r = $B(i, r, t);
+ n++, a > s && (s = a), r = ZB(i, r, t);
}
return {
lineCount: n,
@@ -30375,7 +30375,7 @@ function nT(i, e) {
};
}
for (; ; ) {
- const r = tT(i, t, e);
+ const r = eT(i, t, e);
if (r === null)
return {
lineCount: n,
@@ -30385,10 +30385,10 @@ function nT(i, e) {
}
}
let Tu = null, Ng = /* @__PURE__ */ new WeakMap();
-function Ix() {
+function Cx() {
return Tu === null && (Tu = new Intl.Segmenter(void 0, { granularity: "grapheme" })), Tu;
}
-function iT(i) {
+function nT(i) {
return i ? {
widths: [],
lineEndFitAdvances: [],
@@ -30414,7 +30414,7 @@ function iT(i) {
chunks: []
};
}
-function sT(i, e) {
+function iT(i, e) {
const t = [];
let n = [], s = 0, r = !1, a = !1, o = !1;
function c() {
@@ -30431,7 +30431,7 @@ function sT(i, e) {
const f = af(u);
u.length === 1 && Pr.has(u) ? a = a || f : a = f, o = !1;
}
- for (const u of Ix().segment(i)) {
+ for (const u of Cx().segment(i)) {
const d = u.segment, f = Lr(d);
if (n.length === 0) {
l(d, u.index, f);
@@ -30449,10 +30449,10 @@ function sT(i, e) {
}
return c(), t;
}
-function rT(i, e, t, n) {
- const s = Ja(), { cache: r, emojiCorrection: a } = YB(e, WB(i.normalized)), o = yr("-", Qs("-", r), a), l = yr(" ", Qs(" ", r), a) * 8;
+function sT(i, e, t, n) {
+ const s = Ja(), { cache: r, emojiCorrection: a } = XB(e, VB(i.normalized)), o = yr("-", Qs("-", r), a), l = yr(" ", Qs(" ", r), a) * 8;
if (i.len === 0)
- return iT(t);
+ return nT(t);
const h = [], u = [], d = [], f = [];
let p = i.chunks.length <= 1;
const m = t ? [] : null, g = [], A = t ? [] : null, _ = Array.from({ length: i.len });
@@ -30464,7 +30464,7 @@ function rT(i, e, t, n) {
if (F && v && I.length > 1) {
let O = "sum-graphemes";
th(I) ? O = "pair-context" : s.preferPrefixWidthsForBreakableRuns && (O = "segment-prefixes");
- const Y = XB(I, K, r, a, O);
+ const Y = jB(I, K, r, a, O);
x(I, q, $, D, T, C, Y);
return;
}
@@ -30487,7 +30487,7 @@ function rT(i, e, t, n) {
}
const K = Qs(T, r);
if (v === "text" && K.containsCJK) {
- const $ = sT(T, s);
+ const $ = iT(T, s);
for (let D = 0; D < $.length; D++) {
const O = $[D];
E(O.text, "text", F + O.start, C, !Lr(O.text));
@@ -30496,7 +30496,7 @@ function rT(i, e, t, n) {
}
E(T, v, F, C, !0);
}
- const S = aT(i.chunks, _, h.length), w = m === null ? null : JM(i.normalized, m);
+ const S = rT(i.chunks, _, h.length), w = m === null ? null : YM(i.normalized, m);
return A !== null ? {
widths: h,
lineEndFitAdvances: u,
@@ -30522,7 +30522,7 @@ function rT(i, e, t, n) {
chunks: S
};
}
-function aT(i, e, t) {
+function rT(i, e, t) {
const n = [];
for (let s = 0; s < i.length; s++) {
const r = i[s], a = r.startSegmentIndex < e.length ? e[r.startSegmentIndex] : t, o = r.endSegmentIndex < e.length ? e[r.endSegmentIndex] : t, c = r.consumedEndSegmentIndex < e.length ? e[r.consumedEndSegmentIndex] : t;
@@ -30534,18 +30534,18 @@ function aT(i, e, t) {
}
return n;
}
-function Sx(i, e, t, n) {
- const r = UB(i, Ja(), n?.whiteSpace, "normal");
- return rT(r, e, t);
+function Ix(i, e, t, n) {
+ const r = kB(i, Ja(), n?.whiteSpace, "normal");
+ return sT(r, e, t);
}
function cl(i, e, t) {
- return Sx(i, e, !1, t);
+ return Ix(i, e, !1, t);
}
function nh(i, e, t) {
- return Sx(i, e, !0, t);
+ return Ix(i, e, !0, t);
}
-function oT(i, e, t) {
- const n = eT(i, e);
+function aT(i, e, t) {
+ const n = $B(i, e);
return { lineCount: n, height: n * t };
}
function Dg(i, e, t) {
@@ -30553,28 +30553,28 @@ function Dg(i, e, t) {
if (n !== void 0)
return n;
n = [];
- const s = Ix();
+ const s = Cx();
for (const r of s.segment(e[i]))
n.push(r.segment);
return t.set(i, n), n;
}
-function Mx(i) {
+function Sx(i) {
let e = Ng.get(i);
return e !== void 0 || (e = /* @__PURE__ */ new Map(), Ng.set(i, e)), e;
}
-function cT(i, e, t, n) {
+function oT(i, e, t, n) {
return n > 0 && i[n - 1] === "soft-hyphen" && !(e === n && t > 0);
}
-function lT(i, e, t, n, s, r, a) {
+function cT(i, e, t, n, s, r, a) {
let o = "";
- const c = cT(e, n, s, r);
+ const c = oT(e, n, s, r);
for (let l = n; l < r; l++)
e[l] === "soft-hyphen" || e[l] === "hard-break" || (l === n && s > 0 ? o += Dg(l, i, t).slice(s).join("") : o += i[l]);
return a > 0 ? (c && (o += "-"), o += Dg(r, i, t).slice(n === r ? s : 0, a).join("")) : c && (o += "-"), o;
}
-function Bx(i, e, t, n, s, r, a) {
+function Mx(i, e, t, n, s, r, a) {
return {
- text: lT(i.segments, i.kinds, e, n, s, r, a),
+ text: cT(i.segments, i.kinds, e, n, s, r, a),
width: t,
start: {
segmentIndex: n,
@@ -30586,10 +30586,10 @@ function Bx(i, e, t, n, s, r, a) {
}
};
}
-function hT(i, e, t) {
- return Bx(i, e, t.width, t.startSegmentIndex, t.startGraphemeIndex, t.endSegmentIndex, t.endGraphemeIndex);
+function lT(i, e, t) {
+ return Mx(i, e, t.width, t.startSegmentIndex, t.startGraphemeIndex, t.endSegmentIndex, t.endGraphemeIndex);
}
-function uT(i) {
+function hT(i) {
return {
width: i.width,
start: {
@@ -30602,33 +30602,33 @@ function uT(i) {
}
};
}
-function dT(i, e) {
- return Bx(i, Mx(i), e.width, e.start.segmentIndex, e.start.graphemeIndex, e.end.segmentIndex, e.end.graphemeIndex);
+function uT(i, e) {
+ return Mx(i, Sx(i), e.width, e.start.segmentIndex, e.start.graphemeIndex, e.end.segmentIndex, e.end.graphemeIndex);
}
-function fT(i, e, t) {
+function dT(i, e, t) {
return i.widths.length === 0 ? 0 : Ap(i, e, (n) => {
- t(uT(n));
+ t(hT(n));
});
}
function Ru(i, e) {
- return nT(i, e);
+ return tT(i, e);
}
function Lg(i) {
let e = 0;
- return fT(i, Number.POSITIVE_INFINITY, (t) => {
+ return dT(i, Number.POSITIVE_INFINITY, (t) => {
t.width > e && (e = t.width);
}), e;
}
-function pT(i, e, t) {
+function fT(i, e, t) {
const n = [];
if (i.widths.length === 0)
return { lineCount: 0, height: 0, lines: n };
- const s = Mx(i), r = Ap(i, e, (a) => {
- n.push(hT(i, s, a));
+ const s = Sx(i), r = Ap(i, e, (a) => {
+ n.push(lT(i, s, a));
});
return { lineCount: r, height: r * t, lines: n };
}
-const AT = /[ \t\n\f\r]+/, Pg = /^[ \t\n\f\r]+/, kg = /[ \t\n\f\r]+$/, Fl = { segmentIndex: 0, graphemeIndex: 0 }, Tx = {
+const pT = /[ \t\n\f\r]+/, Pg = /^[ \t\n\f\r]+/, kg = /[ \t\n\f\r]+$/, Fl = { segmentIndex: 0, graphemeIndex: 0 }, Bx = {
itemIndex: 0,
segmentIndex: 0,
graphemeIndex: 0
@@ -30649,7 +30649,7 @@ function ll(i, e) {
const n = Lg(nh("A A", i)), s = Lg(nh("AA", i)), r = Math.max(0, n - s);
return e.set(i, r), r;
}
-function gT(i) {
+function AT(i) {
const e = cf(i, Fl, Number.POSITIVE_INFINITY);
return e === null ? null : {
endGraphemeIndex: e.endGraphemeIndex,
@@ -30657,19 +30657,19 @@ function gT(i) {
width: e.width
};
}
-function mT(i, e) {
+function gT(i, e) {
return i === 0 && e > 0;
}
-function Rx(i) {
+function Tx(i) {
const e = [], t = Array.from({ length: i.length }), n = /* @__PURE__ */ new Map();
let s = 0;
for (let r = 0; r < i.length; r++) {
const a = i[r], o = Pg.test(a.text), c = kg.test(a.text), l = a.text.replace(Pg, "").replace(kg, "");
if (l.length === 0) {
- AT.test(a.text) && s === 0 && (s = ll(a.font, n));
+ pT.test(a.text) && s === 0 && (s = ll(a.font, n));
continue;
}
- const h = s > 0 ? s : o ? ll(a.font, n) : 0, u = nh(l, a.font), d = gT(u);
+ const h = s > 0 ? s : o ? ll(a.font, n) : 0, u = nh(l, a.font), d = AT(u);
if (d === null) {
s = c ? ll(a.font, n) : 0;
continue;
@@ -30691,7 +30691,7 @@ function Rx(i) {
itemsBySourceItemIndex: t
};
}
-function xT(i, e, t, n) {
+function mT(i, e, t, n) {
if (i.items.length === 0 || t.itemIndex >= i.items.length)
return null;
const s = Math.max(1, e);
@@ -30743,7 +30743,7 @@ function xT(i, e, t, n) {
o++, c.segmentIndex = 0, c.graphemeIndex = 0;
continue;
}
- if (r > 0 && u && h > 0 && mT(p.endSegmentIndex, p.endGraphemeIndex)) {
+ if (r > 0 && u && h > 0 && gT(p.endSegmentIndex, p.endGraphemeIndex)) {
const m = cf(l.prepared, Fl, Math.max(1, s - l.extraWidth));
if (m !== null && (m.endSegmentIndex > p.endSegmentIndex || m.endSegmentIndex === p.endSegmentIndex && m.endGraphemeIndex > p.endGraphemeIndex))
break e;
@@ -30760,12 +30760,12 @@ function xT(i, e, t, n) {
}
return r === 0 ? null : (t.itemIndex = o, t.segmentIndex = c.segmentIndex, t.graphemeIndex = c.graphemeIndex, r);
}
-function bT(i, e, t = Tx) {
+function xT(i, e, t = Bx) {
const n = i, s = {
itemIndex: t.itemIndex,
segmentIndex: t.segmentIndex,
graphemeIndex: t.graphemeIndex
- }, r = [], a = xT(n, e, s, (o, c, l, h, u) => {
+ }, r = [], a = mT(n, e, s, (o, c, l, h, u) => {
r.push({
itemIndex: o.sourceItemIndex,
gapBefore: c,
@@ -30780,14 +30780,14 @@ function bT(i, e, t = Tx) {
end: s
};
}
-function ET(i, e) {
- return dT(i.prepared, {
+function bT(i, e) {
+ return uT(i.prepared, {
width: e.occupiedWidth - i.extraWidth,
start: e.start,
end: e.end
}).text;
}
-function Fx(i, e) {
+function Rx(i, e) {
const t = i;
return {
fragments: e.fragments.map((n) => {
@@ -30796,24 +30796,24 @@ function Fx(i, e) {
throw new Error("Missing rich-text inline item for fragment");
return {
...n,
- text: ET(s, n)
+ text: bT(s, n)
};
}),
width: e.width,
end: e.end
};
}
-function Nx(i, e, t) {
- let n = 0, s = Tx;
+function Fx(i, e, t) {
+ let n = 0, s = Bx;
for (; ; ) {
- const r = bT(i, e, s);
+ const r = xT(i, e, s);
if (r === null)
return n;
t(r), n++, s = r.end;
}
}
-const Og = "500 14px Inter, sans-serif", Nu = "600 10px Inter, sans-serif", Du = "300 13px Inter, sans-serif", Qg = "600 10px Inter, sans-serif", Gg = "300 12px Inter, sans-serif", go = 18, hl = 16, hn = 16, Li = 6, Hg = 12, ul = Math.min(window.devicePixelRatio || 1, 2), yT = "rgba(0, 0, 0, 0.75)", _T = "rgba(255, 255, 255, 0.08)", wT = "rgba(255, 255, 255, 0.9)", vT = "rgba(255, 255, 255, 0.30)", CT = "rgba(255, 255, 255, 0.85)", zg = "rgba(255, 255, 255, 0.08)", IT = "rgba(255, 255, 255, 0.45)", ST = "rgba(255, 255, 255, 0.08)", MT = "rgba(255, 255, 255, 0.7)";
-function BT(i) {
+const Og = "500 14px Inter, sans-serif", Nu = "600 10px Inter, sans-serif", Du = "300 13px Inter, sans-serif", Qg = "600 10px Inter, sans-serif", Gg = "300 12px Inter, sans-serif", go = 18, hl = 16, hn = 16, Li = 6, Hg = 12, ul = Math.min(window.devicePixelRatio || 1, 2), ET = "rgba(0, 0, 0, 0.75)", yT = "rgba(255, 255, 255, 0.08)", _T = "rgba(255, 255, 255, 0.9)", wT = "rgba(255, 255, 255, 0.30)", vT = "rgba(255, 255, 255, 0.85)", zg = "rgba(255, 255, 255, 0.08)", CT = "rgba(255, 255, 255, 0.45)", IT = "rgba(255, 255, 255, 0.08)", ST = "rgba(255, 255, 255, 0.7)";
+function MT(i) {
let e = 0, t = 0, n = 0;
const s = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set();
let o = !1, c = !1;
@@ -30843,12 +30843,12 @@ function BT(i) {
function mo(i) {
return i >= 1e6 ? (i / 1e6).toFixed(1) + "M" : i >= 1e3 ? (i / 1e3).toFixed(1) + "K" : i.toString();
}
-function TT(i, e) {
+function BT(i, e) {
const t = [];
return i.hasSkinning && t.push("skinned"), i.hasMorphs && t.push("morph targets"), e && e.length > 0 && t.push(`${e.length} animation${e.length > 1 ? "s" : ""}`), i.materialTypes.length > 0 && t.push(i.materialTypes.join(", ")), t.length > 0 ? t.join(" · ") : "";
}
-function RT(i, e, t) {
- const n = BT(e), s = TT(n, t), r = [
+function TT(i, e, t) {
+ const n = MT(e), s = BT(n, t), r = [
{ label: "MESHES", value: mo(n.meshes) },
{ label: "VERTICES", value: mo(n.vertices) },
{ label: "TRIANGLES", value: mo(n.triangles) },
@@ -30858,11 +30858,11 @@ function RT(i, e, t) {
t && t.length > 0 && r.push({ label: "ANIMATIONS", value: t.length.toString() });
const a = [];
n.materialTypes.forEach((w) => a.push(w)), n.hasSkinning && a.push("Skinned"), n.hasMorphs && a.push("Morph"), t && t.length > 0 && a.push("Animated");
- const o = 200, c = cl("Model Info", Og), l = oT(c, o, go + 2), h = r.map((w) => {
+ const o = 200, c = cl("Model Info", Og), l = aT(c, o, go + 2), h = r.map((w) => {
const I = [
{ text: w.label + " ", font: Nu },
{ text: w.value, font: Du }
- ], T = Rx(I), C = cl(w.label, Nu), v = Ru(C, o), F = cl(w.value, Du), K = Ru(F, o);
+ ], T = Tx(I), C = cl(w.label, Nu), v = Ru(C, o), F = cl(w.value, Du), K = Ru(F, o);
return {
...w,
labelWidth: v.maxLineWidth,
@@ -30875,7 +30875,7 @@ function RT(i, e, t) {
});
let d = [], f = 0;
if (s) {
- const w = nh(s, Gg), I = pT(w, o - hn, go);
+ const w = nh(s, Gg), I = fT(w, o - hn, go);
d = I.lines, f = I.height;
}
const p = Math.max(
@@ -30897,17 +30897,17 @@ function RT(i, e, t) {
hn, _ = document.createElement("canvas");
_.width = m * ul, _.height = A * ul, _.style.width = m + "px", _.style.height = A + "px";
const x = _.getContext("2d");
- x.scale(ul, ul), x.fillStyle = yT, Lu(x, 0, 0, m, A, 10), x.fill(), x.strokeStyle = _T, x.lineWidth = 1, Lu(x, 0.5, 0.5, m - 1, A - 1, 10), x.stroke();
+ x.scale(ul, ul), x.fillStyle = ET, Lu(x, 0, 0, m, A, 10), x.fill(), x.strokeStyle = yT, x.lineWidth = 1, Lu(x, 0.5, 0.5, m - 1, A - 1, 10), x.stroke();
let E = hn;
- if (x.font = Og, x.fillStyle = wT, x.textBaseline = "top", x.fillText("Model Info", hn, E), E += l.height + Li, x.strokeStyle = zg, x.beginPath(), x.moveTo(hn, E), x.lineTo(m - hn, E), x.stroke(), E += Li, h.forEach((w) => {
- x.font = Nu, x.fillStyle = vT, x.textAlign = "left", x.fillText(w.label, hn, E), x.font = Du, x.fillStyle = CT, x.textAlign = "right", x.fillText(w.value, m - hn, E), x.textAlign = "left", E += go + Li;
+ if (x.font = Og, x.fillStyle = _T, x.textBaseline = "top", x.fillText("Model Info", hn, E), E += l.height + Li, x.strokeStyle = zg, x.beginPath(), x.moveTo(hn, E), x.lineTo(m - hn, E), x.stroke(), E += Li, h.forEach((w) => {
+ x.font = Nu, x.fillStyle = wT, x.textAlign = "left", x.fillText(w.label, hn, E), x.font = Du, x.fillStyle = vT, x.textAlign = "right", x.fillText(w.value, m - hn, E), x.textAlign = "left", E += go + Li;
}), u.length > 0) {
let w = hn;
u.forEach((I) => {
- w > hn && w + I.width > m - hn && (w = hn, E += hl + 6), x.fillStyle = ST, Lu(x, w, E, I.width, hl, 4), x.fill(), x.font = Qg, x.fillStyle = MT, x.textBaseline = "top", x.fillText(I.text, w + Hg / 2, E + 3), w += I.width + 6;
+ w > hn && w + I.width > m - hn && (w = hn, E += hl + 6), x.fillStyle = IT, Lu(x, w, E, I.width, hl, 4), x.fill(), x.font = Qg, x.fillStyle = ST, x.textBaseline = "top", x.fillText(I.text, w + Hg / 2, E + 3), w += I.width + 6;
}), E += hl + Li + 4;
}
- d.length > 0 && (x.strokeStyle = zg, x.beginPath(), x.moveTo(hn, E), x.lineTo(m - hn, E), x.stroke(), E += Li, x.font = Gg, x.fillStyle = IT, x.textBaseline = "top", d.forEach((w) => {
+ d.length > 0 && (x.strokeStyle = zg, x.beginPath(), x.moveTo(hn, E), x.lineTo(m - hn, E), x.stroke(), E += Li, x.font = Gg, x.fillStyle = CT, x.textBaseline = "top", d.forEach((w) => {
x.fillText(w.text, hn, E), E += go;
}));
const S = document.createElement("div");
@@ -30922,20 +30922,20 @@ function RT(i, e, t) {
function Lu(i, e, t, n, s, r) {
i.beginPath(), i.moveTo(e + r, t), i.lineTo(e + n - r, t), i.quadraticCurveTo(e + n, t, e + n, t + r), i.lineTo(e + n, t + s - r), i.quadraticCurveTo(e + n, t + s, e + n - r, t + s), i.lineTo(e + r, t + s), i.quadraticCurveTo(e, t + s, e, t + s - r), i.lineTo(e, t + r), i.quadraticCurveTo(e, t, e + r, t), i.closePath();
}
-const FT = "500 11px Inter, sans-serif", Vg = "300 10px Inter, sans-serif", lf = 10, Dx = 6, Lx = 14, dl = Math.min(window.devicePixelRatio || 1, 2), NT = 8;
-function DT(i) {
+const RT = "500 11px Inter, sans-serif", Vg = "300 10px Inter, sans-serif", lf = 10, Nx = 6, Dx = 14, dl = Math.min(window.devicePixelRatio || 1, 2), FT = 8;
+function NT(i) {
const e = [];
return i.traverse((t) => {
- if (e.length >= NT || !t.isMesh || !t.name || t.name.startsWith("_")) return;
- const n = t.geometry, s = Array.isArray(t.material) ? t.material[0] : t.material, r = n && n.attributes.position ? n.attributes.position.count : 0, a = s ? s.type.replace("Material", "") : "", o = [{ text: t.name, font: FT }];
- r > 0 && o.push({ text: " " + PT(r) + " verts", font: Vg }), a && o.push({ text: " " + a, font: Vg });
- const c = Rx(o);
+ if (e.length >= FT || !t.isMesh || !t.name || t.name.startsWith("_")) return;
+ const n = t.geometry, s = Array.isArray(t.material) ? t.material[0] : t.material, r = n && n.attributes.position ? n.attributes.position.count : 0, a = s ? s.type.replace("Material", "") : "", o = [{ text: t.name, font: RT }];
+ r > 0 && o.push({ text: " " + LT(r) + " verts", font: Vg }), a && o.push({ text: " " + a, font: Vg });
+ const c = Tx(o);
let l = 0, h = 0;
- Nx(c, 300, (m) => {
- const g = Fx(c, m);
+ Fx(c, 300, (m) => {
+ const g = Rx(c, m);
l = Math.max(l, g.width), h++;
});
- const u = l + lf * 2, d = h * Lx + Dx * 2;
+ const u = l + lf * 2, d = h * Dx + Nx * 2;
n && n.computeBoundingBox();
const f = n ? n.boundingBox : null, p = new G();
f ? (f.getCenter(p), p.applyMatrix4(t.matrixWorld)) : t.getWorldPosition(p), e.push({
@@ -30950,30 +30950,30 @@ function DT(i) {
});
}), e;
}
-function LT(i) {
+function DT(i) {
const { labelWidth: e, labelHeight: t, items: n, prepared: s } = i, r = document.createElement("canvas");
r.width = e * dl, r.height = t * dl, r.style.width = e + "px", r.style.height = t + "px";
const a = r.getContext("2d");
a.scale(dl, dl), a.fillStyle = "rgba(0, 0, 0, 0.8)", Wg(a, 0, 0, e, t, 6), a.fill(), a.strokeStyle = "rgba(255, 255, 255, 0.1)", a.lineWidth = 1, Wg(a, 0.5, 0.5, e - 1, t - 1, 6), a.stroke(), a.textBaseline = "top";
- let o = Dx;
- return Nx(s, e - lf * 2, (c) => {
- const l = Fx(s, c);
+ let o = Nx;
+ return Fx(s, e - lf * 2, (c) => {
+ const l = Rx(s, c);
let h = lf;
l.fragments.forEach((u) => {
h += u.gapBefore;
const d = n[u.itemIndex];
a.font = d.font, a.fillStyle = u.itemIndex === 0 ? "rgba(255, 255, 255, 0.9)" : "rgba(255, 255, 255, 0.45)", a.fillText(u.text, h, o), h += u.occupiedWidth;
- }), o += Lx;
+ }), o += Dx;
}), r;
}
-function PT(i) {
+function LT(i) {
return i >= 1e6 ? (i / 1e6).toFixed(1) + "M" : i >= 1e3 ? (i / 1e3).toFixed(1) + "K" : i.toString();
}
function Wg(i, e, t, n, s, r) {
i.beginPath(), i.moveTo(e + r, t), i.lineTo(e + n - r, t), i.quadraticCurveTo(e + n, t, e + n, t + r), i.lineTo(e + n, t + s - r), i.quadraticCurveTo(e + n, t + s, e + n - r, t + s), i.lineTo(e + r, t + s), i.quadraticCurveTo(e, t + s, e, t + s - r), i.lineTo(e, t + r), i.quadraticCurveTo(e, t, e + r, t), i.closePath();
}
const Pu = /* @__PURE__ */ new WeakMap();
-class kT extends pi {
+class PT extends pi {
/**
* Constructs a new Draco loader.
*
@@ -31109,7 +31109,7 @@ class kT extends pi {
return e ? t.push(this._loadLibrary("draco_decoder.js", "text")) : (t.push(this._loadLibrary("draco_wasm_wrapper.js", "text")), t.push(this._loadLibrary("draco_decoder.wasm", "arraybuffer"))), this.decoderPending = Promise.all(t).then((n) => {
const s = n[0];
e || (this.decoderConfig.wasmBinary = n[1]);
- const r = UT.toString(), a = [
+ const r = kT.toString(), a = [
"/* draco decoder */",
s,
"",
@@ -31157,7 +31157,7 @@ class kT extends pi {
return this.workerPool.length = 0, this.workerSourceURL !== "" && URL.revokeObjectURL(this.workerSourceURL), this;
}
}
-function UT() {
+function kT() {
let i, e;
onmessage = function(a) {
const o = a.data;
@@ -31247,7 +31247,7 @@ function UT() {
}
}
}
-class OT {
+class UT {
/**
* Constructs a new Worker pool.
*
@@ -31313,8 +31313,8 @@ class OT {
this.workers.forEach((e) => e.terminate()), this.workersResolve.length = 0, this.workers.length = 0, this.queue.length = 0, this.workerStatus = 0;
}
}
-const QT = 0, qg = 2, GT = 1, Kg = 2, HT = 0, zT = 1, VT = 10, WT = 0, Px = 9, kx = 15, Ux = 16, Ox = 22, Qx = 37, Gx = 43, Hx = 76, zx = 83, Vx = 97, Wx = 100, qx = 103, Kx = 109, jx = 165, Xx = 166, mp = 1000066e3;
-class qT {
+const OT = 0, qg = 2, QT = 1, Kg = 2, GT = 0, HT = 1, zT = 10, VT = 0, Lx = 9, Px = 15, kx = 16, Ux = 22, Ox = 37, Qx = 43, Gx = 76, Hx = 83, zx = 97, Vx = 100, Wx = 103, qx = 109, Kx = 165, jx = 166, mp = 1000066e3;
+class WT {
constructor() {
this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null;
}
@@ -31362,10 +31362,10 @@ const Ln = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10];
function jg(i) {
return new TextDecoder().decode(i);
}
-function KT(i) {
+function qT(i) {
const e = new Uint8Array(i.buffer, i.byteOffset, Ln.length);
if (e[0] !== Ln[0] || e[1] !== Ln[1] || e[2] !== Ln[2] || e[3] !== Ln[3] || e[4] !== Ln[4] || e[5] !== Ln[5] || e[6] !== Ln[6] || e[7] !== Ln[7] || e[8] !== Ln[8] || e[9] !== Ln[9] || e[10] !== Ln[10] || e[11] !== Ln[11]) throw new Error("Missing KTX 2.0 identifier.");
- const t = new qT(), n = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new xo(i, Ln.length, n, !0);
+ const t = new WT(), n = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new xo(i, Ln.length, n, !0);
t.vkFormat = s._nextUint32(), t.typeSize = s._nextUint32(), t.pixelWidth = s._nextUint32(), t.pixelHeight = s._nextUint32(), t.pixelDepth = s._nextUint32(), t.layerCount = s._nextUint32(), t.faceCount = s._nextUint32();
const r = s._nextUint32();
t.supercompressionScheme = s._nextUint32();
@@ -31396,7 +31396,7 @@ let ku, ts, hf;
const Uu = { env: { emscripten_notify_memory_growth: function(i) {
hf = new Uint8Array(ts.exports.memory.buffer);
} } };
-class jT {
+class KT {
init() {
return ku || (ku = typeof fetch < "u" ? fetch("data:application/wasm;base64," + Xg).then((e) => e.arrayBuffer()).then((e) => WebAssembly.instantiate(e, Uu)).then(this._init) : WebAssembly.instantiate(Buffer.from(Xg, "base64"), Uu).then(this._init), ku);
}
@@ -31411,7 +31411,7 @@ class jT {
return ts.exports.free(s), ts.exports.free(r), o;
}
}
-const Xg = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/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ADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQ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QiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQE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RAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgE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AAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ", XT = "display-p3", YT = "display-p3-linear", Ou = /* @__PURE__ */ new WeakMap();
+const Xg = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/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iEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQ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iBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQ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= "display-p3", XT = "display-p3-linear", Ou = /* @__PURE__ */ new WeakMap();
let Qu = 0, Gu;
class ci extends pi {
/**
@@ -31420,7 +31420,7 @@ class ci extends pi {
* @param {LoadingManager} [manager] - The loading manager.
*/
constructor(e) {
- super(e), this.transcoderPath = "", this.transcoderBinary = null, this.transcoderPending = null, this.workerPool = new OT(), this.workerSourceURL = "", this.workerConfig = null, typeof MSC_TRANSCODER < "u" && console.warn(
+ super(e), this.transcoderPath = "", this.transcoderBinary = null, this.transcoderPending = null, this.workerPool = new UT(), this.workerSourceURL = "", this.workerConfig = null, typeof MSC_TRANSCODER < "u" && console.warn(
'THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.'
);
}
@@ -31558,12 +31558,12 @@ class ci extends pi {
if (n === "error") return Promise.reject(s);
let u;
if (t.faceCount === 6)
- u = new K_(r, c, l);
+ u = new q_(r, c, l);
else {
const d = r[0].mipmaps;
- u = t.layerCount > 1 ? new q_(d, a, o, t.layerCount, c, l) : new Eh(d, a, o, c, l);
+ u = t.layerCount > 1 ? new W_(d, a, o, t.layerCount, c, l) : new Eh(d, a, o, c, l);
}
- return u.minFilter = r[0].mipmaps.length === 1 ? Xt : ui, u.magFilter = Xt, u.generateMipmaps = !1, u.needsUpdate = !0, u.colorSpace = Yx(t), u.premultiplyAlpha = !!(h & GT), u;
+ return u.minFilter = r[0].mipmaps.length === 1 ? Xt : ui, u.magFilter = Xt, u.generateMipmaps = !1, u.needsUpdate = !0, u.colorSpace = Xx(t), u.premultiplyAlpha = !!(h & QT), u;
}
/**
* @private
@@ -31572,9 +31572,9 @@ class ci extends pi {
* @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
*/
async _createTexture(e, t = {}) {
- const n = KT(new Uint8Array(e)), s = n.vkFormat === mp && n.dataFormatDescriptor[0].colorModel === 167;
- if (!(n.vkFormat === WT || s && !this.workerConfig.astcHDRSupported))
- return ZT(n);
+ const n = qT(new Uint8Array(e)), s = n.vkFormat === mp && n.dataFormatDescriptor[0].colorModel === 167;
+ if (!(n.vkFormat === VT || s && !this.workerConfig.astcHDRSupported))
+ return JT(n);
const a = t, o = this.init().then(() => this.workerPool.postMessage({ type: "transcode", buffer: e, taskConfig: a }, [e])).then((c) => this._createTextureFrom(c.data, n));
return Ou.set(e, { promise: o }), o;
}
@@ -31828,53 +31828,53 @@ ci.BasisWorker = function() {
return g;
}
};
-const JT = /* @__PURE__ */ new Set([pn, Er, cs]), Hu = {
- [Kx]: pn,
- [Vx]: pn,
+const YT = /* @__PURE__ */ new Set([pn, Er, cs]), Hu = {
+ [qx]: pn,
+ [zx]: pn,
+ [Ox]: pn,
[Qx]: pn,
- [Gx]: pn,
- [qx]: Er,
- [zx]: Er,
+ [Wx]: Er,
+ [Hx]: Er,
+ [kx]: Er,
[Ux]: Er,
- [Ox]: Er,
- [Wx]: cs,
- [Hx]: cs,
- [kx]: cs,
+ [Vx]: cs,
+ [Gx]: cs,
[Px]: cs,
+ [Lx]: cs,
[mp]: Wo,
- [Xx]: qo,
- [jx]: qo
+ [jx]: qo,
+ [Kx]: qo
}, zu = {
- [Kx]: fn,
- [Vx]: Gn,
- [Qx]: un,
- [Gx]: un,
[qx]: fn,
[zx]: Gn,
- [Ux]: un,
[Ox]: un,
+ [Qx]: un,
[Wx]: fn,
[Hx]: Gn,
[kx]: un,
+ [Ux]: un,
+ [Vx]: fn,
+ [Gx]: Gn,
[Px]: un,
+ [Lx]: un,
[mp]: Gn,
- [Xx]: un,
- [jx]: un
+ [jx]: un,
+ [Kx]: un
};
-async function ZT(i) {
+async function JT(i) {
const { vkFormat: e } = i;
if (Hu[e] === void 0)
throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");
let t;
i.supercompressionScheme === qg && (Gu || (Gu = new Promise(async (r) => {
- const a = new jT();
+ const a = new KT();
await a.init(), r(a);
})), t = await Gu);
const n = [];
for (let r = 0; r < i.levels.length; r++) {
const a = Math.max(1, i.pixelWidth >> r), o = Math.max(1, i.pixelHeight >> r), c = i.pixelDepth ? Math.max(1, i.pixelDepth >> r) : 0, l = i.levels[r];
let h;
- if (i.supercompressionScheme === QT)
+ if (i.supercompressionScheme === OT)
h = l.levelData;
else if (i.supercompressionScheme === qg)
h = t.decode(l.levelData, l.uncompressedByteLength);
@@ -31897,22 +31897,22 @@ async function ZT(i) {
});
}
let s;
- if (JT.has(Hu[e]))
- s = i.pixelDepth === 0 ? new gh(n[0].data, i.pixelWidth, i.pixelHeight) : new N0(n[0].data, i.pixelWidth, i.pixelHeight, i.pixelDepth);
+ if (YT.has(Hu[e]))
+ s = i.pixelDepth === 0 ? new gh(n[0].data, i.pixelWidth, i.pixelHeight) : new F0(n[0].data, i.pixelWidth, i.pixelHeight, i.pixelDepth);
else {
if (i.pixelDepth > 0) throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");
s = new Eh(n, i.pixelWidth, i.pixelHeight), s.minFilter = n.length === 1 ? Xt : ui, s.magFilter = Xt;
}
- return s.mipmaps = n, s.type = zu[e], s.format = Hu[e], s.colorSpace = Yx(i), s.needsUpdate = !0, Promise.resolve(s);
+ return s.mipmaps = n, s.type = zu[e], s.format = Hu[e], s.colorSpace = Xx(i), s.needsUpdate = !0, Promise.resolve(s);
}
-function Yx(i) {
+function Xx(i) {
const e = i.dataFormatDescriptor[0];
- return e.colorPrimaries === zT ? e.transferFunction === Kg ? _t : An : e.colorPrimaries === VT ? e.transferFunction === Kg ? XT : YT : (e.colorPrimaries === HT || console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`), Ci);
+ return e.colorPrimaries === HT ? e.transferFunction === Kg ? _t : An : e.colorPrimaries === zT ? e.transferFunction === Kg ? jT : XT : (e.colorPrimaries === GT || console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`), Ci);
}
-const fl = "[default]", uf = { ASSET_GENERATOR: "assetgenerator" }, ih = new Y0(), Jx = "https://unpkg.com/[email protected]", $T = new kT(ih).setDecoderPath(
- `${Jx}/examples/jsm/libs/draco/gltf/`
-), eR = new ci(ih).setTranscoderPath(
- `${Jx}/examples/jsm/libs/basis/`
+const fl = "[default]", uf = { ASSET_GENERATOR: "assetgenerator" }, ih = new X0(), Yx = "https://unpkg.com/[email protected]", ZT = new PT(ih).setDecoderPath(
+ `${Yx}/examples/jsm/libs/draco/gltf/`
+), $T = new ci(ih).setTranscoderPath(
+ `${Yx}/examples/jsm/libs/basis/`
);
function Yg(i, e) {
const t = /* @__PURE__ */ new Set();
@@ -31923,22 +31923,22 @@ function Yg(i, e) {
});
});
}
-function tR(i) {
+function eR(i) {
const { state: e, options: t } = i;
if (t.preset === uf.ASSET_GENERATOR) {
- const r = new Sw();
+ const r = new Iw();
r.name = "hemi_light", i.scene.add(r), i.lights.push(r);
return;
}
- const n = new $0(e.ambientColor, e.ambientIntensity);
+ const n = new Z0(e.ambientColor, e.ambientIntensity);
n.name = "ambient_light", i.defaultCamera.add(n);
const s = new tp(e.directColor, e.directIntensity);
s.position.set(0.5, 0, 0.866), s.name = "main_light", i.defaultCamera.add(s), i.lights.push(n, s);
}
-function nR(i) {
+function tR(i) {
i.lights.forEach((e) => e.parent.remove(e)), i.lights.length = 0;
}
-var li = Uint8Array, ya = Uint16Array, iR = Int32Array, Zx = new li([
+var li = Uint8Array, ya = Uint16Array, nR = Int32Array, Jx = new li([
0,
0,
0,
@@ -31973,7 +31973,7 @@ var li = Uint8Array, ya = Uint16Array, iR = Int32Array, Zx = new li([
0,
/* impossible */
0
-]), $x = new li([
+]), Zx = new li([
0,
0,
0,
@@ -32007,16 +32007,16 @@ var li = Uint8Array, ya = Uint16Array, iR = Int32Array, Zx = new li([
/* unused */
0,
0
-]), sR = new li([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]), eb = function(i, e) {
+]), iR = new li([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]), $x = function(i, e) {
for (var t = new ya(31), n = 0; n < 31; ++n)
t[n] = e += 1 << i[n - 1];
- for (var s = new iR(t[30]), n = 1; n < 30; ++n)
+ for (var s = new nR(t[30]), n = 1; n < 30; ++n)
for (var r = t[n]; r < t[n + 1]; ++r)
s[r] = r - t[n] << 5 | n;
return { b: t, r: s };
-}, tb = eb(Zx, 2), nb = tb.b, rR = tb.r;
-nb[28] = 258, rR[258] = 28;
-var aR = eb($x, 0), oR = aR.b, df = new ya(32768);
+}, eb = $x(Jx, 2), tb = eb.b, sR = eb.r;
+tb[28] = 258, sR[258] = 28;
+var rR = $x(Zx, 0), aR = rR.b, df = new ya(32768);
for (var Ot = 0; Ot < 32768; ++Ot) {
var Fs = (Ot & 43690) >> 1 | (Ot & 21845) << 1;
Fs = (Fs & 52428) >> 2 | (Fs & 13107) << 2, Fs = (Fs & 61680) >> 4 | (Fs & 3855) << 4, df[Ot] = ((Fs & 65280) >> 8 | (Fs & 255) << 8) >> 1;
@@ -32048,10 +32048,10 @@ for (var Ot = 256; Ot < 280; ++Ot)
Ac[Ot] = 7;
for (var Ot = 280; Ot < 288; ++Ot)
Ac[Ot] = 8;
-var ib = new li(32);
+var nb = new li(32);
for (var Ot = 0; Ot < 32; ++Ot)
- ib[Ot] = 5;
-var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = function(i) {
+ nb[Ot] = 5;
+var oR = /* @__PURE__ */ Uo(Ac, 9, 1), cR = /* @__PURE__ */ Uo(nb, 5, 1), Vu = function(i) {
for (var e = i[0], t = 1; t < i.length; ++t)
i[t] > e && (e = i[t]);
return e;
@@ -32061,11 +32061,11 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
}, Wu = function(i, e) {
var t = e / 8 | 0;
return (i[t] | i[t + 1] << 8 | i[t + 2] << 16) >> (e & 7);
-}, hR = function(i) {
+}, lR = function(i) {
return (i + 7) / 8 | 0;
-}, uR = function(i, e, t) {
+}, hR = function(i, e, t) {
return (t == null || t > i.length) && (t = i.length), new li(i.subarray(e, t));
-}, dR = [
+}, uR = [
"unexpected EOF",
"invalid block type",
"invalid length/literal",
@@ -32082,11 +32082,11 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
"invalid zip data"
// determined by unknown compression method
], yi = function(i, e, t) {
- var n = new Error(e || dR[i]);
+ var n = new Error(e || uR[i]);
if (n.code = i, Error.captureStackTrace && Error.captureStackTrace(n, yi), !t)
throw n;
return n;
-}, fR = function(i, e, t, n) {
+}, dR = function(i, e, t, n) {
var s = i.length, r = 0;
if (!s || e.f && !e.l)
return t || new li(0);
@@ -32105,12 +32105,12 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
var _ = Ei(i, u + 1, 3);
if (u += 3, _)
if (_ == 1)
- f = cR, p = lR, m = 9, g = 5;
+ f = oR, p = cR, m = 9, g = 5;
else if (_ == 2) {
var w = Ei(i, u, 31) + 257, I = Ei(i, u + 10, 15) + 4, T = w + Ei(i, u + 5, 31) + 1;
u += 14;
for (var C = new li(T), v = new li(19), F = 0; F < I; ++F)
- v[sR[F]] = Ei(i, u + F * 3, 7);
+ v[iR[F]] = Ei(i, u + F * 3, 7);
u += I * 3;
for (var K = Vu(v), q = (1 << K) - 1, $ = Uo(v, K, 1), F = 0; F < T; ) {
var D = $[Ei(i, u, q)];
@@ -32129,7 +32129,7 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
} else
yi(1);
else {
- var x = hR(u) + 4, E = i[x - 4] | i[x - 3] << 8, S = x + E;
+ var x = lR(u) + 4, E = i[x - 4] | i[x - 3] << 8, S = x + E;
if (S > s) {
c && yi(0);
break;
@@ -32157,14 +32157,14 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
} else {
var se = Me - 254;
if (Me > 264) {
- var F = Me - 257, me = Zx[F];
- se = Ei(i, u, (1 << me) - 1) + nb[F], u += me;
+ var F = Me - 257, me = Jx[F];
+ se = Ei(i, u, (1 << me) - 1) + tb[F], u += me;
}
var xe = p[Wu(i, u) & ae], be = xe >> 4;
xe || yi(3), u += xe & 15;
- var J = oR[be];
+ var J = aR[be];
if (be > 3) {
- var me = $x[be];
+ var me = Zx[be];
J += Wu(i, u) & (1 << me) - 1, u += me;
}
if (u > A) {
@@ -32184,19 +32184,19 @@ var cR = /* @__PURE__ */ Uo(Ac, 9, 1), lR = /* @__PURE__ */ Uo(ib, 5, 1), Vu = f
}
e.l = f, e.p = _e, e.b = d, e.f = h, f && (h = 1, e.m = m, e.d = p, e.n = g);
} while (!h);
- return d != t.length && a ? uR(t, 0, d) : t.subarray(0, d);
-}, pR = /* @__PURE__ */ new li(0), AR = function(i, e) {
+ return d != t.length && a ? hR(t, 0, d) : t.subarray(0, d);
+}, fR = /* @__PURE__ */ new li(0), pR = function(i, e) {
return ((i[0] & 15) != 8 || i[0] >> 4 > 7 || (i[0] << 8 | i[1]) % 31) && yi(6, "invalid zlib data"), (i[1] >> 5 & 1) == 1 && yi(6, "invalid zlib data: " + (i[1] & 32 ? "need" : "unexpected") + " dictionary"), (i[1] >> 3 & 4) + 2;
};
function Io(i, e) {
- return fR(i.subarray(AR(i), -4), { i: 2 }, e, e);
+ return dR(i.subarray(pR(i), -4), { i: 2 }, e, e);
}
-var gR = typeof TextDecoder < "u" && /* @__PURE__ */ new TextDecoder(), mR = 0;
+var AR = typeof TextDecoder < "u" && /* @__PURE__ */ new TextDecoder(), gR = 0;
try {
- gR.decode(pR, { stream: !0 }), mR = 1;
+ AR.decode(fR, { stream: !0 }), gR = 1;
} catch {
}
-class xR extends Iw {
+class mR extends Cw {
/**
* Constructs a new EXR loader.
*
@@ -33131,10 +33131,10 @@ class xR extends Iw {
return super.load(e, r, n, s);
}
}
-function bR(i, e) {
+function xR(i, e) {
const { id: t, path: n } = e;
return t === "neutral" ? Promise.resolve({ envMap: i.neutralEnvironment }) : t === "" ? Promise.resolve({ envMap: null }) : new Promise((s, r) => {
- new xR().load(
+ new mR().load(
n,
(a) => {
const o = i.pmremGenerator.fromEquirectangular(a).texture;
@@ -33145,26 +33145,26 @@ function bR(i, e) {
);
});
}
-function ER(i) {
+function bR(i) {
i.renderer.render(i.scene, i.activeCamera), i.renderer.domElement.toBlob((e) => {
if (!e) return;
const t = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19), n = URL.createObjectURL(e), s = document.createElement("a");
s.download = `3d-screenshot-${t}.png`, s.href = n, s.click(), URL.revokeObjectURL(n);
- }, "image/png"), yR(i);
+ }, "image/png"), ER(i);
}
-function yR(i) {
+function ER(i) {
const e = document.createElement("div");
e.className = "screenshot-flash", i.el.appendChild(e), e.addEventListener("animationend", () => e.remove());
}
-function _R(i, e) {
- i.mixer && (i.mixer.stopAllAction(), i.mixer.uncacheRoot(i.mixer.getRoot()), i.mixer = null), i.clips = e, e.length && (i.mixer = new ex(i.content));
+function yR(i, e) {
+ i.mixer && (i.mixer.stopAllAction(), i.mixer.uncacheRoot(i.mixer.getRoot()), i.mixer = null), i.clips = e, e.length && (i.mixer = new $0(i.content));
}
-function wR(i) {
+function _R(i) {
i.clips.forEach((e) => {
i.mixer.clipAction(e).reset().play(), i.state.actionStates[e.name] = !0;
}), i.invalidate();
}
-function sb(i, e, t) {
+function ib(i, e, t) {
const n = t.length - i - 1;
if (e >= t[n])
return n - 1;
@@ -33175,7 +33175,7 @@ function sb(i, e, t) {
e < t[a] ? r = a : s = a, a = Math.floor((s + r) / 2);
return a;
}
-function vR(i, e, t, n) {
+function wR(i, e, t, n) {
const s = [], r = [], a = [];
s[0] = 1;
for (let o = 1; o <= t; ++o) {
@@ -33189,15 +33189,15 @@ function vR(i, e, t, n) {
}
return s;
}
-function CR(i, e, t, n) {
- const s = sb(i, n, e), r = vR(s, n, i, e), a = new mt(0, 0, 0, 0);
+function vR(i, e, t, n) {
+ const s = ib(i, n, e), r = wR(s, n, i, e), a = new mt(0, 0, 0, 0);
for (let o = 0; o <= i; ++o) {
const c = t[s - i + o], l = r[o], h = c.w * l;
a.x += c.x * h, a.y += c.y * h, a.z += c.z * h, a.w += c.w * l;
}
return a;
}
-function IR(i, e, t, n, s) {
+function CR(i, e, t, n, s) {
const r = [];
for (let u = 0; u <= t; ++u)
r[u] = 0;
@@ -33248,8 +33248,8 @@ function IR(i, e, t, n, s) {
}
return a;
}
-function SR(i, e, t, n, s) {
- const r = s < i ? s : i, a = [], o = sb(i, n, e), c = IR(o, n, i, r, e), l = [];
+function IR(i, e, t, n, s) {
+ const r = s < i ? s : i, a = [], o = ib(i, n, e), c = CR(o, n, i, r, e), l = [];
for (let h = 0; h < t.length; ++h) {
const u = t[h].clone(), d = u.w;
u.x *= d, u.y *= d, u.z *= d, l[h] = u;
@@ -33264,7 +33264,7 @@ function SR(i, e, t, n, s) {
a[h] = new mt(0, 0, 0);
return a;
}
-function MR(i, e) {
+function SR(i, e) {
let t = 1;
for (let s = 2; s <= i; ++s)
t *= s;
@@ -33275,7 +33275,7 @@ function MR(i, e) {
n *= s;
return t / n;
}
-function BR(i) {
+function MR(i) {
const e = i.length, t = [], n = [];
for (let r = 0; r < e; ++r) {
const a = i[r];
@@ -33285,16 +33285,16 @@ function BR(i) {
for (let r = 0; r < e; ++r) {
const a = t[r].clone();
for (let o = 1; o <= r; ++o)
- a.sub(s[r - o].clone().multiplyScalar(MR(r, o) * n[o]));
+ a.sub(s[r - o].clone().multiplyScalar(SR(r, o) * n[o]));
s[r] = a.divideScalar(n[0]);
}
return s;
}
-function TR(i, e, t, n, s) {
- const r = SR(i, e, t, n, s);
- return BR(r);
+function BR(i, e, t, n, s) {
+ const r = IR(i, e, t, n, s);
+ return MR(r);
}
-class RR extends j_ {
+class TR extends K_ {
/**
* Constructs a new NURBS curve.
*
@@ -33321,7 +33321,7 @@ class RR extends j_ {
* @return {Vector3} The position on the curve.
*/
getPoint(e, t = new G()) {
- const n = t, s = this.knots[this.startKnot] + e * (this.knots[this.endKnot] - this.knots[this.startKnot]), r = CR(this.degree, this.knots, this.controlPoints, s);
+ const n = t, s = this.knots[this.startKnot] + e * (this.knots[this.endKnot] - this.knots[this.startKnot]), r = vR(this.degree, this.knots, this.controlPoints, s);
return r.w !== 1 && r.divideScalar(r.w), n.set(r.x, r.y, r.z);
}
/**
@@ -33332,7 +33332,7 @@ class RR extends j_ {
* @return {Vector3} The tangent vector.
*/
getTangent(e, t = new G()) {
- const n = t, s = this.knots[0] + e * (this.knots[this.knots.length - 1] - this.knots[0]), r = TR(this.degree, this.knots, this.controlPoints, s, 1);
+ const n = t, s = this.knots[0] + e * (this.knots[this.knots.length - 1] - this.knots[0]), r = BR(this.degree, this.knots, this.controlPoints, s, 1);
return n.copy(r[1]).normalize(), n;
}
toJSON() {
@@ -33344,7 +33344,7 @@ class RR extends j_ {
}
}
let ut, Yt, Un;
-class FR extends pi {
+class RR extends pi {
/**
* Constructs a new FBX loader.
*
@@ -33380,27 +33380,27 @@ class FR extends pi {
* @return {Group} An object representing the parsed asset.
*/
parse(e, t) {
- if (UR(e))
- ut = new kR().parse(e);
+ if (kR(e))
+ ut = new PR().parse(e);
else {
- const s = ob(e);
- if (!OR(s))
+ const s = ab(e);
+ if (!UR(s))
throw new Error("THREE.FBXLoader: Unknown format.");
if (Zg(s) < 7e3)
throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + Zg(s));
- ut = new PR().parse(s);
+ ut = new LR().parse(s);
}
- const n = new J0(this.manager).setPath(this.resourcePath || t).setCrossOrigin(this.crossOrigin);
- return new NR(n, this.manager).parse(ut);
+ const n = new Y0(this.manager).setPath(this.resourcePath || t).setCrossOrigin(this.crossOrigin);
+ return new FR(n, this.manager).parse(ut);
}
}
-class NR {
+class FR {
constructor(e, t) {
this.textureLoader = e, this.manager = t;
}
parse() {
Yt = this.parseConnections();
- const e = this.parseImages(), t = this.parseTextures(e), n = this.parseMaterials(t), s = this.parseDeformers(), r = new DR().parse(s);
+ const e = this.parseImages(), t = this.parseTextures(e), n = this.parseMaterials(t), s = this.parseDeformers(), r = new NR().parse(s);
return this.parseScene(s, r, n), Un;
}
// Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
@@ -33549,7 +33549,7 @@ class NR {
o = new Zc();
break;
case "lambert":
- o = new fw();
+ o = new dw();
break;
default:
console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', r), o = new Zc();
@@ -33684,11 +33684,11 @@ class NR {
}), this.bindSkeleton(e.skeletons, t, s), this.addGlobalSceneSettings(), Un.traverse(function(c) {
if (c.userData.transformData) {
c.parent && (c.userData.transformData.parentMatrix = c.parent.matrix, c.userData.transformData.parentMatrixWorld = c.parent.matrixWorld);
- const l = ab(c.userData.transformData);
+ const l = rb(c.userData.transformData);
c.applyMatrix4(l), c.updateWorldMatrix();
}
});
- const o = new LR().parse();
+ const o = new DR().parse();
Un.children.length === 1 && Un.children[0].isGroup && (Un.children[0].animations = o, Un = Un.children[0]), Un.animations = o;
}
// parse nodes in FBXTree.Objects.Model
@@ -33803,7 +33803,7 @@ class NR {
let l = Math.PI / 3;
n.InnerAngle !== void 0 && (l = Cn.degToRad(n.InnerAngle.value));
let h = 0;
- n.OuterAngle !== void 0 && (h = Cn.degToRad(n.OuterAngle.value), h = Math.max(h, 1)), t = new Z0(r, a, o, l, h, c);
+ n.OuterAngle !== void 0 && (h = Cn.degToRad(n.OuterAngle.value), h = Math.max(h, 1)), t = new J0(r, a, o, l, h, c);
break;
default:
console.warn("THREE.FBXLoader: Unknown light type " + n.LightType.value + ", defaulting to a PointLight."), t = new Zl(r, a);
@@ -33834,7 +33834,7 @@ class NR {
o.push(l);
}
}
- return r.FBX_Deformer ? (s = new Q0(r, a), s.normalizeSkinWeights()) : s = new Zt(r, a), s;
+ return r.FBX_Deformer ? (s = new O0(r, a), s.normalizeSkinWeights()) : s = new Zt(r, a), s;
}
createCurve(e, t) {
const n = e.children.reduce(function(r, a) {
@@ -33896,14 +33896,14 @@ class NR {
const e = ut.GlobalSettings.AmbientColor.value, t = e[0], n = e[1], s = e[2];
if (t !== 0 || n !== 0 || s !== 0) {
const r = new Le().setRGB(t, n, s, _t);
- Un.add(new $0(r, 1));
+ Un.add(new Z0(r, 1));
}
}
"UnitScaleFactor" in ut.GlobalSettings && (Un.userData.unitScaleFactor = ut.GlobalSettings.UnitScaleFactor.value);
}
}
}
-class DR {
+class NR {
constructor() {
this.negativeMaterialIndices = !1;
}
@@ -33942,7 +33942,7 @@ class DR {
});
const c = a[0], l = {};
"RotationOrder" in c && (l.eulerOrder = tc(c.RotationOrder.value)), "InheritType" in c && (l.inheritType = parseInt(c.InheritType.value)), "GeometricTranslation" in c && (l.translation = c.GeometricTranslation.value), "GeometricRotation" in c && (l.rotation = c.GeometricRotation.value), "GeometricScaling" in c && (l.scale = c.GeometricScaling.value);
- const h = ab(l);
+ const h = rb(l);
return this.genGeometry(t, o, r, h);
}
// Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
@@ -34190,11 +34190,11 @@ class DR {
for (let u = 0; u < n; ++u)
r.push(r[u]);
}
- const h = new RR(n, s, r, o, c).getPoints(r.length * 12);
+ const h = new TR(n, s, r, o, c).getPoints(r.length * 12);
return new Tn().setFromPoints(h);
}
}
-class LR {
+class DR {
// take raw animation clips and turn them into three.js animation clips
parse() {
const e = [], t = this.parseClips();
@@ -34238,7 +34238,7 @@ class LR {
for (const n in t) {
const s = {
id: t[n].id,
- times: t[n].KeyTime.a.map(QR),
+ times: t[n].KeyTime.a.map(OR),
values: t[n].KeyValueFloat.a
}, r = Yt.get(s.id);
if (r !== void 0) {
@@ -34447,7 +34447,7 @@ class LR {
return [r, a];
}
}
-class PR {
+class LR {
getPrevNode() {
return this.nodeStack[this.currentIndent - 2];
}
@@ -34467,7 +34467,7 @@ class PR {
this.currentProp = e, this.currentPropName = t;
}
parse(e) {
- this.currentIndent = 0, this.allNodes = new rb(), this.nodeStack = [], this.currentProp = [], this.currentPropName = "";
+ this.currentIndent = 0, this.allNodes = new sb(), this.nodeStack = [], this.currentProp = [], this.currentPropName = "";
const t = this, n = e.split(/[\r\n]+/);
return n.forEach(function(s, r) {
const a = s.match(/^[\s\t]*;/), o = s.match(/^[\s\t]*$/);
@@ -34501,7 +34501,7 @@ class PR {
let u = r.split(",").slice(3);
u = u.map(function(d) {
return d.trim().replace(/^"/, "");
- }), s = "connections", r = [l, h], HR(r, u), a[s] === void 0 && (a[s] = []);
+ }), s = "connections", r = [l, h], GR(r, u), a[s] === void 0 && (a[s] = []);
}
s === "Node" && (a.id = r), s in a && Array.isArray(a[s]) ? a[s].push(r) : s !== "a" ? a[s] = r : a.a = r, this.setCurrentProp(a, s), s === "a" && r.slice(-1) !== "," && (a.a = Ku(r));
}
@@ -34542,14 +34542,14 @@ class PR {
}, this.setCurrentProp(this.getPrevNode(), r);
}
}
-class kR {
+class PR {
parse(e) {
const t = new Jg(e);
t.skip(23);
const n = t.getUint32();
if (n < 6400)
throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + n);
- const s = new rb();
+ const s = new sb();
for (; !this.endOfContent(t); ) {
const r = this.parseNode(t, n);
r !== null && s.add(r.name, r);
@@ -34766,16 +34766,16 @@ class Jg {
return s >= 0 && (n = new Uint8Array(this.dv.buffer, t, s)), this._textDecoder.decode(n);
}
}
-class rb {
+class sb {
add(e, t) {
this[e] = t;
}
}
-function UR(i) {
+function kR(i) {
const e = "Kaydara FBX Binary \0";
- return i.byteLength >= e.length && e === ob(i, 0, e.length);
+ return i.byteLength >= e.length && e === ab(i, 0, e.length);
}
-function OR(i) {
+function UR(i) {
const e = ["K", "a", "y", "d", "a", "r", "a", "\\", "F", "B", "X", "\\", "B", "i", "n", "a", "r", "y", "\\", "\\"];
let t = 0;
function n(s) {
@@ -34793,10 +34793,10 @@ function Zg(i) {
return parseInt(t[1]);
throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.");
}
-function QR(i) {
+function OR(i) {
return i / 46186158e3;
}
-const GR = [];
+const QR = [];
function pl(i, e, t, n) {
let s;
switch (n.mappingType) {
@@ -34817,10 +34817,10 @@ function pl(i, e, t, n) {
}
n.referenceType === "IndexToDirect" && (s = n.indices[s]);
const r = s * n.dataSize, a = r + n.dataSize;
- return zR(GR, n.buffer, r, a);
+ return HR(QR, n.buffer, r, a);
}
const qu = new dn(), ha = new G();
-function ab(i) {
+function rb(i) {
const e = new Ne(), t = new Ne(), n = new Ne(), s = new Ne(), r = new Ne(), a = new Ne(), o = new Ne(), c = new Ne(), l = new Ne(), h = new Ne(), u = new Ne(), d = new Ne(), f = i.inheritType ? i.inheritType : 0;
i.translation && e.setPosition(ha.fromArray(i.translation));
const p = tc(0);
@@ -34879,22 +34879,22 @@ function Ku(i) {
return parseFloat(t);
});
}
-function ob(i, e, t) {
+function ab(i, e, t) {
return e === void 0 && (e = 0), t === void 0 && (t = i.byteLength), new TextDecoder().decode(new Uint8Array(i, e, t));
}
-function HR(i, e) {
+function GR(i, e) {
for (let t = 0, n = i.length, s = e.length; t < s; t++, n++)
i[n] = e[t];
}
-function zR(i, e, t, n) {
+function HR(i, e, t, n) {
for (let s = t, r = 0; s < n; s++, r++)
i[r] = e[s];
return i;
}
-const VR = 0.35;
-class WR {
+const zR = 0.35;
+class VR {
constructor() {
- this.model = null, this.mixer = null, this.clips = /* @__PURE__ */ new Map(), this.actions = /* @__PURE__ */ new Map(), this.currentName = null, this.currentAction = null, this.loader = new rp(), this.fbxLoader = new FR(), this.onChange = null, this._gltfCache = /* @__PURE__ */ new Map(), this._animationDefs = [];
+ this.model = null, this.mixer = null, this.clips = /* @__PURE__ */ new Map(), this.actions = /* @__PURE__ */ new Map(), this.currentName = null, this.currentAction = null, this.loader = new rp(), this.fbxLoader = new RR(), this.onChange = null, this._gltfCache = /* @__PURE__ */ new Map(), this._animationDefs = [];
}
/**
* Attach the manager to a loaded model. Creates a new mixer.
@@ -34902,7 +34902,7 @@ class WR {
* @param {THREE.Object3D} model
*/
attach(e) {
- this.detach(), this.model = e, this.mixer = new ex(e), this.actions.clear(), this.currentAction = null, this.currentName = null;
+ this.detach(), this.model = e, this.mixer = new $0(e), this.actions.clear(), this.currentAction = null, this.currentName = null;
for (const [t, n] of this.clips) {
const s = this._retargetClip(n, t), r = this.mixer.clipAction(s);
r.enabled = !0, this.actions.set(t, r);
@@ -34957,7 +34957,7 @@ class WR {
throw new Error(`No animation found in ${t}`);
if (r = r.clone(), r.name = e, this.clips.set(e, r), this.model && this.mixer) {
const a = this._retargetClip(r, e), o = this.mixer.clipAction(a);
- o.enabled = !0, o.setLoop(n.loop === !1 ? S0 : M0), n.loop === !1 && (o.clampWhenFinished = !0), this.actions.set(e, o);
+ o.enabled = !0, o.setLoop(n.loop === !1 ? I0 : S0), n.loop === !1 && (o.clampWhenFinished = !0), this.actions.set(e, o);
}
return r;
}
@@ -34996,7 +34996,7 @@ class WR {
* @param {string} name
* @param {number} [duration] - Crossfade duration in seconds
*/
- crossfadeTo(e, t = VR) {
+ crossfadeTo(e, t = zR) {
if (e === this.currentName) return;
const n = this.actions.get(e);
if (!n) {
@@ -35094,9 +35094,9 @@ class WR {
}
}
us.enabled = !0;
-class cb {
+class ob {
constructor(e, t) {
- this.el = e, this.options = t, this.lights = [], this.content = null, this.mixer = null, this.clips = [], this.gui = null, this.animationManager = new WR(), this._animPanelEl = null, this.state = {
+ this.el = e, this.options = t, this.lights = [], this.content = null, this.mixer = null, this.clips = [], this.gui = null, this.animationManager = new VR(), this._animPanelEl = null, this.state = {
environment: t.preset === uf.ASSET_GENERATOR ? ol.find((r) => r.id === "footprint-court").name : ol[1].name,
background: !1,
playbackSpeed: 1,
@@ -35125,7 +35125,7 @@ class cb {
followMode: "mouse"
}, this.prevTime = 0, this.stats = new Lo(), this.stats.dom.height = "48px", [].forEach.call(this.stats.dom.children, (r) => r.style.display = ""), this.backgroundColor = new Le(this.state.bgColor), this.scene = new Vd(), this.scene.background = this.backgroundColor;
const n = t.preset === uf.ASSET_GENERATOR ? 0.8 * 180 / Math.PI : 60, s = e.clientWidth / e.clientHeight;
- this.defaultCamera = new In(n, s, 0.01, 1e3), this.activeCamera = this.defaultCamera, this.scene.add(this.defaultCamera), this.renderer = window.renderer = new sg({ antialias: !0, alpha: !0 }), this.renderer.setClearColor(0, 1), this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), this.renderer.setSize(e.clientWidth, e.clientHeight), this.pmremGenerator = new Xd(this.renderer), this.pmremGenerator.compileEquirectangularShader(), this.neutralEnvironment = this.pmremGenerator.fromScene(new CM()).texture, this.controls = new dM(this.defaultCamera, this.renderer.domElement), this.controls.screenSpacePanning = !0, this._onControlsChange = () => this.invalidate(), this.controls.addEventListener("change", this._onControlsChange), this.el.appendChild(this.renderer.domElement), this.cameraCtrl = null, this.cameraFolder = null, this.animFolder = null, this.animCtrls = [], this.morphFolder = null, this.morphCtrls = [], this.skeletonHelpers = [], this.gridHelper = null, this.axesHelper = null, this.modelInfo = null, this.annotationEls = [], this._tempVec = new G(), this.addAxesHelper(), this.addGUI(), t.kiosk && this.gui.close(), this.animate = this.animate.bind(this), this._rafId = null, this._visible = !0, this._tabVisible = !document.hidden, this._disposed = !1, this._loadedEnvironment = null, this._guiWrap = null, this._needsRender = !0, this._animating = !1, this._onVisibilityChange = () => {
+ this.defaultCamera = new In(n, s, 0.01, 1e3), this.activeCamera = this.defaultCamera, this.scene.add(this.defaultCamera), this.renderer = window.renderer = new sg({ antialias: !0, alpha: !0 }), this.renderer.setClearColor(0, 1), this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), this.renderer.setSize(e.clientWidth, e.clientHeight), this.pmremGenerator = new Xd(this.renderer), this.pmremGenerator.compileEquirectangularShader(), this.neutralEnvironment = this.pmremGenerator.fromScene(new vM()).texture, this.controls = new uM(this.defaultCamera, this.renderer.domElement), this.controls.screenSpacePanning = !0, this._onControlsChange = () => this.invalidate(), this.controls.addEventListener("change", this._onControlsChange), this.el.appendChild(this.renderer.domElement), this.cameraCtrl = null, this.cameraFolder = null, this.animFolder = null, this.animCtrls = [], this.morphFolder = null, this.morphCtrls = [], this.skeletonHelpers = [], this.gridHelper = null, this.axesHelper = null, this.modelInfo = null, this.annotationEls = [], this._tempVec = new G(), this.addAxesHelper(), this.addGUI(), t.kiosk && this.gui.close(), this.animate = this.animate.bind(this), this._rafId = null, this._visible = !0, this._tabVisible = !document.hidden, this._disposed = !1, this._loadedEnvironment = null, this._guiWrap = null, this._needsRender = !0, this._animating = !1, this._onVisibilityChange = () => {
const r = !this._tabVisible;
this._tabVisible = !document.hidden, r && this._tabVisible && (this._needsRender = !0), this._updateRenderLoop();
}, document.addEventListener("visibilitychange", this._onVisibilityChange), typeof IntersectionObserver < "u" && (this._intersectionObserver = new IntersectionObserver(
@@ -35172,7 +35172,7 @@ class cb {
this.renderer.render(this.scene, this.activeCamera), this.state.grid && (this.axesCamera.position.copy(this.defaultCamera.position), this.axesCamera.lookAt(this.axesScene.position), this.axesRenderer.render(this.axesScene, this.axesCamera)), this.projectAnnotations();
}
takeScreenshot() {
- ER(this);
+ bR(this);
}
resize() {
const { clientHeight: e, clientWidth: t } = this.el;
@@ -35189,7 +35189,7 @@ class cb {
}
return (h || "") + l;
});
- const o = new rp(ih).setCrossOrigin("anonymous").setDRACOLoader($T).setKTX2Loader(eR.detectSupport(this.renderer)).setMeshoptDecoder(hM), c = [];
+ const o = new rp(ih).setCrossOrigin("anonymous").setDRACOLoader(ZT).setKTX2Loader($T.detectSupport(this.renderer)).setMeshoptDecoder(lM), c = [];
o.load(
e,
(l) => {
@@ -35218,10 +35218,10 @@ class cb {
}), this.setClips(t), this.animationManager.attach(this.content), this._setupAnimationPanel(), this.updateLights(), this.updateGUI(), this.updateEnvironment(), this.updateDisplay(), this.updateModelInfo(e, t), this.updateAnnotations(), window.VIEWER.scene = this.content, this.invalidate();
}
setClips(e) {
- _R(this, e);
+ yR(this, e);
}
playAllClips() {
- wR(this);
+ _R(this);
}
/**
* @param {string} name
@@ -35233,13 +35233,13 @@ class cb {
}
updateLights() {
const e = this.state, t = this.lights;
- e.punctualLights && !t.length ? tR(this) : !e.punctualLights && t.length && nR(this), this.renderer.toneMapping = Number(e.toneMapping), this.renderer.toneMappingExposure = Math.pow(2, e.exposure), t.length === 2 && (t[0].intensity = e.ambientIntensity, t[0].color.set(e.ambientColor), t[1].intensity = e.directIntensity, t[1].color.set(e.directColor)), this.invalidate();
+ e.punctualLights && !t.length ? eR(this) : !e.punctualLights && t.length && tR(this), this.renderer.toneMapping = Number(e.toneMapping), this.renderer.toneMappingExposure = Math.pow(2, e.exposure), t.length === 2 && (t[0].intensity = e.ambientIntensity, t[0].color.set(e.ambientColor), t[1].intensity = e.directIntensity, t[1].color.set(e.directColor)), this.invalidate();
}
updateEnvironment() {
const e = ol.filter(
(t) => t.name === this.state.environment
)[0];
- bR(this, e).then(({ envMap: t }) => {
+ xR(this, e).then(({ envMap: t }) => {
this._disposed || !this.scene || (this.scene.environment = t, this.scene.background = this.state.transparentBg ? null : this.state.background ? t : this.backgroundColor, this.invalidate());
});
}
@@ -35248,10 +35248,10 @@ class cb {
e.wireframe = this.state.wireframe, e instanceof Jf && (e.size = this.state.pointSize);
}), this.content.traverse((e) => {
if (e.geometry && e.skeleton && this.state.skeleton) {
- const t = new Ww(e.skeleton.bones[0].parent);
+ const t = new Vw(e.skeleton.bones[0].parent);
t.material.linewidth = 3, this.scene.add(t), this.skeletonHelpers.push(t);
}
- }), this.state.grid !== !!this.gridHelper && (this.state.grid ? (this.gridHelper = new qw(), this.axesHelper = new NA(), this.axesHelper.renderOrder = 999, this.axesHelper.onBeforeRender = (e) => e.clearDepth(), this.scene.add(this.gridHelper), this.scene.add(this.axesHelper)) : (this.scene.remove(this.gridHelper), this.scene.remove(this.axesHelper), this.gridHelper = null, this.axesHelper = null, this.axesRenderer.clear())), this.controls.autoRotate = this.state.autoRotate, this.invalidate();
+ }), this.state.grid !== !!this.gridHelper && (this.state.grid ? (this.gridHelper = new Ww(), this.axesHelper = new NA(), this.axesHelper.renderOrder = 999, this.axesHelper.onBeforeRender = (e) => e.clearDepth(), this.scene.add(this.gridHelper), this.scene.add(this.axesHelper)) : (this.scene.remove(this.gridHelper), this.scene.remove(this.axesHelper), this.gridHelper = null, this.axesHelper = null, this.axesRenderer.clear())), this.controls.autoRotate = this.state.autoRotate, this.invalidate();
}
updateBackground() {
this.backgroundColor.set(this.state.bgColor), this.state.transparentBg ? (this.scene.background = null, this.renderer.setClearColor(0, 0)) : (this.scene.background = this.backgroundColor, this.renderer.setClearColor(0, 1), this.updateEnvironment()), this.invalidate();
@@ -35270,12 +35270,12 @@ class cb {
* See: https://stackoverflow.com/q/16226693/1314762
*/
updateModelInfo(e, t) {
- this.modelInfo && (this.modelInfo.remove(), this.modelInfo = null), this.state.showInfo && e && (this.modelInfo = RT(this.el, e, t));
+ this.modelInfo && (this.modelInfo.remove(), this.modelInfo = null), this.state.showInfo && e && (this.modelInfo = TT(this.el, e, t));
}
updateAnnotations() {
if (this.annotationEls.forEach((t) => t.el.remove()), this.annotationEls = [], !this.state.showLabels || !this.content) return;
- DT(this.content).forEach((t) => {
- const n = LT(t), s = document.createElement("div");
+ NT(this.content).forEach((t) => {
+ const n = DT(t), s = document.createElement("div");
s.classList.add("annotation-label"), s.appendChild(n), this.el.appendChild(s), this.annotationEls.push({ el: s, position: t.position });
}), this.invalidate();
}
@@ -35297,7 +35297,7 @@ class cb {
this.axesScene = new Vd(), this.axesCamera = new In(50, e / t, 0.1, 10), this.axesScene.add(this.axesCamera), this.axesRenderer = new sg({ alpha: !0 }), this.axesRenderer.setPixelRatio(window.devicePixelRatio), this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight), this.axesCamera.up = this.defaultCamera.up, this.axesCorner = new NA(5), this.axesScene.add(this.axesCorner), this.axesDiv.appendChild(this.axesRenderer.domElement);
}
addGUI() {
- const e = window.innerWidth <= 700, t = this.gui = new KM({
+ const e = window.innerWidth <= 700, t = this.gui = new qM({
autoPlace: !1,
width: e ? 220 : 260,
hideable: !0
@@ -35311,7 +35311,7 @@ class cb {
).onChange(() => this.updateEnvironment()), [
p.add(this.state, "toneMapping", {
Linear: _d,
- "ACES Filmic": x0
+ "ACES Filmic": m0
}),
p.add(this.state, "exposure", -10, 10, 0.01),
p.add(this.state, "punctualLights").listen(),
@@ -35475,7 +35475,7 @@ class cb {
}
}
}
-class qR {
+class WR {
constructor({
model: e = "claude-opus-4-6",
proxyURL: t,
@@ -35533,7 +35533,7 @@ class qR {
return { role: "assistant", content: n };
}
}
-class KR {
+class qR {
// Used when brain.provider === "none" — skills drive the agent.
async complete() {
return { text: "", toolCalls: [], stopReason: "end_turn" };
@@ -35545,13 +35545,13 @@ class KR {
return { role: "assistant", content: e || "" };
}
}
-function jR(i = {}) {
+function KR(i = {}) {
const e = i.provider || "anthropic";
- if (e === "anthropic") return new qR(i);
- if (e === "none") return new KR();
+ if (e === "anthropic") return new WR(i);
+ if (e === "none") return new qR();
throw new Error(`Unsupported provider: ${e}. Supported: anthropic, none`);
}
-class XR {
+class jR {
constructor({ voiceId: e = "default", rate: t = 1, pitch: n = 1, lang: s = "en-US" } = {}) {
this.voiceId = e, this.rate = t, this.pitch = n, this.lang = s, this._queue = [], this._speaking = !1;
}
@@ -35588,7 +35588,7 @@ class XR {
return e.find((t) => t.lang?.startsWith(this.lang.slice(0, 2))) || null;
}
}
-class YR {
+class XR {
constructor({ language: e = "en-US", continuous: t = !1, interimResults: n = !0 } = {}) {
this.language = e, this.continuous = t, this.interimResults = n, this._recognition = null, this._listening = !1;
}
@@ -35628,7 +35628,7 @@ class YR {
return this._listening;
}
}
-class JR {
+class YR {
constructor({
voiceId: e,
modelId: t = "eleven_turbo_v2_5",
@@ -35785,17 +35785,17 @@ class JR {
this._startedFired = !1;
}
}
-function ZR(i = {}) {
+function JR(i = {}) {
const e = i.provider || "browser";
if (e === "none") return null;
- if (e === "browser") return new XR(i);
- if (e === "elevenlabs") return new JR(i);
+ if (e === "browser") return new jR(i);
+ if (e === "elevenlabs") return new YR(i);
throw new Error(`TTS provider "${e}" not implemented yet`);
}
-function $R(i = {}) {
+function ZR(i = {}) {
const e = i.provider || "browser";
if (e === "none") return null;
- if (e === "browser") return new YR(i);
+ if (e === "browser") return new XR(i);
throw new Error(`STT provider "${e}" not implemented yet`);
}
const $g = [
@@ -35876,7 +35876,7 @@ const $g = [
required: ["key", "name", "description", "type", "body"]
}
}
-], eF = [
+], $R = [
{
name: "observe_agents",
description: "List the other agents currently sharing this stage, with their names and positions.",
@@ -35897,7 +35897,7 @@ const $g = [
required: ["agentId", "text"]
}
}
-], tF = {
+], eF = {
async wave(i, e) {
const t = i.duration_ms || 1500;
return await e.viewer.playAnimationByHint?.("wave", { duration: t }), e.memory.note("waved", { duration_ms: t }), { ok: !0 };
@@ -35931,8 +35931,8 @@ const $g = [
const s = e.agentId || "anon";
return e.stage.broadcast(s, { kind: "direct", to: t, text: n }), e.stage.routeMessage(s, t, n);
}
-}, nF = 8;
-class iF extends EventTarget {
+}, tF = 8;
+class nF extends EventTarget {
constructor({
manifest: e,
viewer: t,
@@ -35943,10 +35943,10 @@ class iF extends EventTarget {
stage: o = null,
agentId: c = null
} = {}) {
- super(), this.manifest = e || {}, this.viewer = t, this.memory = n, this.skills = s, this.stage = o, this.agentId = c, this.provider = jR({
+ super(), this.manifest = e || {}, this.viewer = t, this.memory = n, this.skills = s, this.stage = o, this.agentId = c, this.provider = KR({
...this.manifest.brain,
...r
- }), this.tts = ZR({ ...this.manifest.voice?.tts, ...a.tts }), this.stt = $R({ ...this.manifest.voice?.stt, ...a.stt }), this.messages = [], this._busy = !1;
+ }), this.tts = JR({ ...this.manifest.voice?.tts, ...a.tts }), this.stt = ZR({ ...this.manifest.voice?.stt, ...a.stt }), this.messages = [], this._busy = !1;
}
get systemPrompt() {
const e = [];
@@ -35961,7 +35961,7 @@ class iF extends EventTarget {
), this.skills && e.push(this.skills.systemPrompt()), e.join("");
}
get tools() {
- const e = new Set(this.manifest.tools || $g.map((r) => r.name)), t = $g.filter((r) => e.has(r.name)), n = this.skills ? this.skills.allTools() : [], s = this.stage ? eF : [];
+ const e = new Set(this.manifest.tools || $g.map((r) => r.name)), t = $g.filter((r) => e.has(r.name)), n = this.skills ? this.skills.allTools() : [], s = this.stage ? $R : [];
return [...t, ...s, ...n];
}
async send(e, { voice: t = !1 } = {}) {
@@ -35984,7 +35984,7 @@ class iF extends EventTarget {
}
async _loop() {
let e = 0, t = "";
- for (; e++ < nF; ) {
+ for (; e++ < tF; ) {
const n = await this.provider.complete({
system: this.systemPrompt,
messages: this.messages,
@@ -36028,7 +36028,7 @@ class iF extends EventTarget {
async _dispatchTool(e) {
const t = this._context(), n = this.skills?.findSkillForTool(e.name);
if (n) return n.invoke(e.name, e.input, t);
- const s = tF[e.name];
+ const s = eF[e.name];
if (!s) throw new Error(`Unknown tool: ${e.name}`);
return s(e.input, t);
}
@@ -36085,16 +36085,16 @@ const ff = [
"https://dweb.link/ipfs/",
"https://cloudflare-ipfs.com/ipfs/",
"https://ipfs.io/ipfs/"
-], sF = "https://arweave.net/";
+], iF = "https://arweave.net/";
function Xs(i, e = 0) {
if (!i) return i;
const t = i.match(/^ipfs:\/\/(.+)$/i);
if (t)
return ff[e % ff.length] + t[1];
const n = i.match(/^ar:\/\/(.+)$/i);
- return n ? sF + n[1] : i;
+ return n ? iF + n[1] : i;
}
-async function rF(i) {
+async function sF(i) {
let e;
for (let t = 0; t < ff.length; t++) {
const n = Xs(i, t);
@@ -36107,7 +36107,7 @@ async function rF(i) {
}
throw e || new Error("All IPFS gateways failed for " + i);
}
-const aF = {
+const rF = {
idle: "idle",
wave: "reaction",
nod: "reaction",
@@ -36119,8 +36119,8 @@ const aF = {
point: "reaction",
shrug: "defeated"
};
-function oF(i, e) {
- return e && e[i] ? e[i] : aF[i] ?? i;
+function aF(i, e) {
+ return e && e[i] ? e[i] : rF[i] ?? i;
}
const em = {
neutral: {
@@ -36132,7 +36132,7 @@ const em = {
confused: { browInnerUp: 0.5, browOuterUpL: 0.4, mouthPressL: 0.3, mouthPressR: 0.3 },
focused: { browDownL: 0.4, browDownR: 0.4, eyeSquintL: 0.3, eyeSquintR: 0.3 }
};
-class cF {
+class oF {
constructor(e) {
this.viewer = e, this._loader = new rp(), this._userTarget = new G(0, 1.6, 2), this._animationMap = {}, this._group = null, this._groupMixer = null, this._groupClips = null, this._mixerHook = null;
}
@@ -36182,7 +36182,7 @@ class cF {
* @returns {string}
*/
resolveAnimationSlot(e) {
- return oF(e, this._animationMap);
+ return aF(e, this._animationMap);
}
// Delegate raw load for ad-hoc cases
async load(e, t = "", n = /* @__PURE__ */ new Map()) {
@@ -36307,7 +36307,7 @@ class cF {
return this.clips.find((s) => s.name.toLowerCase() === n) || this.clips.find((s) => s.name.toLowerCase().includes(n));
}
}
-const lF = `// Sandbox worker — executes skill handlers in an isolated Web Worker scope.
+const cF = `// Sandbox worker — executes skill handlers in an isolated Web Worker scope.
// No DOM, no window, no document. Only ctx.* and native worker APIs.
/** @type {Map<string, object>} skillURI → module exports */
@@ -36478,34 +36478,34 @@ function _handleResponse({ requestId, result, error }) {
`;
let hi = null, Ma = null;
const Ba = /* @__PURE__ */ new Map(), nc = /* @__PURE__ */ new Map(), zs = /* @__PURE__ */ new Map(), Ih = /* @__PURE__ */ new Map();
-let hF = 0, uF = 0;
+let lF = 0, hF = 0;
function tm(i) {
if (i == null) return null;
- const e = `@h:${++hF}`;
+ const e = `@h:${++lF}`;
return Ih.set(e, i), e;
}
-function dF(i) {
+function uF(i) {
return typeof i == "string" && i.startsWith("@h:") ? Ih.get(i) ?? i : i;
}
-function fF(i) {
- return Array.isArray(i) ? i.map(dF) : i;
+function dF(i) {
+ return Array.isArray(i) ? i.map(uF) : i;
}
-function lb() {
+function cb() {
if (!hi) {
if (!Ma) {
- const i = new Blob([lF], { type: "text/javascript" });
+ const i = new Blob([cF], { type: "text/javascript" });
Ma = URL.createObjectURL(i);
}
- hi = new Worker(Ma), hi.onmessage = AF, hi.onerror = pF;
+ hi = new Worker(Ma), hi.onmessage = pF, hi.onerror = fF;
}
return hi;
}
-function pF(i) {
+function fF(i) {
console.error("[sandbox] worker crashed:", i), hi = null, Ba.clear(), nc.clear(), Ih.clear();
for (const [, e] of zs) e.reject(new Error("Sandbox worker crashed"));
zs.clear();
}
-function AF({ data: i }) {
+function pF({ data: i }) {
switch (i.type) {
case "install-ack": {
const e = nc.get(i.skillURI);
@@ -36522,7 +36522,7 @@ function AF({ data: i }) {
});
return;
}
- gF(n, s, r.mainCtx).then(
+ AF(n, s, r.mainCtx).then(
(a) => hi?.postMessage({ type: "response", requestId: t, result: a ?? null }),
(a) => hi?.postMessage({
type: "response",
@@ -36540,8 +36540,8 @@ function AF({ data: i }) {
}
}
}
-async function gF(i, e, t) {
- const n = fF(e);
+async function AF(i, e, t) {
+ const n = dF(e);
switch (i) {
// viewer
case "viewer.play":
@@ -36593,16 +36593,16 @@ async function gF(i, e, t) {
throw new Error(`Unknown ctx method: ${i}`);
}
}
-async function mF(i, e) {
+async function gF(i, e) {
if (Ba.has(i)) return Ba.get(i);
const t = new Promise((n, s) => {
nc.set(i, { resolve: n, reject: s });
});
- return Ba.set(i, t), lb().postMessage({ type: "install", skillURI: i, handlersSrc: e }), t;
+ return Ba.set(i, t), cb().postMessage({ type: "install", skillURI: i, handlersSrc: e }), t;
}
-async function xF(i, e, t, n, s) {
- await mF(i, n);
- const r = ++uF, a = lb();
+async function mF(i, e, t, n, s) {
+ await gF(i, n);
+ const r = ++hF, a = cb();
return new Promise((o, c) => {
zs.set(r, { resolve: o, reject: c, mainCtx: s }), a.postMessage({
type: "invoke",
@@ -36614,20 +36614,20 @@ async function xF(i, e, t, n, s) {
});
});
}
-function bF() {
+function xF() {
if (hi) {
hi.terminate(), hi = null, Ma && (URL.revokeObjectURL(Ma), Ma = null), Ba.clear(), nc.clear(), Ih.clear();
for (const [, i] of zs) i.reject(new Error("Sandbox terminated"));
zs.clear();
}
}
-function EF() {
- return { invoke: xF, terminate: bF };
+function bF() {
+ return { invoke: mF, terminate: xF };
}
-function yF(i, e) {
+function EF(i, e) {
return /^([a-z]+:|\/)/i.test(e) ? e : (i.endsWith("/") || (i += "/"), i + e);
}
-class _F {
+class yF {
constructor({ uri: e, manifest: t, instructions: n, tools: s, handlers: r, handlersSrc: a }) {
this.uri = e, this.manifest = t, this.name = t.name, this.version = t.version, this.instructions = n, this.tools = s || [], this.handlers = r || {}, this.handlersSrc = a || null;
}
@@ -36641,7 +36641,7 @@ class _F {
}
if (!this.handlersSrc)
throw new Error(`Skill "${this.name}" has no handler source for tool "${e}"`);
- return EF().invoke(this.uri, e, t, this.handlersSrc, s);
+ return bF().invoke(this.uri, e, t, this.handlersSrc, s);
}
systemPromptFragment() {
return this.instructions ? `
@@ -36651,7 +36651,7 @@ ${this.instructions}
</skill>` : "";
}
}
-class wF {
+class _F {
constructor({ fetchFn: e = fetch.bind(globalThis), trust: t = "owned-only", ownerAddress: n } = {}) {
this.fetchFn = e, this.trust = t, this.ownerAddress = n?.toLowerCase(), this.skills = /* @__PURE__ */ new Map();
}
@@ -36664,7 +36664,7 @@ class wF {
this._fetchText(`${n}SKILL.md`).catch(() => ""),
this._fetchJSON(`${n}tools.json`).catch(() => ({ tools: [] })),
r ? this._fetchHandlers(`${n}handlers.js`).catch(() => null) : this._fetchHandlersSrc(`${n}handlers.js`).catch(() => null)
- ]), l = new _F({
+ ]), l = new yF({
uri: n,
manifest: s,
instructions: a,
@@ -36705,7 +36705,7 @@ class wF {
}
_resolveBundleURI(e, t) {
let n = e;
- return !/^([a-z]+:|\/)/i.test(e) && t && (n = yF(t, e)), n.endsWith("/") || (n += "/"), (n.startsWith("ipfs://") || n.startsWith("ar://")) && (n = Xs(n)), n;
+ return !/^([a-z]+:|\/)/i.test(e) && t && (n = EF(t, e)), n.endsWith("/") || (n += "/"), (n.startsWith("ipfs://") || n.startsWith("ar://")) && (n = Xs(n)), n;
}
async _fetchJSON(e) {
const t = await this.fetchFn(e);
@@ -36745,9 +36745,9 @@ class wF {
}
}
}
-const vF = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
+const wF = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
function Al(i) {
- const e = i.match(vF);
+ const e = i.match(wF);
if (!e) return { meta: {}, body: i };
const t = {};
for (const n of e[1].split(`
@@ -36757,7 +36757,7 @@ function Al(i) {
}
return { meta: t, body: e[2] };
}
-function CF(i, e) {
+function vF(i, e) {
const t = ["---"];
for (const [n, s] of Object.entries(i)) t.push(`${n}: ${s}`);
return t.push("---", "", e), t.join(`
@@ -36809,7 +36809,7 @@ class ki {
}
write(e, { name: t, description: n, type: s, body: r, decay: a }) {
const o = e.endsWith(".md") ? e : `${e}.md`, c = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), l = this.files.get(o), h = l && Al(l).meta.created || c, u = { name: t, description: n, type: s, created: h, updated: c };
- a && (u.decay = a), this.files.set(o, CF(u, r || "")), this._rebuildIndex(), this._dirty = !0, this._persist();
+ a && (u.decay = a), this.files.set(o, vF(u, r || "")), this._rebuildIndex(), this._dirty = !0, this._persist();
}
note(e, t) {
const n = { ts: (/* @__PURE__ */ new Date()).toISOString(), type: e, ...t };
@@ -36894,8 +36894,8 @@ class ki {
this._rebuildIndex(), this._persist();
}
}
-const IF = "6.16.0";
-function SF(i, e, t) {
+const CF = "6.16.0";
+function IF(i, e, t) {
const n = e.split("|").map((r) => r.trim());
for (let r = 0; r < n.length; r++)
switch (e) {
@@ -36919,7 +36919,7 @@ function Ye(i, e, t) {
for (let n in e) {
let s = e[n];
const r = t ? t[n] : null;
- r && SF(s, r, n), Object.defineProperty(i, n, { enumerable: !0, value: s, writable: !1 });
+ r && IF(s, r, n), Object.defineProperty(i, n, { enumerable: !0, value: s, writable: !1 });
}
}
function _a(i, e) {
@@ -36977,7 +36977,7 @@ function Gt(i, e, t) {
r.push(a + "=" + _a(o));
}
}
- r.push(`code=${e}`), r.push(`version=${IF}`), r.length && (i += " (" + r.join(", ") + ")");
+ r.push(`code=${e}`), r.push(`version=${CF}`), r.length && (i += " (" + r.join(", ") + ")");
}
let s;
switch (e) {
@@ -37000,7 +37000,7 @@ function ge(i, e, t, n) {
function V(i, e, t, n) {
ge(i, e, "INVALID_ARGUMENT", { argument: t, value: n });
}
-function hb(i, e, t) {
+function lb(i, e, t) {
t == null && (t = ""), t && (t = ": " + t), ge(i >= e, "missing argument" + t, "MISSING_ARGUMENT", {
count: i,
expectedCount: e
@@ -37028,7 +37028,7 @@ function Sh(i, e, t) {
});
}
}
-function ub(i, e, t) {
+function hb(i, e, t) {
if (i instanceof Uint8Array)
return t ? new Uint8Array(i) : i;
if (typeof i == "string" && i.length % 2 === 0 && i.match(/^0x[0-9a-f]*$/i)) {
@@ -37041,10 +37041,10 @@ function ub(i, e, t) {
V(!1, "invalid BytesLike value", e || "value", i);
}
function dt(i, e) {
- return ub(i, e, !1);
+ return hb(i, e, !1);
}
function Qn(i, e) {
- return ub(i, e, !0);
+ return hb(i, e, !0);
}
function Ut(i, e) {
return !(typeof i != "string" || !i.match(/^0x[0-9A-Fa-f]*$/) || typeof e == "number" && i.length !== 2 + 2 * e || e === !0 && i.length % 2 !== 0);
@@ -37076,7 +37076,7 @@ function Kt(i, e, t) {
offset: t
}), Ie(n.slice(e ?? 0, t ?? n.length));
}
-function db(i, e, t) {
+function ub(i, e, t) {
const n = dt(i);
ge(e >= n.length, "padding exceeds data length", "BUFFER_OVERRUN", {
buffer: new Uint8Array(n),
@@ -37087,13 +37087,13 @@ function db(i, e, t) {
return s.fill(0), t ? s.set(n, e - n.length) : s.set(n, 0), Ie(s);
}
function Es(i, e) {
- return db(i, e, !0);
+ return ub(i, e, !0);
}
-function MF(i, e) {
- return db(i, e, !1);
+function SF(i, e) {
+ return ub(i, e, !1);
}
const gc = BigInt(0), Mi = BigInt(1), wa = 9007199254740991;
-function BF(i, e) {
+function MF(i, e) {
const t = Mh(i, "value"), n = BigInt(ft(e, "width"));
if (ge(t >> n === gc, "overflow", "NUMERIC_FAULT", {
operation: "fromTwos",
@@ -37105,7 +37105,7 @@ function BF(i, e) {
}
return t;
}
-function fb(i, e) {
+function db(i, e) {
let t = De(i, "value");
const n = BigInt(ft(e, "width")), s = Mi << n - Mi;
if (t < gc) {
@@ -37180,7 +37180,7 @@ function ft(i, e) {
}
V(!1, "invalid numeric value", e || "value", i);
}
-function TF(i) {
+function BF(i) {
return ft(Ep(i));
}
function Ys(i, e) {
@@ -37223,7 +37223,7 @@ function vi(i) {
const sm = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
BigInt(0);
const rm = BigInt(58);
-function RF(i) {
+function TF(i) {
const e = dt(i);
let t = Ep(e), n = "";
for (; t; )
@@ -37232,21 +37232,21 @@ function RF(i) {
n = sm[0] + n;
return n;
}
-function FF(i) {
+function RF(i) {
i = atob(i);
const e = new Uint8Array(i.length);
for (let t = 0; t < i.length; t++)
e[t] = i.charCodeAt(t);
return dt(e);
}
-function NF(i) {
+function FF(i) {
const e = dt(i);
let t = "";
for (let n = 0; n < e.length; n++)
t += String.fromCharCode(e[n]);
return btoa(t);
}
-class pb {
+class fb {
/**
* The event filter.
*/
@@ -37270,10 +37270,10 @@ class pb {
this.#e != null && await this.emitter.off(this.filter, this.#e);
}
}
-function DF(i, e, t, n, s) {
+function NF(i, e, t, n, s) {
V(!1, `invalid codepoint at offset ${e}; ${i}`, "bytes", t);
}
-function Ab(i, e, t, n, s) {
+function pb(i, e, t, n, s) {
if (i === "BAD_PREFIX" || i === "UNEXPECTED_CONTINUE") {
let r = 0;
for (let a = e + 1; a < t.length && t[a] >> 6 === 2; a++)
@@ -37282,16 +37282,16 @@ function Ab(i, e, t, n, s) {
}
return i === "OVERRUN" ? t.length - e - 1 : 0;
}
-function LF(i, e, t, n, s) {
- return i === "OVERLONG" ? (V(typeof s == "number", "invalid bad code point for replacement", "badCodepoint", s), n.push(s), 0) : (n.push(65533), Ab(i, e, t));
+function DF(i, e, t, n, s) {
+ return i === "OVERLONG" ? (V(typeof s == "number", "invalid bad code point for replacement", "badCodepoint", s), n.push(s), 0) : (n.push(65533), pb(i, e, t));
}
-const PF = Object.freeze({
- error: DF,
- ignore: Ab,
- replace: LF
+const LF = Object.freeze({
+ error: NF,
+ ignore: pb,
+ replace: DF
});
-function kF(i, e) {
- e == null && (e = PF.error);
+function PF(i, e) {
+ e == null && (e = LF.error);
const t = dt(i, "bytes"), n = [];
let s = 0;
for (; s < t.length; ) {
@@ -37362,13 +37362,13 @@ function gs(i, e) {
}
return new Uint8Array(t);
}
-function UF(i) {
+function kF(i) {
return i.map((e) => e <= 65535 ? String.fromCharCode(e) : (e -= 65536, String.fromCharCode((e >> 10 & 1023) + 55296, (e & 1023) + 56320))).join("");
}
function sh(i, e) {
- return UF(kF(i, e));
+ return kF(PF(i, e));
}
-function gb(i) {
+function Ab(i) {
async function e(t, n) {
ge(n == null || !n.cancelled, "request cancelled before sending", "CANCELLED");
const s = t.url.split(":")[0].toLowerCase();
@@ -37412,26 +37412,26 @@ function gb(i) {
}
return e;
}
-const OF = 12, QF = 250;
-let am = gb();
-const GF = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"), HF = new RegExp("^ipfs://(ipfs/)?(.*)$", "i");
+const UF = 12, OF = 250;
+let am = Ab();
+const QF = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"), GF = new RegExp("^ipfs://(ipfs/)?(.*)$", "i");
let ju = !1;
-async function mb(i, e) {
+async function gb(i, e) {
try {
- const t = i.match(GF);
+ const t = i.match(QF);
if (!t)
throw new Error("invalid data");
return new Vs(200, "OK", {
"content-type": t[1] || "text/plain"
- }, t[2] ? FF(t[3]) : VF(t[3]));
+ }, t[2] ? RF(t[3]) : zF(t[3]));
} catch {
return new Vs(599, "BAD REQUEST (invalid data: URI)", {}, null, new Hi(i));
}
}
-function xb(i) {
+function mb(i) {
async function e(t, n) {
try {
- const s = t.match(HF);
+ const s = t.match(GF);
if (!s)
throw new Error("invalid link");
return new Hi(`${i}${s[2]}`);
@@ -37442,14 +37442,14 @@ function xb(i) {
return e;
}
const gl = {
- data: mb,
- ipfs: xb("https://gateway.ipfs.io/ipfs/")
-}, bb = /* @__PURE__ */ new WeakMap();
-class zF {
+ data: gb,
+ ipfs: mb("https://gateway.ipfs.io/ipfs/")
+}, xb = /* @__PURE__ */ new WeakMap();
+class HF {
#e;
#t;
constructor(e) {
- this.#e = [], this.#t = !1, bb.set(e, () => {
+ this.#e = [], this.#t = !1, xb.set(e, () => {
if (!this.#t) {
this.#t = !0;
for (const t of this.#e)
@@ -37565,7 +37565,7 @@ class Hi {
*/
get headers() {
const e = Object.assign({}, this.#n);
- return this.#f && (e.authorization = `Basic ${NF(gs(this.#f))}`), this.allowGzip && (e["accept-encoding"] = "gzip"), e["content-type"] == null && this.#o && (e["content-type"] = this.#o), this.body && (e["content-length"] = String(this.body.length)), e;
+ return this.#f && (e.authorization = `Basic ${FF(gs(this.#f))}`), this.allowGzip && (e["accept-encoding"] = "gzip"), e["content-type"] == null && this.#o && (e["content-type"] = this.#o), this.body && (e["content-length"] = String(this.body.length)), e;
}
/**
* Get the header for %%key%%, ignoring case.
@@ -37713,8 +37713,8 @@ class Hi {
*/
constructor(e) {
this.#a = String(e), this.#e = !1, this.#t = !0, this.#n = {}, this.#i = "", this.#s = 3e5, this.#h = {
- slotInterval: QF,
- maxAttempts: OF
+ slotInterval: OF,
+ maxAttempts: UF
}, this.#u = null;
}
toString() {
@@ -37734,7 +37734,7 @@ class Hi {
operation: "request.send",
reason: "timeout",
request: s
- }), n > 0 && await WF(n);
+ }), n > 0 && await VF(n);
let a = this.clone();
const o = (a.url.split(":")[0] || "").toLowerCase();
if (o in gl) {
@@ -37784,7 +37784,7 @@ class Hi {
* Resolves to the response by sending the request.
*/
send() {
- return ge(this.#c == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }), this.#c = new zF(this), this.#d(0, om() + this.timeout, 0, this, new Vs(0, "", {}, null, this));
+ return ge(this.#c == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }), this.#c = new HF(this), this.#d(0, om() + this.timeout, 0, this, new Vs(0, "", {}, null, this));
}
/**
* Cancels the inflight response, causing a ``CANCELLED``
@@ -37792,7 +37792,7 @@ class Hi {
*/
cancel() {
ge(this.#c != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" });
- const e = bb.get(this);
+ const e = xb.get(this);
if (!e)
throw new Error("missing signal; should not happen");
e();
@@ -37869,7 +37869,7 @@ class Hi {
* content.
*/
static createGetUrlFunc(e) {
- return gb(e);
+ return Ab(e);
}
/**
* Creates a function that can "fetch" data URIs.
@@ -37881,7 +37881,7 @@ class Hi {
* be useful in a wrapper to perfom custom data URI functionality.
*/
static createDataGateway() {
- return mb;
+ return gb;
}
/**
* Creates a function that will fetch IPFS (unvalidated) from
@@ -37891,7 +37891,7 @@ class Hi {
* ``"https:/\/gateway.ipfs.io/ipfs/"``.
*/
static createIpfsGatewayFunc(e) {
- return xb(e);
+ return mb(e);
}
}
class Vs {
@@ -38054,13 +38054,13 @@ class Vs {
function om() {
return (/* @__PURE__ */ new Date()).getTime();
}
-function VF(i) {
+function zF(i) {
return gs(i.replace(/%([0-9a-f][0-9a-f])/gi, (e, t) => String.fromCharCode(parseInt(t, 16))));
}
-function WF(i) {
+function VF(i) {
return new Promise((e) => setTimeout(e, i));
}
-function qF(i) {
+function WF(i) {
let e = i.toString(16);
for (; e.length < 2; )
e = "0" + e;
@@ -38075,7 +38075,7 @@ function cm(i, e, t) {
function lm(i, e, t, n) {
const s = [];
for (; t < e + 1 + n; ) {
- const r = Eb(i, t);
+ const r = bb(i, t);
s.push(r.result), t += r.consumed, ge(t <= e + 1 + n, "child data too short", "BUFFER_OVERRUN", {
buffer: i,
length: n,
@@ -38084,7 +38084,7 @@ function lm(i, e, t, n) {
}
return { consumed: 1 + n, result: s };
}
-function Eb(i, e) {
+function bb(i, e) {
ge(i.length !== 0, "data too short", "BUFFER_OVERRUN", {
buffer: i,
length: 0,
@@ -38118,10 +38118,10 @@ function Eb(i, e) {
const s = Ie(i.slice(e + 1, e + 1 + n));
return { consumed: 1 + n, result: s };
}
- return { consumed: 1, result: qF(i[e]) };
+ return { consumed: 1, result: WF(i[e]) };
}
function mc(i) {
- const e = dt(i, "data"), t = Eb(e, 0);
+ const e = dt(i, "data"), t = bb(e, 0);
return V(t.consumed === e.length, "unexpected junk after rlp payload", "data", i), t.result;
}
function hm(i) {
@@ -38130,11 +38130,11 @@ function hm(i) {
e.unshift(i & 255), i >>= 8;
return e;
}
-function yb(i) {
+function Eb(i) {
if (Array.isArray(i)) {
let n = [];
if (i.forEach(function(r) {
- n = n.concat(yb(r));
+ n = n.concat(Eb(r));
}), n.length <= 55)
return n.unshift(192 + n.length), n;
const s = hm(n.length);
@@ -38151,16 +38151,16 @@ function yb(i) {
const um = "0123456789abcdef";
function ms(i) {
let e = "0x";
- for (const t of yb(i))
+ for (const t of Eb(i))
e += um[t >> 4], e += um[t & 15];
return e;
}
-const Hn = 32, pf = new Uint8Array(Hn), KF = ["then"], xl = {}, _b = /* @__PURE__ */ new WeakMap();
+const Hn = 32, pf = new Uint8Array(Hn), qF = ["then"], xl = {}, yb = /* @__PURE__ */ new WeakMap();
function gr(i) {
- return _b.get(i);
+ return yb.get(i);
}
function dm(i, e) {
- _b.set(i, e);
+ yb.set(i, e);
}
function bo(i, e) {
const t = new Error(`deferred error during ABI decoding triggered accessing ${i}`);
@@ -38203,7 +38203,7 @@ class ds extends Array {
const f = c[d];
return f instanceof Error && bo(`index ${d}`, f), f;
}
- if (KF.indexOf(l) >= 0)
+ if (qF.indexOf(l) >= 0)
return Reflect.get(c, l, h);
const u = c[l];
if (u instanceof Function)
@@ -38430,7 +38430,7 @@ class yp {
return Ep(this.readBytes(Hn));
}
readIndex() {
- return TF(this.readBytes(Hn));
+ return BF(this.readBytes(Hn));
}
}
function rh(i) {
@@ -38443,7 +38443,7 @@ function _p(i, ...e) {
if (e.length > 0 && !e.includes(i.length))
throw new Error(`Expected Uint8Array of length ${e}, not of length=${i.length}`);
}
-function jF(i) {
+function KF(i) {
if (typeof i != "function" || typeof i.create != "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
rh(i.outputLen), rh(i.blockLen);
@@ -38454,31 +38454,31 @@ function Oa(i, e = !0) {
if (e && i.finished)
throw new Error("Hash#digest() has already been called");
}
-function wb(i, e) {
+function _b(i, e) {
_p(i);
const t = e.outputLen;
if (i.length < t)
throw new Error(`digestInto() expects output buffer of length at least ${t}`);
}
const Xu = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
-const vb = (i) => i instanceof Uint8Array, XF = (i) => new Uint32Array(i.buffer, i.byteOffset, Math.floor(i.byteLength / 4)), Yu = (i) => new DataView(i.buffer, i.byteOffset, i.byteLength), Pi = (i, e) => i << 32 - e | i >>> e, YF = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
-if (!YF)
+const wb = (i) => i instanceof Uint8Array, jF = (i) => new Uint32Array(i.buffer, i.byteOffset, Math.floor(i.byteLength / 4)), Yu = (i) => new DataView(i.buffer, i.byteOffset, i.byteLength), Pi = (i, e) => i << 32 - e | i >>> e, XF = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
+if (!XF)
throw new Error("Non little-endian hardware is not supported");
-function JF(i) {
+function YF(i) {
if (typeof i != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof i}`);
return new Uint8Array(new TextEncoder().encode(i));
}
function Bh(i) {
- if (typeof i == "string" && (i = JF(i)), !vb(i))
+ if (typeof i == "string" && (i = YF(i)), !wb(i))
throw new Error(`expected Uint8Array, got ${typeof i}`);
return i;
}
-function ZF(...i) {
+function JF(...i) {
const e = new Uint8Array(i.reduce((n, s) => n + s.length, 0));
let t = 0;
return i.forEach((n) => {
- if (!vb(n))
+ if (!wb(n))
throw new Error("Uint8Array expected");
e.set(n, t), t += n.length;
}), e;
@@ -38493,14 +38493,14 @@ function vp(i) {
const e = (n) => i().update(Bh(n)).digest(), t = i();
return e.outputLen = t.outputLen, e.blockLen = t.blockLen, e.create = () => i(), e;
}
-function $F(i = 32) {
+function ZF(i = 32) {
if (Xu && typeof Xu.getRandomValues == "function")
return Xu.getRandomValues(new Uint8Array(i));
throw new Error("crypto.getRandomValues must be defined");
}
-class Cb extends wp {
+class vb extends wp {
constructor(e, t) {
- super(), this.finished = !1, this.destroyed = !1, jF(e);
+ super(), this.finished = !1, this.destroyed = !1, KF(e);
const n = Bh(t);
if (this.iHash = e.create(), typeof this.iHash.update != "function")
throw new Error("Expected instance of class which extends utils.Hash");
@@ -38533,15 +38533,15 @@ class Cb extends wp {
this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
}
}
-const Ib = (i, e, t) => new Cb(i, e).update(t).digest();
-Ib.create = (i, e) => new Cb(i, e);
-function eN(i, e, t, n) {
+const Cb = (i, e, t) => new vb(i, e).update(t).digest();
+Cb.create = (i, e) => new vb(i, e);
+function $F(i, e, t, n) {
if (typeof i.setBigUint64 == "function")
return i.setBigUint64(e, t, n);
const s = BigInt(32), r = BigInt(4294967295), a = Number(t >> s & r), o = Number(t & r), c = n ? 4 : 0, l = n ? 0 : 4;
i.setUint32(e + c, a, n), i.setUint32(e + l, o, n);
}
-class Sb extends wp {
+class Ib extends wp {
constructor(e, t, n, s) {
super(), this.blockLen = e, this.outputLen = t, this.padOffset = n, this.isLE = s, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = Yu(this.buffer);
}
@@ -38563,13 +38563,13 @@ class Sb extends wp {
return this.length += e.length, this.roundClean(), this;
}
digestInto(e) {
- Oa(this), wb(e, this), this.finished = !0;
+ Oa(this), _b(e, this), this.finished = !0;
const { buffer: t, view: n, blockLen: s, isLE: r } = this;
let { pos: a } = this;
t[a++] = 128, this.buffer.subarray(a).fill(0), this.padOffset > s - a && (this.process(n, 0), a = 0);
for (let u = a; u < s; u++)
t[u] = 0;
- eN(n, s - 8, BigInt(this.length * 8), r), this.process(n, 0);
+ $F(n, s - 8, BigInt(this.length * 8), r), this.process(n, 0);
const o = Yu(e), c = this.outputLen;
if (c % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
@@ -38591,7 +38591,7 @@ class Sb extends wp {
return e.length = s, e.pos = o, e.finished = r, e.destroyed = a, s % t && e.buffer.set(n), e;
}
}
-const tN = (i, e, t) => i & e ^ ~i & t, nN = (i, e, t) => i & e ^ i & t ^ e & t, iN = /* @__PURE__ */ new Uint32Array([
+const eN = (i, e, t) => i & e ^ ~i & t, tN = (i, e, t) => i & e ^ i & t ^ e & t, nN = /* @__PURE__ */ new Uint32Array([
1116352408,
1899447441,
3049323471,
@@ -38666,7 +38666,7 @@ const tN = (i, e, t) => i & e ^ ~i & t, nN = (i, e, t) => i & e ^ i & t ^ e & t,
528734635,
1541459225
]), Ds = /* @__PURE__ */ new Uint32Array(64);
-class sN extends Sb {
+class iN extends Ib {
constructor() {
super(64, 32, 8, !1), this.A = Ns[0] | 0, this.B = Ns[1] | 0, this.C = Ns[2] | 0, this.D = Ns[3] | 0, this.E = Ns[4] | 0, this.F = Ns[5] | 0, this.G = Ns[6] | 0, this.H = Ns[7] | 0;
}
@@ -38687,7 +38687,7 @@ class sN extends Sb {
}
let { A: n, B: s, C: r, D: a, E: o, F: c, G: l, H: h } = this;
for (let u = 0; u < 64; u++) {
- const d = Pi(o, 6) ^ Pi(o, 11) ^ Pi(o, 25), f = h + d + tN(o, c, l) + iN[u] + Ds[u] | 0, m = (Pi(n, 2) ^ Pi(n, 13) ^ Pi(n, 22)) + nN(n, s, r) | 0;
+ const d = Pi(o, 6) ^ Pi(o, 11) ^ Pi(o, 25), f = h + d + eN(o, c, l) + nN[u] + Ds[u] | 0, m = (Pi(n, 2) ^ Pi(n, 13) ^ Pi(n, 22)) + tN(n, s, r) | 0;
h = l, l = c, c = o, o = a + f | 0, a = r, r = s, s = n, n = f + m | 0;
}
n = n + this.A | 0, s = s + this.B | 0, r = r + this.C | 0, a = a + this.D | 0, o = o + this.E | 0, c = c + this.F | 0, l = l + this.G | 0, h = h + this.H | 0, this.set(n, s, r, a, o, c, l, h);
@@ -38699,47 +38699,47 @@ class sN extends Sb {
this.set(0, 0, 0, 0, 0, 0, 0, 0), this.buffer.fill(0);
}
}
-const Mb = /* @__PURE__ */ vp(() => new sN()), bl = /* @__PURE__ */ BigInt(2 ** 32 - 1), mf = /* @__PURE__ */ BigInt(32);
-function Bb(i, e = !1) {
+const Sb = /* @__PURE__ */ vp(() => new iN()), bl = /* @__PURE__ */ BigInt(2 ** 32 - 1), mf = /* @__PURE__ */ BigInt(32);
+function Mb(i, e = !1) {
return e ? { h: Number(i & bl), l: Number(i >> mf & bl) } : { h: Number(i >> mf & bl) | 0, l: Number(i & bl) | 0 };
}
-function Tb(i, e = !1) {
+function Bb(i, e = !1) {
let t = new Uint32Array(i.length), n = new Uint32Array(i.length);
for (let s = 0; s < i.length; s++) {
- const { h: r, l: a } = Bb(i[s], e);
+ const { h: r, l: a } = Mb(i[s], e);
[t[s], n[s]] = [r, a];
}
return [t, n];
}
-const rN = (i, e) => BigInt(i >>> 0) << mf | BigInt(e >>> 0), aN = (i, e, t) => i >>> t, oN = (i, e, t) => i << 32 - t | e >>> t, cN = (i, e, t) => i >>> t | e << 32 - t, lN = (i, e, t) => i << 32 - t | e >>> t, hN = (i, e, t) => i << 64 - t | e >>> t - 32, uN = (i, e, t) => i >>> t - 32 | e << 64 - t, dN = (i, e) => e, fN = (i, e) => i, Rb = (i, e, t) => i << t | e >>> 32 - t, Fb = (i, e, t) => e << t | i >>> 32 - t, Nb = (i, e, t) => e << t - 32 | i >>> 64 - t, Db = (i, e, t) => i << t - 32 | e >>> 64 - t;
-function pN(i, e, t, n) {
+const sN = (i, e) => BigInt(i >>> 0) << mf | BigInt(e >>> 0), rN = (i, e, t) => i >>> t, aN = (i, e, t) => i << 32 - t | e >>> t, oN = (i, e, t) => i >>> t | e << 32 - t, cN = (i, e, t) => i << 32 - t | e >>> t, lN = (i, e, t) => i << 64 - t | e >>> t - 32, hN = (i, e, t) => i >>> t - 32 | e << 64 - t, uN = (i, e) => e, dN = (i, e) => i, Tb = (i, e, t) => i << t | e >>> 32 - t, Rb = (i, e, t) => e << t | i >>> 32 - t, Fb = (i, e, t) => e << t - 32 | i >>> 64 - t, Nb = (i, e, t) => i << t - 32 | e >>> 64 - t;
+function fN(i, e, t, n) {
const s = (e >>> 0) + (n >>> 0);
return { h: i + t + (s / 2 ** 32 | 0) | 0, l: s | 0 };
}
-const AN = (i, e, t) => (i >>> 0) + (e >>> 0) + (t >>> 0), gN = (i, e, t, n) => e + t + n + (i / 2 ** 32 | 0) | 0, mN = (i, e, t, n) => (i >>> 0) + (e >>> 0) + (t >>> 0) + (n >>> 0), xN = (i, e, t, n, s) => e + t + n + s + (i / 2 ** 32 | 0) | 0, bN = (i, e, t, n, s) => (i >>> 0) + (e >>> 0) + (t >>> 0) + (n >>> 0) + (s >>> 0), EN = (i, e, t, n, s, r) => e + t + n + s + r + (i / 2 ** 32 | 0) | 0, ct = {
- fromBig: Bb,
- split: Tb,
- toBig: rN,
- shrSH: aN,
- shrSL: oN,
- rotrSH: cN,
- rotrSL: lN,
- rotrBH: hN,
- rotrBL: uN,
- rotr32H: dN,
- rotr32L: fN,
- rotlSH: Rb,
- rotlSL: Fb,
- rotlBH: Nb,
- rotlBL: Db,
- add: pN,
- add3L: AN,
- add3H: gN,
- add4L: mN,
- add4H: xN,
- add5H: EN,
- add5L: bN
-}, [yN, _N] = ct.split([
+const pN = (i, e, t) => (i >>> 0) + (e >>> 0) + (t >>> 0), AN = (i, e, t, n) => e + t + n + (i / 2 ** 32 | 0) | 0, gN = (i, e, t, n) => (i >>> 0) + (e >>> 0) + (t >>> 0) + (n >>> 0), mN = (i, e, t, n, s) => e + t + n + s + (i / 2 ** 32 | 0) | 0, xN = (i, e, t, n, s) => (i >>> 0) + (e >>> 0) + (t >>> 0) + (n >>> 0) + (s >>> 0), bN = (i, e, t, n, s, r) => e + t + n + s + r + (i / 2 ** 32 | 0) | 0, ct = {
+ fromBig: Mb,
+ split: Bb,
+ toBig: sN,
+ shrSH: rN,
+ shrSL: aN,
+ rotrSH: oN,
+ rotrSL: cN,
+ rotrBH: lN,
+ rotrBL: hN,
+ rotr32H: uN,
+ rotr32L: dN,
+ rotlSH: Tb,
+ rotlSL: Rb,
+ rotlBH: Fb,
+ rotlBL: Nb,
+ add: fN,
+ add3L: pN,
+ add3H: AN,
+ add4L: gN,
+ add4H: mN,
+ add5H: bN,
+ add5L: xN
+}, [EN, yN] = ct.split([
"0x428a2f98d728ae22",
"0x7137449123ef65cd",
"0xb5c0fbcfec4d3b2f",
@@ -38821,7 +38821,7 @@ const AN = (i, e, t) => (i >>> 0) + (e >>> 0) + (t >>> 0), gN = (i, e, t, n) =>
"0x5fcb6fab3ad6faec",
"0x6c44198c4a475817"
].map((i) => BigInt(i))), Ls = /* @__PURE__ */ new Uint32Array(80), Ps = /* @__PURE__ */ new Uint32Array(80);
-class wN extends Sb {
+class _N extends Ib {
constructor() {
super(128, 64, 16, !1), this.Ah = 1779033703, this.Al = -205731576, this.Bh = -1150833019, this.Bl = -2067093701, this.Ch = 1013904242, this.Cl = -23791573, this.Dh = -1521486534, this.Dl = 1595750129, this.Eh = 1359893119, this.El = -1377402159, this.Fh = -1694144372, this.Fl = 725511199, this.Gh = 528734635, this.Gl = -79577749, this.Hh = 1541459225, this.Hl = 327033209;
}
@@ -38843,7 +38843,7 @@ class wN extends Sb {
}
let { Ah: n, Al: s, Bh: r, Bl: a, Ch: o, Cl: c, Dh: l, Dl: h, Eh: u, El: d, Fh: f, Fl: p, Gh: m, Gl: g, Hh: A, Hl: _ } = this;
for (let x = 0; x < 80; x++) {
- const E = ct.rotrSH(u, d, 14) ^ ct.rotrSH(u, d, 18) ^ ct.rotrBH(u, d, 41), S = ct.rotrSL(u, d, 14) ^ ct.rotrSL(u, d, 18) ^ ct.rotrBL(u, d, 41), w = u & f ^ ~u & m, I = d & p ^ ~d & g, T = ct.add5L(_, S, I, _N[x], Ps[x]), C = ct.add5H(T, A, E, w, yN[x], Ls[x]), v = T | 0, F = ct.rotrSH(n, s, 28) ^ ct.rotrBH(n, s, 34) ^ ct.rotrBH(n, s, 39), K = ct.rotrSL(n, s, 28) ^ ct.rotrBL(n, s, 34) ^ ct.rotrBL(n, s, 39), q = n & r ^ n & o ^ r & o, $ = s & a ^ s & c ^ a & c;
+ const E = ct.rotrSH(u, d, 14) ^ ct.rotrSH(u, d, 18) ^ ct.rotrBH(u, d, 41), S = ct.rotrSL(u, d, 14) ^ ct.rotrSL(u, d, 18) ^ ct.rotrBL(u, d, 41), w = u & f ^ ~u & m, I = d & p ^ ~d & g, T = ct.add5L(_, S, I, yN[x], Ps[x]), C = ct.add5H(T, A, E, w, EN[x], Ls[x]), v = T | 0, F = ct.rotrSH(n, s, 28) ^ ct.rotrBH(n, s, 34) ^ ct.rotrBH(n, s, 39), K = ct.rotrSL(n, s, 28) ^ ct.rotrBL(n, s, 34) ^ ct.rotrBL(n, s, 39), q = n & r ^ n & o ^ r & o, $ = s & a ^ s & c ^ a & c;
A = m | 0, _ = g | 0, m = f | 0, g = p | 0, f = u | 0, p = d | 0, { h: u, l: d } = ct.add(l | 0, h | 0, C | 0, v | 0), l = o | 0, h = c | 0, o = r | 0, c = a | 0, r = n | 0, a = s | 0;
const D = ct.add3L(v, K, $);
n = ct.add3H(D, C, F, q), s = D | 0;
@@ -38857,8 +38857,8 @@ class wN extends Sb {
this.buffer.fill(0), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
-const vN = /* @__PURE__ */ vp(() => new wN());
-function CN() {
+const wN = /* @__PURE__ */ vp(() => new _N());
+function vN() {
if (typeof self < "u")
return self;
if (typeof window < "u")
@@ -38867,27 +38867,27 @@ function CN() {
return global;
throw new Error("unable to locate global object");
}
-const pm = CN();
+const pm = vN();
pm.crypto || pm.msCrypto;
-function IN(i) {
+function CN(i) {
switch (i) {
case "sha256":
- return Mb.create();
+ return Sb.create();
case "sha512":
- return vN.create();
+ return wN.create();
}
V(!1, "invalid hashing algorithm name", "algorithm", i);
}
-const [Lb, Pb, kb] = [[], [], []], SN = /* @__PURE__ */ BigInt(0), Eo = /* @__PURE__ */ BigInt(1), MN = /* @__PURE__ */ BigInt(2), BN = /* @__PURE__ */ BigInt(7), TN = /* @__PURE__ */ BigInt(256), RN = /* @__PURE__ */ BigInt(113);
+const [Db, Lb, Pb] = [[], [], []], IN = /* @__PURE__ */ BigInt(0), Eo = /* @__PURE__ */ BigInt(1), SN = /* @__PURE__ */ BigInt(2), MN = /* @__PURE__ */ BigInt(7), BN = /* @__PURE__ */ BigInt(256), TN = /* @__PURE__ */ BigInt(113);
for (let i = 0, e = Eo, t = 1, n = 0; i < 24; i++) {
- [t, n] = [n, (2 * t + 3 * n) % 5], Lb.push(2 * (5 * n + t)), Pb.push((i + 1) * (i + 2) / 2 % 64);
- let s = SN;
+ [t, n] = [n, (2 * t + 3 * n) % 5], Db.push(2 * (5 * n + t)), Lb.push((i + 1) * (i + 2) / 2 % 64);
+ let s = IN;
for (let r = 0; r < 7; r++)
- e = (e << Eo ^ (e >> BN) * RN) % TN, e & MN && (s ^= Eo << (Eo << /* @__PURE__ */ BigInt(r)) - Eo);
- kb.push(s);
+ e = (e << Eo ^ (e >> MN) * TN) % BN, e & SN && (s ^= Eo << (Eo << /* @__PURE__ */ BigInt(r)) - Eo);
+ Pb.push(s);
}
-const [FN, NN] = /* @__PURE__ */ Tb(kb, !0), Am = (i, e, t) => t > 32 ? Nb(i, e, t) : Rb(i, e, t), gm = (i, e, t) => t > 32 ? Db(i, e, t) : Fb(i, e, t);
-function DN(i, e = 24) {
+const [RN, FN] = /* @__PURE__ */ Bb(Pb, !0), Am = (i, e, t) => t > 32 ? Fb(i, e, t) : Tb(i, e, t), gm = (i, e, t) => t > 32 ? Nb(i, e, t) : Rb(i, e, t);
+function NN(i, e = 24) {
const t = new Uint32Array(10);
for (let n = 24 - e; n < 24; n++) {
for (let a = 0; a < 10; a++)
@@ -38899,7 +38899,7 @@ function DN(i, e = 24) {
}
let s = i[2], r = i[3];
for (let a = 0; a < 24; a++) {
- const o = Pb[a], c = Am(s, r, o), l = gm(s, r, o), h = Lb[a];
+ const o = Lb[a], c = Am(s, r, o), l = gm(s, r, o), h = Db[a];
s = i[h], r = i[h + 1], i[h] = c, i[h + 1] = l;
}
for (let a = 0; a < 50; a += 10) {
@@ -38908,7 +38908,7 @@ function DN(i, e = 24) {
for (let o = 0; o < 10; o++)
i[a + o] ^= ~t[(o + 2) % 10] & t[(o + 4) % 10];
}
- i[0] ^= FN[n], i[1] ^= NN[n];
+ i[0] ^= RN[n], i[1] ^= FN[n];
}
t.fill(0);
}
@@ -38917,10 +38917,10 @@ class Cp extends wp {
constructor(e, t, n, s = !1, r = 24) {
if (super(), this.blockLen = e, this.suffix = t, this.outputLen = n, this.enableXOF = s, this.rounds = r, this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, rh(n), 0 >= this.blockLen || this.blockLen >= 200)
throw new Error("Sha3 supports only keccak-f1600 function");
- this.state = new Uint8Array(200), this.state32 = XF(this.state);
+ this.state = new Uint8Array(200), this.state32 = jF(this.state);
}
keccak() {
- DN(this.state32, this.rounds), this.posOut = 0, this.pos = 0;
+ NN(this.state32, this.rounds), this.posOut = 0, this.pos = 0;
}
update(e) {
Oa(this);
@@ -38961,7 +38961,7 @@ class Cp extends wp {
return rh(e), this.xofInto(new Uint8Array(e));
}
digestInto(e) {
- if (wb(e, this), this.finished)
+ if (_b(e, this), this.finished)
throw new Error("digest() was already called");
return this.writeInto(e), this.destroy(), e;
}
@@ -38976,53 +38976,53 @@ class Cp extends wp {
return e || (e = new Cp(t, n, s, a, r)), e.state32.set(this.state32), e.pos = this.pos, e.posOut = this.posOut, e.finished = this.finished, e.rounds = r, e.suffix = n, e.outputLen = s, e.enableXOF = a, e.destroyed = this.destroyed, e;
}
}
-const LN = (i, e, t) => vp(() => new Cp(e, i, t)), PN = /* @__PURE__ */ LN(1, 136, 256 / 8);
-let Ub = !1;
-const Ob = function(i) {
- return PN(i);
+const DN = (i, e, t) => vp(() => new Cp(e, i, t)), LN = /* @__PURE__ */ DN(1, 136, 256 / 8);
+let kb = !1;
+const Ub = function(i) {
+ return LN(i);
};
-let Qb = Ob;
+let Ob = Ub;
function sn(i) {
const e = dt(i, "data");
- return Ie(Qb(e));
+ return Ie(Ob(e));
}
-sn._ = Ob;
+sn._ = Ub;
sn.lock = function() {
- Ub = !0;
+ kb = !0;
};
sn.register = function(i) {
- if (Ub)
+ if (kb)
throw new TypeError("keccak256 is locked");
- Qb = i;
+ Ob = i;
};
Object.freeze(sn);
-const Gb = function(i) {
- return IN("sha256").update(i).digest();
+const Qb = function(i) {
+ return CN("sha256").update(i).digest();
};
-let Hb = Gb, zb = !1;
+let Gb = Qb, Hb = !1;
function Za(i) {
const e = dt(i, "data");
- return Ie(Hb(e));
+ return Ie(Gb(e));
}
-Za._ = Gb;
+Za._ = Qb;
Za.lock = function() {
- zb = !0;
+ Hb = !0;
};
Za.register = function(i) {
- if (zb)
+ if (Hb)
throw new Error("sha256 is locked");
- Hb = i;
+ Gb = i;
};
Object.freeze(Za);
Object.freeze(Za);
BigInt(0);
-const kN = BigInt(1), UN = BigInt(2), Th = (i) => i instanceof Uint8Array, ON = /* @__PURE__ */ Array.from({ length: 256 }, (i, e) => e.toString(16).padStart(2, "0"));
+const PN = BigInt(1), kN = BigInt(2), Th = (i) => i instanceof Uint8Array, UN = /* @__PURE__ */ Array.from({ length: 256 }, (i, e) => e.toString(16).padStart(2, "0"));
function Qa(i) {
if (!Th(i))
throw new Error("Uint8Array expected");
let e = "";
for (let t = 0; t < i.length; t++)
- e += ON[i[t]];
+ e += UN[i[t]];
return e;
}
function Ip(i) {
@@ -39085,8 +39085,8 @@ function sc(...i) {
e.set(n, t), t += n.length;
}), e;
}
-const Bp = (i) => (UN << BigInt(i - 1)) - kN, Ju = (i) => new Uint8Array(i), mm = (i) => Uint8Array.from(i);
-function Vb(i, e, t) {
+const Bp = (i) => (kN << BigInt(i - 1)) - PN, Ju = (i) => new Uint8Array(i), mm = (i) => Uint8Array.from(i);
+function zb(i, e, t) {
if (typeof i != "number" || i < 2)
throw new Error("hashLen must be a number");
if (typeof e != "number" || e < 2)
@@ -39118,7 +39118,7 @@ function Vb(i, e, t) {
return a(), f;
};
}
-const QN = {
+const ON = {
bigint: (i) => typeof i == "bigint",
function: (i) => typeof i == "function",
boolean: (i) => typeof i == "boolean",
@@ -39131,7 +39131,7 @@ const QN = {
};
function xc(i, e, t = {}) {
const n = (s, r, a) => {
- const o = QN[r];
+ const o = ON[r];
if (typeof o != "function")
throw new Error(`Invalid validator "${r}", expected function`);
const c = i[s];
@@ -39144,14 +39144,14 @@ function xc(i, e, t = {}) {
n(s, r, !0);
return i;
}
-const GN = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
+const QN = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
bitMask: Bp,
bytesToHex: Qa,
bytesToNumberBE: Ir,
bytesToNumberLE: Sp,
concatBytes: sc,
- createHmacDrbg: Vb,
+ createHmacDrbg: zb,
ensureBytes: _i,
hexToBytes: ic,
hexToNumber: Ip,
@@ -39159,14 +39159,14 @@ const GN = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
numberToBytesLE: Mp,
validateObject: xc
}, Symbol.toStringTag, { value: "Module" }));
-const wn = BigInt(0), tn = BigInt(1), mr = BigInt(2), HN = BigInt(3), xf = BigInt(4), xm = BigInt(5), bm = BigInt(8);
+const wn = BigInt(0), tn = BigInt(1), mr = BigInt(2), GN = BigInt(3), xf = BigInt(4), xm = BigInt(5), bm = BigInt(8);
BigInt(9);
BigInt(16);
function jn(i, e) {
const t = i % e;
return t >= wn ? t : e + t;
}
-function zN(i, e, t) {
+function HN(i, e, t) {
if (t <= wn || e < wn)
throw new Error("Expected power/modulo > 0");
if (t === tn)
@@ -39194,12 +39194,12 @@ function bf(i, e) {
throw new Error("invert: does not exist");
return jn(s, e);
}
-function VN(i) {
+function zN(i) {
const e = (i - tn) / mr;
let t, n, s;
for (t = i - tn, n = 0; t % mr === wn; t /= mr, n++)
;
- for (s = mr; s < i && zN(s, e, i) !== i - tn; s++)
+ for (s = mr; s < i && HN(s, e, i) !== i - tn; s++)
;
if (n === 1) {
const a = (i + tn) / xf;
@@ -39227,8 +39227,8 @@ function VN(i) {
return u;
};
}
-function WN(i) {
- if (i % xf === HN) {
+function VN(i) {
+ if (i % xf === GN) {
const e = (i + tn) / xf;
return function(n, s) {
const r = n.pow(s, e);
@@ -39246,9 +39246,9 @@ function WN(i) {
return l;
};
}
- return VN(i);
+ return zN(i);
}
-const qN = [
+const WN = [
"create",
"isValid",
"is0",
@@ -39267,16 +39267,16 @@ const qN = [
"mulN",
"sqrN"
];
-function KN(i) {
+function qN(i) {
const e = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
- }, t = qN.reduce((n, s) => (n[s] = "function", n), e);
+ }, t = WN.reduce((n, s) => (n[s] = "function", n), e);
return xc(i, t);
}
-function jN(i, e, t) {
+function KN(i, e, t) {
if (t < wn)
throw new Error("Expected power > 0");
if (t === wn)
@@ -39288,21 +39288,21 @@ function jN(i, e, t) {
t & tn && (n = i.mul(n, s)), s = i.sqr(s), t >>= tn;
return n;
}
-function XN(i, e) {
+function jN(i, e) {
const t = new Array(e.length), n = e.reduce((r, a, o) => i.is0(a) ? r : (t[o] = r, i.mul(r, a)), i.ONE), s = i.inv(n);
return e.reduceRight((r, a, o) => i.is0(a) ? r : (t[o] = i.mul(r, t[o]), i.mul(r, a)), s), t;
}
-function Wb(i, e) {
+function Vb(i, e) {
const t = e !== void 0 ? e : i.toString(2).length, n = Math.ceil(t / 8);
return { nBitLength: t, nByteLength: n };
}
-function YN(i, e, t = !1, n = {}) {
+function XN(i, e, t = !1, n = {}) {
if (i <= wn)
throw new Error(`Expected Field ORDER > 0, got ${i}`);
- const { nBitLength: s, nByteLength: r } = Wb(i, e);
+ const { nBitLength: s, nByteLength: r } = Vb(i, e);
if (r > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
- const a = WN(i), o = Object.freeze({
+ const a = VN(i), o = Object.freeze({
ORDER: i,
BITS: s,
BYTES: r,
@@ -39323,7 +39323,7 @@ function YN(i, e, t = !1, n = {}) {
add: (c, l) => jn(c + l, i),
sub: (c, l) => jn(c - l, i),
mul: (c, l) => jn(c * l, i),
- pow: (c, l) => jN(o, c, l),
+ pow: (c, l) => KN(o, c, l),
div: (c, l) => jn(c * bf(l, i), i),
// Same as above, but doesn't normalize
sqrN: (c) => c * c,
@@ -39332,7 +39332,7 @@ function YN(i, e, t = !1, n = {}) {
mulN: (c, l) => c * l,
inv: (c) => bf(c, i),
sqrt: n.sqrt || ((c) => a(o, c)),
- invertBatch: (c) => XN(o, c),
+ invertBatch: (c) => jN(o, c),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (c, l, h) => h ? l : c,
@@ -39345,25 +39345,25 @@ function YN(i, e, t = !1, n = {}) {
});
return Object.freeze(o);
}
-function qb(i) {
+function Wb(i) {
if (typeof i != "bigint")
throw new Error("field order must be bigint");
const e = i.toString(2).length;
return Math.ceil(e / 8);
}
-function Kb(i) {
- const e = qb(i);
+function qb(i) {
+ const e = Wb(i);
return e + Math.ceil(e / 2);
}
-function JN(i, e, t = !1) {
- const n = i.length, s = qb(e), r = Kb(e);
+function YN(i, e, t = !1) {
+ const n = i.length, s = Wb(e), r = qb(e);
if (n < 16 || n < r || n > 1024)
throw new Error(`expected ${r}-1024 bytes of input, got ${n}`);
const a = t ? Ir(i) : Sp(i), o = jn(a, e - tn) + tn;
return t ? Mp(o, s) : Ga(o, s);
}
-const ZN = BigInt(0), Zu = BigInt(1);
-function $N(i, e) {
+const JN = BigInt(0), Zu = BigInt(1);
+function ZN(i, e) {
const t = (s, r) => {
const a = r.negate();
return s ? a : r;
@@ -39376,7 +39376,7 @@ function $N(i, e) {
// non-const time multiplication ladder
unsafeLadder(s, r) {
let a = i.ZERO, o = s;
- for (; r > ZN; )
+ for (; r > JN; )
r & Zu && (a = a.add(o)), o = o.double(), r >>= Zu;
return a;
},
@@ -39428,8 +39428,8 @@ function $N(i, e) {
}
};
}
-function jb(i) {
- return KN(i.Fp), xc(i, {
+function Kb(i) {
+ return qN(i.Fp), xc(i, {
n: "bigint",
h: "bigint",
Gx: "field",
@@ -39438,13 +39438,13 @@ function jb(i) {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
}), Object.freeze({
- ...Wb(i.n, i.nBitLength),
+ ...Vb(i.n, i.nBitLength),
...i,
p: i.Fp.ORDER
});
}
-function eD(i) {
- const e = jb(i);
+function $N(i) {
+ const e = Kb(i);
xc(e, {
a: "field",
b: "field"
@@ -39466,7 +39466,7 @@ function eD(i) {
}
return Object.freeze({ ...e });
}
-const { bytesToNumberBE: tD, hexToBytes: nD } = GN, _r = {
+const { bytesToNumberBE: eD, hexToBytes: tD } = QN, _r = {
// asn.1 DER encoding utils
Err: class extends Error {
constructor(e = "") {
@@ -39484,10 +39484,10 @@ const { bytesToNumberBE: tD, hexToBytes: nD } = GN, _r = {
throw new e("Invalid signature integer: negative");
if (n[0] === 0 && !(n[1] & 128))
throw new e("Invalid signature integer: unnecessary leading zero");
- return { d: tD(n), l: i.subarray(t + 2) };
+ return { d: eD(n), l: i.subarray(t + 2) };
},
toSig(i) {
- const { Err: e } = _r, t = typeof i == "string" ? nD(i) : i;
+ const { Err: e } = _r, t = typeof i == "string" ? tD(i) : i;
if (!(t instanceof Uint8Array))
throw new Error("ui8a expected");
let n = t.length;
@@ -39511,8 +39511,8 @@ const { bytesToNumberBE: tD, hexToBytes: nD } = GN, _r = {
BigInt(2);
const Em = BigInt(3);
BigInt(4);
-function iD(i) {
- const e = eD(i), { Fp: t } = e, n = e.toBytes || ((p, m, g) => {
+function nD(i) {
+ const e = $N(i), { Fp: t } = e, n = e.toBytes || ((p, m, g) => {
const A = m.toAffine();
return sc(Uint8Array.from([4]), t.toBytes(A.x), t.toBytes(A.y));
}), s = e.fromBytes || ((p) => {
@@ -39760,7 +39760,7 @@ function iD(i) {
}
}
u.BASE = new u(e.Gx, e.Gy, t.ONE), u.ZERO = new u(t.ZERO, t.ONE, t.ZERO);
- const d = e.nBitLength, f = $N(u, e.endo ? Math.ceil(d / 2) : d);
+ const d = e.nBitLength, f = ZN(u, e.endo ? Math.ceil(d / 2) : d);
return {
CURVE: e,
ProjectivePoint: u,
@@ -39769,8 +39769,8 @@ function iD(i) {
isWithinCurveOrder: a
};
}
-function sD(i) {
- const e = jb(i);
+function iD(i) {
+ const e = Kb(i);
return xc(e, {
hash: "hash",
hmac: "function",
@@ -39781,8 +39781,8 @@ function sD(i) {
lowS: "boolean"
}), Object.freeze({ lowS: !0, ...e });
}
-function rD(i) {
- const e = sD(i), { Fp: t, n } = e, s = t.BYTES + 1, r = 2 * t.BYTES + 1;
+function sD(i) {
+ const e = iD(i), { Fp: t, n } = e, s = t.BYTES + 1, r = 2 * t.BYTES + 1;
function a(D) {
return as < D && D < t.ORDER;
}
@@ -39792,7 +39792,7 @@ function rD(i) {
function c(D) {
return bf(D, n);
}
- const { ProjectivePoint: l, normPrivateKeyToScalar: h, weierstrassEquation: u, isWithinCurveOrder: d } = iD({
+ const { ProjectivePoint: l, normPrivateKeyToScalar: h, weierstrassEquation: u, isWithinCurveOrder: d } = nD({
...e,
toBytes(D, O, Y) {
const Q = O.toAffine(), J = t.toBytes(Q.x), ee = sc;
@@ -39895,8 +39895,8 @@ function rD(i) {
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
- const D = Kb(e.n);
- return JN(e.randomBytes(D), e.n);
+ const D = qb(e.n);
+ return YN(e.randomBytes(D), e.n);
},
/**
* Creates precompute table for an arbitrary EC point. Makes point "cached".
@@ -39967,7 +39967,7 @@ function rD(i) {
const F = { lowS: e.lowS, prehash: !1 }, K = { lowS: e.lowS, prehash: !1 };
function q(D, O, Y = F) {
const { seed: Q, k2sig: J } = v(D, O, Y), ee = e;
- return Vb(ee.hash.outputLen, ee.nByteLength, ee.hmac)(Q, J);
+ return zb(ee.hash.outputLen, ee.nByteLength, ee.hmac)(Q, J);
}
l.BASE._setWindowSize(8);
function $(D, O, Y, Q = K) {
@@ -40013,25 +40013,25 @@ function rD(i) {
utils: _
};
}
-function aD(i) {
+function rD(i) {
return {
hash: i,
- hmac: (e, ...t) => Ib(i, e, ZF(...t)),
- randomBytes: $F
+ hmac: (e, ...t) => Cb(i, e, JF(...t)),
+ randomBytes: ZF
};
}
-function oD(i, e) {
- const t = (n) => rD({ ...i, ...aD(n) });
+function aD(i, e) {
+ const t = (n) => sD({ ...i, ...rD(n) });
return Object.freeze({ ...t(e), create: t });
}
-const Xb = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), ym = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), cD = BigInt(1), Ef = BigInt(2), _m = (i, e) => (i + e / Ef) / e;
-function lD(i) {
- const e = Xb, t = BigInt(3), n = BigInt(6), s = BigInt(11), r = BigInt(22), a = BigInt(23), o = BigInt(44), c = BigInt(88), l = i * i * i % e, h = l * l * i % e, u = ri(h, t, e) * h % e, d = ri(u, t, e) * h % e, f = ri(d, Ef, e) * l % e, p = ri(f, s, e) * f % e, m = ri(p, r, e) * p % e, g = ri(m, o, e) * m % e, A = ri(g, c, e) * g % e, _ = ri(A, o, e) * m % e, x = ri(_, t, e) * h % e, E = ri(x, a, e) * p % e, S = ri(E, n, e) * l % e, w = ri(S, Ef, e);
+const jb = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), ym = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), oD = BigInt(1), Ef = BigInt(2), _m = (i, e) => (i + e / Ef) / e;
+function cD(i) {
+ const e = jb, t = BigInt(3), n = BigInt(6), s = BigInt(11), r = BigInt(22), a = BigInt(23), o = BigInt(44), c = BigInt(88), l = i * i * i % e, h = l * l * i % e, u = ri(h, t, e) * h % e, d = ri(u, t, e) * h % e, f = ri(d, Ef, e) * l % e, p = ri(f, s, e) * f % e, m = ri(p, r, e) * p % e, g = ri(m, o, e) * m % e, A = ri(g, c, e) * g % e, _ = ri(A, o, e) * m % e, x = ri(_, t, e) * h % e, E = ri(x, a, e) * p % e, S = ri(E, n, e) * l % e, w = ri(S, Ef, e);
if (!yf.eql(yf.sqr(w), i))
throw new Error("Cannot find square root");
return w;
}
-const yf = YN(Xb, void 0, void 0, { sqrt: lD }), ks = oD({
+const yf = XN(jb, void 0, void 0, { sqrt: cD }), ks = aD({
a: BigInt(0),
b: BigInt(7),
Fp: yf,
@@ -40050,7 +40050,7 @@ const yf = YN(Xb, void 0, void 0, { sqrt: lD }), ks = oD({
endo: {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
splitScalar: (i) => {
- const e = ym, t = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), n = -cD * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), s = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), r = t, a = BigInt("0x100000000000000000000000000000000"), o = _m(r * i, e), c = _m(-n * i, e);
+ const e = ym, t = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), n = -oD * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), s = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), r = t, a = BigInt("0x100000000000000000000000000000000"), o = _m(r * i, e), c = _m(-n * i, e);
let l = jn(i - o * t - c * s, e), h = jn(-o * n - c * r, e);
const u = l > a, d = h > a;
if (u && (l = e - l), d && (h = e - h), l > a || h > a)
@@ -40058,10 +40058,10 @@ const yf = YN(Xb, void 0, void 0, { sqrt: lD }), ks = oD({
return { k1neg: u, k1: l, k2neg: d, k2: h };
}
}
-}, Mb);
+}, Sb);
BigInt(0);
ks.ProjectivePoint;
-const rc = "0x0000000000000000000000000000000000000000", wm = "0x0000000000000000000000000000000000000000000000000000000000000000", vm = BigInt(0), Cm = BigInt(1), _f = BigInt(2), Im = BigInt(27), Sm = BigInt(28), El = BigInt(35), Yb = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), hD = Yb / _f, uD = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), lr = {};
+const rc = "0x0000000000000000000000000000000000000000", wm = "0x0000000000000000000000000000000000000000000000000000000000000000", vm = BigInt(0), Cm = BigInt(1), _f = BigInt(2), Im = BigInt(27), Sm = BigInt(28), El = BigInt(35), Xb = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), lD = Xb / _f, hD = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), lr = {};
function $u(i) {
return Es(rn(i), 32);
}
@@ -40106,7 +40106,7 @@ class zt {
* Returns true if the Signature is valid for [[link-eip-2]] signatures.
*/
isValid() {
- return BigInt(this.#t) <= hD;
+ return BigInt(this.#t) <= lD;
}
/**
* The ``v`` value for a signature.
@@ -40184,7 +40184,7 @@ class zt {
getCanonical() {
if (this.isValid())
return this;
- const e = Yb - BigInt(this._s), t = 55 - this.v, n = new zt(lr, this.r, $u(e), t);
+ const e = Xb - BigInt(this._s), t = 55 - this.v, n = new zt(lr, this.r, $u(e), t);
return this.networkV && (n.#i = this.networkV), n;
}
/**
@@ -40207,7 +40207,7 @@ class zt {
v: this.v
};
}
- [uD]() {
+ [hD]() {
return this.toString();
}
toString() {
@@ -40484,7 +40484,7 @@ class os {
return "0x" + s.add(r).toHex(!!n);
}
}
-const dD = BigInt(0), fD = BigInt(36);
+const uD = BigInt(0), dD = BigInt(36);
function Mm(i) {
i = i.toLowerCase();
const e = i.substring(2).split(""), t = new Uint8Array(40);
@@ -40501,7 +40501,7 @@ for (let i = 0; i < 10; i++)
for (let i = 0; i < 26; i++)
Tp[String.fromCharCode(65 + i)] = String(10 + i);
const Bm = 15;
-function pD(i) {
+function fD(i) {
i = i.toUpperCase(), i = i.substring(4) + i.substring(0, 2) + "00";
let e = i.split("").map((n) => Tp[n]).join("");
for (; e.length >= Bm; ) {
@@ -40513,7 +40513,7 @@ function pD(i) {
t = "0" + t;
return t;
}
-const AD = (function() {
+const pD = (function() {
const i = {};
for (let e = 0; e < 36; e++) {
const t = "0123456789abcdefghijklmnopqrstuvwxyz"[e];
@@ -40521,11 +40521,11 @@ const AD = (function() {
}
return i;
})();
-function gD(i) {
+function AD(i) {
i = i.toLowerCase();
- let e = dD;
+ let e = uD;
for (let t = 0; t < i.length; t++)
- e = e * fD + AD[i[t]];
+ e = e * dD + pD[i[t]];
return e;
}
function Mt(i) {
@@ -40535,20 +40535,20 @@ function Mt(i) {
return V(!i.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || e === i, "bad address checksum", "address", i), e;
}
if (i.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
- V(i.substring(2, 4) === pD(i), "bad icap checksum", "address", i);
- let e = gD(i.substring(4)).toString(16);
+ V(i.substring(2, 4) === fD(i), "bad icap checksum", "address", i);
+ let e = AD(i.substring(4)).toString(16);
for (; e.length < 40; )
e = "0" + e;
return Mm("0x" + e);
}
V(!1, "invalid address", "address", i);
}
-function mD(i) {
+function gD(i) {
const e = Mt(i.from);
let n = De(i.nonce, "tx.nonce").toString(16);
return n === "0" ? n = "0x" : n.length % 2 ? n = "0x0" + n : n = "0x" + n, Mt(Kt(sn(ms([e, n])), 12));
}
-function Jb(i) {
+function Yb(i) {
return i && typeof i.getAddress == "function";
}
async function ed(i, e) {
@@ -40558,7 +40558,7 @@ async function ed(i, e) {
function zn(i, e) {
if (typeof i == "string")
return i.match(/^0x[0-9a-f]{40}$/i) ? Mt(i) : (ge(e != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" }), ed(i, e.resolveName(i)));
- if (Jb(i))
+ if (Yb(i))
return ed(i, i.getAddress());
if (i && typeof i.then == "function")
return ed(i, i);
@@ -41319,7 +41319,7 @@ class jt {
return e;
}
}
-class xD extends _s {
+class mD extends _s {
constructor(e) {
super("address", "address", e, !1);
}
@@ -41339,7 +41339,7 @@ class xD extends _s {
return Mt(Ys(e.readValue(), 20));
}
}
-class bD extends _s {
+class xD extends _s {
coder;
constructor(e) {
super(e.name, e.type, "_", e.dynamic), this.coder = e;
@@ -41354,7 +41354,7 @@ class bD extends _s {
return this.coder.decode(e);
}
}
-function Zb(i, e, t) {
+function Jb(i, e, t) {
let n = [];
if (Array.isArray(t))
n = t;
@@ -41385,7 +41385,7 @@ function Zb(i, e, t) {
let o = i.appendWriter(s);
return o += i.appendWriter(r), o;
}
-function $b(i, e) {
+function Zb(i, e) {
let t = [], n = [], s = i.subReader(0);
return e.forEach((r) => {
let a = null;
@@ -41411,7 +41411,7 @@ function $b(i, e) {
t.push(a), n.push(r.localName || null);
}), ds.fromItems(t, n);
}
-class ED extends _s {
+class bD extends _s {
coder;
length;
constructor(e, t, n) {
@@ -41428,22 +41428,22 @@ class ED extends _s {
const n = jt.dereference(t, "array");
Array.isArray(n) || this._throwError("expected array value", n);
let s = this.length;
- s === -1 && (s = n.length, e.writeValue(n.length)), hb(n.length, s, "coder array" + (this.localName ? " " + this.localName : ""));
+ s === -1 && (s = n.length, e.writeValue(n.length)), lb(n.length, s, "coder array" + (this.localName ? " " + this.localName : ""));
let r = [];
for (let a = 0; a < n.length; a++)
r.push(this.coder);
- return Zb(e, r, n);
+ return Jb(e, r, n);
}
decode(e) {
let t = this.length;
t === -1 && (t = e.readIndex(), ge(t * Hn <= e.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: e.bytes, offset: t * Hn, length: e.dataLength }));
let n = [];
for (let s = 0; s < t; s++)
- n.push(new bD(this.coder));
- return $b(e, n);
+ n.push(new xD(this.coder));
+ return Zb(e, n);
}
}
-class yD extends _s {
+class ED extends _s {
constructor(e) {
super("bool", "bool", e, !1);
}
@@ -41458,7 +41458,7 @@ class yD extends _s {
return !!e.readValue();
}
}
-class eE extends _s {
+class $b extends _s {
constructor(e, t) {
super(e, e, t, !0);
}
@@ -41474,7 +41474,7 @@ class eE extends _s {
return e.readBytes(e.readIndex(), !0);
}
}
-class _D extends eE {
+class yD extends $b {
constructor(e) {
super("bytes", e);
}
@@ -41482,7 +41482,7 @@ class _D extends eE {
return Ie(super.decode(e));
}
}
-class wD extends _s {
+class _D extends _s {
size;
constructor(e, t) {
let n = "bytes" + String(e);
@@ -41499,8 +41499,8 @@ class wD extends _s {
return Ie(e.readBytes(this.size));
}
}
-const vD = new Uint8Array([]);
-class CD extends _s {
+const wD = new Uint8Array([]);
+class vD extends _s {
constructor(e) {
super("null", "", e, !1);
}
@@ -41508,14 +41508,14 @@ class CD extends _s {
return null;
}
encode(e, t) {
- return t != null && this._throwError("not null", t), e.writeBytes(vD);
+ return t != null && this._throwError("not null", t), e.writeBytes(wD);
}
decode(e) {
return e.readBytes(0), null;
}
}
-const ID = BigInt(0), SD = BigInt(1), MD = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
-class BD extends _s {
+const CD = BigInt(0), ID = BigInt(1), SD = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
+class MD extends _s {
size;
signed;
constructor(e, t, n) {
@@ -41526,19 +41526,19 @@ class BD extends _s {
return 0;
}
encode(e, t) {
- let n = De(jt.dereference(t, this.type)), s = So(MD, Hn * 8);
+ let n = De(jt.dereference(t, this.type)), s = So(SD, Hn * 8);
if (this.signed) {
let r = So(s, this.size * 8 - 1);
- (n > r || n < -(r + SD)) && this._throwError("value out-of-bounds", t), n = fb(n, 8 * Hn);
- } else (n < ID || n > So(s, this.size * 8)) && this._throwError("value out-of-bounds", t);
+ (n > r || n < -(r + ID)) && this._throwError("value out-of-bounds", t), n = db(n, 8 * Hn);
+ } else (n < CD || n > So(s, this.size * 8)) && this._throwError("value out-of-bounds", t);
return e.writeValue(n);
}
decode(e) {
let t = So(e.readValue(), this.size * 8);
- return this.signed && (t = BF(t, this.size * 8)), t;
+ return this.signed && (t = MF(t, this.size * 8)), t;
}
}
-class TD extends eE {
+class BD extends $b {
constructor(e) {
super("string", e);
}
@@ -41579,10 +41579,10 @@ class yl extends _s {
}
encode(e, t) {
const n = jt.dereference(t, "tuple");
- return Zb(e, this.coders, n);
+ return Jb(e, this.coders, n);
}
decode(e) {
- return $b(e, this.coders);
+ return Zb(e, this.coders);
}
}
function td(i, e) {
@@ -41601,7 +41601,7 @@ function Hr(i) {
});
return e.sort((t, n) => t.address.localeCompare(n.address)), e;
}
-function tE(i) {
+function eE(i) {
return {
address: Mt(i.address),
nonce: De(i.nonce != null ? i.nonce : 0),
@@ -41609,15 +41609,15 @@ function tE(i) {
signature: zt.from(i.signature)
};
}
-function RD(i) {
+function TD(i) {
let e;
return typeof i == "string" ? e = os.computePublicKey(i, !1) : e = i.publicKey, Mt(sn("0x" + e.substring(4)).substring(26));
}
-function FD(i, e) {
- return RD(os.recoverPublicKey(i, e));
+function RD(i, e) {
+ return TD(os.recoverPublicKey(i, e));
}
-const _n = BigInt(0), ND = BigInt(2), DD = BigInt(27), LD = BigInt(28), PD = BigInt(35), kD = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), UD = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), nd = 4096 * 32, Nl = 128;
-function OD(i) {
+const _n = BigInt(0), FD = BigInt(2), ND = BigInt(27), DD = BigInt(28), LD = BigInt(35), PD = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), kD = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), nd = 4096 * 32, Nl = 128;
+function UD(i) {
return { blobToKzgCommitment: (n) => {
if ("computeBlobProof" in i) {
if ("blobToKzgCommitment" in i && typeof i.blobToKzgCommitment == "function")
@@ -41653,7 +41653,7 @@ function Rh(i, e) {
V(!1, t.message, e, i);
}
}
-function QD(i, e) {
+function OD(i, e) {
try {
if (!Array.isArray(i))
throw new Error("authorizationList: invalid array");
@@ -41689,7 +41689,7 @@ function Nt(i, e) {
if (i === "0x")
return _n;
const t = De(i, e);
- return V(t <= kD, "value exceeds uint size", e, t), t;
+ return V(t <= PD, "value exceeds uint size", e, t), t;
}
function Et(i, e) {
const t = De(i, "value"), n = rn(t);
@@ -41698,7 +41698,7 @@ function Et(i, e) {
function Fh(i) {
return Hr(i).map((e) => [e.address, e.storageKeys]);
}
-function GD(i) {
+function QD(i) {
return i.map((e) => [
Et(e.chainId, "chainId"),
e.address,
@@ -41708,13 +41708,13 @@ function GD(i) {
rn(e.signature._s)
]);
}
-function HD(i, e) {
+function GD(i, e) {
V(Array.isArray(i), `invalid ${e}`, "value", i);
for (let t = 0; t < i.length; t++)
V(Ut(i[t], 32), "invalid ${ param } hash", `value[${t}]`, i[t]);
return i;
}
-function zD(i) {
+function HD(i) {
const e = mc(i);
V(Array.isArray(e) && (e.length === 9 || e.length === 6), "invalid field count for legacy transaction", "data", i);
const t = {
@@ -41733,8 +41733,8 @@ function zD(i) {
if (s === _n && r === _n)
t.chainId = n;
else {
- let a = (n - PD) / ND;
- a < _n && (a = _n), t.chainId = a, V(a !== _n || n === DD || n === LD, "non-canonical legacy v", "v", e[6]), t.signature = zt.from({
+ let a = (n - LD) / FD;
+ a < _n && (a = _n), t.chainId = a, V(a !== _n || n === ND || n === DD, "non-canonical legacy v", "v", e[6]), t.signature = zt.from({
r: Es(e[7], 32),
s: Es(e[8], 32),
v: n
@@ -41742,7 +41742,7 @@ function zD(i) {
}
return t;
}
-function VD(i, e) {
+function zD(i, e) {
const t = [
Et(i.nonce, "nonce"),
Et(i.gasPrice || 0, "gasPrice"),
@@ -41774,7 +41774,7 @@ function Nh(i, e) {
const n = Es(e[1], 32), s = Es(e[2], 32), r = zt.from({ r: n, s, yParity: t });
i.signature = r;
}
-function WD(i) {
+function VD(i) {
const e = mc(dt(i).slice(1));
V(Array.isArray(e) && (e.length === 9 || e.length === 12), "invalid field count for transaction type: 2", "data", Ie(i));
const t = {
@@ -41792,7 +41792,7 @@ function WD(i) {
};
return e.length === 9 || Nh(t, e.slice(9)), t;
}
-function qD(i, e) {
+function WD(i, e) {
const t = [
Et(i.chainId, "chainId"),
Et(i.nonce, "nonce"),
@@ -41806,7 +41806,7 @@ function qD(i, e) {
];
return e && (t.push(Et(e.yParity, "yParity")), t.push(rn(e.r)), t.push(rn(e.s))), Ht(["0x02", ms(t)]);
}
-function KD(i) {
+function qD(i) {
const e = mc(dt(i).slice(1));
V(Array.isArray(e) && (e.length === 8 || e.length === 11), "invalid field count for transaction type: 1", "data", Ie(i));
const t = {
@@ -41822,7 +41822,7 @@ function KD(i) {
};
return e.length === 8 || Nh(t, e.slice(8)), t;
}
-function jD(i, e) {
+function KD(i, e) {
const t = [
Et(i.chainId, "chainId"),
Et(i.nonce, "nonce"),
@@ -41835,7 +41835,7 @@ function jD(i, e) {
];
return e && (t.push(Et(e.yParity, "recoveryParam")), t.push(rn(e.r)), t.push(rn(e.s))), Ht(["0x01", ms(t)]);
}
-function XD(i) {
+function jD(i) {
let e = mc(dt(i).slice(1)), t = "3", n = null, s = null;
if (e.length === 4 && Array.isArray(e[0])) {
t = "3 (network format)";
@@ -41886,7 +41886,7 @@ function XD(i) {
V(Ut(r.blobVersionedHashes[a], 32), `invalid blobVersionedHash at index ${a}: must be length 32`, "data", i);
return e.length === 11 || Nh(r, e.slice(11)), r;
}
-function YD(i, e, t) {
+function XD(i, e, t) {
const n = [
Et(i.chainId, "chainId"),
Et(i.nonce, "nonce"),
@@ -41898,7 +41898,7 @@ function YD(i, e, t) {
i.data,
Fh(i.accessList || []),
Et(i.maxFeePerBlobGas || 0, "maxFeePerBlobGas"),
- HD(i.blobVersionedHashes || [], "blobVersionedHashes")
+ GD(i.blobVersionedHashes || [], "blobVersionedHashes")
];
if (e && (n.push(Et(e.yParity, "yParity")), n.push(rn(e.r)), n.push(rn(e.s)), t)) {
if (i.blobWrapperVersion != null) {
@@ -41931,7 +41931,7 @@ function YD(i, e, t) {
}
return Ht(["0x03", ms(n)]);
}
-function JD(i) {
+function YD(i) {
const e = mc(dt(i).slice(1));
V(Array.isArray(e) && (e.length === 10 || e.length === 13), "invalid field count for transaction type: 4", "data", Ie(i));
const t = {
@@ -41946,11 +41946,11 @@ function JD(i) {
value: Nt(e[6], "value"),
data: Ie(e[7]),
accessList: Rh(e[8], "accessList"),
- authorizationList: QD(e[9], "authorizationList")
+ authorizationList: OD(e[9], "authorizationList")
};
return e.length === 10 || Nh(t, e.slice(10)), t;
}
-function ZD(i, e) {
+function JD(i, e) {
const t = [
Et(i.chainId, "chainId"),
Et(i.nonce, "nonce"),
@@ -41961,7 +41961,7 @@ function ZD(i, e) {
Et(i.value, "value"),
i.data,
Fh(i.accessList || []),
- GD(i.authorizationList || [])
+ QD(i.authorizationList || [])
];
return e && (t.push(Et(e.yParity, "yParity")), t.push(rn(e.r)), t.push(rn(e.s))), Ht(["0x04", ms(t)]);
}
@@ -42175,7 +42175,7 @@ class wi {
return e == null && this.type === 4 ? [] : e;
}
set authorizationList(e) {
- this.#x = e == null ? null : e.map((t) => tE(t));
+ this.#x = e == null ? null : e.map((t) => eE(t));
}
/**
* The max fee per blob gas for Cancun transactions.
@@ -42267,7 +42267,7 @@ class wi {
return this.#u;
}
set kzg(e) {
- e == null ? this.#u = null : this.#u = OD(e);
+ e == null ? this.#u = null : this.#u = UD(e);
}
get blobWrapperVersion() {
return this.#g;
@@ -42300,7 +42300,7 @@ class wi {
* The sending address, if signed. Otherwise, ``null``.
*/
get from() {
- return this.signature == null ? null : FD(this.unsignedHash, this.signature.getCanonical());
+ return this.signature == null ? null : RD(this.unsignedHash, this.signature.getCanonical());
}
/**
* The public key of the sender, if signed. Otherwise, ``null``.
@@ -42322,15 +42322,15 @@ class wi {
const n = e ? this.signature : null;
switch (this.inferType()) {
case 0:
- return VD(this, n);
+ return zD(this, n);
case 1:
- return jD(this, n);
+ return KD(this, n);
case 2:
- return qD(this, n);
+ return WD(this, n);
case 3:
- return YD(this, n, t ? this.blobs : null);
+ return XD(this, n, t ? this.blobs : null);
case 4:
- return ZD(this, n);
+ return JD(this, n);
}
ge(!1, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
}
@@ -42437,7 +42437,7 @@ class wi {
accessList: this.accessList
};
}
- [UD]() {
+ [kD]() {
return this.toString();
}
toString() {
@@ -42467,16 +42467,16 @@ class wi {
if (typeof e == "string") {
const n = dt(e);
if (n[0] >= 127)
- return wi.from(zD(n));
+ return wi.from(HD(n));
switch (n[0]) {
case 1:
- return wi.from(KD(n));
+ return wi.from(qD(n));
case 2:
- return wi.from(WD(n));
+ return wi.from(VD(n));
case 3:
- return wi.from(XD(n));
+ return wi.from(jD(n));
case 4:
- return wi.from(JD(n));
+ return wi.from(YD(n));
}
ge(!1, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" });
}
@@ -42487,9 +42487,9 @@ class wi {
function kr(i) {
return sn(gs(i));
}
-var $D = "AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmx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nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI";
const Fm = /* @__PURE__ */ new Map([[8217, "apostrophe"], [8260, "fraction slash"], [12539, "middle dot"]]), Nm = 4;
-function eL(i) {
+function $D(i) {
let e = 0;
function t() {
return i[e++] << 8 | i[e++];
@@ -42536,14 +42536,14 @@ function eL(i) {
}
});
}
-function tL(i) {
+function eL(i) {
let e = 0;
return () => i[e++];
}
-function nE(i) {
- return tL(eL(nL(i)));
+function tE(i) {
+ return eL($D(tL(i)));
}
-function nL(i) {
+function tL(i) {
let e = [];
[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((s, r) => e[s.charCodeAt(0)] = r);
let t = i.length, n = new Uint8Array(6 * t >> 3);
@@ -42551,12 +42551,12 @@ function nL(i) {
o = o << 6 | e[i.charCodeAt(s)], a += 6, a >= 8 && (n[r++] = o >> (a -= 8));
return n;
}
-function iL(i) {
+function nL(i) {
return i & 1 ? ~i >> 1 : i >> 1;
}
-function sL(i, e) {
+function iL(i, e) {
let t = Array(i);
- for (let n = 0, s = 0; n < i; n++) t[n] = s += iL(e());
+ for (let n = 0, s = 0; n < i; n++) t[n] = s += nL(e());
return t;
}
function ac(i, e = 0) {
@@ -42571,23 +42571,23 @@ function ac(i, e = 0) {
}
return t;
}
-function iE(i) {
+function nE(i) {
return oc(() => {
let e = ac(i);
if (e.length) return e;
});
}
-function sE(i) {
+function iE(i) {
let e = [];
for (; ; ) {
let t = i();
if (t == 0) break;
- e.push(rL(t, i));
+ e.push(sL(t, i));
}
for (; ; ) {
let t = i() - 1;
if (t < 0) break;
- e.push(aL(t, i));
+ e.push(rL(t, i));
}
return e.flat();
}
@@ -42600,15 +42600,15 @@ function oc(i) {
}
return e;
}
-function rE(i, e, t) {
+function sE(i, e, t) {
let n = Array(i).fill().map(() => []);
for (let s = 0; s < e; s++)
- sL(i, t).forEach((r, a) => n[a].push(r));
+ iL(i, t).forEach((r, a) => n[a].push(r));
return n;
}
-function rL(i, e) {
+function sL(i, e) {
let t = 1 + e(), n = e(), s = oc(e);
- return rE(s.length, 1 + i, e).flatMap((a, o) => {
+ return sE(s.length, 1 + i, e).flatMap((a, o) => {
let [c, ...l] = a;
return Array(s[o]).fill().map((h, u) => {
let d = u * n;
@@ -42616,11 +42616,11 @@ function rL(i, e) {
});
});
}
-function aL(i, e) {
+function rL(i, e) {
let t = 1 + e();
- return rE(t, 1 + i, e).map((s) => [s[0], s.slice(1)]);
+ return sE(t, 1 + i, e).map((s) => [s[0], s.slice(1)]);
}
-function oL(i) {
+function aL(i) {
let e = [], t = ac(i);
return s(n([]), []), e;
function n(r) {
@@ -42639,13 +42639,13 @@ function oL(i) {
}
}
}
-function cL(i) {
+function oL(i) {
return i.toString(16).toUpperCase().padStart(2, "0");
}
-function aE(i) {
- return `{${cL(i)}}`;
+function rE(i) {
+ return `{${oL(i)}}`;
}
-function lL(i) {
+function cL(i) {
let e = [];
for (let t = 0, n = i.length; t < n; ) {
let s = i.codePointAt(t);
@@ -42661,24 +42661,24 @@ function Ha(i) {
n.push(String.fromCodePoint(...i.slice(s, s += 4096)));
return n.join("");
}
-function hL(i, e) {
+function lL(i, e) {
let t = i.length, n = t - e.length;
for (let s = 0; n == 0 && s < t; s++) n = i[s] - e[s];
return n;
}
-var uL = "AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2Hcg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yS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";
-const cc = 44032, ah = 4352, oh = 4449, ch = 4519, oE = 19, cE = 21, za = 28, lh = cE * za, dL = oE * lh, fL = cc + dL, pL = ah + oE, AL = oh + cE, gL = ch + za;
+var hL = "AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09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fs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";
+const cc = 44032, ah = 4352, oh = 4449, ch = 4519, aE = 19, oE = 21, za = 28, lh = oE * za, uL = aE * lh, dL = cc + uL, fL = ah + aE, pL = oh + oE, AL = ch + za;
function Mo(i) {
return i >> 24 & 255;
}
-function lE(i) {
+function cE(i) {
return i & 16777215;
}
let wf, Dm, vf, Dl;
-function mL() {
- let i = nE(uL);
- wf = new Map(iE(i).flatMap((e, t) => e.map((n) => [n, t + 1 << 24]))), Dm = new Set(ac(i)), vf = /* @__PURE__ */ new Map(), Dl = /* @__PURE__ */ new Map();
- for (let [e, t] of sE(i)) {
+function gL() {
+ let i = tE(hL);
+ wf = new Map(nE(i).flatMap((e, t) => e.map((n) => [n, t + 1 << 24]))), Dm = new Set(ac(i)), vf = /* @__PURE__ */ new Map(), Dl = /* @__PURE__ */ new Map();
+ for (let [e, t] of iE(i)) {
if (!Dm.has(e) && t.length == 2) {
let [n, s] = t, r = Dl.get(n);
r || (r = /* @__PURE__ */ new Map(), Dl.set(n, r)), r.set(s, e);
@@ -42686,21 +42686,21 @@ function mL() {
vf.set(e, t.reverse());
}
}
-function hE(i) {
- return i >= cc && i < fL;
+function lE(i) {
+ return i >= cc && i < dL;
}
-function xL(i, e) {
- if (i >= ah && i < pL && e >= oh && e < AL)
+function mL(i, e) {
+ if (i >= ah && i < fL && e >= oh && e < pL)
return cc + (i - ah) * lh + (e - oh) * za;
- if (hE(i) && e > ch && e < gL && (i - cc) % za == 0)
+ if (lE(i) && e > ch && e < AL && (i - cc) % za == 0)
return i + (e - ch);
{
let t = Dl.get(i);
return t && (t = t.get(e), t) ? t : -1;
}
}
-function uE(i) {
- wf || mL();
+function hE(i) {
+ wf || gL();
let e = [], t = [], n = !1;
function s(r) {
let a = wf.get(r);
@@ -42710,7 +42710,7 @@ function uE(i) {
for (; ; ) {
if (r < 128)
e.push(r);
- else if (hE(r)) {
+ else if (lE(r)) {
let a = r - cc, o = a / lh | 0, c = a % lh / za | 0, l = a % za;
s(ah + o), s(oh + c), l > 0 && s(ch + l);
} else {
@@ -42738,44 +42738,44 @@ function uE(i) {
}
return e;
}
-function bL(i) {
+function xL(i) {
let e = [], t = [], n = -1, s = 0;
for (let r of i) {
- let a = Mo(r), o = lE(r);
+ let a = Mo(r), o = cE(r);
if (n == -1)
a == 0 ? n = o : e.push(o);
else if (s > 0 && s >= a)
a == 0 ? (e.push(n, ...t), t.length = 0, n = o) : t.push(o), s = a;
else {
- let c = xL(n, o);
+ let c = mL(n, o);
c >= 0 ? n = c : s == 0 && a == 0 ? (e.push(n), n = o) : (t.push(o), s = a);
}
}
return n >= 0 && e.push(n, ...t), e;
}
-function dE(i) {
- return uE(i).map(lE);
+function uE(i) {
+ return hE(i).map(cE);
}
-function EL(i) {
- return bL(uE(i));
+function bL(i) {
+ return xL(hE(i));
}
-const Lm = 45, fE = ".", pE = 65039, AE = 1, hh = (i) => Array.from(i);
+const Lm = 45, dE = ".", fE = 65039, pE = 1, hh = (i) => Array.from(i);
function lc(i, e) {
return i.P.has(e) || i.Q.has(e);
}
-class yL extends Array {
+class EL extends Array {
get is_emoji() {
return !0;
}
// free tagging system
}
-let Cf, gE, wr, If, mE, Ra, id, Aa, fr, Pm, Sf;
+let Cf, AE, wr, If, gE, Ra, id, Aa, fr, Pm, Sf;
function Rp() {
if (Cf) return;
- let i = nE($D);
+ let i = tE(ZD);
const e = () => ac(i), t = () => new Set(e()), n = (h, u) => u.forEach((d) => h.add(d));
- Cf = new Map(sE(i)), gE = t(), wr = e(), If = new Set(e().map((h) => wr[h])), wr = new Set(wr), mE = t(), t();
- let s = iE(i), r = i();
+ Cf = new Map(iE(i)), AE = t(), wr = e(), If = new Set(e().map((h) => wr[h])), wr = new Set(wr), gE = t(), t();
+ let s = nE(i), r = i();
const a = () => {
let h = /* @__PURE__ */ new Set();
return e().forEach((u) => n(h, s[u])), n(h, e()), h;
@@ -42815,8 +42815,8 @@ function Rp() {
for (let u of h.Q) l(u);
}
for (let h of fr)
- !Aa.has(h) && !c.has(h) && Aa.set(h, AE);
- n(fr, dE(fr)), Pm = oL(i).map((h) => yL.from(h)).sort(hL), Sf = /* @__PURE__ */ new Map();
+ !Aa.has(h) && !c.has(h) && Aa.set(h, pE);
+ n(fr, uE(fr)), Pm = aL(i).map((h) => EL.from(h)).sort(lL), Sf = /* @__PURE__ */ new Map();
for (let h of Pm) {
let u = [Sf];
for (let d of h) {
@@ -42824,28 +42824,28 @@ function Rp() {
let m = p.get(d);
return m || (m = /* @__PURE__ */ new Map(), p.set(d, m)), m;
});
- d === pE ? u.push(...f) : u = f;
+ d === fE ? u.push(...f) : u = f;
}
for (let d of u)
d.V = h;
}
}
function Fp(i) {
- return (xE(i) ? "" : `${Np(Dh([i]))} `) + aE(i);
+ return (mE(i) ? "" : `${Np(Dh([i]))} `) + rE(i);
}
function Np(i) {
return `"${i}"‎`;
}
-function _L(i) {
+function yL(i) {
if (i.length >= 4 && i[2] == Lm && i[3] == Lm)
throw new Error(`invalid label extension: "${Ha(i.slice(0, 4))}"`);
}
-function wL(i) {
+function _L(i) {
for (let t = i.lastIndexOf(95); t > 0; )
if (i[--t] !== 95)
throw new Error("underscore allowed only at start");
}
-function vL(i) {
+function wL(i) {
let e = i[0], t = Fm.get(e);
if (t) throw Oo(`leading ${t}`);
let n = i.length, s = -1;
@@ -42859,43 +42859,43 @@ function vL(i) {
}
if (s == n) throw Oo(`trailing ${t}`);
}
-function Dh(i, e = 1 / 0, t = aE) {
+function Dh(i, e = 1 / 0, t = rE) {
let n = [];
- CL(i[0]) && n.push("◌"), i.length > e && (e >>= 1, i = [...i.slice(0, e), 8230, ...i.slice(-e)]);
+ vL(i[0]) && n.push("◌"), i.length > e && (e >>= 1, i = [...i.slice(0, e), 8230, ...i.slice(-e)]);
let s = 0, r = i.length;
for (let a = 0; a < r; a++) {
let o = i[a];
- xE(o) && (n.push(Ha(i.slice(s, a))), n.push(t(o)), s = a + 1);
+ mE(o) && (n.push(Ha(i.slice(s, a))), n.push(t(o)), s = a + 1);
}
return n.push(Ha(i.slice(s, r))), n.join("");
}
-function CL(i) {
+function vL(i) {
return Rp(), wr.has(i);
}
-function xE(i) {
- return Rp(), mE.has(i);
+function mE(i) {
+ return Rp(), gE.has(i);
}
-function IL(i) {
- return TL(SL(i, EL, NL));
+function CL(i) {
+ return BL(IL(i, bL, FL));
}
-function SL(i, e, t) {
+function IL(i, e, t) {
if (!i) return [];
Rp();
let n = 0;
- return i.split(fE).map((s) => {
- let r = lL(s), a = {
+ return i.split(dE).map((s) => {
+ let r = cL(s), a = {
input: r,
offset: n
// codepoint, not substring!
};
n += r.length + 1;
try {
- let o = a.tokens = FL(r, e, t), c = o.length, l;
+ let o = a.tokens = RL(r, e, t), c = o.length, l;
if (!c)
throw new Error("empty label");
let h = a.output = o.flat();
- if (wL(h), !(a.emoji = c > 1 || o[0].is_emoji) && h.every((d) => d < 128))
- _L(h), l = "ASCII";
+ if (_L(h), !(a.emoji = c > 1 || o[0].is_emoji) && h.every((d) => d < 128))
+ yL(h), l = "ASCII";
else {
let d = o.flatMap((f) => f.is_emoji ? [] : f);
if (!d.length)
@@ -42907,9 +42907,9 @@ function SL(i, e, t) {
if (!g.is_emoji && wr.has(g[0]))
throw Oo(`emoji + combining mark: "${Ha(o[m - 1])} + ${Dh([g[0]])}"`);
}
- vL(h);
- let f = hh(new Set(d)), [p] = BL(f);
- RL(p, d), ML(p, f), l = p.N;
+ wL(h);
+ let f = hh(new Set(d)), [p] = ML(f);
+ TL(p, d), SL(p, f), l = p.N;
}
}
a.type = l;
@@ -42919,11 +42919,11 @@ function SL(i, e, t) {
return a;
});
}
-function ML(i, e) {
+function SL(i, e) {
let t, n = [];
for (let s of e) {
let r = Aa.get(s);
- if (r === AE) return;
+ if (r === pE) return;
if (r) {
let a = r.M.get(s);
if (t = t ? t.filter((o) => a.has(o)) : hh(a), !t.length) return;
@@ -42936,41 +42936,41 @@ function ML(i, e) {
throw new Error(`whole-script confusable: ${i.N}/${s.N}`);
}
}
-function BL(i) {
+function ML(i) {
let e = Ra;
for (let t of i) {
let n = e.filter((s) => lc(s, t));
if (!n.length)
- throw Ra.some((s) => lc(s, t)) ? EE(e[0], t) : bE(t);
+ throw Ra.some((s) => lc(s, t)) ? bE(e[0], t) : xE(t);
if (e = n, n.length == 1) break;
}
return e;
}
-function TL(i) {
+function BL(i) {
return i.map(({ input: e, error: t, output: n }) => {
if (t) {
let s = t.message;
throw new Error(i.length == 1 ? s : `Invalid label ${Np(Dh(e, 63))}: ${s}`);
}
return Ha(n);
- }).join(fE);
+ }).join(dE);
}
-function bE(i) {
+function xE(i) {
return new Error(`disallowed character: ${Fp(i)}`);
}
-function EE(i, e) {
+function bE(i, e) {
let t = Fp(e), n = Ra.find((s) => s.P.has(e));
return n && (t = `${n.N} ${t}`), new Error(`illegal mixture: ${i.N} + ${t}`);
}
function Oo(i) {
return new Error(`illegal placement: ${i}`);
}
-function RL(i, e) {
+function TL(i, e) {
for (let t of e)
if (!lc(i, t))
- throw EE(i, t);
+ throw bE(i, t);
if (i.M) {
- let t = dE(e);
+ let t = uE(e);
for (let n = 1, s = t.length; n < s; n++)
if (If.has(t[n])) {
let r = n + 1;
@@ -42984,10 +42984,10 @@ function RL(i, e) {
}
}
}
-function FL(i, e, t) {
+function RL(i, e, t) {
let n = [], s = [];
for (i = i.slice().reverse(); i.length; ) {
- let r = DL(i);
+ let r = NL(i);
if (r)
s.length && (n.push(e(s)), s = []), n.push(t(r));
else {
@@ -42998,17 +42998,17 @@ function FL(i, e, t) {
let o = Cf.get(a);
if (o)
s.push(...o);
- else if (!gE.has(a))
- throw bE(a);
+ else if (!AE.has(a))
+ throw xE(a);
}
}
}
return s.length && n.push(e(s)), n;
}
-function NL(i) {
- return i.filter((e) => e != pE);
+function FL(i) {
+ return i.filter((e) => e != fE);
}
-function DL(i, e) {
+function NL(i, e) {
let t = Sf, n, s = i.length;
for (; s && (t = t.get(i[--s]), !!t); ) {
let { V: r } = t;
@@ -43016,13 +43016,13 @@ function DL(i, e) {
}
return n;
}
-const yE = new Uint8Array(32);
-yE.fill(0);
+const EE = new Uint8Array(32);
+EE.fill(0);
function km(i) {
return V(i.length !== 0, "invalid ENS name; empty component", "comp", i), i;
}
-function _E(i) {
- const e = gs(LL(i)), t = [];
+function yE(i) {
+ const e = gs(DL(i)), t = [];
if (i.length === 0)
return t;
let n = 0;
@@ -43030,39 +43030,39 @@ function _E(i) {
e[s] === 46 && (t.push(km(e.slice(n, s))), n = s + 1);
return V(n < e.length, "invalid ENS name; empty component", "name", i), t.push(km(e.slice(n))), t;
}
-function LL(i) {
+function DL(i) {
try {
if (i.length === 0)
throw new Error("empty label");
- return IL(i);
+ return CL(i);
} catch (e) {
V(!1, `invalid ENS name (${e.message})`, "name", i);
}
}
function Mf(i) {
V(typeof i == "string", "invalid ENS name; not a string", "name", i), V(i.length, "invalid ENS name (empty label)", "name", i);
- let e = yE;
- const t = _E(i);
+ let e = EE;
+ const t = yE(i);
for (; t.length; )
e = sn(Ht([e, sn(t.pop())]));
return Ie(e);
}
-function PL(i, e) {
+function LL(i, e) {
const t = e;
- return V(t <= 255, "DNS encoded label cannot exceed 255", "length", t), Ie(Ht(_E(i).map((n) => {
+ return V(t <= 255, "DNS encoded label cannot exceed 255", "length", t), Ie(Ht(yE(i).map((n) => {
V(n.length <= t, `label ${JSON.stringify(i)} exceeds ${t} bytes`, "name", i);
const s = new Uint8Array(n.length + 1);
return s.set(n, 1), s[0] = s.length - 1, s;
}))) + "00";
}
-const wE = new Uint8Array(32);
-wE.fill(0);
-const kL = BigInt(-1), vE = BigInt(0), CE = BigInt(1), UL = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
-function OL(i) {
+const _E = new Uint8Array(32);
+_E.fill(0);
+const PL = BigInt(-1), wE = BigInt(0), vE = BigInt(1), kL = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
+function UL(i) {
const e = dt(i), t = e.length % 32;
- return t ? Ht([e, wE.slice(t)]) : Ie(e);
+ return t ? Ht([e, _E.slice(t)]) : Ie(e);
}
-const QL = Ys(CE, 32), GL = Ys(vE, 32), Um = {
+const OL = Ys(vE, 32), QL = Ys(wE, 32), Um = {
name: "string",
version: "string",
chainId: "uint256",
@@ -43080,7 +43080,7 @@ function Om(i) {
return V(typeof e == "string", `invalid domain value for ${JSON.stringify(i)}`, `domain.${i}`, e), e;
};
}
-const HL = {
+const GL = {
name: Om("name"),
version: Om("version"),
chainId: function(i) {
@@ -43105,10 +43105,10 @@ function rd(i) {
if (e) {
const t = e[1] === "", n = parseInt(e[2]);
V(n % 8 === 0 && n !== 0 && n <= 256 && e[2] === String(n), "invalid numeric width", "type", i);
- const s = So(UL, t ? n - 1 : n), r = t ? (s + CE) * kL : vE;
+ const s = So(kL, t ? n - 1 : n), r = t ? (s + vE) * PL : wE;
return function(a) {
const o = De(a, "value");
- return V(o >= r && o <= s, `value out-of-bounds for ${i}`, "value", o), Ys(t ? fb(o, 256) : o, 32);
+ return V(o >= r && o <= s, `value out-of-bounds for ${i}`, "value", o), Ys(t ? db(o, 256) : o, 32);
};
}
}
@@ -43118,7 +43118,7 @@ function rd(i) {
const t = parseInt(e[1]);
return V(t !== 0 && t <= 32 && e[1] === String(t), "invalid bytes width", "type", i), function(n) {
const s = dt(n);
- return V(s.length === t, `invalid length for ${i}`, "value", n), OL(n);
+ return V(s.length === t, `invalid length for ${i}`, "value", n), UL(n);
};
}
}
@@ -43129,7 +43129,7 @@ function rd(i) {
};
case "bool":
return function(e) {
- return e ? QL : GL;
+ return e ? OL : QL;
};
case "bytes":
return function(e) {
@@ -43381,7 +43381,7 @@ class ei {
const s = {}, r = [];
sd.forEach((c) => {
const l = e[c];
- l != null && (s[c] = HL[c](l), r.push({ name: c, type: Um[c] }));
+ l != null && (s[c] = GL[c](l), r.push({ name: c, type: Um[c] }));
});
const a = ei.from(t);
t = a.types;
@@ -43412,14 +43412,14 @@ function Vn(i) {
const e = /* @__PURE__ */ new Set();
return i.forEach((t) => e.add(t)), Object.freeze(e);
}
-const zL = "external public payable override", VL = Vn(zL.split(" ")), IE = "constant external internal payable private public pure view override", WL = Vn(IE.split(" ")), SE = "constructor error event fallback function receive struct", ME = Vn(SE.split(" ")), BE = "calldata memory storage payable indexed", qL = Vn(BE.split(" ")), KL = "tuple returns", jL = [SE, BE, KL, IE].join(" "), XL = Vn(jL.split(" ")), YL = {
+const HL = "external public payable override", zL = Vn(HL.split(" ")), CE = "constant external internal payable private public pure view override", VL = Vn(CE.split(" ")), IE = "constructor error event fallback function receive struct", SE = Vn(IE.split(" ")), ME = "calldata memory storage payable indexed", WL = Vn(ME.split(" ")), qL = "tuple returns", KL = [IE, ME, qL, CE].join(" "), jL = Vn(KL.split(" ")), XL = {
"(": "OPEN_PAREN",
")": "CLOSE_PAREN",
"[": "OPEN_BRACKET",
"]": "CLOSE_BRACKET",
",": "COMMA",
"@": "AT"
-}, JL = new RegExp("^(\\s*)"), ZL = new RegExp("^([0-9]+)"), $L = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"), TE = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"), RE = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
+}, YL = new RegExp("^(\\s*)"), JL = new RegExp("^([0-9]+)"), ZL = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"), BE = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"), TE = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
class Ai {
#e;
#t;
@@ -43519,11 +43519,11 @@ function er(i) {
};
let n = [], s = [], r = 0;
for (; r < i.length; ) {
- let a = i.substring(r), o = a.match(JL);
+ let a = i.substring(r), o = a.match(YL);
o && (r += o[1].length, a = i.substring(r));
const c = { depth: n.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset: r, value: -1 };
e.push(c);
- let l = YL[a[0]] || "";
+ let l = XL[a[0]] || "";
if (l) {
if (c.type = l, c.text = a[0], r++, l === "OPEN_PAREN")
n.push(e.length - 1), s.push(e.length - 1);
@@ -43545,19 +43545,19 @@ function er(i) {
}
continue;
}
- if (o = a.match($L), o) {
- if (c.text = o[1], r += c.text.length, XL.has(c.text)) {
+ if (o = a.match(ZL), o) {
+ if (c.text = o[1], r += c.text.length, jL.has(c.text)) {
c.type = "KEYWORD";
continue;
}
- if (c.text.match(RE)) {
+ if (c.text.match(TE)) {
c.type = "TYPE";
continue;
}
c.type = "ID";
continue;
}
- if (o = a.match(ZL), o) {
+ if (o = a.match(JL), o) {
c.text = o[1], c.type = "NUMBER", r += c.text.length;
continue;
}
@@ -43573,7 +43573,7 @@ function Gm(i, e) {
throw new Error(`conflicting types: ${t.join(", ")}`);
}
function Lh(i, e) {
- if (e.peekKeyword(ME)) {
+ if (e.peekKeyword(SE)) {
const t = e.pop().text;
if (t !== i)
throw new Error(`expected ${i}, got ${t}`);
@@ -43592,14 +43592,14 @@ function ys(i, e) {
}
return Object.freeze(t);
}
-function FE(i) {
- let e = ys(i, WL);
+function RE(i) {
+ let e = ys(i, VL);
return Gm(e, Vn("constant payable nonpayable".split(" "))), Gm(e, Vn("pure view payable nonpayable".split(" "))), e.has("view") ? "view" : e.has("pure") ? "pure" : e.has("payable") ? "payable" : e.has("nonpayable") ? "nonpayable" : e.has("constant") ? "view" : "nonpayable";
}
function xs(i, e) {
return i.popParams().map((t) => Pt.from(t, e));
}
-function NE(i) {
+function FE(i) {
if (i.peekType("AT")) {
if (i.pop(), i.peekType("NUMBER"))
return De(i.pop().text);
@@ -43611,9 +43611,9 @@ function Ur(i) {
if (i.length)
throw new Error(`unexpected tokens at offset ${i.offset}: ${i.toString()}`);
}
-const e2 = new RegExp(/^(.*)\[([0-9]*)\]$/);
+const $L = new RegExp(/^(.*)\[([0-9]*)\]$/);
function Hm(i) {
- const e = i.match(RE);
+ const e = i.match(TE);
if (V(e, "invalid type", "type", i), i === "uint")
return "uint256";
if (i === "int")
@@ -43848,7 +43848,7 @@ class Pt {
h = new Pt(Vt, "", o, c, null, l, u, h), u = m.value, o += m.text, c = "array", l = null;
}
let d = null;
- if (ys(e, qL).has("indexed")) {
+ if (ys(e, WL).has("indexed")) {
if (!t)
throw new Error("");
d = !0;
@@ -43859,10 +43859,10 @@ class Pt {
return new Pt(Vt, p, o, c, d, l, u, h);
}
const n = e.name;
- V(!n || typeof n == "string" && n.match(TE), "invalid name", "obj.name", n);
+ V(!n || typeof n == "string" && n.match(BE), "invalid name", "obj.name", n);
let s = e.indexed;
s != null && (V(t, "parameter cannot be indexed", "obj.indexed", e.indexed), s = !!s);
- let r = e.type, a = r.match(e2);
+ let r = e.type, a = r.match($L);
if (a) {
const o = parseInt(a[2] || "-1"), c = Pt.from({
type: a[1],
@@ -43917,7 +43917,7 @@ class Or {
return Or.from(er(e));
}
if (e instanceof Ai)
- switch (e.peekKeyword(ME)) {
+ switch (e.peekKeyword(SE)) {
case "constructor":
return fs.from(e);
case "error":
@@ -43994,7 +43994,7 @@ class Ph extends Or {
* @private
*/
constructor(e, t, n, s) {
- super(e, t, s), V(typeof n == "string" && n.match(TE), "invalid identifier", "name", n), s = Object.freeze(s.slice()), Ye(this, { name: n });
+ super(e, t, s), V(typeof n == "string" && n.match(BE), "invalid identifier", "name", n), s = Object.freeze(s.slice()), Ye(this, { name: n });
}
}
function hc(i, e) {
@@ -44155,7 +44155,7 @@ class fs extends Or {
}
else if (e instanceof Ai) {
ys(e, Vn(["constructor"]));
- const t = xs(e), n = !!ys(e, VL).has("payable"), s = NE(e);
+ const t = xs(e), n = !!ys(e, zL).has("payable"), s = FE(e);
return Ur(e), new fs(Vt, "constructor", t, n, s);
}
return new fs(Vt, "constructor", e.inputs ? e.inputs.map(Pt.from) : [], !!e.payable, e.gas != null ? e.gas : null);
@@ -44207,7 +44207,7 @@ class ss extends Or {
}
let r = xs(e);
r.length ? V(r.length === 1 && r[0].type === "bytes", "invalid fallback inputs", "obj.inputs", r.map((o) => o.format("minimal")).join(", ")) : r = [Pt.from("bytes")];
- const a = FE(e);
+ const a = RE(e);
if (V(a === "nonpayable" || a === "payable", "fallback cannot be constants", "obj.stateMutability", a), ys(e, Vn(["returns"])).has("returns")) {
const o = xs(e);
V(o.length === 1 && o[0].type === "bytes", "invalid fallback outputs", "obj.outputs", o.map((c) => c.format("minimal")).join(", "));
@@ -44301,10 +44301,10 @@ class Gi extends Ph {
V(!1, "invalid function fragment", "obj", e);
}
else if (e instanceof Ai) {
- const n = Lh("function", e), s = xs(e), r = FE(e);
+ const n = Lh("function", e), s = xs(e), r = RE(e);
let a = [];
ys(e, Vn(["returns"])).has("returns") && (a = xs(e));
- const o = NE(e);
+ const o = FE(e);
return Ur(e), new Gi(Vt, n, r, s, a, o);
}
let t = e.stateMutability;
@@ -44367,9 +44367,9 @@ Ni.set(49, "STACK_UNDERFLOW");
Ni.set(50, "ARRAY_RANGE_ERROR");
Ni.set(65, "OUT_OF_MEMORY");
Ni.set(81, "UNINITIALIZED_FUNCTION_CALL");
-const t2 = new RegExp(/^bytes([0-9]*)$/), n2 = new RegExp(/^(u?int)([0-9]*)$/);
+const e2 = new RegExp(/^bytes([0-9]*)$/), t2 = new RegExp(/^(u?int)([0-9]*)$/);
let ad = null, Ym = 1024;
-function i2(i, e, t, n) {
+function n2(i, e, t, n) {
let s = "missing revert data", r = null;
const a = null;
let o = null;
@@ -44420,29 +44420,29 @@ function i2(i, e, t, n) {
class Va {
#e(e) {
if (e.isArray())
- return new ED(this.#e(e.arrayChildren), e.arrayLength, e.name);
+ return new bD(this.#e(e.arrayChildren), e.arrayLength, e.name);
if (e.isTuple())
return new yl(e.components.map((n) => this.#e(n)), e.name);
switch (e.baseType) {
case "address":
- return new xD(e.name);
+ return new mD(e.name);
case "bool":
- return new yD(e.name);
+ return new ED(e.name);
case "string":
- return new TD(e.name);
+ return new BD(e.name);
case "bytes":
- return new _D(e.name);
+ return new yD(e.name);
case "":
- return new CD(e.name);
+ return new vD(e.name);
}
- let t = e.type.match(n2);
+ let t = e.type.match(t2);
if (t) {
let n = parseInt(t[2] || "256");
- return V(n !== 0 && n <= 256 && n % 8 === 0, "invalid " + t[1] + " bit length", "param", e), new BD(n / 8, t[1] === "int", e.name);
+ return V(n !== 0 && n <= 256 && n % 8 === 0, "invalid " + t[1] + " bit length", "param", e), new MD(n / 8, t[1] === "int", e.name);
}
- if (t = e.type.match(t2), t) {
+ if (t = e.type.match(e2), t) {
let n = parseInt(t[1]);
- return V(n !== 0 && n <= 32, "invalid bytes length", "param", e), new wD(n, e.name);
+ return V(n !== 0 && n <= 32, "invalid bytes length", "param", e), new _D(n, e.name);
}
V(!1, "invalid type", "type", e.type);
}
@@ -44462,7 +44462,7 @@ class Va {
* @returns DataHexstring
*/
encode(e, t) {
- hb(t.length, e.length, "types/values length mismatch");
+ lb(t.length, e.length, "types/values length mismatch");
const n = e.map((a) => this.#e(Pt.from(a))), s = new yl(n, "_"), r = new gf();
return s.encode(r, t), r.data;
}
@@ -44494,10 +44494,10 @@ class Va {
* the Transaction %%tx%%.
*/
static getBuiltinCallException(e, t, n) {
- return i2(e, t, n, Va.defaultAbiCoder());
+ return n2(e, t, n, Va.defaultAbiCoder());
}
}
-class s2 {
+class i2 {
/**
* The matching fragment for the ``topic0``.
*/
@@ -44532,7 +44532,7 @@ class s2 {
});
}
}
-class r2 {
+class s2 {
/**
* The matching fragment from the transaction ``data``.
*/
@@ -44572,7 +44572,7 @@ class r2 {
});
}
}
-class a2 {
+class r2 {
/**
* The matching fragment.
*/
@@ -45194,7 +45194,7 @@ class xr {
ge(t.length <= e.inputs.length, `too many arguments for ${e.format()}`, "UNEXPECTED_ARGUMENT", { count: t.length, expectedCount: e.inputs.length });
const n = [];
e.anonymous || n.push(e.topicHash);
- const s = (r, a) => r.type === "string" ? kr(a) : r.type === "bytes" ? sn(Ie(a)) : (r.type === "bool" && typeof a == "boolean" ? a = a ? "0x01" : "0x00" : r.type.match(/^u?int/) ? a = Ys(a) : r.type.match(/^bytes/) ? a = MF(a, 32) : r.type === "address" && this.#i.encode(["address"], [a]), Es(Ie(a), 32));
+ const s = (r, a) => r.type === "string" ? kr(a) : r.type === "bytes" ? sn(Ie(a)) : (r.type === "bool" && typeof a == "boolean" ? a = a ? "0x01" : "0x00" : r.type.match(/^u?int/) ? a = Ys(a) : r.type.match(/^bytes/) ? a = SF(a, 32) : r.type === "address" && this.#i.encode(["address"], [a]), Es(Ie(a), 32));
for (t.forEach((r, a) => {
const o = e.inputs[a];
if (!o.indexed) {
@@ -45280,7 +45280,7 @@ class xr {
if (!s)
return null;
const r = this.#i.decode(s.inputs, t.slice(4));
- return new r2(s, s.selector, r, n);
+ return new s2(s, s.selector, r, n);
}
parseCallResult(e) {
throw new Error("@TODO");
@@ -45293,7 +45293,7 @@ class xr {
*/
parseLog(e) {
const t = this.getEvent(e.topics[0]);
- return !t || t.anonymous ? null : new s2(t, t.topicHash, this.decodeEventLog(t, e.data, e.topics));
+ return !t || t.anonymous ? null : new i2(t, t.topicHash, this.decodeEventLog(t, e.data, e.topics));
}
/**
* Parses a revert data, finding the matching error and extracts
@@ -45306,7 +45306,7 @@ class xr {
if (!n)
return null;
const s = this.#i.decode(n.inputs, Kt(t, 4));
- return new a2(n, n.selector, s);
+ return new r2(n, n.selector, s);
}
/**
* Creates a new [[Interface]] from the ABI %%value%%.
@@ -45318,7 +45318,7 @@ class xr {
return e instanceof xr ? e : typeof e == "string" ? new xr(JSON.parse(e)) : typeof e.formatJson == "function" ? new xr(e.formatJson()) : typeof e.format == "function" ? new xr(e.format("json")) : new xr(e);
}
}
-const DE = BigInt(0);
+const NE = BigInt(0);
function Fa(i) {
return i ?? null;
}
@@ -45388,7 +45388,7 @@ function uh(i) {
!(s in i) || i[s] == null || (e[s] = ft(i[s], `request.${s}`));
return i.accessList && (e.accessList = Hr(i.accessList)), i.authorizationList && (e.authorizationList = i.authorizationList.slice()), "blockTag" in i && (e.blockTag = i.blockTag), "enableCcipRead" in i && (e.enableCcipRead = !!i.enableCcipRead), "customData" in i && (e.customData = i.customData), "blobVersionedHashes" in i && i.blobVersionedHashes && (e.blobVersionedHashes = i.blobVersionedHashes.slice()), "kzg" in i && (e.kzg = i.kzg), "blobWrapperVersion" in i && (e.blobWrapperVersion = i.blobWrapperVersion), "blobs" in i && i.blobs && (e.blobs = i.blobs.map((s) => bp(s) ? Ie(s) : Object.assign({}, s))), e;
}
-class o2 {
+class a2 {
/**
* The provider connected to the block used to fetch additional details
* if necessary.
@@ -45646,7 +45646,7 @@ class o2 {
orphanedEvent() {
if (!this.isMined())
throw new Error("");
- return c2(this);
+ return o2(this);
}
}
class bc {
@@ -45766,10 +45766,10 @@ class bc {
* @_ignore:
*/
removedEvent() {
- return l2(this);
+ return c2(this);
}
}
-class LE {
+class DE {
/**
* The provider connected to the log used to fetch additional details
* if necessary.
@@ -45871,7 +45871,7 @@ class LE {
*/
constructor(e, t) {
this.#e = Object.freeze(e.logs.map((s) => new bc(s, t)));
- let n = DE;
+ let n = NE;
e.effectiveGasPrice != null ? n = e.effectiveGasPrice : e.gasPrice != null && (n = e.gasPrice), Ye(this, {
provider: t,
to: e.to,
@@ -45993,13 +45993,13 @@ class LE {
* @_ignore:
*/
removedEvent() {
- return kE(this);
+ return PE(this);
}
/**
* @_ignore:
*/
reorderedEvent(e) {
- return ge(!e || e.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }), PE(this, e);
+ return ge(!e || e.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }), LE(this, e);
}
}
class Ec {
@@ -46240,7 +46240,7 @@ class Ec {
if (_ == null || d - _.blockNumber + 1 < n)
return;
let x = "replaced";
- A.data === this.data && A.to === this.to && A.value === this.value ? x = "repriced" : A.data === "0x" && A.from === A.to && A.value === DE && (x = "cancelled"), ge(!1, "transaction was replaced", "TRANSACTION_REPLACED", {
+ A.data === this.data && A.to === this.to && A.value === this.value ? x = "repriced" : A.data === "0x" && A.from === A.to && A.value === NE && (x = "cancelled"), ge(!1, "transaction was replaced", "TRANSACTION_REPLACED", {
cancelled: x === "replaced" || x === "cancelled",
reason: x,
replacement: A.replaceableTransaction(r),
@@ -46376,14 +46376,14 @@ class Ec {
* that evict this transaction.
*/
removedEvent() {
- return ge(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), kE(this);
+ return ge(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), PE(this);
}
/**
* Returns a filter which can be used to listen for orphan events
* that re-order this event against %%other%%.
*/
reorderedEvent(e) {
- return ge(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), ge(!e || e.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), PE(this, e);
+ return ge(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), ge(!e || e.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), LE(this, e);
}
/**
* Returns a new TransactionResponse instance which has the ability to
@@ -46400,16 +46400,16 @@ class Ec {
return t.#e = e, t;
}
}
-function c2(i) {
+function o2(i) {
return { orphan: "drop-block", hash: i.hash, number: i.number };
}
-function PE(i, e) {
+function LE(i, e) {
return { orphan: "reorder-transaction", tx: i, other: e };
}
-function kE(i) {
+function PE(i) {
return { orphan: "drop-transaction", tx: i };
}
-function l2(i) {
+function c2(i) {
return { orphan: "drop-log", log: {
transactionHash: i.transactionHash,
blockHash: i.blockHash,
@@ -46454,7 +46454,7 @@ class Dp extends bc {
return this.fragment.format();
}
}
-class UE extends bc {
+class kE extends bc {
/**
* The error encounted when trying to decode the log.
*/
@@ -46466,7 +46466,7 @@ class UE extends bc {
super(e, e.provider), Ye(this, { error: t });
}
}
-class h2 extends LE {
+class l2 extends DE {
#e;
/**
* @_ignore:
@@ -46485,7 +46485,7 @@ class h2 extends LE {
try {
return new Dp(e, this.#e, t);
} catch (n) {
- return new UE(e, n);
+ return new kE(e, n);
}
return e;
});
@@ -46510,10 +46510,10 @@ class Lp extends Ec {
*/
async wait(e, t) {
const n = await super.wait(e, t);
- return n == null ? null : new h2(this.#e, this.provider, n);
+ return n == null ? null : new l2(this.#e, this.provider, n);
}
}
-class OE extends pb {
+class UE extends fb {
/**
* The log with no matching events.
*/
@@ -46543,7 +46543,7 @@ class OE extends pb {
return await this.log.getTransactionReceipt();
}
}
-class u2 extends OE {
+class h2 extends UE {
/**
* @_ignore:
*/
@@ -46566,19 +46566,19 @@ class u2 extends OE {
}
}
const t0 = BigInt(0);
-function QE(i) {
+function OE(i) {
return i && typeof i.call == "function";
}
-function GE(i) {
+function QE(i) {
return i && typeof i.estimateGas == "function";
}
function kh(i) {
return i && typeof i.resolveName == "function";
}
-function HE(i) {
+function GE(i) {
return i && typeof i.sendTransaction == "function";
}
-function zE(i) {
+function HE(i) {
if (i != null) {
if (kh(i))
return i;
@@ -46586,7 +46586,7 @@ function zE(i) {
return i.provider;
}
}
-class d2 {
+class u2 {
#e;
fragment;
constructor(e, t, n) {
@@ -46608,27 +46608,27 @@ function Qr(i, e) {
function vr(i) {
return i == null ? null : i.provider || null;
}
-async function VE(i, e) {
+async function zE(i, e) {
const t = jt.dereference(i, "overrides");
V(typeof t == "object", "invalid overrides parameter", "overrides", i);
const n = uh(t);
return V(n.to == null || (e || []).indexOf("to") >= 0, "cannot override to", "overrides.to", n.to), V(n.data == null || (e || []).indexOf("data") >= 0, "cannot override data", "overrides.data", n.data), n.from && (n.from = n.from), n;
}
-async function f2(i, e, t) {
+async function d2(i, e, t) {
const n = Qr(i, "resolveName"), s = kh(n) ? n : null;
return await Promise.all(e.map((r, a) => r.walkAsync(t[a], (o, c) => (c = jt.dereference(c, o), o === "address" ? zn(c, s) : c))));
}
-function p2(i) {
+function f2(i) {
const e = async function(a) {
- const o = await VE(a, ["data"]);
- o.to = await i.getAddress(), o.from && (o.from = await zn(o.from, zE(i.runner)));
+ const o = await zE(a, ["data"]);
+ o.to = await i.getAddress(), o.from && (o.from = await zn(o.from, HE(i.runner)));
const c = i.interface, l = De(o.value || t0, "overrides.value") === t0, h = (o.data || "0x") === "0x";
c.fallback && !c.fallback.payable && c.receive && !h && !l && V(!1, "cannot send data to receive or send value to non-payable fallback", "overrides", a), V(c.fallback || h, "cannot send data to receive-only contract", "overrides.data", o.data);
const u = c.receive || c.fallback && c.fallback.payable;
return V(u || l, "cannot send value to non-payable fallback", "overrides.value", o.value), V(c.fallback || h, "cannot send data to receive-only contract", "overrides.data", o.data), o;
}, t = async function(a) {
const o = Qr(i.runner, "call");
- ge(QE(o), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
+ ge(OE(o), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
const c = await e(a);
try {
return await o.call(c);
@@ -46637,12 +46637,12 @@ function p2(i) {
}
}, n = async function(a) {
const o = i.runner;
- ge(HE(o), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
+ ge(GE(o), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
const c = await o.sendTransaction(await e(a)), l = vr(i.runner);
return new Lp(i.interface, l, c);
}, s = async function(a) {
const o = Qr(i.runner, "estimateGas");
- return ge(GE(o), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await o.estimateGas(await e(a));
+ return ge(QE(o), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await o.estimateGas(await e(a));
}, r = async (a) => await n(a);
return Ye(r, {
_contract: i,
@@ -46652,7 +46652,7 @@ function p2(i) {
staticCall: t
}), r;
}
-function A2(i, e) {
+function p2(i, e) {
const t = function(...l) {
const h = i.interface.getFunction(e, l);
return ge(h, "no matching fragment", "UNSUPPORTED_OPERATION", {
@@ -46662,9 +46662,9 @@ function A2(i, e) {
}, n = async function(...l) {
const h = t(...l);
let u = {};
- if (h.inputs.length + 1 === l.length && (u = await VE(l.pop()), u.from && (u.from = await zn(u.from, zE(i.runner)))), h.inputs.length !== l.length)
+ if (h.inputs.length + 1 === l.length && (u = await zE(l.pop()), u.from && (u.from = await zn(u.from, HE(i.runner)))), h.inputs.length !== l.length)
throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");
- const d = await f2(i.runner, h.inputs, l);
+ const d = await d2(i.runner, h.inputs, l);
return Object.assign({}, u, await On({
to: i.getAddress(),
data: i.interface.encodeFunctionData(h, d)
@@ -46674,15 +46674,15 @@ function A2(i, e) {
return h.length === 1 ? h[0] : h;
}, r = async function(...l) {
const h = i.runner;
- ge(HE(h), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
+ ge(GE(h), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
const u = await h.sendTransaction(await n(...l)), d = vr(i.runner);
return new Lp(i.interface, d, u);
}, a = async function(...l) {
const h = Qr(i.runner, "estimateGas");
- return ge(GE(h), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await h.estimateGas(await n(...l));
+ return ge(QE(h), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await h.estimateGas(await n(...l));
}, o = async function(...l) {
const h = Qr(i.runner, "call");
- ge(QE(h), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
+ ge(OE(h), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
const u = await n(...l);
let d = "0x";
try {
@@ -46715,7 +46715,7 @@ function A2(i, e) {
}
}), c;
}
-function g2(i, e) {
+function A2(i, e) {
const t = function(...s) {
const r = i.interface.getEvent(e, s);
return ge(r, "no matching fragment", "UNSUPPORTED_OPERATION", {
@@ -46723,7 +46723,7 @@ function g2(i, e) {
info: { key: e, args: s }
}), r;
}, n = function(...s) {
- return new d2(i, t(...s), s);
+ return new u2(i, t(...s), s);
};
return Ye(n, {
name: i.interface.getEventName(e),
@@ -46742,14 +46742,14 @@ function g2(i, e) {
}
}), n;
}
-const dh = /* @__PURE__ */ Symbol.for("_ethersInternal_contract"), WE = /* @__PURE__ */ new WeakMap();
-function m2(i, e) {
- WE.set(i[dh], e);
+const dh = /* @__PURE__ */ Symbol.for("_ethersInternal_contract"), VE = /* @__PURE__ */ new WeakMap();
+function g2(i, e) {
+ VE.set(i[dh], e);
}
function ti(i) {
- return WE.get(i[dh]);
+ return VE.get(i[dh]);
}
-function x2(i) {
+function m2(i) {
return i && typeof i == "object" && "getTopicFilter" in i && typeof i.getTopicFilter == "function" && i.fragment;
}
async function Pp(i, e) {
@@ -46762,7 +46762,7 @@ async function Pp(i, e) {
return V(o, "unknown fragment", "name", a), o.topicHash;
};
t = e.map((a) => a == null ? null : Array.isArray(a) ? a.map(r) : r(a));
- } else e === "*" ? t = [null] : typeof e == "string" ? Ut(e, 32) ? t = [e] : (n = i.interface.getEvent(e), V(n, "unknown fragment", "event", e), t = [n.topicHash]) : x2(e) ? t = await e.getTopicFilter() : "fragment" in e ? (n = e.fragment, t = [n.topicHash]) : V(!1, "unknown event name", "event", e);
+ } else e === "*" ? t = [null] : typeof e == "string" ? Ut(e, 32) ? t = [e] : (n = i.interface.getEvent(e), V(n, "unknown fragment", "event", e), t = [n.topicHash]) : m2(e) ? t = await e.getTopicFilter() : "fragment" in e ? (n = e.fragment, t = [n.topicHash]) : V(!1, "unknown event name", "event", e);
t = t.map((r) => {
if (r == null)
return null;
@@ -46794,9 +46794,9 @@ async function n0(i, e, t) {
}
if (A) {
const _ = A, x = s ? i.interface.decodeEventLog(s, g.data, g.topics) : [];
- Tf(i, t, x, (E) => new u2(i, E, t, _, g));
+ Tf(i, t, x, (E) => new h2(i, E, t, _, g));
} else
- Tf(i, t, [], (_) => new OE(i, _, t, g));
+ Tf(i, t, [], (_) => new UE(i, _, t, g));
};
let f = [];
l = { tag: r, listeners: [], start: () => {
@@ -46811,7 +46811,7 @@ async function n0(i, e, t) {
return l;
}
let Bf = Promise.resolve();
-async function b2(i, e, t, n) {
+async function x2(i, e, t, n) {
await Bf;
const s = await Bo(i, e);
if (!s)
@@ -46832,7 +46832,7 @@ async function Tf(i, e, t, n) {
await Bf;
} catch {
}
- const s = b2(i, e, t, n);
+ const s = x2(i, e, t, n);
return Bf = s, await s;
}
const wl = ["then"];
@@ -46875,7 +46875,7 @@ class Qo {
* of.
*/
constructor(e, t, n, s) {
- V(typeof e == "string" || Jb(e), "invalid value for Contract target", "target", e), n == null && (n = null);
+ V(typeof e == "string" || Yb(e), "invalid value for Contract target", "target", e), n == null && (n = null);
const r = xr.from(t);
Ye(this, { target: e, runner: n, interface: r }), Object.defineProperty(this, dh, { value: {} });
let a, o = null, c = null;
@@ -46907,7 +46907,7 @@ class Qo {
throw new Error("TODO");
return ti(this).addr = u, u;
});
- m2(this, { addrPromise: a, addr: o, deployTx: c, subs: l });
+ g2(this, { addrPromise: a, addr: o, deployTx: c, subs: l });
const h = new Proxy({}, {
get: (u, d, f) => {
if (typeof d == "symbol" || wl.indexOf(d) >= 0)
@@ -46922,7 +46922,7 @@ class Qo {
has: (u, d) => wl.indexOf(d) >= 0 ? Reflect.has(u, d) : Reflect.has(u, d) || this.interface.hasEvent(String(d))
});
return Ye(this, { filters: h }), Ye(this, {
- fallback: r.receive || r.fallback ? p2(this) : null
+ fallback: r.receive || r.fallback ? f2(this) : null
}), new Proxy(this, {
get: (u, d, f) => {
if (typeof d == "symbol" || d in u || wl.indexOf(d) >= 0)
@@ -47005,7 +47005,7 @@ class Qo {
* when using a Contract programmatically.
*/
getFunction(e) {
- return typeof e != "string" && (e = e.format()), A2(this, e);
+ return typeof e != "string" && (e = e.format()), p2(this, e);
}
/**
* Return the event for a given name. This is useful when a contract
@@ -47013,7 +47013,7 @@ class Qo {
* when using a Contract programmatically.
*/
getEvent(e) {
- return typeof e != "string" && (e = e.format()), g2(this, e);
+ return typeof e != "string" && (e = e.format()), A2(this, e);
}
/**
* @_ignore:
@@ -47055,7 +47055,7 @@ class Qo {
try {
return new Dp(u, this.interface, d);
} catch (f) {
- return new UE(u, f);
+ return new kE(u, f);
}
return new bc(u, h);
});
@@ -47174,15 +47174,15 @@ class Qo {
return n == null && (n = null), new this(e, t, n);
}
}
-function E2() {
+function b2() {
return Qo;
}
-class Mr extends E2() {
+class Mr extends b2() {
}
function od(i) {
return i.match(/^ipfs:\/\/ipfs\//i) ? i = i.substring(12) : i.match(/^ipfs:\/\//i) ? i = i.substring(7) : V(!1, "unsupported IPFS format", "link", i), `https://gateway.ipfs.io/ipfs/${i}`;
}
-class y2 {
+class E2 {
/**
* The name.
*/
@@ -47215,10 +47215,10 @@ class y2 {
throw new Error("unsupported coin");
}
}
-const qE = new RegExp("^(ipfs)://(.*)$", "i"), i0 = [
+const WE = new RegExp("^(ipfs)://(.*)$", "i"), i0 = [
new RegExp("^(https)://(.*)$", "i"),
new RegExp("^(data):(.*)$", "i"),
- qE,
+ WE,
new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i")
];
class Na {
@@ -47269,7 +47269,7 @@ class Na {
await this.supportsWildcard() && (s = n.getFunction(e), ge(s, "missing fragment", "UNKNOWN_ERROR", {
info: { funcName: e }
}), t = [
- PL(this.name, 255),
+ LL(this.name, 255),
n.encodeFunctionData(s, t)
], e = "resolve(bytes,bytes)"), t.push({
enableCcipRead: !0
@@ -47305,7 +47305,7 @@ class Na {
}
let t = null;
for (const r of this.provider.plugins)
- if (r instanceof y2 && r.supportsCoinType(e)) {
+ if (r instanceof E2 && r.supportsCoinType(e)) {
t = r;
break;
}
@@ -47341,7 +47341,7 @@ class Na {
if (t) {
const s = t[1] === "e3010170" ? "ipfs" : "ipns", r = parseInt(t[4], 16);
if (t[5].length === r * 2)
- return `${s}://${RF("0x" + t[2])}`;
+ return `${s}://${TF("0x" + t[2])}`;
}
const n = e.match(/^0xe40101fa011b20([0-9a-f]*)$/);
if (n && n[1].length === 64)
@@ -47444,7 +47444,7 @@ class Na {
if (typeof p != "string")
return e.push({ type: "!imageUrl", value: "" }), { url: null, linkage: e };
if (!p.match(/^(https:\/\/|data:)/i)) {
- if (p.match(qE) == null)
+ if (p.match(WE) == null)
return e.push({ type: "!imageUrl-ipfs", value: p }), { url: null, linkage: e };
e.push({ type: "imageUrl-ipfs", value: p }), p = od(p);
}
@@ -47533,7 +47533,7 @@ function yc(i, e) {
return n;
});
}
-function _2(i) {
+function y2(i) {
switch (i) {
case !0:
case "true":
@@ -47550,23 +47550,23 @@ function Wa(i) {
function Sn(i) {
return V(Ut(i, 32), "invalid hash", "value", i), i;
}
-const w2 = yc({
+const _2 = yc({
address: Mt,
blockHash: Sn,
blockNumber: ft,
data: Wa,
index: ft,
- removed: bt(_2, !1),
+ removed: bt(y2, !1),
topics: uc(Sn),
transactionHash: Sn,
transactionIndex: ft
}, {
index: ["logIndex"]
});
-function v2(i) {
- return w2(i);
+function w2(i) {
+ return _2(i);
}
-const C2 = yc({
+const v2 = yc({
hash: bt(Sn),
parentHash: Sn,
parentBeaconBlockRoot: bt(Sn, null),
@@ -47587,11 +47587,11 @@ const C2 = yc({
}, {
prevRandao: ["mixHash"]
});
-function I2(i) {
- const e = C2(i);
- return e.transactions = i.transactions.map((t) => typeof t == "string" ? t : KE(t)), e;
+function C2(i) {
+ const e = v2(i);
+ return e.transactions = i.transactions.map((t) => typeof t == "string" ? t : qE(t)), e;
}
-const S2 = yc({
+const I2 = yc({
transactionIndex: ft,
blockNumber: ft,
transactionHash: Sn,
@@ -47603,10 +47603,10 @@ const S2 = yc({
}, {
index: ["logIndex"]
});
-function M2(i) {
- return S2(i);
+function S2(i) {
+ return I2(i);
}
-const B2 = yc({
+const M2 = yc({
to: bt(Mt, null),
from: bt(Mt, null),
contractAddress: bt(Mt, null),
@@ -47618,7 +47618,7 @@ const B2 = yc({
logsBloom: bt(Wa),
blockHash: Sn,
hash: Sn,
- logs: uc(M2),
+ logs: uc(S2),
blockNumber: ft,
//confirmations: allowNull(getNumber, null),
cumulativeGasUsed: De,
@@ -47631,10 +47631,10 @@ const B2 = yc({
hash: ["transactionHash"],
index: ["transactionIndex"]
});
-function T2(i) {
- return B2(i);
+function B2(i) {
+ return M2(i);
}
-function KE(i) {
+function qE(i) {
i.to && De(i.to) === s0 && (i.to = "0x0000000000000000000000000000000000000000");
const e = yc({
hash: Sn,
@@ -47679,13 +47679,13 @@ function KE(i) {
gasLimit: ["gas"],
index: ["transactionIndex"]
})(i);
- if (e.to == null && e.creates == null && (e.creates = mD(e)), (i.type === 1 || i.type === 2) && i.accessList == null && (e.accessList = []), i.signature ? e.signature = zt.from(i.signature) : e.signature = zt.from(i), e.chainId == null) {
+ if (e.to == null && e.creates == null && (e.creates = gD(e)), (i.type === 1 || i.type === 2) && i.accessList == null && (e.accessList = []), i.signature ? e.signature = zt.from(i.signature) : e.signature = zt.from(i), e.chainId == null) {
const t = e.signature.legacyChainId;
t != null && (e.chainId = t);
}
return e.blockHash && De(e.blockHash) === s0 && (e.blockHash = null), e;
}
-const R2 = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
+const T2 = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
class _c {
/**
* The name of the plugin.
@@ -47773,7 +47773,7 @@ class Oh extends _c {
*/
constructor(e, t) {
super("org.ethers.plugins.network.Ens"), Ye(this, {
- address: e || R2,
+ address: e || T2,
targetNetwork: t ?? 1
});
}
@@ -47781,7 +47781,7 @@ class Oh extends _c {
return new Oh(this.address, this.targetNetwork);
}
}
-class F2 extends _c {
+class R2 extends _c {
#e;
#t;
/**
@@ -47944,7 +47944,7 @@ class ii {
* Returns a new Network for the %%network%% name or chainId.
*/
static from(e) {
- if (N2(), e == null)
+ if (F2(), e == null)
return ii.from("mainnet");
if (typeof e == "number" && (e = BigInt(e)), typeof e == "string" || typeof e == "bigint") {
const t = cd.get(e);
@@ -47989,7 +47989,7 @@ function r0(i, e) {
return BigInt(n[0] + n[1]);
}
function a0(i) {
- return new F2(i, async (e, t, n) => {
+ return new R2(i, async (e, t, n) => {
n.setHeader("User-Agent", "ethers");
let s;
try {
@@ -48010,7 +48010,7 @@ function a0(i) {
});
}
let o0 = !1;
-function N2() {
+function F2() {
if (o0)
return;
o0 = !0;
@@ -48045,7 +48045,7 @@ function N2() {
function Rf(i) {
return JSON.parse(JSON.stringify(i));
}
-class D2 {
+class N2 {
#e;
#t;
#n;
@@ -48130,7 +48130,7 @@ class kp {
this.start();
}
}
-class L2 extends kp {
+class D2 extends kp {
#e;
#t;
constructor(e, t) {
@@ -48144,7 +48144,7 @@ class L2 extends kp {
n != null && (this.#t === -2 ? this.#t = n.number : n.number > this.#t && (t.emit(this.#e, n.number), this.#t = n.number));
}
}
-class P2 extends kp {
+class L2 extends kp {
#e;
constructor(e, t) {
super(e), this.#e = Rf(t);
@@ -48153,7 +48153,7 @@ class P2 extends kp {
throw new Error("@TODO");
}
}
-class k2 extends kp {
+class P2 extends kp {
#e;
/**
* Create a new **PollingTransactionSubscriber** attached to
@@ -48210,7 +48210,7 @@ class Up {
this.start();
}
}
-const U2 = BigInt(2), O2 = 10;
+const k2 = BigInt(2), U2 = 10;
function vl(i) {
return i && typeof i.then == "function";
}
@@ -48229,7 +48229,7 @@ function Ll(i, e) {
return n;
});
}
-class jE {
+class KE {
/**
* The name fof the event.
*/
@@ -48249,7 +48249,7 @@ class jE {
resume() {
}
}
-function Q2(i) {
+function O2(i) {
return JSON.parse(JSON.stringify(i));
}
function Ff(i) {
@@ -48275,7 +48275,7 @@ async function ld(i, e) {
}
if (i.orphan) {
const t = i;
- return { type: "orphan", tag: Ll("orphan", t), filter: Q2(t) };
+ return { type: "orphan", tag: Ll("orphan", t), filter: O2(t) };
}
if (i.address || i.topics) {
const t = i, n = {
@@ -48296,11 +48296,11 @@ async function ld(i, e) {
function hd() {
return (/* @__PURE__ */ new Date()).getTime();
}
-const G2 = {
+const Q2 = {
cacheTimeout: 250,
pollingInterval: 4e3
};
-class H2 {
+class G2 {
#e;
#t;
// null=unpaused, true=paused+dropWhilePaused, false=paused
@@ -48321,7 +48321,7 @@ class H2 {
* [[Network]] if necessary.
*/
constructor(e, t) {
- if (this.#A = Object.assign({}, G2, t || {}), e === "any")
+ if (this.#A = Object.assign({}, Q2, t || {}), e === "any")
this.#a = !0, this.#s = null;
else if (e) {
const n = ii.from(e);
@@ -48421,7 +48421,7 @@ class H2 {
* sub-class of [[Block]].
*/
_wrapBlock(e, t) {
- return new o2(I2(e), this);
+ return new a2(C2(e), this);
}
/**
* Provides the opportunity for a sub-class to wrap a log before
@@ -48429,7 +48429,7 @@ class H2 {
* sub-class of [[Log]].
*/
_wrapLog(e, t) {
- return new bc(v2(e), this);
+ return new bc(w2(e), this);
}
/**
* Provides the opportunity for a sub-class to wrap a transaction
@@ -48437,7 +48437,7 @@ class H2 {
* alternate sub-class of [[TransactionReceipt]].
*/
_wrapTransactionReceipt(e, t) {
- return new LE(T2(e), this);
+ return new DE(B2(e), this);
}
/**
* Provides the opportunity for a sub-class to wrap a transaction
@@ -48445,7 +48445,7 @@ class H2 {
* alternate sub-class of [[TransactionResponse]].
*/
_wrapTransactionResponse(e, t) {
- return new Ec(KE(e), this);
+ return new Ec(qE(e), this);
}
/**
* Resolves to the Network, forcing a network detection using whatever
@@ -48607,7 +48607,7 @@ class H2 {
});
let o = null, c = null;
const l = this._wrapBlock(s, e);
- return l && l.baseFeePerGas && (c = a ?? BigInt("1000000000"), o = l.baseFeePerGas * U2 + c), new e0(r, o, c);
+ return l && l.baseFeePerGas && (c = a ?? BigInt("1000000000"), o = l.baseFeePerGas * k2 + c), new e0(r, o, c);
}, n = e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
if (n) {
const s = new Hi(n.url), r = await n.processFunc(t, this, s);
@@ -48623,7 +48623,7 @@ class H2 {
}), "%response");
}
async #h(e, t, n) {
- ge(n < O2, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
+ ge(n < U2, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
reason: "TOO_MANY_REDIRECTS",
transaction: Object.assign({}, e, { blockTag: t, enableCcipRead: !0 })
});
@@ -48635,7 +48635,7 @@ class H2 {
const a = r.data, o = await zn(s.to, this);
let c;
try {
- c = K2(Kt(r.data, 4));
+ c = q2(Kt(r.data, 4));
} catch (u) {
ge(!1, u.message, "OFFCHAIN_FAULT", {
reason: "BAD_DATA",
@@ -48663,7 +48663,7 @@ class H2 {
});
const h = {
to: o,
- data: Ht([c.selector, q2([l, c.extraData])])
+ data: Ht([c.selector, W2([l, c.extraData])])
};
this.emit("debug", { action: "sendCcipReadCall", transaction: h });
try {
@@ -48890,20 +48890,20 @@ class H2 {
case "debug":
case "error":
case "network":
- return new jE(e.type);
+ return new KE(e.type);
case "block": {
- const t = new D2(this);
+ const t = new N2(this);
return t.pollingInterval = this.pollingInterval, t;
}
case "safe":
case "finalized":
- return new L2(this, e.type);
+ return new D2(this, e.type);
case "event":
return new Up(this, e.filter);
case "transaction":
- return new k2(this, e.hash);
+ return new P2(this, e.hash);
case "orphan":
- return new P2(this, e.filter);
+ return new L2(this, e.filter);
}
throw new Error(`unsupported event: ${e.type}`);
}
@@ -48946,7 +48946,7 @@ class H2 {
return !1;
const s = n.listeners.length;
return n.listeners = n.listeners.filter(({ listener: r, once: a }) => {
- const o = new pb(this, a ? null : r, e);
+ const o = new fb(this, a ? null : r, e);
try {
r.call(this, ...t, o);
} catch {
@@ -49070,7 +49070,7 @@ class H2 {
}
}
}
-function z2(i, e) {
+function H2(i, e) {
try {
const t = Nf(i, e);
if (t)
@@ -49096,26 +49096,26 @@ function c0(i) {
const t = new Uint8Array(32);
return t.set(e, 32 - e.length), t;
}
-function V2(i) {
+function z2(i) {
if (i.length % 32 === 0)
return i;
const e = new Uint8Array(Math.ceil(i.length / 32) * 32);
return e.set(i), e;
}
-const W2 = new Uint8Array([]);
-function q2(i) {
+const V2 = new Uint8Array([]);
+function W2(i) {
const e = [];
let t = 0;
for (let n = 0; n < i.length; n++)
- e.push(W2), t += 32;
+ e.push(V2), t += 32;
for (let n = 0; n < i.length; n++) {
const s = dt(i[n]);
- e[n] = c0(t), e.push(c0(s.length)), e.push(V2(s)), t += 32 + Math.ceil(s.length / 32) * 32;
+ e[n] = c0(t), e.push(c0(s.length)), e.push(z2(s)), t += 32 + Math.ceil(s.length / 32) * 32;
}
return Ht(e);
}
const l0 = "0x0000000000000000000000000000000000000000000000000000000000000000";
-function K2(i) {
+function q2(i) {
const e = {
sender: "",
urls: [],
@@ -49134,7 +49134,7 @@ function K2(i) {
try {
const n = [], s = ft(Kt(i, 32, 64)), r = ft(Kt(i, s, s + 32)), a = Kt(i, s + 32);
for (let o = 0; o < r; o++) {
- const c = z2(a, o * 32);
+ const c = H2(a, o * 32);
if (c == null)
throw new Error("abort");
n.push(c);
@@ -49187,7 +49187,7 @@ async function h0(i, e) {
t.from = i.getAddress();
return await On(t);
}
-class j2 {
+class K2 {
/**
* The provider this signer is connected to.
*/
@@ -49263,10 +49263,10 @@ class j2 {
ge(!1, "authorization not implemented for this signer", "UNSUPPORTED_OPERATION", { operation: "authorize" });
}
}
-function X2(i) {
+function j2(i) {
return JSON.parse(JSON.stringify(i));
}
-class XE {
+class jE {
#e;
#t;
#n;
@@ -49344,14 +49344,14 @@ class XE {
this.start();
}
}
-class Y2 extends XE {
+class X2 extends jE {
#e;
/**
* Creates a new **FilterIdEventSubscriber** attached to %%provider%%
* listening for %%filter%%.
*/
constructor(e, t) {
- super(e), this.#e = X2(t);
+ super(e), this.#e = j2(t);
}
_recover(e) {
return new Up(e, this.#e);
@@ -49364,7 +49364,7 @@ class Y2 extends XE {
e.emit(this.#e, e._wrapLog(n, e._network));
}
}
-class J2 extends XE {
+class Y2 extends jE {
async _subscribe(e) {
return await e.send("eth_newPendingTransactionFilter", []);
}
@@ -49373,9 +49373,9 @@ class J2 extends XE {
e.emit("pending", n);
}
}
-const Z2 = "bigint,boolean,function,number,string,symbol".split(/,/g);
+const J2 = "bigint,boolean,function,number,string,symbol".split(/,/g);
function Pl(i) {
- if (i == null || Z2.indexOf(typeof i) >= 0 || typeof i.getAddress == "function")
+ if (i == null || J2.indexOf(typeof i) >= 0 || typeof i.getAddress == "function")
return i;
if (Array.isArray(i))
return i.map(Pl);
@@ -49383,7 +49383,7 @@ function Pl(i) {
return Object.keys(i).reduce((e, t) => (e[t] = i[t], e), {});
throw new Error(`should not happen: ${i} (${typeof i})`);
}
-function $2(i) {
+function Z2(i) {
return new Promise((e) => {
setTimeout(e, i);
});
@@ -49394,7 +49394,7 @@ function ua(i) {
function u0(i) {
return i && typeof i.pollingInterval == "number";
}
-const YE = {
+const XE = {
polling: !1,
staticNetwork: null,
batchStallTime: 10,
@@ -49403,7 +49403,7 @@ const YE = {
cacheTimeout: 250,
pollingInterval: 4e3
};
-class ud extends j2 {
+class ud extends K2 {
address;
constructor(e, t) {
super(e), t = Mt(t), Ye(this, { address: t });
@@ -49517,7 +49517,7 @@ class ud extends j2 {
]);
}
}
-class eP extends H2 {
+class $2 extends G2 {
#e;
// The next ID to use for the JSON-RPC ID field
#t;
@@ -49577,7 +49577,7 @@ class eP extends H2 {
}, e);
}
constructor(e, t) {
- super(e, t), this.#t = 1, this.#e = Object.assign({}, YE, t || {}), this.#n = [], this.#i = null, this.#a = null, this.#r = null;
+ super(e, t), this.#t = 1, this.#e = Object.assign({}, XE, t || {}), this.#n = [], this.#i = null, this.#a = null, this.#r = null;
{
let s = null;
const r = new Promise((a) => {
@@ -49678,7 +49678,7 @@ class eP extends H2 {
} catch (e) {
if (this.destroyed)
break;
- console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"), this.emit("error", Gt("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error: e } })), await $2(1e3);
+ console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"), this.emit("error", Gt("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error: e } })), await Z2(1e3);
}
this.#o();
})());
@@ -49699,7 +49699,7 @@ class eP extends H2 {
* subscription management.
*/
_getSubscriber(e) {
- return e.type === "pending" ? new J2(this) : e.type === "event" ? this._getOption("polling") ? new Up(this, e.filter) : new Y2(this, e.filter) : e.type === "orphan" && e.filter.orphan === "drop-log" ? new jE("orphan") : super._getSubscriber(e);
+ return e.type === "pending" ? new Y2(this) : e.type === "event" ? this._getOption("polling") ? new Up(this, e.filter) : new X2(this, e.filter) : e.type === "orphan" && e.filter.orphan === "drop-log" ? new KE("orphan") : super._getSubscriber(e);
}
/**
* Returns true only if the [[_start]] has been called.
@@ -49722,7 +49722,7 @@ class eP extends H2 {
}), ["from", "to", "data"].forEach((n) => {
e[n] != null && (t[n] = Ie(e[n]));
}), e.accessList && (t.accessList = Hr(e.accessList)), e.blobVersionedHashes && (t.blobVersionedHashes = e.blobVersionedHashes.map((n) => n.toLowerCase())), e.authorizationList && (t.authorizationList = e.authorizationList.map((n) => {
- const s = tE(n);
+ const s = eE(n);
return {
address: s.address,
nonce: vi(s.nonce),
@@ -49838,7 +49838,7 @@ class eP extends H2 {
const o = Df(s), c = Va.getBuiltinCallException(n === "eth_call" ? "call" : "estimateGas", e.params[0], o ? o.data : null);
return c.info = { error: s, payload: e }, c;
}
- const r = JSON.stringify(tP(s));
+ const r = JSON.stringify(eP(s));
if (typeof s.message == "string" && s.message.match(/user denied|ethers-user-denied/i))
return Gt("user rejected action", "ACTION_REJECTED", {
action: {
@@ -49942,12 +49942,12 @@ class eP extends H2 {
this.#n = [], super.destroy();
}
}
-class JE extends eP {
+class YE extends $2 {
#e;
constructor(e, t) {
super(e, t);
let n = this._getOption("pollingInterval");
- n == null && (n = YE.pollingInterval), this.#e = n;
+ n == null && (n = XE.pollingInterval), this.#e = n;
}
_getSubscriber(e) {
const t = super._getSubscriber(e);
@@ -49967,7 +49967,7 @@ class JE extends eP {
});
}
}
-class ZE extends JE {
+class JE extends YE {
#e;
constructor(e, t, n) {
e == null && (e = "http://localhost:8545"), super(t, n), typeof e == "string" ? this.#e = new Hi(e) : this.#e = e.clone();
@@ -50019,11 +50019,11 @@ function Lf(i, e) {
}
}
}
-function tP(i) {
+function eP(i) {
const e = [];
return Lf(i, e), e;
}
-class br extends JE {
+class br extends YE {
#e;
#t;
/**
@@ -50148,7 +50148,7 @@ class br extends JE {
});
}
}
-const $E = [
+const ZE = [
// --- Registration ---
"function register() external returns (uint256 agentId)",
"function register(string agentURI) external returns (uint256 agentId)",
@@ -50235,10 +50235,10 @@ const $E = [
43113: ur
// Avalanche Fuji
};
-function nP(i, e) {
+function tP(i, e) {
return `eip155:${i}:${e}`;
}
-const ey = {
+const $E = {
// ── Mainnets ──────────────────────────────────────────────────────────
1: {
name: "Ethereum",
@@ -50418,27 +50418,27 @@ const ey = {
testnet: !0
}
};
-function iP(i, e) {
+function nP(i, e) {
if (e) return new br(e);
- const t = ey[i];
+ const t = $E[i];
if (!t) throw new Error(`No RPC configured for chainId ${i}`);
- return new ZE(t.rpcUrl, i);
+ return new JE(t.rpcUrl, i);
}
-function sP(i, e) {
+function iP(i, e) {
const t = Qh[i];
if (!t || !t.identityRegistry)
throw new Error(`No Identity Registry for chainId ${i}`);
- const n = iP(i, e);
- return new Mr(t.identityRegistry, $E, n);
+ const n = nP(i, e);
+ return new Mr(t.identityRegistry, ZE, n);
}
-async function rP({ chainId: i, agentId: e, ethProvider: t }) {
- const n = sP(i, t), [s, r] = await Promise.all([
+async function sP({ chainId: i, agentId: e, ethProvider: t }) {
+ const n = iP(i, t), [s, r] = await Promise.all([
n.ownerOf(e).catch(() => null),
n.tokenURI(e).catch(() => null)
]);
return { agentId: BigInt(e), owner: s, uri: r };
}
-function ty(i) {
+function ey(i) {
if (!i || typeof i != "object") return null;
const e = Array.isArray(i.services) ? i.services : [];
for (const n of e) {
@@ -50451,7 +50451,7 @@ function ty(i) {
const t = String(i.image || "").trim();
return /\.(glb|gltf)(\?|#|$)/i.test(t) ? t : null;
}
-async function aP(i) {
+async function rP(i) {
if (!i) return { ok: !1, error: "empty uri" };
if (i.startsWith("data:"))
try {
@@ -50471,13 +50471,13 @@ async function aP(i) {
return { ok: !1, error: t.message, resolvedUrl: e };
}
}
-const oP = {
+const aP = {
base: 8453,
"base-mainnet": 8453,
"base-sepolia": 84532,
ethereum: 1,
mainnet: 1
-}, cP = {
+}, oP = {
8453: "https://mainnet.base.org",
84532: "https://sepolia.base.org",
1: "https://eth.llamarpc.com"
@@ -50485,7 +50485,7 @@ const oP = {
async function Cl(i, { rpcURL: e, registry: t } = {}) {
if (!i) throw new Error("loadManifest: source required");
if (i.startsWith("agent://"))
- return lP(i, { rpcURL: e, registryOverride: t });
+ return cP(i, { rpcURL: e, registryOverride: t });
if (i.startsWith("ipfs://") || i.startsWith("ar://")) {
const n = Xs(i), s = await Pf(n);
return kf(s, { baseURI: Uf(n) });
@@ -50496,15 +50496,15 @@ async function Cl(i, { rpcURL: e, registry: t } = {}) {
}
throw new Error(`Unsupported manifest source: ${i}`);
}
-async function lP(i, { rpcURL: e, registryOverride: t }) {
+async function cP(i, { rpcURL: e, registryOverride: t }) {
const n = i.match(/^agent:\/\/([^/]+)\/(\d+)$/);
if (!n) throw new Error(`Malformed agent URI: ${i}`);
- const [, s, r] = n, a = oP[s.toLowerCase()] || Number(s);
+ const [, s, r] = n, a = aP[s.toLowerCase()] || Number(s);
if (!a) throw new Error(`Unknown chain: ${s}`);
const o = Qh[a], c = t || o?.identityRegistry;
if (!c)
throw new Error(`No registry deployed on chain ${a}. Pass registry= override.`);
- const l = new ZE(e || cP[a]), h = new Mr(c, $E, l), u = BigInt(r), d = await h.tokenURI(u);
+ const l = new JE(e || oP[a]), h = new Mr(c, ZE, l), u = BigInt(r), d = await h.tokenURI(u);
if (!d) throw new Error(`Agent ${r} on chain ${a} has no URI`);
const f = Xs(d), p = await Pf(f), m = kf(p, { baseURI: Uf(f) });
return m.id = {
@@ -50520,7 +50520,7 @@ async function Pf(i) {
try {
e = await fetch(i);
} catch {
- e = await rF(i);
+ e = await sF(i);
}
if (!e.ok) throw new Error(`Manifest fetch failed: ${i} (${e.status})`);
return e.json();
@@ -50531,7 +50531,7 @@ function kf(i, { baseURI: e = "" } = {}) {
return t.body = t.body || {}, !t.body.uri && t.image && (t.body.uri = t.image), t;
}
if (i.type && i.type.includes("eip-8004")) {
- const t = i.registrations?.[0] || {}, n = ty(i);
+ const t = i.registrations?.[0] || {}, n = ey(i);
return {
spec: "agent-manifest/0.1",
_baseURI: e,
@@ -50573,7 +50573,7 @@ function Uf(i) {
const e = i.lastIndexOf("/");
return e >= 0 ? i.slice(0, e + 1) : i;
}
-async function hP(i, e) {
+async function lP(i, e) {
if (!i._baseURI) return null;
try {
const t = new URL(e, i._baseURI).href, n = await fetch(t);
@@ -50615,8 +50615,8 @@ async function d0(i, { fetchFn: e }) {
throw new Nn("network", `invalid JSON from ${i}: ${n.message || n}`);
}
}
-const da = /* @__PURE__ */ new Map(), uP = 100;
-async function dP(i, e) {
+const da = /* @__PURE__ */ new Map(), hP = 100;
+async function uP(i, e) {
if (!i) throw new Nn("not-found", "agentId required");
if (da.has(i)) return da.get(i);
const t = typeof location < "u" ? location.origin : "", n = `${t}/api/agents/${encodeURIComponent(i)}`;
@@ -50653,9 +50653,9 @@ async function dP(i, e) {
} catch {
o = a;
}
- return da.size >= uP && da.delete(da.keys().next().value), da.set(i, o), o;
+ return da.size >= hP && da.delete(da.keys().next().value), da.set(i, o), o;
}
-async function fP(i, { origin: e = typeof location < "u" ? location.origin : "", fetchFn: t = fetch } = {}) {
+async function dP(i, { origin: e = typeof location < "u" ? location.origin : "", fetchFn: t = fetch } = {}) {
if (!i) throw new Nn("not_found", "agentId required");
const n = t.bind(typeof globalThis < "u" ? globalThis : void 0), r = (await d0(`${e}/api/agents/${encodeURIComponent(i)}`, {
fetchFn: n
@@ -50691,7 +50691,7 @@ async function fP(i, { origin: e = typeof location < "u" ? location.origin : "",
_source: "agent-id"
};
}
-function ny(i) {
+function ty(i) {
if (!i) return null;
if (typeof i == "object")
return i.chainId && i.agentId !== void 0 ? {
@@ -50704,28 +50704,28 @@ function ny(i) {
let t = e.match(/^eip155:(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/);
return t ? { chainId: Number(t[1]), registry: t[2], agentId: t[3] } : (t = e.match(/^eip155:(\d+)\/erc721:(0x[0-9a-fA-F]{40})\/(\d+)$/), t ? { chainId: Number(t[1]), registry: t[2], agentId: t[3] } : (t = e.match(/^onchain:(\d+):(\d+)$/), t ? { chainId: Number(t[1]), agentId: t[2] } : (t = e.match(/^agent:\/\/(\d+)\/(\d+)$/), t ? { chainId: Number(t[1]), agentId: t[2] } : (t = e.match(/^\/?a\/(\d+)\/(\d+)(?:\/(embed))?\/?$/), t ? { chainId: Number(t[1]), agentId: t[2] } : (t = e.match(/^\/?a\/(\d+)\/(0x[0-9a-fA-F]{40})\/(\d+)\/?$/), t ? { chainId: Number(t[1]), registry: t[2], agentId: t[3] } : null)))));
}
-function pP(i) {
+function fP(i) {
const e = i.registry || Qh[i.chainId]?.identityRegistry;
return e ? `eip155:${i.chainId}:${e}:${i.agentId}` : `onchain:${i.chainId}:${i.agentId}`;
}
-function AP(i, { embed: e = !1, origin: t } = {}) {
+function pP(i, { embed: e = !1, origin: t } = {}) {
return `${t || (typeof location < "u" ? location.origin : "")}/a/${i.chainId}/${i.agentId}${e ? "/embed" : ""}`;
}
-const gP = [
+const AP = [
"https://ipfs.io/ipfs/",
"https://dweb.link/ipfs/",
"https://cloudflare-ipfs.com/ipfs/",
"https://gateway.pinata.cloud/ipfs/"
-], mP = "https://arweave.net/";
+], gP = "https://arweave.net/";
function f0(i) {
- return i ? i.startsWith("ipfs://") ? gP[0] + i.slice(7) : i.startsWith("ar://") ? mP + i.slice(5) : i : "";
+ return i ? i.startsWith("ipfs://") ? AP[0] + i.slice(7) : i.startsWith("ar://") ? gP + i.slice(5) : i : "";
}
const yo = /* @__PURE__ */ new Map();
-function xP(i) {
+function mP(i) {
return `${i.chainId}:${i.agentId}`;
}
-async function bP(i, { ethProvider: e, fresh: t = !1 } = {}) {
- const n = ny(i);
+async function xP(i, { ethProvider: e, fresh: t = !1 } = {}) {
+ const n = ty(i);
if (!n) throw new Error(`Unrecognised agent reference: ${i}`);
const s = {
chainId: n.chainId,
@@ -50733,12 +50733,12 @@ async function bP(i, { ethProvider: e, fresh: t = !1 } = {}) {
registry: n.registry || Qh[n.chainId]?.identityRegistry || null
};
if (!s.registry) throw new Error(`No registry deployed on chain ${s.chainId}`);
- const r = xP(s);
+ const r = mP(s);
if (!t && yo.has(r)) return yo.get(r);
- const a = ey[s.chainId] || null, o = {
+ const a = $E[s.chainId] || null, o = {
ref: s,
- caip: pP(s),
- publicUrl: typeof location < "u" ? AP(s) : `/a/${s.chainId}/${s.agentId}`,
+ caip: fP(s),
+ publicUrl: typeof location < "u" ? pP(s) : `/a/${s.chainId}/${s.agentId}`,
chain: a ? { name: a.name, testnet: !!a.testnet, explorer: a.explorer } : null,
onchain: { owner: null, uri: null },
metadata: null,
@@ -50750,28 +50750,28 @@ async function bP(i, { ethProvider: e, fresh: t = !1 } = {}) {
services: []
};
try {
- const { owner: c, uri: l } = await rP({
+ const { owner: c, uri: l } = await sP({
chainId: s.chainId,
agentId: s.agentId,
ethProvider: e
});
if (o.onchain = { owner: c, uri: l }, !l)
return o.error = "agentURI not set", yo.set(r, o), o;
- const h = await aP(l);
+ const h = await rP(l);
if (!h.ok)
return o.error = h.error, o.metadataUrl = h.resolvedUrl || null, yo.set(r, o), o;
const u = h.data;
- o.metadata = u, o.metadataUrl = h.resolvedUrl || null, o.name = u?.name && String(u.name) || o.name, o.description = u?.description && String(u.description) || "", o.image = u?.image ? String(u.image) : null, o.services = Array.isArray(u?.services) ? u.services : [], o.glbUrl = ty(u);
+ o.metadata = u, o.metadataUrl = h.resolvedUrl || null, o.name = u?.name && String(u.name) || o.name, o.description = u?.description && String(u.description) || "", o.image = u?.image ? String(u.image) : null, o.services = Array.isArray(u?.services) ? u.services : [], o.glbUrl = ey(u);
} catch (c) {
o.error = c.message || String(c);
}
return yo.set(r, o), o;
}
-function EP(i) {
+function bP(i) {
const e = Array.isArray(i.services) ? i.services : [], t = e.find((a) => /brain|llm|chat/i.test(a?.name || a?.type || "")), n = e.filter((a) => /skill/i.test(a?.name || a?.type || "")), s = i.glbUrl ? f0(i.glbUrl) : "", r = i.image ? f0(i.image) : "";
return {
spec: "agent-manifest/0.1",
- _baseURI: i.metadataUrl ? yP(i.metadataUrl) : "",
+ _baseURI: i.metadataUrl ? EP(i.metadataUrl) : "",
_source: "erc8004-resolver",
id: {
agentId: i.ref.agentId,
@@ -50780,7 +50780,7 @@ function EP(i) {
owner: i.onchain.owner || void 0,
walletAddress: i.onchain.owner || void 0,
caip: i.caip,
- agentRegistry: nP(i.ref.chainId, i.ref.registry)
+ agentRegistry: tP(i.ref.chainId, i.ref.registry)
},
name: i.name,
description: i.description,
@@ -50797,11 +50797,11 @@ function EP(i) {
embedPolicy: i.metadata?.embedPolicy || null
};
}
-function yP(i) {
+function EP(i) {
const e = i.lastIndexOf("/");
return e >= 0 ? i.slice(0, e + 1) : i;
}
-const p0 = 1, _P = 256;
+const p0 = 1, yP = 256;
function Il() {
return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (i) => {
const e = Math.random() * 16 | 0;
@@ -50814,7 +50814,7 @@ const dd = {
emote: "emote",
look: "look-at"
};
-class wP {
+class _P {
/**
* @param {{ protocol: object, avatar?: object, manifest: object, window: Window }} opts
*/
@@ -50921,16 +50921,13 @@ class wP {
}
};
if (!this._subscribed) {
- this._evtQueue.length >= _P && this._evtQueue.shift(), this._evtQueue.push(t);
+ this._evtQueue.length >= yP && this._evtQueue.shift(), this._evtQueue.push(t);
return;
}
this._toParent(t);
}
}
-const vP = {
- SPEAK: "speak"
-};
-class CP extends EventTarget {
+class wP extends EventTarget {
constructor() {
super(), this._history = [], this._maxHistory = 200;
}
@@ -50985,14 +50982,14 @@ class CP extends EventTarget {
t.__protocolWrapped = s, n ? this.addEventListener(e, s, { once: !0 }) : this.addEventListener(e, s);
}
}
-const A0 = new CP(), IP = ["inline", "floating", "section", "fullscreen"], g0 = (() => {
+const vP = new wP(), CP = ["inline", "floating", "section", "fullscreen"], A0 = (() => {
try {
return new URL(import.meta.url).origin;
} catch {
return "";
}
})();
-function SP(i, e, t = []) {
+function IP(i, e, t = []) {
if (!i) return !1;
let n;
try {
@@ -51007,7 +51004,7 @@ function SP(i, e, t = []) {
});
return r === "allowlist" ? a : !a;
}
-const MP = `
+const SP = `
:host {
display: block;
position: relative;
@@ -51172,7 +51169,7 @@ const MP = `
font: 14px var(--agent-chat-font);
}
`;
-class iy extends HTMLElement {
+class ny extends HTMLElement {
static get observedAttributes() {
return [
"src",
@@ -51203,7 +51200,7 @@ class iy extends HTMLElement {
}
_renderShell() {
const e = document.createElement("style");
- e.textContent = MP, this.shadowRoot.appendChild(e);
+ e.textContent = SP, this.shadowRoot.appendChild(e);
const t = document.createElement("div");
t.className = "stage", t.part = "stage", this.shadowRoot.appendChild(t), this._stageEl = t;
const n = document.createElement("div");
@@ -51250,7 +51247,7 @@ class iy extends HTMLElement {
}
_applyLayout() {
const e = this.getAttribute("mode") || "inline";
- if (!IP.includes(e)) return;
+ if (!CP.includes(e)) return;
const t = this._isResponsive();
if (e === "floating") {
if (!this._pillActive) {
@@ -51335,8 +51332,8 @@ class iy extends HTMLElement {
if (this._manifest = e, this.dispatchEvent(
new CustomEvent("agent:load-progress", { detail: { phase: "manifest", pct: 0.3 } })
), typeof e.brain?.instructions == "string" && e.brain.instructions.endsWith(".md")) {
- const l = await hP(e, e.brain.instructions);
- l && (e.instructions = BP(l));
+ const l = await lP(e, e.brain.instructions);
+ l && (e.instructions = MP(l));
} else e.brain?.instructions && (e.instructions = e.brain.instructions);
const t = (() => {
const l = this.getAttribute("agent-id") || e.id?.agentId || "";
@@ -51344,7 +51341,7 @@ class iy extends HTMLElement {
})();
if (t)
try {
- const l = g0 || window.location.origin, h = await fetch(
+ const l = A0 || window.location.origin, h = await fetch(
`${l}/api/agents/${t}/embed-policy`,
{ credentials: "omit" }
);
@@ -51359,7 +51356,7 @@ class iy extends HTMLElement {
return;
}
const d = ["3dagent.vercel.app", "localhost"], f = window.location.origin;
- if (!f.startsWith("http://localhost") && !SP(f, u, d)) {
+ if (!f.startsWith("http://localhost") && !IP(f, u, d)) {
this._fail(
"embed_denied_origin",
`This agent isn't permitted on ${f}.`
@@ -51374,10 +51371,10 @@ class iy extends HTMLElement {
this.dispatchEvent(
new CustomEvent("agent:load-progress", { detail: { phase: "body", pct: 0.45 } })
);
- const n = new cb(this._stageEl, { kiosk: this.hasAttribute("kiosk") });
+ const n = new ob(this._stageEl, { kiosk: this.hasAttribute("kiosk") });
this._viewer = n;
const s = Xs(e.body?.uri);
- s && await n.load(s, "", /* @__PURE__ */ new Map()), this._scene = new cF(n), this.dispatchEvent(
+ s && await n.load(s, "", /* @__PURE__ */ new Map()), this._scene = new oF(n), this.dispatchEvent(
new CustomEvent("agent:load-progress", { detail: { phase: "memory", pct: 0.6 } })
);
const r = e.id?.agentId || this.getAttribute("memory-key") || e.name || "anon";
@@ -51388,7 +51385,7 @@ class iy extends HTMLElement {
fetchFn: fetch.bind(globalThis)
}), this.dispatchEvent(
new CustomEvent("agent:load-progress", { detail: { phase: "skills", pct: 0.75 } })
- ), this._skills = new wF({
+ ), this._skills = new _F({
trust: this.getAttribute("skill-trust") || "owned-only",
ownerAddress: e.id?.owner
});
@@ -51413,9 +51410,9 @@ class iy extends HTMLElement {
apiKey: this.getAttribute("api-key") || void 0,
proxyURL: this.getAttribute("key-proxy") || void 0,
agentId: t || void 0,
- apiOrigin: g0 || window.location.origin
+ apiOrigin: A0 || window.location.origin
}, c = this._parseTTSAttribute();
- c && (e.voice = e.voice || {}, e.voice.tts = { ...e.voice.tts || {}, ...c }), this._runtime = new iF({
+ c && (e.voice = e.voice || {}, e.voice.tts = { ...e.voice.tts || {}, ...c }), this._runtime = new nF({
manifest: e,
viewer: this._scene,
memory: this._memory,
@@ -51437,8 +51434,8 @@ class iy extends HTMLElement {
new CustomEvent(l, { detail: h.detail, bubbles: !0, composed: !0 })
), l === "brain:message" && this._chatEl && this._renderMessage(h.detail);
});
- this._mounted = !0, window !== window.parent && (this._embedBridge = new wP({
- protocol: A0,
+ this._mounted = !0, window !== window.parent && (this._embedBridge = new _P({
+ protocol: vP,
manifest: this._manifest,
window
}), this._embedBridge.start()), this._loadingEl.hidden = !0, this._pillActive || (this._posterEl.style.opacity = "0"), this.dispatchEvent(
@@ -51478,16 +51475,16 @@ class iy extends HTMLElement {
chainId: Number(r),
agentId: s,
registry: this.getAttribute("registry") || void 0
- } : s, o = ny(a);
+ } : s, o = ty(a);
if (o) {
- const l = await bP(o);
+ const l = await xP(o);
if (l.error && !l.glbUrl)
throw new Error(`On-chain resolve failed: ${l.error}`);
- return EP(l);
+ return bP(l);
}
if (t) return Cl(t);
- const c = await dP(s);
- return c ? (this._autoResolvedManifest = !0, this.setAttribute("manifest", c), Cl(c)) : fP(s);
+ const c = await uP(s);
+ return c ? (this._autoResolvedManifest = !0, this.setAttribute("manifest", c), Cl(c)) : dP(s);
}
if (t) return Cl(t);
if (n) {
@@ -51586,9 +51583,10 @@ class iy extends HTMLElement {
async say(e, t = {}) {
return this._runtime || await this._waitForReady(), this._runtime.send(e, { voice: t.voice ?? this.hasAttribute("voice") });
}
- // Emit speak directly on the protocol bus — triggers avatar animation without going through LLM.
+ // Play speak animation — tries 'talk', falls back to 'yes', then 'wave'.
speak(e, t = {}) {
- A0.emit(vP.SPEAK, { text: e, sentiment: t.sentiment ?? 0 });
+ const n = Math.max(1.5, (e?.split(" ").length ?? 3) * 0.3), s = this._scene;
+ s && (s.playAnimationByHint("talk", { duration: n }) || s.playAnimationByHint("yes", { duration: n }) || s.playAnimationByHint("wave", { duration: n }));
}
async ask(e, t = {}) {
return (await this.say(e, t))?.text || "";
@@ -51650,12 +51648,12 @@ class iy extends HTMLElement {
});
}
}
-function BP(i) {
+function MP(i) {
const e = i.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);
return e ? e[1] : i;
}
-customElements.get("agent-3d") || customElements.define("agent-3d", iy);
-const TP = ["row", "circle", "freeform"], RP = `
+customElements.get("agent-3d") || customElements.define("agent-3d", ny);
+const BP = ["row", "circle", "freeform"], TP = `
:host {
display: block;
position: relative;
@@ -51676,7 +51674,7 @@ const TP = ["row", "circle", "freeform"], RP = `
pointer-events: none;
}
`;
-class FP extends HTMLElement {
+class RP extends HTMLElement {
static get observedAttributes() {
return ["formation"];
}
@@ -51703,14 +51701,14 @@ class FP extends HTMLElement {
}
get formation() {
const e = this.getAttribute("formation") || "row";
- return TP.includes(e) ? e : "row";
+ return BP.includes(e) ? e : "row";
}
get viewer() {
return this._viewer;
}
_renderShell() {
const e = document.createElement("style");
- e.textContent = RP, this.shadowRoot.appendChild(e);
+ e.textContent = TP, this.shadowRoot.appendChild(e);
const t = document.createElement("div");
t.className = "stage-canvas", t.part = "stage", this.shadowRoot.appendChild(t), this._canvasBox = t;
const n = document.createElement("slot");
@@ -51718,7 +51716,7 @@ class FP extends HTMLElement {
}
_initViewer() {
if (!this._initialized) {
- this._viewer = new cb(this._canvasBox, { kiosk: !0 }), this._viewer.defaultCamera.position.set(0, 1.55, 3.4), this._viewer.defaultCamera.lookAt(0, 1.2, 0), this._viewer.controls.target.set(0, 1.2, 0), this._viewer.controls.update();
+ this._viewer = new ob(this._canvasBox, { kiosk: !0 }), this._viewer.defaultCamera.position.set(0, 1.55, 3.4), this._viewer.defaultCamera.lookAt(0, 1.2, 0), this._viewer.controls.target.set(0, 1.2, 0), this._viewer.controls.update();
try {
this._viewer.updateLights?.();
} catch {
@@ -51749,7 +51747,7 @@ class FP extends HTMLElement {
this._viewer?.scene.remove(n.group);
} catch {
}
- NP(n.group), this._repositionAll(), this.dispatchEvent(
+ FP(n.group), this._repositionAll(), this.dispatchEvent(
new CustomEvent("stage:agent-left", {
detail: { agentId: n.id, element: n.element },
bubbles: !0,
@@ -51847,7 +51845,7 @@ class FP extends HTMLElement {
};
}
}
-function NP(i) {
+function FP(i) {
i.traverse((e) => {
if (e.geometry)
try {
@@ -51873,22 +51871,22 @@ function NP(i) {
}
}), i.parent && i.parent.remove(i);
}
-customElements.get("agent-stage") || customElements.define("agent-stage", FP);
-const PP = (i = "agent-3d") => {
- customElements.get(i) || customElements.define(i, iy);
+customElements.get("agent-stage") || customElements.define("agent-stage", RP);
+const LP = (i = "agent-3d") => {
+ customElements.get(i) || customElements.define(i, ny);
};
export {
- iy as Agent3DElement,
- FP as AgentStageElement,
+ ny as Agent3DElement,
+ RP as AgentStageElement,
ki as Memory,
- iF as Runtime,
- cF as SceneController,
- _F as Skill,
- wF as SkillRegistry,
- cb as Viewer,
- PP as defineElement,
- hP as fetchRelative,
- rF as fetchWithFallback,
+ nF as Runtime,
+ oF as SceneController,
+ yF as Skill,
+ _F as SkillRegistry,
+ ob as Viewer,
+ LP as defineElement,
+ lP as fetchRelative,
+ sF as fetchWithFallback,
Cl as loadManifest,
kf as normalize,
Xs as resolveURI
diff --git a/dist-lib/agent-3d.umd.cjs b/dist-lib/agent-3d.umd.cjs
index aeba5143b..6c0aaf8fb 100644
--- a/dist-lib/agent-3d.umd.cjs
+++ b/dist-lib/agent-3d.umd.cjs
@@ -1,8 +1,8 @@
-(function(on,nr){typeof exports=="object"&&typeof module<"u"?nr(exports):typeof define=="function"&&define.amd?define(["exports"],nr):(on=typeof globalThis<"u"?globalThis:on||self,nr(on.Agent3D={}))})(this,(function(on){"use strict";var nr=typeof document<"u"?document.currentScript:null;const Ic="176",qr={ROTATE:0,DOLLY:1,PAN:2},Kr={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},py=0,Vp=1,Ay=2,Wp=1,gy=2,Ki=3,ji=0,Ln=1,Pi=2,Cs=0,jr=1,qp=2,Kp=3,jp=4,my=5,ir=100,xy=101,by=102,Ey=103,yy=104,_y=200,wy=201,vy=202,Cy=203,Wh=204,qh=205,Iy=206,Sy=207,My=208,By=209,Ty=210,Ry=211,Fy=212,Ny=213,Dy=214,Kh=0,jh=1,Xh=2,Xr=3,Yh=4,Jh=5,Zh=6,$h=7,Sc=0,Ly=1,Py=2,Is=0,eu=1,ky=2,Uy=3,Xp=4,Oy=5,Qy=6,Gy=7,Yp="attached",Hy="detached",Jp=300,sr=301,Yr=302,Mc=303,tu=304,Bc=306,Ss=1e3,Zn=1001,Tc=1002,Pn=1003,Zp=1004,no=1005,qt=1006,Rc=1007,ri=1008,cn=1009,$p=1010,eA=1011,io=1012,nu=1013,rr=1014,ln=1015,kn=1016,iu=1017,su=1018,so=1020,tA=35902,nA=1021,iA=1022,hn=1023,ro=1026,ao=1027,Xi=1028,ru=1029,ar=1030,au=1031,ou=1033,Fc=33776,oo=33777,Nc=33778,co=33779,Dc=35840,cu=35841,Lc=35842,lu=35843,Pc=36196,kc=37492,Uc=37496,lo=37808,hu=37809,uu=37810,du=37811,ho=37812,fu=37813,pu=37814,Au=37815,gu=37816,mu=37817,xu=37818,bu=37819,Eu=37820,yu=37821,uo=36492,_u=36494,Oc=36495,sA=36283,wu=36284,vu=36285,Cu=36286,rA=2200,aA=2201,zy=2202,fo=2300,po=2301,Iu=2302,Jr=2400,Zr=2401,Qc=2402,Su=2500,Vy=2501,Wy=0,oA=1,Mu=2,qy=3200,Ky=3201,Gc=0,jy=1,mi="",yt="srgb",un="srgb-linear",Hc="linear",Rt="srgb",$r=7680,cA=519,Xy=512,Yy=513,Jy=514,lA=515,Zy=516,$y=517,e_=518,t_=519,Bu=35044,hA="300 es",Yi=2e3,zc=2001;class Ms{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,a=s.length;r<a;r++)s[r].call(this,e);e.target=null}}}const Fn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let uA=1234567;const Ao=Math.PI/180,ea=180/Math.PI;function xi(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Fn[i&255]+Fn[i>>8&255]+Fn[i>>16&255]+Fn[i>>24&255]+"-"+Fn[e&255]+Fn[e>>8&255]+"-"+Fn[e>>16&15|64]+Fn[e>>24&255]+"-"+Fn[t&63|128]+Fn[t>>8&255]+"-"+Fn[t>>16&255]+Fn[t>>24&255]+Fn[n&255]+Fn[n>>8&255]+Fn[n>>16&255]+Fn[n>>24&255]).toLowerCase()}function at(i,e,t){return Math.max(e,Math.min(t,i))}function Tu(i,e){return(i%e+e)%e}function n_(i,e,t,n,s){return n+(i-e)*(s-n)/(t-e)}function i_(i,e,t){return i!==e?(t-i)/(e-i):0}function go(i,e,t){return(1-t)*i+t*e}function s_(i,e,t,n){return go(i,e,1-Math.exp(-t*n))}function r_(i,e=1){return e-Math.abs(Tu(i,e*2)-e)}function a_(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*(3-2*i))}function o_(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*i*(i*(i*6-15)+10))}function c_(i,e){return i+Math.floor(Math.random()*(e-i+1))}function l_(i,e){return i+Math.random()*(e-i)}function h_(i){return i*(.5-Math.random())}function u_(i){i!==void 0&&(uA=i);let e=uA+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function d_(i){return i*Ao}function f_(i){return i*ea}function p_(i){return(i&i-1)===0&&i!==0}function A_(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function g_(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function m_(i,e,t,n,s){const r=Math.cos,a=Math.sin,o=r(t/2),c=a(t/2),l=r((e+n)/2),h=a((e+n)/2),u=r((e-n)/2),d=a((e-n)/2),f=r((n-e)/2),p=a((n-e)/2);switch(s){case"XYX":i.set(o*h,c*u,c*d,o*l);break;case"YZY":i.set(c*d,o*h,c*u,o*l);break;case"ZXZ":i.set(c*u,c*d,o*h,o*l);break;case"XZX":i.set(o*h,c*p,c*f,o*l);break;case"YXY":i.set(c*f,o*h,c*p,o*l);break;case"ZYZ":i.set(c*p,c*f,o*h,o*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function bi(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function Bt(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}const In={DEG2RAD:Ao,RAD2DEG:ea,generateUUID:xi,clamp:at,euclideanModulo:Tu,mapLinear:n_,inverseLerp:i_,lerp:go,damp:s_,pingpong:r_,smoothstep:a_,smootherstep:o_,randInt:c_,randFloat:l_,randFloatSpread:h_,seededRandom:u_,degToRad:d_,radToDeg:f_,isPowerOfTwo:p_,ceilPowerOfTwo:A_,floorPowerOfTwo:g_,setQuaternionFromProperEuler:m_,normalize:Bt,denormalize:bi};class Je{constructor(e=0,t=0){Je.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(at(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*s+e.x,this.y=r*s+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ot{constructor(e,t,n,s,r,a,o,c,l){ot.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l)}set(e,t,n,s,r,a,o,c,l){const h=this.elements;return h[0]=e,h[1]=s,h[2]=o,h[3]=t,h[4]=r,h[5]=c,h[6]=n,h[7]=a,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],h=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=s[0],g=s[3],A=s[6],_=s[1],x=s[4],E=s[7],S=s[2],w=s[5],I=s[8];return r[0]=a*m+o*_+c*S,r[3]=a*g+o*x+c*w,r[6]=a*A+o*E+c*I,r[1]=l*m+h*_+u*S,r[4]=l*g+h*x+u*w,r[7]=l*A+h*E+u*I,r[2]=d*m+f*_+p*S,r[5]=d*g+f*x+p*w,r[8]=d*A+f*E+p*I,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8];return t*a*h-t*o*l-n*r*h+n*o*c+s*r*l-s*a*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=h*a-o*l,d=o*c-h*r,f=l*r-a*c,p=t*u+n*d+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(s*l-h*n)*m,e[2]=(o*n-s*a)*m,e[3]=d*m,e[4]=(h*t-s*c)*m,e[5]=(s*r-o*t)*m,e[6]=f*m,e[7]=(n*c-l*t)*m,e[8]=(a*t-n*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,a,o){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-s*l,s*c,-s*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Ru.makeScale(e,t)),this}rotate(e){return this.premultiply(Ru.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ru.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Ru=new ot;function dA(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function mo(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function x_(){const i=mo("canvas");return i.style.display="block",i}const fA={};function Vc(i){i in fA||(fA[i]=!0,console.warn(i))}function b_(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}function E_(i){const e=i.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function y_(i){const e=i.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const pA=new ot().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),AA=new ot().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function __(){const i={enabled:!0,workingColorSpace:un,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===Rt&&(s.r=Ji(s.r),s.g=Ji(s.g),s.b=Ji(s.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Rt&&(s.r=ta(s.r),s.g=ta(s.g),s.b=ta(s.b))),s},fromWorkingColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},toWorkingColorSpace:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===mi?Hc:this.spaces[s].transfer},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,a){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[un]:{primaries:e,whitePoint:n,transfer:Hc,toXYZ:pA,fromXYZ:AA,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:yt},outputColorSpaceConfig:{drawingBufferColorSpace:yt}},[yt]:{primaries:e,whitePoint:n,transfer:Rt,toXYZ:pA,fromXYZ:AA,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:yt}}}),i}const tt=__();function Ji(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ta(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let na;class w_{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{na===void 0&&(na=mo("canvas")),na.width=e.width,na.height=e.height;const s=na.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=na}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=mo("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let a=0;a<r.length;a++)r[a]=Ji(r[a]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Ji(t[n]/255)*255):t[n]=Ji(t[n]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let v_=0;class Fu{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:v_++}),this.uuid=xi(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let a=0,o=s.length;a<o;a++)s[a].isDataTexture?r.push(Nu(s[a].image)):r.push(Nu(s[a]))}else r=Nu(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Nu(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?w_.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let C_=0;class nn extends Ms{constructor(e=nn.DEFAULT_IMAGE,t=nn.DEFAULT_MAPPING,n=Zn,s=Zn,r=qt,a=ri,o=hn,c=cn,l=nn.DEFAULT_ANISOTROPY,h=mi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:C_++}),this.uuid=xi(),this.name="",this.source=new Fu(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=a,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=c,this.offset=new Je(0,0),this.repeat=new Je(1,1),this.center=new Je(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ot,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isTextureArray=!1,this.pmremVersion=0}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isTextureArray=e.isTextureArray,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Jp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ss:e.x=e.x-Math.floor(e.x);break;case Zn:e.x=e.x<0?0:1;break;case Tc:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Ss:e.y=e.y-Math.floor(e.y);break;case Zn:e.y=e.y<0?0:1;break;case Tc:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}nn.DEFAULT_IMAGE=null,nn.DEFAULT_MAPPING=Jp,nn.DEFAULT_ANISOTROPY=1;class gt{constructor(e=0,t=0,n=0,s=1){gt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*s+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*s+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*s+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*s+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],m=c[2],g=c[6],A=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(p-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(p+g)<.1&&Math.abs(l+f+A-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const x=(l+1)/2,E=(f+1)/2,S=(A+1)/2,w=(h+d)/4,I=(u+m)/4,T=(p+g)/4;return x>E&&x>S?x<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(x),s=w/n,r=I/n):E>S?E<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(E),n=w/s,r=T/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=I/r,s=T/r),this.set(n,s,r,t),this}let _=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(g-p)/_,this.y=(u-m)/_,this.z=(d-h)/_,this.w=Math.acos((l+f+A-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this.z=at(this.z,e.z,t.z),this.w=at(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this.z=at(this.z,e,t),this.w=at(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class I_ extends Ms{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth?n.depth:1,this.scissor=new gt(0,0,e,t),this.scissorTest=!1,this.viewport=new gt(0,0,e,t);const s={width:e,height:t,depth:this.depth};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:qt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,multiview:!1},n);const r=new nn(s,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);r.flipY=!1,r.generateMipmaps=n.generateMipmaps,r.internalFormat=n.internalFormat,this.textures=[];const a=n.count;for(let o=0;o<a;o++)this.textures[o]=r.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Fu(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class or extends I_{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class gA extends nn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Pn,this.minFilter=Pn,this.wrapR=Zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class mA extends nn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Pn,this.minFilter=Pn,this.wrapR=Zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Yt{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,a,o){let c=n[s+0],l=n[s+1],h=n[s+2],u=n[s+3];const d=r[a+0],f=r[a+1],p=r[a+2],m=r[a+3];if(o===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}if(u!==m||c!==d||l!==f||h!==p){let g=1-o;const A=c*d+l*f+h*p+u*m,_=A>=0?1:-1,x=1-A*A;if(x>Number.EPSILON){const S=Math.sqrt(x),w=Math.atan2(S,A*_);g=Math.sin(g*w)/S,o=Math.sin(o*w)/S}const E=o*_;if(c=c*g+d*E,l=l*g+f*E,h=h*g+p*E,u=u*g+m*E,g===1-o){const S=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=S,l*=S,h*=S,u*=S}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,a){const o=n[s],c=n[s+1],l=n[s+2],h=n[s+3],u=r[a],d=r[a+1],f=r[a+2],p=r[a+3];return e[t]=o*p+h*u+c*f-l*d,e[t+1]=c*p+h*d+l*u-o*f,e[t+2]=l*p+h*f+o*d-c*u,e[t+3]=h*p-o*u-c*d-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),h=o(s/2),u=o(r/2),d=c(n/2),f=c(s/2),p=c(r/2);switch(a){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],a=t[1],o=t[5],c=t[9],l=t[2],h=t[6],u=t[10],d=n+o+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(r-l)*f,this._z=(a-s)*f}else if(n>o&&n>u){const f=2*Math.sqrt(1+n-o-u);this._w=(h-c)/f,this._x=.25*f,this._y=(s+a)/f,this._z=(r+l)/f}else if(o>u){const f=2*Math.sqrt(1+o-n-u);this._w=(r-l)/f,this._x=(s+a)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-n-o);this._w=(a-s)/f,this._x=(r+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<Number.EPSILON?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(at(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,a=e._w,o=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+a*o+s*l-r*c,this._y=s*h+a*c+r*o-n*l,this._z=r*h+a*l+n*c-s*o,this._w=a*h-n*o-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const n=this._x,s=this._y,r=this._z,a=this._w;let o=a*e._w+n*e._x+s*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=s,this._z=r,this;const c=1-o*o;if(c<=Number.EPSILON){const f=1-t;return this._w=f*a+t*this._w,this._x=f*n+t*this._x,this._y=f*s+t*this._y,this._z=f*r+t*this._z,this.normalize(),this}const l=Math.sqrt(c),h=Math.atan2(l,o),u=Math.sin((1-t)*h)/l,d=Math.sin(t*h)/l;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=s*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class G{constructor(e=0,t=0,n=0){G.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(xA.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(xA.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*s-o*n),h=2*(o*t-r*s),u=2*(r*n-a*t);return this.x=t+c*l+a*u-o*h,this.y=n+c*h+o*l-r*u,this.z=s+c*u+r*h-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this.z=at(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this.z=at(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,a=t.x,o=t.y,c=t.z;return this.x=s*c-r*o,this.y=r*a-n*c,this.z=n*o-s*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Du.copy(this).projectOnVector(e),this.sub(Du)}reflect(e){return this.sub(Du.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(at(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Du=new G,xA=new Yt;class ki{constructor(e=new G(1/0,1/0,1/0),t=new G(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Ei.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ei.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Ei.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,Ei):Ei.fromBufferAttribute(r,a),Ei.applyMatrix4(e.matrixWorld),this.expandByPoint(Ei);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Wc.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Wc.copy(n.boundingBox)),Wc.applyMatrix4(e.matrixWorld),this.union(Wc)}const s=e.children;for(let r=0,a=s.length;r<a;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ei),Ei.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(xo),qc.subVectors(this.max,xo),ia.subVectors(e.a,xo),sa.subVectors(e.b,xo),ra.subVectors(e.c,xo),Bs.subVectors(sa,ia),Ts.subVectors(ra,sa),cr.subVectors(ia,ra);let t=[0,-Bs.z,Bs.y,0,-Ts.z,Ts.y,0,-cr.z,cr.y,Bs.z,0,-Bs.x,Ts.z,0,-Ts.x,cr.z,0,-cr.x,-Bs.y,Bs.x,0,-Ts.y,Ts.x,0,-cr.y,cr.x,0];return!Lu(t,ia,sa,ra,qc)||(t=[1,0,0,0,1,0,0,0,1],!Lu(t,ia,sa,ra,qc))?!1:(Kc.crossVectors(Bs,Ts),t=[Kc.x,Kc.y,Kc.z],Lu(t,ia,sa,ra,qc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ei).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ei).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Zi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Zi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Zi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Zi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Zi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Zi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Zi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Zi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Zi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Zi=[new G,new G,new G,new G,new G,new G,new G,new G],Ei=new G,Wc=new ki,ia=new G,sa=new G,ra=new G,Bs=new G,Ts=new G,cr=new G,xo=new G,qc=new G,Kc=new G,lr=new G;function Lu(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){lr.fromArray(i,r);const o=s.x*Math.abs(lr.x)+s.y*Math.abs(lr.y)+s.z*Math.abs(lr.z),c=e.dot(lr),l=t.dot(lr),h=n.dot(lr);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>o)return!1}return!0}const S_=new ki,bo=new G,Pu=new G;class Ui{constructor(e=new G,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):S_.setFromPoints(e).getCenter(n);let s=0;for(let r=0,a=e.length;r<a;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;bo.subVectors(e,this.center);const t=bo.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(bo,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Pu.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(bo.copy(e.center).add(Pu)),this.expandByPoint(bo.copy(e.center).sub(Pu))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const $i=new G,ku=new G,jc=new G,Rs=new G,Uu=new G,Xc=new G,Ou=new G;class Eo{constructor(e=new G,t=new G(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,$i)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=$i.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):($i.copy(this.origin).addScaledVector(this.direction,t),$i.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){ku.copy(e).add(t).multiplyScalar(.5),jc.copy(t).sub(e).normalize(),Rs.copy(this.origin).sub(ku);const r=e.distanceTo(t)*.5,a=-this.direction.dot(jc),o=Rs.dot(this.direction),c=-Rs.dot(jc),l=Rs.lengthSq(),h=Math.abs(1-a*a);let u,d,f,p;if(h>0)if(u=a*c-o,d=a*o-c,p=r*h,u>=0)if(d>=-p)if(d<=p){const m=1/h;u*=m,d*=m,f=u*(u+a*d+2*o)+d*(a*u+d+2*c)+l}else d=r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;else d=-r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-a*r+o)),d=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-r,-c),r),f=d*(d+2*c)+l):(u=Math.max(0,-(a*r+o)),d=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+d*(d+2*c)+l);else d=a>0?-r:r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(ku).addScaledVector(jc,d),f}intersectSphere(e,t){$i.subVectors(e.center,this.origin);const n=$i.dot(this.direction),s=$i.dot($i)-n*n,r=e.radius*e.radius;if(s>r)return null;const a=Math.sqrt(r-s),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,a,o,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(n=(e.min.x-d.x)*l,s=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,s=(e.min.x-d.x)*l),h>=0?(r=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),n>a||r>s||((r>n||isNaN(n))&&(n=r),(a<s||isNaN(s))&&(s=a),u>=0?(o=(e.min.z-d.z)*u,c=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,c=(e.min.z-d.z)*u),n>c||o>s)||((o>n||n!==n)&&(n=o),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,$i)!==null}intersectTriangle(e,t,n,s,r){Uu.subVectors(t,e),Xc.subVectors(n,e),Ou.crossVectors(Uu,Xc);let a=this.direction.dot(Ou),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Rs.subVectors(this.origin,e);const c=o*this.direction.dot(Xc.crossVectors(Rs,Xc));if(c<0)return null;const l=o*this.direction.dot(Uu.cross(Rs));if(l<0||c+l>a)return null;const h=-o*Rs.dot(Ou);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Re{constructor(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){Re.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g)}set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){const A=this.elements;return A[0]=e,A[4]=t,A[8]=n,A[12]=s,A[1]=r,A[5]=a,A[9]=o,A[13]=c,A[2]=l,A[6]=h,A[10]=u,A[14]=d,A[3]=f,A[7]=p,A[11]=m,A[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Re().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,s=1/aa.setFromMatrixColumn(e,0).length(),r=1/aa.setFromMatrixColumn(e,1).length(),a=1/aa.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(s),l=Math.sin(s),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const d=a*h,f=a*u,p=o*h,m=o*u;t[0]=c*h,t[4]=-c*u,t[8]=l,t[1]=f+p*l,t[5]=d-m*l,t[9]=-o*c,t[2]=m-d*l,t[6]=p+f*l,t[10]=a*c}else if(e.order==="YXZ"){const d=c*h,f=c*u,p=l*h,m=l*u;t[0]=d+m*o,t[4]=p*o-f,t[8]=a*l,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=f*o-p,t[6]=m+d*o,t[10]=a*c}else if(e.order==="ZXY"){const d=c*h,f=c*u,p=l*h,m=l*u;t[0]=d-m*o,t[4]=-a*u,t[8]=p+f*o,t[1]=f+p*o,t[5]=a*h,t[9]=m-d*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const d=a*h,f=a*u,p=o*h,m=o*u;t[0]=c*h,t[4]=p*l-f,t[8]=d*l+m,t[1]=c*u,t[5]=m*l+d,t[9]=f*l-p,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const d=a*c,f=a*l,p=o*c,m=o*l;t[0]=c*h,t[4]=m-d*u,t[8]=p*u+f,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-l*h,t[6]=f*u+p,t[10]=d-m*u}else if(e.order==="XZY"){const d=a*c,f=a*l,p=o*c,m=o*l;t[0]=c*h,t[4]=-u,t[8]=l*h,t[1]=d*u+m,t[5]=a*h,t[9]=f*u-p,t[2]=p*u-f,t[6]=o*h,t[10]=m*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(M_,e,B_)}lookAt(e,t,n){const s=this.elements;return $n.subVectors(e,t),$n.lengthSq()===0&&($n.z=1),$n.normalize(),Fs.crossVectors(n,$n),Fs.lengthSq()===0&&(Math.abs(n.z)===1?$n.x+=1e-4:$n.z+=1e-4,$n.normalize(),Fs.crossVectors(n,$n)),Fs.normalize(),Yc.crossVectors($n,Fs),s[0]=Fs.x,s[4]=Yc.x,s[8]=$n.x,s[1]=Fs.y,s[5]=Yc.y,s[9]=$n.y,s[2]=Fs.z,s[6]=Yc.z,s[10]=$n.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],h=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],g=n[10],A=n[14],_=n[3],x=n[7],E=n[11],S=n[15],w=s[0],I=s[4],T=s[8],C=s[12],v=s[1],F=s[5],K=s[9],q=s[13],$=s[2],D=s[6],O=s[10],Y=s[14],Q=s[3],J=s[7],ee=s[11],ae=s[15];return r[0]=a*w+o*v+c*$+l*Q,r[4]=a*I+o*F+c*D+l*J,r[8]=a*T+o*K+c*O+l*ee,r[12]=a*C+o*q+c*Y+l*ae,r[1]=h*w+u*v+d*$+f*Q,r[5]=h*I+u*F+d*D+f*J,r[9]=h*T+u*K+d*O+f*ee,r[13]=h*C+u*q+d*Y+f*ae,r[2]=p*w+m*v+g*$+A*Q,r[6]=p*I+m*F+g*D+A*J,r[10]=p*T+m*K+g*O+A*ee,r[14]=p*C+m*q+g*Y+A*ae,r[3]=_*w+x*v+E*$+S*Q,r[7]=_*I+x*F+E*D+S*J,r[11]=_*T+x*K+E*O+S*ee,r[15]=_*C+x*q+E*Y+S*ae,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],a=e[1],o=e[5],c=e[9],l=e[13],h=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],g=e[11],A=e[15];return p*(+r*c*u-s*l*u-r*o*d+n*l*d+s*o*f-n*c*f)+m*(+t*c*f-t*l*d+r*a*d-s*a*f+s*l*h-r*c*h)+g*(+t*l*u-t*o*f-r*a*u+n*a*f+r*o*h-n*l*h)+A*(-s*o*h-t*c*u+t*o*d+s*a*u-n*a*d+n*c*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],g=e[14],A=e[15],_=u*g*l-m*d*l+m*c*f-o*g*f-u*c*A+o*d*A,x=p*d*l-h*g*l-p*c*f+a*g*f+h*c*A-a*d*A,E=h*m*l-p*u*l+p*o*f-a*m*f-h*o*A+a*u*A,S=p*u*c-h*m*c-p*o*d+a*m*d+h*o*g-a*u*g,w=t*_+n*x+s*E+r*S;if(w===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const I=1/w;return e[0]=_*I,e[1]=(m*d*r-u*g*r-m*s*f+n*g*f+u*s*A-n*d*A)*I,e[2]=(o*g*r-m*c*r+m*s*l-n*g*l-o*s*A+n*c*A)*I,e[3]=(u*c*r-o*d*r-u*s*l+n*d*l+o*s*f-n*c*f)*I,e[4]=x*I,e[5]=(h*g*r-p*d*r+p*s*f-t*g*f-h*s*A+t*d*A)*I,e[6]=(p*c*r-a*g*r-p*s*l+t*g*l+a*s*A-t*c*A)*I,e[7]=(a*d*r-h*c*r+h*s*l-t*d*l-a*s*f+t*c*f)*I,e[8]=E*I,e[9]=(p*u*r-h*m*r-p*n*f+t*m*f+h*n*A-t*u*A)*I,e[10]=(a*m*r-p*o*r+p*n*l-t*m*l-a*n*A+t*o*A)*I,e[11]=(h*o*r-a*u*r-h*n*l+t*u*l+a*n*f-t*o*f)*I,e[12]=S*I,e[13]=(h*m*s-p*u*s+p*n*d-t*m*d-h*n*g+t*u*g)*I,e[14]=(p*o*s-a*m*s-p*n*c+t*m*c+a*n*g-t*o*g)*I,e[15]=(a*u*s-h*o*s+h*n*c-t*u*c-a*n*d+t*o*d)*I,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,a=e.x,o=e.y,c=e.z,l=r*a,h=r*o;return this.set(l*a+n,l*o-s*c,l*c+s*o,0,l*o+s*c,h*o+n,h*c-s*a,0,l*c-s*o,h*c+s*a,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,a){return this.set(1,n,r,0,e,1,a,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,a=t._y,o=t._z,c=t._w,l=r+r,h=a+a,u=o+o,d=r*l,f=r*h,p=r*u,m=a*h,g=a*u,A=o*u,_=c*l,x=c*h,E=c*u,S=n.x,w=n.y,I=n.z;return s[0]=(1-(m+A))*S,s[1]=(f+E)*S,s[2]=(p-x)*S,s[3]=0,s[4]=(f-E)*w,s[5]=(1-(d+A))*w,s[6]=(g+_)*w,s[7]=0,s[8]=(p+x)*I,s[9]=(g-_)*I,s[10]=(1-(d+m))*I,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;let r=aa.set(s[0],s[1],s[2]).length();const a=aa.set(s[4],s[5],s[6]).length(),o=aa.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),e.x=s[12],e.y=s[13],e.z=s[14],yi.copy(this);const l=1/r,h=1/a,u=1/o;return yi.elements[0]*=l,yi.elements[1]*=l,yi.elements[2]*=l,yi.elements[4]*=h,yi.elements[5]*=h,yi.elements[6]*=h,yi.elements[8]*=u,yi.elements[9]*=u,yi.elements[10]*=u,t.setFromRotationMatrix(yi),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=Yi){const c=this.elements,l=2*r/(t-e),h=2*r/(n-s),u=(t+e)/(t-e),d=(n+s)/(n-s);let f,p;if(o===Yi)f=-(a+r)/(a-r),p=-2*a*r/(a-r);else if(o===zc)f=-a/(a-r),p=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=u,c[12]=0,c[1]=0,c[5]=h,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=p,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,s,r,a,o=Yi){const c=this.elements,l=1/(t-e),h=1/(n-s),u=1/(a-r),d=(t+e)*l,f=(n+s)*h;let p,m;if(o===Yi)p=(a+r)*u,m=-2*u;else if(o===zc)p=r*u,m=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-d,c[1]=0,c[5]=2*h,c[9]=0,c[13]=-f,c[2]=0,c[6]=0,c[10]=m,c[14]=-p,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const aa=new G,yi=new Re,M_=new G(0,0,0),B_=new G(1,1,1),Fs=new G,Yc=new G,$n=new G,bA=new Re,EA=new Yt;class dn{constructor(e=0,t=0,n=0,s=dn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],a=s[4],o=s[8],c=s[1],l=s[5],h=s[9],u=s[2],d=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(at(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-at(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(at(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-at(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(at(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-at(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return bA.makeRotationFromQuaternion(e),this.setFromRotationMatrix(bA,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return EA.setFromEuler(this),this.setFromQuaternion(EA,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dn.DEFAULT_ORDER="XYZ";class yA{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let T_=0;const _A=new G,oa=new Yt,es=new Re,Jc=new G,yo=new G,R_=new G,F_=new Yt,wA=new G(1,0,0),vA=new G(0,1,0),CA=new G(0,0,1),IA={type:"added"},N_={type:"removed"},ca={type:"childadded",child:null},Qu={type:"childremoved",child:null};class Tt extends Ms{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:T_++}),this.uuid=xi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Tt.DEFAULT_UP.clone();const e=new G,t=new dn,n=new Yt,s=new G(1,1,1);function r(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Re},normalMatrix:{value:new ot}}),this.matrix=new Re,this.matrixWorld=new Re,this.matrixAutoUpdate=Tt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new yA,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return oa.setFromAxisAngle(e,t),this.quaternion.multiply(oa),this}rotateOnWorldAxis(e,t){return oa.setFromAxisAngle(e,t),this.quaternion.premultiply(oa),this}rotateX(e){return this.rotateOnAxis(wA,e)}rotateY(e){return this.rotateOnAxis(vA,e)}rotateZ(e){return this.rotateOnAxis(CA,e)}translateOnAxis(e,t){return _A.copy(e).applyQuaternion(this.quaternion),this.position.add(_A.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(wA,e)}translateY(e){return this.translateOnAxis(vA,e)}translateZ(e){return this.translateOnAxis(CA,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(es.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Jc.copy(e):Jc.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),yo.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?es.lookAt(yo,Jc,this.up):es.lookAt(Jc,yo,this.up),this.quaternion.setFromRotationMatrix(es),s&&(es.extractRotation(s.matrixWorld),oa.setFromRotationMatrix(es),this.quaternion.premultiply(oa.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(IA),ca.child=e,this.dispatchEvent(ca),ca.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(N_),Qu.child=e,this.dispatchEvent(Qu),Qu.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),es.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),es.multiply(e.parent.matrixWorld)),e.applyMatrix4(es),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(IA),ca.child=e,this.dispatchEvent(ca),ca.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(yo,e,R_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(yo,F_,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?{min:o.boundingBox.min.toArray(),max:o.boundingBox.max.toArray()}:void 0,boundingSphere:o.boundingSphere?{radius:o.boundingSphere.radius,center:o.boundingSphere.center.toArray()}:void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere={center:this.boundingSphere.center.toArray(),radius:this.boundingSphere.radius}),this.boundingBox!==null&&(s.boundingBox={min:this.boundingBox.min.toArray(),max:this.boundingBox.max.toArray()}));function r(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let c=0,l=this.material.length;c<l;c++)o.push(r(e.materials,this.material[c]));s.material=o}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let o=0;o<this.children.length;o++)s.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let o=0;o<this.animations.length;o++){const c=this.animations[o];s.animations.push(r(e.animations,c))}}if(t){const o=a(e.geometries),c=a(e.materials),l=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),f=a(e.animations),p=a(e.nodes);o.length>0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),f.length>0&&(n.animations=f),p.length>0&&(n.nodes=p)}return n.object=s,n;function a(o){const c=[];for(const l in o){const h=o[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Tt.DEFAULT_UP=new G(0,1,0),Tt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const _i=new G,ts=new G,Gu=new G,ns=new G,la=new G,ha=new G,SA=new G,Hu=new G,zu=new G,Vu=new G,Wu=new gt,qu=new gt,Ku=new gt;class wi{constructor(e=new G,t=new G,n=new G){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),_i.subVectors(e,t),s.cross(_i);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){_i.subVectors(s,t),ts.subVectors(n,t),Gu.subVectors(e,t);const a=_i.dot(_i),o=_i.dot(ts),c=_i.dot(Gu),l=ts.dot(ts),h=ts.dot(Gu),u=a*l-o*o;if(u===0)return r.set(0,0,0),null;const d=1/u,f=(l*c-o*h)*d,p=(a*h-o*c)*d;return r.set(1-f-p,p,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,ns)===null?!1:ns.x>=0&&ns.y>=0&&ns.x+ns.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,ns)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,ns.x),c.addScaledVector(a,ns.y),c.addScaledVector(o,ns.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return Wu.setScalar(0),qu.setScalar(0),Ku.setScalar(0),Wu.fromBufferAttribute(e,t),qu.fromBufferAttribute(e,n),Ku.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(Wu,r.x),a.addScaledVector(qu,r.y),a.addScaledVector(Ku,r.z),a}static isFrontFacing(e,t,n,s){return _i.subVectors(n,t),ts.subVectors(e,t),_i.cross(ts).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return _i.subVectors(this.c,this.b),ts.subVectors(this.a,this.b),_i.cross(ts).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return wi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return wi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return wi.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return wi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return wi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let a,o;la.subVectors(s,n),ha.subVectors(r,n),Hu.subVectors(e,n);const c=la.dot(Hu),l=ha.dot(Hu);if(c<=0&&l<=0)return t.copy(n);zu.subVectors(e,s);const h=la.dot(zu),u=ha.dot(zu);if(h>=0&&u<=h)return t.copy(s);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(la,a);Vu.subVectors(e,r);const f=la.dot(Vu),p=ha.dot(Vu);if(p>=0&&f<=p)return t.copy(r);const m=f*l-c*p;if(m<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(n).addScaledVector(ha,o);const g=h*p-f*u;if(g<=0&&u-h>=0&&f-p>=0)return SA.subVectors(r,s),o=(u-h)/(u-h+(f-p)),t.copy(s).addScaledVector(SA,o);const A=1/(g+m+d);return a=m*A,o=d*A,t.copy(n).addScaledVector(la,a).addScaledVector(ha,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const MA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ns={h:0,s:0,l:0},Zc={h:0,s:0,l:0};function ju(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}let Fe=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=yt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,tt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,s=tt.workingColorSpace){return this.r=e,this.g=t,this.b=n,tt.toWorkingColorSpace(this,s),this}setHSL(e,t,n,s=tt.workingColorSpace){if(e=Tu(e,1),t=at(t,0,1),n=at(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,a=2*n-r;this.r=ju(a,r,e+1/3),this.g=ju(a,r,e),this.b=ju(a,r,e-1/3)}return tt.toWorkingColorSpace(this,s),this}setStyle(e,t=yt){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=s[1],o=s[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=yt){const n=MA[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ji(e.r),this.g=Ji(e.g),this.b=Ji(e.b),this}copyLinearToSRGB(e){return this.r=ta(e.r),this.g=ta(e.g),this.b=ta(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=yt){return tt.fromWorkingColorSpace(Nn.copy(this),e),Math.round(at(Nn.r*255,0,255))*65536+Math.round(at(Nn.g*255,0,255))*256+Math.round(at(Nn.b*255,0,255))}getHexString(e=yt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=tt.workingColorSpace){tt.fromWorkingColorSpace(Nn.copy(this),t);const n=Nn.r,s=Nn.g,r=Nn.b,a=Math.max(n,s,r),o=Math.min(n,s,r);let c,l;const h=(o+a)/2;if(o===a)c=0,l=0;else{const u=a-o;switch(l=h<=.5?u/(a+o):u/(2-a-o),a){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=h,e}getRGB(e,t=tt.workingColorSpace){return tt.fromWorkingColorSpace(Nn.copy(this),t),e.r=Nn.r,e.g=Nn.g,e.b=Nn.b,e}getStyle(e=yt){tt.fromWorkingColorSpace(Nn.copy(this),e);const t=Nn.r,n=Nn.g,s=Nn.b;return e!==yt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Ns),this.setHSL(Ns.h+e,Ns.s+t,Ns.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ns),e.getHSL(Zc);const n=go(Ns.h,Zc.h,t),s=go(Ns.s,Zc.s,t),r=go(Ns.l,Zc.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const Nn=new Fe;Fe.NAMES=MA;let D_=0;class ai extends Ms{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:D_++}),this.uuid=xi(),this.name="",this.type="Material",this.blending=jr,this.side=ji,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Wh,this.blendDst=qh,this.blendEquation=ir,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Fe(0,0,0),this.blendAlpha=0,this.depthFunc=Xr,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=cA,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=$r,this.stencilZFail=$r,this.stencilZPass=$r,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==jr&&(n.blending=this.blending),this.side!==ji&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Wh&&(n.blendSrc=this.blendSrc),this.blendDst!==qh&&(n.blendDst=this.blendDst),this.blendEquation!==ir&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Xr&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==cA&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==$r&&(n.stencilFail=this.stencilFail),this.stencilZFail!==$r&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==$r&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const a=[];for(const o in r){const c=r[o];delete c.metadata,a.push(c)}return a}if(t){const r=s(e.textures),a=s(e.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ds extends ai{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Fe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const is=L_();function L_(){const i=new ArrayBuffer(4),e=new Float32Array(i),t=new Uint32Array(i),n=new Uint32Array(512),s=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(n[c]=0,n[c|256]=32768,s[c]=24,s[c|256]=24):l<-14?(n[c]=1024>>-l-14,n[c|256]=1024>>-l-14|32768,s[c]=-l-1,s[c|256]=-l-1):l<=15?(n[c]=l+15<<10,n[c|256]=l+15<<10|32768,s[c]=13,s[c|256]=13):l<128?(n[c]=31744,n[c|256]=64512,s[c]=24,s[c|256]=24):(n[c]=31744,n[c|256]=64512,s[c]=13,s[c|256]=13)}const r=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,r[c]=l|h}for(let c=1024;c<2048;++c)r[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)a[c]=c<<23;a[31]=1199570944,a[32]=2147483648;for(let c=33;c<63;++c)a[c]=2147483648+(c-32<<23);a[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(o[c]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:s,mantissaTable:r,exponentTable:a,offsetTable:o}}function P_(i){Math.abs(i)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),i=at(i,-65504,65504),is.floatView[0]=i;const e=is.uint32View[0],t=e>>23&511;return is.baseTable[t]+((e&8388607)>>is.shiftTable[t])}function k_(i){const e=i>>10;return is.uint32View[0]=is.mantissaTable[is.offsetTable[e]+(i&1023)]+is.exponentTable[e],is.floatView[0]}class BA{static toHalfFloat(e){return P_(e)}static fromHalfFloat(e){return k_(e)}}const sn=new G,$c=new Je;let U_=0;class Sn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:U_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Bu,this.updateRanges=[],this.gpuType=ln,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)$c.fromBufferAttribute(this,t),$c.applyMatrix3(e),this.setXY(t,$c.x,$c.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyMatrix3(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyMatrix4(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyNormalMatrix(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.transformDirection(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=bi(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Bt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=bi(t,this.array)),t}setX(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=bi(t,this.array)),t}setY(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=bi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=bi(t,this.array)),t}setW(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array),r=Bt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Bu&&(e.usage=this.usage),e}}class Xu extends Sn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class TA extends Sn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class Jt extends Sn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let O_=0;const oi=new Re,Yu=new Tt,ua=new G,ei=new ki,_o=new ki,bn=new G;class Mn extends Ms{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:O_++}),this.uuid=xi(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(dA(e)?TA:Xu)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new ot().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return oi.makeRotationFromQuaternion(e),this.applyMatrix4(oi),this}rotateX(e){return oi.makeRotationX(e),this.applyMatrix4(oi),this}rotateY(e){return oi.makeRotationY(e),this.applyMatrix4(oi),this}rotateZ(e){return oi.makeRotationZ(e),this.applyMatrix4(oi),this}translate(e,t,n){return oi.makeTranslation(e,t,n),this.applyMatrix4(oi),this}scale(e,t,n){return oi.makeScale(e,t,n),this.applyMatrix4(oi),this}lookAt(e){return Yu.lookAt(e),Yu.updateMatrix(),this.applyMatrix4(Yu.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ua).negate(),this.translate(ua.x,ua.y,ua.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const a=e[s];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Jt(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ki);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new G(-1/0,-1/0,-1/0),new G(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];ei.setFromBufferAttribute(r),this.morphTargetsRelative?(bn.addVectors(this.boundingBox.min,ei.min),this.boundingBox.expandByPoint(bn),bn.addVectors(this.boundingBox.max,ei.max),this.boundingBox.expandByPoint(bn)):(this.boundingBox.expandByPoint(ei.min),this.boundingBox.expandByPoint(ei.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Ui);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new G,1/0);return}if(e){const n=this.boundingSphere.center;if(ei.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];_o.setFromBufferAttribute(o),this.morphTargetsRelative?(bn.addVectors(ei.min,_o.min),ei.expandByPoint(bn),bn.addVectors(ei.max,_o.max),ei.expandByPoint(bn)):(ei.expandByPoint(_o.min),ei.expandByPoint(_o.max))}ei.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)bn.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(bn));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],c=this.morphTargetsRelative;for(let l=0,h=o.count;l<h;l++)bn.fromBufferAttribute(o,l),c&&(ua.fromBufferAttribute(e,l),bn.add(ua)),s=Math.max(s,n.distanceToSquared(bn))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Sn(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let T=0;T<n.count;T++)o[T]=new G,c[T]=new G;const l=new G,h=new G,u=new G,d=new Je,f=new Je,p=new Je,m=new G,g=new G;function A(T,C,v){l.fromBufferAttribute(n,T),h.fromBufferAttribute(n,C),u.fromBufferAttribute(n,v),d.fromBufferAttribute(r,T),f.fromBufferAttribute(r,C),p.fromBufferAttribute(r,v),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const F=1/(f.x*p.y-p.x*f.y);isFinite(F)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(F),g.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(F),o[T].add(m),o[C].add(m),o[v].add(m),c[T].add(g),c[C].add(g),c[v].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let T=0,C=_.length;T<C;++T){const v=_[T],F=v.start,K=v.count;for(let q=F,$=F+K;q<$;q+=3)A(e.getX(q+0),e.getX(q+1),e.getX(q+2))}const x=new G,E=new G,S=new G,w=new G;function I(T){S.fromBufferAttribute(s,T),w.copy(S);const C=o[T];x.copy(C),x.sub(S.multiplyScalar(S.dot(C))).normalize(),E.crossVectors(w,C);const F=E.dot(c[T])<0?-1:1;a.setXYZW(T,x.x,x.y,x.z,F)}for(let T=0,C=_.length;T<C;++T){const v=_[T],F=v.start,K=v.count;for(let q=F,$=F+K;q<$;q+=3)I(e.getX(q+0)),I(e.getX(q+1)),I(e.getX(q+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Sn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);const s=new G,r=new G,a=new G,o=new G,c=new G,l=new G,h=new G,u=new G;if(e)for(let d=0,f=e.count;d<f;d+=3){const p=e.getX(d+0),m=e.getX(d+1),g=e.getX(d+2);s.fromBufferAttribute(t,p),r.fromBufferAttribute(t,m),a.fromBufferAttribute(t,g),h.subVectors(a,r),u.subVectors(s,r),h.cross(u),o.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),l.fromBufferAttribute(n,g),o.add(h),c.add(h),l.add(h),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(m,c.x,c.y,c.z),n.setXYZ(g,l.x,l.y,l.z)}else for(let d=0,f=t.count;d<f;d+=3)s.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,r),u.subVectors(s,r),h.cross(u),n.setXYZ(d+0,h.x,h.y,h.z),n.setXYZ(d+1,h.x,h.y,h.z),n.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)bn.fromBufferAttribute(e,t),bn.normalize(),e.setXYZ(t,bn.x,bn.y,bn.z)}toNonIndexed(){function e(o,c){const l=o.array,h=o.itemSize,u=o.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let m=0,g=c.length;m<g;m++){o.isInterleavedBufferAttribute?f=c[m]*o.data.stride+o.offset:f=c[m]*h;for(let A=0;A<h;A++)d[p++]=l[f++]}return new Sn(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Mn,n=this.index.array,s=this.attributes;for(const o in s){const c=s[o],l=e(c,n);t.setAttribute(o,l)}const r=this.morphAttributes;for(const o in r){const c=[],l=r[o];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=e(d,n);c.push(f)}t.morphAttributes[o]=c}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,c=a.length;o<c;o++){const l=a[o];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(e.data))}h.length>0&&(s[c]=h,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const h=s[l];this.setAttribute(l,h.clone(t))}const r=e.morphAttributes;for(const l in r){const h=[],u=r[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(t));this.morphAttributes[l]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let l=0,h=a.length;l<h;l++){const u=a[l];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const RA=new Re,hr=new Eo,el=new Ui,FA=new G,tl=new G,nl=new G,il=new G,Ju=new G,sl=new G,NA=new G,rl=new G;class Zt extends Tt{constructor(e=new Mn,t=new Ds){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const o=this.morphTargetInfluences;if(r&&o){sl.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const h=o[c],u=r[c];h!==0&&(Ju.fromBufferAttribute(u,e),a?sl.addScaledVector(Ju,h):sl.addScaledVector(Ju.sub(t),h))}t.add(sl)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),el.copy(n.boundingSphere),el.applyMatrix4(r),hr.copy(e.ray).recast(e.near),!(el.containsPoint(hr.origin)===!1&&(hr.intersectSphere(el,FA)===null||hr.origin.distanceToSquared(FA)>(e.far-e.near)**2))&&(RA.copy(r).invert(),hr.copy(e.ray).applyMatrix4(RA),!(n.boundingBox!==null&&hr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,hr)))}_computeIntersections(e,t,n){let s;const r=this.geometry,a=this.material,o=r.index,c=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,m=d.length;p<m;p++){const g=d[p],A=a[g.materialIndex],_=Math.max(g.start,f.start),x=Math.min(o.count,Math.min(g.start+g.count,f.start+f.count));for(let E=_,S=x;E<S;E+=3){const w=o.getX(E),I=o.getX(E+1),T=o.getX(E+2);s=al(this,A,e,n,l,h,u,w,I,T),s&&(s.faceIndex=Math.floor(E/3),s.face.materialIndex=g.materialIndex,t.push(s))}}else{const p=Math.max(0,f.start),m=Math.min(o.count,f.start+f.count);for(let g=p,A=m;g<A;g+=3){const _=o.getX(g),x=o.getX(g+1),E=o.getX(g+2);s=al(this,a,e,n,l,h,u,_,x,E),s&&(s.faceIndex=Math.floor(g/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(a))for(let p=0,m=d.length;p<m;p++){const g=d[p],A=a[g.materialIndex],_=Math.max(g.start,f.start),x=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let E=_,S=x;E<S;E+=3){const w=E,I=E+1,T=E+2;s=al(this,A,e,n,l,h,u,w,I,T),s&&(s.faceIndex=Math.floor(E/3),s.face.materialIndex=g.materialIndex,t.push(s))}}else{const p=Math.max(0,f.start),m=Math.min(c.count,f.start+f.count);for(let g=p,A=m;g<A;g+=3){const _=g,x=g+1,E=g+2;s=al(this,a,e,n,l,h,u,_,x,E),s&&(s.faceIndex=Math.floor(g/3),t.push(s))}}}}function Q_(i,e,t,n,s,r,a,o){let c;if(e.side===Ln?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===ji,o),c===null)return null;rl.copy(o),rl.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(rl);return l<t.near||l>t.far?null:{distance:l,point:rl.clone(),object:i}}function al(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,tl),i.getVertexPosition(c,nl),i.getVertexPosition(l,il);const h=Q_(i,e,t,n,tl,nl,il,NA);if(h){const u=new G;wi.getBarycoord(NA,tl,nl,il,u),s&&(h.uv=wi.getInterpolatedAttribute(s,o,c,l,u,new Je)),r&&(h.uv1=wi.getInterpolatedAttribute(r,o,c,l,u,new Je)),a&&(h.normal=wi.getInterpolatedAttribute(a,o,c,l,u,new G),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const d={a:o,b:c,c:l,normal:new G,materialIndex:0};wi.getNormal(tl,nl,il,d.normal),h.face=d,h.barycoord=u}return h}class da extends Mn{constructor(e=1,t=1,n=1,s=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:a};const o=this;s=Math.floor(s),r=Math.floor(r),a=Math.floor(a);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,n,t,e,a,r,0),p("z","y","x",1,-1,n,t,-e,a,r,1),p("x","z","y",1,1,e,n,t,s,a,2),p("x","z","y",1,-1,e,n,-t,s,a,3),p("x","y","z",1,-1,e,t,n,s,r,4),p("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new Jt(l,3)),this.setAttribute("normal",new Jt(h,3)),this.setAttribute("uv",new Jt(u,2));function p(m,g,A,_,x,E,S,w,I,T,C){const v=E/I,F=S/T,K=E/2,q=S/2,$=w/2,D=I+1,O=T+1;let Y=0,Q=0;const J=new G;for(let ee=0;ee<O;ee++){const ae=ee*F-q;for(let _e=0;_e<D;_e++){const Me=_e*v-K;J[m]=Me*_,J[g]=ae*x,J[A]=$,l.push(J.x,J.y,J.z),J[m]=0,J[g]=0,J[A]=w>0?1:-1,h.push(J.x,J.y,J.z),u.push(_e/I),u.push(1-ee/T),Y+=1}}for(let ee=0;ee<T;ee++)for(let ae=0;ae<I;ae++){const _e=d+ae+D*ee,Me=d+ae+D*(ee+1),se=d+(ae+1)+D*(ee+1),me=d+(ae+1)+D*ee;c.push(_e,Me,me),c.push(Me,se,me),Q+=6}o.addGroup(f,Q,C),f+=Q,d+=Y}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new da(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function fa(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function Un(i){const e={};for(let t=0;t<i.length;t++){const n=fa(i[t]);for(const s in n)e[s]=n[s]}return e}function G_(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function DA(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:tt.workingColorSpace}const H_={clone:fa,merge:Un};var z_=`void main() {
+(function(on,nr){typeof exports=="object"&&typeof module<"u"?nr(exports):typeof define=="function"&&define.amd?define(["exports"],nr):(on=typeof globalThis<"u"?globalThis:on||self,nr(on.Agent3D={}))})(this,(function(on){"use strict";var nr=typeof document<"u"?document.currentScript:null;const Ic="176",qr={ROTATE:0,DOLLY:1,PAN:2},Kr={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},fy=0,Vp=1,py=2,Wp=1,Ay=2,Ki=3,ji=0,Ln=1,Pi=2,Cs=0,jr=1,qp=2,Kp=3,jp=4,gy=5,ir=100,my=101,xy=102,by=103,Ey=104,yy=200,_y=201,wy=202,vy=203,Wh=204,qh=205,Cy=206,Iy=207,Sy=208,My=209,By=210,Ty=211,Ry=212,Fy=213,Ny=214,Kh=0,jh=1,Xh=2,Xr=3,Yh=4,Jh=5,Zh=6,$h=7,Sc=0,Dy=1,Ly=2,Is=0,eu=1,Py=2,ky=3,Xp=4,Uy=5,Oy=6,Qy=7,Yp="attached",Gy="detached",Jp=300,sr=301,Yr=302,Mc=303,tu=304,Bc=306,Ss=1e3,Zn=1001,Tc=1002,Pn=1003,Zp=1004,no=1005,qt=1006,Rc=1007,ri=1008,cn=1009,$p=1010,eA=1011,io=1012,nu=1013,rr=1014,ln=1015,kn=1016,iu=1017,su=1018,so=1020,tA=35902,nA=1021,iA=1022,hn=1023,ro=1026,ao=1027,Xi=1028,ru=1029,ar=1030,au=1031,ou=1033,Fc=33776,oo=33777,Nc=33778,co=33779,Dc=35840,cu=35841,Lc=35842,lu=35843,Pc=36196,kc=37492,Uc=37496,lo=37808,hu=37809,uu=37810,du=37811,ho=37812,fu=37813,pu=37814,Au=37815,gu=37816,mu=37817,xu=37818,bu=37819,Eu=37820,yu=37821,uo=36492,_u=36494,Oc=36495,sA=36283,wu=36284,vu=36285,Cu=36286,rA=2200,aA=2201,Hy=2202,fo=2300,po=2301,Iu=2302,Jr=2400,Zr=2401,Qc=2402,Su=2500,zy=2501,Vy=0,oA=1,Mu=2,Wy=3200,qy=3201,Gc=0,Ky=1,mi="",yt="srgb",un="srgb-linear",Hc="linear",Rt="srgb",$r=7680,cA=519,jy=512,Xy=513,Yy=514,lA=515,Jy=516,Zy=517,$y=518,e_=519,Bu=35044,hA="300 es",Yi=2e3,zc=2001;class Ms{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,a=s.length;r<a;r++)s[r].call(this,e);e.target=null}}}const Fn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let uA=1234567;const Ao=Math.PI/180,ea=180/Math.PI;function xi(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Fn[i&255]+Fn[i>>8&255]+Fn[i>>16&255]+Fn[i>>24&255]+"-"+Fn[e&255]+Fn[e>>8&255]+"-"+Fn[e>>16&15|64]+Fn[e>>24&255]+"-"+Fn[t&63|128]+Fn[t>>8&255]+"-"+Fn[t>>16&255]+Fn[t>>24&255]+Fn[n&255]+Fn[n>>8&255]+Fn[n>>16&255]+Fn[n>>24&255]).toLowerCase()}function at(i,e,t){return Math.max(e,Math.min(t,i))}function Tu(i,e){return(i%e+e)%e}function t_(i,e,t,n,s){return n+(i-e)*(s-n)/(t-e)}function n_(i,e,t){return i!==e?(t-i)/(e-i):0}function go(i,e,t){return(1-t)*i+t*e}function i_(i,e,t,n){return go(i,e,1-Math.exp(-t*n))}function s_(i,e=1){return e-Math.abs(Tu(i,e*2)-e)}function r_(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*(3-2*i))}function a_(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*i*(i*(i*6-15)+10))}function o_(i,e){return i+Math.floor(Math.random()*(e-i+1))}function c_(i,e){return i+Math.random()*(e-i)}function l_(i){return i*(.5-Math.random())}function h_(i){i!==void 0&&(uA=i);let e=uA+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function u_(i){return i*Ao}function d_(i){return i*ea}function f_(i){return(i&i-1)===0&&i!==0}function p_(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function A_(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function g_(i,e,t,n,s){const r=Math.cos,a=Math.sin,o=r(t/2),c=a(t/2),l=r((e+n)/2),h=a((e+n)/2),u=r((e-n)/2),d=a((e-n)/2),f=r((n-e)/2),p=a((n-e)/2);switch(s){case"XYX":i.set(o*h,c*u,c*d,o*l);break;case"YZY":i.set(c*d,o*h,c*u,o*l);break;case"ZXZ":i.set(c*u,c*d,o*h,o*l);break;case"XZX":i.set(o*h,c*p,c*f,o*l);break;case"YXY":i.set(c*f,o*h,c*p,o*l);break;case"ZYZ":i.set(c*p,c*f,o*h,o*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function bi(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function Bt(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}const In={DEG2RAD:Ao,RAD2DEG:ea,generateUUID:xi,clamp:at,euclideanModulo:Tu,mapLinear:t_,inverseLerp:n_,lerp:go,damp:i_,pingpong:s_,smoothstep:r_,smootherstep:a_,randInt:o_,randFloat:c_,randFloatSpread:l_,seededRandom:h_,degToRad:u_,radToDeg:d_,isPowerOfTwo:f_,ceilPowerOfTwo:p_,floorPowerOfTwo:A_,setQuaternionFromProperEuler:g_,normalize:Bt,denormalize:bi};class Je{constructor(e=0,t=0){Je.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(at(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*s+e.x,this.y=r*s+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ot{constructor(e,t,n,s,r,a,o,c,l){ot.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l)}set(e,t,n,s,r,a,o,c,l){const h=this.elements;return h[0]=e,h[1]=s,h[2]=o,h[3]=t,h[4]=r,h[5]=c,h[6]=n,h[7]=a,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],h=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=s[0],g=s[3],A=s[6],_=s[1],x=s[4],E=s[7],S=s[2],w=s[5],I=s[8];return r[0]=a*m+o*_+c*S,r[3]=a*g+o*x+c*w,r[6]=a*A+o*E+c*I,r[1]=l*m+h*_+u*S,r[4]=l*g+h*x+u*w,r[7]=l*A+h*E+u*I,r[2]=d*m+f*_+p*S,r[5]=d*g+f*x+p*w,r[8]=d*A+f*E+p*I,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8];return t*a*h-t*o*l-n*r*h+n*o*c+s*r*l-s*a*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=h*a-o*l,d=o*c-h*r,f=l*r-a*c,p=t*u+n*d+s*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(s*l-h*n)*m,e[2]=(o*n-s*a)*m,e[3]=d*m,e[4]=(h*t-s*c)*m,e[5]=(s*r-o*t)*m,e[6]=f*m,e[7]=(n*c-l*t)*m,e[8]=(a*t-n*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,a,o){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-s*l,s*c,-s*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Ru.makeScale(e,t)),this}rotate(e){return this.premultiply(Ru.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ru.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Ru=new ot;function dA(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function mo(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function m_(){const i=mo("canvas");return i.style.display="block",i}const fA={};function Vc(i){i in fA||(fA[i]=!0,console.warn(i))}function x_(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}function b_(i){const e=i.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function E_(i){const e=i.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const pA=new ot().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),AA=new ot().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function y_(){const i={enabled:!0,workingColorSpace:un,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===Rt&&(s.r=Ji(s.r),s.g=Ji(s.g),s.b=Ji(s.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Rt&&(s.r=ta(s.r),s.g=ta(s.g),s.b=ta(s.b))),s},fromWorkingColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},toWorkingColorSpace:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===mi?Hc:this.spaces[s].transfer},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,a){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[un]:{primaries:e,whitePoint:n,transfer:Hc,toXYZ:pA,fromXYZ:AA,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:yt},outputColorSpaceConfig:{drawingBufferColorSpace:yt}},[yt]:{primaries:e,whitePoint:n,transfer:Rt,toXYZ:pA,fromXYZ:AA,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:yt}}}),i}const tt=y_();function Ji(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ta(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let na;class __{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{na===void 0&&(na=mo("canvas")),na.width=e.width,na.height=e.height;const s=na.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=na}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=mo("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let a=0;a<r.length;a++)r[a]=Ji(r[a]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Ji(t[n]/255)*255):t[n]=Ji(t[n]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let w_=0;class Fu{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:w_++}),this.uuid=xi(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let a=0,o=s.length;a<o;a++)s[a].isDataTexture?r.push(Nu(s[a].image)):r.push(Nu(s[a]))}else r=Nu(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function Nu(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?__.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let v_=0;class nn extends Ms{constructor(e=nn.DEFAULT_IMAGE,t=nn.DEFAULT_MAPPING,n=Zn,s=Zn,r=qt,a=ri,o=hn,c=cn,l=nn.DEFAULT_ANISOTROPY,h=mi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:v_++}),this.uuid=xi(),this.name="",this.source=new Fu(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=a,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=c,this.offset=new Je(0,0),this.repeat=new Je(1,1),this.center=new Je(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ot,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isTextureArray=!1,this.pmremVersion=0}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isTextureArray=e.isTextureArray,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Jp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Ss:e.x=e.x-Math.floor(e.x);break;case Zn:e.x=e.x<0?0:1;break;case Tc:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Ss:e.y=e.y-Math.floor(e.y);break;case Zn:e.y=e.y<0?0:1;break;case Tc:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}nn.DEFAULT_IMAGE=null,nn.DEFAULT_MAPPING=Jp,nn.DEFAULT_ANISOTROPY=1;class gt{constructor(e=0,t=0,n=0,s=1){gt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*s+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*s+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*s+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*s+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],m=c[2],g=c[6],A=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-m)<.01&&Math.abs(p-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+m)<.1&&Math.abs(p+g)<.1&&Math.abs(l+f+A-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const x=(l+1)/2,E=(f+1)/2,S=(A+1)/2,w=(h+d)/4,I=(u+m)/4,T=(p+g)/4;return x>E&&x>S?x<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(x),s=w/n,r=I/n):E>S?E<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(E),n=w/s,r=T/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=I/r,s=T/r),this.set(n,s,r,t),this}let _=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(g-p)/_,this.y=(u-m)/_,this.z=(d-h)/_,this.w=Math.acos((l+f+A-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this.z=at(this.z,e.z,t.z),this.w=at(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this.z=at(this.z,e,t),this.w=at(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class C_ extends Ms{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth?n.depth:1,this.scissor=new gt(0,0,e,t),this.scissorTest=!1,this.viewport=new gt(0,0,e,t);const s={width:e,height:t,depth:this.depth};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:qt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,multiview:!1},n);const r=new nn(s,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);r.flipY=!1,r.generateMipmaps=n.generateMipmaps,r.internalFormat=n.internalFormat,this.textures=[];const a=n.count;for(let o=0;o<a;o++)this.textures[o]=r.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Fu(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class or extends C_{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class gA extends nn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Pn,this.minFilter=Pn,this.wrapR=Zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class mA extends nn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Pn,this.minFilter=Pn,this.wrapR=Zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Yt{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,a,o){let c=n[s+0],l=n[s+1],h=n[s+2],u=n[s+3];const d=r[a+0],f=r[a+1],p=r[a+2],m=r[a+3];if(o===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}if(u!==m||c!==d||l!==f||h!==p){let g=1-o;const A=c*d+l*f+h*p+u*m,_=A>=0?1:-1,x=1-A*A;if(x>Number.EPSILON){const S=Math.sqrt(x),w=Math.atan2(S,A*_);g=Math.sin(g*w)/S,o=Math.sin(o*w)/S}const E=o*_;if(c=c*g+d*E,l=l*g+f*E,h=h*g+p*E,u=u*g+m*E,g===1-o){const S=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=S,l*=S,h*=S,u*=S}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,a){const o=n[s],c=n[s+1],l=n[s+2],h=n[s+3],u=r[a],d=r[a+1],f=r[a+2],p=r[a+3];return e[t]=o*p+h*u+c*f-l*d,e[t+1]=c*p+h*d+l*u-o*f,e[t+2]=l*p+h*f+o*d-c*u,e[t+3]=h*p-o*u-c*d-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),h=o(s/2),u=o(r/2),d=c(n/2),f=c(s/2),p=c(r/2);switch(a){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],a=t[1],o=t[5],c=t[9],l=t[2],h=t[6],u=t[10],d=n+o+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(r-l)*f,this._z=(a-s)*f}else if(n>o&&n>u){const f=2*Math.sqrt(1+n-o-u);this._w=(h-c)/f,this._x=.25*f,this._y=(s+a)/f,this._z=(r+l)/f}else if(o>u){const f=2*Math.sqrt(1+o-n-u);this._w=(r-l)/f,this._x=(s+a)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-n-o);this._w=(a-s)/f,this._x=(r+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<Number.EPSILON?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(at(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,a=e._w,o=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+a*o+s*l-r*c,this._y=s*h+a*c+r*o-n*l,this._z=r*h+a*l+n*c-s*o,this._w=a*h-n*o-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const n=this._x,s=this._y,r=this._z,a=this._w;let o=a*e._w+n*e._x+s*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=s,this._z=r,this;const c=1-o*o;if(c<=Number.EPSILON){const f=1-t;return this._w=f*a+t*this._w,this._x=f*n+t*this._x,this._y=f*s+t*this._y,this._z=f*r+t*this._z,this.normalize(),this}const l=Math.sqrt(c),h=Math.atan2(l,o),u=Math.sin((1-t)*h)/l,d=Math.sin(t*h)/l;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=s*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class G{constructor(e=0,t=0,n=0){G.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(xA.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(xA.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*s-o*n),h=2*(o*t-r*s),u=2*(r*n-a*t);return this.x=t+c*l+a*u-o*h,this.y=n+c*h+o*l-r*u,this.z=s+c*u+r*h-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=at(this.x,e.x,t.x),this.y=at(this.y,e.y,t.y),this.z=at(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=at(this.x,e,t),this.y=at(this.y,e,t),this.z=at(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(at(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,a=t.x,o=t.y,c=t.z;return this.x=s*c-r*o,this.y=r*a-n*c,this.z=n*o-s*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Du.copy(this).projectOnVector(e),this.sub(Du)}reflect(e){return this.sub(Du.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(at(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Du=new G,xA=new Yt;class ki{constructor(e=new G(1/0,1/0,1/0),t=new G(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Ei.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ei.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Ei.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,Ei):Ei.fromBufferAttribute(r,a),Ei.applyMatrix4(e.matrixWorld),this.expandByPoint(Ei);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Wc.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Wc.copy(n.boundingBox)),Wc.applyMatrix4(e.matrixWorld),this.union(Wc)}const s=e.children;for(let r=0,a=s.length;r<a;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ei),Ei.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(xo),qc.subVectors(this.max,xo),ia.subVectors(e.a,xo),sa.subVectors(e.b,xo),ra.subVectors(e.c,xo),Bs.subVectors(sa,ia),Ts.subVectors(ra,sa),cr.subVectors(ia,ra);let t=[0,-Bs.z,Bs.y,0,-Ts.z,Ts.y,0,-cr.z,cr.y,Bs.z,0,-Bs.x,Ts.z,0,-Ts.x,cr.z,0,-cr.x,-Bs.y,Bs.x,0,-Ts.y,Ts.x,0,-cr.y,cr.x,0];return!Lu(t,ia,sa,ra,qc)||(t=[1,0,0,0,1,0,0,0,1],!Lu(t,ia,sa,ra,qc))?!1:(Kc.crossVectors(Bs,Ts),t=[Kc.x,Kc.y,Kc.z],Lu(t,ia,sa,ra,qc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ei).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ei).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Zi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Zi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Zi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Zi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Zi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Zi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Zi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Zi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Zi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Zi=[new G,new G,new G,new G,new G,new G,new G,new G],Ei=new G,Wc=new ki,ia=new G,sa=new G,ra=new G,Bs=new G,Ts=new G,cr=new G,xo=new G,qc=new G,Kc=new G,lr=new G;function Lu(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){lr.fromArray(i,r);const o=s.x*Math.abs(lr.x)+s.y*Math.abs(lr.y)+s.z*Math.abs(lr.z),c=e.dot(lr),l=t.dot(lr),h=n.dot(lr);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>o)return!1}return!0}const I_=new ki,bo=new G,Pu=new G;class Ui{constructor(e=new G,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):I_.setFromPoints(e).getCenter(n);let s=0;for(let r=0,a=e.length;r<a;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;bo.subVectors(e,this.center);const t=bo.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(bo,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Pu.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(bo.copy(e.center).add(Pu)),this.expandByPoint(bo.copy(e.center).sub(Pu))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const $i=new G,ku=new G,jc=new G,Rs=new G,Uu=new G,Xc=new G,Ou=new G;class Eo{constructor(e=new G,t=new G(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,$i)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=$i.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):($i.copy(this.origin).addScaledVector(this.direction,t),$i.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){ku.copy(e).add(t).multiplyScalar(.5),jc.copy(t).sub(e).normalize(),Rs.copy(this.origin).sub(ku);const r=e.distanceTo(t)*.5,a=-this.direction.dot(jc),o=Rs.dot(this.direction),c=-Rs.dot(jc),l=Rs.lengthSq(),h=Math.abs(1-a*a);let u,d,f,p;if(h>0)if(u=a*c-o,d=a*o-c,p=r*h,u>=0)if(d>=-p)if(d<=p){const m=1/h;u*=m,d*=m,f=u*(u+a*d+2*o)+d*(a*u+d+2*c)+l}else d=r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;else d=-r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-a*r+o)),d=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-r,-c),r),f=d*(d+2*c)+l):(u=Math.max(0,-(a*r+o)),d=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+d*(d+2*c)+l);else d=a>0?-r:r,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(ku).addScaledVector(jc,d),f}intersectSphere(e,t){$i.subVectors(e.center,this.origin);const n=$i.dot(this.direction),s=$i.dot($i)-n*n,r=e.radius*e.radius;if(s>r)return null;const a=Math.sqrt(r-s),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,a,o,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(n=(e.min.x-d.x)*l,s=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,s=(e.min.x-d.x)*l),h>=0?(r=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),n>a||r>s||((r>n||isNaN(n))&&(n=r),(a<s||isNaN(s))&&(s=a),u>=0?(o=(e.min.z-d.z)*u,c=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,c=(e.min.z-d.z)*u),n>c||o>s)||((o>n||n!==n)&&(n=o),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,$i)!==null}intersectTriangle(e,t,n,s,r){Uu.subVectors(t,e),Xc.subVectors(n,e),Ou.crossVectors(Uu,Xc);let a=this.direction.dot(Ou),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Rs.subVectors(this.origin,e);const c=o*this.direction.dot(Xc.crossVectors(Rs,Xc));if(c<0)return null;const l=o*this.direction.dot(Uu.cross(Rs));if(l<0||c+l>a)return null;const h=-o*Rs.dot(Ou);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Re{constructor(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){Re.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g)}set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){const A=this.elements;return A[0]=e,A[4]=t,A[8]=n,A[12]=s,A[1]=r,A[5]=a,A[9]=o,A[13]=c,A[2]=l,A[6]=h,A[10]=u,A[14]=d,A[3]=f,A[7]=p,A[11]=m,A[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Re().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,s=1/aa.setFromMatrixColumn(e,0).length(),r=1/aa.setFromMatrixColumn(e,1).length(),a=1/aa.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(s),l=Math.sin(s),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const d=a*h,f=a*u,p=o*h,m=o*u;t[0]=c*h,t[4]=-c*u,t[8]=l,t[1]=f+p*l,t[5]=d-m*l,t[9]=-o*c,t[2]=m-d*l,t[6]=p+f*l,t[10]=a*c}else if(e.order==="YXZ"){const d=c*h,f=c*u,p=l*h,m=l*u;t[0]=d+m*o,t[4]=p*o-f,t[8]=a*l,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=f*o-p,t[6]=m+d*o,t[10]=a*c}else if(e.order==="ZXY"){const d=c*h,f=c*u,p=l*h,m=l*u;t[0]=d-m*o,t[4]=-a*u,t[8]=p+f*o,t[1]=f+p*o,t[5]=a*h,t[9]=m-d*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const d=a*h,f=a*u,p=o*h,m=o*u;t[0]=c*h,t[4]=p*l-f,t[8]=d*l+m,t[1]=c*u,t[5]=m*l+d,t[9]=f*l-p,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const d=a*c,f=a*l,p=o*c,m=o*l;t[0]=c*h,t[4]=m-d*u,t[8]=p*u+f,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-l*h,t[6]=f*u+p,t[10]=d-m*u}else if(e.order==="XZY"){const d=a*c,f=a*l,p=o*c,m=o*l;t[0]=c*h,t[4]=-u,t[8]=l*h,t[1]=d*u+m,t[5]=a*h,t[9]=f*u-p,t[2]=p*u-f,t[6]=o*h,t[10]=m*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(S_,e,M_)}lookAt(e,t,n){const s=this.elements;return $n.subVectors(e,t),$n.lengthSq()===0&&($n.z=1),$n.normalize(),Fs.crossVectors(n,$n),Fs.lengthSq()===0&&(Math.abs(n.z)===1?$n.x+=1e-4:$n.z+=1e-4,$n.normalize(),Fs.crossVectors(n,$n)),Fs.normalize(),Yc.crossVectors($n,Fs),s[0]=Fs.x,s[4]=Yc.x,s[8]=$n.x,s[1]=Fs.y,s[5]=Yc.y,s[9]=$n.y,s[2]=Fs.z,s[6]=Yc.z,s[10]=$n.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],h=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],g=n[10],A=n[14],_=n[3],x=n[7],E=n[11],S=n[15],w=s[0],I=s[4],T=s[8],C=s[12],v=s[1],F=s[5],K=s[9],q=s[13],$=s[2],D=s[6],O=s[10],Y=s[14],Q=s[3],J=s[7],ee=s[11],ae=s[15];return r[0]=a*w+o*v+c*$+l*Q,r[4]=a*I+o*F+c*D+l*J,r[8]=a*T+o*K+c*O+l*ee,r[12]=a*C+o*q+c*Y+l*ae,r[1]=h*w+u*v+d*$+f*Q,r[5]=h*I+u*F+d*D+f*J,r[9]=h*T+u*K+d*O+f*ee,r[13]=h*C+u*q+d*Y+f*ae,r[2]=p*w+m*v+g*$+A*Q,r[6]=p*I+m*F+g*D+A*J,r[10]=p*T+m*K+g*O+A*ee,r[14]=p*C+m*q+g*Y+A*ae,r[3]=_*w+x*v+E*$+S*Q,r[7]=_*I+x*F+E*D+S*J,r[11]=_*T+x*K+E*O+S*ee,r[15]=_*C+x*q+E*Y+S*ae,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],a=e[1],o=e[5],c=e[9],l=e[13],h=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],g=e[11],A=e[15];return p*(+r*c*u-s*l*u-r*o*d+n*l*d+s*o*f-n*c*f)+m*(+t*c*f-t*l*d+r*a*d-s*a*f+s*l*h-r*c*h)+g*(+t*l*u-t*o*f-r*a*u+n*a*f+r*o*h-n*l*h)+A*(-s*o*h-t*c*u+t*o*d+s*a*u-n*a*d+n*c*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],g=e[14],A=e[15],_=u*g*l-m*d*l+m*c*f-o*g*f-u*c*A+o*d*A,x=p*d*l-h*g*l-p*c*f+a*g*f+h*c*A-a*d*A,E=h*m*l-p*u*l+p*o*f-a*m*f-h*o*A+a*u*A,S=p*u*c-h*m*c-p*o*d+a*m*d+h*o*g-a*u*g,w=t*_+n*x+s*E+r*S;if(w===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const I=1/w;return e[0]=_*I,e[1]=(m*d*r-u*g*r-m*s*f+n*g*f+u*s*A-n*d*A)*I,e[2]=(o*g*r-m*c*r+m*s*l-n*g*l-o*s*A+n*c*A)*I,e[3]=(u*c*r-o*d*r-u*s*l+n*d*l+o*s*f-n*c*f)*I,e[4]=x*I,e[5]=(h*g*r-p*d*r+p*s*f-t*g*f-h*s*A+t*d*A)*I,e[6]=(p*c*r-a*g*r-p*s*l+t*g*l+a*s*A-t*c*A)*I,e[7]=(a*d*r-h*c*r+h*s*l-t*d*l-a*s*f+t*c*f)*I,e[8]=E*I,e[9]=(p*u*r-h*m*r-p*n*f+t*m*f+h*n*A-t*u*A)*I,e[10]=(a*m*r-p*o*r+p*n*l-t*m*l-a*n*A+t*o*A)*I,e[11]=(h*o*r-a*u*r-h*n*l+t*u*l+a*n*f-t*o*f)*I,e[12]=S*I,e[13]=(h*m*s-p*u*s+p*n*d-t*m*d-h*n*g+t*u*g)*I,e[14]=(p*o*s-a*m*s-p*n*c+t*m*c+a*n*g-t*o*g)*I,e[15]=(a*u*s-h*o*s+h*n*c-t*u*c-a*n*d+t*o*d)*I,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,a=e.x,o=e.y,c=e.z,l=r*a,h=r*o;return this.set(l*a+n,l*o-s*c,l*c+s*o,0,l*o+s*c,h*o+n,h*c-s*a,0,l*c-s*o,h*c+s*a,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,a){return this.set(1,n,r,0,e,1,a,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,a=t._y,o=t._z,c=t._w,l=r+r,h=a+a,u=o+o,d=r*l,f=r*h,p=r*u,m=a*h,g=a*u,A=o*u,_=c*l,x=c*h,E=c*u,S=n.x,w=n.y,I=n.z;return s[0]=(1-(m+A))*S,s[1]=(f+E)*S,s[2]=(p-x)*S,s[3]=0,s[4]=(f-E)*w,s[5]=(1-(d+A))*w,s[6]=(g+_)*w,s[7]=0,s[8]=(p+x)*I,s[9]=(g-_)*I,s[10]=(1-(d+m))*I,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;let r=aa.set(s[0],s[1],s[2]).length();const a=aa.set(s[4],s[5],s[6]).length(),o=aa.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),e.x=s[12],e.y=s[13],e.z=s[14],yi.copy(this);const l=1/r,h=1/a,u=1/o;return yi.elements[0]*=l,yi.elements[1]*=l,yi.elements[2]*=l,yi.elements[4]*=h,yi.elements[5]*=h,yi.elements[6]*=h,yi.elements[8]*=u,yi.elements[9]*=u,yi.elements[10]*=u,t.setFromRotationMatrix(yi),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=Yi){const c=this.elements,l=2*r/(t-e),h=2*r/(n-s),u=(t+e)/(t-e),d=(n+s)/(n-s);let f,p;if(o===Yi)f=-(a+r)/(a-r),p=-2*a*r/(a-r);else if(o===zc)f=-a/(a-r),p=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=u,c[12]=0,c[1]=0,c[5]=h,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=p,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,s,r,a,o=Yi){const c=this.elements,l=1/(t-e),h=1/(n-s),u=1/(a-r),d=(t+e)*l,f=(n+s)*h;let p,m;if(o===Yi)p=(a+r)*u,m=-2*u;else if(o===zc)p=r*u,m=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-d,c[1]=0,c[5]=2*h,c[9]=0,c[13]=-f,c[2]=0,c[6]=0,c[10]=m,c[14]=-p,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const aa=new G,yi=new Re,S_=new G(0,0,0),M_=new G(1,1,1),Fs=new G,Yc=new G,$n=new G,bA=new Re,EA=new Yt;class dn{constructor(e=0,t=0,n=0,s=dn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],a=s[4],o=s[8],c=s[1],l=s[5],h=s[9],u=s[2],d=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(at(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-at(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(at(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-at(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(at(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-at(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return bA.makeRotationFromQuaternion(e),this.setFromRotationMatrix(bA,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return EA.setFromEuler(this),this.setFromQuaternion(EA,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}dn.DEFAULT_ORDER="XYZ";class yA{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let B_=0;const _A=new G,oa=new Yt,es=new Re,Jc=new G,yo=new G,T_=new G,R_=new Yt,wA=new G(1,0,0),vA=new G(0,1,0),CA=new G(0,0,1),IA={type:"added"},F_={type:"removed"},ca={type:"childadded",child:null},Qu={type:"childremoved",child:null};class Tt extends Ms{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:B_++}),this.uuid=xi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Tt.DEFAULT_UP.clone();const e=new G,t=new dn,n=new Yt,s=new G(1,1,1);function r(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Re},normalMatrix:{value:new ot}}),this.matrix=new Re,this.matrixWorld=new Re,this.matrixAutoUpdate=Tt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new yA,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return oa.setFromAxisAngle(e,t),this.quaternion.multiply(oa),this}rotateOnWorldAxis(e,t){return oa.setFromAxisAngle(e,t),this.quaternion.premultiply(oa),this}rotateX(e){return this.rotateOnAxis(wA,e)}rotateY(e){return this.rotateOnAxis(vA,e)}rotateZ(e){return this.rotateOnAxis(CA,e)}translateOnAxis(e,t){return _A.copy(e).applyQuaternion(this.quaternion),this.position.add(_A.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(wA,e)}translateY(e){return this.translateOnAxis(vA,e)}translateZ(e){return this.translateOnAxis(CA,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(es.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Jc.copy(e):Jc.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),yo.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?es.lookAt(yo,Jc,this.up):es.lookAt(Jc,yo,this.up),this.quaternion.setFromRotationMatrix(es),s&&(es.extractRotation(s.matrixWorld),oa.setFromRotationMatrix(es),this.quaternion.premultiply(oa.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(IA),ca.child=e,this.dispatchEvent(ca),ca.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(F_),Qu.child=e,this.dispatchEvent(Qu),Qu.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),es.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),es.multiply(e.parent.matrixWorld)),e.applyMatrix4(es),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(IA),ca.child=e,this.dispatchEvent(ca),ca.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(yo,e,T_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(yo,R_,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?{min:o.boundingBox.min.toArray(),max:o.boundingBox.max.toArray()}:void 0,boundingSphere:o.boundingSphere?{radius:o.boundingSphere.radius,center:o.boundingSphere.center.toArray()}:void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere={center:this.boundingSphere.center.toArray(),radius:this.boundingSphere.radius}),this.boundingBox!==null&&(s.boundingBox={min:this.boundingBox.min.toArray(),max:this.boundingBox.max.toArray()}));function r(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let c=0,l=this.material.length;c<l;c++)o.push(r(e.materials,this.material[c]));s.material=o}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let o=0;o<this.children.length;o++)s.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let o=0;o<this.animations.length;o++){const c=this.animations[o];s.animations.push(r(e.animations,c))}}if(t){const o=a(e.geometries),c=a(e.materials),l=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),f=a(e.animations),p=a(e.nodes);o.length>0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),f.length>0&&(n.animations=f),p.length>0&&(n.nodes=p)}return n.object=s,n;function a(o){const c=[];for(const l in o){const h=o[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Tt.DEFAULT_UP=new G(0,1,0),Tt.DEFAULT_MATRIX_AUTO_UPDATE=!0,Tt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const _i=new G,ts=new G,Gu=new G,ns=new G,la=new G,ha=new G,SA=new G,Hu=new G,zu=new G,Vu=new G,Wu=new gt,qu=new gt,Ku=new gt;class wi{constructor(e=new G,t=new G,n=new G){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),_i.subVectors(e,t),s.cross(_i);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){_i.subVectors(s,t),ts.subVectors(n,t),Gu.subVectors(e,t);const a=_i.dot(_i),o=_i.dot(ts),c=_i.dot(Gu),l=ts.dot(ts),h=ts.dot(Gu),u=a*l-o*o;if(u===0)return r.set(0,0,0),null;const d=1/u,f=(l*c-o*h)*d,p=(a*h-o*c)*d;return r.set(1-f-p,p,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,ns)===null?!1:ns.x>=0&&ns.y>=0&&ns.x+ns.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,ns)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,ns.x),c.addScaledVector(a,ns.y),c.addScaledVector(o,ns.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return Wu.setScalar(0),qu.setScalar(0),Ku.setScalar(0),Wu.fromBufferAttribute(e,t),qu.fromBufferAttribute(e,n),Ku.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(Wu,r.x),a.addScaledVector(qu,r.y),a.addScaledVector(Ku,r.z),a}static isFrontFacing(e,t,n,s){return _i.subVectors(n,t),ts.subVectors(e,t),_i.cross(ts).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return _i.subVectors(this.c,this.b),ts.subVectors(this.a,this.b),_i.cross(ts).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return wi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return wi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return wi.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return wi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return wi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let a,o;la.subVectors(s,n),ha.subVectors(r,n),Hu.subVectors(e,n);const c=la.dot(Hu),l=ha.dot(Hu);if(c<=0&&l<=0)return t.copy(n);zu.subVectors(e,s);const h=la.dot(zu),u=ha.dot(zu);if(h>=0&&u<=h)return t.copy(s);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(la,a);Vu.subVectors(e,r);const f=la.dot(Vu),p=ha.dot(Vu);if(p>=0&&f<=p)return t.copy(r);const m=f*l-c*p;if(m<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(n).addScaledVector(ha,o);const g=h*p-f*u;if(g<=0&&u-h>=0&&f-p>=0)return SA.subVectors(r,s),o=(u-h)/(u-h+(f-p)),t.copy(s).addScaledVector(SA,o);const A=1/(g+m+d);return a=m*A,o=d*A,t.copy(n).addScaledVector(la,a).addScaledVector(ha,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const MA={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ns={h:0,s:0,l:0},Zc={h:0,s:0,l:0};function ju(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}let Fe=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=yt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,tt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,s=tt.workingColorSpace){return this.r=e,this.g=t,this.b=n,tt.toWorkingColorSpace(this,s),this}setHSL(e,t,n,s=tt.workingColorSpace){if(e=Tu(e,1),t=at(t,0,1),n=at(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,a=2*n-r;this.r=ju(a,r,e+1/3),this.g=ju(a,r,e),this.b=ju(a,r,e-1/3)}return tt.toWorkingColorSpace(this,s),this}setStyle(e,t=yt){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=s[1],o=s[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=yt){const n=MA[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ji(e.r),this.g=Ji(e.g),this.b=Ji(e.b),this}copyLinearToSRGB(e){return this.r=ta(e.r),this.g=ta(e.g),this.b=ta(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=yt){return tt.fromWorkingColorSpace(Nn.copy(this),e),Math.round(at(Nn.r*255,0,255))*65536+Math.round(at(Nn.g*255,0,255))*256+Math.round(at(Nn.b*255,0,255))}getHexString(e=yt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=tt.workingColorSpace){tt.fromWorkingColorSpace(Nn.copy(this),t);const n=Nn.r,s=Nn.g,r=Nn.b,a=Math.max(n,s,r),o=Math.min(n,s,r);let c,l;const h=(o+a)/2;if(o===a)c=0,l=0;else{const u=a-o;switch(l=h<=.5?u/(a+o):u/(2-a-o),a){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=h,e}getRGB(e,t=tt.workingColorSpace){return tt.fromWorkingColorSpace(Nn.copy(this),t),e.r=Nn.r,e.g=Nn.g,e.b=Nn.b,e}getStyle(e=yt){tt.fromWorkingColorSpace(Nn.copy(this),e);const t=Nn.r,n=Nn.g,s=Nn.b;return e!==yt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Ns),this.setHSL(Ns.h+e,Ns.s+t,Ns.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ns),e.getHSL(Zc);const n=go(Ns.h,Zc.h,t),s=go(Ns.s,Zc.s,t),r=go(Ns.l,Zc.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const Nn=new Fe;Fe.NAMES=MA;let N_=0;class ai extends Ms{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:N_++}),this.uuid=xi(),this.name="",this.type="Material",this.blending=jr,this.side=ji,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Wh,this.blendDst=qh,this.blendEquation=ir,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Fe(0,0,0),this.blendAlpha=0,this.depthFunc=Xr,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=cA,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=$r,this.stencilZFail=$r,this.stencilZPass=$r,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==jr&&(n.blending=this.blending),this.side!==ji&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Wh&&(n.blendSrc=this.blendSrc),this.blendDst!==qh&&(n.blendDst=this.blendDst),this.blendEquation!==ir&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Xr&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==cA&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==$r&&(n.stencilFail=this.stencilFail),this.stencilZFail!==$r&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==$r&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const a=[];for(const o in r){const c=r[o];delete c.metadata,a.push(c)}return a}if(t){const r=s(e.textures),a=s(e.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Ds extends ai{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Fe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const is=D_();function D_(){const i=new ArrayBuffer(4),e=new Float32Array(i),t=new Uint32Array(i),n=new Uint32Array(512),s=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(n[c]=0,n[c|256]=32768,s[c]=24,s[c|256]=24):l<-14?(n[c]=1024>>-l-14,n[c|256]=1024>>-l-14|32768,s[c]=-l-1,s[c|256]=-l-1):l<=15?(n[c]=l+15<<10,n[c|256]=l+15<<10|32768,s[c]=13,s[c|256]=13):l<128?(n[c]=31744,n[c|256]=64512,s[c]=24,s[c|256]=24):(n[c]=31744,n[c|256]=64512,s[c]=13,s[c|256]=13)}const r=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,r[c]=l|h}for(let c=1024;c<2048;++c)r[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)a[c]=c<<23;a[31]=1199570944,a[32]=2147483648;for(let c=33;c<63;++c)a[c]=2147483648+(c-32<<23);a[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(o[c]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:s,mantissaTable:r,exponentTable:a,offsetTable:o}}function L_(i){Math.abs(i)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),i=at(i,-65504,65504),is.floatView[0]=i;const e=is.uint32View[0],t=e>>23&511;return is.baseTable[t]+((e&8388607)>>is.shiftTable[t])}function P_(i){const e=i>>10;return is.uint32View[0]=is.mantissaTable[is.offsetTable[e]+(i&1023)]+is.exponentTable[e],is.floatView[0]}class BA{static toHalfFloat(e){return L_(e)}static fromHalfFloat(e){return P_(e)}}const sn=new G,$c=new Je;let k_=0;class Sn{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:k_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Bu,this.updateRanges=[],this.gpuType=ln,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)$c.fromBufferAttribute(this,t),$c.applyMatrix3(e),this.setXY(t,$c.x,$c.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyMatrix3(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyMatrix4(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.applyNormalMatrix(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)sn.fromBufferAttribute(this,t),sn.transformDirection(e),this.setXYZ(t,sn.x,sn.y,sn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=bi(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Bt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=bi(t,this.array)),t}setX(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=bi(t,this.array)),t}setY(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=bi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=bi(t,this.array)),t}setW(e,t){return this.normalized&&(t=Bt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array),r=Bt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Bu&&(e.usage=this.usage),e}}class Xu extends Sn{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class TA extends Sn{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class Jt extends Sn{constructor(e,t,n){super(new Float32Array(e),t,n)}}let U_=0;const oi=new Re,Yu=new Tt,ua=new G,ei=new ki,_o=new ki,bn=new G;class Mn extends Ms{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:U_++}),this.uuid=xi(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(dA(e)?TA:Xu)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new ot().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return oi.makeRotationFromQuaternion(e),this.applyMatrix4(oi),this}rotateX(e){return oi.makeRotationX(e),this.applyMatrix4(oi),this}rotateY(e){return oi.makeRotationY(e),this.applyMatrix4(oi),this}rotateZ(e){return oi.makeRotationZ(e),this.applyMatrix4(oi),this}translate(e,t,n){return oi.makeTranslation(e,t,n),this.applyMatrix4(oi),this}scale(e,t,n){return oi.makeScale(e,t,n),this.applyMatrix4(oi),this}lookAt(e){return Yu.lookAt(e),Yu.updateMatrix(),this.applyMatrix4(Yu.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ua).negate(),this.translate(ua.x,ua.y,ua.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const a=e[s];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Jt(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ki);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new G(-1/0,-1/0,-1/0),new G(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];ei.setFromBufferAttribute(r),this.morphTargetsRelative?(bn.addVectors(this.boundingBox.min,ei.min),this.boundingBox.expandByPoint(bn),bn.addVectors(this.boundingBox.max,ei.max),this.boundingBox.expandByPoint(bn)):(this.boundingBox.expandByPoint(ei.min),this.boundingBox.expandByPoint(ei.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Ui);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new G,1/0);return}if(e){const n=this.boundingSphere.center;if(ei.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];_o.setFromBufferAttribute(o),this.morphTargetsRelative?(bn.addVectors(ei.min,_o.min),ei.expandByPoint(bn),bn.addVectors(ei.max,_o.max),ei.expandByPoint(bn)):(ei.expandByPoint(_o.min),ei.expandByPoint(_o.max))}ei.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)bn.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(bn));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],c=this.morphTargetsRelative;for(let l=0,h=o.count;l<h;l++)bn.fromBufferAttribute(o,l),c&&(ua.fromBufferAttribute(e,l),bn.add(ua)),s=Math.max(s,n.distanceToSquared(bn))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Sn(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let T=0;T<n.count;T++)o[T]=new G,c[T]=new G;const l=new G,h=new G,u=new G,d=new Je,f=new Je,p=new Je,m=new G,g=new G;function A(T,C,v){l.fromBufferAttribute(n,T),h.fromBufferAttribute(n,C),u.fromBufferAttribute(n,v),d.fromBufferAttribute(r,T),f.fromBufferAttribute(r,C),p.fromBufferAttribute(r,v),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const F=1/(f.x*p.y-p.x*f.y);isFinite(F)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(F),g.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(F),o[T].add(m),o[C].add(m),o[v].add(m),c[T].add(g),c[C].add(g),c[v].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let T=0,C=_.length;T<C;++T){const v=_[T],F=v.start,K=v.count;for(let q=F,$=F+K;q<$;q+=3)A(e.getX(q+0),e.getX(q+1),e.getX(q+2))}const x=new G,E=new G,S=new G,w=new G;function I(T){S.fromBufferAttribute(s,T),w.copy(S);const C=o[T];x.copy(C),x.sub(S.multiplyScalar(S.dot(C))).normalize(),E.crossVectors(w,C);const F=E.dot(c[T])<0?-1:1;a.setXYZW(T,x.x,x.y,x.z,F)}for(let T=0,C=_.length;T<C;++T){const v=_[T],F=v.start,K=v.count;for(let q=F,$=F+K;q<$;q+=3)I(e.getX(q+0)),I(e.getX(q+1)),I(e.getX(q+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Sn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);const s=new G,r=new G,a=new G,o=new G,c=new G,l=new G,h=new G,u=new G;if(e)for(let d=0,f=e.count;d<f;d+=3){const p=e.getX(d+0),m=e.getX(d+1),g=e.getX(d+2);s.fromBufferAttribute(t,p),r.fromBufferAttribute(t,m),a.fromBufferAttribute(t,g),h.subVectors(a,r),u.subVectors(s,r),h.cross(u),o.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),l.fromBufferAttribute(n,g),o.add(h),c.add(h),l.add(h),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(m,c.x,c.y,c.z),n.setXYZ(g,l.x,l.y,l.z)}else for(let d=0,f=t.count;d<f;d+=3)s.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,r),u.subVectors(s,r),h.cross(u),n.setXYZ(d+0,h.x,h.y,h.z),n.setXYZ(d+1,h.x,h.y,h.z),n.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)bn.fromBufferAttribute(e,t),bn.normalize(),e.setXYZ(t,bn.x,bn.y,bn.z)}toNonIndexed(){function e(o,c){const l=o.array,h=o.itemSize,u=o.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let m=0,g=c.length;m<g;m++){o.isInterleavedBufferAttribute?f=c[m]*o.data.stride+o.offset:f=c[m]*h;for(let A=0;A<h;A++)d[p++]=l[f++]}return new Sn(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Mn,n=this.index.array,s=this.attributes;for(const o in s){const c=s[o],l=e(c,n);t.setAttribute(o,l)}const r=this.morphAttributes;for(const o in r){const c=[],l=r[o];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=e(d,n);c.push(f)}t.morphAttributes[o]=c}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,c=a.length;o<c;o++){const l=a[o];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(e.data))}h.length>0&&(s[c]=h,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const h=s[l];this.setAttribute(l,h.clone(t))}const r=e.morphAttributes;for(const l in r){const h=[],u=r[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(t));this.morphAttributes[l]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let l=0,h=a.length;l<h;l++){const u=a[l];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const RA=new Re,hr=new Eo,el=new Ui,FA=new G,tl=new G,nl=new G,il=new G,Ju=new G,sl=new G,NA=new G,rl=new G;class Zt extends Tt{constructor(e=new Mn,t=new Ds){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const o=this.morphTargetInfluences;if(r&&o){sl.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const h=o[c],u=r[c];h!==0&&(Ju.fromBufferAttribute(u,e),a?sl.addScaledVector(Ju,h):sl.addScaledVector(Ju.sub(t),h))}t.add(sl)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),el.copy(n.boundingSphere),el.applyMatrix4(r),hr.copy(e.ray).recast(e.near),!(el.containsPoint(hr.origin)===!1&&(hr.intersectSphere(el,FA)===null||hr.origin.distanceToSquared(FA)>(e.far-e.near)**2))&&(RA.copy(r).invert(),hr.copy(e.ray).applyMatrix4(RA),!(n.boundingBox!==null&&hr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,hr)))}_computeIntersections(e,t,n){let s;const r=this.geometry,a=this.material,o=r.index,c=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let p=0,m=d.length;p<m;p++){const g=d[p],A=a[g.materialIndex],_=Math.max(g.start,f.start),x=Math.min(o.count,Math.min(g.start+g.count,f.start+f.count));for(let E=_,S=x;E<S;E+=3){const w=o.getX(E),I=o.getX(E+1),T=o.getX(E+2);s=al(this,A,e,n,l,h,u,w,I,T),s&&(s.faceIndex=Math.floor(E/3),s.face.materialIndex=g.materialIndex,t.push(s))}}else{const p=Math.max(0,f.start),m=Math.min(o.count,f.start+f.count);for(let g=p,A=m;g<A;g+=3){const _=o.getX(g),x=o.getX(g+1),E=o.getX(g+2);s=al(this,a,e,n,l,h,u,_,x,E),s&&(s.faceIndex=Math.floor(g/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(a))for(let p=0,m=d.length;p<m;p++){const g=d[p],A=a[g.materialIndex],_=Math.max(g.start,f.start),x=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let E=_,S=x;E<S;E+=3){const w=E,I=E+1,T=E+2;s=al(this,A,e,n,l,h,u,w,I,T),s&&(s.faceIndex=Math.floor(E/3),s.face.materialIndex=g.materialIndex,t.push(s))}}else{const p=Math.max(0,f.start),m=Math.min(c.count,f.start+f.count);for(let g=p,A=m;g<A;g+=3){const _=g,x=g+1,E=g+2;s=al(this,a,e,n,l,h,u,_,x,E),s&&(s.faceIndex=Math.floor(g/3),t.push(s))}}}}function O_(i,e,t,n,s,r,a,o){let c;if(e.side===Ln?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===ji,o),c===null)return null;rl.copy(o),rl.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(rl);return l<t.near||l>t.far?null:{distance:l,point:rl.clone(),object:i}}function al(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,tl),i.getVertexPosition(c,nl),i.getVertexPosition(l,il);const h=O_(i,e,t,n,tl,nl,il,NA);if(h){const u=new G;wi.getBarycoord(NA,tl,nl,il,u),s&&(h.uv=wi.getInterpolatedAttribute(s,o,c,l,u,new Je)),r&&(h.uv1=wi.getInterpolatedAttribute(r,o,c,l,u,new Je)),a&&(h.normal=wi.getInterpolatedAttribute(a,o,c,l,u,new G),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const d={a:o,b:c,c:l,normal:new G,materialIndex:0};wi.getNormal(tl,nl,il,d.normal),h.face=d,h.barycoord=u}return h}class da extends Mn{constructor(e=1,t=1,n=1,s=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:a};const o=this;s=Math.floor(s),r=Math.floor(r),a=Math.floor(a);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,n,t,e,a,r,0),p("z","y","x",1,-1,n,t,-e,a,r,1),p("x","z","y",1,1,e,n,t,s,a,2),p("x","z","y",1,-1,e,n,-t,s,a,3),p("x","y","z",1,-1,e,t,n,s,r,4),p("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new Jt(l,3)),this.setAttribute("normal",new Jt(h,3)),this.setAttribute("uv",new Jt(u,2));function p(m,g,A,_,x,E,S,w,I,T,C){const v=E/I,F=S/T,K=E/2,q=S/2,$=w/2,D=I+1,O=T+1;let Y=0,Q=0;const J=new G;for(let ee=0;ee<O;ee++){const ae=ee*F-q;for(let _e=0;_e<D;_e++){const Me=_e*v-K;J[m]=Me*_,J[g]=ae*x,J[A]=$,l.push(J.x,J.y,J.z),J[m]=0,J[g]=0,J[A]=w>0?1:-1,h.push(J.x,J.y,J.z),u.push(_e/I),u.push(1-ee/T),Y+=1}}for(let ee=0;ee<T;ee++)for(let ae=0;ae<I;ae++){const _e=d+ae+D*ee,Me=d+ae+D*(ee+1),se=d+(ae+1)+D*(ee+1),me=d+(ae+1)+D*ee;c.push(_e,Me,me),c.push(Me,se,me),Q+=6}o.addGroup(f,Q,C),f+=Q,d+=Y}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new da(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function fa(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function Un(i){const e={};for(let t=0;t<i.length;t++){const n=fa(i[t]);for(const s in n)e[s]=n[s]}return e}function Q_(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function DA(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:tt.workingColorSpace}const G_={clone:fa,merge:Un};var H_=`void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
-}`,V_=`void main() {
+}`,z_=`void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
-}`;class Ls extends ai{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=z_,this.fragmentShader=V_,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=fa(e.uniforms),this.uniformsGroups=G_(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const a=this.uniforms[s].value;a&&a.isTexture?t.uniforms[s]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[s]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[s]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[s]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[s]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[s]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[s]={type:"m4",value:a.toArray()}:t.uniforms[s]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class LA extends Tt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Re,this.projectionMatrix=new Re,this.projectionMatrixInverse=new Re,this.coordinateSystem=Yi}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ps=new G,PA=new Je,kA=new Je;class Bn extends LA{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ea*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Ao*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ea*2*Math.atan(Math.tan(Ao*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Ps.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ps.x,Ps.y).multiplyScalar(-e/Ps.z),Ps.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Ps.x,Ps.y).multiplyScalar(-e/Ps.z)}getViewSize(e,t){return this.getViewBounds(e,PA,kA),t.subVectors(kA,PA)}setViewOffset(e,t,n,s,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Ao*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;r+=a.offsetX*s/c,t-=a.offsetY*n/l,s*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const pa=-90,Aa=1;class W_ extends Tt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Bn(pa,Aa,e,t);s.layers=this.layers,this.add(s);const r=new Bn(pa,Aa,e,t);r.layers=this.layers,this.add(r);const a=new Bn(pa,Aa,e,t);a.layers=this.layers,this.add(a);const o=new Bn(pa,Aa,e,t);o.layers=this.layers,this.add(o);const c=new Bn(pa,Aa,e,t);c.layers=this.layers,this.add(c);const l=new Bn(pa,Aa,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,a,o,c]=t;for(const l of t)this.remove(l);if(e===Yi)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===zc)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,c,l,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,a),e.setRenderTarget(n,2,s),e.render(t,o),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,s),e.render(t,h),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class UA extends nn{constructor(e=[],t=sr,n,s,r,a,o,c,l,h){super(e,t,n,s,r,a,o,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class q_ extends or{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new UA(s,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:qt}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
+}`;class Ls extends ai{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=H_,this.fragmentShader=z_,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=fa(e.uniforms),this.uniformsGroups=Q_(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const a=this.uniforms[s].value;a&&a.isTexture?t.uniforms[s]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[s]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[s]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[s]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[s]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[s]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[s]={type:"m4",value:a.toArray()}:t.uniforms[s]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class LA extends Tt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Re,this.projectionMatrix=new Re,this.projectionMatrixInverse=new Re,this.coordinateSystem=Yi}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Ps=new G,PA=new Je,kA=new Je;class Bn extends LA{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ea*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Ao*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ea*2*Math.atan(Math.tan(Ao*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Ps.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ps.x,Ps.y).multiplyScalar(-e/Ps.z),Ps.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Ps.x,Ps.y).multiplyScalar(-e/Ps.z)}getViewSize(e,t){return this.getViewBounds(e,PA,kA),t.subVectors(kA,PA)}setViewOffset(e,t,n,s,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Ao*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;r+=a.offsetX*s/c,t-=a.offsetY*n/l,s*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const pa=-90,Aa=1;class V_ extends Tt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Bn(pa,Aa,e,t);s.layers=this.layers,this.add(s);const r=new Bn(pa,Aa,e,t);r.layers=this.layers,this.add(r);const a=new Bn(pa,Aa,e,t);a.layers=this.layers,this.add(a);const o=new Bn(pa,Aa,e,t);o.layers=this.layers,this.add(o);const c=new Bn(pa,Aa,e,t);c.layers=this.layers,this.add(c);const l=new Bn(pa,Aa,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,a,o,c]=t;for(const l of t)this.remove(l);if(e===Yi)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===zc)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,c,l,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,a),e.setRenderTarget(n,2,s),e.render(t,o),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,s),e.render(t,h),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class UA extends nn{constructor(e=[],t=sr,n,s,r,a,o,c,l,h){super(e,t,n,s,r,a,o,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class W_ extends or{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new UA(s,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:qt}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
varying vec3 vWorldDirection;
@@ -37,9 +37,9 @@
gl_FragColor = texture2D( tEquirect, sampleUV );
}
- `},s=new da(5,5,5),r=new Ls({name:"CubemapFromEquirect",uniforms:fa(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ln,blending:Cs});r.uniforms.tEquirect.value=t;const a=new Zt(s,r),o=t.minFilter;return t.minFilter===ri&&(t.minFilter=qt),new W_(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,s);e.setRenderTarget(r)}}class ss extends Tt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const K_={type:"move"};class Zu{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ss,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new ss,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new G,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new G),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ss,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new G,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new G),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const m of e.hand.values()){const g=t.getJointPose(m,n),A=this._getHandJoint(l,m);g!==null&&(A.matrix.fromArray(g.transform.matrix),A.matrix.decompose(A.position,A.rotation,A.scale),A.matrixWorldNeedsUpdate=!0,A.jointRadius=g.radius),A.visible=g!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(K_)))}return o!==null&&(o.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new ss;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class $u extends Tt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dn,this.environmentIntensity=1,this.environmentRotation=new dn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class j_{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Bu,this.updateRanges=[],this.version=0,this.uuid=xi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let s=0,r=this.stride;s<r;s++)this.array[e+s]=t.array[n+s];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=xi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=xi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const On=new G;class ed{constructor(e,t,n,s=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=s}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)On.fromBufferAttribute(this,t),On.applyMatrix4(e),this.setXYZ(t,On.x,On.y,On.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)On.fromBufferAttribute(this,t),On.applyNormalMatrix(e),this.setXYZ(t,On.x,On.y,On.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)On.fromBufferAttribute(this,t),On.transformDirection(e),this.setXYZ(t,On.x,On.y,On.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=bi(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Bt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=bi(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=bi(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=bi(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=bi(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array),r=Bt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=s,this.data.array[e+3]=r,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const s=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[s+r])}return new Sn(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new ed(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const s=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[s+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}const OA=new G,QA=new gt,GA=new gt,X_=new G,HA=new Re,ol=new G,td=new Ui,zA=new Re,nd=new Eo;class VA extends Zt{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Yp,this.bindMatrix=new Re,this.bindMatrixInverse=new Re,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new ki),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ol),this.boundingBox.expandByPoint(ol)}computeBoundingSphere(){const e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Ui),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ol),this.boundingSphere.expandByPoint(ol)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const n=this.material,s=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),td.copy(this.boundingSphere),td.applyMatrix4(s),e.ray.intersectsSphere(td)!==!1&&(zA.copy(s).invert(),nd.copy(e.ray).applyMatrix4(zA),!(this.boundingBox!==null&&nd.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,nd)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const e=new gt,t=this.geometry.attributes.skinWeight;for(let n=0,s=t.count;n<s;n++){e.fromBufferAttribute(t,n);const r=1/e.manhattanLength();r!==1/0?e.multiplyScalar(r):e.set(1,0,0,0),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===Yp?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===Hy?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const n=this.skeleton,s=this.geometry;QA.fromBufferAttribute(s.attributes.skinIndex,e),GA.fromBufferAttribute(s.attributes.skinWeight,e),OA.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let r=0;r<4;r++){const a=GA.getComponent(r);if(a!==0){const o=QA.getComponent(r);HA.multiplyMatrices(n.bones[o].matrixWorld,n.boneInverses[o]),t.addScaledVector(X_.copy(OA).applyMatrix4(HA),a)}}return t.applyMatrix4(this.bindMatrixInverse)}}class cl extends Tt{constructor(){super(),this.isBone=!0,this.type="Bone"}}class ll extends nn{constructor(e=null,t=1,n=1,s,r,a,o,c,l=Pn,h=Pn,u,d){super(null,a,o,c,l,h,s,r,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const WA=new Re,Y_=new Re;class hl{constructor(e=[],t=[]){this.uuid=xi(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,s=this.bones.length;n<s;n++)this.boneInverses.push(new Re)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const n=new Re;this.bones[e]&&n.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(n)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const n=this.bones[e];n&&n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const n=this.bones[e];n&&(n.parent&&n.parent.isBone?(n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld)):n.matrix.copy(n.matrixWorld),n.matrix.decompose(n.position,n.quaternion,n.scale))}}update(){const e=this.bones,t=this.boneInverses,n=this.boneMatrices,s=this.boneTexture;for(let r=0,a=e.length;r<a;r++){const o=e[r]?e[r].matrixWorld:Y_;WA.multiplyMatrices(o,t[r]),WA.toArray(n,r*16)}s!==null&&(s.needsUpdate=!0)}clone(){return new hl(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const n=new ll(t,e,e,hn,ln);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){const s=this.bones[t];if(s.name===e)return s}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,s=e.bones.length;n<s;n++){const r=e.bones[n];let a=t[r];a===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",r),a=new cl),this.bones.push(a),this.boneInverses.push(new Re().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){const e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,n=this.boneInverses;for(let s=0,r=t.length;s<r;s++){const a=t[s];e.bones.push(a.uuid);const o=n[s];e.boneInverses.push(o.toArray())}return e}}class id extends Sn{constructor(e,t,n,s=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const ga=new Re,qA=new Re,ul=[],KA=new ki,J_=new Re,wo=new Zt,vo=new Ui;class jA extends Zt{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new id(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let s=0;s<n;s++)this.setMatrixAt(s,J_)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new ki),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ga),KA.copy(e.boundingBox).applyMatrix4(ga),this.boundingBox.union(KA)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Ui),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ga),vo.copy(e.boundingSphere).applyMatrix4(ga),this.boundingSphere.union(vo)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const n=t.morphTargetInfluences,s=this.morphTexture.source.data.data,r=n.length+1,a=e*r+1;for(let o=0;o<n.length;o++)n[o]=s[a+o]}raycast(e,t){const n=this.matrixWorld,s=this.count;if(wo.geometry=this.geometry,wo.material=this.material,wo.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),vo.copy(this.boundingSphere),vo.applyMatrix4(n),e.ray.intersectsSphere(vo)!==!1))for(let r=0;r<s;r++){this.getMatrixAt(r,ga),qA.multiplyMatrices(n,ga),wo.matrixWorld=qA,wo.raycast(e,ul);for(let a=0,o=ul.length;a<o;a++){const c=ul[a];c.instanceId=r,c.object=this,t.push(c)}ul.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new id(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){const n=t.morphTargetInfluences,s=n.length+1;this.morphTexture===null&&(this.morphTexture=new ll(new Float32Array(s*this.count),s,this.count,Xi,ln));const r=this.morphTexture.source.data.data;let a=0;for(let l=0;l<n.length;l++)a+=n[l];const o=this.geometry.morphTargetsRelative?1:1-a,c=s*e;r[c]=o,r.set(n,c+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const sd=new G,Z_=new G,$_=new ot;class ks{constructor(e=new G(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=sd.subVectors(n,t).cross(Z_.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(sd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||$_.getNormalMatrix(e),s=this.coplanarPoint(sd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ur=new Ui,dl=new G;class rd{constructor(e=new ks,t=new ks,n=new ks,s=new ks,r=new ks,a=new ks){this.planes=[e,t,n,s,r,a]}set(e,t,n,s,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(s),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Yi){const n=this.planes,s=e.elements,r=s[0],a=s[1],o=s[2],c=s[3],l=s[4],h=s[5],u=s[6],d=s[7],f=s[8],p=s[9],m=s[10],g=s[11],A=s[12],_=s[13],x=s[14],E=s[15];if(n[0].setComponents(c-r,d-l,g-f,E-A).normalize(),n[1].setComponents(c+r,d+l,g+f,E+A).normalize(),n[2].setComponents(c+a,d+h,g+p,E+_).normalize(),n[3].setComponents(c-a,d-h,g-p,E-_).normalize(),n[4].setComponents(c-o,d-u,g-m,E-x).normalize(),t===Yi)n[5].setComponents(c+o,d+u,g+m,E+x).normalize();else if(t===zc)n[5].setComponents(o,u,m,x).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ur.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ur.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ur)}intersectsSprite(e){return ur.center.set(0,0,0),ur.radius=.7071067811865476,ur.applyMatrix4(e.matrixWorld),this.intersectsSphere(ur)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(dl.x=s.normal.x>0?e.max.x:e.min.x,dl.y=s.normal.y>0?e.max.y:e.min.y,dl.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(dl)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class ma extends ai{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Fe(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const fl=new G,pl=new G,XA=new Re,Co=new Eo,Al=new Ui,ad=new G,YA=new G;class gl extends Tt{constructor(e=new Mn,t=new ma){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let s=1,r=t.count;s<r;s++)fl.fromBufferAttribute(t,s-1),pl.fromBufferAttribute(t,s),n[s]=n[s-1],n[s]+=fl.distanceTo(pl);e.setAttribute("lineDistance",new Jt(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Al.copy(n.boundingSphere),Al.applyMatrix4(s),Al.radius+=r,e.ray.intersectsSphere(Al)===!1)return;XA.copy(s).invert(),Co.copy(e.ray).applyMatrix4(XA);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=o*o,l=this.isLineSegments?2:1,h=n.index,d=n.attributes.position;if(h!==null){const f=Math.max(0,a.start),p=Math.min(h.count,a.start+a.count);for(let m=f,g=p-1;m<g;m+=l){const A=h.getX(m),_=h.getX(m+1),x=ml(this,e,Co,c,A,_,m);x&&t.push(x)}if(this.isLineLoop){const m=h.getX(p-1),g=h.getX(f),A=ml(this,e,Co,c,m,g,p-1);A&&t.push(A)}}else{const f=Math.max(0,a.start),p=Math.min(d.count,a.start+a.count);for(let m=f,g=p-1;m<g;m+=l){const A=ml(this,e,Co,c,m,m+1,m);A&&t.push(A)}if(this.isLineLoop){const m=ml(this,e,Co,c,p-1,f,p-1);m&&t.push(m)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function ml(i,e,t,n,s,r,a){const o=i.geometry.attributes.position;if(fl.fromBufferAttribute(o,s),pl.fromBufferAttribute(o,r),t.distanceSqToSegment(fl,pl,ad,YA)>n)return;ad.applyMatrix4(i.matrixWorld);const l=e.ray.origin.distanceTo(ad);if(!(l<e.near||l>e.far))return{distance:l,point:YA.clone().applyMatrix4(i.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:i}}const JA=new G,ZA=new G;class xl extends gl{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[];for(let s=0,r=t.count;s<r;s+=2)JA.fromBufferAttribute(t,s),ZA.fromBufferAttribute(t,s+1),n[s]=s===0?0:n[s-1],n[s+1]=n[s]+JA.distanceTo(ZA);e.setAttribute("lineDistance",new Jt(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class ew extends gl{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class od extends ai{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Fe(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const $A=new Re,cd=new Eo,bl=new Ui,El=new G;class tw extends Tt{constructor(e=new Mn,t=new od){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),bl.copy(n.boundingSphere),bl.applyMatrix4(s),bl.radius+=r,e.ray.intersectsSphere(bl)===!1)return;$A.copy(s).invert(),cd.copy(e.ray).applyMatrix4($A);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=o*o,l=n.index,u=n.attributes.position;if(l!==null){const d=Math.max(0,a.start),f=Math.min(l.count,a.start+a.count);for(let p=d,m=f;p<m;p++){const g=l.getX(p);El.fromBufferAttribute(u,g),eg(El,g,c,s,e,t,this)}}else{const d=Math.max(0,a.start),f=Math.min(u.count,a.start+a.count);for(let p=d,m=f;p<m;p++)El.fromBufferAttribute(u,p),eg(El,p,c,s,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function eg(i,e,t,n,s,r,a){const o=cd.distanceSqToPoint(i);if(o<t){const c=new G;cd.closestPointToPoint(i,c),c.applyMatrix4(n);const l=s.ray.origin.distanceTo(c);if(l<s.near||l>s.far)return;r.push({distance:l,distanceToRay:Math.sqrt(o),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class yl extends nn{constructor(e,t,n,s,r,a,o,c,l,h,u,d){super(null,a,o,c,l,h,s,r,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class nw extends yl{constructor(e,t,n,s,r,a){super(e,t,n,r,a),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Zn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class iw extends yl{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,sr),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class tg extends nn{constructor(e,t,n=rr,s,r,a,o=Pn,c=Pn,l,h=ro){if(h!==ro&&h!==ao)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,s,r,a,o,c,h,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Fu(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class sw{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,s=this.getPoint(0),r=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),r+=n.distanceTo(s),t.push(r),s=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let s=0;const r=n.length;let a;t?a=t:a=e*n[r-1];let o=0,c=r-1,l;for(;o<=c;)if(s=Math.floor(o+(c-o)/2),l=n[s]-a,l<0)o=s+1;else if(l>0)c=s-1;else{c=s;break}if(s=c,n[s]===a)return s/(r-1);const h=n[s],d=n[s+1]-h,f=(a-h)/d;return(s+f)/(r-1)}getTangent(e,t){let s=e-1e-4,r=e+1e-4;s<0&&(s=0),r>1&&(r=1);const a=this.getPoint(s),o=this.getPoint(r),c=t||(a.isVector2?new Je:new G);return c.copy(o).sub(a).normalize(),c}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new G,s=[],r=[],a=[],o=new G,c=new Re;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new G)}r[0]=new G,a[0]=new G;let l=Number.MAX_VALUE;const h=Math.abs(s[0].x),u=Math.abs(s[0].y),d=Math.abs(s[0].z);h<=l&&(l=h,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),d<=l&&n.set(0,0,1),o.crossVectors(s[0],n).normalize(),r[0].crossVectors(s[0],o),a[0].crossVectors(s[0],r[0]);for(let f=1;f<=e;f++){if(r[f]=r[f-1].clone(),a[f]=a[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(at(s[f-1].dot(s[f]),-1,1));r[f].applyMatrix4(c.makeRotationAxis(o,p))}a[f].crossVectors(s[f],r[f])}if(t===!0){let f=Math.acos(at(r[0].dot(r[e]),-1,1));f/=e,s[0].dot(o.crossVectors(r[0],r[e]))>0&&(f=-f);for(let p=1;p<=e;p++)r[p].applyMatrix4(c.makeRotationAxis(s[p],f*p)),a[p].crossVectors(s[p],r[p])}return{tangents:s,normals:r,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}function rw(i,e,t=2){const n=e&&e.length,s=n?e[0]*t:i.length;let r=ng(i,0,s,t,!0);const a=[];if(!r||r.next===r.prev)return a;let o,c,l;if(n&&(r=hw(i,e,r,t)),i.length>80*t){o=1/0,c=1/0;let h=-1/0,u=-1/0;for(let d=t;d<s;d+=t){const f=i[d],p=i[d+1];f<o&&(o=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-o,u-c),l=l!==0?32767/l:0}return Io(r,a,t,o,c,l,0),a}function ng(i,e,t,n,s){let r;if(s===yw(i,e,t,n)>0)for(let a=e;a<t;a+=n)r=ag(a/n|0,i[a],i[a+1],r);else for(let a=t-n;a>=e;a-=n)r=ag(a/n|0,i[a],i[a+1],r);return r&&xa(r,r.next)&&(Bo(r),r=r.next),r}function dr(i,e){if(!i)return i;e||(e=i);let t=i,n;do if(n=!1,!t.steiner&&(xa(t,t.next)||zt(t.prev,t,t.next)===0)){if(Bo(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function Io(i,e,t,n,s,r,a){if(!i)return;!a&&r&&Aw(i,n,s,r);let o=i;for(;i.prev!==i.next;){const c=i.prev,l=i.next;if(r?ow(i,n,s,r):aw(i)){e.push(c.i,i.i,l.i),Bo(i),i=l.next,o=l.next;continue}if(i=l,i===o){a?a===1?(i=cw(dr(i),e),Io(i,e,t,n,s,r,2)):a===2&&lw(i,e,t,n,s,r):Io(dr(i),e,t,n,s,r,1);break}}}function aw(i){const e=i.prev,t=i,n=i.next;if(zt(e,t,n)>=0)return!1;const s=e.x,r=t.x,a=n.x,o=e.y,c=t.y,l=n.y,h=Math.min(s,r,a),u=Math.min(o,c,l),d=Math.max(s,r,a),f=Math.max(o,c,l);let p=n.next;for(;p!==e;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&So(s,o,r,c,a,l,p.x,p.y)&&zt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function ow(i,e,t,n){const s=i.prev,r=i,a=i.next;if(zt(s,r,a)>=0)return!1;const o=s.x,c=r.x,l=a.x,h=s.y,u=r.y,d=a.y,f=Math.min(o,c,l),p=Math.min(h,u,d),m=Math.max(o,c,l),g=Math.max(h,u,d),A=ld(f,p,e,t,n),_=ld(m,g,e,t,n);let x=i.prevZ,E=i.nextZ;for(;x&&x.z>=A&&E&&E.z<=_;){if(x.x>=f&&x.x<=m&&x.y>=p&&x.y<=g&&x!==s&&x!==a&&So(o,h,c,u,l,d,x.x,x.y)&&zt(x.prev,x,x.next)>=0||(x=x.prevZ,E.x>=f&&E.x<=m&&E.y>=p&&E.y<=g&&E!==s&&E!==a&&So(o,h,c,u,l,d,E.x,E.y)&&zt(E.prev,E,E.next)>=0))return!1;E=E.nextZ}for(;x&&x.z>=A;){if(x.x>=f&&x.x<=m&&x.y>=p&&x.y<=g&&x!==s&&x!==a&&So(o,h,c,u,l,d,x.x,x.y)&&zt(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;E&&E.z<=_;){if(E.x>=f&&E.x<=m&&E.y>=p&&E.y<=g&&E!==s&&E!==a&&So(o,h,c,u,l,d,E.x,E.y)&&zt(E.prev,E,E.next)>=0)return!1;E=E.nextZ}return!0}function cw(i,e){let t=i;do{const n=t.prev,s=t.next.next;!xa(n,s)&&sg(n,t,t.next,s)&&Mo(n,s)&&Mo(s,n)&&(e.push(n.i,t.i,s.i),Bo(t),Bo(t.next),t=i=s),t=t.next}while(t!==i);return dr(t)}function lw(i,e,t,n,s,r){let a=i;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&xw(a,o)){let c=rg(a,o);a=dr(a,a.next),c=dr(c,c.next),Io(a,e,t,n,s,r,0),Io(c,e,t,n,s,r,0);return}o=o.next}a=a.next}while(a!==i)}function hw(i,e,t,n){const s=[];for(let r=0,a=e.length;r<a;r++){const o=e[r]*n,c=r<a-1?e[r+1]*n:i.length,l=ng(i,o,c,n,!1);l===l.next&&(l.steiner=!0),s.push(mw(l))}s.sort(uw);for(let r=0;r<s.length;r++)t=dw(s[r],t);return t}function uw(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const n=(i.next.y-i.y)/(i.next.x-i.x),s=(e.next.y-e.y)/(e.next.x-e.x);t=n-s}return t}function dw(i,e){const t=fw(i,e);if(!t)return e;const n=rg(t,i);return dr(n,n.next),dr(t,t.next)}function fw(i,e){let t=e;const n=i.x,s=i.y;let r=-1/0,a;if(xa(i,t))return t;do{if(xa(i,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const u=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=n&&u>r&&(r=u,a=t.x<t.next.x?t:t.next,u===n))return a}t=t.next}while(t!==e);if(!a)return null;const o=a,c=a.x,l=a.y;let h=1/0;t=a;do{if(n>=t.x&&t.x>=c&&n!==t.x&&ig(s<l?n:r,s,c,l,s<l?r:n,s,t.x,t.y)){const u=Math.abs(s-t.y)/(n-t.x);Mo(t,i)&&(u<h||u===h&&(t.x>a.x||t.x===a.x&&pw(a,t)))&&(a=t,h=u)}t=t.next}while(t!==o);return a}function pw(i,e){return zt(i.prev,i,e.prev)<0&&zt(e.next,i,i.next)<0}function Aw(i,e,t,n){let s=i;do s.z===0&&(s.z=ld(s.x,s.y,e,t,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==i);s.prevZ.nextZ=null,s.prevZ=null,gw(s)}function gw(i){let e,t=1;do{let n=i,s;i=null;let r=null;for(e=0;n;){e++;let a=n,o=0;for(let l=0;l<t&&(o++,a=a.nextZ,!!a);l++);let c=t;for(;o>0||c>0&&a;)o!==0&&(c===0||!a||n.z<=a.z)?(s=n,n=n.nextZ,o--):(s=a,a=a.nextZ,c--),r?r.nextZ=s:i=s,s.prevZ=r,r=s;n=a}r.nextZ=null,t*=2}while(e>1);return i}function ld(i,e,t,n,s){return i=(i-t)*s|0,e=(e-n)*s|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function mw(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function ig(i,e,t,n,s,r,a,o){return(s-a)*(e-o)>=(i-a)*(r-o)&&(i-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(r-o)>=(s-a)*(n-o)}function So(i,e,t,n,s,r,a,o){return!(i===a&&e===o)&&ig(i,e,t,n,s,r,a,o)}function xw(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!bw(i,e)&&(Mo(i,e)&&Mo(e,i)&&Ew(i,e)&&(zt(i.prev,i,e.prev)||zt(i,e.prev,e))||xa(i,e)&&zt(i.prev,i,i.next)>0&&zt(e.prev,e,e.next)>0)}function zt(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function xa(i,e){return i.x===e.x&&i.y===e.y}function sg(i,e,t,n){const s=wl(zt(i,e,t)),r=wl(zt(i,e,n)),a=wl(zt(t,n,i)),o=wl(zt(t,n,e));return!!(s!==r&&a!==o||s===0&&_l(i,t,e)||r===0&&_l(i,n,e)||a===0&&_l(t,i,n)||o===0&&_l(t,e,n))}function _l(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function wl(i){return i>0?1:i<0?-1:0}function bw(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&sg(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function Mo(i,e){return zt(i.prev,i,i.next)<0?zt(i,e,i.next)>=0&&zt(i,i.prev,e)>=0:zt(i,e,i.prev)<0||zt(i,i.next,e)<0}function Ew(i,e){let t=i,n=!1;const s=(i.x+e.x)/2,r=(i.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&s<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==i);return n}function rg(i,e){const t=hd(i.i,i.x,i.y),n=hd(e.i,e.x,e.y),s=i.next,r=e.prev;return i.next=e,e.prev=i,t.next=s,s.prev=t,n.next=t,t.prev=n,r.next=n,n.prev=r,n}function ag(i,e,t,n){const s=hd(i,e,t);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function Bo(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function hd(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function yw(i,e,t,n){let s=0;for(let r=e,a=t-n;r<t;r+=n)s+=(i[a]-i[r])*(i[r+1]+i[a+1]),a=r;return s}class _w{static triangulate(e,t,n=2){return rw(e,t,n)}}class ud{static area(e){const t=e.length;let n=0;for(let s=t-1,r=0;r<t;s=r++)n+=e[s].x*e[r].y-e[r].x*e[s].y;return n*.5}static isClockWise(e){return ud.area(e)<0}static triangulateShape(e,t){const n=[],s=[],r=[];og(e),cg(n,e);let a=e.length;t.forEach(og);for(let c=0;c<t.length;c++)s.push(a),a+=t[c].length,cg(n,t[c]);const o=_w.triangulate(n,s);for(let c=0;c<o.length;c+=3)r.push(o.slice(c,c+3));return r}}function og(i){const e=i.length;e>2&&i[e-1].equals(i[0])&&i.pop()}function cg(i,e){for(let t=0;t<e.length;t++)i.push(e[t].x),i.push(e[t].y)}class vl extends Mn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,a=t/2,o=Math.floor(n),c=Math.floor(s),l=o+1,h=c+1,u=e/o,d=t/c,f=[],p=[],m=[],g=[];for(let A=0;A<h;A++){const _=A*d-a;for(let x=0;x<l;x++){const E=x*u-r;p.push(E,-_,0),m.push(0,0,1),g.push(x/o),g.push(1-A/c)}}for(let A=0;A<c;A++)for(let _=0;_<o;_++){const x=_+l*A,E=_+l*(A+1),S=_+1+l*(A+1),w=_+1+l*A;f.push(x,E,w),f.push(E,S,w)}this.setIndex(f),this.setAttribute("position",new Jt(p,3)),this.setAttribute("normal",new Jt(m,3)),this.setAttribute("uv",new Jt(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vl(e.width,e.height,e.widthSegments,e.heightSegments)}}class To extends ai{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Fe(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Oi extends To{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Je(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return at(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Fe(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Fe(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Fe(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Cl extends ai{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Fe(16777215),this.specular=new Fe(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ww extends ai{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Fe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class vw extends ai{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=qy,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Cw extends ai{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}function Il(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function Iw(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Sw(i){function e(s,r){return i[s]-i[r]}const t=i.length,n=new Array(t);for(let s=0;s!==t;++s)n[s]=s;return n.sort(e),n}function lg(i,e,t){const n=i.length,s=new i.constructor(n);for(let r=0,a=0;a!==n;++r){const o=t[r]*e;for(let c=0;c!==e;++c)s[a++]=i[o+c]}return s}function hg(i,e,t,n){let s=1,r=i[0];for(;r!==void 0&&r[n]===void 0;)r=i[s++];if(r===void 0)return;let a=r[n];if(a!==void 0)if(Array.isArray(a))do a=r[n],a!==void 0&&(e.push(r.time),t.push(...a)),r=i[s++];while(r!==void 0);else if(a.toArray!==void 0)do a=r[n],a!==void 0&&(e.push(r.time),a.toArray(t,t.length)),r=i[s++];while(r!==void 0);else do a=r[n],a!==void 0&&(e.push(r.time),t.push(a)),r=i[s++];while(r!==void 0)}class Ro{constructor(e,t,n,s){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let n=this._cachedIndex,s=t[n],r=t[n-1];e:{t:{let a;n:{i:if(!(e<s)){for(let o=n+2;;){if(s===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(r=s,s=t[++n],e<s)break t}a=t.length;break n}if(!(e>=r)){const o=t[1];e<o&&(n=2,r=o);for(let c=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===c)break;if(s=r,r=t[--n-1],e>=r)break t}a=n,n=0;break n}break e}for(;n<a;){const o=n+a>>>1;e<t[o]?a=o:n=o+1}if(s=t[n],r=t[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(s===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,s)}return this.interpolate_(n,r,e,s)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s;for(let a=0;a!==s;++a)t[a]=n[r+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Mw extends Ro{constructor(e,t,n,s){super(e,t,n,s),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Jr,endingEnd:Jr}}intervalChanged_(e,t,n){const s=this.parameterPositions;let r=e-2,a=e+1,o=s[r],c=s[a];if(o===void 0)switch(this.getSettings_().endingStart){case Zr:r=e,o=2*t-n;break;case Qc:r=s.length-2,o=t+s[r]-s[r+1];break;default:r=e,o=n}if(c===void 0)switch(this.getSettings_().endingEnd){case Zr:a=e,c=2*n-t;break;case Qc:a=1,c=n+s[1]-s[0];break;default:a=e-1,c=t}const l=(n-t)*.5,h=this.valueSize;this._weightPrev=l/(t-o),this._weightNext=l/(c-n),this._offsetPrev=r*h,this._offsetNext=a*h}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=e*o,l=c-o,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(s-t),m=p*p,g=m*p,A=-d*g+2*d*m-d*p,_=(1+d)*g+(-1.5-2*d)*m+(-.5+d)*p+1,x=(-1-f)*g+(1.5+f)*m+.5*p,E=f*g-f*m;for(let S=0;S!==o;++S)r[S]=A*a[h+S]+_*a[l+S]+x*a[c+S]+E*a[u+S];return r}}class ug extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=e*o,l=c-o,h=(n-t)/(s-t),u=1-h;for(let d=0;d!==o;++d)r[d]=a[l+d]*u+a[c+d]*h;return r}}class Bw extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e){return this.copySampleValue_(e-1)}}class vi{constructor(e,t,n,s){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Il(t,this.TimeBufferType),this.values=Il(n,this.ValueBufferType),this.setInterpolation(s||this.DefaultInterpolation)}static toJSON(e){const t=e.constructor;let n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Il(e.times,Array),values:Il(e.values,Array)};const s=e.getInterpolation();s!==e.DefaultInterpolation&&(n.interpolation=s)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Bw(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ug(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Mw(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case fo:t=this.InterpolantFactoryMethodDiscrete;break;case po:t=this.InterpolantFactoryMethodLinear;break;case Iu:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){const n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return console.warn("THREE.KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return fo;case this.InterpolantFactoryMethodLinear:return po;case this.InterpolantFactoryMethodSmooth:return Iu}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){const t=this.times;for(let n=0,s=t.length;n!==s;++n)t[n]+=e}return this}scale(e){if(e!==1){const t=this.times;for(let n=0,s=t.length;n!==s;++n)t[n]*=e}return this}trim(e,t){const n=this.times,s=n.length;let r=0,a=s-1;for(;r!==s&&n[r]<e;)++r;for(;a!==-1&&n[a]>t;)--a;if(++a,r!==0||a!==s){r>=a&&(a=Math.max(a,1),r=a-1);const o=this.getValueSize();this.times=n.slice(r,a),this.values=this.values.slice(r*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,s=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==r;o++){const c=n[o];if(typeof c=="number"&&isNaN(c)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,c),e=!1;break}if(a!==null&&a>c){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,c,a),e=!1;break}a=c}if(s!==void 0&&Iw(s))for(let o=0,c=s.length;o!==c;++o){const l=s[o];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,l),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===Iu,r=e.length-1;let a=1;for(let o=1;o<r;++o){let c=!1;const l=e[o],h=e[o+1];if(l!==h&&(o!==1||l!==e[0]))if(s)c=!0;else{const u=o*n,d=u-n,f=u+n;for(let p=0;p!==n;++p){const m=t[u+p];if(m!==t[d+p]||m!==t[f+p]){c=!0;break}}}if(c){if(o!==a){e[a]=e[o];const u=o*n,d=a*n;for(let f=0;f!==n;++f)t[d+f]=t[u+f]}++a}}if(r>0){e[a]=e[r];for(let o=r*n,c=a*n,l=0;l!==n;++l)t[c+l]=t[o+l];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=this.constructor,s=new n(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}vi.prototype.ValueTypeName="",vi.prototype.TimeBufferType=Float32Array,vi.prototype.ValueBufferType=Float32Array,vi.prototype.DefaultInterpolation=po;class ba extends vi{constructor(e,t,n){super(e,t,n)}}ba.prototype.ValueTypeName="bool",ba.prototype.ValueBufferType=Array,ba.prototype.DefaultInterpolation=fo,ba.prototype.InterpolantFactoryMethodLinear=void 0,ba.prototype.InterpolantFactoryMethodSmooth=void 0;class dg extends vi{constructor(e,t,n,s){super(e,t,n,s)}}dg.prototype.ValueTypeName="color";class fr extends vi{constructor(e,t,n,s){super(e,t,n,s)}}fr.prototype.ValueTypeName="number";class Tw extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=(n-t)/(s-t);let l=e*o;for(let h=l+o;l!==h;l+=4)Yt.slerpFlat(r,0,a,l-o,a,l,c);return r}}class Us extends vi{constructor(e,t,n,s){super(e,t,n,s)}InterpolantFactoryMethodLinear(e){return new Tw(this.times,this.values,this.getValueSize(),e)}}Us.prototype.ValueTypeName="quaternion",Us.prototype.InterpolantFactoryMethodSmooth=void 0;class Ea extends vi{constructor(e,t,n){super(e,t,n)}}Ea.prototype.ValueTypeName="string",Ea.prototype.ValueBufferType=Array,Ea.prototype.DefaultInterpolation=fo,Ea.prototype.InterpolantFactoryMethodLinear=void 0,Ea.prototype.InterpolantFactoryMethodSmooth=void 0;class pr extends vi{constructor(e,t,n,s){super(e,t,n,s)}}pr.prototype.ValueTypeName="vector";class Sl{constructor(e="",t=-1,n=[],s=Su){this.name=e,this.tracks=n,this.duration=t,this.blendMode=s,this.uuid=xi(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,s=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(Fw(n[a]).scale(s));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],n=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let r=0,a=n.length;r!==a;++r)t.push(vi.toJSON(n[r]));return s}static CreateFromMorphTargetSequence(e,t,n,s){const r=t.length,a=[];for(let o=0;o<r;o++){let c=[],l=[];c.push((o+r-1)%r,o,(o+1)%r),l.push(0,1,0);const h=Sw(c);c=lg(c,1,h),l=lg(l,1,h),!s&&c[0]===0&&(c.push(r),l.push(l[0])),a.push(new fr(".morphTargetInfluences["+t[o].name+"]",c,l).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){const s=e;n=s.geometry&&s.geometry.animations||s.animations}for(let s=0;s<n.length;s++)if(n[s].name===t)return n[s];return null}static CreateClipsFromMorphTargetSequences(e,t,n){const s={},r=/^([\w-]*?)([\d]+)$/;for(let o=0,c=e.length;o<c;o++){const l=e[o],h=l.name.match(r);if(h&&h.length>1){const u=h[1];let d=s[u];d||(s[u]=d=[]),d.push(l)}}const a=[];for(const o in s)a.push(this.CreateFromMorphTargetSequence(o,s[o],t,n));return a}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(u,d,f,p,m){if(f.length!==0){const g=[],A=[];hg(f,g,A,p),g.length!==0&&m.push(new u(d,g,A))}},s=[],r=e.name||"default",a=e.fps||30,o=e.blendMode;let c=e.length||-1;const l=e.hierarchy||[];for(let u=0;u<l.length;u++){const d=l[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){const f={};let p;for(p=0;p<d.length;p++)if(d[p].morphTargets)for(let m=0;m<d[p].morphTargets.length;m++)f[d[p].morphTargets[m]]=-1;for(const m in f){const g=[],A=[];for(let _=0;_!==d[p].morphTargets.length;++_){const x=d[p];g.push(x.time),A.push(x.morphTarget===m?1:0)}s.push(new fr(".morphTargetInfluence["+m+"]",g,A))}c=f.length*a}else{const f=".bones["+t[u].name+"]";n(pr,f+".position",d,"pos",s),n(Us,f+".quaternion",d,"rot",s),n(pr,f+".scale",d,"scl",s)}}return s.length===0?null:new this(r,c,s,o)}resetDuration(){const e=this.tracks;let t=0;for(let n=0,s=e.length;n!==s;++n){const r=this.tracks[n];t=Math.max(t,r.times[r.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){const e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());return new this.constructor(this.name,this.duration,e,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function Rw(i){switch(i.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return fr;case"vector":case"vector2":case"vector3":case"vector4":return pr;case"color":return dg;case"quaternion":return Us;case"bool":case"boolean":return ba;case"string":return Ea}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+i)}function Fw(i){if(i.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=Rw(i.type);if(i.times===void 0){const t=[],n=[];hg(i.keys,t,n,"value"),i.times=t,i.values=n}return e.parse!==void 0?e.parse(i):new e(i.name,i.times,i.values,i.interpolation)}const rs={enabled:!1,files:{},add:function(i,e){this.enabled!==!1&&(this.files[i]=e)},get:function(i){if(this.enabled!==!1)return this.files[i]},remove:function(i){delete this.files[i]},clear:function(){this.files={}}};class fg{constructor(e,t,n){const s=this;let r=!1,a=0,o=0,c;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(h){o++,r===!1&&s.onStart!==void 0&&s.onStart(h,a,o),r=!0},this.itemEnd=function(h){a++,s.onProgress!==void 0&&s.onProgress(h,a,o),a===o&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return c?c(h):h},this.setURLModifier=function(h){return c=h,this},this.addHandler=function(h,u){return l.push(h,u),this},this.removeHandler=function(h){const u=l.indexOf(h);return u!==-1&&l.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=l.length;u<d;u+=2){const f=l[u],p=l[u+1];if(f.global&&(f.lastIndex=0),f.test(h))return p}return null}}}const Nw=new fg;class ci{constructor(e){this.manager=e!==void 0?e:Nw,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const n=this;return new Promise(function(s,r){n.load(e,s,t,r)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}ci.DEFAULT_MATERIAL_NAME="__DEFAULT";const as={};class Dw extends Error{constructor(e,t){super(e),this.response=t}}class os extends ci{constructor(e){super(e),this.mimeType="",this.responseType=""}load(e,t,n,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=rs.get(e);if(r!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(r),this.manager.itemEnd(e)},0),r;if(as[e]!==void 0){as[e].push({onLoad:t,onProgress:n,onError:s});return}as[e]=[],as[e].push({onLoad:t,onProgress:n,onError:s});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,c=this.responseType;fetch(a).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;const h=as[e],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,p=f!==0;let m=0;const g=new ReadableStream({start(A){_();function _(){u.read().then(({done:x,value:E})=>{if(x)A.close();else{m+=E.byteLength;const S=new ProgressEvent("progress",{lengthComputable:p,loaded:m,total:f});for(let w=0,I=h.length;w<I;w++){const T=h[w];T.onProgress&&T.onProgress(S)}A.enqueue(E),_()}},x=>{A.error(x)})}}});return new Response(g)}else throw new Dw(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return l.json();default:if(o==="")return l.text();{const u=/charset="?([^;"\s]*)"?/i.exec(o),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return l.arrayBuffer().then(p=>f.decode(p))}}}).then(l=>{rs.add(e,l);const h=as[e];delete as[e];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{const h=as[e];if(h===void 0)throw this.manager.itemError(e),l;delete as[e];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onError&&f.onError(l)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Lw extends ci{constructor(e){super(e)}load(e,t,n,s){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,a=rs.get(e);if(a!==void 0)return r.manager.itemStart(e),setTimeout(function(){t&&t(a),r.manager.itemEnd(e)},0),a;const o=mo("img");function c(){h(),rs.add(e,this),t&&t(this),r.manager.itemEnd(e)}function l(u){h(),s&&s(u),r.manager.itemError(e),r.manager.itemEnd(e)}function h(){o.removeEventListener("load",c,!1),o.removeEventListener("error",l,!1)}return o.addEventListener("load",c,!1),o.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),r.manager.itemStart(e),o.src=e,o}}class Pw extends ci{constructor(e){super(e)}load(e,t,n,s){const r=this,a=new ll,o=new os(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(r.withCredentials),o.load(e,function(c){let l;try{l=r.parse(c)}catch(h){if(s!==void 0)s(h);else{console.error(h);return}}l.image!==void 0?a.image=l.image:l.data!==void 0&&(a.image.width=l.width,a.image.height=l.height,a.image.data=l.data),a.wrapS=l.wrapS!==void 0?l.wrapS:Zn,a.wrapT=l.wrapT!==void 0?l.wrapT:Zn,a.magFilter=l.magFilter!==void 0?l.magFilter:qt,a.minFilter=l.minFilter!==void 0?l.minFilter:qt,a.anisotropy=l.anisotropy!==void 0?l.anisotropy:1,l.colorSpace!==void 0&&(a.colorSpace=l.colorSpace),l.flipY!==void 0&&(a.flipY=l.flipY),l.format!==void 0&&(a.format=l.format),l.type!==void 0&&(a.type=l.type),l.mipmaps!==void 0&&(a.mipmaps=l.mipmaps,a.minFilter=ri),l.mipmapCount===1&&(a.minFilter=qt),l.generateMipmaps!==void 0&&(a.generateMipmaps=l.generateMipmaps),a.needsUpdate=!0,t&&t(a,l)},n,s),a}}class pg extends ci{constructor(e){super(e)}load(e,t,n,s){const r=new nn,a=new Lw(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){r.image=o,r.needsUpdate=!0,t!==void 0&&t(r)},n,s),r}}class Fo extends Tt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Fe(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}class kw extends Fo{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Fe(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const dd=new Re,Ag=new G,gg=new G;class fd{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Je(512,512),this.mapType=cn,this.map=null,this.mapPass=null,this.matrix=new Re,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new rd,this._frameExtents=new Je(1,1),this._viewportCount=1,this._viewports=[new gt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Ag.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ag),gg.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(gg),t.updateMatrixWorld(),dd.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(dd),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(dd)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class Uw extends fd{constructor(){super(new Bn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,n=ea*2*e.angle*this.focus,s=this.mapSize.width/this.mapSize.height,r=e.distance||t.far;(n!==t.fov||s!==t.aspect||r!==t.far)&&(t.fov=n,t.aspect=s,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class mg extends Fo{constructor(e,t,n=0,s=Math.PI/3,r=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.target=new Tt,this.distance=n,this.angle=s,this.penumbra=r,this.decay=a,this.map=null,this.shadow=new Uw}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}const xg=new Re,No=new G,pd=new G;class Ow extends fd{constructor(){super(new Bn(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Je(4,2),this._viewportCount=6,this._viewports=[new gt(2,1,1,1),new gt(0,1,1,1),new gt(3,1,1,1),new gt(1,1,1,1),new gt(3,0,1,1),new gt(1,0,1,1)],this._cubeDirections=[new G(1,0,0),new G(-1,0,0),new G(0,0,1),new G(0,0,-1),new G(0,1,0),new G(0,-1,0)],this._cubeUps=[new G(0,1,0),new G(0,1,0),new G(0,1,0),new G(0,1,0),new G(0,0,1),new G(0,0,-1)]}updateMatrices(e,t=0){const n=this.camera,s=this.matrix,r=e.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),No.setFromMatrixPosition(e.matrixWorld),n.position.copy(No),pd.copy(n.position),pd.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(pd),n.updateMatrixWorld(),s.makeTranslation(-No.x,-No.y,-No.z),xg.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xg)}}class Ml extends Fo{constructor(e,t,n=0,s=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=s,this.shadow=new Ow}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class Ad extends LA{constructor(e=-1,t=1,n=1,s=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,a=n+e,o=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,a=r+l*this.view.width,o-=h*this.view.offsetY,c=o-h*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class Qw extends fd{constructor(){super(new Ad(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class gd extends Fo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.target=new Tt,this.shadow=new Qw}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class bg extends Fo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Ar{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class Gw extends ci{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,n,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,a=rs.get(e);if(a!==void 0){if(r.manager.itemStart(e),a.then){a.then(l=>{t&&t(l),r.manager.itemEnd(e)}).catch(l=>{s&&s(l)});return}return setTimeout(function(){t&&t(a),r.manager.itemEnd(e)},0),a}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader;const c=fetch(e,o).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(l){return rs.add(e,l),t&&t(l),r.manager.itemEnd(e),l}).catch(function(l){s&&s(l),rs.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)});rs.add(e,c),r.manager.itemStart(e)}}class Hw extends Bn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class zw{constructor(e,t,n){this.binding=e,this.valueSize=n;let s,r,a;switch(t){case"quaternion":s=this._slerp,r=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":s=this._select,r=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(n*5);break;default:s=this._lerp,r=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=s,this._mixBufferRegionAdditive=r,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){const n=this.buffer,s=this.valueSize,r=e*s+s;let a=this.cumulativeWeight;if(a===0){for(let o=0;o!==s;++o)n[r+o]=n[o];a=t}else{a+=t;const o=t/a;this._mixBufferRegion(n,r,0,o,s)}this.cumulativeWeight=a}accumulateAdditive(e){const t=this.buffer,n=this.valueSize,s=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,s,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){const t=this.valueSize,n=this.buffer,s=e*t+t,r=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const c=t*this._origIndex;this._mixBufferRegion(n,s,c,1-r,t)}a>0&&this._mixBufferRegionAdditive(n,s,this._addIndex*t,1,t);for(let c=t,l=t+t;c!==l;++c)if(n[c]!==n[c+t]){o.setValue(n,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,s=n*this._origIndex;e.getValue(t,s);for(let r=n,a=s;r!==a;++r)t[r]=t[s+r%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,s,r){if(s>=.5)for(let a=0;a!==r;++a)e[t+a]=e[n+a]}_slerp(e,t,n,s){Yt.slerpFlat(e,t,e,t,e,n,s)}_slerpAdditive(e,t,n,s,r){const a=this._workIndex*r;Yt.multiplyQuaternionsFlat(e,a,e,t,e,n),Yt.slerpFlat(e,t,e,t,e,a,s)}_lerp(e,t,n,s,r){const a=1-s;for(let o=0;o!==r;++o){const c=t+o;e[c]=e[c]*a+e[n+o]*s}}_lerpAdditive(e,t,n,s,r){for(let a=0;a!==r;++a){const o=t+a;e[o]=e[o]+e[n+a]*s}}}const md="\\[\\]\\.:\\/",Vw=new RegExp("["+md+"]","g"),xd="[^"+md+"]",Ww="[^"+md.replace("\\.","")+"]",qw=/((?:WC+[\/:])*)/.source.replace("WC",xd),Kw=/(WCOD+)?/.source.replace("WCOD",Ww),jw=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",xd),Xw=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",xd),Yw=new RegExp("^"+qw+Kw+jw+Xw+"$"),Jw=["material","materials","bones","map"];class Zw{constructor(e,t,n){const s=n||_t.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,s=this._bindings[n];s!==void 0&&s.getValue(e,t)}setValue(e,t){const n=this._bindings;for(let s=this._targetGroup.nCachedObjects_,r=n.length;s!==r;++s)n[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}}class _t{constructor(e,t,n){this.path=t,this.parsedPath=n||_t.parseTrackName(t),this.node=_t.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new _t.Composite(e,t,n):new _t(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Vw,"")}static parseTrackName(e){const t=Yw.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=n.nodeName&&n.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const r=n.nodeName.substring(s+1);Jw.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,s),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){const n=function(r){for(let a=0;a<r.length;a++){const o=r[a];if(o.name===t||o.uuid===t)return o;const c=n(o.children);if(c)return c}return null},s=n(e.children);if(s)return s}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)e[t++]=n[s]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node;const t=this.parsedPath,n=t.objectName,s=t.propertyName;let r=t.propertyIndex;if(e||(e=_t.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let l=t.objectIndex;switch(n){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===l){l=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(l!==void 0){if(e[l]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[l]}}const a=e[s];if(a===void 0){const l=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+l+"."+s+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?o=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(r!==void 0){if(s==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[r]!==void 0&&(r=e.morphTargetDictionary[r])}c=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=r}else a.fromArray!==void 0&&a.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(c=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=s;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}_t.Composite=Zw,_t.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},_t.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},_t.prototype.GetterByBindingType=[_t.prototype._getValue_direct,_t.prototype._getValue_array,_t.prototype._getValue_arrayElement,_t.prototype._getValue_toArray],_t.prototype.SetterByBindingTypeAndVersioning=[[_t.prototype._setValue_direct,_t.prototype._setValue_direct_setNeedsUpdate,_t.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_array,_t.prototype._setValue_array_setNeedsUpdate,_t.prototype._setValue_array_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_arrayElement,_t.prototype._setValue_arrayElement_setNeedsUpdate,_t.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_fromArray,_t.prototype._setValue_fromArray_setNeedsUpdate,_t.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class $w{constructor(e,t,n=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=s;const r=t.tracks,a=r.length,o=new Array(a),c={endingStart:Jr,endingEnd:Jr};for(let l=0;l!==a;++l){const h=r[l].createInterpolant(null);o[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=aA,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){const s=this._clip.duration,r=e._clip.duration,a=r/s,o=s/r;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const s=this._mixer,r=s.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const c=o.parameterPositions,l=o.sampleValues;return c[0]=r,c[1]=r+n,l[0]=e/a,l[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,s){if(!this.enabled){this._updateWeight(e);return}const r=this._startTime;if(r!==null){const c=(e-r)*n;c<0||n===0?t=0:(this._startTime=null,t=n*c)}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case Vy:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(a),l[h].accumulateAdditive(o);break;case Su:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(a),l[h].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(n!==null){const s=n.evaluate(e)[0];t*=s,e>n.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(n!==null){const s=n.evaluate(e)[0];t*=s,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let s=this.time+e,r=this._loopCount;const a=n===zy;if(e===0)return r===-1?s:a&&(r&1)===1?t-s:s;if(n===rA){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1&&(e>=0?(r=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,r+=Math.abs(o);const c=this.repetitions-r;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(c===1){const l=e<0;this._setEndings(l,!l,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(a&&(r&1)===1)return t-s}return s}_setEndings(e,t,n){const s=this._interpolantSettings;n?(s.endingStart=Zr,s.endingEnd=Zr):(e?s.endingStart=this.zeroSlopeAtStart?Zr:Jr:s.endingStart=Qc,t?s.endingEnd=this.zeroSlopeAtEnd?Zr:Jr:s.endingEnd=Qc)}_scheduleFading(e,t,n){const s=this._mixer,r=s.time;let a=this._weightInterpolant;a===null&&(a=s._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,c=a.sampleValues;return o[0]=r,c[0]=t,o[1]=r+e,c[1]=n,this}}const ev=new Float32Array(1);class Eg extends Ms{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,s=e._clip.tracks,r=s.length,a=e._propertyBindings,o=e._interpolants,c=n.uuid,l=this._bindingsByRootAndName;let h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==r;++u){const d=s[u],f=d.name;let p=h[f];if(p!==void 0)++p.referenceCount,a[u]=p;else{if(p=a[u],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,c,f));continue}const m=t&&t._propertyBindings[u].binding.parsedPath;p=new zw(_t.create(n,f,m),d.ValueTypeName,d.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,c,f),a[u]=p}o[u].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const n=(e._localRoot||this._root).uuid,s=e._clip.uuid,r=this._actionsByClip[s];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,s,n)}const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];r.useCount++===0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];--r.useCount===0&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){const s=this._actions,r=this._actionsByClip;let a=r[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=a;else{const o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=s.length,s.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){const t=this._actions,n=t[t.length-1],s=e._cacheIndex;n._cacheIndex=s,t[s]=n,t.pop(),e._cacheIndex=null;const r=e._clip.uuid,a=this._actionsByClip,o=a[r],c=o.knownActions,l=c[c.length-1],h=e._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),e._byClipCacheIndex=null;const u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],c.length===0&&delete a[r],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];--r.referenceCount===0&&this._removeInactiveBinding(r)}}_lendAction(e){const t=this._actions,n=e._cacheIndex,s=this._nActiveActions++,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){const t=this._actions,n=e._cacheIndex,s=--this._nActiveActions,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){const s=this._bindingsByRootAndName,r=this._bindings;let a=s[t];a===void 0&&(a={},s[t]=a),a[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){const t=this._bindings,n=e.binding,s=n.rootNode.uuid,r=n.path,a=this._bindingsByRootAndName,o=a[s],c=t[t.length-1],l=e._cacheIndex;c._cacheIndex=l,t[l]=c,t.pop(),delete o[r],Object.keys(o).length===0&&delete a[s]}_lendBinding(e){const t=this._bindings,n=e._cacheIndex,s=this._nActiveBindings++,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){const t=this._bindings,n=e._cacheIndex,s=--this._nActiveBindings,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let n=e[t];return n===void 0&&(n=new ug(new Float32Array(2),new Float32Array(2),1,ev),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){const t=this._controlInterpolants,n=e.__cacheIndex,s=--this._nActiveControlInterpolants,r=t[s];e.__cacheIndex=s,t[s]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){const s=t||this._root,r=s.uuid;let a=typeof e=="string"?Sl.findByName(s,e):e;const o=a!==null?a.uuid:e,c=this._actionsByClip[o];let l=null;if(n===void 0&&(a!==null?n=a.blendMode:n=Su),c!==void 0){const u=c.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;l=c.knownActions[0],a===null&&(a=l._clip)}if(a===null)return null;const h=new $w(this,a,t,n);return this._bindAction(h,l),this._addInactiveAction(h,o,r),h}existingAction(e,t){const n=t||this._root,s=n.uuid,r=typeof e=="string"?Sl.findByName(n,e):e,a=r?r.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[s]||null}stopAllAction(){const e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,s=this.time+=e,r=Math.sign(e),a=this._accuIndex^=1;for(let l=0;l!==n;++l)t[l]._update(s,e,r,a);const o=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)o[l].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,n=e.uuid,s=this._actionsByClip,r=s[n];if(r!==void 0){const a=r.knownActions;for(let o=0,c=a.length;o!==c;++o){const l=a[o];this._deactivateAction(l);const h=l._cacheIndex,u=t[t.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=h,t[h]=u,t.pop(),this._removeInactiveBindingsForAction(l)}delete s[n]}}uncacheRoot(e){const t=e.uuid,n=this._actionsByClip;for(const a in n){const o=n[a].actionByRoot,c=o[t];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}const s=this._bindingsByRootAndName,r=s[t];if(r!==void 0)for(const a in r){const o=r[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){const n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}}class yg{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=at(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(at(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const Os=new G,Bl=new Re,bd=new Re;class tv extends xl{constructor(e){const t=_g(e),n=new Mn,s=[],r=[],a=new Fe(0,0,1),o=new Fe(0,1,0);for(let l=0;l<t.length;l++){const h=t[l];h.parent&&h.parent.isBone&&(s.push(0,0,0),s.push(0,0,0),r.push(a.r,a.g,a.b),r.push(o.r,o.g,o.b))}n.setAttribute("position",new Jt(s,3)),n.setAttribute("color",new Jt(r,3));const c=new ma({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,c),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){const t=this.bones,n=this.geometry,s=n.getAttribute("position");bd.copy(this.root.matrixWorld).invert();for(let r=0,a=0;r<t.length;r++){const o=t[r];o.parent&&o.parent.isBone&&(Bl.multiplyMatrices(bd,o.matrixWorld),Os.setFromMatrixPosition(Bl),s.setXYZ(a,Os.x,Os.y,Os.z),Bl.multiplyMatrices(bd,o.parent.matrixWorld),Os.setFromMatrixPosition(Bl),s.setXYZ(a+1,Os.x,Os.y,Os.z),a+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}}function _g(i){const e=[];i.isBone===!0&&e.push(i);for(let t=0;t<i.children.length;t++)e.push(..._g(i.children[t]));return e}class nv extends xl{constructor(e=10,t=10,n=4473924,s=8947848){n=new Fe(n),s=new Fe(s);const r=t/2,a=e/t,o=e/2,c=[],l=[];for(let d=0,f=0,p=-o;d<=t;d++,p+=a){c.push(-o,0,p,o,0,p),c.push(p,0,-o,p,0,o);const m=d===r?n:s;m.toArray(l,f),f+=3,m.toArray(l,f),f+=3,m.toArray(l,f),f+=3,m.toArray(l,f),f+=3}const h=new Mn;h.setAttribute("position",new Jt(c,3)),h.setAttribute("color",new Jt(l,3));const u=new ma({vertexColors:!0,toneMapped:!1});super(h,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class wg extends xl{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Mn;s.setAttribute("position",new Jt(t,3)),s.setAttribute("color",new Jt(n,3));const r=new ma({vertexColors:!0,toneMapped:!1});super(s,r),this.type="AxesHelper"}setColors(e,t,n){const s=new Fe,r=this.geometry.attributes.color.array;return s.set(e),s.toArray(r,0),s.toArray(r,3),s.set(t),s.toArray(r,6),s.toArray(r,9),s.set(n),s.toArray(r,12),s.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class iv extends Ms{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){console.warn("THREE.Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function vg(i,e,t,n){const s=sv(n);switch(t){case nA:return i*e;case Xi:return i*e/s.components*s.byteLength;case ru:return i*e/s.components*s.byteLength;case ar:return i*e*2/s.components*s.byteLength;case au:return i*e*2/s.components*s.byteLength;case iA:return i*e*3/s.components*s.byteLength;case hn:return i*e*4/s.components*s.byteLength;case ou:return i*e*4/s.components*s.byteLength;case Fc:case oo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Nc:case co:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case cu:case lu:return Math.max(i,16)*Math.max(e,8)/4;case Dc:case Lc:return Math.max(i,8)*Math.max(e,8)/2;case Pc:case kc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Uc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case lo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case hu:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case uu:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case du:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case ho:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case fu:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case pu:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case Au:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case gu:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case mu:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case xu:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case bu:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Eu:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case yu:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case uo:case _u:case Oc:return Math.ceil(i/4)*Math.ceil(e/4)*16;case sA:case wu:return Math.ceil(i/4)*Math.ceil(e/4)*8;case vu:case Cu:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function sv(i){switch(i){case cn:case $p:return{byteLength:1,components:1};case io:case eA:case kn:return{byteLength:2,components:1};case iu:case su:return{byteLength:2,components:4};case rr:case nu:case ln:return{byteLength:4,components:1};case tA:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Ic}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Ic);function Cg(){let i=null,e=!1,t=null,n=null;function s(r,a){t(r,a),n=i.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(n=i.requestAnimationFrame(s),e=!0)},stop:function(){i.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){i=r}}}function rv(i){const e=new WeakMap;function t(o,c){const l=o.array,h=o.usage,u=l.byteLength,d=i.createBuffer();i.bindBuffer(c,d),i.bufferData(c,l,h),o.onUploadCallback();let f;if(l instanceof Float32Array)f=i.FLOAT;else if(l instanceof Uint16Array)o.isFloat16BufferAttribute?f=i.HALF_FLOAT:f=i.UNSIGNED_SHORT;else if(l instanceof Int16Array)f=i.SHORT;else if(l instanceof Uint32Array)f=i.UNSIGNED_INT;else if(l instanceof Int32Array)f=i.INT;else if(l instanceof Int8Array)f=i.BYTE;else if(l instanceof Uint8Array)f=i.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)f=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:d,type:f,bytesPerElement:l.BYTES_PER_ELEMENT,version:o.version,size:u}}function n(o,c,l){const h=c.array,u=c.updateRanges;if(i.bindBuffer(l,o),u.length===0)i.bufferSubData(l,0,h);else{u.sort((f,p)=>f.start-p.start);let d=0;for(let f=1;f<u.length;f++){const p=u[d],m=u[f];m.start<=p.start+p.count+1?p.count=Math.max(p.count,m.start+m.count-p.start):(++d,u[d]=m)}u.length=d+1;for(let f=0,p=u.length;f<p;f++){const m=u[f];i.bufferSubData(l,m.start*h.BYTES_PER_ELEMENT,h,m.start,m.count)}c.clearUpdateRanges()}c.onUploadCallback()}function s(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function r(o){o.isInterleavedBufferAttribute&&(o=o.data);const c=e.get(o);c&&(i.deleteBuffer(c.buffer),e.delete(o))}function a(o,c){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){const h=e.get(o);(!h||h.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}const l=e.get(o);if(l===void 0)e.set(o,t(o,c));else if(l.version<o.version){if(l.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(l.buffer,o,c),l.version=o.version}}return{get:s,remove:r,update:a}}var av=`#ifdef USE_ALPHAHASH
+ `},s=new da(5,5,5),r=new Ls({name:"CubemapFromEquirect",uniforms:fa(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ln,blending:Cs});r.uniforms.tEquirect.value=t;const a=new Zt(s,r),o=t.minFilter;return t.minFilter===ri&&(t.minFilter=qt),new V_(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,s);e.setRenderTarget(r)}}class ss extends Tt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const q_={type:"move"};class Zu{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ss,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new ss,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new G,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new G),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ss,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new G,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new G),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const m of e.hand.values()){const g=t.getJointPose(m,n),A=this._getHandJoint(l,m);g!==null&&(A.matrix.fromArray(g.transform.matrix),A.matrix.decompose(A.position,A.rotation,A.scale),A.matrixWorldNeedsUpdate=!0,A.jointRadius=g.radius),A.visible=g!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(q_)))}return o!==null&&(o.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new ss;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class $u extends Tt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new dn,this.environmentIntensity=1,this.environmentRotation=new dn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class K_{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Bu,this.updateRanges=[],this.version=0,this.uuid=xi()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let s=0,r=this.stride;s<r;s++)this.array[e+s]=t.array[n+s];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=xi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=xi()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const On=new G;class ed{constructor(e,t,n,s=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=s}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)On.fromBufferAttribute(this,t),On.applyMatrix4(e),this.setXYZ(t,On.x,On.y,On.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)On.fromBufferAttribute(this,t),On.applyNormalMatrix(e),this.setXYZ(t,On.x,On.y,On.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)On.fromBufferAttribute(this,t),On.transformDirection(e),this.setXYZ(t,On.x,On.y,On.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=bi(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Bt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Bt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=bi(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=bi(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=bi(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=bi(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Bt(t,this.array),n=Bt(n,this.array),s=Bt(s,this.array),r=Bt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=s,this.data.array[e+3]=r,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const s=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[s+r])}return new Sn(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new ed(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const s=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[s+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}const OA=new G,QA=new gt,GA=new gt,j_=new G,HA=new Re,ol=new G,td=new Ui,zA=new Re,nd=new Eo;class VA extends Zt{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Yp,this.bindMatrix=new Re,this.bindMatrixInverse=new Re,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new ki),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ol),this.boundingBox.expandByPoint(ol)}computeBoundingSphere(){const e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Ui),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ol),this.boundingSphere.expandByPoint(ol)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const n=this.material,s=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),td.copy(this.boundingSphere),td.applyMatrix4(s),e.ray.intersectsSphere(td)!==!1&&(zA.copy(s).invert(),nd.copy(e.ray).applyMatrix4(zA),!(this.boundingBox!==null&&nd.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,nd)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const e=new gt,t=this.geometry.attributes.skinWeight;for(let n=0,s=t.count;n<s;n++){e.fromBufferAttribute(t,n);const r=1/e.manhattanLength();r!==1/0?e.multiplyScalar(r):e.set(1,0,0,0),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===Yp?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===Gy?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const n=this.skeleton,s=this.geometry;QA.fromBufferAttribute(s.attributes.skinIndex,e),GA.fromBufferAttribute(s.attributes.skinWeight,e),OA.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let r=0;r<4;r++){const a=GA.getComponent(r);if(a!==0){const o=QA.getComponent(r);HA.multiplyMatrices(n.bones[o].matrixWorld,n.boneInverses[o]),t.addScaledVector(j_.copy(OA).applyMatrix4(HA),a)}}return t.applyMatrix4(this.bindMatrixInverse)}}class cl extends Tt{constructor(){super(),this.isBone=!0,this.type="Bone"}}class ll extends nn{constructor(e=null,t=1,n=1,s,r,a,o,c,l=Pn,h=Pn,u,d){super(null,a,o,c,l,h,s,r,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const WA=new Re,X_=new Re;class hl{constructor(e=[],t=[]){this.uuid=xi(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,s=this.bones.length;n<s;n++)this.boneInverses.push(new Re)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const n=new Re;this.bones[e]&&n.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(n)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const n=this.bones[e];n&&n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const n=this.bones[e];n&&(n.parent&&n.parent.isBone?(n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld)):n.matrix.copy(n.matrixWorld),n.matrix.decompose(n.position,n.quaternion,n.scale))}}update(){const e=this.bones,t=this.boneInverses,n=this.boneMatrices,s=this.boneTexture;for(let r=0,a=e.length;r<a;r++){const o=e[r]?e[r].matrixWorld:X_;WA.multiplyMatrices(o,t[r]),WA.toArray(n,r*16)}s!==null&&(s.needsUpdate=!0)}clone(){return new hl(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const n=new ll(t,e,e,hn,ln);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){const s=this.bones[t];if(s.name===e)return s}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,s=e.bones.length;n<s;n++){const r=e.bones[n];let a=t[r];a===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",r),a=new cl),this.bones.push(a),this.boneInverses.push(new Re().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){const e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,n=this.boneInverses;for(let s=0,r=t.length;s<r;s++){const a=t[s];e.bones.push(a.uuid);const o=n[s];e.boneInverses.push(o.toArray())}return e}}class id extends Sn{constructor(e,t,n,s=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const ga=new Re,qA=new Re,ul=[],KA=new ki,Y_=new Re,wo=new Zt,vo=new Ui;class jA extends Zt{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new id(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let s=0;s<n;s++)this.setMatrixAt(s,Y_)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new ki),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ga),KA.copy(e.boundingBox).applyMatrix4(ga),this.boundingBox.union(KA)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Ui),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ga),vo.copy(e.boundingSphere).applyMatrix4(ga),this.boundingSphere.union(vo)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const n=t.morphTargetInfluences,s=this.morphTexture.source.data.data,r=n.length+1,a=e*r+1;for(let o=0;o<n.length;o++)n[o]=s[a+o]}raycast(e,t){const n=this.matrixWorld,s=this.count;if(wo.geometry=this.geometry,wo.material=this.material,wo.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),vo.copy(this.boundingSphere),vo.applyMatrix4(n),e.ray.intersectsSphere(vo)!==!1))for(let r=0;r<s;r++){this.getMatrixAt(r,ga),qA.multiplyMatrices(n,ga),wo.matrixWorld=qA,wo.raycast(e,ul);for(let a=0,o=ul.length;a<o;a++){const c=ul[a];c.instanceId=r,c.object=this,t.push(c)}ul.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new id(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){const n=t.morphTargetInfluences,s=n.length+1;this.morphTexture===null&&(this.morphTexture=new ll(new Float32Array(s*this.count),s,this.count,Xi,ln));const r=this.morphTexture.source.data.data;let a=0;for(let l=0;l<n.length;l++)a+=n[l];const o=this.geometry.morphTargetsRelative?1:1-a,c=s*e;r[c]=o,r.set(n,c+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const sd=new G,J_=new G,Z_=new ot;class ks{constructor(e=new G(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=sd.subVectors(n,t).cross(J_.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(sd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Z_.getNormalMatrix(e),s=this.coplanarPoint(sd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const ur=new Ui,dl=new G;class rd{constructor(e=new ks,t=new ks,n=new ks,s=new ks,r=new ks,a=new ks){this.planes=[e,t,n,s,r,a]}set(e,t,n,s,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(s),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Yi){const n=this.planes,s=e.elements,r=s[0],a=s[1],o=s[2],c=s[3],l=s[4],h=s[5],u=s[6],d=s[7],f=s[8],p=s[9],m=s[10],g=s[11],A=s[12],_=s[13],x=s[14],E=s[15];if(n[0].setComponents(c-r,d-l,g-f,E-A).normalize(),n[1].setComponents(c+r,d+l,g+f,E+A).normalize(),n[2].setComponents(c+a,d+h,g+p,E+_).normalize(),n[3].setComponents(c-a,d-h,g-p,E-_).normalize(),n[4].setComponents(c-o,d-u,g-m,E-x).normalize(),t===Yi)n[5].setComponents(c+o,d+u,g+m,E+x).normalize();else if(t===zc)n[5].setComponents(o,u,m,x).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ur.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ur.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ur)}intersectsSprite(e){return ur.center.set(0,0,0),ur.radius=.7071067811865476,ur.applyMatrix4(e.matrixWorld),this.intersectsSphere(ur)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(dl.x=s.normal.x>0?e.max.x:e.min.x,dl.y=s.normal.y>0?e.max.y:e.min.y,dl.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(dl)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class ma extends ai{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Fe(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const fl=new G,pl=new G,XA=new Re,Co=new Eo,Al=new Ui,ad=new G,YA=new G;class gl extends Tt{constructor(e=new Mn,t=new ma){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let s=1,r=t.count;s<r;s++)fl.fromBufferAttribute(t,s-1),pl.fromBufferAttribute(t,s),n[s]=n[s-1],n[s]+=fl.distanceTo(pl);e.setAttribute("lineDistance",new Jt(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Al.copy(n.boundingSphere),Al.applyMatrix4(s),Al.radius+=r,e.ray.intersectsSphere(Al)===!1)return;XA.copy(s).invert(),Co.copy(e.ray).applyMatrix4(XA);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=o*o,l=this.isLineSegments?2:1,h=n.index,d=n.attributes.position;if(h!==null){const f=Math.max(0,a.start),p=Math.min(h.count,a.start+a.count);for(let m=f,g=p-1;m<g;m+=l){const A=h.getX(m),_=h.getX(m+1),x=ml(this,e,Co,c,A,_,m);x&&t.push(x)}if(this.isLineLoop){const m=h.getX(p-1),g=h.getX(f),A=ml(this,e,Co,c,m,g,p-1);A&&t.push(A)}}else{const f=Math.max(0,a.start),p=Math.min(d.count,a.start+a.count);for(let m=f,g=p-1;m<g;m+=l){const A=ml(this,e,Co,c,m,m+1,m);A&&t.push(A)}if(this.isLineLoop){const m=ml(this,e,Co,c,p-1,f,p-1);m&&t.push(m)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function ml(i,e,t,n,s,r,a){const o=i.geometry.attributes.position;if(fl.fromBufferAttribute(o,s),pl.fromBufferAttribute(o,r),t.distanceSqToSegment(fl,pl,ad,YA)>n)return;ad.applyMatrix4(i.matrixWorld);const l=e.ray.origin.distanceTo(ad);if(!(l<e.near||l>e.far))return{distance:l,point:YA.clone().applyMatrix4(i.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:i}}const JA=new G,ZA=new G;class xl extends gl{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[];for(let s=0,r=t.count;s<r;s+=2)JA.fromBufferAttribute(t,s),ZA.fromBufferAttribute(t,s+1),n[s]=s===0?0:n[s-1],n[s+1]=n[s]+JA.distanceTo(ZA);e.setAttribute("lineDistance",new Jt(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class $_ extends gl{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class od extends ai{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Fe(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const $A=new Re,cd=new Eo,bl=new Ui,El=new G;class ew extends Tt{constructor(e=new Mn,t=new od){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const n=this.geometry,s=this.matrixWorld,r=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),bl.copy(n.boundingSphere),bl.applyMatrix4(s),bl.radius+=r,e.ray.intersectsSphere(bl)===!1)return;$A.copy(s).invert(),cd.copy(e.ray).applyMatrix4($A);const o=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=o*o,l=n.index,u=n.attributes.position;if(l!==null){const d=Math.max(0,a.start),f=Math.min(l.count,a.start+a.count);for(let p=d,m=f;p<m;p++){const g=l.getX(p);El.fromBufferAttribute(u,g),eg(El,g,c,s,e,t,this)}}else{const d=Math.max(0,a.start),f=Math.min(u.count,a.start+a.count);for(let p=d,m=f;p<m;p++)El.fromBufferAttribute(u,p),eg(El,p,c,s,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function eg(i,e,t,n,s,r,a){const o=cd.distanceSqToPoint(i);if(o<t){const c=new G;cd.closestPointToPoint(i,c),c.applyMatrix4(n);const l=s.ray.origin.distanceTo(c);if(l<s.near||l>s.far)return;r.push({distance:l,distanceToRay:Math.sqrt(o),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class yl extends nn{constructor(e,t,n,s,r,a,o,c,l,h,u,d){super(null,a,o,c,l,h,s,r,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class tw extends yl{constructor(e,t,n,s,r,a){super(e,t,n,r,a),this.isCompressedArrayTexture=!0,this.image.depth=s,this.wrapR=Zn,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class nw extends yl{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,sr),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class tg extends nn{constructor(e,t,n=rr,s,r,a,o=Pn,c=Pn,l,h=ro){if(h!==ro&&h!==ao)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,s,r,a,o,c,h,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Fu(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class iw{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,s=this.getPoint(0),r=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),r+=n.distanceTo(s),t.push(r),s=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let s=0;const r=n.length;let a;t?a=t:a=e*n[r-1];let o=0,c=r-1,l;for(;o<=c;)if(s=Math.floor(o+(c-o)/2),l=n[s]-a,l<0)o=s+1;else if(l>0)c=s-1;else{c=s;break}if(s=c,n[s]===a)return s/(r-1);const h=n[s],d=n[s+1]-h,f=(a-h)/d;return(s+f)/(r-1)}getTangent(e,t){let s=e-1e-4,r=e+1e-4;s<0&&(s=0),r>1&&(r=1);const a=this.getPoint(s),o=this.getPoint(r),c=t||(a.isVector2?new Je:new G);return c.copy(o).sub(a).normalize(),c}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new G,s=[],r=[],a=[],o=new G,c=new Re;for(let f=0;f<=e;f++){const p=f/e;s[f]=this.getTangentAt(p,new G)}r[0]=new G,a[0]=new G;let l=Number.MAX_VALUE;const h=Math.abs(s[0].x),u=Math.abs(s[0].y),d=Math.abs(s[0].z);h<=l&&(l=h,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),d<=l&&n.set(0,0,1),o.crossVectors(s[0],n).normalize(),r[0].crossVectors(s[0],o),a[0].crossVectors(s[0],r[0]);for(let f=1;f<=e;f++){if(r[f]=r[f-1].clone(),a[f]=a[f-1].clone(),o.crossVectors(s[f-1],s[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(at(s[f-1].dot(s[f]),-1,1));r[f].applyMatrix4(c.makeRotationAxis(o,p))}a[f].crossVectors(s[f],r[f])}if(t===!0){let f=Math.acos(at(r[0].dot(r[e]),-1,1));f/=e,s[0].dot(o.crossVectors(r[0],r[e]))>0&&(f=-f);for(let p=1;p<=e;p++)r[p].applyMatrix4(c.makeRotationAxis(s[p],f*p)),a[p].crossVectors(s[p],r[p])}return{tangents:s,normals:r,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}function sw(i,e,t=2){const n=e&&e.length,s=n?e[0]*t:i.length;let r=ng(i,0,s,t,!0);const a=[];if(!r||r.next===r.prev)return a;let o,c,l;if(n&&(r=lw(i,e,r,t)),i.length>80*t){o=1/0,c=1/0;let h=-1/0,u=-1/0;for(let d=t;d<s;d+=t){const f=i[d],p=i[d+1];f<o&&(o=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-o,u-c),l=l!==0?32767/l:0}return Io(r,a,t,o,c,l,0),a}function ng(i,e,t,n,s){let r;if(s===Ew(i,e,t,n)>0)for(let a=e;a<t;a+=n)r=ag(a/n|0,i[a],i[a+1],r);else for(let a=t-n;a>=e;a-=n)r=ag(a/n|0,i[a],i[a+1],r);return r&&xa(r,r.next)&&(Bo(r),r=r.next),r}function dr(i,e){if(!i)return i;e||(e=i);let t=i,n;do if(n=!1,!t.steiner&&(xa(t,t.next)||zt(t.prev,t,t.next)===0)){if(Bo(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function Io(i,e,t,n,s,r,a){if(!i)return;!a&&r&&pw(i,n,s,r);let o=i;for(;i.prev!==i.next;){const c=i.prev,l=i.next;if(r?aw(i,n,s,r):rw(i)){e.push(c.i,i.i,l.i),Bo(i),i=l.next,o=l.next;continue}if(i=l,i===o){a?a===1?(i=ow(dr(i),e),Io(i,e,t,n,s,r,2)):a===2&&cw(i,e,t,n,s,r):Io(dr(i),e,t,n,s,r,1);break}}}function rw(i){const e=i.prev,t=i,n=i.next;if(zt(e,t,n)>=0)return!1;const s=e.x,r=t.x,a=n.x,o=e.y,c=t.y,l=n.y,h=Math.min(s,r,a),u=Math.min(o,c,l),d=Math.max(s,r,a),f=Math.max(o,c,l);let p=n.next;for(;p!==e;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&So(s,o,r,c,a,l,p.x,p.y)&&zt(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function aw(i,e,t,n){const s=i.prev,r=i,a=i.next;if(zt(s,r,a)>=0)return!1;const o=s.x,c=r.x,l=a.x,h=s.y,u=r.y,d=a.y,f=Math.min(o,c,l),p=Math.min(h,u,d),m=Math.max(o,c,l),g=Math.max(h,u,d),A=ld(f,p,e,t,n),_=ld(m,g,e,t,n);let x=i.prevZ,E=i.nextZ;for(;x&&x.z>=A&&E&&E.z<=_;){if(x.x>=f&&x.x<=m&&x.y>=p&&x.y<=g&&x!==s&&x!==a&&So(o,h,c,u,l,d,x.x,x.y)&&zt(x.prev,x,x.next)>=0||(x=x.prevZ,E.x>=f&&E.x<=m&&E.y>=p&&E.y<=g&&E!==s&&E!==a&&So(o,h,c,u,l,d,E.x,E.y)&&zt(E.prev,E,E.next)>=0))return!1;E=E.nextZ}for(;x&&x.z>=A;){if(x.x>=f&&x.x<=m&&x.y>=p&&x.y<=g&&x!==s&&x!==a&&So(o,h,c,u,l,d,x.x,x.y)&&zt(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;E&&E.z<=_;){if(E.x>=f&&E.x<=m&&E.y>=p&&E.y<=g&&E!==s&&E!==a&&So(o,h,c,u,l,d,E.x,E.y)&&zt(E.prev,E,E.next)>=0)return!1;E=E.nextZ}return!0}function ow(i,e){let t=i;do{const n=t.prev,s=t.next.next;!xa(n,s)&&sg(n,t,t.next,s)&&Mo(n,s)&&Mo(s,n)&&(e.push(n.i,t.i,s.i),Bo(t),Bo(t.next),t=i=s),t=t.next}while(t!==i);return dr(t)}function cw(i,e,t,n,s,r){let a=i;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&mw(a,o)){let c=rg(a,o);a=dr(a,a.next),c=dr(c,c.next),Io(a,e,t,n,s,r,0),Io(c,e,t,n,s,r,0);return}o=o.next}a=a.next}while(a!==i)}function lw(i,e,t,n){const s=[];for(let r=0,a=e.length;r<a;r++){const o=e[r]*n,c=r<a-1?e[r+1]*n:i.length,l=ng(i,o,c,n,!1);l===l.next&&(l.steiner=!0),s.push(gw(l))}s.sort(hw);for(let r=0;r<s.length;r++)t=uw(s[r],t);return t}function hw(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const n=(i.next.y-i.y)/(i.next.x-i.x),s=(e.next.y-e.y)/(e.next.x-e.x);t=n-s}return t}function uw(i,e){const t=dw(i,e);if(!t)return e;const n=rg(t,i);return dr(n,n.next),dr(t,t.next)}function dw(i,e){let t=e;const n=i.x,s=i.y;let r=-1/0,a;if(xa(i,t))return t;do{if(xa(i,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const u=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=n&&u>r&&(r=u,a=t.x<t.next.x?t:t.next,u===n))return a}t=t.next}while(t!==e);if(!a)return null;const o=a,c=a.x,l=a.y;let h=1/0;t=a;do{if(n>=t.x&&t.x>=c&&n!==t.x&&ig(s<l?n:r,s,c,l,s<l?r:n,s,t.x,t.y)){const u=Math.abs(s-t.y)/(n-t.x);Mo(t,i)&&(u<h||u===h&&(t.x>a.x||t.x===a.x&&fw(a,t)))&&(a=t,h=u)}t=t.next}while(t!==o);return a}function fw(i,e){return zt(i.prev,i,e.prev)<0&&zt(e.next,i,i.next)<0}function pw(i,e,t,n){let s=i;do s.z===0&&(s.z=ld(s.x,s.y,e,t,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==i);s.prevZ.nextZ=null,s.prevZ=null,Aw(s)}function Aw(i){let e,t=1;do{let n=i,s;i=null;let r=null;for(e=0;n;){e++;let a=n,o=0;for(let l=0;l<t&&(o++,a=a.nextZ,!!a);l++);let c=t;for(;o>0||c>0&&a;)o!==0&&(c===0||!a||n.z<=a.z)?(s=n,n=n.nextZ,o--):(s=a,a=a.nextZ,c--),r?r.nextZ=s:i=s,s.prevZ=r,r=s;n=a}r.nextZ=null,t*=2}while(e>1);return i}function ld(i,e,t,n,s){return i=(i-t)*s|0,e=(e-n)*s|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function gw(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function ig(i,e,t,n,s,r,a,o){return(s-a)*(e-o)>=(i-a)*(r-o)&&(i-a)*(n-o)>=(t-a)*(e-o)&&(t-a)*(r-o)>=(s-a)*(n-o)}function So(i,e,t,n,s,r,a,o){return!(i===a&&e===o)&&ig(i,e,t,n,s,r,a,o)}function mw(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!xw(i,e)&&(Mo(i,e)&&Mo(e,i)&&bw(i,e)&&(zt(i.prev,i,e.prev)||zt(i,e.prev,e))||xa(i,e)&&zt(i.prev,i,i.next)>0&&zt(e.prev,e,e.next)>0)}function zt(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function xa(i,e){return i.x===e.x&&i.y===e.y}function sg(i,e,t,n){const s=wl(zt(i,e,t)),r=wl(zt(i,e,n)),a=wl(zt(t,n,i)),o=wl(zt(t,n,e));return!!(s!==r&&a!==o||s===0&&_l(i,t,e)||r===0&&_l(i,n,e)||a===0&&_l(t,i,n)||o===0&&_l(t,e,n))}function _l(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function wl(i){return i>0?1:i<0?-1:0}function xw(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&sg(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function Mo(i,e){return zt(i.prev,i,i.next)<0?zt(i,e,i.next)>=0&&zt(i,i.prev,e)>=0:zt(i,e,i.prev)<0||zt(i,i.next,e)<0}function bw(i,e){let t=i,n=!1;const s=(i.x+e.x)/2,r=(i.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&s<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==i);return n}function rg(i,e){const t=hd(i.i,i.x,i.y),n=hd(e.i,e.x,e.y),s=i.next,r=e.prev;return i.next=e,e.prev=i,t.next=s,s.prev=t,n.next=t,t.prev=n,r.next=n,n.prev=r,n}function ag(i,e,t,n){const s=hd(i,e,t);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function Bo(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function hd(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Ew(i,e,t,n){let s=0;for(let r=e,a=t-n;r<t;r+=n)s+=(i[a]-i[r])*(i[r+1]+i[a+1]),a=r;return s}class yw{static triangulate(e,t,n=2){return sw(e,t,n)}}class ud{static area(e){const t=e.length;let n=0;for(let s=t-1,r=0;r<t;s=r++)n+=e[s].x*e[r].y-e[r].x*e[s].y;return n*.5}static isClockWise(e){return ud.area(e)<0}static triangulateShape(e,t){const n=[],s=[],r=[];og(e),cg(n,e);let a=e.length;t.forEach(og);for(let c=0;c<t.length;c++)s.push(a),a+=t[c].length,cg(n,t[c]);const o=yw.triangulate(n,s);for(let c=0;c<o.length;c+=3)r.push(o.slice(c,c+3));return r}}function og(i){const e=i.length;e>2&&i[e-1].equals(i[0])&&i.pop()}function cg(i,e){for(let t=0;t<e.length;t++)i.push(e[t].x),i.push(e[t].y)}class vl extends Mn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,a=t/2,o=Math.floor(n),c=Math.floor(s),l=o+1,h=c+1,u=e/o,d=t/c,f=[],p=[],m=[],g=[];for(let A=0;A<h;A++){const _=A*d-a;for(let x=0;x<l;x++){const E=x*u-r;p.push(E,-_,0),m.push(0,0,1),g.push(x/o),g.push(1-A/c)}}for(let A=0;A<c;A++)for(let _=0;_<o;_++){const x=_+l*A,E=_+l*(A+1),S=_+1+l*(A+1),w=_+1+l*A;f.push(x,E,w),f.push(E,S,w)}this.setIndex(f),this.setAttribute("position",new Jt(p,3)),this.setAttribute("normal",new Jt(m,3)),this.setAttribute("uv",new Jt(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vl(e.width,e.height,e.widthSegments,e.heightSegments)}}class To extends ai{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Fe(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Oi extends To{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Je(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return at(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Fe(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Fe(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Fe(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Cl extends ai{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Fe(16777215),this.specular=new Fe(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class _w extends ai{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Fe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Fe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Gc,this.normalScale=new Je(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new dn,this.combine=Sc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ww extends ai{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Wy,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class vw extends ai{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}function Il(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function Cw(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Iw(i){function e(s,r){return i[s]-i[r]}const t=i.length,n=new Array(t);for(let s=0;s!==t;++s)n[s]=s;return n.sort(e),n}function lg(i,e,t){const n=i.length,s=new i.constructor(n);for(let r=0,a=0;a!==n;++r){const o=t[r]*e;for(let c=0;c!==e;++c)s[a++]=i[o+c]}return s}function hg(i,e,t,n){let s=1,r=i[0];for(;r!==void 0&&r[n]===void 0;)r=i[s++];if(r===void 0)return;let a=r[n];if(a!==void 0)if(Array.isArray(a))do a=r[n],a!==void 0&&(e.push(r.time),t.push(...a)),r=i[s++];while(r!==void 0);else if(a.toArray!==void 0)do a=r[n],a!==void 0&&(e.push(r.time),a.toArray(t,t.length)),r=i[s++];while(r!==void 0);else do a=r[n],a!==void 0&&(e.push(r.time),t.push(a)),r=i[s++];while(r!==void 0)}class Ro{constructor(e,t,n,s){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let n=this._cachedIndex,s=t[n],r=t[n-1];e:{t:{let a;n:{i:if(!(e<s)){for(let o=n+2;;){if(s===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(r=s,s=t[++n],e<s)break t}a=t.length;break n}if(!(e>=r)){const o=t[1];e<o&&(n=2,r=o);for(let c=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===c)break;if(s=r,r=t[--n-1],e>=r)break t}a=n,n=0;break n}break e}for(;n<a;){const o=n+a>>>1;e<t[o]?a=o:n=o+1}if(s=t[n],r=t[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(s===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,s)}return this.interpolate_(n,r,e,s)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s;for(let a=0;a!==s;++a)t[a]=n[r+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Sw extends Ro{constructor(e,t,n,s){super(e,t,n,s),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Jr,endingEnd:Jr}}intervalChanged_(e,t,n){const s=this.parameterPositions;let r=e-2,a=e+1,o=s[r],c=s[a];if(o===void 0)switch(this.getSettings_().endingStart){case Zr:r=e,o=2*t-n;break;case Qc:r=s.length-2,o=t+s[r]-s[r+1];break;default:r=e,o=n}if(c===void 0)switch(this.getSettings_().endingEnd){case Zr:a=e,c=2*n-t;break;case Qc:a=1,c=n+s[1]-s[0];break;default:a=e-1,c=t}const l=(n-t)*.5,h=this.valueSize;this._weightPrev=l/(t-o),this._weightNext=l/(c-n),this._offsetPrev=r*h,this._offsetNext=a*h}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=e*o,l=c-o,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(s-t),m=p*p,g=m*p,A=-d*g+2*d*m-d*p,_=(1+d)*g+(-1.5-2*d)*m+(-.5+d)*p+1,x=(-1-f)*g+(1.5+f)*m+.5*p,E=f*g-f*m;for(let S=0;S!==o;++S)r[S]=A*a[h+S]+_*a[l+S]+x*a[c+S]+E*a[u+S];return r}}class ug extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=e*o,l=c-o,h=(n-t)/(s-t),u=1-h;for(let d=0;d!==o;++d)r[d]=a[l+d]*u+a[c+d]*h;return r}}class Mw extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e){return this.copySampleValue_(e-1)}}class vi{constructor(e,t,n,s){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Il(t,this.TimeBufferType),this.values=Il(n,this.ValueBufferType),this.setInterpolation(s||this.DefaultInterpolation)}static toJSON(e){const t=e.constructor;let n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Il(e.times,Array),values:Il(e.values,Array)};const s=e.getInterpolation();s!==e.DefaultInterpolation&&(n.interpolation=s)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Mw(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ug(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Sw(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case fo:t=this.InterpolantFactoryMethodDiscrete;break;case po:t=this.InterpolantFactoryMethodLinear;break;case Iu:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){const n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return console.warn("THREE.KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return fo;case this.InterpolantFactoryMethodLinear:return po;case this.InterpolantFactoryMethodSmooth:return Iu}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){const t=this.times;for(let n=0,s=t.length;n!==s;++n)t[n]+=e}return this}scale(e){if(e!==1){const t=this.times;for(let n=0,s=t.length;n!==s;++n)t[n]*=e}return this}trim(e,t){const n=this.times,s=n.length;let r=0,a=s-1;for(;r!==s&&n[r]<e;)++r;for(;a!==-1&&n[a]>t;)--a;if(++a,r!==0||a!==s){r>=a&&(a=Math.max(a,1),r=a-1);const o=this.getValueSize();this.times=n.slice(r,a),this.values=this.values.slice(r*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,s=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==r;o++){const c=n[o];if(typeof c=="number"&&isNaN(c)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,c),e=!1;break}if(a!==null&&a>c){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,c,a),e=!1;break}a=c}if(s!==void 0&&Cw(s))for(let o=0,c=s.length;o!==c;++o){const l=s[o];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,l),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===Iu,r=e.length-1;let a=1;for(let o=1;o<r;++o){let c=!1;const l=e[o],h=e[o+1];if(l!==h&&(o!==1||l!==e[0]))if(s)c=!0;else{const u=o*n,d=u-n,f=u+n;for(let p=0;p!==n;++p){const m=t[u+p];if(m!==t[d+p]||m!==t[f+p]){c=!0;break}}}if(c){if(o!==a){e[a]=e[o];const u=o*n,d=a*n;for(let f=0;f!==n;++f)t[d+f]=t[u+f]}++a}}if(r>0){e[a]=e[r];for(let o=r*n,c=a*n,l=0;l!==n;++l)t[c+l]=t[o+l];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),n=this.constructor,s=new n(this.name,e,t);return s.createInterpolant=this.createInterpolant,s}}vi.prototype.ValueTypeName="",vi.prototype.TimeBufferType=Float32Array,vi.prototype.ValueBufferType=Float32Array,vi.prototype.DefaultInterpolation=po;class ba extends vi{constructor(e,t,n){super(e,t,n)}}ba.prototype.ValueTypeName="bool",ba.prototype.ValueBufferType=Array,ba.prototype.DefaultInterpolation=fo,ba.prototype.InterpolantFactoryMethodLinear=void 0,ba.prototype.InterpolantFactoryMethodSmooth=void 0;class dg extends vi{constructor(e,t,n,s){super(e,t,n,s)}}dg.prototype.ValueTypeName="color";class fr extends vi{constructor(e,t,n,s){super(e,t,n,s)}}fr.prototype.ValueTypeName="number";class Bw extends Ro{constructor(e,t,n,s){super(e,t,n,s)}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=(n-t)/(s-t);let l=e*o;for(let h=l+o;l!==h;l+=4)Yt.slerpFlat(r,0,a,l-o,a,l,c);return r}}class Us extends vi{constructor(e,t,n,s){super(e,t,n,s)}InterpolantFactoryMethodLinear(e){return new Bw(this.times,this.values,this.getValueSize(),e)}}Us.prototype.ValueTypeName="quaternion",Us.prototype.InterpolantFactoryMethodSmooth=void 0;class Ea extends vi{constructor(e,t,n){super(e,t,n)}}Ea.prototype.ValueTypeName="string",Ea.prototype.ValueBufferType=Array,Ea.prototype.DefaultInterpolation=fo,Ea.prototype.InterpolantFactoryMethodLinear=void 0,Ea.prototype.InterpolantFactoryMethodSmooth=void 0;class pr extends vi{constructor(e,t,n,s){super(e,t,n,s)}}pr.prototype.ValueTypeName="vector";class Sl{constructor(e="",t=-1,n=[],s=Su){this.name=e,this.tracks=n,this.duration=t,this.blendMode=s,this.uuid=xi(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,s=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(Rw(n[a]).scale(s));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],n=e.tracks,s={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let r=0,a=n.length;r!==a;++r)t.push(vi.toJSON(n[r]));return s}static CreateFromMorphTargetSequence(e,t,n,s){const r=t.length,a=[];for(let o=0;o<r;o++){let c=[],l=[];c.push((o+r-1)%r,o,(o+1)%r),l.push(0,1,0);const h=Iw(c);c=lg(c,1,h),l=lg(l,1,h),!s&&c[0]===0&&(c.push(r),l.push(l[0])),a.push(new fr(".morphTargetInfluences["+t[o].name+"]",c,l).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){const s=e;n=s.geometry&&s.geometry.animations||s.animations}for(let s=0;s<n.length;s++)if(n[s].name===t)return n[s];return null}static CreateClipsFromMorphTargetSequences(e,t,n){const s={},r=/^([\w-]*?)([\d]+)$/;for(let o=0,c=e.length;o<c;o++){const l=e[o],h=l.name.match(r);if(h&&h.length>1){const u=h[1];let d=s[u];d||(s[u]=d=[]),d.push(l)}}const a=[];for(const o in s)a.push(this.CreateFromMorphTargetSequence(o,s[o],t,n));return a}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(u,d,f,p,m){if(f.length!==0){const g=[],A=[];hg(f,g,A,p),g.length!==0&&m.push(new u(d,g,A))}},s=[],r=e.name||"default",a=e.fps||30,o=e.blendMode;let c=e.length||-1;const l=e.hierarchy||[];for(let u=0;u<l.length;u++){const d=l[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){const f={};let p;for(p=0;p<d.length;p++)if(d[p].morphTargets)for(let m=0;m<d[p].morphTargets.length;m++)f[d[p].morphTargets[m]]=-1;for(const m in f){const g=[],A=[];for(let _=0;_!==d[p].morphTargets.length;++_){const x=d[p];g.push(x.time),A.push(x.morphTarget===m?1:0)}s.push(new fr(".morphTargetInfluence["+m+"]",g,A))}c=f.length*a}else{const f=".bones["+t[u].name+"]";n(pr,f+".position",d,"pos",s),n(Us,f+".quaternion",d,"rot",s),n(pr,f+".scale",d,"scl",s)}}return s.length===0?null:new this(r,c,s,o)}resetDuration(){const e=this.tracks;let t=0;for(let n=0,s=e.length;n!==s;++n){const r=this.tracks[n];t=Math.max(t,r.times[r.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){const e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());return new this.constructor(this.name,this.duration,e,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}}function Tw(i){switch(i.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return fr;case"vector":case"vector2":case"vector3":case"vector4":return pr;case"color":return dg;case"quaternion":return Us;case"bool":case"boolean":return ba;case"string":return Ea}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+i)}function Rw(i){if(i.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=Tw(i.type);if(i.times===void 0){const t=[],n=[];hg(i.keys,t,n,"value"),i.times=t,i.values=n}return e.parse!==void 0?e.parse(i):new e(i.name,i.times,i.values,i.interpolation)}const rs={enabled:!1,files:{},add:function(i,e){this.enabled!==!1&&(this.files[i]=e)},get:function(i){if(this.enabled!==!1)return this.files[i]},remove:function(i){delete this.files[i]},clear:function(){this.files={}}};class fg{constructor(e,t,n){const s=this;let r=!1,a=0,o=0,c;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(h){o++,r===!1&&s.onStart!==void 0&&s.onStart(h,a,o),r=!0},this.itemEnd=function(h){a++,s.onProgress!==void 0&&s.onProgress(h,a,o),a===o&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return c?c(h):h},this.setURLModifier=function(h){return c=h,this},this.addHandler=function(h,u){return l.push(h,u),this},this.removeHandler=function(h){const u=l.indexOf(h);return u!==-1&&l.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=l.length;u<d;u+=2){const f=l[u],p=l[u+1];if(f.global&&(f.lastIndex=0),f.test(h))return p}return null}}}const Fw=new fg;class ci{constructor(e){this.manager=e!==void 0?e:Fw,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const n=this;return new Promise(function(s,r){n.load(e,s,t,r)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}ci.DEFAULT_MATERIAL_NAME="__DEFAULT";const as={};class Nw extends Error{constructor(e,t){super(e),this.response=t}}class os extends ci{constructor(e){super(e),this.mimeType="",this.responseType=""}load(e,t,n,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=rs.get(e);if(r!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(r),this.manager.itemEnd(e)},0),r;if(as[e]!==void 0){as[e].push({onLoad:t,onProgress:n,onError:s});return}as[e]=[],as[e].push({onLoad:t,onProgress:n,onError:s});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,c=this.responseType;fetch(a).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;const h=as[e],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,p=f!==0;let m=0;const g=new ReadableStream({start(A){_();function _(){u.read().then(({done:x,value:E})=>{if(x)A.close();else{m+=E.byteLength;const S=new ProgressEvent("progress",{lengthComputable:p,loaded:m,total:f});for(let w=0,I=h.length;w<I;w++){const T=h[w];T.onProgress&&T.onProgress(S)}A.enqueue(E),_()}},x=>{A.error(x)})}}});return new Response(g)}else throw new Nw(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return l.json();default:if(o==="")return l.text();{const u=/charset="?([^;"\s]*)"?/i.exec(o),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return l.arrayBuffer().then(p=>f.decode(p))}}}).then(l=>{rs.add(e,l);const h=as[e];delete as[e];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{const h=as[e];if(h===void 0)throw this.manager.itemError(e),l;delete as[e];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onError&&f.onError(l)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Dw extends ci{constructor(e){super(e)}load(e,t,n,s){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,a=rs.get(e);if(a!==void 0)return r.manager.itemStart(e),setTimeout(function(){t&&t(a),r.manager.itemEnd(e)},0),a;const o=mo("img");function c(){h(),rs.add(e,this),t&&t(this),r.manager.itemEnd(e)}function l(u){h(),s&&s(u),r.manager.itemError(e),r.manager.itemEnd(e)}function h(){o.removeEventListener("load",c,!1),o.removeEventListener("error",l,!1)}return o.addEventListener("load",c,!1),o.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),r.manager.itemStart(e),o.src=e,o}}class Lw extends ci{constructor(e){super(e)}load(e,t,n,s){const r=this,a=new ll,o=new os(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(r.withCredentials),o.load(e,function(c){let l;try{l=r.parse(c)}catch(h){if(s!==void 0)s(h);else{console.error(h);return}}l.image!==void 0?a.image=l.image:l.data!==void 0&&(a.image.width=l.width,a.image.height=l.height,a.image.data=l.data),a.wrapS=l.wrapS!==void 0?l.wrapS:Zn,a.wrapT=l.wrapT!==void 0?l.wrapT:Zn,a.magFilter=l.magFilter!==void 0?l.magFilter:qt,a.minFilter=l.minFilter!==void 0?l.minFilter:qt,a.anisotropy=l.anisotropy!==void 0?l.anisotropy:1,l.colorSpace!==void 0&&(a.colorSpace=l.colorSpace),l.flipY!==void 0&&(a.flipY=l.flipY),l.format!==void 0&&(a.format=l.format),l.type!==void 0&&(a.type=l.type),l.mipmaps!==void 0&&(a.mipmaps=l.mipmaps,a.minFilter=ri),l.mipmapCount===1&&(a.minFilter=qt),l.generateMipmaps!==void 0&&(a.generateMipmaps=l.generateMipmaps),a.needsUpdate=!0,t&&t(a,l)},n,s),a}}class pg extends ci{constructor(e){super(e)}load(e,t,n,s){const r=new nn,a=new Dw(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){r.image=o,r.needsUpdate=!0,t!==void 0&&t(r)},n,s),r}}class Fo extends Tt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Fe(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}class Pw extends Fo{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Fe(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const dd=new Re,Ag=new G,gg=new G;class fd{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Je(512,512),this.mapType=cn,this.map=null,this.mapPass=null,this.matrix=new Re,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new rd,this._frameExtents=new Je(1,1),this._viewportCount=1,this._viewports=[new gt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Ag.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ag),gg.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(gg),t.updateMatrixWorld(),dd.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(dd),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(dd)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class kw extends fd{constructor(){super(new Bn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,n=ea*2*e.angle*this.focus,s=this.mapSize.width/this.mapSize.height,r=e.distance||t.far;(n!==t.fov||s!==t.aspect||r!==t.far)&&(t.fov=n,t.aspect=s,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class mg extends Fo{constructor(e,t,n=0,s=Math.PI/3,r=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.target=new Tt,this.distance=n,this.angle=s,this.penumbra=r,this.decay=a,this.map=null,this.shadow=new kw}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}const xg=new Re,No=new G,pd=new G;class Uw extends fd{constructor(){super(new Bn(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Je(4,2),this._viewportCount=6,this._viewports=[new gt(2,1,1,1),new gt(0,1,1,1),new gt(3,1,1,1),new gt(1,1,1,1),new gt(3,0,1,1),new gt(1,0,1,1)],this._cubeDirections=[new G(1,0,0),new G(-1,0,0),new G(0,0,1),new G(0,0,-1),new G(0,1,0),new G(0,-1,0)],this._cubeUps=[new G(0,1,0),new G(0,1,0),new G(0,1,0),new G(0,1,0),new G(0,0,1),new G(0,0,-1)]}updateMatrices(e,t=0){const n=this.camera,s=this.matrix,r=e.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),No.setFromMatrixPosition(e.matrixWorld),n.position.copy(No),pd.copy(n.position),pd.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(pd),n.updateMatrixWorld(),s.makeTranslation(-No.x,-No.y,-No.z),xg.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xg)}}class Ml extends Fo{constructor(e,t,n=0,s=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=s,this.shadow=new Uw}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class Ad extends LA{constructor(e=-1,t=1,n=1,s=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,a=n+e,o=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,a=r+l*this.view.width,o-=h*this.view.offsetY,c=o-h*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class Ow extends fd{constructor(){super(new Ad(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class gd extends Fo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Tt.DEFAULT_UP),this.updateMatrix(),this.target=new Tt,this.shadow=new Ow}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class bg extends Fo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Ar{static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}}class Qw extends ci{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,n,s){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,a=rs.get(e);if(a!==void 0){if(r.manager.itemStart(e),a.then){a.then(l=>{t&&t(l),r.manager.itemEnd(e)}).catch(l=>{s&&s(l)});return}return setTimeout(function(){t&&t(a),r.manager.itemEnd(e)},0),a}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader;const c=fetch(e,o).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(l){return rs.add(e,l),t&&t(l),r.manager.itemEnd(e),l}).catch(function(l){s&&s(l),rs.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)});rs.add(e,c),r.manager.itemStart(e)}}class Gw extends Bn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Hw{constructor(e,t,n){this.binding=e,this.valueSize=n;let s,r,a;switch(t){case"quaternion":s=this._slerp,r=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":s=this._select,r=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(n*5);break;default:s=this._lerp,r=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=s,this._mixBufferRegionAdditive=r,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){const n=this.buffer,s=this.valueSize,r=e*s+s;let a=this.cumulativeWeight;if(a===0){for(let o=0;o!==s;++o)n[r+o]=n[o];a=t}else{a+=t;const o=t/a;this._mixBufferRegion(n,r,0,o,s)}this.cumulativeWeight=a}accumulateAdditive(e){const t=this.buffer,n=this.valueSize,s=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,s,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){const t=this.valueSize,n=this.buffer,s=e*t+t,r=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const c=t*this._origIndex;this._mixBufferRegion(n,s,c,1-r,t)}a>0&&this._mixBufferRegionAdditive(n,s,this._addIndex*t,1,t);for(let c=t,l=t+t;c!==l;++c)if(n[c]!==n[c+t]){o.setValue(n,s);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,s=n*this._origIndex;e.getValue(t,s);for(let r=n,a=s;r!==a;++r)t[r]=t[s+r%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,s,r){if(s>=.5)for(let a=0;a!==r;++a)e[t+a]=e[n+a]}_slerp(e,t,n,s){Yt.slerpFlat(e,t,e,t,e,n,s)}_slerpAdditive(e,t,n,s,r){const a=this._workIndex*r;Yt.multiplyQuaternionsFlat(e,a,e,t,e,n),Yt.slerpFlat(e,t,e,t,e,a,s)}_lerp(e,t,n,s,r){const a=1-s;for(let o=0;o!==r;++o){const c=t+o;e[c]=e[c]*a+e[n+o]*s}}_lerpAdditive(e,t,n,s,r){for(let a=0;a!==r;++a){const o=t+a;e[o]=e[o]+e[n+a]*s}}}const md="\\[\\]\\.:\\/",zw=new RegExp("["+md+"]","g"),xd="[^"+md+"]",Vw="[^"+md.replace("\\.","")+"]",Ww=/((?:WC+[\/:])*)/.source.replace("WC",xd),qw=/(WCOD+)?/.source.replace("WCOD",Vw),Kw=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",xd),jw=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",xd),Xw=new RegExp("^"+Ww+qw+Kw+jw+"$"),Yw=["material","materials","bones","map"];class Jw{constructor(e,t,n){const s=n||_t.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,s)}getValue(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,s=this._bindings[n];s!==void 0&&s.getValue(e,t)}setValue(e,t){const n=this._bindings;for(let s=this._targetGroup.nCachedObjects_,r=n.length;s!==r;++s)n[s].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}}class _t{constructor(e,t,n){this.path=t,this.parsedPath=n||_t.parseTrackName(t),this.node=_t.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new _t.Composite(e,t,n):new _t(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(zw,"")}static parseTrackName(e){const t=Xw.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},s=n.nodeName&&n.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){const r=n.nodeName.substring(s+1);Yw.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,s),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){const n=function(r){for(let a=0;a<r.length;a++){const o=r[a];if(o.name===t||o.uuid===t)return o;const c=n(o.children);if(c)return c}return null},s=n(e.children);if(s)return s}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)e[t++]=n[s]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node;const t=this.parsedPath,n=t.objectName,s=t.propertyName;let r=t.propertyIndex;if(e||(e=_t.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let l=t.objectIndex;switch(n){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===l){l=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(l!==void 0){if(e[l]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[l]}}const a=e[s];if(a===void 0){const l=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+l+"."+s+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?o=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(r!==void 0){if(s==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[r]!==void 0&&(r=e.morphTargetDictionary[r])}c=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=r}else a.fromArray!==void 0&&a.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(c=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=s;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}_t.Composite=Jw,_t.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},_t.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},_t.prototype.GetterByBindingType=[_t.prototype._getValue_direct,_t.prototype._getValue_array,_t.prototype._getValue_arrayElement,_t.prototype._getValue_toArray],_t.prototype.SetterByBindingTypeAndVersioning=[[_t.prototype._setValue_direct,_t.prototype._setValue_direct_setNeedsUpdate,_t.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_array,_t.prototype._setValue_array_setNeedsUpdate,_t.prototype._setValue_array_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_arrayElement,_t.prototype._setValue_arrayElement_setNeedsUpdate,_t.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[_t.prototype._setValue_fromArray,_t.prototype._setValue_fromArray_setNeedsUpdate,_t.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class Zw{constructor(e,t,n=null,s=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=s;const r=t.tracks,a=r.length,o=new Array(a),c={endingStart:Jr,endingEnd:Jr};for(let l=0;l!==a;++l){const h=r[l].createInterpolant(null);o[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=aA,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){const s=this._clip.duration,r=e._clip.duration,a=r/s,o=s/r;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const s=this._mixer,r=s.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=s._lendControlInterpolant(),this._timeScaleInterpolant=o);const c=o.parameterPositions,l=o.sampleValues;return c[0]=r,c[1]=r+n,l[0]=e/a,l[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,s){if(!this.enabled){this._updateWeight(e);return}const r=this._startTime;if(r!==null){const c=(e-r)*n;c<0||n===0?t=0:(this._startTime=null,t=n*c)}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case zy:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(a),l[h].accumulateAdditive(o);break;case Su:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(a),l[h].accumulate(s,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(n!==null){const s=n.evaluate(e)[0];t*=s,e>n.parameterPositions[1]&&(this.stopFading(),s===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;if(n!==null){const s=n.evaluate(e)[0];t*=s,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let s=this.time+e,r=this._loopCount;const a=n===Hy;if(e===0)return r===-1?s:a&&(r&1)===1?t-s:s;if(n===rA){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(s>=t)s=t;else if(s<0)s=0;else{this.time=s;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1&&(e>=0?(r=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),s>=t||s<0){const o=Math.floor(s/t);s-=t*o,r+=Math.abs(o);const c=this.repetitions-r;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,s=e>0?t:0,this.time=s,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(c===1){const l=e<0;this._setEndings(l,!l,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this.time=s,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=s;if(a&&(r&1)===1)return t-s}return s}_setEndings(e,t,n){const s=this._interpolantSettings;n?(s.endingStart=Zr,s.endingEnd=Zr):(e?s.endingStart=this.zeroSlopeAtStart?Zr:Jr:s.endingStart=Qc,t?s.endingEnd=this.zeroSlopeAtEnd?Zr:Jr:s.endingEnd=Qc)}_scheduleFading(e,t,n){const s=this._mixer,r=s.time;let a=this._weightInterpolant;a===null&&(a=s._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,c=a.sampleValues;return o[0]=r,c[0]=t,o[1]=r+e,c[1]=n,this}}const $w=new Float32Array(1);class Eg extends Ms{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,s=e._clip.tracks,r=s.length,a=e._propertyBindings,o=e._interpolants,c=n.uuid,l=this._bindingsByRootAndName;let h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==r;++u){const d=s[u],f=d.name;let p=h[f];if(p!==void 0)++p.referenceCount,a[u]=p;else{if(p=a[u],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,c,f));continue}const m=t&&t._propertyBindings[u].binding.parsedPath;p=new Hw(_t.create(n,f,m),d.ValueTypeName,d.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,c,f),a[u]=p}o[u].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const n=(e._localRoot||this._root).uuid,s=e._clip.uuid,r=this._actionsByClip[s];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,s,n)}const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];r.useCount++===0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];--r.useCount===0&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){const s=this._actions,r=this._actionsByClip;let a=r[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=a;else{const o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=s.length,s.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){const t=this._actions,n=t[t.length-1],s=e._cacheIndex;n._cacheIndex=s,t[s]=n,t.pop(),e._cacheIndex=null;const r=e._clip.uuid,a=this._actionsByClip,o=a[r],c=o.knownActions,l=c[c.length-1],h=e._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),e._byClipCacheIndex=null;const u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],c.length===0&&delete a[r],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let n=0,s=t.length;n!==s;++n){const r=t[n];--r.referenceCount===0&&this._removeInactiveBinding(r)}}_lendAction(e){const t=this._actions,n=e._cacheIndex,s=this._nActiveActions++,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){const t=this._actions,n=e._cacheIndex,s=--this._nActiveActions,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){const s=this._bindingsByRootAndName,r=this._bindings;let a=s[t];a===void 0&&(a={},s[t]=a),a[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){const t=this._bindings,n=e.binding,s=n.rootNode.uuid,r=n.path,a=this._bindingsByRootAndName,o=a[s],c=t[t.length-1],l=e._cacheIndex;c._cacheIndex=l,t[l]=c,t.pop(),delete o[r],Object.keys(o).length===0&&delete a[s]}_lendBinding(e){const t=this._bindings,n=e._cacheIndex,s=this._nActiveBindings++,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){const t=this._bindings,n=e._cacheIndex,s=--this._nActiveBindings,r=t[s];e._cacheIndex=s,t[s]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let n=e[t];return n===void 0&&(n=new ug(new Float32Array(2),new Float32Array(2),1,$w),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){const t=this._controlInterpolants,n=e.__cacheIndex,s=--this._nActiveControlInterpolants,r=t[s];e.__cacheIndex=s,t[s]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){const s=t||this._root,r=s.uuid;let a=typeof e=="string"?Sl.findByName(s,e):e;const o=a!==null?a.uuid:e,c=this._actionsByClip[o];let l=null;if(n===void 0&&(a!==null?n=a.blendMode:n=Su),c!==void 0){const u=c.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;l=c.knownActions[0],a===null&&(a=l._clip)}if(a===null)return null;const h=new Zw(this,a,t,n);return this._bindAction(h,l),this._addInactiveAction(h,o,r),h}existingAction(e,t){const n=t||this._root,s=n.uuid,r=typeof e=="string"?Sl.findByName(n,e):e,a=r?r.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[s]||null}stopAllAction(){const e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,s=this.time+=e,r=Math.sign(e),a=this._accuIndex^=1;for(let l=0;l!==n;++l)t[l]._update(s,e,r,a);const o=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)o[l].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,n=e.uuid,s=this._actionsByClip,r=s[n];if(r!==void 0){const a=r.knownActions;for(let o=0,c=a.length;o!==c;++o){const l=a[o];this._deactivateAction(l);const h=l._cacheIndex,u=t[t.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=h,t[h]=u,t.pop(),this._removeInactiveBindingsForAction(l)}delete s[n]}}uncacheRoot(e){const t=e.uuid,n=this._actionsByClip;for(const a in n){const o=n[a].actionByRoot,c=o[t];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}const s=this._bindingsByRootAndName,r=s[t];if(r!==void 0)for(const a in r){const o=r[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){const n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}}class yg{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=at(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(at(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const Os=new G,Bl=new Re,bd=new Re;class ev extends xl{constructor(e){const t=_g(e),n=new Mn,s=[],r=[],a=new Fe(0,0,1),o=new Fe(0,1,0);for(let l=0;l<t.length;l++){const h=t[l];h.parent&&h.parent.isBone&&(s.push(0,0,0),s.push(0,0,0),r.push(a.r,a.g,a.b),r.push(o.r,o.g,o.b))}n.setAttribute("position",new Jt(s,3)),n.setAttribute("color",new Jt(r,3));const c=new ma({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,c),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){const t=this.bones,n=this.geometry,s=n.getAttribute("position");bd.copy(this.root.matrixWorld).invert();for(let r=0,a=0;r<t.length;r++){const o=t[r];o.parent&&o.parent.isBone&&(Bl.multiplyMatrices(bd,o.matrixWorld),Os.setFromMatrixPosition(Bl),s.setXYZ(a,Os.x,Os.y,Os.z),Bl.multiplyMatrices(bd,o.parent.matrixWorld),Os.setFromMatrixPosition(Bl),s.setXYZ(a+1,Os.x,Os.y,Os.z),a+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}}function _g(i){const e=[];i.isBone===!0&&e.push(i);for(let t=0;t<i.children.length;t++)e.push(..._g(i.children[t]));return e}class tv extends xl{constructor(e=10,t=10,n=4473924,s=8947848){n=new Fe(n),s=new Fe(s);const r=t/2,a=e/t,o=e/2,c=[],l=[];for(let d=0,f=0,p=-o;d<=t;d++,p+=a){c.push(-o,0,p,o,0,p),c.push(p,0,-o,p,0,o);const m=d===r?n:s;m.toArray(l,f),f+=3,m.toArray(l,f),f+=3,m.toArray(l,f),f+=3,m.toArray(l,f),f+=3}const h=new Mn;h.setAttribute("position",new Jt(c,3)),h.setAttribute("color",new Jt(l,3));const u=new ma({vertexColors:!0,toneMapped:!1});super(h,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class wg extends xl{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],s=new Mn;s.setAttribute("position",new Jt(t,3)),s.setAttribute("color",new Jt(n,3));const r=new ma({vertexColors:!0,toneMapped:!1});super(s,r),this.type="AxesHelper"}setColors(e,t,n){const s=new Fe,r=this.geometry.attributes.color.array;return s.set(e),s.toArray(r,0),s.toArray(r,3),s.set(t),s.toArray(r,6),s.toArray(r,9),s.set(n),s.toArray(r,12),s.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class nv extends Ms{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){console.warn("THREE.Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function vg(i,e,t,n){const s=iv(n);switch(t){case nA:return i*e;case Xi:return i*e/s.components*s.byteLength;case ru:return i*e/s.components*s.byteLength;case ar:return i*e*2/s.components*s.byteLength;case au:return i*e*2/s.components*s.byteLength;case iA:return i*e*3/s.components*s.byteLength;case hn:return i*e*4/s.components*s.byteLength;case ou:return i*e*4/s.components*s.byteLength;case Fc:case oo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Nc:case co:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case cu:case lu:return Math.max(i,16)*Math.max(e,8)/4;case Dc:case Lc:return Math.max(i,8)*Math.max(e,8)/2;case Pc:case kc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Uc:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case lo:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case hu:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case uu:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case du:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case ho:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case fu:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case pu:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case Au:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case gu:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case mu:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case xu:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case bu:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Eu:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case yu:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case uo:case _u:case Oc:return Math.ceil(i/4)*Math.ceil(e/4)*16;case sA:case wu:return Math.ceil(i/4)*Math.ceil(e/4)*8;case vu:case Cu:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function iv(i){switch(i){case cn:case $p:return{byteLength:1,components:1};case io:case eA:case kn:return{byteLength:2,components:1};case iu:case su:return{byteLength:2,components:4};case rr:case nu:case ln:return{byteLength:4,components:1};case tA:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Ic}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Ic);function Cg(){let i=null,e=!1,t=null,n=null;function s(r,a){t(r,a),n=i.requestAnimationFrame(s)}return{start:function(){e!==!0&&t!==null&&(n=i.requestAnimationFrame(s),e=!0)},stop:function(){i.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){i=r}}}function sv(i){const e=new WeakMap;function t(o,c){const l=o.array,h=o.usage,u=l.byteLength,d=i.createBuffer();i.bindBuffer(c,d),i.bufferData(c,l,h),o.onUploadCallback();let f;if(l instanceof Float32Array)f=i.FLOAT;else if(l instanceof Uint16Array)o.isFloat16BufferAttribute?f=i.HALF_FLOAT:f=i.UNSIGNED_SHORT;else if(l instanceof Int16Array)f=i.SHORT;else if(l instanceof Uint32Array)f=i.UNSIGNED_INT;else if(l instanceof Int32Array)f=i.INT;else if(l instanceof Int8Array)f=i.BYTE;else if(l instanceof Uint8Array)f=i.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)f=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:d,type:f,bytesPerElement:l.BYTES_PER_ELEMENT,version:o.version,size:u}}function n(o,c,l){const h=c.array,u=c.updateRanges;if(i.bindBuffer(l,o),u.length===0)i.bufferSubData(l,0,h);else{u.sort((f,p)=>f.start-p.start);let d=0;for(let f=1;f<u.length;f++){const p=u[d],m=u[f];m.start<=p.start+p.count+1?p.count=Math.max(p.count,m.start+m.count-p.start):(++d,u[d]=m)}u.length=d+1;for(let f=0,p=u.length;f<p;f++){const m=u[f];i.bufferSubData(l,m.start*h.BYTES_PER_ELEMENT,h,m.start,m.count)}c.clearUpdateRanges()}c.onUploadCallback()}function s(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function r(o){o.isInterleavedBufferAttribute&&(o=o.data);const c=e.get(o);c&&(i.deleteBuffer(c.buffer),e.delete(o))}function a(o,c){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){const h=e.get(o);(!h||h.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}const l=e.get(o);if(l===void 0)e.set(o,t(o,c));else if(l.version<o.version){if(l.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(l.buffer,o,c),l.version=o.version}}return{get:s,remove:r,update:a}}var rv=`#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
-#endif`,ov=`#ifdef USE_ALPHAHASH
+#endif`,av=`#ifdef USE_ALPHAHASH
const float ALPHA_HASH_SCALE = 0.05;
float hash2D( vec2 value ) {
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
@@ -74,20 +74,20 @@
: cases.z;
return clamp( threshold , 1.0e-6, 1.0 );
}
-#endif`,cv=`#ifdef USE_ALPHAMAP
+#endif`,ov=`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
-#endif`,lv=`#ifdef USE_ALPHAMAP
+#endif`,cv=`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
-#endif`,hv=`#ifdef USE_ALPHATEST
+#endif`,lv=`#ifdef USE_ALPHATEST
#ifdef ALPHA_TO_COVERAGE
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
if ( diffuseColor.a == 0.0 ) discard;
#else
if ( diffuseColor.a < alphaTest ) discard;
#endif
-#endif`,uv=`#ifdef USE_ALPHATEST
+#endif`,hv=`#ifdef USE_ALPHATEST
uniform float alphaTest;
-#endif`,dv=`#ifdef USE_AOMAP
+#endif`,uv=`#ifdef USE_AOMAP
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
reflectedLight.indirectDiffuse *= ambientOcclusion;
#if defined( USE_CLEARCOAT )
@@ -100,10 +100,10 @@
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
#endif
-#endif`,fv=`#ifdef USE_AOMAP
+#endif`,dv=`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
-#endif`,pv=`#ifdef USE_BATCHING
+#endif`,fv=`#ifdef USE_BATCHING
#if ! defined( GL_ANGLE_multi_draw )
#define gl_DrawID _gl_DrawID
uniform int _gl_DrawID;
@@ -137,15 +137,15 @@
int y = j / size;
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
}
-#endif`,Av=`#ifdef USE_BATCHING
+#endif`,pv=`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
-#endif`,gv=`vec3 transformed = vec3( position );
+#endif`,Av=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
-#endif`,mv=`vec3 objectNormal = vec3( normal );
+#endif`,gv=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
-#endif`,xv=`float G_BlinnPhong_Implicit( ) {
+#endif`,mv=`float G_BlinnPhong_Implicit( ) {
return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
@@ -159,7 +159,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
float G = G_BlinnPhong_Implicit( );
float D = D_BlinnPhong( shininess, dotNH );
return F * ( G * D );
-} // validated`,bv=`#ifdef USE_IRIDESCENCE
+} // validated`,xv=`#ifdef USE_IRIDESCENCE
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
@@ -222,7 +222,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
}
return max( I, vec3( 0.0 ) );
}
-#endif`,Ev=`#ifdef USE_BUMPMAP
+#endif`,bv=`#ifdef USE_BUMPMAP
uniform sampler2D bumpMap;
uniform float bumpScale;
vec2 dHdxy_fwd() {
@@ -243,7 +243,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}
-#endif`,yv=`#if NUM_CLIPPING_PLANES > 0
+#endif`,Ev=`#if NUM_CLIPPING_PLANES > 0
vec4 plane;
#ifdef ALPHA_TO_COVERAGE
float distanceToPlane, distanceGradient;
@@ -289,26 +289,26 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
if ( clipped ) discard;
#endif
#endif
-#endif`,_v=`#if NUM_CLIPPING_PLANES > 0
+#endif`,yv=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
-#endif`,wv=`#if NUM_CLIPPING_PLANES > 0
+#endif`,_v=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
-#endif`,vv=`#if NUM_CLIPPING_PLANES > 0
+#endif`,wv=`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
-#endif`,Cv=`#if defined( USE_COLOR_ALPHA )
+#endif`,vv=`#if defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#elif defined( USE_COLOR )
diffuseColor.rgb *= vColor;
-#endif`,Iv=`#if defined( USE_COLOR_ALPHA )
+#endif`,Cv=`#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR )
varying vec3 vColor;
-#endif`,Sv=`#if defined( USE_COLOR_ALPHA )
+#endif`,Iv=`#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec3 vColor;
-#endif`,Mv=`#if defined( USE_COLOR_ALPHA )
+#endif`,Sv=`#if defined( USE_COLOR_ALPHA )
vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
vColor = vec3( 1.0 );
@@ -322,7 +322,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve
#ifdef USE_BATCHING_COLOR
vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
vColor.xyz *= batchingColor.xyz;
-#endif`,Bv=`#define PI 3.141592653589793
+#endif`,Mv=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
@@ -396,7 +396,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
-} // validated`,Tv=`#ifdef ENVMAP_TYPE_CUBE_UV
+} // validated`,Bv=`#ifdef ENVMAP_TYPE_CUBE_UV
#define cubeUV_minMipLevel 4.0
#define cubeUV_minTileSize 16.0
float getFace( vec3 direction ) {
@@ -489,7 +489,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
return vec4( mix( color0, color1, mipF ), 1.0 );
}
}
-#endif`,Rv=`vec3 transformedNormal = objectNormal;
+#endif`,Tv=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
vec3 transformedTangent = objectTangent;
#endif
@@ -518,21 +518,21 @@ transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
transformedTangent = - transformedTangent;
#endif
-#endif`,Fv=`#ifdef USE_DISPLACEMENTMAP
+#endif`,Rv=`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
-#endif`,Nv=`#ifdef USE_DISPLACEMENTMAP
+#endif`,Fv=`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
-#endif`,Dv=`#ifdef USE_EMISSIVEMAP
+#endif`,Nv=`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
-#endif`,Lv=`#ifdef USE_EMISSIVEMAP
+#endif`,Dv=`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
-#endif`,Pv="gl_FragColor = linearToOutputTexel( gl_FragColor );",kv=`vec4 LinearTransferOETF( in vec4 value ) {
+#endif`,Lv="gl_FragColor = linearToOutputTexel( gl_FragColor );",Pv=`vec4 LinearTransferOETF( in vec4 value ) {
return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
@@ -540,7 +540,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) {
}
vec4 sRGBTransferOETF( in vec4 value ) {
return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
-}`,Uv=`#ifdef USE_ENVMAP
+}`,kv=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vec3 cameraToFrag;
if ( isOrthographic ) {
@@ -569,7 +569,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
#elif defined( ENVMAP_BLENDING_ADD )
outgoingLight += envColor.xyz * specularStrength * reflectivity;
#endif
-#endif`,Ov=`#ifdef USE_ENVMAP
+#endif`,Uv=`#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform float flipEnvMap;
uniform mat3 envMapRotation;
@@ -579,7 +579,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
uniform sampler2D envMap;
#endif
-#endif`,Qv=`#ifdef USE_ENVMAP
+#endif`,Ov=`#ifdef USE_ENVMAP
uniform float reflectivity;
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
@@ -590,7 +590,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
#else
varying vec3 vReflect;
#endif
-#endif`,Gv=`#ifdef USE_ENVMAP
+#endif`,Qv=`#ifdef USE_ENVMAP
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
#define ENV_WORLDPOS
#endif
@@ -601,7 +601,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
varying vec3 vReflect;
uniform float refractionRatio;
#endif
-#endif`,Hv=`#ifdef USE_ENVMAP
+#endif`,Gv=`#ifdef USE_ENVMAP
#ifdef ENV_WORLDPOS
vWorldPosition = worldPosition.xyz;
#else
@@ -618,18 +618,18 @@ vec4 sRGBTransferOETF( in vec4 value ) {
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
-#endif`,zv=`#ifdef USE_FOG
+#endif`,Hv=`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
-#endif`,Vv=`#ifdef USE_FOG
+#endif`,zv=`#ifdef USE_FOG
varying float vFogDepth;
-#endif`,Wv=`#ifdef USE_FOG
+#endif`,Vv=`#ifdef USE_FOG
#ifdef FOG_EXP2
float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
#else
float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
#endif
gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
-#endif`,qv=`#ifdef USE_FOG
+#endif`,Wv=`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
@@ -638,7 +638,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
uniform float fogNear;
uniform float fogFar;
#endif
-#endif`,Kv=`#ifdef USE_GRADIENTMAP
+#endif`,qv=`#ifdef USE_GRADIENTMAP
uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
@@ -650,12 +650,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
vec2 fw = fwidth( coord ) * 0.5;
return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
#endif
-}`,jv=`#ifdef USE_LIGHTMAP
+}`,Kv=`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
-#endif`,Xv=`LambertMaterial material;
+#endif`,jv=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
-material.specularStrength = specularStrength;`,Yv=`varying vec3 vViewPosition;
+material.specularStrength = specularStrength;`,Xv=`varying vec3 vViewPosition;
struct LambertMaterial {
vec3 diffuseColor;
float specularStrength;
@@ -669,7 +669,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Lambert
-#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Jv=`uniform bool receiveShadow;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Yv=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
uniform vec3 lightProbe[ 9 ];
@@ -785,7 +785,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi
vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
return irradiance;
}
-#endif`,Zv=`#ifdef USE_ENVMAP
+#endif`,Jv=`#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
@@ -818,8 +818,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi
#endif
}
#endif
-#endif`,$v=`ToonMaterial material;
-material.diffuseColor = diffuseColor.rgb;`,eC=`varying vec3 vViewPosition;
+#endif`,Zv=`ToonMaterial material;
+material.diffuseColor = diffuseColor.rgb;`,$v=`varying vec3 vViewPosition;
struct ToonMaterial {
vec3 diffuseColor;
};
@@ -831,11 +831,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_Toon
-#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,tC=`BlinnPhongMaterial material;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,eC=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
-material.specularStrength = specularStrength;`,nC=`varying vec3 vViewPosition;
+material.specularStrength = specularStrength;`,tC=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
vec3 diffuseColor;
vec3 specularColor;
@@ -852,7 +852,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct RE_Direct_BlinnPhong
-#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,iC=`PhysicalMaterial material;
+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,nC=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
@@ -938,7 +938,7 @@ material.roughness = min( material.roughness, 1.0 );
material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
-#endif`,sC=`struct PhysicalMaterial {
+#endif`,iC=`struct PhysicalMaterial {
vec3 diffuseColor;
float roughness;
vec3 specularColor;
@@ -1239,7 +1239,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia
#define RE_IndirectSpecular RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
-}`,rC=`
+}`,sC=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
@@ -1354,7 +1354,7 @@ IncidentLight directLight;
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
-#endif`,aC=`#if defined( RE_IndirectDiffuse )
+#endif`,rC=`#if defined( RE_IndirectDiffuse )
#ifdef USE_LIGHTMAP
vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
@@ -1373,32 +1373,32 @@ IncidentLight directLight;
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
#endif
-#endif`,oC=`#if defined( RE_IndirectDiffuse )
+#endif`,aC=`#if defined( RE_IndirectDiffuse )
RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
-#endif`,cC=`#if defined( USE_LOGDEPTHBUF )
+#endif`,oC=`#if defined( USE_LOGDEPTHBUF )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
-#endif`,lC=`#if defined( USE_LOGDEPTHBUF )
+#endif`,cC=`#if defined( USE_LOGDEPTHBUF )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
-#endif`,hC=`#ifdef USE_LOGDEPTHBUF
+#endif`,lC=`#ifdef USE_LOGDEPTHBUF
varying float vFragDepth;
varying float vIsPerspective;
-#endif`,uC=`#ifdef USE_LOGDEPTHBUF
+#endif`,hC=`#ifdef USE_LOGDEPTHBUF
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
-#endif`,dC=`#ifdef USE_MAP
+#endif`,uC=`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
-#endif`,fC=`#ifdef USE_MAP
+#endif`,dC=`#ifdef USE_MAP
uniform sampler2D map;
-#endif`,pC=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
+#endif`,fC=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
#if defined( USE_POINTS_UV )
vec2 uv = vUv;
#else
@@ -1410,7 +1410,7 @@ IncidentLight directLight;
#endif
#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, uv ).g;
-#endif`,AC=`#if defined( USE_POINTS_UV )
+#endif`,pC=`#if defined( USE_POINTS_UV )
varying vec2 vUv;
#else
#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
@@ -1422,19 +1422,19 @@ IncidentLight directLight;
#endif
#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
-#endif`,gC=`float metalnessFactor = metalness;
+#endif`,AC=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
-#endif`,mC=`#ifdef USE_METALNESSMAP
+#endif`,gC=`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
-#endif`,xC=`#ifdef USE_INSTANCING_MORPH
+#endif`,mC=`#ifdef USE_INSTANCING_MORPH
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
}
-#endif`,bC=`#if defined( USE_MORPHCOLORS )
+#endif`,xC=`#if defined( USE_MORPHCOLORS )
vColor *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
#if defined( USE_COLOR_ALPHA )
@@ -1443,12 +1443,12 @@ IncidentLight directLight;
if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
#endif
}
-#endif`,EC=`#ifdef USE_MORPHNORMALS
+#endif`,bC=`#ifdef USE_MORPHNORMALS
objectNormal *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
}
-#endif`,yC=`#ifdef USE_MORPHTARGETS
+#endif`,EC=`#ifdef USE_MORPHTARGETS
#ifndef USE_INSTANCING_MORPH
uniform float morphTargetBaseInfluence;
uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
@@ -1462,12 +1462,12 @@ IncidentLight directLight;
ivec3 morphUV = ivec3( x, y, morphTargetIndex );
return texelFetch( morphTargetsTexture, morphUV, 0 );
}
-#endif`,_C=`#ifdef USE_MORPHTARGETS
+#endif`,yC=`#ifdef USE_MORPHTARGETS
transformed *= morphTargetBaseInfluence;
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
}
-#endif`,wC=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
+#endif`,_C=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
vec3 fdx = dFdx( vViewPosition );
vec3 fdy = dFdy( vViewPosition );
@@ -1508,7 +1508,7 @@ IncidentLight directLight;
tbn2[1] *= faceDirection;
#endif
#endif
-vec3 nonPerturbedNormal = normal;`,vC=`#ifdef USE_NORMALMAP_OBJECTSPACE
+vec3 nonPerturbedNormal = normal;`,wC=`#ifdef USE_NORMALMAP_OBJECTSPACE
normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
#ifdef FLIP_SIDED
normal = - normal;
@@ -1523,25 +1523,25 @@ vec3 nonPerturbedNormal = normal;`,vC=`#ifdef USE_NORMALMAP_OBJECTSPACE
normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
-#endif`,CC=`#ifndef FLAT_SHADED
+#endif`,vC=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
-#endif`,IC=`#ifndef FLAT_SHADED
+#endif`,CC=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
-#endif`,SC=`#ifndef FLAT_SHADED
+#endif`,IC=`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#endif
-#endif`,MC=`#ifdef USE_NORMALMAP
+#endif`,SC=`#ifdef USE_NORMALMAP
uniform sampler2D normalMap;
uniform vec2 normalScale;
#endif
@@ -1563,13 +1563,13 @@ vec3 nonPerturbedNormal = normal;`,vC=`#ifdef USE_NORMALMAP_OBJECTSPACE
float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
return mat3( T * scale, B * scale, N );
}
-#endif`,BC=`#ifdef USE_CLEARCOAT
+#endif`,MC=`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
-#endif`,TC=`#ifdef USE_CLEARCOAT_NORMALMAP
+#endif`,BC=`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
-#endif`,RC=`#ifdef USE_CLEARCOATMAP
+#endif`,TC=`#ifdef USE_CLEARCOATMAP
uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
@@ -1578,18 +1578,18 @@ vec3 nonPerturbedNormal = normal;`,vC=`#ifdef USE_NORMALMAP_OBJECTSPACE
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
uniform sampler2D clearcoatRoughnessMap;
-#endif`,FC=`#ifdef USE_IRIDESCENCEMAP
+#endif`,RC=`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
-#endif`,NC=`#ifdef OPAQUE
+#endif`,FC=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
-gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,DC=`vec3 packNormalToRGB( const in vec3 normal ) {
+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,NC=`vec3 packNormalToRGB( const in vec3 normal ) {
return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
@@ -1658,9 +1658,9 @@ float viewZToPerspectiveDepth( const in float viewZ, const in float near, const
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
return ( near * far ) / ( ( far - near ) * depth - far );
-}`,LC=`#ifdef PREMULTIPLIED_ALPHA
+}`,DC=`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
-#endif`,PC=`vec4 mvPosition = vec4( transformed, 1.0 );
+#endif`,LC=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
mvPosition = batchingMatrix * mvPosition;
#endif
@@ -1668,22 +1668,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const
mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
-gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
+gl_Position = projectionMatrix * mvPosition;`,PC=`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
-#endif`,UC=`#ifdef DITHERING
+#endif`,kC=`#ifdef DITHERING
vec3 dithering( vec3 color ) {
float grid_position = rand( gl_FragCoord.xy );
vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
return color + dither_shift_RGB;
}
-#endif`,OC=`float roughnessFactor = roughness;
+#endif`,UC=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
-#endif`,QC=`#ifdef USE_ROUGHNESSMAP
+#endif`,OC=`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
-#endif`,GC=`#if NUM_SPOT_LIGHT_COORDS > 0
+#endif`,QC=`#if NUM_SPOT_LIGHT_COORDS > 0
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
@@ -1869,7 +1869,7 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
}
return mix( 1.0, shadow, shadowIntensity );
}
-#endif`,HC=`#if NUM_SPOT_LIGHT_COORDS > 0
+#endif`,GC=`#if NUM_SPOT_LIGHT_COORDS > 0
uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
@@ -1910,7 +1910,7 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
};
uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
#endif
-#endif`,zC=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
+#endif`,HC=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
vec4 shadowWorldPosition;
#endif
@@ -1942,7 +1942,7 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
}
#pragma unroll_loop_end
-#endif`,VC=`float getShadowMask() {
+#endif`,zC=`float getShadowMask() {
float shadow = 1.0;
#ifdef USE_SHADOWMAP
#if NUM_DIR_LIGHT_SHADOWS > 0
@@ -1974,12 +1974,12 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
#endif
#endif
return shadow;
-}`,WC=`#ifdef USE_SKINNING
+}`,VC=`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
-#endif`,qC=`#ifdef USE_SKINNING
+#endif`,WC=`#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
uniform highp sampler2D boneTexture;
@@ -1994,7 +1994,7 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
return mat4( v1, v2, v3, v4 );
}
-#endif`,KC=`#ifdef USE_SKINNING
+#endif`,qC=`#ifdef USE_SKINNING
vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
vec4 skinned = vec4( 0.0 );
skinned += boneMatX * skinVertex * skinWeight.x;
@@ -2002,7 +2002,7 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
skinned += boneMatZ * skinVertex * skinWeight.z;
skinned += boneMatW * skinVertex * skinWeight.w;
transformed = ( bindMatrixInverse * skinned ).xyz;
-#endif`,jC=`#ifdef USE_SKINNING
+#endif`,KC=`#ifdef USE_SKINNING
mat4 skinMatrix = mat4( 0.0 );
skinMatrix += skinWeight.x * boneMatX;
skinMatrix += skinWeight.y * boneMatY;
@@ -2013,17 +2013,17 @@ gl_Position = projectionMatrix * mvPosition;`,kC=`#ifdef DITHERING
#ifdef USE_TANGENT
objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
#endif
-#endif`,XC=`float specularStrength;
+#endif`,jC=`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
-#endif`,YC=`#ifdef USE_SPECULARMAP
+#endif`,XC=`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
-#endif`,JC=`#if defined( TONE_MAPPING )
+#endif`,YC=`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
-#endif`,ZC=`#ifndef saturate
+#endif`,JC=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
@@ -2120,7 +2120,7 @@ vec3 NeutralToneMapping( vec3 color ) {
float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
return mix( color, vec3( newPeak ), g );
}
-vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISSION
+vec3 CustomToneMapping( vec3 color ) { return color; }`,ZC=`#ifdef USE_TRANSMISSION
material.transmission = transmission;
material.transmissionAlpha = 1.0;
material.thickness = thickness;
@@ -2141,7 +2141,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
material.attenuationColor, material.attenuationDistance );
material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
-#endif`,eI=`#ifdef USE_TRANSMISSION
+#endif`,$C=`#ifdef USE_TRANSMISSION
uniform float transmission;
uniform float thickness;
uniform float attenuationDistance;
@@ -2267,7 +2267,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
}
-#endif`,tI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`,eI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
@@ -2337,7 +2337,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
-#endif`,nI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`,tI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
varying vec2 vUv;
#endif
#ifdef USE_MAP
@@ -2431,7 +2431,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
#ifdef USE_THICKNESSMAP
uniform mat3 thicknessMapTransform;
varying vec2 vThicknessMapUv;
-#endif`,iI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+#endif`,nI=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
@@ -2502,7 +2502,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
#endif
#ifdef USE_THICKNESSMAP
vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
-#endif`,sI=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
+#endif`,iI=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
vec4 worldPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
worldPosition = batchingMatrix * worldPosition;
@@ -2511,7 +2511,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,$C=`#ifdef USE_TRANSMISS
worldPosition = instanceMatrix * worldPosition;
#endif
worldPosition = modelMatrix * worldPosition;
-#endif`;const ct={alphahash_fragment:av,alphahash_pars_fragment:ov,alphamap_fragment:cv,alphamap_pars_fragment:lv,alphatest_fragment:hv,alphatest_pars_fragment:uv,aomap_fragment:dv,aomap_pars_fragment:fv,batching_pars_vertex:pv,batching_vertex:Av,begin_vertex:gv,beginnormal_vertex:mv,bsdfs:xv,iridescence_fragment:bv,bumpmap_pars_fragment:Ev,clipping_planes_fragment:yv,clipping_planes_pars_fragment:_v,clipping_planes_pars_vertex:wv,clipping_planes_vertex:vv,color_fragment:Cv,color_pars_fragment:Iv,color_pars_vertex:Sv,color_vertex:Mv,common:Bv,cube_uv_reflection_fragment:Tv,defaultnormal_vertex:Rv,displacementmap_pars_vertex:Fv,displacementmap_vertex:Nv,emissivemap_fragment:Dv,emissivemap_pars_fragment:Lv,colorspace_fragment:Pv,colorspace_pars_fragment:kv,envmap_fragment:Uv,envmap_common_pars_fragment:Ov,envmap_pars_fragment:Qv,envmap_pars_vertex:Gv,envmap_physical_pars_fragment:Zv,envmap_vertex:Hv,fog_vertex:zv,fog_pars_vertex:Vv,fog_fragment:Wv,fog_pars_fragment:qv,gradientmap_pars_fragment:Kv,lightmap_pars_fragment:jv,lights_lambert_fragment:Xv,lights_lambert_pars_fragment:Yv,lights_pars_begin:Jv,lights_toon_fragment:$v,lights_toon_pars_fragment:eC,lights_phong_fragment:tC,lights_phong_pars_fragment:nC,lights_physical_fragment:iC,lights_physical_pars_fragment:sC,lights_fragment_begin:rC,lights_fragment_maps:aC,lights_fragment_end:oC,logdepthbuf_fragment:cC,logdepthbuf_pars_fragment:lC,logdepthbuf_pars_vertex:hC,logdepthbuf_vertex:uC,map_fragment:dC,map_pars_fragment:fC,map_particle_fragment:pC,map_particle_pars_fragment:AC,metalnessmap_fragment:gC,metalnessmap_pars_fragment:mC,morphinstance_vertex:xC,morphcolor_vertex:bC,morphnormal_vertex:EC,morphtarget_pars_vertex:yC,morphtarget_vertex:_C,normal_fragment_begin:wC,normal_fragment_maps:vC,normal_pars_fragment:CC,normal_pars_vertex:IC,normal_vertex:SC,normalmap_pars_fragment:MC,clearcoat_normal_fragment_begin:BC,clearcoat_normal_fragment_maps:TC,clearcoat_pars_fragment:RC,iridescence_pars_fragment:FC,opaque_fragment:NC,packing:DC,premultiplied_alpha_fragment:LC,project_vertex:PC,dithering_fragment:kC,dithering_pars_fragment:UC,roughnessmap_fragment:OC,roughnessmap_pars_fragment:QC,shadowmap_pars_fragment:GC,shadowmap_pars_vertex:HC,shadowmap_vertex:zC,shadowmask_pars_fragment:VC,skinbase_vertex:WC,skinning_pars_vertex:qC,skinning_vertex:KC,skinnormal_vertex:jC,specularmap_fragment:XC,specularmap_pars_fragment:YC,tonemapping_fragment:JC,tonemapping_pars_fragment:ZC,transmission_fragment:$C,transmission_pars_fragment:eI,uv_pars_fragment:tI,uv_pars_vertex:nI,uv_vertex:iI,worldpos_vertex:sI,background_vert:`varying vec2 vUv;
+#endif`;const ct={alphahash_fragment:rv,alphahash_pars_fragment:av,alphamap_fragment:ov,alphamap_pars_fragment:cv,alphatest_fragment:lv,alphatest_pars_fragment:hv,aomap_fragment:uv,aomap_pars_fragment:dv,batching_pars_vertex:fv,batching_vertex:pv,begin_vertex:Av,beginnormal_vertex:gv,bsdfs:mv,iridescence_fragment:xv,bumpmap_pars_fragment:bv,clipping_planes_fragment:Ev,clipping_planes_pars_fragment:yv,clipping_planes_pars_vertex:_v,clipping_planes_vertex:wv,color_fragment:vv,color_pars_fragment:Cv,color_pars_vertex:Iv,color_vertex:Sv,common:Mv,cube_uv_reflection_fragment:Bv,defaultnormal_vertex:Tv,displacementmap_pars_vertex:Rv,displacementmap_vertex:Fv,emissivemap_fragment:Nv,emissivemap_pars_fragment:Dv,colorspace_fragment:Lv,colorspace_pars_fragment:Pv,envmap_fragment:kv,envmap_common_pars_fragment:Uv,envmap_pars_fragment:Ov,envmap_pars_vertex:Qv,envmap_physical_pars_fragment:Jv,envmap_vertex:Gv,fog_vertex:Hv,fog_pars_vertex:zv,fog_fragment:Vv,fog_pars_fragment:Wv,gradientmap_pars_fragment:qv,lightmap_pars_fragment:Kv,lights_lambert_fragment:jv,lights_lambert_pars_fragment:Xv,lights_pars_begin:Yv,lights_toon_fragment:Zv,lights_toon_pars_fragment:$v,lights_phong_fragment:eC,lights_phong_pars_fragment:tC,lights_physical_fragment:nC,lights_physical_pars_fragment:iC,lights_fragment_begin:sC,lights_fragment_maps:rC,lights_fragment_end:aC,logdepthbuf_fragment:oC,logdepthbuf_pars_fragment:cC,logdepthbuf_pars_vertex:lC,logdepthbuf_vertex:hC,map_fragment:uC,map_pars_fragment:dC,map_particle_fragment:fC,map_particle_pars_fragment:pC,metalnessmap_fragment:AC,metalnessmap_pars_fragment:gC,morphinstance_vertex:mC,morphcolor_vertex:xC,morphnormal_vertex:bC,morphtarget_pars_vertex:EC,morphtarget_vertex:yC,normal_fragment_begin:_C,normal_fragment_maps:wC,normal_pars_fragment:vC,normal_pars_vertex:CC,normal_vertex:IC,normalmap_pars_fragment:SC,clearcoat_normal_fragment_begin:MC,clearcoat_normal_fragment_maps:BC,clearcoat_pars_fragment:TC,iridescence_pars_fragment:RC,opaque_fragment:FC,packing:NC,premultiplied_alpha_fragment:DC,project_vertex:LC,dithering_fragment:PC,dithering_pars_fragment:kC,roughnessmap_fragment:UC,roughnessmap_pars_fragment:OC,shadowmap_pars_fragment:QC,shadowmap_pars_vertex:GC,shadowmap_vertex:HC,shadowmask_pars_fragment:zC,skinbase_vertex:VC,skinning_pars_vertex:WC,skinning_vertex:qC,skinnormal_vertex:KC,specularmap_fragment:jC,specularmap_pars_fragment:XC,tonemapping_fragment:YC,tonemapping_pars_fragment:JC,transmission_fragment:ZC,transmission_pars_fragment:$C,uv_pars_fragment:eI,uv_pars_vertex:tI,uv_vertex:nI,worldpos_vertex:iI,background_vert:`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
@@ -3563,7 +3563,7 @@ void main() {
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
-}`},we={common:{diffuse:{value:new Fe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ot},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ot}},envmap:{envMap:{value:null},envMapRotation:{value:new ot},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ot},normalScale:{value:new Je(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Fe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Fe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0},uvTransform:{value:new ot}},sprite:{diffuse:{value:new Fe(16777215)},opacity:{value:1},center:{value:new Je(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ot},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0}}},Qi={basic:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.fog]),vertexShader:ct.meshbasic_vert,fragmentShader:ct.meshbasic_frag},lambert:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.fog,we.lights,{emissive:{value:new Fe(0)}}]),vertexShader:ct.meshlambert_vert,fragmentShader:ct.meshlambert_frag},phong:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.fog,we.lights,{emissive:{value:new Fe(0)},specular:{value:new Fe(1118481)},shininess:{value:30}}]),vertexShader:ct.meshphong_vert,fragmentShader:ct.meshphong_frag},standard:{uniforms:Un([we.common,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.roughnessmap,we.metalnessmap,we.fog,we.lights,{emissive:{value:new Fe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ct.meshphysical_vert,fragmentShader:ct.meshphysical_frag},toon:{uniforms:Un([we.common,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.gradientmap,we.fog,we.lights,{emissive:{value:new Fe(0)}}]),vertexShader:ct.meshtoon_vert,fragmentShader:ct.meshtoon_frag},matcap:{uniforms:Un([we.common,we.bumpmap,we.normalmap,we.displacementmap,we.fog,{matcap:{value:null}}]),vertexShader:ct.meshmatcap_vert,fragmentShader:ct.meshmatcap_frag},points:{uniforms:Un([we.points,we.fog]),vertexShader:ct.points_vert,fragmentShader:ct.points_frag},dashed:{uniforms:Un([we.common,we.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ct.linedashed_vert,fragmentShader:ct.linedashed_frag},depth:{uniforms:Un([we.common,we.displacementmap]),vertexShader:ct.depth_vert,fragmentShader:ct.depth_frag},normal:{uniforms:Un([we.common,we.bumpmap,we.normalmap,we.displacementmap,{opacity:{value:1}}]),vertexShader:ct.meshnormal_vert,fragmentShader:ct.meshnormal_frag},sprite:{uniforms:Un([we.sprite,we.fog]),vertexShader:ct.sprite_vert,fragmentShader:ct.sprite_frag},background:{uniforms:{uvTransform:{value:new ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ct.background_vert,fragmentShader:ct.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ot}},vertexShader:ct.backgroundCube_vert,fragmentShader:ct.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ct.cube_vert,fragmentShader:ct.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ct.equirect_vert,fragmentShader:ct.equirect_frag},distanceRGBA:{uniforms:Un([we.common,we.displacementmap,{referencePosition:{value:new G},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ct.distanceRGBA_vert,fragmentShader:ct.distanceRGBA_frag},shadow:{uniforms:Un([we.lights,we.fog,{color:{value:new Fe(0)},opacity:{value:1}}]),vertexShader:ct.shadow_vert,fragmentShader:ct.shadow_frag}};Qi.physical={uniforms:Un([Qi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ot},clearcoatNormalScale:{value:new Je(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ot},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ot},sheen:{value:0},sheenColor:{value:new Fe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ot},transmissionSamplerSize:{value:new Je},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ot},attenuationDistance:{value:0},attenuationColor:{value:new Fe(0)},specularColor:{value:new Fe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ot},anisotropyVector:{value:new Je},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ot}}]),vertexShader:ct.meshphysical_vert,fragmentShader:ct.meshphysical_frag};const Tl={r:0,b:0,g:0},gr=new dn,rI=new Re;function aI(i,e,t,n,s,r,a){const o=new Fe(0);let c=r===!0?0:1,l,h,u=null,d=0,f=null;function p(x){let E=x.isScene===!0?x.background:null;return E&&E.isTexture&&(E=(x.backgroundBlurriness>0?t:e).get(E)),E}function m(x){let E=!1;const S=p(x);S===null?A(o,c):S&&S.isColor&&(A(S,1),E=!0);const w=i.xr.getEnvironmentBlendMode();w==="additive"?n.buffers.color.setClear(0,0,0,1,a):w==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||E)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function g(x,E){const S=p(E);S&&(S.isCubeTexture||S.mapping===Bc)?(h===void 0&&(h=new Zt(new da(1,1,1),new Ls({name:"BackgroundCubeMaterial",uniforms:fa(Qi.backgroundCube.uniforms),vertexShader:Qi.backgroundCube.vertexShader,fragmentShader:Qi.backgroundCube.fragmentShader,side:Ln,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(w,I,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(h)),gr.copy(E.backgroundRotation),gr.x*=-1,gr.y*=-1,gr.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(gr.y*=-1,gr.z*=-1),h.material.uniforms.envMap.value=S,h.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(rI.makeRotationFromEuler(gr)),h.material.toneMapped=tt.getTransfer(S.colorSpace)!==Rt,(u!==S||d!==S.version||f!==i.toneMapping)&&(h.material.needsUpdate=!0,u=S,d=S.version,f=i.toneMapping),h.layers.enableAll(),x.unshift(h,h.geometry,h.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Zt(new vl(2,2),new Ls({name:"BackgroundMaterial",uniforms:fa(Qi.background.uniforms),vertexShader:Qi.background.vertexShader,fragmentShader:Qi.background.fragmentShader,side:ji,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=tt.getTransfer(S.colorSpace)!==Rt,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||d!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,d=S.version,f=i.toneMapping),l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null))}function A(x,E){x.getRGB(Tl,DA(i)),n.buffers.color.setClear(Tl.r,Tl.g,Tl.b,E,a)}function _(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(x,E=1){o.set(x),c=E,A(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(x){c=x,A(o,c)},render:m,addToRenderList:g,dispose:_}}function oI(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=d(null);let r=s,a=!1;function o(v,F,K,q,$){let D=!1;const O=u(q,K,F);r!==O&&(r=O,l(r.object)),D=f(v,q,K,$),D&&p(v,q,K,$),$!==null&&e.update($,i.ELEMENT_ARRAY_BUFFER),(D||a)&&(a=!1,E(v,F,K,q),$!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get($).buffer))}function c(){return i.createVertexArray()}function l(v){return i.bindVertexArray(v)}function h(v){return i.deleteVertexArray(v)}function u(v,F,K){const q=K.wireframe===!0;let $=n[v.id];$===void 0&&($={},n[v.id]=$);let D=$[F.id];D===void 0&&(D={},$[F.id]=D);let O=D[q];return O===void 0&&(O=d(c()),D[q]=O),O}function d(v){const F=[],K=[],q=[];for(let $=0;$<t;$++)F[$]=0,K[$]=0,q[$]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:F,enabledAttributes:K,attributeDivisors:q,object:v,attributes:{},index:null}}function f(v,F,K,q){const $=r.attributes,D=F.attributes;let O=0;const Y=K.getAttributes();for(const Q in Y)if(Y[Q].location>=0){const ee=$[Q];let ae=D[Q];if(ae===void 0&&(Q==="instanceMatrix"&&v.instanceMatrix&&(ae=v.instanceMatrix),Q==="instanceColor"&&v.instanceColor&&(ae=v.instanceColor)),ee===void 0||ee.attribute!==ae||ae&&ee.data!==ae.data)return!0;O++}return r.attributesNum!==O||r.index!==q}function p(v,F,K,q){const $={},D=F.attributes;let O=0;const Y=K.getAttributes();for(const Q in Y)if(Y[Q].location>=0){let ee=D[Q];ee===void 0&&(Q==="instanceMatrix"&&v.instanceMatrix&&(ee=v.instanceMatrix),Q==="instanceColor"&&v.instanceColor&&(ee=v.instanceColor));const ae={};ae.attribute=ee,ee&&ee.data&&(ae.data=ee.data),$[Q]=ae,O++}r.attributes=$,r.attributesNum=O,r.index=q}function m(){const v=r.newAttributes;for(let F=0,K=v.length;F<K;F++)v[F]=0}function g(v){A(v,0)}function A(v,F){const K=r.newAttributes,q=r.enabledAttributes,$=r.attributeDivisors;K[v]=1,q[v]===0&&(i.enableVertexAttribArray(v),q[v]=1),$[v]!==F&&(i.vertexAttribDivisor(v,F),$[v]=F)}function _(){const v=r.newAttributes,F=r.enabledAttributes;for(let K=0,q=F.length;K<q;K++)F[K]!==v[K]&&(i.disableVertexAttribArray(K),F[K]=0)}function x(v,F,K,q,$,D,O){O===!0?i.vertexAttribIPointer(v,F,K,$,D):i.vertexAttribPointer(v,F,K,q,$,D)}function E(v,F,K,q){m();const $=q.attributes,D=K.getAttributes(),O=F.defaultAttributeValues;for(const Y in D){const Q=D[Y];if(Q.location>=0){let J=$[Y];if(J===void 0&&(Y==="instanceMatrix"&&v.instanceMatrix&&(J=v.instanceMatrix),Y==="instanceColor"&&v.instanceColor&&(J=v.instanceColor)),J!==void 0){const ee=J.normalized,ae=J.itemSize,_e=e.get(J);if(_e===void 0)continue;const Me=_e.buffer,se=_e.type,me=_e.bytesPerElement,xe=se===i.INT||se===i.UNSIGNED_INT||J.gpuType===nu;if(J.isInterleavedBufferAttribute){const be=J.data,Ue=be.stride,et=J.offset;if(be.isInstancedInterleavedBuffer){for(let He=0;He<Q.locationSize;He++)A(Q.location+He,be.meshPerAttribute);v.isInstancedMesh!==!0&&q._maxInstanceCount===void 0&&(q._maxInstanceCount=be.meshPerAttribute*be.count)}else for(let He=0;He<Q.locationSize;He++)g(Q.location+He);i.bindBuffer(i.ARRAY_BUFFER,Me);for(let He=0;He<Q.locationSize;He++)x(Q.location+He,ae/Q.locationSize,se,ee,Ue*me,(et+ae/Q.locationSize*He)*me,xe)}else{if(J.isInstancedBufferAttribute){for(let be=0;be<Q.locationSize;be++)A(Q.location+be,J.meshPerAttribute);v.isInstancedMesh!==!0&&q._maxInstanceCount===void 0&&(q._maxInstanceCount=J.meshPerAttribute*J.count)}else for(let be=0;be<Q.locationSize;be++)g(Q.location+be);i.bindBuffer(i.ARRAY_BUFFER,Me);for(let be=0;be<Q.locationSize;be++)x(Q.location+be,ae/Q.locationSize,se,ee,ae*me,ae/Q.locationSize*be*me,xe)}}else if(O!==void 0){const ee=O[Y];if(ee!==void 0)switch(ee.length){case 2:i.vertexAttrib2fv(Q.location,ee);break;case 3:i.vertexAttrib3fv(Q.location,ee);break;case 4:i.vertexAttrib4fv(Q.location,ee);break;default:i.vertexAttrib1fv(Q.location,ee)}}}}_()}function S(){T();for(const v in n){const F=n[v];for(const K in F){const q=F[K];for(const $ in q)h(q[$].object),delete q[$];delete F[K]}delete n[v]}}function w(v){if(n[v.id]===void 0)return;const F=n[v.id];for(const K in F){const q=F[K];for(const $ in q)h(q[$].object),delete q[$];delete F[K]}delete n[v.id]}function I(v){for(const F in n){const K=n[F];if(K[v.id]===void 0)continue;const q=K[v.id];for(const $ in q)h(q[$].object),delete q[$];delete K[v.id]}}function T(){C(),a=!0,r!==s&&(r=s,l(r.object))}function C(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:o,reset:T,resetDefaultState:C,dispose:S,releaseStatesOfGeometry:w,releaseStatesOfProgram:I,initAttributes:m,enableAttribute:g,disableUnusedAttributes:_}}function cI(i,e,t){let n;function s(l){n=l}function r(l,h){i.drawArrays(n,l,h),t.update(h,n,1)}function a(l,h,u){u!==0&&(i.drawArraysInstanced(n,l,h,u),t.update(h,n,u))}function o(l,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,h,0,u);let f=0;for(let p=0;p<u;p++)f+=h[p];t.update(f,n,1)}function c(l,h,u,d){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let p=0;p<l.length;p++)a(l[p],h[p],d[p]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,h,0,d,0,u);let p=0;for(let m=0;m<u;m++)p+=h[m]*d[m];t.update(p,n,1)}}this.setMode=s,this.render=r,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=c}function lI(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const I=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(I.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function a(I){return!(I!==hn&&n.convert(I)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(I){const T=I===kn&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(I!==cn&&n.convert(I)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&I!==ln&&!T)}function c(I){if(I==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";I="mediump"}return I==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const h=c(l);h!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);const u=t.logarithmicDepthBuffer===!0,d=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),p=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=i.getParameter(i.MAX_TEXTURE_SIZE),g=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),A=i.getParameter(i.MAX_VERTEX_ATTRIBS),_=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),x=i.getParameter(i.MAX_VARYING_VECTORS),E=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=p>0,w=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:u,reverseDepthBuffer:d,maxTextures:f,maxVertexTextures:p,maxTextureSize:m,maxCubemapSize:g,maxAttributes:A,maxVertexUniforms:_,maxVaryings:x,maxFragmentUniforms:E,vertexTextures:S,maxSamples:w}}function hI(i){const e=this;let t=null,n=0,s=!1,r=!1;const a=new ks,o=new ot,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||n!==0||s;return s=d,n=u.length,f},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,m=u.clipIntersection,g=u.clipShadows,A=i.get(u);if(!s||p===null||p.length===0||r&&!g)r?h(null):l();else{const _=r?0:n,x=_*4;let E=A.clippingState||null;c.value=E,E=h(p,d,x,f);for(let S=0;S!==x;++S)E[S]=t[S];A.clippingState=E,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=_}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,d,f,p){const m=u!==null?u.length:0;let g=null;if(m!==0){if(g=c.value,p!==!0||g===null){const A=f+m*4,_=d.matrixWorldInverse;o.getNormalMatrix(_),(g===null||g.length<A)&&(g=new Float32Array(A));for(let x=0,E=f;x!==m;++x,E+=4)a.copy(u[x]).applyMatrix4(_,o),a.normal.toArray(g,E),g[E+3]=a.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=m,e.numIntersection=0,g}}function uI(i){let e=new WeakMap;function t(a,o){return o===Mc?a.mapping=sr:o===tu&&(a.mapping=Yr),a}function n(a){if(a&&a.isTexture){const o=a.mapping;if(o===Mc||o===tu)if(e.has(a)){const c=e.get(a).texture;return t(c,a.mapping)}else{const c=a.image;if(c&&c.height>0){const l=new q_(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",s),t(l.texture,a.mapping)}else return null}}return a}function s(a){const o=a.target;o.removeEventListener("dispose",s);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const ya=4,Ig=[.125,.215,.35,.446,.526,.582],mr=20,Ed=new Ad,Sg=new Fe;let yd=null,_d=0,wd=0,vd=!1;const xr=(1+Math.sqrt(5))/2,_a=1/xr,Mg=[new G(-xr,_a,0),new G(xr,_a,0),new G(-_a,0,xr),new G(_a,0,xr),new G(0,xr,-_a),new G(0,xr,_a),new G(-1,1,-1),new G(1,1,-1),new G(-1,1,1),new G(1,1,1)],dI=new G;class Cd{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,s=100,r={}){const{size:a=256,position:o=dI}=r;yd=this._renderer.getRenderTarget(),_d=this._renderer.getActiveCubeFace(),wd=this._renderer.getActiveMipmapLevel(),vd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Rg(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Tg(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(yd,_d,wd),this._renderer.xr.enabled=vd,e.scissorTest=!1,Rl(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===sr||e.mapping===Yr?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),yd=this._renderer.getRenderTarget(),_d=this._renderer.getActiveCubeFace(),wd=this._renderer.getActiveMipmapLevel(),vd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:qt,minFilter:qt,generateMipmaps:!1,type:kn,format:hn,colorSpace:un,depthBuffer:!1},s=Bg(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Bg(e,t,n);const{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=fI(r)),this._blurMaterial=pI(r,e,t)}return s}_compileMaterial(e){const t=new Zt(this._lodPlanes[0],e);this._renderer.compile(t,Ed)}_sceneToCubeUV(e,t,n,s,r){const c=new Bn(90,1,t,n),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,f=u.toneMapping;u.getClearColor(Sg),u.toneMapping=Is,u.autoClear=!1;const p=new Ds({name:"PMREM.Background",side:Ln,depthWrite:!1,depthTest:!1}),m=new Zt(new da,p);let g=!1;const A=e.background;A?A.isColor&&(p.color.copy(A),e.background=null,g=!0):(p.color.copy(Sg),g=!0);for(let _=0;_<6;_++){const x=_%3;x===0?(c.up.set(0,l[_],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+h[_],r.y,r.z)):x===1?(c.up.set(0,0,l[_]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+h[_],r.z)):(c.up.set(0,l[_],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+h[_]));const E=this._cubeSize;Rl(s,x*E,_>2?E:0,E,E),u.setRenderTarget(s),g&&u.render(m,c),u.render(e,c)}m.geometry.dispose(),m.material.dispose(),u.toneMapping=f,u.autoClear=d,e.background=A}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===sr||e.mapping===Yr;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Rg()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Tg());const r=s?this._cubemapMaterial:this._equirectMaterial,a=new Zt(this._lodPlanes[0],r),o=r.uniforms;o.envMap.value=e;const c=this._cubeSize;Rl(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,Ed)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let r=1;r<s;r++){const a=Math.sqrt(this._sigmas[r]*this._sigmas[r]-this._sigmas[r-1]*this._sigmas[r-1]),o=Mg[(s-r-1)%Mg.length];this._blur(e,r-1,r,a,o)}t.autoClear=n}_blur(e,t,n,s,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,s,"latitudinal",r),this._halfBlur(a,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,a,o){const c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new Zt(this._lodPlanes[s],l),d=l.uniforms,f=this._sizeLods[n]-1,p=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*mr-1),m=r/p,g=isFinite(r)?1+Math.floor(h*m):mr;g>mr&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${mr}`);const A=[];let _=0;for(let I=0;I<mr;++I){const T=I/m,C=Math.exp(-T*T/2);A.push(C),I===0?_+=C:I<g&&(_+=2*C)}for(let I=0;I<A.length;I++)A[I]=A[I]/_;d.envMap.value=e.texture,d.samples.value=g,d.weights.value=A,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:x}=this;d.dTheta.value=p,d.mipInt.value=x-n;const E=this._sizeLods[s],S=3*E*(s>x-ya?s-x+ya:0),w=4*(this._cubeSize-E);Rl(t,S,w,3*E,2*E),c.setRenderTarget(t),c.render(u,Ed)}}function fI(i){const e=[],t=[],n=[];let s=i;const r=i-ya+1+Ig.length;for(let a=0;a<r;a++){const o=Math.pow(2,s);t.push(o);let c=1/o;a>i-ya?c=Ig[a-i+ya-1]:a===0&&(c=0),n.push(c);const l=1/(o-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,m=3,g=2,A=1,_=new Float32Array(m*p*f),x=new Float32Array(g*p*f),E=new Float32Array(A*p*f);for(let w=0;w<f;w++){const I=w%3*2/3-1,T=w>2?0:-1,C=[I,T,0,I+2/3,T,0,I+2/3,T+1,0,I,T,0,I+2/3,T+1,0,I,T+1,0];_.set(C,m*p*w),x.set(d,g*p*w);const v=[w,w,w,w,w,w];E.set(v,A*p*w)}const S=new Mn;S.setAttribute("position",new Sn(_,m)),S.setAttribute("uv",new Sn(x,g)),S.setAttribute("faceIndex",new Sn(E,A)),e.push(S),s>ya&&s--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Bg(i,e,t){const n=new or(i,e,t);return n.texture.mapping=Bc,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Rl(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function pI(i,e,t){const n=new Float32Array(mr),s=new G(0,1,0);return new Ls({name:"SphericalGaussianBlur",defines:{n:mr,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Id(),fragmentShader:`
+}`},we={common:{diffuse:{value:new Fe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ot},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ot}},envmap:{envMap:{value:null},envMapRotation:{value:new ot},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ot},normalScale:{value:new Je(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Fe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Fe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0},uvTransform:{value:new ot}},sprite:{diffuse:{value:new Fe(16777215)},opacity:{value:1},center:{value:new Je(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ot},alphaMap:{value:null},alphaMapTransform:{value:new ot},alphaTest:{value:0}}},Qi={basic:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.fog]),vertexShader:ct.meshbasic_vert,fragmentShader:ct.meshbasic_frag},lambert:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.fog,we.lights,{emissive:{value:new Fe(0)}}]),vertexShader:ct.meshlambert_vert,fragmentShader:ct.meshlambert_frag},phong:{uniforms:Un([we.common,we.specularmap,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.fog,we.lights,{emissive:{value:new Fe(0)},specular:{value:new Fe(1118481)},shininess:{value:30}}]),vertexShader:ct.meshphong_vert,fragmentShader:ct.meshphong_frag},standard:{uniforms:Un([we.common,we.envmap,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.roughnessmap,we.metalnessmap,we.fog,we.lights,{emissive:{value:new Fe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ct.meshphysical_vert,fragmentShader:ct.meshphysical_frag},toon:{uniforms:Un([we.common,we.aomap,we.lightmap,we.emissivemap,we.bumpmap,we.normalmap,we.displacementmap,we.gradientmap,we.fog,we.lights,{emissive:{value:new Fe(0)}}]),vertexShader:ct.meshtoon_vert,fragmentShader:ct.meshtoon_frag},matcap:{uniforms:Un([we.common,we.bumpmap,we.normalmap,we.displacementmap,we.fog,{matcap:{value:null}}]),vertexShader:ct.meshmatcap_vert,fragmentShader:ct.meshmatcap_frag},points:{uniforms:Un([we.points,we.fog]),vertexShader:ct.points_vert,fragmentShader:ct.points_frag},dashed:{uniforms:Un([we.common,we.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ct.linedashed_vert,fragmentShader:ct.linedashed_frag},depth:{uniforms:Un([we.common,we.displacementmap]),vertexShader:ct.depth_vert,fragmentShader:ct.depth_frag},normal:{uniforms:Un([we.common,we.bumpmap,we.normalmap,we.displacementmap,{opacity:{value:1}}]),vertexShader:ct.meshnormal_vert,fragmentShader:ct.meshnormal_frag},sprite:{uniforms:Un([we.sprite,we.fog]),vertexShader:ct.sprite_vert,fragmentShader:ct.sprite_frag},background:{uniforms:{uvTransform:{value:new ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ct.background_vert,fragmentShader:ct.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ot}},vertexShader:ct.backgroundCube_vert,fragmentShader:ct.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ct.cube_vert,fragmentShader:ct.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ct.equirect_vert,fragmentShader:ct.equirect_frag},distanceRGBA:{uniforms:Un([we.common,we.displacementmap,{referencePosition:{value:new G},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ct.distanceRGBA_vert,fragmentShader:ct.distanceRGBA_frag},shadow:{uniforms:Un([we.lights,we.fog,{color:{value:new Fe(0)},opacity:{value:1}}]),vertexShader:ct.shadow_vert,fragmentShader:ct.shadow_frag}};Qi.physical={uniforms:Un([Qi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ot},clearcoatNormalScale:{value:new Je(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ot},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ot},sheen:{value:0},sheenColor:{value:new Fe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ot},transmissionSamplerSize:{value:new Je},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ot},attenuationDistance:{value:0},attenuationColor:{value:new Fe(0)},specularColor:{value:new Fe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ot},anisotropyVector:{value:new Je},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ot}}]),vertexShader:ct.meshphysical_vert,fragmentShader:ct.meshphysical_frag};const Tl={r:0,b:0,g:0},gr=new dn,sI=new Re;function rI(i,e,t,n,s,r,a){const o=new Fe(0);let c=r===!0?0:1,l,h,u=null,d=0,f=null;function p(x){let E=x.isScene===!0?x.background:null;return E&&E.isTexture&&(E=(x.backgroundBlurriness>0?t:e).get(E)),E}function m(x){let E=!1;const S=p(x);S===null?A(o,c):S&&S.isColor&&(A(S,1),E=!0);const w=i.xr.getEnvironmentBlendMode();w==="additive"?n.buffers.color.setClear(0,0,0,1,a):w==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||E)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function g(x,E){const S=p(E);S&&(S.isCubeTexture||S.mapping===Bc)?(h===void 0&&(h=new Zt(new da(1,1,1),new Ls({name:"BackgroundCubeMaterial",uniforms:fa(Qi.backgroundCube.uniforms),vertexShader:Qi.backgroundCube.vertexShader,fragmentShader:Qi.backgroundCube.fragmentShader,side:Ln,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(w,I,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(h)),gr.copy(E.backgroundRotation),gr.x*=-1,gr.y*=-1,gr.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(gr.y*=-1,gr.z*=-1),h.material.uniforms.envMap.value=S,h.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(sI.makeRotationFromEuler(gr)),h.material.toneMapped=tt.getTransfer(S.colorSpace)!==Rt,(u!==S||d!==S.version||f!==i.toneMapping)&&(h.material.needsUpdate=!0,u=S,d=S.version,f=i.toneMapping),h.layers.enableAll(),x.unshift(h,h.geometry,h.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Zt(new vl(2,2),new Ls({name:"BackgroundMaterial",uniforms:fa(Qi.background.uniforms),vertexShader:Qi.background.vertexShader,fragmentShader:Qi.background.fragmentShader,side:ji,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=tt.getTransfer(S.colorSpace)!==Rt,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||d!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,d=S.version,f=i.toneMapping),l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null))}function A(x,E){x.getRGB(Tl,DA(i)),n.buffers.color.setClear(Tl.r,Tl.g,Tl.b,E,a)}function _(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(x,E=1){o.set(x),c=E,A(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(x){c=x,A(o,c)},render:m,addToRenderList:g,dispose:_}}function aI(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=d(null);let r=s,a=!1;function o(v,F,K,q,$){let D=!1;const O=u(q,K,F);r!==O&&(r=O,l(r.object)),D=f(v,q,K,$),D&&p(v,q,K,$),$!==null&&e.update($,i.ELEMENT_ARRAY_BUFFER),(D||a)&&(a=!1,E(v,F,K,q),$!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get($).buffer))}function c(){return i.createVertexArray()}function l(v){return i.bindVertexArray(v)}function h(v){return i.deleteVertexArray(v)}function u(v,F,K){const q=K.wireframe===!0;let $=n[v.id];$===void 0&&($={},n[v.id]=$);let D=$[F.id];D===void 0&&(D={},$[F.id]=D);let O=D[q];return O===void 0&&(O=d(c()),D[q]=O),O}function d(v){const F=[],K=[],q=[];for(let $=0;$<t;$++)F[$]=0,K[$]=0,q[$]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:F,enabledAttributes:K,attributeDivisors:q,object:v,attributes:{},index:null}}function f(v,F,K,q){const $=r.attributes,D=F.attributes;let O=0;const Y=K.getAttributes();for(const Q in Y)if(Y[Q].location>=0){const ee=$[Q];let ae=D[Q];if(ae===void 0&&(Q==="instanceMatrix"&&v.instanceMatrix&&(ae=v.instanceMatrix),Q==="instanceColor"&&v.instanceColor&&(ae=v.instanceColor)),ee===void 0||ee.attribute!==ae||ae&&ee.data!==ae.data)return!0;O++}return r.attributesNum!==O||r.index!==q}function p(v,F,K,q){const $={},D=F.attributes;let O=0;const Y=K.getAttributes();for(const Q in Y)if(Y[Q].location>=0){let ee=D[Q];ee===void 0&&(Q==="instanceMatrix"&&v.instanceMatrix&&(ee=v.instanceMatrix),Q==="instanceColor"&&v.instanceColor&&(ee=v.instanceColor));const ae={};ae.attribute=ee,ee&&ee.data&&(ae.data=ee.data),$[Q]=ae,O++}r.attributes=$,r.attributesNum=O,r.index=q}function m(){const v=r.newAttributes;for(let F=0,K=v.length;F<K;F++)v[F]=0}function g(v){A(v,0)}function A(v,F){const K=r.newAttributes,q=r.enabledAttributes,$=r.attributeDivisors;K[v]=1,q[v]===0&&(i.enableVertexAttribArray(v),q[v]=1),$[v]!==F&&(i.vertexAttribDivisor(v,F),$[v]=F)}function _(){const v=r.newAttributes,F=r.enabledAttributes;for(let K=0,q=F.length;K<q;K++)F[K]!==v[K]&&(i.disableVertexAttribArray(K),F[K]=0)}function x(v,F,K,q,$,D,O){O===!0?i.vertexAttribIPointer(v,F,K,$,D):i.vertexAttribPointer(v,F,K,q,$,D)}function E(v,F,K,q){m();const $=q.attributes,D=K.getAttributes(),O=F.defaultAttributeValues;for(const Y in D){const Q=D[Y];if(Q.location>=0){let J=$[Y];if(J===void 0&&(Y==="instanceMatrix"&&v.instanceMatrix&&(J=v.instanceMatrix),Y==="instanceColor"&&v.instanceColor&&(J=v.instanceColor)),J!==void 0){const ee=J.normalized,ae=J.itemSize,_e=e.get(J);if(_e===void 0)continue;const Me=_e.buffer,se=_e.type,me=_e.bytesPerElement,xe=se===i.INT||se===i.UNSIGNED_INT||J.gpuType===nu;if(J.isInterleavedBufferAttribute){const be=J.data,Ue=be.stride,et=J.offset;if(be.isInstancedInterleavedBuffer){for(let He=0;He<Q.locationSize;He++)A(Q.location+He,be.meshPerAttribute);v.isInstancedMesh!==!0&&q._maxInstanceCount===void 0&&(q._maxInstanceCount=be.meshPerAttribute*be.count)}else for(let He=0;He<Q.locationSize;He++)g(Q.location+He);i.bindBuffer(i.ARRAY_BUFFER,Me);for(let He=0;He<Q.locationSize;He++)x(Q.location+He,ae/Q.locationSize,se,ee,Ue*me,(et+ae/Q.locationSize*He)*me,xe)}else{if(J.isInstancedBufferAttribute){for(let be=0;be<Q.locationSize;be++)A(Q.location+be,J.meshPerAttribute);v.isInstancedMesh!==!0&&q._maxInstanceCount===void 0&&(q._maxInstanceCount=J.meshPerAttribute*J.count)}else for(let be=0;be<Q.locationSize;be++)g(Q.location+be);i.bindBuffer(i.ARRAY_BUFFER,Me);for(let be=0;be<Q.locationSize;be++)x(Q.location+be,ae/Q.locationSize,se,ee,ae*me,ae/Q.locationSize*be*me,xe)}}else if(O!==void 0){const ee=O[Y];if(ee!==void 0)switch(ee.length){case 2:i.vertexAttrib2fv(Q.location,ee);break;case 3:i.vertexAttrib3fv(Q.location,ee);break;case 4:i.vertexAttrib4fv(Q.location,ee);break;default:i.vertexAttrib1fv(Q.location,ee)}}}}_()}function S(){T();for(const v in n){const F=n[v];for(const K in F){const q=F[K];for(const $ in q)h(q[$].object),delete q[$];delete F[K]}delete n[v]}}function w(v){if(n[v.id]===void 0)return;const F=n[v.id];for(const K in F){const q=F[K];for(const $ in q)h(q[$].object),delete q[$];delete F[K]}delete n[v.id]}function I(v){for(const F in n){const K=n[F];if(K[v.id]===void 0)continue;const q=K[v.id];for(const $ in q)h(q[$].object),delete q[$];delete K[v.id]}}function T(){C(),a=!0,r!==s&&(r=s,l(r.object))}function C(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:o,reset:T,resetDefaultState:C,dispose:S,releaseStatesOfGeometry:w,releaseStatesOfProgram:I,initAttributes:m,enableAttribute:g,disableUnusedAttributes:_}}function oI(i,e,t){let n;function s(l){n=l}function r(l,h){i.drawArrays(n,l,h),t.update(h,n,1)}function a(l,h,u){u!==0&&(i.drawArraysInstanced(n,l,h,u),t.update(h,n,u))}function o(l,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,h,0,u);let f=0;for(let p=0;p<u;p++)f+=h[p];t.update(f,n,1)}function c(l,h,u,d){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let p=0;p<l.length;p++)a(l[p],h[p],d[p]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,h,0,d,0,u);let p=0;for(let m=0;m<u;m++)p+=h[m]*d[m];t.update(p,n,1)}}this.setMode=s,this.render=r,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=c}function cI(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const I=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(I.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function a(I){return!(I!==hn&&n.convert(I)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(I){const T=I===kn&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(I!==cn&&n.convert(I)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&I!==ln&&!T)}function c(I){if(I==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";I="mediump"}return I==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const h=c(l);h!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);const u=t.logarithmicDepthBuffer===!0,d=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),p=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=i.getParameter(i.MAX_TEXTURE_SIZE),g=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),A=i.getParameter(i.MAX_VERTEX_ATTRIBS),_=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),x=i.getParameter(i.MAX_VARYING_VECTORS),E=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=p>0,w=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:u,reverseDepthBuffer:d,maxTextures:f,maxVertexTextures:p,maxTextureSize:m,maxCubemapSize:g,maxAttributes:A,maxVertexUniforms:_,maxVaryings:x,maxFragmentUniforms:E,vertexTextures:S,maxSamples:w}}function lI(i){const e=this;let t=null,n=0,s=!1,r=!1;const a=new ks,o=new ot,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const f=u.length!==0||d||n!==0||s;return s=d,n=u.length,f},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,f){const p=u.clippingPlanes,m=u.clipIntersection,g=u.clipShadows,A=i.get(u);if(!s||p===null||p.length===0||r&&!g)r?h(null):l();else{const _=r?0:n,x=_*4;let E=A.clippingState||null;c.value=E,E=h(p,d,x,f);for(let S=0;S!==x;++S)E[S]=t[S];A.clippingState=E,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=_}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,d,f,p){const m=u!==null?u.length:0;let g=null;if(m!==0){if(g=c.value,p!==!0||g===null){const A=f+m*4,_=d.matrixWorldInverse;o.getNormalMatrix(_),(g===null||g.length<A)&&(g=new Float32Array(A));for(let x=0,E=f;x!==m;++x,E+=4)a.copy(u[x]).applyMatrix4(_,o),a.normal.toArray(g,E),g[E+3]=a.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=m,e.numIntersection=0,g}}function hI(i){let e=new WeakMap;function t(a,o){return o===Mc?a.mapping=sr:o===tu&&(a.mapping=Yr),a}function n(a){if(a&&a.isTexture){const o=a.mapping;if(o===Mc||o===tu)if(e.has(a)){const c=e.get(a).texture;return t(c,a.mapping)}else{const c=a.image;if(c&&c.height>0){const l=new W_(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",s),t(l.texture,a.mapping)}else return null}}return a}function s(a){const o=a.target;o.removeEventListener("dispose",s);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const ya=4,Ig=[.125,.215,.35,.446,.526,.582],mr=20,Ed=new Ad,Sg=new Fe;let yd=null,_d=0,wd=0,vd=!1;const xr=(1+Math.sqrt(5))/2,_a=1/xr,Mg=[new G(-xr,_a,0),new G(xr,_a,0),new G(-_a,0,xr),new G(_a,0,xr),new G(0,xr,-_a),new G(0,xr,_a),new G(-1,1,-1),new G(1,1,-1),new G(-1,1,1),new G(1,1,1)],uI=new G;class Cd{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,s=100,r={}){const{size:a=256,position:o=uI}=r;yd=this._renderer.getRenderTarget(),_d=this._renderer.getActiveCubeFace(),wd=this._renderer.getActiveMipmapLevel(),vd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Rg(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Tg(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(yd,_d,wd),this._renderer.xr.enabled=vd,e.scissorTest=!1,Rl(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===sr||e.mapping===Yr?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),yd=this._renderer.getRenderTarget(),_d=this._renderer.getActiveCubeFace(),wd=this._renderer.getActiveMipmapLevel(),vd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:qt,minFilter:qt,generateMipmaps:!1,type:kn,format:hn,colorSpace:un,depthBuffer:!1},s=Bg(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Bg(e,t,n);const{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=dI(r)),this._blurMaterial=fI(r,e,t)}return s}_compileMaterial(e){const t=new Zt(this._lodPlanes[0],e);this._renderer.compile(t,Ed)}_sceneToCubeUV(e,t,n,s,r){const c=new Bn(90,1,t,n),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,f=u.toneMapping;u.getClearColor(Sg),u.toneMapping=Is,u.autoClear=!1;const p=new Ds({name:"PMREM.Background",side:Ln,depthWrite:!1,depthTest:!1}),m=new Zt(new da,p);let g=!1;const A=e.background;A?A.isColor&&(p.color.copy(A),e.background=null,g=!0):(p.color.copy(Sg),g=!0);for(let _=0;_<6;_++){const x=_%3;x===0?(c.up.set(0,l[_],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+h[_],r.y,r.z)):x===1?(c.up.set(0,0,l[_]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+h[_],r.z)):(c.up.set(0,l[_],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+h[_]));const E=this._cubeSize;Rl(s,x*E,_>2?E:0,E,E),u.setRenderTarget(s),g&&u.render(m,c),u.render(e,c)}m.geometry.dispose(),m.material.dispose(),u.toneMapping=f,u.autoClear=d,e.background=A}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===sr||e.mapping===Yr;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Rg()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Tg());const r=s?this._cubemapMaterial:this._equirectMaterial,a=new Zt(this._lodPlanes[0],r),o=r.uniforms;o.envMap.value=e;const c=this._cubeSize;Rl(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,Ed)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let r=1;r<s;r++){const a=Math.sqrt(this._sigmas[r]*this._sigmas[r]-this._sigmas[r-1]*this._sigmas[r-1]),o=Mg[(s-r-1)%Mg.length];this._blur(e,r-1,r,a,o)}t.autoClear=n}_blur(e,t,n,s,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,s,"latitudinal",r),this._halfBlur(a,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,a,o){const c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new Zt(this._lodPlanes[s],l),d=l.uniforms,f=this._sizeLods[n]-1,p=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*mr-1),m=r/p,g=isFinite(r)?1+Math.floor(h*m):mr;g>mr&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${mr}`);const A=[];let _=0;for(let I=0;I<mr;++I){const T=I/m,C=Math.exp(-T*T/2);A.push(C),I===0?_+=C:I<g&&(_+=2*C)}for(let I=0;I<A.length;I++)A[I]=A[I]/_;d.envMap.value=e.texture,d.samples.value=g,d.weights.value=A,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:x}=this;d.dTheta.value=p,d.mipInt.value=x-n;const E=this._sizeLods[s],S=3*E*(s>x-ya?s-x+ya:0),w=4*(this._cubeSize-E);Rl(t,S,w,3*E,2*E),c.setRenderTarget(t),c.render(u,Ed)}}function dI(i){const e=[],t=[],n=[];let s=i;const r=i-ya+1+Ig.length;for(let a=0;a<r;a++){const o=Math.pow(2,s);t.push(o);let c=1/o;a>i-ya?c=Ig[a-i+ya-1]:a===0&&(c=0),n.push(c);const l=1/(o-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,p=6,m=3,g=2,A=1,_=new Float32Array(m*p*f),x=new Float32Array(g*p*f),E=new Float32Array(A*p*f);for(let w=0;w<f;w++){const I=w%3*2/3-1,T=w>2?0:-1,C=[I,T,0,I+2/3,T,0,I+2/3,T+1,0,I,T,0,I+2/3,T+1,0,I,T+1,0];_.set(C,m*p*w),x.set(d,g*p*w);const v=[w,w,w,w,w,w];E.set(v,A*p*w)}const S=new Mn;S.setAttribute("position",new Sn(_,m)),S.setAttribute("uv",new Sn(x,g)),S.setAttribute("faceIndex",new Sn(E,A)),e.push(S),s>ya&&s--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Bg(i,e,t){const n=new or(i,e,t);return n.texture.mapping=Bc,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Rl(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function fI(i,e,t){const n=new Float32Array(mr),s=new G(0,1,0);return new Ls({name:"SphericalGaussianBlur",defines:{n:mr,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:Id(),fragmentShader:`
precision mediump float;
precision mediump int;
@@ -3713,17 +3713,17 @@ void main() {
gl_Position = vec4( position, 1.0 );
}
- `}function AI(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===Mc||c===tu,h=c===sr||c===Yr;if(l||h){let u=e.get(o);const d=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return t===null&&(t=new Cd(i)),u=l?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const f=o.image;return l&&f&&f.height>0||h&&f&&s(f)?(t===null&&(t=new Cd(i)),u=l?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",r),u.texture):null}}}return o}function s(o){let c=0;const l=6;for(let h=0;h<l;h++)o[h]!==void 0&&c++;return c===l}function r(o){const c=o.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:a}}function gI(i){const e={};function t(n){if(e[n]!==void 0)return e[n];let s;switch(n){case"WEBGL_depth_texture":s=i.getExtension("WEBGL_depth_texture")||i.getExtension("MOZ_WEBGL_depth_texture")||i.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=i.getExtension("EXT_texture_filter_anisotropic")||i.getExtension("MOZ_EXT_texture_filter_anisotropic")||i.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=i.getExtension("WEBGL_compressed_texture_s3tc")||i.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=i.getExtension("WEBGL_compressed_texture_pvrtc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=i.getExtension(n)}return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Vc("THREE.WebGLRenderer: "+n+" extension not supported."),s}}}function mI(i,e,t,n){const s={},r=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const p in d.attributes)e.remove(d.attributes[p]);d.removeEventListener("dispose",a),delete s[d.id];const f=r.get(d);f&&(e.remove(f),r.delete(d)),n.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return s[d.id]===!0||(d.addEventListener("dispose",a),s[d.id]=!0,t.memory.geometries++),d}function c(u){const d=u.attributes;for(const f in d)e.update(d[f],i.ARRAY_BUFFER)}function l(u){const d=[],f=u.index,p=u.attributes.position;let m=0;if(f!==null){const _=f.array;m=f.version;for(let x=0,E=_.length;x<E;x+=3){const S=_[x+0],w=_[x+1],I=_[x+2];d.push(S,w,w,I,I,S)}}else if(p!==void 0){const _=p.array;m=p.version;for(let x=0,E=_.length/3-1;x<E;x+=3){const S=x+0,w=x+1,I=x+2;d.push(S,w,w,I,I,S)}}else return;const g=new(dA(d)?TA:Xu)(d,1);g.version=m;const A=r.get(u);A&&e.remove(A),r.set(u,g)}function h(u){const d=r.get(u);if(d){const f=u.index;f!==null&&d.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:o,update:c,getWireframeAttribute:h}}function xI(i,e,t){let n;function s(d){n=d}let r,a;function o(d){r=d.type,a=d.bytesPerElement}function c(d,f){i.drawElements(n,f,r,d*a),t.update(f,n,1)}function l(d,f,p){p!==0&&(i.drawElementsInstanced(n,f,r,d*a,p),t.update(f,n,p))}function h(d,f,p){if(p===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,d,0,p);let g=0;for(let A=0;A<p;A++)g+=f[A];t.update(g,n,1)}function u(d,f,p,m){if(p===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let A=0;A<d.length;A++)l(d[A]/a,f[A],m[A]);else{g.multiDrawElementsInstancedWEBGL(n,f,0,r,d,0,m,0,p);let A=0;for(let _=0;_<p;_++)A+=f[_]*m[_];t.update(A,n,1)}}this.setMode=s,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=h,this.renderMultiDrawInstances=u}function bI(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,a,o){switch(t.calls++,a){case i.TRIANGLES:t.triangles+=o*(r/3);break;case i.LINES:t.lines+=o*(r/2);break;case i.LINE_STRIP:t.lines+=o*(r-1);break;case i.LINE_LOOP:t.lines+=o*r;break;case i.POINTS:t.points+=o*r;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function EI(i,e,t){const n=new WeakMap,s=new gt;function r(a,o,c){const l=a.morphTargetInfluences,h=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=h!==void 0?h.length:0;let d=n.get(o);if(d===void 0||d.count!==u){let C=function(){I.dispose(),n.delete(o),o.removeEventListener("dispose",C)};d!==void 0&&d.texture.dispose();const f=o.morphAttributes.position!==void 0,p=o.morphAttributes.normal!==void 0,m=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],A=o.morphAttributes.normal||[],_=o.morphAttributes.color||[];let x=0;f===!0&&(x=1),p===!0&&(x=2),m===!0&&(x=3);let E=o.attributes.position.count*x,S=1;E>e.maxTextureSize&&(S=Math.ceil(E/e.maxTextureSize),E=e.maxTextureSize);const w=new Float32Array(E*S*4*u),I=new gA(w,E,S,u);I.type=ln,I.needsUpdate=!0;const T=x*4;for(let v=0;v<u;v++){const F=g[v],K=A[v],q=_[v],$=E*S*4*v;for(let D=0;D<F.count;D++){const O=D*T;f===!0&&(s.fromBufferAttribute(F,D),w[$+O+0]=s.x,w[$+O+1]=s.y,w[$+O+2]=s.z,w[$+O+3]=0),p===!0&&(s.fromBufferAttribute(K,D),w[$+O+4]=s.x,w[$+O+5]=s.y,w[$+O+6]=s.z,w[$+O+7]=0),m===!0&&(s.fromBufferAttribute(q,D),w[$+O+8]=s.x,w[$+O+9]=s.y,w[$+O+10]=s.z,w[$+O+11]=q.itemSize===4?s.w:1)}}d={count:u,texture:I,size:new Je(E,S)},n.set(o,d),o.addEventListener("dispose",C)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",a.morphTexture,t);else{let f=0;for(let m=0;m<l.length;m++)f+=l[m];const p=o.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",p),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",d.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",d.size)}return{update:r}}function yI(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,h=c.geometry,u=e.get(c,h);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",o)===!1&&c.addEventListener("dispose",o),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const d=c.skeleton;s.get(d)!==l&&(d.update(),s.set(d,l))}return u}function a(){s=new WeakMap}function o(c){const l=c.target;l.removeEventListener("dispose",o),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:a}}const Fg=new nn,Ng=new tg(1,1),Dg=new gA,Lg=new mA,Pg=new UA,kg=[],Ug=[],Og=new Float32Array(16),Qg=new Float32Array(9),Gg=new Float32Array(4);function wa(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=kg[s];if(r===void 0&&(r=new Float32Array(s),kg[s]=r),e!==0){n.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(r,o)}return r}function fn(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function pn(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Fl(i,e){let t=Ug[e];t===void 0&&(t=new Int32Array(e),Ug[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function _I(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function wI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2fv(this.addr,e),pn(t,e)}}function vI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(fn(t,e))return;i.uniform3fv(this.addr,e),pn(t,e)}}function CI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4fv(this.addr,e),pn(t,e)}}function II(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Gg.set(n),i.uniformMatrix2fv(this.addr,!1,Gg),pn(t,n)}}function SI(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Qg.set(n),i.uniformMatrix3fv(this.addr,!1,Qg),pn(t,n)}}function MI(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Og.set(n),i.uniformMatrix4fv(this.addr,!1,Og),pn(t,n)}}function BI(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function TI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2iv(this.addr,e),pn(t,e)}}function RI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(fn(t,e))return;i.uniform3iv(this.addr,e),pn(t,e)}}function FI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4iv(this.addr,e),pn(t,e)}}function NI(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function DI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2uiv(this.addr,e),pn(t,e)}}function LI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(fn(t,e))return;i.uniform3uiv(this.addr,e),pn(t,e)}}function PI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4uiv(this.addr,e),pn(t,e)}}function kI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(Ng.compareFunction=lA,r=Ng):r=Fg,t.setTexture2D(e||r,s)}function UI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||Lg,s)}function OI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||Pg,s)}function QI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||Dg,s)}function GI(i){switch(i){case 5126:return _I;case 35664:return wI;case 35665:return vI;case 35666:return CI;case 35674:return II;case 35675:return SI;case 35676:return MI;case 5124:case 35670:return BI;case 35667:case 35671:return TI;case 35668:case 35672:return RI;case 35669:case 35673:return FI;case 5125:return NI;case 36294:return DI;case 36295:return LI;case 36296:return PI;case 35678:case 36198:case 36298:case 36306:case 35682:return kI;case 35679:case 36299:case 36307:return UI;case 35680:case 36300:case 36308:case 36293:return OI;case 36289:case 36303:case 36311:case 36292:return QI}}function HI(i,e){i.uniform1fv(this.addr,e)}function zI(i,e){const t=wa(e,this.size,2);i.uniform2fv(this.addr,t)}function VI(i,e){const t=wa(e,this.size,3);i.uniform3fv(this.addr,t)}function WI(i,e){const t=wa(e,this.size,4);i.uniform4fv(this.addr,t)}function qI(i,e){const t=wa(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function KI(i,e){const t=wa(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function jI(i,e){const t=wa(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function XI(i,e){i.uniform1iv(this.addr,e)}function YI(i,e){i.uniform2iv(this.addr,e)}function JI(i,e){i.uniform3iv(this.addr,e)}function ZI(i,e){i.uniform4iv(this.addr,e)}function $I(i,e){i.uniform1uiv(this.addr,e)}function eS(i,e){i.uniform2uiv(this.addr,e)}function tS(i,e){i.uniform3uiv(this.addr,e)}function nS(i,e){i.uniform4uiv(this.addr,e)}function iS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture2D(e[a]||Fg,r[a])}function sS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture3D(e[a]||Lg,r[a])}function rS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTextureCube(e[a]||Pg,r[a])}function aS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture2DArray(e[a]||Dg,r[a])}function oS(i){switch(i){case 5126:return HI;case 35664:return zI;case 35665:return VI;case 35666:return WI;case 35674:return qI;case 35675:return KI;case 35676:return jI;case 5124:case 35670:return XI;case 35667:case 35671:return YI;case 35668:case 35672:return JI;case 35669:case 35673:return ZI;case 5125:return $I;case 36294:return eS;case 36295:return tS;case 36296:return nS;case 35678:case 36198:case 36298:case 36306:case 35682:return iS;case 35679:case 36299:case 36307:return sS;case 35680:case 36300:case 36308:case 36293:return rS;case 36289:case 36303:case 36311:case 36292:return aS}}class cS{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=GI(t.type)}}class lS{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=oS(t.type)}}class hS{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,a=s.length;r!==a;++r){const o=s[r];o.setValue(e,t[o.id],n)}}}const Sd=/(\w+)(\])?(\[|\.)?/g;function Hg(i,e){i.seq.push(e),i.map[e.id]=e}function uS(i,e,t){const n=i.name,s=n.length;for(Sd.lastIndex=0;;){const r=Sd.exec(n),a=Sd.lastIndex;let o=r[1];const c=r[2]==="]",l=r[3];if(c&&(o=o|0),l===void 0||l==="["&&a+2===s){Hg(t,l===void 0?new cS(o,i,e):new lS(o,i,e));break}else{let u=t.map[o];u===void 0&&(u=new hS(o),Hg(t,u)),t=u}}}class Nl{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){const r=e.getActiveUniform(t,s),a=e.getUniformLocation(t,r.name);uS(r,a,this)}}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,a=t.length;r!==a;++r){const o=t[r],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const a=e[s];a.id in t&&n.push(a)}return n}}function zg(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const dS=37297;let fS=0;function pS(i,e){const t=i.split(`
+ `}function pI(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===Mc||c===tu,h=c===sr||c===Yr;if(l||h){let u=e.get(o);const d=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return t===null&&(t=new Cd(i)),u=l?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const f=o.image;return l&&f&&f.height>0||h&&f&&s(f)?(t===null&&(t=new Cd(i)),u=l?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",r),u.texture):null}}}return o}function s(o){let c=0;const l=6;for(let h=0;h<l;h++)o[h]!==void 0&&c++;return c===l}function r(o){const c=o.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:a}}function AI(i){const e={};function t(n){if(e[n]!==void 0)return e[n];let s;switch(n){case"WEBGL_depth_texture":s=i.getExtension("WEBGL_depth_texture")||i.getExtension("MOZ_WEBGL_depth_texture")||i.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=i.getExtension("EXT_texture_filter_anisotropic")||i.getExtension("MOZ_EXT_texture_filter_anisotropic")||i.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=i.getExtension("WEBGL_compressed_texture_s3tc")||i.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=i.getExtension("WEBGL_compressed_texture_pvrtc")||i.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=i.getExtension(n)}return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Vc("THREE.WebGLRenderer: "+n+" extension not supported."),s}}}function gI(i,e,t,n){const s={},r=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const p in d.attributes)e.remove(d.attributes[p]);d.removeEventListener("dispose",a),delete s[d.id];const f=r.get(d);f&&(e.remove(f),r.delete(d)),n.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return s[d.id]===!0||(d.addEventListener("dispose",a),s[d.id]=!0,t.memory.geometries++),d}function c(u){const d=u.attributes;for(const f in d)e.update(d[f],i.ARRAY_BUFFER)}function l(u){const d=[],f=u.index,p=u.attributes.position;let m=0;if(f!==null){const _=f.array;m=f.version;for(let x=0,E=_.length;x<E;x+=3){const S=_[x+0],w=_[x+1],I=_[x+2];d.push(S,w,w,I,I,S)}}else if(p!==void 0){const _=p.array;m=p.version;for(let x=0,E=_.length/3-1;x<E;x+=3){const S=x+0,w=x+1,I=x+2;d.push(S,w,w,I,I,S)}}else return;const g=new(dA(d)?TA:Xu)(d,1);g.version=m;const A=r.get(u);A&&e.remove(A),r.set(u,g)}function h(u){const d=r.get(u);if(d){const f=u.index;f!==null&&d.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:o,update:c,getWireframeAttribute:h}}function mI(i,e,t){let n;function s(d){n=d}let r,a;function o(d){r=d.type,a=d.bytesPerElement}function c(d,f){i.drawElements(n,f,r,d*a),t.update(f,n,1)}function l(d,f,p){p!==0&&(i.drawElementsInstanced(n,f,r,d*a,p),t.update(f,n,p))}function h(d,f,p){if(p===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,d,0,p);let g=0;for(let A=0;A<p;A++)g+=f[A];t.update(g,n,1)}function u(d,f,p,m){if(p===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let A=0;A<d.length;A++)l(d[A]/a,f[A],m[A]);else{g.multiDrawElementsInstancedWEBGL(n,f,0,r,d,0,m,0,p);let A=0;for(let _=0;_<p;_++)A+=f[_]*m[_];t.update(A,n,1)}}this.setMode=s,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=h,this.renderMultiDrawInstances=u}function xI(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,a,o){switch(t.calls++,a){case i.TRIANGLES:t.triangles+=o*(r/3);break;case i.LINES:t.lines+=o*(r/2);break;case i.LINE_STRIP:t.lines+=o*(r-1);break;case i.LINE_LOOP:t.lines+=o*r;break;case i.POINTS:t.points+=o*r;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function bI(i,e,t){const n=new WeakMap,s=new gt;function r(a,o,c){const l=a.morphTargetInfluences,h=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=h!==void 0?h.length:0;let d=n.get(o);if(d===void 0||d.count!==u){let C=function(){I.dispose(),n.delete(o),o.removeEventListener("dispose",C)};d!==void 0&&d.texture.dispose();const f=o.morphAttributes.position!==void 0,p=o.morphAttributes.normal!==void 0,m=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],A=o.morphAttributes.normal||[],_=o.morphAttributes.color||[];let x=0;f===!0&&(x=1),p===!0&&(x=2),m===!0&&(x=3);let E=o.attributes.position.count*x,S=1;E>e.maxTextureSize&&(S=Math.ceil(E/e.maxTextureSize),E=e.maxTextureSize);const w=new Float32Array(E*S*4*u),I=new gA(w,E,S,u);I.type=ln,I.needsUpdate=!0;const T=x*4;for(let v=0;v<u;v++){const F=g[v],K=A[v],q=_[v],$=E*S*4*v;for(let D=0;D<F.count;D++){const O=D*T;f===!0&&(s.fromBufferAttribute(F,D),w[$+O+0]=s.x,w[$+O+1]=s.y,w[$+O+2]=s.z,w[$+O+3]=0),p===!0&&(s.fromBufferAttribute(K,D),w[$+O+4]=s.x,w[$+O+5]=s.y,w[$+O+6]=s.z,w[$+O+7]=0),m===!0&&(s.fromBufferAttribute(q,D),w[$+O+8]=s.x,w[$+O+9]=s.y,w[$+O+10]=s.z,w[$+O+11]=q.itemSize===4?s.w:1)}}d={count:u,texture:I,size:new Je(E,S)},n.set(o,d),o.addEventListener("dispose",C)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",a.morphTexture,t);else{let f=0;for(let m=0;m<l.length;m++)f+=l[m];const p=o.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",p),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",d.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",d.size)}return{update:r}}function EI(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,h=c.geometry,u=e.get(c,h);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",o)===!1&&c.addEventListener("dispose",o),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const d=c.skeleton;s.get(d)!==l&&(d.update(),s.set(d,l))}return u}function a(){s=new WeakMap}function o(c){const l=c.target;l.removeEventListener("dispose",o),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:a}}const Fg=new nn,Ng=new tg(1,1),Dg=new gA,Lg=new mA,Pg=new UA,kg=[],Ug=[],Og=new Float32Array(16),Qg=new Float32Array(9),Gg=new Float32Array(4);function wa(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=kg[s];if(r===void 0&&(r=new Float32Array(s),kg[s]=r),e!==0){n.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(r,o)}return r}function fn(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function pn(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Fl(i,e){let t=Ug[e];t===void 0&&(t=new Int32Array(e),Ug[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function yI(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function _I(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2fv(this.addr,e),pn(t,e)}}function wI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(fn(t,e))return;i.uniform3fv(this.addr,e),pn(t,e)}}function vI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4fv(this.addr,e),pn(t,e)}}function CI(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Gg.set(n),i.uniformMatrix2fv(this.addr,!1,Gg),pn(t,n)}}function II(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Qg.set(n),i.uniformMatrix3fv(this.addr,!1,Qg),pn(t,n)}}function SI(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(fn(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),pn(t,e)}else{if(fn(t,n))return;Og.set(n),i.uniformMatrix4fv(this.addr,!1,Og),pn(t,n)}}function MI(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function BI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2iv(this.addr,e),pn(t,e)}}function TI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(fn(t,e))return;i.uniform3iv(this.addr,e),pn(t,e)}}function RI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4iv(this.addr,e),pn(t,e)}}function FI(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function NI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(fn(t,e))return;i.uniform2uiv(this.addr,e),pn(t,e)}}function DI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(fn(t,e))return;i.uniform3uiv(this.addr,e),pn(t,e)}}function LI(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(fn(t,e))return;i.uniform4uiv(this.addr,e),pn(t,e)}}function PI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(Ng.compareFunction=lA,r=Ng):r=Fg,t.setTexture2D(e||r,s)}function kI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||Lg,s)}function UI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||Pg,s)}function OI(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||Dg,s)}function QI(i){switch(i){case 5126:return yI;case 35664:return _I;case 35665:return wI;case 35666:return vI;case 35674:return CI;case 35675:return II;case 35676:return SI;case 5124:case 35670:return MI;case 35667:case 35671:return BI;case 35668:case 35672:return TI;case 35669:case 35673:return RI;case 5125:return FI;case 36294:return NI;case 36295:return DI;case 36296:return LI;case 35678:case 36198:case 36298:case 36306:case 35682:return PI;case 35679:case 36299:case 36307:return kI;case 35680:case 36300:case 36308:case 36293:return UI;case 36289:case 36303:case 36311:case 36292:return OI}}function GI(i,e){i.uniform1fv(this.addr,e)}function HI(i,e){const t=wa(e,this.size,2);i.uniform2fv(this.addr,t)}function zI(i,e){const t=wa(e,this.size,3);i.uniform3fv(this.addr,t)}function VI(i,e){const t=wa(e,this.size,4);i.uniform4fv(this.addr,t)}function WI(i,e){const t=wa(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function qI(i,e){const t=wa(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function KI(i,e){const t=wa(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function jI(i,e){i.uniform1iv(this.addr,e)}function XI(i,e){i.uniform2iv(this.addr,e)}function YI(i,e){i.uniform3iv(this.addr,e)}function JI(i,e){i.uniform4iv(this.addr,e)}function ZI(i,e){i.uniform1uiv(this.addr,e)}function $I(i,e){i.uniform2uiv(this.addr,e)}function eS(i,e){i.uniform3uiv(this.addr,e)}function tS(i,e){i.uniform4uiv(this.addr,e)}function nS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture2D(e[a]||Fg,r[a])}function iS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture3D(e[a]||Lg,r[a])}function sS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTextureCube(e[a]||Pg,r[a])}function rS(i,e,t){const n=this.cache,s=e.length,r=Fl(t,s);fn(n,r)||(i.uniform1iv(this.addr,r),pn(n,r));for(let a=0;a!==s;++a)t.setTexture2DArray(e[a]||Dg,r[a])}function aS(i){switch(i){case 5126:return GI;case 35664:return HI;case 35665:return zI;case 35666:return VI;case 35674:return WI;case 35675:return qI;case 35676:return KI;case 5124:case 35670:return jI;case 35667:case 35671:return XI;case 35668:case 35672:return YI;case 35669:case 35673:return JI;case 5125:return ZI;case 36294:return $I;case 36295:return eS;case 36296:return tS;case 35678:case 36198:case 36298:case 36306:case 35682:return nS;case 35679:case 36299:case 36307:return iS;case 35680:case 36300:case 36308:case 36293:return sS;case 36289:case 36303:case 36311:case 36292:return rS}}class oS{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=QI(t.type)}}class cS{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=aS(t.type)}}class lS{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,a=s.length;r!==a;++r){const o=s[r];o.setValue(e,t[o.id],n)}}}const Sd=/(\w+)(\])?(\[|\.)?/g;function Hg(i,e){i.seq.push(e),i.map[e.id]=e}function hS(i,e,t){const n=i.name,s=n.length;for(Sd.lastIndex=0;;){const r=Sd.exec(n),a=Sd.lastIndex;let o=r[1];const c=r[2]==="]",l=r[3];if(c&&(o=o|0),l===void 0||l==="["&&a+2===s){Hg(t,l===void 0?new oS(o,i,e):new cS(o,i,e));break}else{let u=t.map[o];u===void 0&&(u=new lS(o),Hg(t,u)),t=u}}}class Nl{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){const r=e.getActiveUniform(t,s),a=e.getUniformLocation(t,r.name);hS(r,a,this)}}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,a=t.length;r!==a;++r){const o=t[r],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const a=e[s];a.id in t&&n.push(a)}return n}}function zg(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const uS=37297;let dS=0;function fS(i,e){const t=i.split(`
`),n=[],s=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let a=s;a<r;a++){const o=a+1;n.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return n.join(`
-`)}const Vg=new ot;function AS(i){tt._getMatrix(Vg,tt.workingColorSpace,i);const e=`mat3( ${Vg.elements.map(t=>t.toFixed(4))} )`;switch(tt.getTransfer(i)){case Hc:return[e,"LinearTransferOETF"];case Rt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Wg(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),s=i.getShaderInfoLog(e).trim();if(n&&s==="")return"";const r=/ERROR: 0:(\d+)/.exec(s);if(r){const a=parseInt(r[1]);return t.toUpperCase()+`
+`)}const Vg=new ot;function pS(i){tt._getMatrix(Vg,tt.workingColorSpace,i);const e=`mat3( ${Vg.elements.map(t=>t.toFixed(4))} )`;switch(tt.getTransfer(i)){case Hc:return[e,"LinearTransferOETF"];case Rt:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Wg(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),s=i.getShaderInfoLog(e).trim();if(n&&s==="")return"";const r=/ERROR: 0:(\d+)/.exec(s);if(r){const a=parseInt(r[1]);return t.toUpperCase()+`
`+s+`
-`+pS(i.getShaderSource(e),a)}else return s}function gS(i,e){const t=AS(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
-`)}function mS(i,e){let t;switch(e){case eu:t="Linear";break;case ky:t="Reinhard";break;case Uy:t="Cineon";break;case Xp:t="ACESFilmic";break;case Qy:t="AgX";break;case Gy:t="Neutral";break;case Oy:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Dl=new G;function xS(){tt.getLuminanceCoefficients(Dl);const i=Dl.x.toFixed(4),e=Dl.y.toFixed(4),t=Dl.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
-`)}function bS(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Do).join(`
-`)}function ES(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`
-`)}function yS(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){const r=i.getActiveAttrib(e,s),a=r.name;let o=1;r.type===i.FLOAT_MAT2&&(o=2),r.type===i.FLOAT_MAT3&&(o=3),r.type===i.FLOAT_MAT4&&(o=4),t[a]={type:r.type,location:i.getAttribLocation(e,a),locationSize:o}}return t}function Do(i){return i!==""}function qg(i,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return i.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function Kg(i,e){return i.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const _S=/^[ \t]*#include +<([\w\d./]+)>/gm;function Md(i){return i.replace(_S,vS)}const wS=new Map;function vS(i,e){let t=ct[e];if(t===void 0){const n=wS.get(e);if(n!==void 0)t=ct[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Md(t)}const CS=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function jg(i){return i.replace(CS,IS)}function IS(i,e,t,n){let s="";for(let r=parseInt(e);r<parseInt(t);r++)s+=n.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return s}function Xg(i){let e=`precision ${i.precision} float;
+`+fS(i.getShaderSource(e),a)}else return s}function AS(i,e){const t=pS(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
+`)}function gS(i,e){let t;switch(e){case eu:t="Linear";break;case Py:t="Reinhard";break;case ky:t="Cineon";break;case Xp:t="ACESFilmic";break;case Oy:t="AgX";break;case Qy:t="Neutral";break;case Uy:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Dl=new G;function mS(){tt.getLuminanceCoefficients(Dl);const i=Dl.x.toFixed(4),e=Dl.y.toFixed(4),t=Dl.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
+`)}function xS(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Do).join(`
+`)}function bS(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`
+`)}function ES(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){const r=i.getActiveAttrib(e,s),a=r.name;let o=1;r.type===i.FLOAT_MAT2&&(o=2),r.type===i.FLOAT_MAT3&&(o=3),r.type===i.FLOAT_MAT4&&(o=4),t[a]={type:r.type,location:i.getAttribLocation(e,a),locationSize:o}}return t}function Do(i){return i!==""}function qg(i,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return i.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function Kg(i,e){return i.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const yS=/^[ \t]*#include +<([\w\d./]+)>/gm;function Md(i){return i.replace(yS,wS)}const _S=new Map;function wS(i,e){let t=ct[e];if(t===void 0){const n=_S.get(e);if(n!==void 0)t=ct[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Md(t)}const vS=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function jg(i){return i.replace(vS,CS)}function CS(i,e,t,n){let s="";for(let r=parseInt(e);r<parseInt(t);r++)s+=n.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return s}function Xg(i){let e=`precision ${i.precision} float;
precision ${i.precision} int;
precision ${i.precision} sampler2D;
precision ${i.precision} samplerCube;
@@ -3743,14 +3743,14 @@ void main() {
`;return i.precision==="highp"?e+=`
#define HIGH_PRECISION`:i.precision==="mediump"?e+=`
#define MEDIUM_PRECISION`:i.precision==="lowp"&&(e+=`
-#define LOW_PRECISION`),e}function SS(i){let e="SHADOWMAP_TYPE_BASIC";return i.shadowMapType===Wp?e="SHADOWMAP_TYPE_PCF":i.shadowMapType===gy?e="SHADOWMAP_TYPE_PCF_SOFT":i.shadowMapType===Ki&&(e="SHADOWMAP_TYPE_VSM"),e}function MS(i){let e="ENVMAP_TYPE_CUBE";if(i.envMap)switch(i.envMapMode){case sr:case Yr:e="ENVMAP_TYPE_CUBE";break;case Bc:e="ENVMAP_TYPE_CUBE_UV";break}return e}function BS(i){let e="ENVMAP_MODE_REFLECTION";return i.envMap&&i.envMapMode===Yr&&(e="ENVMAP_MODE_REFRACTION"),e}function TS(i){let e="ENVMAP_BLENDING_NONE";if(i.envMap)switch(i.combine){case Sc:e="ENVMAP_BLENDING_MULTIPLY";break;case Ly:e="ENVMAP_BLENDING_MIX";break;case Py:e="ENVMAP_BLENDING_ADD";break}return e}function RS(i){const e=i.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function FS(i,e,t,n){const s=i.getContext(),r=t.defines;let a=t.vertexShader,o=t.fragmentShader;const c=SS(t),l=MS(t),h=BS(t),u=TS(t),d=RS(t),f=bS(t),p=ES(r),m=s.createProgram();let g,A,_=t.glslVersion?"#version "+t.glslVersion+`
+#define LOW_PRECISION`),e}function IS(i){let e="SHADOWMAP_TYPE_BASIC";return i.shadowMapType===Wp?e="SHADOWMAP_TYPE_PCF":i.shadowMapType===Ay?e="SHADOWMAP_TYPE_PCF_SOFT":i.shadowMapType===Ki&&(e="SHADOWMAP_TYPE_VSM"),e}function SS(i){let e="ENVMAP_TYPE_CUBE";if(i.envMap)switch(i.envMapMode){case sr:case Yr:e="ENVMAP_TYPE_CUBE";break;case Bc:e="ENVMAP_TYPE_CUBE_UV";break}return e}function MS(i){let e="ENVMAP_MODE_REFLECTION";return i.envMap&&i.envMapMode===Yr&&(e="ENVMAP_MODE_REFRACTION"),e}function BS(i){let e="ENVMAP_BLENDING_NONE";if(i.envMap)switch(i.combine){case Sc:e="ENVMAP_BLENDING_MULTIPLY";break;case Dy:e="ENVMAP_BLENDING_MIX";break;case Ly:e="ENVMAP_BLENDING_ADD";break}return e}function TS(i){const e=i.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function RS(i,e,t,n){const s=i.getContext(),r=t.defines;let a=t.vertexShader,o=t.fragmentShader;const c=IS(t),l=SS(t),h=MS(t),u=BS(t),d=TS(t),f=xS(t),p=bS(r),m=s.createProgram();let g,A,_=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(Do).join(`
`),g.length>0&&(g+=`
`),A=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(Do).join(`
`),A.length>0&&(A+=`
`)):(g=[Xg(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",`
`].filter(Do).join(`
-`),A=[Xg(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Is?"#define TONE_MAPPING":"",t.toneMapping!==Is?ct.tonemapping_pars_fragment:"",t.toneMapping!==Is?mS("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ct.colorspace_pars_fragment,gS("linearToOutputTexel",t.outputColorSpace),xS(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
+`),A=[Xg(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Is?"#define TONE_MAPPING":"",t.toneMapping!==Is?ct.tonemapping_pars_fragment:"",t.toneMapping!==Is?gS("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ct.colorspace_pars_fragment,AS("linearToOutputTexel",t.outputColorSpace),mS(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(Do).join(`
`)),a=Md(a),a=qg(a,t),a=Kg(a,t),o=Md(o),o=qg(o,t),o=Kg(o,t),a=jg(a),o=jg(o),t.isRawShaderMaterial!==!0&&(_=`#version 300 es
`,g=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
@@ -3764,9 +3764,9 @@ Material Type: `+F.type+`
Program Info Log: `+K+`
`+Y+`
-`+Q)}else K!==""?console.warn("THREE.WebGLProgram: Program Info Log:",K):(q===""||$==="")&&(O=!1);O&&(F.diagnostics={runnable:D,programLog:K,vertexShader:{log:q,prefix:g},fragmentShader:{log:$,prefix:A}})}s.deleteShader(S),s.deleteShader(w),T=new Nl(s,m),C=yS(s,m)}let T;this.getUniforms=function(){return T===void 0&&I(this),T};let C;this.getAttributes=function(){return C===void 0&&I(this),C};let v=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return v===!1&&(v=s.getProgramParameter(m,dS)),v},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=fS++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=S,this.fragmentShader=w,this}let NS=0;class DS{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(s)===!1&&(a.add(s),s.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new LS(e),t.set(e,n)),n}}class LS{constructor(e){this.id=NS++,this.code=e,this.usedTimes=0}}function PS(i,e,t,n,s,r,a){const o=new yA,c=new DS,l=new Set,h=[],u=s.logarithmicDepthBuffer,d=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(C){return l.add(C),C===0?"uv":`uv${C}`}function g(C,v,F,K,q){const $=K.fog,D=q.geometry,O=C.isMeshStandardMaterial?K.environment:null,Y=(C.isMeshStandardMaterial?t:e).get(C.envMap||O),Q=Y&&Y.mapping===Bc?Y.image.height:null,J=p[C.type];C.precision!==null&&(f=s.getMaxPrecision(C.precision),f!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",f,"instead."));const ee=D.morphAttributes.position||D.morphAttributes.normal||D.morphAttributes.color,ae=ee!==void 0?ee.length:0;let _e=0;D.morphAttributes.position!==void 0&&(_e=1),D.morphAttributes.normal!==void 0&&(_e=2),D.morphAttributes.color!==void 0&&(_e=3);let Me,se,me,xe;if(J){const Ct=Qi[J];Me=Ct.vertexShader,se=Ct.fragmentShader}else Me=C.vertexShader,se=C.fragmentShader,c.update(C),me=c.getVertexShaderID(C),xe=c.getFragmentShaderID(C);const be=i.getRenderTarget(),Ue=i.state.buffers.depth.getReversed(),et=q.isInstancedMesh===!0,He=q.isBatchedMesh===!0,Mt=!!C.map,ft=!!C.matcap,$e=!!Y,H=!!C.aoMap,wn=!!C.lightMap,pt=!!C.bumpMap,mt=!!C.normalMap,We=!!C.displacementMap,Dt=!!C.emissiveMap,ze=!!C.metalnessMap,L=!!C.roughnessMap,M=C.anisotropy>0,Z=C.clearcoat>0,le=C.dispersion>0,Ae=C.iridescence>0,oe=C.sheen>0,Qe=C.transmission>0,ve=M&&!!C.anisotropyMap,qe=Z&&!!C.clearcoatMap,Ze=Z&&!!C.clearcoatNormalMap,Ee=Z&&!!C.clearcoatRoughnessMap,De=Ae&&!!C.iridescenceMap,Oe=Ae&&!!C.iridescenceThicknessMap,Ge=oe&&!!C.sheenColorMap,Te=oe&&!!C.sheenRoughnessMap,nt=!!C.specularMap,Ke=!!C.specularColorMap,it=!!C.specularIntensityMap,W=Qe&&!!C.transmissionMap,ne=Qe&&!!C.thicknessMap,re=!!C.gradientMap,de=!!C.alphaMap,Se=C.alphaTest>0,Ie=!!C.alphaHash,st=!!C.extensions;let Ht=Is;C.toneMapped&&(be===null||be.isXRRenderTarget===!0)&&(Ht=i.toneMapping);const vn={shaderID:J,shaderType:C.type,shaderName:C.name,vertexShader:Me,fragmentShader:se,defines:C.defines,customVertexShaderID:me,customFragmentShaderID:xe,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:f,batching:He,batchingColor:He&&q._colorsTexture!==null,instancing:et,instancingColor:et&&q.instanceColor!==null,instancingMorph:et&&q.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:be===null?i.outputColorSpace:be.isXRRenderTarget===!0?be.texture.colorSpace:un,alphaToCoverage:!!C.alphaToCoverage,map:Mt,matcap:ft,envMap:$e,envMapMode:$e&&Y.mapping,envMapCubeUVHeight:Q,aoMap:H,lightMap:wn,bumpMap:pt,normalMap:mt,displacementMap:d&&We,emissiveMap:Dt,normalMapObjectSpace:mt&&C.normalMapType===jy,normalMapTangentSpace:mt&&C.normalMapType===Gc,metalnessMap:ze,roughnessMap:L,anisotropy:M,anisotropyMap:ve,clearcoat:Z,clearcoatMap:qe,clearcoatNormalMap:Ze,clearcoatRoughnessMap:Ee,dispersion:le,iridescence:Ae,iridescenceMap:De,iridescenceThicknessMap:Oe,sheen:oe,sheenColorMap:Ge,sheenRoughnessMap:Te,specularMap:nt,specularColorMap:Ke,specularIntensityMap:it,transmission:Qe,transmissionMap:W,thicknessMap:ne,gradientMap:re,opaque:C.transparent===!1&&C.blending===jr&&C.alphaToCoverage===!1,alphaMap:de,alphaTest:Se,alphaHash:Ie,combine:C.combine,mapUv:Mt&&m(C.map.channel),aoMapUv:H&&m(C.aoMap.channel),lightMapUv:wn&&m(C.lightMap.channel),bumpMapUv:pt&&m(C.bumpMap.channel),normalMapUv:mt&&m(C.normalMap.channel),displacementMapUv:We&&m(C.displacementMap.channel),emissiveMapUv:Dt&&m(C.emissiveMap.channel),metalnessMapUv:ze&&m(C.metalnessMap.channel),roughnessMapUv:L&&m(C.roughnessMap.channel),anisotropyMapUv:ve&&m(C.anisotropyMap.channel),clearcoatMapUv:qe&&m(C.clearcoatMap.channel),clearcoatNormalMapUv:Ze&&m(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ee&&m(C.clearcoatRoughnessMap.channel),iridescenceMapUv:De&&m(C.iridescenceMap.channel),iridescenceThicknessMapUv:Oe&&m(C.iridescenceThicknessMap.channel),sheenColorMapUv:Ge&&m(C.sheenColorMap.channel),sheenRoughnessMapUv:Te&&m(C.sheenRoughnessMap.channel),specularMapUv:nt&&m(C.specularMap.channel),specularColorMapUv:Ke&&m(C.specularColorMap.channel),specularIntensityMapUv:it&&m(C.specularIntensityMap.channel),transmissionMapUv:W&&m(C.transmissionMap.channel),thicknessMapUv:ne&&m(C.thicknessMap.channel),alphaMapUv:de&&m(C.alphaMap.channel),vertexTangents:!!D.attributes.tangent&&(mt||M),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!D.attributes.color&&D.attributes.color.itemSize===4,pointsUvs:q.isPoints===!0&&!!D.attributes.uv&&(Mt||de),fog:!!$,useFog:C.fog===!0,fogExp2:!!$&&$.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:u,reverseDepthBuffer:Ue,skinning:q.isSkinnedMesh===!0,morphTargets:D.morphAttributes.position!==void 0,morphNormals:D.morphAttributes.normal!==void 0,morphColors:D.morphAttributes.color!==void 0,morphTargetsCount:ae,morphTextureStride:_e,numDirLights:v.directional.length,numPointLights:v.point.length,numSpotLights:v.spot.length,numSpotLightMaps:v.spotLightMap.length,numRectAreaLights:v.rectArea.length,numHemiLights:v.hemi.length,numDirLightShadows:v.directionalShadowMap.length,numPointLightShadows:v.pointShadowMap.length,numSpotLightShadows:v.spotShadowMap.length,numSpotLightShadowsWithMaps:v.numSpotLightShadowsWithMaps,numLightProbes:v.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:C.dithering,shadowMapEnabled:i.shadowMap.enabled&&F.length>0,shadowMapType:i.shadowMap.type,toneMapping:Ht,decodeVideoTexture:Mt&&C.map.isVideoTexture===!0&&tt.getTransfer(C.map.colorSpace)===Rt,decodeVideoTextureEmissive:Dt&&C.emissiveMap.isVideoTexture===!0&&tt.getTransfer(C.emissiveMap.colorSpace)===Rt,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Pi,flipSided:C.side===Ln,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:st&&C.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(st&&C.extensions.multiDraw===!0||He)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return vn.vertexUv1s=l.has(1),vn.vertexUv2s=l.has(2),vn.vertexUv3s=l.has(3),l.clear(),vn}function A(C){const v=[];if(C.shaderID?v.push(C.shaderID):(v.push(C.customVertexShaderID),v.push(C.customFragmentShaderID)),C.defines!==void 0)for(const F in C.defines)v.push(F),v.push(C.defines[F]);return C.isRawShaderMaterial===!1&&(_(v,C),x(v,C),v.push(i.outputColorSpace)),v.push(C.customProgramCacheKey),v.join()}function _(C,v){C.push(v.precision),C.push(v.outputColorSpace),C.push(v.envMapMode),C.push(v.envMapCubeUVHeight),C.push(v.mapUv),C.push(v.alphaMapUv),C.push(v.lightMapUv),C.push(v.aoMapUv),C.push(v.bumpMapUv),C.push(v.normalMapUv),C.push(v.displacementMapUv),C.push(v.emissiveMapUv),C.push(v.metalnessMapUv),C.push(v.roughnessMapUv),C.push(v.anisotropyMapUv),C.push(v.clearcoatMapUv),C.push(v.clearcoatNormalMapUv),C.push(v.clearcoatRoughnessMapUv),C.push(v.iridescenceMapUv),C.push(v.iridescenceThicknessMapUv),C.push(v.sheenColorMapUv),C.push(v.sheenRoughnessMapUv),C.push(v.specularMapUv),C.push(v.specularColorMapUv),C.push(v.specularIntensityMapUv),C.push(v.transmissionMapUv),C.push(v.thicknessMapUv),C.push(v.combine),C.push(v.fogExp2),C.push(v.sizeAttenuation),C.push(v.morphTargetsCount),C.push(v.morphAttributeCount),C.push(v.numDirLights),C.push(v.numPointLights),C.push(v.numSpotLights),C.push(v.numSpotLightMaps),C.push(v.numHemiLights),C.push(v.numRectAreaLights),C.push(v.numDirLightShadows),C.push(v.numPointLightShadows),C.push(v.numSpotLightShadows),C.push(v.numSpotLightShadowsWithMaps),C.push(v.numLightProbes),C.push(v.shadowMapType),C.push(v.toneMapping),C.push(v.numClippingPlanes),C.push(v.numClipIntersection),C.push(v.depthPacking)}function x(C,v){o.disableAll(),v.supportsVertexTextures&&o.enable(0),v.instancing&&o.enable(1),v.instancingColor&&o.enable(2),v.instancingMorph&&o.enable(3),v.matcap&&o.enable(4),v.envMap&&o.enable(5),v.normalMapObjectSpace&&o.enable(6),v.normalMapTangentSpace&&o.enable(7),v.clearcoat&&o.enable(8),v.iridescence&&o.enable(9),v.alphaTest&&o.enable(10),v.vertexColors&&o.enable(11),v.vertexAlphas&&o.enable(12),v.vertexUv1s&&o.enable(13),v.vertexUv2s&&o.enable(14),v.vertexUv3s&&o.enable(15),v.vertexTangents&&o.enable(16),v.anisotropy&&o.enable(17),v.alphaHash&&o.enable(18),v.batching&&o.enable(19),v.dispersion&&o.enable(20),v.batchingColor&&o.enable(21),C.push(o.mask),o.disableAll(),v.fog&&o.enable(0),v.useFog&&o.enable(1),v.flatShading&&o.enable(2),v.logarithmicDepthBuffer&&o.enable(3),v.reverseDepthBuffer&&o.enable(4),v.skinning&&o.enable(5),v.morphTargets&&o.enable(6),v.morphNormals&&o.enable(7),v.morphColors&&o.enable(8),v.premultipliedAlpha&&o.enable(9),v.shadowMapEnabled&&o.enable(10),v.doubleSided&&o.enable(11),v.flipSided&&o.enable(12),v.useDepthPacking&&o.enable(13),v.dithering&&o.enable(14),v.transmission&&o.enable(15),v.sheen&&o.enable(16),v.opaque&&o.enable(17),v.pointsUvs&&o.enable(18),v.decodeVideoTexture&&o.enable(19),v.decodeVideoTextureEmissive&&o.enable(20),v.alphaToCoverage&&o.enable(21),C.push(o.mask)}function E(C){const v=p[C.type];let F;if(v){const K=Qi[v];F=H_.clone(K.uniforms)}else F=C.uniforms;return F}function S(C,v){let F;for(let K=0,q=h.length;K<q;K++){const $=h[K];if($.cacheKey===v){F=$,++F.usedTimes;break}}return F===void 0&&(F=new FS(i,v,C,r),h.push(F)),F}function w(C){if(--C.usedTimes===0){const v=h.indexOf(C);h[v]=h[h.length-1],h.pop(),C.destroy()}}function I(C){c.remove(C)}function T(){c.dispose()}return{getParameters:g,getProgramCacheKey:A,getUniforms:E,acquireProgram:S,releaseProgram:w,releaseShaderCache:I,programs:h,dispose:T}}function kS(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function s(a,o,c){i.get(a)[o]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function US(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function Yg(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Jg(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function a(u,d,f,p,m,g){let A=i[e];return A===void 0?(A={id:u.id,object:u,geometry:d,material:f,groupOrder:p,renderOrder:u.renderOrder,z:m,group:g},i[e]=A):(A.id=u.id,A.object=u,A.geometry=d,A.material=f,A.groupOrder=p,A.renderOrder=u.renderOrder,A.z=m,A.group=g),e++,A}function o(u,d,f,p,m,g){const A=a(u,d,f,p,m,g);f.transmission>0?n.push(A):f.transparent===!0?s.push(A):t.push(A)}function c(u,d,f,p,m,g){const A=a(u,d,f,p,m,g);f.transmission>0?n.unshift(A):f.transparent===!0?s.unshift(A):t.unshift(A)}function l(u,d){t.length>1&&t.sort(u||US),n.length>1&&n.sort(d||Yg),s.length>1&&s.sort(d||Yg)}function h(){for(let u=e,d=i.length;u<d;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:o,unshift:c,finish:h,sort:l}}function OS(){let i=new WeakMap;function e(n,s){const r=i.get(n);let a;return r===void 0?(a=new Jg,i.set(n,[a])):s>=r.length?(a=new Jg,r.push(a)):a=r[s],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function QS(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new G,color:new Fe};break;case"SpotLight":t={position:new G,direction:new G,color:new Fe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new G,color:new Fe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new G,skyColor:new Fe,groundColor:new Fe};break;case"RectAreaLight":t={color:new Fe,position:new G,halfWidth:new G,halfHeight:new G};break}return i[e.id]=t,t}}}function GS(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let HS=0;function zS(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function VS(i){const e=new QS,t=GS(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new G);const s=new G,r=new Re,a=new Re;function o(l){let h=0,u=0,d=0;for(let C=0;C<9;C++)n.probe[C].set(0,0,0);let f=0,p=0,m=0,g=0,A=0,_=0,x=0,E=0,S=0,w=0,I=0;l.sort(zS);for(let C=0,v=l.length;C<v;C++){const F=l[C],K=F.color,q=F.intensity,$=F.distance,D=F.shadow&&F.shadow.map?F.shadow.map.texture:null;if(F.isAmbientLight)h+=K.r*q,u+=K.g*q,d+=K.b*q;else if(F.isLightProbe){for(let O=0;O<9;O++)n.probe[O].addScaledVector(F.sh.coefficients[O],q);I++}else if(F.isDirectionalLight){const O=e.get(F);if(O.color.copy(F.color).multiplyScalar(F.intensity),F.castShadow){const Y=F.shadow,Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,n.directionalShadow[f]=Q,n.directionalShadowMap[f]=D,n.directionalShadowMatrix[f]=F.shadow.matrix,_++}n.directional[f]=O,f++}else if(F.isSpotLight){const O=e.get(F);O.position.setFromMatrixPosition(F.matrixWorld),O.color.copy(K).multiplyScalar(q),O.distance=$,O.coneCos=Math.cos(F.angle),O.penumbraCos=Math.cos(F.angle*(1-F.penumbra)),O.decay=F.decay,n.spot[m]=O;const Y=F.shadow;if(F.map&&(n.spotLightMap[S]=F.map,S++,Y.updateMatrices(F),F.castShadow&&w++),n.spotLightMatrix[m]=Y.matrix,F.castShadow){const Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,n.spotShadow[m]=Q,n.spotShadowMap[m]=D,E++}m++}else if(F.isRectAreaLight){const O=e.get(F);O.color.copy(K).multiplyScalar(q),O.halfWidth.set(F.width*.5,0,0),O.halfHeight.set(0,F.height*.5,0),n.rectArea[g]=O,g++}else if(F.isPointLight){const O=e.get(F);if(O.color.copy(F.color).multiplyScalar(F.intensity),O.distance=F.distance,O.decay=F.decay,F.castShadow){const Y=F.shadow,Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,Q.shadowCameraNear=Y.camera.near,Q.shadowCameraFar=Y.camera.far,n.pointShadow[p]=Q,n.pointShadowMap[p]=D,n.pointShadowMatrix[p]=F.shadow.matrix,x++}n.point[p]=O,p++}else if(F.isHemisphereLight){const O=e.get(F);O.skyColor.copy(F.color).multiplyScalar(q),O.groundColor.copy(F.groundColor).multiplyScalar(q),n.hemi[A]=O,A++}}g>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=we.LTC_FLOAT_1,n.rectAreaLTC2=we.LTC_FLOAT_2):(n.rectAreaLTC1=we.LTC_HALF_1,n.rectAreaLTC2=we.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=d;const T=n.hash;(T.directionalLength!==f||T.pointLength!==p||T.spotLength!==m||T.rectAreaLength!==g||T.hemiLength!==A||T.numDirectionalShadows!==_||T.numPointShadows!==x||T.numSpotShadows!==E||T.numSpotMaps!==S||T.numLightProbes!==I)&&(n.directional.length=f,n.spot.length=m,n.rectArea.length=g,n.point.length=p,n.hemi.length=A,n.directionalShadow.length=_,n.directionalShadowMap.length=_,n.pointShadow.length=x,n.pointShadowMap.length=x,n.spotShadow.length=E,n.spotShadowMap.length=E,n.directionalShadowMatrix.length=_,n.pointShadowMatrix.length=x,n.spotLightMatrix.length=E+S-w,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=w,n.numLightProbes=I,T.directionalLength=f,T.pointLength=p,T.spotLength=m,T.rectAreaLength=g,T.hemiLength=A,T.numDirectionalShadows=_,T.numPointShadows=x,T.numSpotShadows=E,T.numSpotMaps=S,T.numLightProbes=I,n.version=HS++)}function c(l,h){let u=0,d=0,f=0,p=0,m=0;const g=h.matrixWorldInverse;for(let A=0,_=l.length;A<_;A++){const x=l[A];if(x.isDirectionalLight){const E=n.directional[u];E.direction.setFromMatrixPosition(x.matrixWorld),s.setFromMatrixPosition(x.target.matrixWorld),E.direction.sub(s),E.direction.transformDirection(g),u++}else if(x.isSpotLight){const E=n.spot[f];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),E.direction.setFromMatrixPosition(x.matrixWorld),s.setFromMatrixPosition(x.target.matrixWorld),E.direction.sub(s),E.direction.transformDirection(g),f++}else if(x.isRectAreaLight){const E=n.rectArea[p];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),a.identity(),r.copy(x.matrixWorld),r.premultiply(g),a.extractRotation(r),E.halfWidth.set(x.width*.5,0,0),E.halfHeight.set(0,x.height*.5,0),E.halfWidth.applyMatrix4(a),E.halfHeight.applyMatrix4(a),p++}else if(x.isPointLight){const E=n.point[d];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),d++}else if(x.isHemisphereLight){const E=n.hemi[m];E.direction.setFromMatrixPosition(x.matrixWorld),E.direction.transformDirection(g),m++}}}return{setup:o,setupView:c,state:n}}function Zg(i){const e=new VS(i),t=[],n=[];function s(h){l.camera=h,t.length=0,n.length=0}function r(h){t.push(h)}function a(h){n.push(h)}function o(){e.setup(t)}function c(h){e.setupView(t,h)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:o,setupLightsView:c,pushLight:r,pushShadow:a}}function WS(i){let e=new WeakMap;function t(s,r=0){const a=e.get(s);let o;return a===void 0?(o=new Zg(i),e.set(s,[o])):r>=a.length?(o=new Zg(i),a.push(o)):o=a[r],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const qS=`void main() {
+`+Q)}else K!==""?console.warn("THREE.WebGLProgram: Program Info Log:",K):(q===""||$==="")&&(O=!1);O&&(F.diagnostics={runnable:D,programLog:K,vertexShader:{log:q,prefix:g},fragmentShader:{log:$,prefix:A}})}s.deleteShader(S),s.deleteShader(w),T=new Nl(s,m),C=ES(s,m)}let T;this.getUniforms=function(){return T===void 0&&I(this),T};let C;this.getAttributes=function(){return C===void 0&&I(this),C};let v=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return v===!1&&(v=s.getProgramParameter(m,uS)),v},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=dS++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=S,this.fragmentShader=w,this}let FS=0;class NS{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(s)===!1&&(a.add(s),s.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new DS(e),t.set(e,n)),n}}class DS{constructor(e){this.id=FS++,this.code=e,this.usedTimes=0}}function LS(i,e,t,n,s,r,a){const o=new yA,c=new NS,l=new Set,h=[],u=s.logarithmicDepthBuffer,d=s.vertexTextures;let f=s.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(C){return l.add(C),C===0?"uv":`uv${C}`}function g(C,v,F,K,q){const $=K.fog,D=q.geometry,O=C.isMeshStandardMaterial?K.environment:null,Y=(C.isMeshStandardMaterial?t:e).get(C.envMap||O),Q=Y&&Y.mapping===Bc?Y.image.height:null,J=p[C.type];C.precision!==null&&(f=s.getMaxPrecision(C.precision),f!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",f,"instead."));const ee=D.morphAttributes.position||D.morphAttributes.normal||D.morphAttributes.color,ae=ee!==void 0?ee.length:0;let _e=0;D.morphAttributes.position!==void 0&&(_e=1),D.morphAttributes.normal!==void 0&&(_e=2),D.morphAttributes.color!==void 0&&(_e=3);let Me,se,me,xe;if(J){const Ct=Qi[J];Me=Ct.vertexShader,se=Ct.fragmentShader}else Me=C.vertexShader,se=C.fragmentShader,c.update(C),me=c.getVertexShaderID(C),xe=c.getFragmentShaderID(C);const be=i.getRenderTarget(),Ue=i.state.buffers.depth.getReversed(),et=q.isInstancedMesh===!0,He=q.isBatchedMesh===!0,Mt=!!C.map,ft=!!C.matcap,$e=!!Y,H=!!C.aoMap,wn=!!C.lightMap,pt=!!C.bumpMap,mt=!!C.normalMap,We=!!C.displacementMap,Dt=!!C.emissiveMap,ze=!!C.metalnessMap,L=!!C.roughnessMap,M=C.anisotropy>0,Z=C.clearcoat>0,le=C.dispersion>0,Ae=C.iridescence>0,oe=C.sheen>0,Qe=C.transmission>0,ve=M&&!!C.anisotropyMap,qe=Z&&!!C.clearcoatMap,Ze=Z&&!!C.clearcoatNormalMap,Ee=Z&&!!C.clearcoatRoughnessMap,De=Ae&&!!C.iridescenceMap,Oe=Ae&&!!C.iridescenceThicknessMap,Ge=oe&&!!C.sheenColorMap,Te=oe&&!!C.sheenRoughnessMap,nt=!!C.specularMap,Ke=!!C.specularColorMap,it=!!C.specularIntensityMap,W=Qe&&!!C.transmissionMap,ne=Qe&&!!C.thicknessMap,re=!!C.gradientMap,de=!!C.alphaMap,Se=C.alphaTest>0,Ie=!!C.alphaHash,st=!!C.extensions;let Ht=Is;C.toneMapped&&(be===null||be.isXRRenderTarget===!0)&&(Ht=i.toneMapping);const vn={shaderID:J,shaderType:C.type,shaderName:C.name,vertexShader:Me,fragmentShader:se,defines:C.defines,customVertexShaderID:me,customFragmentShaderID:xe,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:f,batching:He,batchingColor:He&&q._colorsTexture!==null,instancing:et,instancingColor:et&&q.instanceColor!==null,instancingMorph:et&&q.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:be===null?i.outputColorSpace:be.isXRRenderTarget===!0?be.texture.colorSpace:un,alphaToCoverage:!!C.alphaToCoverage,map:Mt,matcap:ft,envMap:$e,envMapMode:$e&&Y.mapping,envMapCubeUVHeight:Q,aoMap:H,lightMap:wn,bumpMap:pt,normalMap:mt,displacementMap:d&&We,emissiveMap:Dt,normalMapObjectSpace:mt&&C.normalMapType===Ky,normalMapTangentSpace:mt&&C.normalMapType===Gc,metalnessMap:ze,roughnessMap:L,anisotropy:M,anisotropyMap:ve,clearcoat:Z,clearcoatMap:qe,clearcoatNormalMap:Ze,clearcoatRoughnessMap:Ee,dispersion:le,iridescence:Ae,iridescenceMap:De,iridescenceThicknessMap:Oe,sheen:oe,sheenColorMap:Ge,sheenRoughnessMap:Te,specularMap:nt,specularColorMap:Ke,specularIntensityMap:it,transmission:Qe,transmissionMap:W,thicknessMap:ne,gradientMap:re,opaque:C.transparent===!1&&C.blending===jr&&C.alphaToCoverage===!1,alphaMap:de,alphaTest:Se,alphaHash:Ie,combine:C.combine,mapUv:Mt&&m(C.map.channel),aoMapUv:H&&m(C.aoMap.channel),lightMapUv:wn&&m(C.lightMap.channel),bumpMapUv:pt&&m(C.bumpMap.channel),normalMapUv:mt&&m(C.normalMap.channel),displacementMapUv:We&&m(C.displacementMap.channel),emissiveMapUv:Dt&&m(C.emissiveMap.channel),metalnessMapUv:ze&&m(C.metalnessMap.channel),roughnessMapUv:L&&m(C.roughnessMap.channel),anisotropyMapUv:ve&&m(C.anisotropyMap.channel),clearcoatMapUv:qe&&m(C.clearcoatMap.channel),clearcoatNormalMapUv:Ze&&m(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ee&&m(C.clearcoatRoughnessMap.channel),iridescenceMapUv:De&&m(C.iridescenceMap.channel),iridescenceThicknessMapUv:Oe&&m(C.iridescenceThicknessMap.channel),sheenColorMapUv:Ge&&m(C.sheenColorMap.channel),sheenRoughnessMapUv:Te&&m(C.sheenRoughnessMap.channel),specularMapUv:nt&&m(C.specularMap.channel),specularColorMapUv:Ke&&m(C.specularColorMap.channel),specularIntensityMapUv:it&&m(C.specularIntensityMap.channel),transmissionMapUv:W&&m(C.transmissionMap.channel),thicknessMapUv:ne&&m(C.thicknessMap.channel),alphaMapUv:de&&m(C.alphaMap.channel),vertexTangents:!!D.attributes.tangent&&(mt||M),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!D.attributes.color&&D.attributes.color.itemSize===4,pointsUvs:q.isPoints===!0&&!!D.attributes.uv&&(Mt||de),fog:!!$,useFog:C.fog===!0,fogExp2:!!$&&$.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:u,reverseDepthBuffer:Ue,skinning:q.isSkinnedMesh===!0,morphTargets:D.morphAttributes.position!==void 0,morphNormals:D.morphAttributes.normal!==void 0,morphColors:D.morphAttributes.color!==void 0,morphTargetsCount:ae,morphTextureStride:_e,numDirLights:v.directional.length,numPointLights:v.point.length,numSpotLights:v.spot.length,numSpotLightMaps:v.spotLightMap.length,numRectAreaLights:v.rectArea.length,numHemiLights:v.hemi.length,numDirLightShadows:v.directionalShadowMap.length,numPointLightShadows:v.pointShadowMap.length,numSpotLightShadows:v.spotShadowMap.length,numSpotLightShadowsWithMaps:v.numSpotLightShadowsWithMaps,numLightProbes:v.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:C.dithering,shadowMapEnabled:i.shadowMap.enabled&&F.length>0,shadowMapType:i.shadowMap.type,toneMapping:Ht,decodeVideoTexture:Mt&&C.map.isVideoTexture===!0&&tt.getTransfer(C.map.colorSpace)===Rt,decodeVideoTextureEmissive:Dt&&C.emissiveMap.isVideoTexture===!0&&tt.getTransfer(C.emissiveMap.colorSpace)===Rt,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Pi,flipSided:C.side===Ln,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:st&&C.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(st&&C.extensions.multiDraw===!0||He)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return vn.vertexUv1s=l.has(1),vn.vertexUv2s=l.has(2),vn.vertexUv3s=l.has(3),l.clear(),vn}function A(C){const v=[];if(C.shaderID?v.push(C.shaderID):(v.push(C.customVertexShaderID),v.push(C.customFragmentShaderID)),C.defines!==void 0)for(const F in C.defines)v.push(F),v.push(C.defines[F]);return C.isRawShaderMaterial===!1&&(_(v,C),x(v,C),v.push(i.outputColorSpace)),v.push(C.customProgramCacheKey),v.join()}function _(C,v){C.push(v.precision),C.push(v.outputColorSpace),C.push(v.envMapMode),C.push(v.envMapCubeUVHeight),C.push(v.mapUv),C.push(v.alphaMapUv),C.push(v.lightMapUv),C.push(v.aoMapUv),C.push(v.bumpMapUv),C.push(v.normalMapUv),C.push(v.displacementMapUv),C.push(v.emissiveMapUv),C.push(v.metalnessMapUv),C.push(v.roughnessMapUv),C.push(v.anisotropyMapUv),C.push(v.clearcoatMapUv),C.push(v.clearcoatNormalMapUv),C.push(v.clearcoatRoughnessMapUv),C.push(v.iridescenceMapUv),C.push(v.iridescenceThicknessMapUv),C.push(v.sheenColorMapUv),C.push(v.sheenRoughnessMapUv),C.push(v.specularMapUv),C.push(v.specularColorMapUv),C.push(v.specularIntensityMapUv),C.push(v.transmissionMapUv),C.push(v.thicknessMapUv),C.push(v.combine),C.push(v.fogExp2),C.push(v.sizeAttenuation),C.push(v.morphTargetsCount),C.push(v.morphAttributeCount),C.push(v.numDirLights),C.push(v.numPointLights),C.push(v.numSpotLights),C.push(v.numSpotLightMaps),C.push(v.numHemiLights),C.push(v.numRectAreaLights),C.push(v.numDirLightShadows),C.push(v.numPointLightShadows),C.push(v.numSpotLightShadows),C.push(v.numSpotLightShadowsWithMaps),C.push(v.numLightProbes),C.push(v.shadowMapType),C.push(v.toneMapping),C.push(v.numClippingPlanes),C.push(v.numClipIntersection),C.push(v.depthPacking)}function x(C,v){o.disableAll(),v.supportsVertexTextures&&o.enable(0),v.instancing&&o.enable(1),v.instancingColor&&o.enable(2),v.instancingMorph&&o.enable(3),v.matcap&&o.enable(4),v.envMap&&o.enable(5),v.normalMapObjectSpace&&o.enable(6),v.normalMapTangentSpace&&o.enable(7),v.clearcoat&&o.enable(8),v.iridescence&&o.enable(9),v.alphaTest&&o.enable(10),v.vertexColors&&o.enable(11),v.vertexAlphas&&o.enable(12),v.vertexUv1s&&o.enable(13),v.vertexUv2s&&o.enable(14),v.vertexUv3s&&o.enable(15),v.vertexTangents&&o.enable(16),v.anisotropy&&o.enable(17),v.alphaHash&&o.enable(18),v.batching&&o.enable(19),v.dispersion&&o.enable(20),v.batchingColor&&o.enable(21),C.push(o.mask),o.disableAll(),v.fog&&o.enable(0),v.useFog&&o.enable(1),v.flatShading&&o.enable(2),v.logarithmicDepthBuffer&&o.enable(3),v.reverseDepthBuffer&&o.enable(4),v.skinning&&o.enable(5),v.morphTargets&&o.enable(6),v.morphNormals&&o.enable(7),v.morphColors&&o.enable(8),v.premultipliedAlpha&&o.enable(9),v.shadowMapEnabled&&o.enable(10),v.doubleSided&&o.enable(11),v.flipSided&&o.enable(12),v.useDepthPacking&&o.enable(13),v.dithering&&o.enable(14),v.transmission&&o.enable(15),v.sheen&&o.enable(16),v.opaque&&o.enable(17),v.pointsUvs&&o.enable(18),v.decodeVideoTexture&&o.enable(19),v.decodeVideoTextureEmissive&&o.enable(20),v.alphaToCoverage&&o.enable(21),C.push(o.mask)}function E(C){const v=p[C.type];let F;if(v){const K=Qi[v];F=G_.clone(K.uniforms)}else F=C.uniforms;return F}function S(C,v){let F;for(let K=0,q=h.length;K<q;K++){const $=h[K];if($.cacheKey===v){F=$,++F.usedTimes;break}}return F===void 0&&(F=new RS(i,v,C,r),h.push(F)),F}function w(C){if(--C.usedTimes===0){const v=h.indexOf(C);h[v]=h[h.length-1],h.pop(),C.destroy()}}function I(C){c.remove(C)}function T(){c.dispose()}return{getParameters:g,getProgramCacheKey:A,getUniforms:E,acquireProgram:S,releaseProgram:w,releaseShaderCache:I,programs:h,dispose:T}}function PS(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function s(a,o,c){i.get(a)[o]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function kS(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function Yg(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Jg(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function a(u,d,f,p,m,g){let A=i[e];return A===void 0?(A={id:u.id,object:u,geometry:d,material:f,groupOrder:p,renderOrder:u.renderOrder,z:m,group:g},i[e]=A):(A.id=u.id,A.object=u,A.geometry=d,A.material=f,A.groupOrder=p,A.renderOrder=u.renderOrder,A.z=m,A.group=g),e++,A}function o(u,d,f,p,m,g){const A=a(u,d,f,p,m,g);f.transmission>0?n.push(A):f.transparent===!0?s.push(A):t.push(A)}function c(u,d,f,p,m,g){const A=a(u,d,f,p,m,g);f.transmission>0?n.unshift(A):f.transparent===!0?s.unshift(A):t.unshift(A)}function l(u,d){t.length>1&&t.sort(u||kS),n.length>1&&n.sort(d||Yg),s.length>1&&s.sort(d||Yg)}function h(){for(let u=e,d=i.length;u<d;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:o,unshift:c,finish:h,sort:l}}function US(){let i=new WeakMap;function e(n,s){const r=i.get(n);let a;return r===void 0?(a=new Jg,i.set(n,[a])):s>=r.length?(a=new Jg,r.push(a)):a=r[s],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function OS(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new G,color:new Fe};break;case"SpotLight":t={position:new G,direction:new G,color:new Fe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new G,color:new Fe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new G,skyColor:new Fe,groundColor:new Fe};break;case"RectAreaLight":t={color:new Fe,position:new G,halfWidth:new G,halfHeight:new G};break}return i[e.id]=t,t}}}function QS(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Je,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let GS=0;function HS(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function zS(i){const e=new OS,t=QS(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new G);const s=new G,r=new Re,a=new Re;function o(l){let h=0,u=0,d=0;for(let C=0;C<9;C++)n.probe[C].set(0,0,0);let f=0,p=0,m=0,g=0,A=0,_=0,x=0,E=0,S=0,w=0,I=0;l.sort(HS);for(let C=0,v=l.length;C<v;C++){const F=l[C],K=F.color,q=F.intensity,$=F.distance,D=F.shadow&&F.shadow.map?F.shadow.map.texture:null;if(F.isAmbientLight)h+=K.r*q,u+=K.g*q,d+=K.b*q;else if(F.isLightProbe){for(let O=0;O<9;O++)n.probe[O].addScaledVector(F.sh.coefficients[O],q);I++}else if(F.isDirectionalLight){const O=e.get(F);if(O.color.copy(F.color).multiplyScalar(F.intensity),F.castShadow){const Y=F.shadow,Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,n.directionalShadow[f]=Q,n.directionalShadowMap[f]=D,n.directionalShadowMatrix[f]=F.shadow.matrix,_++}n.directional[f]=O,f++}else if(F.isSpotLight){const O=e.get(F);O.position.setFromMatrixPosition(F.matrixWorld),O.color.copy(K).multiplyScalar(q),O.distance=$,O.coneCos=Math.cos(F.angle),O.penumbraCos=Math.cos(F.angle*(1-F.penumbra)),O.decay=F.decay,n.spot[m]=O;const Y=F.shadow;if(F.map&&(n.spotLightMap[S]=F.map,S++,Y.updateMatrices(F),F.castShadow&&w++),n.spotLightMatrix[m]=Y.matrix,F.castShadow){const Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,n.spotShadow[m]=Q,n.spotShadowMap[m]=D,E++}m++}else if(F.isRectAreaLight){const O=e.get(F);O.color.copy(K).multiplyScalar(q),O.halfWidth.set(F.width*.5,0,0),O.halfHeight.set(0,F.height*.5,0),n.rectArea[g]=O,g++}else if(F.isPointLight){const O=e.get(F);if(O.color.copy(F.color).multiplyScalar(F.intensity),O.distance=F.distance,O.decay=F.decay,F.castShadow){const Y=F.shadow,Q=t.get(F);Q.shadowIntensity=Y.intensity,Q.shadowBias=Y.bias,Q.shadowNormalBias=Y.normalBias,Q.shadowRadius=Y.radius,Q.shadowMapSize=Y.mapSize,Q.shadowCameraNear=Y.camera.near,Q.shadowCameraFar=Y.camera.far,n.pointShadow[p]=Q,n.pointShadowMap[p]=D,n.pointShadowMatrix[p]=F.shadow.matrix,x++}n.point[p]=O,p++}else if(F.isHemisphereLight){const O=e.get(F);O.skyColor.copy(F.color).multiplyScalar(q),O.groundColor.copy(F.groundColor).multiplyScalar(q),n.hemi[A]=O,A++}}g>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=we.LTC_FLOAT_1,n.rectAreaLTC2=we.LTC_FLOAT_2):(n.rectAreaLTC1=we.LTC_HALF_1,n.rectAreaLTC2=we.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=d;const T=n.hash;(T.directionalLength!==f||T.pointLength!==p||T.spotLength!==m||T.rectAreaLength!==g||T.hemiLength!==A||T.numDirectionalShadows!==_||T.numPointShadows!==x||T.numSpotShadows!==E||T.numSpotMaps!==S||T.numLightProbes!==I)&&(n.directional.length=f,n.spot.length=m,n.rectArea.length=g,n.point.length=p,n.hemi.length=A,n.directionalShadow.length=_,n.directionalShadowMap.length=_,n.pointShadow.length=x,n.pointShadowMap.length=x,n.spotShadow.length=E,n.spotShadowMap.length=E,n.directionalShadowMatrix.length=_,n.pointShadowMatrix.length=x,n.spotLightMatrix.length=E+S-w,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=w,n.numLightProbes=I,T.directionalLength=f,T.pointLength=p,T.spotLength=m,T.rectAreaLength=g,T.hemiLength=A,T.numDirectionalShadows=_,T.numPointShadows=x,T.numSpotShadows=E,T.numSpotMaps=S,T.numLightProbes=I,n.version=GS++)}function c(l,h){let u=0,d=0,f=0,p=0,m=0;const g=h.matrixWorldInverse;for(let A=0,_=l.length;A<_;A++){const x=l[A];if(x.isDirectionalLight){const E=n.directional[u];E.direction.setFromMatrixPosition(x.matrixWorld),s.setFromMatrixPosition(x.target.matrixWorld),E.direction.sub(s),E.direction.transformDirection(g),u++}else if(x.isSpotLight){const E=n.spot[f];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),E.direction.setFromMatrixPosition(x.matrixWorld),s.setFromMatrixPosition(x.target.matrixWorld),E.direction.sub(s),E.direction.transformDirection(g),f++}else if(x.isRectAreaLight){const E=n.rectArea[p];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),a.identity(),r.copy(x.matrixWorld),r.premultiply(g),a.extractRotation(r),E.halfWidth.set(x.width*.5,0,0),E.halfHeight.set(0,x.height*.5,0),E.halfWidth.applyMatrix4(a),E.halfHeight.applyMatrix4(a),p++}else if(x.isPointLight){const E=n.point[d];E.position.setFromMatrixPosition(x.matrixWorld),E.position.applyMatrix4(g),d++}else if(x.isHemisphereLight){const E=n.hemi[m];E.direction.setFromMatrixPosition(x.matrixWorld),E.direction.transformDirection(g),m++}}}return{setup:o,setupView:c,state:n}}function Zg(i){const e=new zS(i),t=[],n=[];function s(h){l.camera=h,t.length=0,n.length=0}function r(h){t.push(h)}function a(h){n.push(h)}function o(){e.setup(t)}function c(h){e.setupView(t,h)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:o,setupLightsView:c,pushLight:r,pushShadow:a}}function VS(i){let e=new WeakMap;function t(s,r=0){const a=e.get(s);let o;return a===void 0?(o=new Zg(i),e.set(s,[o])):r>=a.length?(o=new Zg(i),a.push(o)):o=a[r],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const WS=`void main() {
gl_Position = vec4( position, 1.0 );
-}`,KS=`uniform sampler2D shadow_pass;
+}`,qS=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
@@ -3792,12 +3792,12 @@ void main() {
squared_mean = squared_mean / samples;
float std_dev = sqrt( squared_mean - mean * mean );
gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
-}`;function jS(i,e,t){let n=new rd;const s=new Je,r=new Je,a=new gt,o=new vw({depthPacking:Ky}),c=new Cw,l={},h=t.maxTextureSize,u={[ji]:Ln,[Ln]:ji,[Pi]:Pi},d=new Ls({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Je},radius:{value:4}},vertexShader:qS,fragmentShader:KS}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new Mn;p.setAttribute("position",new Sn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Zt(p,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Wp;let A=this.type;this.render=function(w,I,T){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||w.length===0)return;const C=i.getRenderTarget(),v=i.getActiveCubeFace(),F=i.getActiveMipmapLevel(),K=i.state;K.setBlending(Cs),K.buffers.color.setClear(1,1,1,1),K.buffers.depth.setTest(!0),K.setScissorTest(!1);const q=A!==Ki&&this.type===Ki,$=A===Ki&&this.type!==Ki;for(let D=0,O=w.length;D<O;D++){const Y=w[D],Q=Y.shadow;if(Q===void 0){console.warn("THREE.WebGLShadowMap:",Y,"has no shadow.");continue}if(Q.autoUpdate===!1&&Q.needsUpdate===!1)continue;s.copy(Q.mapSize);const J=Q.getFrameExtents();if(s.multiply(J),r.copy(Q.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/J.x),s.x=r.x*J.x,Q.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/J.y),s.y=r.y*J.y,Q.mapSize.y=r.y)),Q.map===null||q===!0||$===!0){const ae=this.type!==Ki?{minFilter:Pn,magFilter:Pn}:{};Q.map!==null&&Q.map.dispose(),Q.map=new or(s.x,s.y,ae),Q.map.texture.name=Y.name+".shadowMap",Q.camera.updateProjectionMatrix()}i.setRenderTarget(Q.map),i.clear();const ee=Q.getViewportCount();for(let ae=0;ae<ee;ae++){const _e=Q.getViewport(ae);a.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),K.viewport(a),Q.updateMatrices(Y,ae),n=Q.getFrustum(),E(I,T,Q.camera,Y,this.type)}Q.isPointLightShadow!==!0&&this.type===Ki&&_(Q,T),Q.needsUpdate=!1}A=this.type,g.needsUpdate=!1,i.setRenderTarget(C,v,F)};function _(w,I){const T=e.update(m);d.defines.VSM_SAMPLES!==w.blurSamples&&(d.defines.VSM_SAMPLES=w.blurSamples,f.defines.VSM_SAMPLES=w.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),w.mapPass===null&&(w.mapPass=new or(s.x,s.y)),d.uniforms.shadow_pass.value=w.map.texture,d.uniforms.resolution.value=w.mapSize,d.uniforms.radius.value=w.radius,i.setRenderTarget(w.mapPass),i.clear(),i.renderBufferDirect(I,null,T,d,m,null),f.uniforms.shadow_pass.value=w.mapPass.texture,f.uniforms.resolution.value=w.mapSize,f.uniforms.radius.value=w.radius,i.setRenderTarget(w.map),i.clear(),i.renderBufferDirect(I,null,T,f,m,null)}function x(w,I,T,C){let v=null;const F=T.isPointLight===!0?w.customDistanceMaterial:w.customDepthMaterial;if(F!==void 0)v=F;else if(v=T.isPointLight===!0?c:o,i.localClippingEnabled&&I.clipShadows===!0&&Array.isArray(I.clippingPlanes)&&I.clippingPlanes.length!==0||I.displacementMap&&I.displacementScale!==0||I.alphaMap&&I.alphaTest>0||I.map&&I.alphaTest>0||I.alphaToCoverage===!0){const K=v.uuid,q=I.uuid;let $=l[K];$===void 0&&($={},l[K]=$);let D=$[q];D===void 0&&(D=v.clone(),$[q]=D,I.addEventListener("dispose",S)),v=D}if(v.visible=I.visible,v.wireframe=I.wireframe,C===Ki?v.side=I.shadowSide!==null?I.shadowSide:I.side:v.side=I.shadowSide!==null?I.shadowSide:u[I.side],v.alphaMap=I.alphaMap,v.alphaTest=I.alphaToCoverage===!0?.5:I.alphaTest,v.map=I.map,v.clipShadows=I.clipShadows,v.clippingPlanes=I.clippingPlanes,v.clipIntersection=I.clipIntersection,v.displacementMap=I.displacementMap,v.displacementScale=I.displacementScale,v.displacementBias=I.displacementBias,v.wireframeLinewidth=I.wireframeLinewidth,v.linewidth=I.linewidth,T.isPointLight===!0&&v.isMeshDistanceMaterial===!0){const K=i.properties.get(v);K.light=T}return v}function E(w,I,T,C,v){if(w.visible===!1)return;if(w.layers.test(I.layers)&&(w.isMesh||w.isLine||w.isPoints)&&(w.castShadow||w.receiveShadow&&v===Ki)&&(!w.frustumCulled||n.intersectsObject(w))){w.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,w.matrixWorld);const q=e.update(w),$=w.material;if(Array.isArray($)){const D=q.groups;for(let O=0,Y=D.length;O<Y;O++){const Q=D[O],J=$[Q.materialIndex];if(J&&J.visible){const ee=x(w,J,C,v);w.onBeforeShadow(i,w,I,T,q,ee,Q),i.renderBufferDirect(T,null,q,ee,w,Q),w.onAfterShadow(i,w,I,T,q,ee,Q)}}}else if($.visible){const D=x(w,$,C,v);w.onBeforeShadow(i,w,I,T,q,D,null),i.renderBufferDirect(T,null,q,D,w,null),w.onAfterShadow(i,w,I,T,q,D,null)}}const K=w.children;for(let q=0,$=K.length;q<$;q++)E(K[q],I,T,C,v)}function S(w){w.target.removeEventListener("dispose",S);for(const T in l){const C=l[T],v=w.target.uuid;v in C&&(C[v].dispose(),delete C[v])}}}const XS={[Kh]:jh,[Xh]:Zh,[Yh]:$h,[Xr]:Jh,[jh]:Kh,[Zh]:Xh,[$h]:Yh,[Jh]:Xr};function YS(i,e){function t(){let W=!1;const ne=new gt;let re=null;const de=new gt(0,0,0,0);return{setMask:function(Se){re!==Se&&!W&&(i.colorMask(Se,Se,Se,Se),re=Se)},setLocked:function(Se){W=Se},setClear:function(Se,Ie,st,Ht,vn){vn===!0&&(Se*=Ht,Ie*=Ht,st*=Ht),ne.set(Se,Ie,st,Ht),de.equals(ne)===!1&&(i.clearColor(Se,Ie,st,Ht),de.copy(ne))},reset:function(){W=!1,re=null,de.set(-1,0,0,0)}}}function n(){let W=!1,ne=!1,re=null,de=null,Se=null;return{setReversed:function(Ie){if(ne!==Ie){const st=e.get("EXT_clip_control");Ie?st.clipControlEXT(st.LOWER_LEFT_EXT,st.ZERO_TO_ONE_EXT):st.clipControlEXT(st.LOWER_LEFT_EXT,st.NEGATIVE_ONE_TO_ONE_EXT),ne=Ie;const Ht=Se;Se=null,this.setClear(Ht)}},getReversed:function(){return ne},setTest:function(Ie){Ie?be(i.DEPTH_TEST):Ue(i.DEPTH_TEST)},setMask:function(Ie){re!==Ie&&!W&&(i.depthMask(Ie),re=Ie)},setFunc:function(Ie){if(ne&&(Ie=XS[Ie]),de!==Ie){switch(Ie){case Kh:i.depthFunc(i.NEVER);break;case jh:i.depthFunc(i.ALWAYS);break;case Xh:i.depthFunc(i.LESS);break;case Xr:i.depthFunc(i.LEQUAL);break;case Yh:i.depthFunc(i.EQUAL);break;case Jh:i.depthFunc(i.GEQUAL);break;case Zh:i.depthFunc(i.GREATER);break;case $h:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}de=Ie}},setLocked:function(Ie){W=Ie},setClear:function(Ie){Se!==Ie&&(ne&&(Ie=1-Ie),i.clearDepth(Ie),Se=Ie)},reset:function(){W=!1,re=null,de=null,Se=null,ne=!1}}}function s(){let W=!1,ne=null,re=null,de=null,Se=null,Ie=null,st=null,Ht=null,vn=null;return{setTest:function(Ct){W||(Ct?be(i.STENCIL_TEST):Ue(i.STENCIL_TEST))},setMask:function(Ct){ne!==Ct&&!W&&(i.stencilMask(Ct),ne=Ct)},setFunc:function(Ct,si,Li){(re!==Ct||de!==si||Se!==Li)&&(i.stencilFunc(Ct,si,Li),re=Ct,de=si,Se=Li)},setOp:function(Ct,si,Li){(Ie!==Ct||st!==si||Ht!==Li)&&(i.stencilOp(Ct,si,Li),Ie=Ct,st=si,Ht=Li)},setLocked:function(Ct){W=Ct},setClear:function(Ct){vn!==Ct&&(i.clearStencil(Ct),vn=Ct)},reset:function(){W=!1,ne=null,re=null,de=null,Se=null,Ie=null,st=null,Ht=null,vn=null}}}const r=new t,a=new n,o=new s,c=new WeakMap,l=new WeakMap;let h={},u={},d=new WeakMap,f=[],p=null,m=!1,g=null,A=null,_=null,x=null,E=null,S=null,w=null,I=new Fe(0,0,0),T=0,C=!1,v=null,F=null,K=null,q=null,$=null;const D=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let O=!1,Y=0;const Q=i.getParameter(i.VERSION);Q.indexOf("WebGL")!==-1?(Y=parseFloat(/^WebGL (\d)/.exec(Q)[1]),O=Y>=1):Q.indexOf("OpenGL ES")!==-1&&(Y=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),O=Y>=2);let J=null,ee={};const ae=i.getParameter(i.SCISSOR_BOX),_e=i.getParameter(i.VIEWPORT),Me=new gt().fromArray(ae),se=new gt().fromArray(_e);function me(W,ne,re,de){const Se=new Uint8Array(4),Ie=i.createTexture();i.bindTexture(W,Ie),i.texParameteri(W,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(W,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let st=0;st<re;st++)W===i.TEXTURE_3D||W===i.TEXTURE_2D_ARRAY?i.texImage3D(ne,0,i.RGBA,1,1,de,0,i.RGBA,i.UNSIGNED_BYTE,Se):i.texImage2D(ne+st,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,Se);return Ie}const xe={};xe[i.TEXTURE_2D]=me(i.TEXTURE_2D,i.TEXTURE_2D,1),xe[i.TEXTURE_CUBE_MAP]=me(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),xe[i.TEXTURE_2D_ARRAY]=me(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),xe[i.TEXTURE_3D]=me(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),a.setClear(1),o.setClear(0),be(i.DEPTH_TEST),a.setFunc(Xr),pt(!1),mt(Vp),be(i.CULL_FACE),H(Cs);function be(W){h[W]!==!0&&(i.enable(W),h[W]=!0)}function Ue(W){h[W]!==!1&&(i.disable(W),h[W]=!1)}function et(W,ne){return u[W]!==ne?(i.bindFramebuffer(W,ne),u[W]=ne,W===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=ne),W===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=ne),!0):!1}function He(W,ne){let re=f,de=!1;if(W){re=d.get(ne),re===void 0&&(re=[],d.set(ne,re));const Se=W.textures;if(re.length!==Se.length||re[0]!==i.COLOR_ATTACHMENT0){for(let Ie=0,st=Se.length;Ie<st;Ie++)re[Ie]=i.COLOR_ATTACHMENT0+Ie;re.length=Se.length,de=!0}}else re[0]!==i.BACK&&(re[0]=i.BACK,de=!0);de&&i.drawBuffers(re)}function Mt(W){return p!==W?(i.useProgram(W),p=W,!0):!1}const ft={[ir]:i.FUNC_ADD,[xy]:i.FUNC_SUBTRACT,[by]:i.FUNC_REVERSE_SUBTRACT};ft[Ey]=i.MIN,ft[yy]=i.MAX;const $e={[_y]:i.ZERO,[wy]:i.ONE,[vy]:i.SRC_COLOR,[Wh]:i.SRC_ALPHA,[Ty]:i.SRC_ALPHA_SATURATE,[My]:i.DST_COLOR,[Iy]:i.DST_ALPHA,[Cy]:i.ONE_MINUS_SRC_COLOR,[qh]:i.ONE_MINUS_SRC_ALPHA,[By]:i.ONE_MINUS_DST_COLOR,[Sy]:i.ONE_MINUS_DST_ALPHA,[Ry]:i.CONSTANT_COLOR,[Fy]:i.ONE_MINUS_CONSTANT_COLOR,[Ny]:i.CONSTANT_ALPHA,[Dy]:i.ONE_MINUS_CONSTANT_ALPHA};function H(W,ne,re,de,Se,Ie,st,Ht,vn,Ct){if(W===Cs){m===!0&&(Ue(i.BLEND),m=!1);return}if(m===!1&&(be(i.BLEND),m=!0),W!==my){if(W!==g||Ct!==C){if((A!==ir||E!==ir)&&(i.blendEquation(i.FUNC_ADD),A=ir,E=ir),Ct)switch(W){case jr:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case qp:i.blendFunc(i.ONE,i.ONE);break;case Kp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case jp:i.blendFuncSeparate(i.ZERO,i.SRC_COLOR,i.ZERO,i.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",W);break}else switch(W){case jr:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case qp:i.blendFunc(i.SRC_ALPHA,i.ONE);break;case Kp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case jp:i.blendFunc(i.ZERO,i.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",W);break}_=null,x=null,S=null,w=null,I.set(0,0,0),T=0,g=W,C=Ct}return}Se=Se||ne,Ie=Ie||re,st=st||de,(ne!==A||Se!==E)&&(i.blendEquationSeparate(ft[ne],ft[Se]),A=ne,E=Se),(re!==_||de!==x||Ie!==S||st!==w)&&(i.blendFuncSeparate($e[re],$e[de],$e[Ie],$e[st]),_=re,x=de,S=Ie,w=st),(Ht.equals(I)===!1||vn!==T)&&(i.blendColor(Ht.r,Ht.g,Ht.b,vn),I.copy(Ht),T=vn),g=W,C=!1}function wn(W,ne){W.side===Pi?Ue(i.CULL_FACE):be(i.CULL_FACE);let re=W.side===Ln;ne&&(re=!re),pt(re),W.blending===jr&&W.transparent===!1?H(Cs):H(W.blending,W.blendEquation,W.blendSrc,W.blendDst,W.blendEquationAlpha,W.blendSrcAlpha,W.blendDstAlpha,W.blendColor,W.blendAlpha,W.premultipliedAlpha),a.setFunc(W.depthFunc),a.setTest(W.depthTest),a.setMask(W.depthWrite),r.setMask(W.colorWrite);const de=W.stencilWrite;o.setTest(de),de&&(o.setMask(W.stencilWriteMask),o.setFunc(W.stencilFunc,W.stencilRef,W.stencilFuncMask),o.setOp(W.stencilFail,W.stencilZFail,W.stencilZPass)),Dt(W.polygonOffset,W.polygonOffsetFactor,W.polygonOffsetUnits),W.alphaToCoverage===!0?be(i.SAMPLE_ALPHA_TO_COVERAGE):Ue(i.SAMPLE_ALPHA_TO_COVERAGE)}function pt(W){v!==W&&(W?i.frontFace(i.CW):i.frontFace(i.CCW),v=W)}function mt(W){W!==py?(be(i.CULL_FACE),W!==F&&(W===Vp?i.cullFace(i.BACK):W===Ay?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ue(i.CULL_FACE),F=W}function We(W){W!==K&&(O&&i.lineWidth(W),K=W)}function Dt(W,ne,re){W?(be(i.POLYGON_OFFSET_FILL),(q!==ne||$!==re)&&(i.polygonOffset(ne,re),q=ne,$=re)):Ue(i.POLYGON_OFFSET_FILL)}function ze(W){W?be(i.SCISSOR_TEST):Ue(i.SCISSOR_TEST)}function L(W){W===void 0&&(W=i.TEXTURE0+D-1),J!==W&&(i.activeTexture(W),J=W)}function M(W,ne,re){re===void 0&&(J===null?re=i.TEXTURE0+D-1:re=J);let de=ee[re];de===void 0&&(de={type:void 0,texture:void 0},ee[re]=de),(de.type!==W||de.texture!==ne)&&(J!==re&&(i.activeTexture(re),J=re),i.bindTexture(W,ne||xe[W]),de.type=W,de.texture=ne)}function Z(){const W=ee[J];W!==void 0&&W.type!==void 0&&(i.bindTexture(W.type,null),W.type=void 0,W.texture=void 0)}function le(){try{i.compressedTexImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ae(){try{i.compressedTexImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function oe(){try{i.texSubImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Qe(){try{i.texSubImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function ve(){try{i.compressedTexSubImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function qe(){try{i.compressedTexSubImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ze(){try{i.texStorage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ee(){try{i.texStorage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function De(){try{i.texImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Oe(){try{i.texImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ge(W){Me.equals(W)===!1&&(i.scissor(W.x,W.y,W.z,W.w),Me.copy(W))}function Te(W){se.equals(W)===!1&&(i.viewport(W.x,W.y,W.z,W.w),se.copy(W))}function nt(W,ne){let re=l.get(ne);re===void 0&&(re=new WeakMap,l.set(ne,re));let de=re.get(W);de===void 0&&(de=i.getUniformBlockIndex(ne,W.name),re.set(W,de))}function Ke(W,ne){const de=l.get(ne).get(W);c.get(ne)!==de&&(i.uniformBlockBinding(ne,de,W.__bindingPointIndex),c.set(ne,de))}function it(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),a.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),h={},J=null,ee={},u={},d=new WeakMap,f=[],p=null,m=!1,g=null,A=null,_=null,x=null,E=null,S=null,w=null,I=new Fe(0,0,0),T=0,C=!1,v=null,F=null,K=null,q=null,$=null,Me.set(0,0,i.canvas.width,i.canvas.height),se.set(0,0,i.canvas.width,i.canvas.height),r.reset(),a.reset(),o.reset()}return{buffers:{color:r,depth:a,stencil:o},enable:be,disable:Ue,bindFramebuffer:et,drawBuffers:He,useProgram:Mt,setBlending:H,setMaterial:wn,setFlipSided:pt,setCullFace:mt,setLineWidth:We,setPolygonOffset:Dt,setScissorTest:ze,activeTexture:L,bindTexture:M,unbindTexture:Z,compressedTexImage2D:le,compressedTexImage3D:Ae,texImage2D:De,texImage3D:Oe,updateUBOMapping:nt,uniformBlockBinding:Ke,texStorage2D:Ze,texStorage3D:Ee,texSubImage2D:oe,texSubImage3D:Qe,compressedTexSubImage2D:ve,compressedTexSubImage3D:qe,scissor:Ge,viewport:Te,reset:it}}function JS(i,e,t,n,s,r,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Je,h=new WeakMap;let u;const d=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(L,M){return f?new OffscreenCanvas(L,M):mo("canvas")}function m(L,M,Z){let le=1;const Ae=ze(L);if((Ae.width>Z||Ae.height>Z)&&(le=Z/Math.max(Ae.width,Ae.height)),le<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const oe=Math.floor(le*Ae.width),Qe=Math.floor(le*Ae.height);u===void 0&&(u=p(oe,Qe));const ve=M?p(oe,Qe):u;return ve.width=oe,ve.height=Qe,ve.getContext("2d").drawImage(L,0,0,oe,Qe),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Ae.width+"x"+Ae.height+") to ("+oe+"x"+Qe+")."),ve}else return"data"in L&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Ae.width+"x"+Ae.height+")."),L;return L}function g(L){return L.generateMipmaps}function A(L){i.generateMipmap(L)}function _(L){return L.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?i.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function x(L,M,Z,le,Ae=!1){if(L!==null){if(i[L]!==void 0)return i[L];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let oe=M;if(M===i.RED&&(Z===i.FLOAT&&(oe=i.R32F),Z===i.HALF_FLOAT&&(oe=i.R16F),Z===i.UNSIGNED_BYTE&&(oe=i.R8)),M===i.RED_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.R8UI),Z===i.UNSIGNED_SHORT&&(oe=i.R16UI),Z===i.UNSIGNED_INT&&(oe=i.R32UI),Z===i.BYTE&&(oe=i.R8I),Z===i.SHORT&&(oe=i.R16I),Z===i.INT&&(oe=i.R32I)),M===i.RG&&(Z===i.FLOAT&&(oe=i.RG32F),Z===i.HALF_FLOAT&&(oe=i.RG16F),Z===i.UNSIGNED_BYTE&&(oe=i.RG8)),M===i.RG_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RG8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RG16UI),Z===i.UNSIGNED_INT&&(oe=i.RG32UI),Z===i.BYTE&&(oe=i.RG8I),Z===i.SHORT&&(oe=i.RG16I),Z===i.INT&&(oe=i.RG32I)),M===i.RGB_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RGB8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RGB16UI),Z===i.UNSIGNED_INT&&(oe=i.RGB32UI),Z===i.BYTE&&(oe=i.RGB8I),Z===i.SHORT&&(oe=i.RGB16I),Z===i.INT&&(oe=i.RGB32I)),M===i.RGBA_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RGBA8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RGBA16UI),Z===i.UNSIGNED_INT&&(oe=i.RGBA32UI),Z===i.BYTE&&(oe=i.RGBA8I),Z===i.SHORT&&(oe=i.RGBA16I),Z===i.INT&&(oe=i.RGBA32I)),M===i.RGB&&Z===i.UNSIGNED_INT_5_9_9_9_REV&&(oe=i.RGB9_E5),M===i.RGBA){const Qe=Ae?Hc:tt.getTransfer(le);Z===i.FLOAT&&(oe=i.RGBA32F),Z===i.HALF_FLOAT&&(oe=i.RGBA16F),Z===i.UNSIGNED_BYTE&&(oe=Qe===Rt?i.SRGB8_ALPHA8:i.RGBA8),Z===i.UNSIGNED_SHORT_4_4_4_4&&(oe=i.RGBA4),Z===i.UNSIGNED_SHORT_5_5_5_1&&(oe=i.RGB5_A1)}return(oe===i.R16F||oe===i.R32F||oe===i.RG16F||oe===i.RG32F||oe===i.RGBA16F||oe===i.RGBA32F)&&e.get("EXT_color_buffer_float"),oe}function E(L,M){let Z;return L?M===null||M===rr||M===so?Z=i.DEPTH24_STENCIL8:M===ln?Z=i.DEPTH32F_STENCIL8:M===io&&(Z=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===rr||M===so?Z=i.DEPTH_COMPONENT24:M===ln?Z=i.DEPTH_COMPONENT32F:M===io&&(Z=i.DEPTH_COMPONENT16),Z}function S(L,M){return g(L)===!0||L.isFramebufferTexture&&L.minFilter!==Pn&&L.minFilter!==qt?Math.log2(Math.max(M.width,M.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?M.mipmaps.length:1}function w(L){const M=L.target;M.removeEventListener("dispose",w),T(M),M.isVideoTexture&&h.delete(M)}function I(L){const M=L.target;M.removeEventListener("dispose",I),v(M)}function T(L){const M=n.get(L);if(M.__webglInit===void 0)return;const Z=L.source,le=d.get(Z);if(le){const Ae=le[M.__cacheKey];Ae.usedTimes--,Ae.usedTimes===0&&C(L),Object.keys(le).length===0&&d.delete(Z)}n.remove(L)}function C(L){const M=n.get(L);i.deleteTexture(M.__webglTexture);const Z=L.source,le=d.get(Z);delete le[M.__cacheKey],a.memory.textures--}function v(L){const M=n.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),n.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let le=0;le<6;le++){if(Array.isArray(M.__webglFramebuffer[le]))for(let Ae=0;Ae<M.__webglFramebuffer[le].length;Ae++)i.deleteFramebuffer(M.__webglFramebuffer[le][Ae]);else i.deleteFramebuffer(M.__webglFramebuffer[le]);M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer[le])}else{if(Array.isArray(M.__webglFramebuffer))for(let le=0;le<M.__webglFramebuffer.length;le++)i.deleteFramebuffer(M.__webglFramebuffer[le]);else i.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&i.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let le=0;le<M.__webglColorRenderbuffer.length;le++)M.__webglColorRenderbuffer[le]&&i.deleteRenderbuffer(M.__webglColorRenderbuffer[le]);M.__webglDepthRenderbuffer&&i.deleteRenderbuffer(M.__webglDepthRenderbuffer)}const Z=L.textures;for(let le=0,Ae=Z.length;le<Ae;le++){const oe=n.get(Z[le]);oe.__webglTexture&&(i.deleteTexture(oe.__webglTexture),a.memory.textures--),n.remove(Z[le])}n.remove(L)}let F=0;function K(){F=0}function q(){const L=F;return L>=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+s.maxTextures),F+=1,L}function $(L){const M=[];return M.push(L.wrapS),M.push(L.wrapT),M.push(L.wrapR||0),M.push(L.magFilter),M.push(L.minFilter),M.push(L.anisotropy),M.push(L.internalFormat),M.push(L.format),M.push(L.type),M.push(L.generateMipmaps),M.push(L.premultiplyAlpha),M.push(L.flipY),M.push(L.unpackAlignment),M.push(L.colorSpace),M.join()}function D(L,M){const Z=n.get(L);if(L.isVideoTexture&&We(L),L.isRenderTargetTexture===!1&&L.version>0&&Z.__version!==L.version){const le=L.image;if(le===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(le.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{se(Z,L,M);return}}t.bindTexture(i.TEXTURE_2D,Z.__webglTexture,i.TEXTURE0+M)}function O(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){se(Z,L,M);return}t.bindTexture(i.TEXTURE_2D_ARRAY,Z.__webglTexture,i.TEXTURE0+M)}function Y(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){se(Z,L,M);return}t.bindTexture(i.TEXTURE_3D,Z.__webglTexture,i.TEXTURE0+M)}function Q(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){me(Z,L,M);return}t.bindTexture(i.TEXTURE_CUBE_MAP,Z.__webglTexture,i.TEXTURE0+M)}const J={[Ss]:i.REPEAT,[Zn]:i.CLAMP_TO_EDGE,[Tc]:i.MIRRORED_REPEAT},ee={[Pn]:i.NEAREST,[Zp]:i.NEAREST_MIPMAP_NEAREST,[no]:i.NEAREST_MIPMAP_LINEAR,[qt]:i.LINEAR,[Rc]:i.LINEAR_MIPMAP_NEAREST,[ri]:i.LINEAR_MIPMAP_LINEAR},ae={[Xy]:i.NEVER,[t_]:i.ALWAYS,[Yy]:i.LESS,[lA]:i.LEQUAL,[Jy]:i.EQUAL,[e_]:i.GEQUAL,[Zy]:i.GREATER,[$y]:i.NOTEQUAL};function _e(L,M){if(M.type===ln&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===qt||M.magFilter===Rc||M.magFilter===no||M.magFilter===ri||M.minFilter===qt||M.minFilter===Rc||M.minFilter===no||M.minFilter===ri)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(L,i.TEXTURE_WRAP_S,J[M.wrapS]),i.texParameteri(L,i.TEXTURE_WRAP_T,J[M.wrapT]),(L===i.TEXTURE_3D||L===i.TEXTURE_2D_ARRAY)&&i.texParameteri(L,i.TEXTURE_WRAP_R,J[M.wrapR]),i.texParameteri(L,i.TEXTURE_MAG_FILTER,ee[M.magFilter]),i.texParameteri(L,i.TEXTURE_MIN_FILTER,ee[M.minFilter]),M.compareFunction&&(i.texParameteri(L,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(L,i.TEXTURE_COMPARE_FUNC,ae[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Pn||M.minFilter!==no&&M.minFilter!==ri||M.type===ln&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||n.get(M).__currentAnisotropy){const Z=e.get("EXT_texture_filter_anisotropic");i.texParameterf(L,Z.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,s.getMaxAnisotropy())),n.get(M).__currentAnisotropy=M.anisotropy}}}function Me(L,M){let Z=!1;L.__webglInit===void 0&&(L.__webglInit=!0,M.addEventListener("dispose",w));const le=M.source;let Ae=d.get(le);Ae===void 0&&(Ae={},d.set(le,Ae));const oe=$(M);if(oe!==L.__cacheKey){Ae[oe]===void 0&&(Ae[oe]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,Z=!0),Ae[oe].usedTimes++;const Qe=Ae[L.__cacheKey];Qe!==void 0&&(Ae[L.__cacheKey].usedTimes--,Qe.usedTimes===0&&C(M)),L.__cacheKey=oe,L.__webglTexture=Ae[oe].texture}return Z}function se(L,M,Z){let le=i.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(le=i.TEXTURE_2D_ARRAY),M.isData3DTexture&&(le=i.TEXTURE_3D);const Ae=Me(L,M),oe=M.source;t.bindTexture(le,L.__webglTexture,i.TEXTURE0+Z);const Qe=n.get(oe);if(oe.version!==Qe.__version||Ae===!0){t.activeTexture(i.TEXTURE0+Z);const ve=tt.getPrimaries(tt.workingColorSpace),qe=M.colorSpace===mi?null:tt.getPrimaries(M.colorSpace),Ze=M.colorSpace===mi||ve===qe?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ze);let Ee=m(M.image,!1,s.maxTextureSize);Ee=Dt(M,Ee);const De=r.convert(M.format,M.colorSpace),Oe=r.convert(M.type);let Ge=x(M.internalFormat,De,Oe,M.colorSpace,M.isVideoTexture);_e(le,M);let Te;const nt=M.mipmaps,Ke=M.isVideoTexture!==!0,it=Qe.__version===void 0||Ae===!0,W=oe.dataReady,ne=S(M,Ee);if(M.isDepthTexture)Ge=E(M.format===ao,M.type),it&&(Ke?t.texStorage2D(i.TEXTURE_2D,1,Ge,Ee.width,Ee.height):t.texImage2D(i.TEXTURE_2D,0,Ge,Ee.width,Ee.height,0,De,Oe,null));else if(M.isDataTexture)if(nt.length>0){Ke&&it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,nt[0].width,nt[0].height);for(let re=0,de=nt.length;re<de;re++)Te=nt[re],Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Oe,Te.data):t.texImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,De,Oe,Te.data);M.generateMipmaps=!1}else Ke?(it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,Ee.width,Ee.height),W&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,Ee.width,Ee.height,De,Oe,Ee.data)):t.texImage2D(i.TEXTURE_2D,0,Ge,Ee.width,Ee.height,0,De,Oe,Ee.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){Ke&&it&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ne,Ge,nt[0].width,nt[0].height,Ee.depth);for(let re=0,de=nt.length;re<de;re++)if(Te=nt[re],M.format!==hn)if(De!==null)if(Ke){if(W)if(M.layerUpdates.size>0){const Se=vg(Te.width,Te.height,M.format,M.type);for(const Ie of M.layerUpdates){const st=Te.data.subarray(Ie*Se/Te.data.BYTES_PER_ELEMENT,(Ie+1)*Se/Te.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,Ie,Te.width,Te.height,1,De,st)}M.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,0,Te.width,Te.height,Ee.depth,De,Te.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,re,Ge,Te.width,Te.height,Ee.depth,0,Te.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Ke?W&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,0,Te.width,Te.height,Ee.depth,De,Oe,Te.data):t.texImage3D(i.TEXTURE_2D_ARRAY,re,Ge,Te.width,Te.height,Ee.depth,0,De,Oe,Te.data)}else{Ke&&it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,nt[0].width,nt[0].height);for(let re=0,de=nt.length;re<de;re++)Te=nt[re],M.format!==hn?De!==null?Ke?W&&t.compressedTexSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Te.data):t.compressedTexImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,Te.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Oe,Te.data):t.texImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,De,Oe,Te.data)}else if(M.isDataArrayTexture)if(Ke){if(it&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ne,Ge,Ee.width,Ee.height,Ee.depth),W)if(M.layerUpdates.size>0){const re=vg(Ee.width,Ee.height,M.format,M.type);for(const de of M.layerUpdates){const Se=Ee.data.subarray(de*re/Ee.data.BYTES_PER_ELEMENT,(de+1)*re/Ee.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,de,Ee.width,Ee.height,1,De,Oe,Se)}M.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,Ee.width,Ee.height,Ee.depth,De,Oe,Ee.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Ge,Ee.width,Ee.height,Ee.depth,0,De,Oe,Ee.data);else if(M.isData3DTexture)Ke?(it&&t.texStorage3D(i.TEXTURE_3D,ne,Ge,Ee.width,Ee.height,Ee.depth),W&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,Ee.width,Ee.height,Ee.depth,De,Oe,Ee.data)):t.texImage3D(i.TEXTURE_3D,0,Ge,Ee.width,Ee.height,Ee.depth,0,De,Oe,Ee.data);else if(M.isFramebufferTexture){if(it)if(Ke)t.texStorage2D(i.TEXTURE_2D,ne,Ge,Ee.width,Ee.height);else{let re=Ee.width,de=Ee.height;for(let Se=0;Se<ne;Se++)t.texImage2D(i.TEXTURE_2D,Se,Ge,re,de,0,De,Oe,null),re>>=1,de>>=1}}else if(nt.length>0){if(Ke&&it){const re=ze(nt[0]);t.texStorage2D(i.TEXTURE_2D,ne,Ge,re.width,re.height)}for(let re=0,de=nt.length;re<de;re++)Te=nt[re],Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,De,Oe,Te):t.texImage2D(i.TEXTURE_2D,re,Ge,De,Oe,Te);M.generateMipmaps=!1}else if(Ke){if(it){const re=ze(Ee);t.texStorage2D(i.TEXTURE_2D,ne,Ge,re.width,re.height)}W&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,De,Oe,Ee)}else t.texImage2D(i.TEXTURE_2D,0,Ge,De,Oe,Ee);g(M)&&A(le),Qe.__version=oe.version,M.onUpdate&&M.onUpdate(M)}L.__version=M.version}function me(L,M,Z){if(M.image.length!==6)return;const le=Me(L,M),Ae=M.source;t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+Z);const oe=n.get(Ae);if(Ae.version!==oe.__version||le===!0){t.activeTexture(i.TEXTURE0+Z);const Qe=tt.getPrimaries(tt.workingColorSpace),ve=M.colorSpace===mi?null:tt.getPrimaries(M.colorSpace),qe=M.colorSpace===mi||Qe===ve?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,qe);const Ze=M.isCompressedTexture||M.image[0].isCompressedTexture,Ee=M.image[0]&&M.image[0].isDataTexture,De=[];for(let de=0;de<6;de++)!Ze&&!Ee?De[de]=m(M.image[de],!0,s.maxCubemapSize):De[de]=Ee?M.image[de].image:M.image[de],De[de]=Dt(M,De[de]);const Oe=De[0],Ge=r.convert(M.format,M.colorSpace),Te=r.convert(M.type),nt=x(M.internalFormat,Ge,Te,M.colorSpace),Ke=M.isVideoTexture!==!0,it=oe.__version===void 0||le===!0,W=Ae.dataReady;let ne=S(M,Oe);_e(i.TEXTURE_CUBE_MAP,M);let re;if(Ze){Ke&&it&&t.texStorage2D(i.TEXTURE_CUBE_MAP,ne,nt,Oe.width,Oe.height);for(let de=0;de<6;de++){re=De[de].mipmaps;for(let Se=0;Se<re.length;Se++){const Ie=re[Se];M.format!==hn?Ge!==null?Ke?W&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,0,0,Ie.width,Ie.height,Ge,Ie.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,nt,Ie.width,Ie.height,0,Ie.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,0,0,Ie.width,Ie.height,Ge,Te,Ie.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,nt,Ie.width,Ie.height,0,Ge,Te,Ie.data)}}}else{if(re=M.mipmaps,Ke&&it){re.length>0&&ne++;const de=ze(De[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,ne,nt,de.width,de.height)}for(let de=0;de<6;de++)if(Ee){Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,0,0,De[de].width,De[de].height,Ge,Te,De[de].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,nt,De[de].width,De[de].height,0,Ge,Te,De[de].data);for(let Se=0;Se<re.length;Se++){const st=re[Se].image[de].image;Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,0,0,st.width,st.height,Ge,Te,st.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,nt,st.width,st.height,0,Ge,Te,st.data)}}else{Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,0,0,Ge,Te,De[de]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,nt,Ge,Te,De[de]);for(let Se=0;Se<re.length;Se++){const Ie=re[Se];Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,0,0,Ge,Te,Ie.image[de]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,nt,Ge,Te,Ie.image[de])}}}g(M)&&A(i.TEXTURE_CUBE_MAP),oe.__version=Ae.version,M.onUpdate&&M.onUpdate(M)}L.__version=M.version}function xe(L,M,Z,le,Ae,oe){const Qe=r.convert(Z.format,Z.colorSpace),ve=r.convert(Z.type),qe=x(Z.internalFormat,Qe,ve,Z.colorSpace),Ze=n.get(M),Ee=n.get(Z);if(Ee.__renderTarget=M,!Ze.__hasExternalTextures){const De=Math.max(1,M.width>>oe),Oe=Math.max(1,M.height>>oe);Ae===i.TEXTURE_3D||Ae===i.TEXTURE_2D_ARRAY?t.texImage3D(Ae,oe,qe,De,Oe,M.depth,0,Qe,ve,null):t.texImage2D(Ae,oe,qe,De,Oe,0,Qe,ve,null)}t.bindFramebuffer(i.FRAMEBUFFER,L),mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,le,Ae,Ee.__webglTexture,0,pt(M)):(Ae===i.TEXTURE_2D||Ae>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&Ae<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,le,Ae,Ee.__webglTexture,oe),t.bindFramebuffer(i.FRAMEBUFFER,null)}function be(L,M,Z){if(i.bindRenderbuffer(i.RENDERBUFFER,L),M.depthBuffer){const le=M.depthTexture,Ae=le&&le.isDepthTexture?le.type:null,oe=E(M.stencilBuffer,Ae),Qe=M.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ve=pt(M);mt(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,ve,oe,M.width,M.height):Z?i.renderbufferStorageMultisample(i.RENDERBUFFER,ve,oe,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,oe,M.width,M.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Qe,i.RENDERBUFFER,L)}else{const le=M.textures;for(let Ae=0;Ae<le.length;Ae++){const oe=le[Ae],Qe=r.convert(oe.format,oe.colorSpace),ve=r.convert(oe.type),qe=x(oe.internalFormat,Qe,ve,oe.colorSpace),Ze=pt(M);Z&&mt(M)===!1?i.renderbufferStorageMultisample(i.RENDERBUFFER,Ze,qe,M.width,M.height):mt(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,Ze,qe,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,qe,M.width,M.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ue(L,M){if(M&&M.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(i.FRAMEBUFFER,L),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const le=n.get(M.depthTexture);le.__renderTarget=M,(!le.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),D(M.depthTexture,0);const Ae=le.__webglTexture,oe=pt(M);if(M.depthTexture.format===ro)mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,Ae,0,oe):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,Ae,0);else if(M.depthTexture.format===ao)mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,Ae,0,oe):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,Ae,0);else throw new Error("Unknown depthTexture format")}function et(L){const M=n.get(L),Z=L.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==L.depthTexture){const le=L.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),le){const Ae=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,le.removeEventListener("dispose",Ae)};le.addEventListener("dispose",Ae),M.__depthDisposeCallback=Ae}M.__boundDepthTexture=le}if(L.depthTexture&&!M.__autoAllocateDepthBuffer){if(Z)throw new Error("target.depthTexture not supported in Cube render targets");const le=L.texture.mipmaps;le&&le.length>0?Ue(M.__webglFramebuffer[0],L):Ue(M.__webglFramebuffer,L)}else if(Z){M.__webglDepthbuffer=[];for(let le=0;le<6;le++)if(t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[le]),M.__webglDepthbuffer[le]===void 0)M.__webglDepthbuffer[le]=i.createRenderbuffer(),be(M.__webglDepthbuffer[le],L,!1);else{const Ae=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,oe=M.__webglDepthbuffer[le];i.bindRenderbuffer(i.RENDERBUFFER,oe),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ae,i.RENDERBUFFER,oe)}}else{const le=L.texture.mipmaps;if(le&&le.length>0?t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=i.createRenderbuffer(),be(M.__webglDepthbuffer,L,!1);else{const Ae=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,oe=M.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,oe),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ae,i.RENDERBUFFER,oe)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function He(L,M,Z){const le=n.get(L);M!==void 0&&xe(le.__webglFramebuffer,L,L.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),Z!==void 0&&et(L)}function Mt(L){const M=L.texture,Z=n.get(L),le=n.get(M);L.addEventListener("dispose",I);const Ae=L.textures,oe=L.isWebGLCubeRenderTarget===!0,Qe=Ae.length>1;if(Qe||(le.__webglTexture===void 0&&(le.__webglTexture=i.createTexture()),le.__version=M.version,a.memory.textures++),oe){Z.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer[ve]=[];for(let qe=0;qe<M.mipmaps.length;qe++)Z.__webglFramebuffer[ve][qe]=i.createFramebuffer()}else Z.__webglFramebuffer[ve]=i.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer=[];for(let ve=0;ve<M.mipmaps.length;ve++)Z.__webglFramebuffer[ve]=i.createFramebuffer()}else Z.__webglFramebuffer=i.createFramebuffer();if(Qe)for(let ve=0,qe=Ae.length;ve<qe;ve++){const Ze=n.get(Ae[ve]);Ze.__webglTexture===void 0&&(Ze.__webglTexture=i.createTexture(),a.memory.textures++)}if(L.samples>0&&mt(L)===!1){Z.__webglMultisampledFramebuffer=i.createFramebuffer(),Z.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,Z.__webglMultisampledFramebuffer);for(let ve=0;ve<Ae.length;ve++){const qe=Ae[ve];Z.__webglColorRenderbuffer[ve]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,Z.__webglColorRenderbuffer[ve]);const Ze=r.convert(qe.format,qe.colorSpace),Ee=r.convert(qe.type),De=x(qe.internalFormat,Ze,Ee,qe.colorSpace,L.isXRRenderTarget===!0),Oe=pt(L);i.renderbufferStorageMultisample(i.RENDERBUFFER,Oe,De,L.width,L.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+ve,i.RENDERBUFFER,Z.__webglColorRenderbuffer[ve])}i.bindRenderbuffer(i.RENDERBUFFER,null),L.depthBuffer&&(Z.__webglDepthRenderbuffer=i.createRenderbuffer(),be(Z.__webglDepthRenderbuffer,L,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(oe){t.bindTexture(i.TEXTURE_CUBE_MAP,le.__webglTexture),_e(i.TEXTURE_CUBE_MAP,M);for(let ve=0;ve<6;ve++)if(M.mipmaps&&M.mipmaps.length>0)for(let qe=0;qe<M.mipmaps.length;qe++)xe(Z.__webglFramebuffer[ve][qe],L,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ve,qe);else xe(Z.__webglFramebuffer[ve],L,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);g(M)&&A(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Qe){for(let ve=0,qe=Ae.length;ve<qe;ve++){const Ze=Ae[ve],Ee=n.get(Ze);t.bindTexture(i.TEXTURE_2D,Ee.__webglTexture),_e(i.TEXTURE_2D,Ze),xe(Z.__webglFramebuffer,L,Ze,i.COLOR_ATTACHMENT0+ve,i.TEXTURE_2D,0),g(Ze)&&A(i.TEXTURE_2D)}t.unbindTexture()}else{let ve=i.TEXTURE_2D;if((L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(ve=L.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ve,le.__webglTexture),_e(ve,M),M.mipmaps&&M.mipmaps.length>0)for(let qe=0;qe<M.mipmaps.length;qe++)xe(Z.__webglFramebuffer[qe],L,M,i.COLOR_ATTACHMENT0,ve,qe);else xe(Z.__webglFramebuffer,L,M,i.COLOR_ATTACHMENT0,ve,0);g(M)&&A(ve),t.unbindTexture()}L.depthBuffer&&et(L)}function ft(L){const M=L.textures;for(let Z=0,le=M.length;Z<le;Z++){const Ae=M[Z];if(g(Ae)){const oe=_(L),Qe=n.get(Ae).__webglTexture;t.bindTexture(oe,Qe),A(oe),t.unbindTexture()}}}const $e=[],H=[];function wn(L){if(L.samples>0){if(mt(L)===!1){const M=L.textures,Z=L.width,le=L.height;let Ae=i.COLOR_BUFFER_BIT;const oe=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Qe=n.get(L),ve=M.length>1;if(ve)for(let Ze=0;Ze<M.length;Ze++)t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer);const qe=L.texture.mipmaps;qe&&qe.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer);for(let Ze=0;Ze<M.length;Ze++){if(L.resolveDepthBuffer&&(L.depthBuffer&&(Ae|=i.DEPTH_BUFFER_BIT),L.stencilBuffer&&L.resolveStencilBuffer&&(Ae|=i.STENCIL_BUFFER_BIT)),ve){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Qe.__webglColorRenderbuffer[Ze]);const Ee=n.get(M[Ze]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,Ee,0)}i.blitFramebuffer(0,0,Z,le,0,0,Z,le,Ae,i.NEAREST),c===!0&&($e.length=0,H.length=0,$e.push(i.COLOR_ATTACHMENT0+Ze),L.depthBuffer&&L.resolveDepthBuffer===!1&&($e.push(oe),H.push(oe),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,H)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,$e))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),ve)for(let Ze=0;Ze<M.length;Ze++){t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.RENDERBUFFER,Qe.__webglColorRenderbuffer[Ze]);const Ee=n.get(M[Ze]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.TEXTURE_2D,Ee,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer)}else if(L.depthBuffer&&L.resolveDepthBuffer===!1&&c){const M=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[M])}}}function pt(L){return Math.min(s.maxSamples,L.samples)}function mt(L){const M=n.get(L);return L.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function We(L){const M=a.render.frame;h.get(L)!==M&&(h.set(L,M),L.update())}function Dt(L,M){const Z=L.colorSpace,le=L.format,Ae=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||Z!==un&&Z!==mi&&(tt.getTransfer(Z)===Rt?(le!==hn||Ae!==cn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",Z)),M}function ze(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(l.width=L.naturalWidth||L.width,l.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(l.width=L.displayWidth,l.height=L.displayHeight):(l.width=L.width,l.height=L.height),l}this.allocateTextureUnit=q,this.resetTextureUnits=K,this.setTexture2D=D,this.setTexture2DArray=O,this.setTexture3D=Y,this.setTextureCube=Q,this.rebindTextures=He,this.setupRenderTarget=Mt,this.updateRenderTargetMipmap=ft,this.updateMultisampleRenderTarget=wn,this.setupDepthRenderbuffer=et,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=mt}function ZS(i,e){function t(n,s=mi){let r;const a=tt.getTransfer(s);if(n===cn)return i.UNSIGNED_BYTE;if(n===iu)return i.UNSIGNED_SHORT_4_4_4_4;if(n===su)return i.UNSIGNED_SHORT_5_5_5_1;if(n===tA)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===$p)return i.BYTE;if(n===eA)return i.SHORT;if(n===io)return i.UNSIGNED_SHORT;if(n===nu)return i.INT;if(n===rr)return i.UNSIGNED_INT;if(n===ln)return i.FLOAT;if(n===kn)return i.HALF_FLOAT;if(n===nA)return i.ALPHA;if(n===iA)return i.RGB;if(n===hn)return i.RGBA;if(n===ro)return i.DEPTH_COMPONENT;if(n===ao)return i.DEPTH_STENCIL;if(n===Xi)return i.RED;if(n===ru)return i.RED_INTEGER;if(n===ar)return i.RG;if(n===au)return i.RG_INTEGER;if(n===ou)return i.RGBA_INTEGER;if(n===Fc||n===oo||n===Nc||n===co)if(a===Rt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Fc)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===oo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Nc)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===co)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Fc)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===oo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Nc)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===co)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Dc||n===cu||n===Lc||n===lu)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Dc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===cu)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Lc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===lu)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Pc||n===kc||n===Uc)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===Pc||n===kc)return a===Rt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Uc)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===lo||n===hu||n===uu||n===du||n===ho||n===fu||n===pu||n===Au||n===gu||n===mu||n===xu||n===bu||n===Eu||n===yu)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===lo)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===hu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===uu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===du)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ho)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===fu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===pu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Au)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===gu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===mu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===xu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===bu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Eu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===yu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===uo||n===_u||n===Oc)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===uo)return a===Rt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===_u)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Oc)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===sA||n===wu||n===vu||n===Cu)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===uo)return r.COMPRESSED_RED_RGTC1_EXT;if(n===wu)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===vu)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Cu)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===so?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const $S=`
+}`;function KS(i,e,t){let n=new rd;const s=new Je,r=new Je,a=new gt,o=new ww({depthPacking:qy}),c=new vw,l={},h=t.maxTextureSize,u={[ji]:Ln,[Ln]:ji,[Pi]:Pi},d=new Ls({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Je},radius:{value:4}},vertexShader:WS,fragmentShader:qS}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new Mn;p.setAttribute("position",new Sn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Zt(p,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Wp;let A=this.type;this.render=function(w,I,T){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||w.length===0)return;const C=i.getRenderTarget(),v=i.getActiveCubeFace(),F=i.getActiveMipmapLevel(),K=i.state;K.setBlending(Cs),K.buffers.color.setClear(1,1,1,1),K.buffers.depth.setTest(!0),K.setScissorTest(!1);const q=A!==Ki&&this.type===Ki,$=A===Ki&&this.type!==Ki;for(let D=0,O=w.length;D<O;D++){const Y=w[D],Q=Y.shadow;if(Q===void 0){console.warn("THREE.WebGLShadowMap:",Y,"has no shadow.");continue}if(Q.autoUpdate===!1&&Q.needsUpdate===!1)continue;s.copy(Q.mapSize);const J=Q.getFrameExtents();if(s.multiply(J),r.copy(Q.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/J.x),s.x=r.x*J.x,Q.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/J.y),s.y=r.y*J.y,Q.mapSize.y=r.y)),Q.map===null||q===!0||$===!0){const ae=this.type!==Ki?{minFilter:Pn,magFilter:Pn}:{};Q.map!==null&&Q.map.dispose(),Q.map=new or(s.x,s.y,ae),Q.map.texture.name=Y.name+".shadowMap",Q.camera.updateProjectionMatrix()}i.setRenderTarget(Q.map),i.clear();const ee=Q.getViewportCount();for(let ae=0;ae<ee;ae++){const _e=Q.getViewport(ae);a.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),K.viewport(a),Q.updateMatrices(Y,ae),n=Q.getFrustum(),E(I,T,Q.camera,Y,this.type)}Q.isPointLightShadow!==!0&&this.type===Ki&&_(Q,T),Q.needsUpdate=!1}A=this.type,g.needsUpdate=!1,i.setRenderTarget(C,v,F)};function _(w,I){const T=e.update(m);d.defines.VSM_SAMPLES!==w.blurSamples&&(d.defines.VSM_SAMPLES=w.blurSamples,f.defines.VSM_SAMPLES=w.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),w.mapPass===null&&(w.mapPass=new or(s.x,s.y)),d.uniforms.shadow_pass.value=w.map.texture,d.uniforms.resolution.value=w.mapSize,d.uniforms.radius.value=w.radius,i.setRenderTarget(w.mapPass),i.clear(),i.renderBufferDirect(I,null,T,d,m,null),f.uniforms.shadow_pass.value=w.mapPass.texture,f.uniforms.resolution.value=w.mapSize,f.uniforms.radius.value=w.radius,i.setRenderTarget(w.map),i.clear(),i.renderBufferDirect(I,null,T,f,m,null)}function x(w,I,T,C){let v=null;const F=T.isPointLight===!0?w.customDistanceMaterial:w.customDepthMaterial;if(F!==void 0)v=F;else if(v=T.isPointLight===!0?c:o,i.localClippingEnabled&&I.clipShadows===!0&&Array.isArray(I.clippingPlanes)&&I.clippingPlanes.length!==0||I.displacementMap&&I.displacementScale!==0||I.alphaMap&&I.alphaTest>0||I.map&&I.alphaTest>0||I.alphaToCoverage===!0){const K=v.uuid,q=I.uuid;let $=l[K];$===void 0&&($={},l[K]=$);let D=$[q];D===void 0&&(D=v.clone(),$[q]=D,I.addEventListener("dispose",S)),v=D}if(v.visible=I.visible,v.wireframe=I.wireframe,C===Ki?v.side=I.shadowSide!==null?I.shadowSide:I.side:v.side=I.shadowSide!==null?I.shadowSide:u[I.side],v.alphaMap=I.alphaMap,v.alphaTest=I.alphaToCoverage===!0?.5:I.alphaTest,v.map=I.map,v.clipShadows=I.clipShadows,v.clippingPlanes=I.clippingPlanes,v.clipIntersection=I.clipIntersection,v.displacementMap=I.displacementMap,v.displacementScale=I.displacementScale,v.displacementBias=I.displacementBias,v.wireframeLinewidth=I.wireframeLinewidth,v.linewidth=I.linewidth,T.isPointLight===!0&&v.isMeshDistanceMaterial===!0){const K=i.properties.get(v);K.light=T}return v}function E(w,I,T,C,v){if(w.visible===!1)return;if(w.layers.test(I.layers)&&(w.isMesh||w.isLine||w.isPoints)&&(w.castShadow||w.receiveShadow&&v===Ki)&&(!w.frustumCulled||n.intersectsObject(w))){w.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,w.matrixWorld);const q=e.update(w),$=w.material;if(Array.isArray($)){const D=q.groups;for(let O=0,Y=D.length;O<Y;O++){const Q=D[O],J=$[Q.materialIndex];if(J&&J.visible){const ee=x(w,J,C,v);w.onBeforeShadow(i,w,I,T,q,ee,Q),i.renderBufferDirect(T,null,q,ee,w,Q),w.onAfterShadow(i,w,I,T,q,ee,Q)}}}else if($.visible){const D=x(w,$,C,v);w.onBeforeShadow(i,w,I,T,q,D,null),i.renderBufferDirect(T,null,q,D,w,null),w.onAfterShadow(i,w,I,T,q,D,null)}}const K=w.children;for(let q=0,$=K.length;q<$;q++)E(K[q],I,T,C,v)}function S(w){w.target.removeEventListener("dispose",S);for(const T in l){const C=l[T],v=w.target.uuid;v in C&&(C[v].dispose(),delete C[v])}}}const jS={[Kh]:jh,[Xh]:Zh,[Yh]:$h,[Xr]:Jh,[jh]:Kh,[Zh]:Xh,[$h]:Yh,[Jh]:Xr};function XS(i,e){function t(){let W=!1;const ne=new gt;let re=null;const de=new gt(0,0,0,0);return{setMask:function(Se){re!==Se&&!W&&(i.colorMask(Se,Se,Se,Se),re=Se)},setLocked:function(Se){W=Se},setClear:function(Se,Ie,st,Ht,vn){vn===!0&&(Se*=Ht,Ie*=Ht,st*=Ht),ne.set(Se,Ie,st,Ht),de.equals(ne)===!1&&(i.clearColor(Se,Ie,st,Ht),de.copy(ne))},reset:function(){W=!1,re=null,de.set(-1,0,0,0)}}}function n(){let W=!1,ne=!1,re=null,de=null,Se=null;return{setReversed:function(Ie){if(ne!==Ie){const st=e.get("EXT_clip_control");Ie?st.clipControlEXT(st.LOWER_LEFT_EXT,st.ZERO_TO_ONE_EXT):st.clipControlEXT(st.LOWER_LEFT_EXT,st.NEGATIVE_ONE_TO_ONE_EXT),ne=Ie;const Ht=Se;Se=null,this.setClear(Ht)}},getReversed:function(){return ne},setTest:function(Ie){Ie?be(i.DEPTH_TEST):Ue(i.DEPTH_TEST)},setMask:function(Ie){re!==Ie&&!W&&(i.depthMask(Ie),re=Ie)},setFunc:function(Ie){if(ne&&(Ie=jS[Ie]),de!==Ie){switch(Ie){case Kh:i.depthFunc(i.NEVER);break;case jh:i.depthFunc(i.ALWAYS);break;case Xh:i.depthFunc(i.LESS);break;case Xr:i.depthFunc(i.LEQUAL);break;case Yh:i.depthFunc(i.EQUAL);break;case Jh:i.depthFunc(i.GEQUAL);break;case Zh:i.depthFunc(i.GREATER);break;case $h:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}de=Ie}},setLocked:function(Ie){W=Ie},setClear:function(Ie){Se!==Ie&&(ne&&(Ie=1-Ie),i.clearDepth(Ie),Se=Ie)},reset:function(){W=!1,re=null,de=null,Se=null,ne=!1}}}function s(){let W=!1,ne=null,re=null,de=null,Se=null,Ie=null,st=null,Ht=null,vn=null;return{setTest:function(Ct){W||(Ct?be(i.STENCIL_TEST):Ue(i.STENCIL_TEST))},setMask:function(Ct){ne!==Ct&&!W&&(i.stencilMask(Ct),ne=Ct)},setFunc:function(Ct,si,Li){(re!==Ct||de!==si||Se!==Li)&&(i.stencilFunc(Ct,si,Li),re=Ct,de=si,Se=Li)},setOp:function(Ct,si,Li){(Ie!==Ct||st!==si||Ht!==Li)&&(i.stencilOp(Ct,si,Li),Ie=Ct,st=si,Ht=Li)},setLocked:function(Ct){W=Ct},setClear:function(Ct){vn!==Ct&&(i.clearStencil(Ct),vn=Ct)},reset:function(){W=!1,ne=null,re=null,de=null,Se=null,Ie=null,st=null,Ht=null,vn=null}}}const r=new t,a=new n,o=new s,c=new WeakMap,l=new WeakMap;let h={},u={},d=new WeakMap,f=[],p=null,m=!1,g=null,A=null,_=null,x=null,E=null,S=null,w=null,I=new Fe(0,0,0),T=0,C=!1,v=null,F=null,K=null,q=null,$=null;const D=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let O=!1,Y=0;const Q=i.getParameter(i.VERSION);Q.indexOf("WebGL")!==-1?(Y=parseFloat(/^WebGL (\d)/.exec(Q)[1]),O=Y>=1):Q.indexOf("OpenGL ES")!==-1&&(Y=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),O=Y>=2);let J=null,ee={};const ae=i.getParameter(i.SCISSOR_BOX),_e=i.getParameter(i.VIEWPORT),Me=new gt().fromArray(ae),se=new gt().fromArray(_e);function me(W,ne,re,de){const Se=new Uint8Array(4),Ie=i.createTexture();i.bindTexture(W,Ie),i.texParameteri(W,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(W,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let st=0;st<re;st++)W===i.TEXTURE_3D||W===i.TEXTURE_2D_ARRAY?i.texImage3D(ne,0,i.RGBA,1,1,de,0,i.RGBA,i.UNSIGNED_BYTE,Se):i.texImage2D(ne+st,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,Se);return Ie}const xe={};xe[i.TEXTURE_2D]=me(i.TEXTURE_2D,i.TEXTURE_2D,1),xe[i.TEXTURE_CUBE_MAP]=me(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),xe[i.TEXTURE_2D_ARRAY]=me(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),xe[i.TEXTURE_3D]=me(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),a.setClear(1),o.setClear(0),be(i.DEPTH_TEST),a.setFunc(Xr),pt(!1),mt(Vp),be(i.CULL_FACE),H(Cs);function be(W){h[W]!==!0&&(i.enable(W),h[W]=!0)}function Ue(W){h[W]!==!1&&(i.disable(W),h[W]=!1)}function et(W,ne){return u[W]!==ne?(i.bindFramebuffer(W,ne),u[W]=ne,W===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=ne),W===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=ne),!0):!1}function He(W,ne){let re=f,de=!1;if(W){re=d.get(ne),re===void 0&&(re=[],d.set(ne,re));const Se=W.textures;if(re.length!==Se.length||re[0]!==i.COLOR_ATTACHMENT0){for(let Ie=0,st=Se.length;Ie<st;Ie++)re[Ie]=i.COLOR_ATTACHMENT0+Ie;re.length=Se.length,de=!0}}else re[0]!==i.BACK&&(re[0]=i.BACK,de=!0);de&&i.drawBuffers(re)}function Mt(W){return p!==W?(i.useProgram(W),p=W,!0):!1}const ft={[ir]:i.FUNC_ADD,[my]:i.FUNC_SUBTRACT,[xy]:i.FUNC_REVERSE_SUBTRACT};ft[by]=i.MIN,ft[Ey]=i.MAX;const $e={[yy]:i.ZERO,[_y]:i.ONE,[wy]:i.SRC_COLOR,[Wh]:i.SRC_ALPHA,[By]:i.SRC_ALPHA_SATURATE,[Sy]:i.DST_COLOR,[Cy]:i.DST_ALPHA,[vy]:i.ONE_MINUS_SRC_COLOR,[qh]:i.ONE_MINUS_SRC_ALPHA,[My]:i.ONE_MINUS_DST_COLOR,[Iy]:i.ONE_MINUS_DST_ALPHA,[Ty]:i.CONSTANT_COLOR,[Ry]:i.ONE_MINUS_CONSTANT_COLOR,[Fy]:i.CONSTANT_ALPHA,[Ny]:i.ONE_MINUS_CONSTANT_ALPHA};function H(W,ne,re,de,Se,Ie,st,Ht,vn,Ct){if(W===Cs){m===!0&&(Ue(i.BLEND),m=!1);return}if(m===!1&&(be(i.BLEND),m=!0),W!==gy){if(W!==g||Ct!==C){if((A!==ir||E!==ir)&&(i.blendEquation(i.FUNC_ADD),A=ir,E=ir),Ct)switch(W){case jr:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case qp:i.blendFunc(i.ONE,i.ONE);break;case Kp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case jp:i.blendFuncSeparate(i.ZERO,i.SRC_COLOR,i.ZERO,i.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",W);break}else switch(W){case jr:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case qp:i.blendFunc(i.SRC_ALPHA,i.ONE);break;case Kp:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case jp:i.blendFunc(i.ZERO,i.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",W);break}_=null,x=null,S=null,w=null,I.set(0,0,0),T=0,g=W,C=Ct}return}Se=Se||ne,Ie=Ie||re,st=st||de,(ne!==A||Se!==E)&&(i.blendEquationSeparate(ft[ne],ft[Se]),A=ne,E=Se),(re!==_||de!==x||Ie!==S||st!==w)&&(i.blendFuncSeparate($e[re],$e[de],$e[Ie],$e[st]),_=re,x=de,S=Ie,w=st),(Ht.equals(I)===!1||vn!==T)&&(i.blendColor(Ht.r,Ht.g,Ht.b,vn),I.copy(Ht),T=vn),g=W,C=!1}function wn(W,ne){W.side===Pi?Ue(i.CULL_FACE):be(i.CULL_FACE);let re=W.side===Ln;ne&&(re=!re),pt(re),W.blending===jr&&W.transparent===!1?H(Cs):H(W.blending,W.blendEquation,W.blendSrc,W.blendDst,W.blendEquationAlpha,W.blendSrcAlpha,W.blendDstAlpha,W.blendColor,W.blendAlpha,W.premultipliedAlpha),a.setFunc(W.depthFunc),a.setTest(W.depthTest),a.setMask(W.depthWrite),r.setMask(W.colorWrite);const de=W.stencilWrite;o.setTest(de),de&&(o.setMask(W.stencilWriteMask),o.setFunc(W.stencilFunc,W.stencilRef,W.stencilFuncMask),o.setOp(W.stencilFail,W.stencilZFail,W.stencilZPass)),Dt(W.polygonOffset,W.polygonOffsetFactor,W.polygonOffsetUnits),W.alphaToCoverage===!0?be(i.SAMPLE_ALPHA_TO_COVERAGE):Ue(i.SAMPLE_ALPHA_TO_COVERAGE)}function pt(W){v!==W&&(W?i.frontFace(i.CW):i.frontFace(i.CCW),v=W)}function mt(W){W!==fy?(be(i.CULL_FACE),W!==F&&(W===Vp?i.cullFace(i.BACK):W===py?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ue(i.CULL_FACE),F=W}function We(W){W!==K&&(O&&i.lineWidth(W),K=W)}function Dt(W,ne,re){W?(be(i.POLYGON_OFFSET_FILL),(q!==ne||$!==re)&&(i.polygonOffset(ne,re),q=ne,$=re)):Ue(i.POLYGON_OFFSET_FILL)}function ze(W){W?be(i.SCISSOR_TEST):Ue(i.SCISSOR_TEST)}function L(W){W===void 0&&(W=i.TEXTURE0+D-1),J!==W&&(i.activeTexture(W),J=W)}function M(W,ne,re){re===void 0&&(J===null?re=i.TEXTURE0+D-1:re=J);let de=ee[re];de===void 0&&(de={type:void 0,texture:void 0},ee[re]=de),(de.type!==W||de.texture!==ne)&&(J!==re&&(i.activeTexture(re),J=re),i.bindTexture(W,ne||xe[W]),de.type=W,de.texture=ne)}function Z(){const W=ee[J];W!==void 0&&W.type!==void 0&&(i.bindTexture(W.type,null),W.type=void 0,W.texture=void 0)}function le(){try{i.compressedTexImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ae(){try{i.compressedTexImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function oe(){try{i.texSubImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Qe(){try{i.texSubImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function ve(){try{i.compressedTexSubImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function qe(){try{i.compressedTexSubImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ze(){try{i.texStorage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ee(){try{i.texStorage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function De(){try{i.texImage2D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Oe(){try{i.texImage3D(...arguments)}catch(W){console.error("THREE.WebGLState:",W)}}function Ge(W){Me.equals(W)===!1&&(i.scissor(W.x,W.y,W.z,W.w),Me.copy(W))}function Te(W){se.equals(W)===!1&&(i.viewport(W.x,W.y,W.z,W.w),se.copy(W))}function nt(W,ne){let re=l.get(ne);re===void 0&&(re=new WeakMap,l.set(ne,re));let de=re.get(W);de===void 0&&(de=i.getUniformBlockIndex(ne,W.name),re.set(W,de))}function Ke(W,ne){const de=l.get(ne).get(W);c.get(ne)!==de&&(i.uniformBlockBinding(ne,de,W.__bindingPointIndex),c.set(ne,de))}function it(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),a.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),h={},J=null,ee={},u={},d=new WeakMap,f=[],p=null,m=!1,g=null,A=null,_=null,x=null,E=null,S=null,w=null,I=new Fe(0,0,0),T=0,C=!1,v=null,F=null,K=null,q=null,$=null,Me.set(0,0,i.canvas.width,i.canvas.height),se.set(0,0,i.canvas.width,i.canvas.height),r.reset(),a.reset(),o.reset()}return{buffers:{color:r,depth:a,stencil:o},enable:be,disable:Ue,bindFramebuffer:et,drawBuffers:He,useProgram:Mt,setBlending:H,setMaterial:wn,setFlipSided:pt,setCullFace:mt,setLineWidth:We,setPolygonOffset:Dt,setScissorTest:ze,activeTexture:L,bindTexture:M,unbindTexture:Z,compressedTexImage2D:le,compressedTexImage3D:Ae,texImage2D:De,texImage3D:Oe,updateUBOMapping:nt,uniformBlockBinding:Ke,texStorage2D:Ze,texStorage3D:Ee,texSubImage2D:oe,texSubImage3D:Qe,compressedTexSubImage2D:ve,compressedTexSubImage3D:qe,scissor:Ge,viewport:Te,reset:it}}function YS(i,e,t,n,s,r,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Je,h=new WeakMap;let u;const d=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function p(L,M){return f?new OffscreenCanvas(L,M):mo("canvas")}function m(L,M,Z){let le=1;const Ae=ze(L);if((Ae.width>Z||Ae.height>Z)&&(le=Z/Math.max(Ae.width,Ae.height)),le<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){const oe=Math.floor(le*Ae.width),Qe=Math.floor(le*Ae.height);u===void 0&&(u=p(oe,Qe));const ve=M?p(oe,Qe):u;return ve.width=oe,ve.height=Qe,ve.getContext("2d").drawImage(L,0,0,oe,Qe),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Ae.width+"x"+Ae.height+") to ("+oe+"x"+Qe+")."),ve}else return"data"in L&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Ae.width+"x"+Ae.height+")."),L;return L}function g(L){return L.generateMipmaps}function A(L){i.generateMipmap(L)}function _(L){return L.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?i.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function x(L,M,Z,le,Ae=!1){if(L!==null){if(i[L]!==void 0)return i[L];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let oe=M;if(M===i.RED&&(Z===i.FLOAT&&(oe=i.R32F),Z===i.HALF_FLOAT&&(oe=i.R16F),Z===i.UNSIGNED_BYTE&&(oe=i.R8)),M===i.RED_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.R8UI),Z===i.UNSIGNED_SHORT&&(oe=i.R16UI),Z===i.UNSIGNED_INT&&(oe=i.R32UI),Z===i.BYTE&&(oe=i.R8I),Z===i.SHORT&&(oe=i.R16I),Z===i.INT&&(oe=i.R32I)),M===i.RG&&(Z===i.FLOAT&&(oe=i.RG32F),Z===i.HALF_FLOAT&&(oe=i.RG16F),Z===i.UNSIGNED_BYTE&&(oe=i.RG8)),M===i.RG_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RG8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RG16UI),Z===i.UNSIGNED_INT&&(oe=i.RG32UI),Z===i.BYTE&&(oe=i.RG8I),Z===i.SHORT&&(oe=i.RG16I),Z===i.INT&&(oe=i.RG32I)),M===i.RGB_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RGB8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RGB16UI),Z===i.UNSIGNED_INT&&(oe=i.RGB32UI),Z===i.BYTE&&(oe=i.RGB8I),Z===i.SHORT&&(oe=i.RGB16I),Z===i.INT&&(oe=i.RGB32I)),M===i.RGBA_INTEGER&&(Z===i.UNSIGNED_BYTE&&(oe=i.RGBA8UI),Z===i.UNSIGNED_SHORT&&(oe=i.RGBA16UI),Z===i.UNSIGNED_INT&&(oe=i.RGBA32UI),Z===i.BYTE&&(oe=i.RGBA8I),Z===i.SHORT&&(oe=i.RGBA16I),Z===i.INT&&(oe=i.RGBA32I)),M===i.RGB&&Z===i.UNSIGNED_INT_5_9_9_9_REV&&(oe=i.RGB9_E5),M===i.RGBA){const Qe=Ae?Hc:tt.getTransfer(le);Z===i.FLOAT&&(oe=i.RGBA32F),Z===i.HALF_FLOAT&&(oe=i.RGBA16F),Z===i.UNSIGNED_BYTE&&(oe=Qe===Rt?i.SRGB8_ALPHA8:i.RGBA8),Z===i.UNSIGNED_SHORT_4_4_4_4&&(oe=i.RGBA4),Z===i.UNSIGNED_SHORT_5_5_5_1&&(oe=i.RGB5_A1)}return(oe===i.R16F||oe===i.R32F||oe===i.RG16F||oe===i.RG32F||oe===i.RGBA16F||oe===i.RGBA32F)&&e.get("EXT_color_buffer_float"),oe}function E(L,M){let Z;return L?M===null||M===rr||M===so?Z=i.DEPTH24_STENCIL8:M===ln?Z=i.DEPTH32F_STENCIL8:M===io&&(Z=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===rr||M===so?Z=i.DEPTH_COMPONENT24:M===ln?Z=i.DEPTH_COMPONENT32F:M===io&&(Z=i.DEPTH_COMPONENT16),Z}function S(L,M){return g(L)===!0||L.isFramebufferTexture&&L.minFilter!==Pn&&L.minFilter!==qt?Math.log2(Math.max(M.width,M.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?M.mipmaps.length:1}function w(L){const M=L.target;M.removeEventListener("dispose",w),T(M),M.isVideoTexture&&h.delete(M)}function I(L){const M=L.target;M.removeEventListener("dispose",I),v(M)}function T(L){const M=n.get(L);if(M.__webglInit===void 0)return;const Z=L.source,le=d.get(Z);if(le){const Ae=le[M.__cacheKey];Ae.usedTimes--,Ae.usedTimes===0&&C(L),Object.keys(le).length===0&&d.delete(Z)}n.remove(L)}function C(L){const M=n.get(L);i.deleteTexture(M.__webglTexture);const Z=L.source,le=d.get(Z);delete le[M.__cacheKey],a.memory.textures--}function v(L){const M=n.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),n.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let le=0;le<6;le++){if(Array.isArray(M.__webglFramebuffer[le]))for(let Ae=0;Ae<M.__webglFramebuffer[le].length;Ae++)i.deleteFramebuffer(M.__webglFramebuffer[le][Ae]);else i.deleteFramebuffer(M.__webglFramebuffer[le]);M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer[le])}else{if(Array.isArray(M.__webglFramebuffer))for(let le=0;le<M.__webglFramebuffer.length;le++)i.deleteFramebuffer(M.__webglFramebuffer[le]);else i.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&i.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let le=0;le<M.__webglColorRenderbuffer.length;le++)M.__webglColorRenderbuffer[le]&&i.deleteRenderbuffer(M.__webglColorRenderbuffer[le]);M.__webglDepthRenderbuffer&&i.deleteRenderbuffer(M.__webglDepthRenderbuffer)}const Z=L.textures;for(let le=0,Ae=Z.length;le<Ae;le++){const oe=n.get(Z[le]);oe.__webglTexture&&(i.deleteTexture(oe.__webglTexture),a.memory.textures--),n.remove(Z[le])}n.remove(L)}let F=0;function K(){F=0}function q(){const L=F;return L>=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+s.maxTextures),F+=1,L}function $(L){const M=[];return M.push(L.wrapS),M.push(L.wrapT),M.push(L.wrapR||0),M.push(L.magFilter),M.push(L.minFilter),M.push(L.anisotropy),M.push(L.internalFormat),M.push(L.format),M.push(L.type),M.push(L.generateMipmaps),M.push(L.premultiplyAlpha),M.push(L.flipY),M.push(L.unpackAlignment),M.push(L.colorSpace),M.join()}function D(L,M){const Z=n.get(L);if(L.isVideoTexture&&We(L),L.isRenderTargetTexture===!1&&L.version>0&&Z.__version!==L.version){const le=L.image;if(le===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(le.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{se(Z,L,M);return}}t.bindTexture(i.TEXTURE_2D,Z.__webglTexture,i.TEXTURE0+M)}function O(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){se(Z,L,M);return}t.bindTexture(i.TEXTURE_2D_ARRAY,Z.__webglTexture,i.TEXTURE0+M)}function Y(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){se(Z,L,M);return}t.bindTexture(i.TEXTURE_3D,Z.__webglTexture,i.TEXTURE0+M)}function Q(L,M){const Z=n.get(L);if(L.version>0&&Z.__version!==L.version){me(Z,L,M);return}t.bindTexture(i.TEXTURE_CUBE_MAP,Z.__webglTexture,i.TEXTURE0+M)}const J={[Ss]:i.REPEAT,[Zn]:i.CLAMP_TO_EDGE,[Tc]:i.MIRRORED_REPEAT},ee={[Pn]:i.NEAREST,[Zp]:i.NEAREST_MIPMAP_NEAREST,[no]:i.NEAREST_MIPMAP_LINEAR,[qt]:i.LINEAR,[Rc]:i.LINEAR_MIPMAP_NEAREST,[ri]:i.LINEAR_MIPMAP_LINEAR},ae={[jy]:i.NEVER,[e_]:i.ALWAYS,[Xy]:i.LESS,[lA]:i.LEQUAL,[Yy]:i.EQUAL,[$y]:i.GEQUAL,[Jy]:i.GREATER,[Zy]:i.NOTEQUAL};function _e(L,M){if(M.type===ln&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===qt||M.magFilter===Rc||M.magFilter===no||M.magFilter===ri||M.minFilter===qt||M.minFilter===Rc||M.minFilter===no||M.minFilter===ri)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(L,i.TEXTURE_WRAP_S,J[M.wrapS]),i.texParameteri(L,i.TEXTURE_WRAP_T,J[M.wrapT]),(L===i.TEXTURE_3D||L===i.TEXTURE_2D_ARRAY)&&i.texParameteri(L,i.TEXTURE_WRAP_R,J[M.wrapR]),i.texParameteri(L,i.TEXTURE_MAG_FILTER,ee[M.magFilter]),i.texParameteri(L,i.TEXTURE_MIN_FILTER,ee[M.minFilter]),M.compareFunction&&(i.texParameteri(L,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(L,i.TEXTURE_COMPARE_FUNC,ae[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Pn||M.minFilter!==no&&M.minFilter!==ri||M.type===ln&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||n.get(M).__currentAnisotropy){const Z=e.get("EXT_texture_filter_anisotropic");i.texParameterf(L,Z.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,s.getMaxAnisotropy())),n.get(M).__currentAnisotropy=M.anisotropy}}}function Me(L,M){let Z=!1;L.__webglInit===void 0&&(L.__webglInit=!0,M.addEventListener("dispose",w));const le=M.source;let Ae=d.get(le);Ae===void 0&&(Ae={},d.set(le,Ae));const oe=$(M);if(oe!==L.__cacheKey){Ae[oe]===void 0&&(Ae[oe]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,Z=!0),Ae[oe].usedTimes++;const Qe=Ae[L.__cacheKey];Qe!==void 0&&(Ae[L.__cacheKey].usedTimes--,Qe.usedTimes===0&&C(M)),L.__cacheKey=oe,L.__webglTexture=Ae[oe].texture}return Z}function se(L,M,Z){let le=i.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(le=i.TEXTURE_2D_ARRAY),M.isData3DTexture&&(le=i.TEXTURE_3D);const Ae=Me(L,M),oe=M.source;t.bindTexture(le,L.__webglTexture,i.TEXTURE0+Z);const Qe=n.get(oe);if(oe.version!==Qe.__version||Ae===!0){t.activeTexture(i.TEXTURE0+Z);const ve=tt.getPrimaries(tt.workingColorSpace),qe=M.colorSpace===mi?null:tt.getPrimaries(M.colorSpace),Ze=M.colorSpace===mi||ve===qe?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ze);let Ee=m(M.image,!1,s.maxTextureSize);Ee=Dt(M,Ee);const De=r.convert(M.format,M.colorSpace),Oe=r.convert(M.type);let Ge=x(M.internalFormat,De,Oe,M.colorSpace,M.isVideoTexture);_e(le,M);let Te;const nt=M.mipmaps,Ke=M.isVideoTexture!==!0,it=Qe.__version===void 0||Ae===!0,W=oe.dataReady,ne=S(M,Ee);if(M.isDepthTexture)Ge=E(M.format===ao,M.type),it&&(Ke?t.texStorage2D(i.TEXTURE_2D,1,Ge,Ee.width,Ee.height):t.texImage2D(i.TEXTURE_2D,0,Ge,Ee.width,Ee.height,0,De,Oe,null));else if(M.isDataTexture)if(nt.length>0){Ke&&it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,nt[0].width,nt[0].height);for(let re=0,de=nt.length;re<de;re++)Te=nt[re],Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Oe,Te.data):t.texImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,De,Oe,Te.data);M.generateMipmaps=!1}else Ke?(it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,Ee.width,Ee.height),W&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,Ee.width,Ee.height,De,Oe,Ee.data)):t.texImage2D(i.TEXTURE_2D,0,Ge,Ee.width,Ee.height,0,De,Oe,Ee.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){Ke&&it&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ne,Ge,nt[0].width,nt[0].height,Ee.depth);for(let re=0,de=nt.length;re<de;re++)if(Te=nt[re],M.format!==hn)if(De!==null)if(Ke){if(W)if(M.layerUpdates.size>0){const Se=vg(Te.width,Te.height,M.format,M.type);for(const Ie of M.layerUpdates){const st=Te.data.subarray(Ie*Se/Te.data.BYTES_PER_ELEMENT,(Ie+1)*Se/Te.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,Ie,Te.width,Te.height,1,De,st)}M.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,0,Te.width,Te.height,Ee.depth,De,Te.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,re,Ge,Te.width,Te.height,Ee.depth,0,Te.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Ke?W&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,re,0,0,0,Te.width,Te.height,Ee.depth,De,Oe,Te.data):t.texImage3D(i.TEXTURE_2D_ARRAY,re,Ge,Te.width,Te.height,Ee.depth,0,De,Oe,Te.data)}else{Ke&&it&&t.texStorage2D(i.TEXTURE_2D,ne,Ge,nt[0].width,nt[0].height);for(let re=0,de=nt.length;re<de;re++)Te=nt[re],M.format!==hn?De!==null?Ke?W&&t.compressedTexSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Te.data):t.compressedTexImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,Te.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,Te.width,Te.height,De,Oe,Te.data):t.texImage2D(i.TEXTURE_2D,re,Ge,Te.width,Te.height,0,De,Oe,Te.data)}else if(M.isDataArrayTexture)if(Ke){if(it&&t.texStorage3D(i.TEXTURE_2D_ARRAY,ne,Ge,Ee.width,Ee.height,Ee.depth),W)if(M.layerUpdates.size>0){const re=vg(Ee.width,Ee.height,M.format,M.type);for(const de of M.layerUpdates){const Se=Ee.data.subarray(de*re/Ee.data.BYTES_PER_ELEMENT,(de+1)*re/Ee.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,de,Ee.width,Ee.height,1,De,Oe,Se)}M.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,Ee.width,Ee.height,Ee.depth,De,Oe,Ee.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Ge,Ee.width,Ee.height,Ee.depth,0,De,Oe,Ee.data);else if(M.isData3DTexture)Ke?(it&&t.texStorage3D(i.TEXTURE_3D,ne,Ge,Ee.width,Ee.height,Ee.depth),W&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,Ee.width,Ee.height,Ee.depth,De,Oe,Ee.data)):t.texImage3D(i.TEXTURE_3D,0,Ge,Ee.width,Ee.height,Ee.depth,0,De,Oe,Ee.data);else if(M.isFramebufferTexture){if(it)if(Ke)t.texStorage2D(i.TEXTURE_2D,ne,Ge,Ee.width,Ee.height);else{let re=Ee.width,de=Ee.height;for(let Se=0;Se<ne;Se++)t.texImage2D(i.TEXTURE_2D,Se,Ge,re,de,0,De,Oe,null),re>>=1,de>>=1}}else if(nt.length>0){if(Ke&&it){const re=ze(nt[0]);t.texStorage2D(i.TEXTURE_2D,ne,Ge,re.width,re.height)}for(let re=0,de=nt.length;re<de;re++)Te=nt[re],Ke?W&&t.texSubImage2D(i.TEXTURE_2D,re,0,0,De,Oe,Te):t.texImage2D(i.TEXTURE_2D,re,Ge,De,Oe,Te);M.generateMipmaps=!1}else if(Ke){if(it){const re=ze(Ee);t.texStorage2D(i.TEXTURE_2D,ne,Ge,re.width,re.height)}W&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,De,Oe,Ee)}else t.texImage2D(i.TEXTURE_2D,0,Ge,De,Oe,Ee);g(M)&&A(le),Qe.__version=oe.version,M.onUpdate&&M.onUpdate(M)}L.__version=M.version}function me(L,M,Z){if(M.image.length!==6)return;const le=Me(L,M),Ae=M.source;t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+Z);const oe=n.get(Ae);if(Ae.version!==oe.__version||le===!0){t.activeTexture(i.TEXTURE0+Z);const Qe=tt.getPrimaries(tt.workingColorSpace),ve=M.colorSpace===mi?null:tt.getPrimaries(M.colorSpace),qe=M.colorSpace===mi||Qe===ve?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,qe);const Ze=M.isCompressedTexture||M.image[0].isCompressedTexture,Ee=M.image[0]&&M.image[0].isDataTexture,De=[];for(let de=0;de<6;de++)!Ze&&!Ee?De[de]=m(M.image[de],!0,s.maxCubemapSize):De[de]=Ee?M.image[de].image:M.image[de],De[de]=Dt(M,De[de]);const Oe=De[0],Ge=r.convert(M.format,M.colorSpace),Te=r.convert(M.type),nt=x(M.internalFormat,Ge,Te,M.colorSpace),Ke=M.isVideoTexture!==!0,it=oe.__version===void 0||le===!0,W=Ae.dataReady;let ne=S(M,Oe);_e(i.TEXTURE_CUBE_MAP,M);let re;if(Ze){Ke&&it&&t.texStorage2D(i.TEXTURE_CUBE_MAP,ne,nt,Oe.width,Oe.height);for(let de=0;de<6;de++){re=De[de].mipmaps;for(let Se=0;Se<re.length;Se++){const Ie=re[Se];M.format!==hn?Ge!==null?Ke?W&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,0,0,Ie.width,Ie.height,Ge,Ie.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,nt,Ie.width,Ie.height,0,Ie.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,0,0,Ie.width,Ie.height,Ge,Te,Ie.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se,nt,Ie.width,Ie.height,0,Ge,Te,Ie.data)}}}else{if(re=M.mipmaps,Ke&&it){re.length>0&&ne++;const de=ze(De[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,ne,nt,de.width,de.height)}for(let de=0;de<6;de++)if(Ee){Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,0,0,De[de].width,De[de].height,Ge,Te,De[de].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,nt,De[de].width,De[de].height,0,Ge,Te,De[de].data);for(let Se=0;Se<re.length;Se++){const st=re[Se].image[de].image;Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,0,0,st.width,st.height,Ge,Te,st.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,nt,st.width,st.height,0,Ge,Te,st.data)}}else{Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,0,0,Ge,Te,De[de]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,nt,Ge,Te,De[de]);for(let Se=0;Se<re.length;Se++){const Ie=re[Se];Ke?W&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,0,0,Ge,Te,Ie.image[de]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+de,Se+1,nt,Ge,Te,Ie.image[de])}}}g(M)&&A(i.TEXTURE_CUBE_MAP),oe.__version=Ae.version,M.onUpdate&&M.onUpdate(M)}L.__version=M.version}function xe(L,M,Z,le,Ae,oe){const Qe=r.convert(Z.format,Z.colorSpace),ve=r.convert(Z.type),qe=x(Z.internalFormat,Qe,ve,Z.colorSpace),Ze=n.get(M),Ee=n.get(Z);if(Ee.__renderTarget=M,!Ze.__hasExternalTextures){const De=Math.max(1,M.width>>oe),Oe=Math.max(1,M.height>>oe);Ae===i.TEXTURE_3D||Ae===i.TEXTURE_2D_ARRAY?t.texImage3D(Ae,oe,qe,De,Oe,M.depth,0,Qe,ve,null):t.texImage2D(Ae,oe,qe,De,Oe,0,Qe,ve,null)}t.bindFramebuffer(i.FRAMEBUFFER,L),mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,le,Ae,Ee.__webglTexture,0,pt(M)):(Ae===i.TEXTURE_2D||Ae>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&Ae<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,le,Ae,Ee.__webglTexture,oe),t.bindFramebuffer(i.FRAMEBUFFER,null)}function be(L,M,Z){if(i.bindRenderbuffer(i.RENDERBUFFER,L),M.depthBuffer){const le=M.depthTexture,Ae=le&&le.isDepthTexture?le.type:null,oe=E(M.stencilBuffer,Ae),Qe=M.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ve=pt(M);mt(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,ve,oe,M.width,M.height):Z?i.renderbufferStorageMultisample(i.RENDERBUFFER,ve,oe,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,oe,M.width,M.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Qe,i.RENDERBUFFER,L)}else{const le=M.textures;for(let Ae=0;Ae<le.length;Ae++){const oe=le[Ae],Qe=r.convert(oe.format,oe.colorSpace),ve=r.convert(oe.type),qe=x(oe.internalFormat,Qe,ve,oe.colorSpace),Ze=pt(M);Z&&mt(M)===!1?i.renderbufferStorageMultisample(i.RENDERBUFFER,Ze,qe,M.width,M.height):mt(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,Ze,qe,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,qe,M.width,M.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ue(L,M){if(M&&M.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(i.FRAMEBUFFER,L),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const le=n.get(M.depthTexture);le.__renderTarget=M,(!le.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),D(M.depthTexture,0);const Ae=le.__webglTexture,oe=pt(M);if(M.depthTexture.format===ro)mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,Ae,0,oe):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,Ae,0);else if(M.depthTexture.format===ao)mt(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,Ae,0,oe):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,Ae,0);else throw new Error("Unknown depthTexture format")}function et(L){const M=n.get(L),Z=L.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==L.depthTexture){const le=L.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),le){const Ae=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,le.removeEventListener("dispose",Ae)};le.addEventListener("dispose",Ae),M.__depthDisposeCallback=Ae}M.__boundDepthTexture=le}if(L.depthTexture&&!M.__autoAllocateDepthBuffer){if(Z)throw new Error("target.depthTexture not supported in Cube render targets");const le=L.texture.mipmaps;le&&le.length>0?Ue(M.__webglFramebuffer[0],L):Ue(M.__webglFramebuffer,L)}else if(Z){M.__webglDepthbuffer=[];for(let le=0;le<6;le++)if(t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[le]),M.__webglDepthbuffer[le]===void 0)M.__webglDepthbuffer[le]=i.createRenderbuffer(),be(M.__webglDepthbuffer[le],L,!1);else{const Ae=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,oe=M.__webglDepthbuffer[le];i.bindRenderbuffer(i.RENDERBUFFER,oe),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ae,i.RENDERBUFFER,oe)}}else{const le=L.texture.mipmaps;if(le&&le.length>0?t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=i.createRenderbuffer(),be(M.__webglDepthbuffer,L,!1);else{const Ae=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,oe=M.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,oe),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ae,i.RENDERBUFFER,oe)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function He(L,M,Z){const le=n.get(L);M!==void 0&&xe(le.__webglFramebuffer,L,L.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),Z!==void 0&&et(L)}function Mt(L){const M=L.texture,Z=n.get(L),le=n.get(M);L.addEventListener("dispose",I);const Ae=L.textures,oe=L.isWebGLCubeRenderTarget===!0,Qe=Ae.length>1;if(Qe||(le.__webglTexture===void 0&&(le.__webglTexture=i.createTexture()),le.__version=M.version,a.memory.textures++),oe){Z.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer[ve]=[];for(let qe=0;qe<M.mipmaps.length;qe++)Z.__webglFramebuffer[ve][qe]=i.createFramebuffer()}else Z.__webglFramebuffer[ve]=i.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer=[];for(let ve=0;ve<M.mipmaps.length;ve++)Z.__webglFramebuffer[ve]=i.createFramebuffer()}else Z.__webglFramebuffer=i.createFramebuffer();if(Qe)for(let ve=0,qe=Ae.length;ve<qe;ve++){const Ze=n.get(Ae[ve]);Ze.__webglTexture===void 0&&(Ze.__webglTexture=i.createTexture(),a.memory.textures++)}if(L.samples>0&&mt(L)===!1){Z.__webglMultisampledFramebuffer=i.createFramebuffer(),Z.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,Z.__webglMultisampledFramebuffer);for(let ve=0;ve<Ae.length;ve++){const qe=Ae[ve];Z.__webglColorRenderbuffer[ve]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,Z.__webglColorRenderbuffer[ve]);const Ze=r.convert(qe.format,qe.colorSpace),Ee=r.convert(qe.type),De=x(qe.internalFormat,Ze,Ee,qe.colorSpace,L.isXRRenderTarget===!0),Oe=pt(L);i.renderbufferStorageMultisample(i.RENDERBUFFER,Oe,De,L.width,L.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+ve,i.RENDERBUFFER,Z.__webglColorRenderbuffer[ve])}i.bindRenderbuffer(i.RENDERBUFFER,null),L.depthBuffer&&(Z.__webglDepthRenderbuffer=i.createRenderbuffer(),be(Z.__webglDepthRenderbuffer,L,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(oe){t.bindTexture(i.TEXTURE_CUBE_MAP,le.__webglTexture),_e(i.TEXTURE_CUBE_MAP,M);for(let ve=0;ve<6;ve++)if(M.mipmaps&&M.mipmaps.length>0)for(let qe=0;qe<M.mipmaps.length;qe++)xe(Z.__webglFramebuffer[ve][qe],L,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ve,qe);else xe(Z.__webglFramebuffer[ve],L,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);g(M)&&A(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Qe){for(let ve=0,qe=Ae.length;ve<qe;ve++){const Ze=Ae[ve],Ee=n.get(Ze);t.bindTexture(i.TEXTURE_2D,Ee.__webglTexture),_e(i.TEXTURE_2D,Ze),xe(Z.__webglFramebuffer,L,Ze,i.COLOR_ATTACHMENT0+ve,i.TEXTURE_2D,0),g(Ze)&&A(i.TEXTURE_2D)}t.unbindTexture()}else{let ve=i.TEXTURE_2D;if((L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(ve=L.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ve,le.__webglTexture),_e(ve,M),M.mipmaps&&M.mipmaps.length>0)for(let qe=0;qe<M.mipmaps.length;qe++)xe(Z.__webglFramebuffer[qe],L,M,i.COLOR_ATTACHMENT0,ve,qe);else xe(Z.__webglFramebuffer,L,M,i.COLOR_ATTACHMENT0,ve,0);g(M)&&A(ve),t.unbindTexture()}L.depthBuffer&&et(L)}function ft(L){const M=L.textures;for(let Z=0,le=M.length;Z<le;Z++){const Ae=M[Z];if(g(Ae)){const oe=_(L),Qe=n.get(Ae).__webglTexture;t.bindTexture(oe,Qe),A(oe),t.unbindTexture()}}}const $e=[],H=[];function wn(L){if(L.samples>0){if(mt(L)===!1){const M=L.textures,Z=L.width,le=L.height;let Ae=i.COLOR_BUFFER_BIT;const oe=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Qe=n.get(L),ve=M.length>1;if(ve)for(let Ze=0;Ze<M.length;Ze++)t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer);const qe=L.texture.mipmaps;qe&&qe.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglFramebuffer);for(let Ze=0;Ze<M.length;Ze++){if(L.resolveDepthBuffer&&(L.depthBuffer&&(Ae|=i.DEPTH_BUFFER_BIT),L.stencilBuffer&&L.resolveStencilBuffer&&(Ae|=i.STENCIL_BUFFER_BIT)),ve){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Qe.__webglColorRenderbuffer[Ze]);const Ee=n.get(M[Ze]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,Ee,0)}i.blitFramebuffer(0,0,Z,le,0,0,Z,le,Ae,i.NEAREST),c===!0&&($e.length=0,H.length=0,$e.push(i.COLOR_ATTACHMENT0+Ze),L.depthBuffer&&L.resolveDepthBuffer===!1&&($e.push(oe),H.push(oe),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,H)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,$e))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),ve)for(let Ze=0;Ze<M.length;Ze++){t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.RENDERBUFFER,Qe.__webglColorRenderbuffer[Ze]);const Ee=n.get(M[Ze]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Qe.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ze,i.TEXTURE_2D,Ee,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Qe.__webglMultisampledFramebuffer)}else if(L.depthBuffer&&L.resolveDepthBuffer===!1&&c){const M=L.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[M])}}}function pt(L){return Math.min(s.maxSamples,L.samples)}function mt(L){const M=n.get(L);return L.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function We(L){const M=a.render.frame;h.get(L)!==M&&(h.set(L,M),L.update())}function Dt(L,M){const Z=L.colorSpace,le=L.format,Ae=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||Z!==un&&Z!==mi&&(tt.getTransfer(Z)===Rt?(le!==hn||Ae!==cn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",Z)),M}function ze(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(l.width=L.naturalWidth||L.width,l.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(l.width=L.displayWidth,l.height=L.displayHeight):(l.width=L.width,l.height=L.height),l}this.allocateTextureUnit=q,this.resetTextureUnits=K,this.setTexture2D=D,this.setTexture2DArray=O,this.setTexture3D=Y,this.setTextureCube=Q,this.rebindTextures=He,this.setupRenderTarget=Mt,this.updateRenderTargetMipmap=ft,this.updateMultisampleRenderTarget=wn,this.setupDepthRenderbuffer=et,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=mt}function JS(i,e){function t(n,s=mi){let r;const a=tt.getTransfer(s);if(n===cn)return i.UNSIGNED_BYTE;if(n===iu)return i.UNSIGNED_SHORT_4_4_4_4;if(n===su)return i.UNSIGNED_SHORT_5_5_5_1;if(n===tA)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===$p)return i.BYTE;if(n===eA)return i.SHORT;if(n===io)return i.UNSIGNED_SHORT;if(n===nu)return i.INT;if(n===rr)return i.UNSIGNED_INT;if(n===ln)return i.FLOAT;if(n===kn)return i.HALF_FLOAT;if(n===nA)return i.ALPHA;if(n===iA)return i.RGB;if(n===hn)return i.RGBA;if(n===ro)return i.DEPTH_COMPONENT;if(n===ao)return i.DEPTH_STENCIL;if(n===Xi)return i.RED;if(n===ru)return i.RED_INTEGER;if(n===ar)return i.RG;if(n===au)return i.RG_INTEGER;if(n===ou)return i.RGBA_INTEGER;if(n===Fc||n===oo||n===Nc||n===co)if(a===Rt)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Fc)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===oo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Nc)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===co)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Fc)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===oo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Nc)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===co)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Dc||n===cu||n===Lc||n===lu)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Dc)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===cu)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Lc)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===lu)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Pc||n===kc||n===Uc)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===Pc||n===kc)return a===Rt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Uc)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===lo||n===hu||n===uu||n===du||n===ho||n===fu||n===pu||n===Au||n===gu||n===mu||n===xu||n===bu||n===Eu||n===yu)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===lo)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===hu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===uu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===du)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ho)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===fu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===pu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Au)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===gu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===mu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===xu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===bu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Eu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===yu)return a===Rt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===uo||n===_u||n===Oc)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===uo)return a===Rt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===_u)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Oc)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===sA||n===wu||n===vu||n===Cu)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===uo)return r.COMPRESSED_RED_RGTC1_EXT;if(n===wu)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===vu)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Cu)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===so?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const ZS=`
void main() {
gl_Position = vec4( position, 1.0 );
-}`,e1=`
+}`,$S=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;
@@ -3816,7 +3816,7 @@ void main() {
}
-}`;class t1{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){const s=new nn,r=e.properties.get(s);r.__webglTexture=t.texture,(t.depthNear!==n.depthNear||t.depthFar!==n.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=s}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Ls({vertexShader:$S,fragmentShader:e1,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Zt(new vl(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class n1 extends Ms{constructor(e,t){super();const n=this;let s=null,r=1,a=null,o="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=new t1,g=t.getContextAttributes();let A=null,_=null;const x=[],E=[],S=new Je;let w=null;const I=new Bn;I.viewport=new gt;const T=new Bn;T.viewport=new gt;const C=[I,T],v=new Hw;let F=null,K=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getTargetRaySpace()},this.getControllerGrip=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getGripSpace()},this.getHand=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getHandSpace()};function q(se){const me=E.indexOf(se.inputSource);if(me===-1)return;const xe=x[me];xe!==void 0&&(xe.update(se.inputSource,se.frame,l||a),xe.dispatchEvent({type:se.type,data:se.inputSource}))}function $(){s.removeEventListener("select",q),s.removeEventListener("selectstart",q),s.removeEventListener("selectend",q),s.removeEventListener("squeeze",q),s.removeEventListener("squeezestart",q),s.removeEventListener("squeezeend",q),s.removeEventListener("end",$),s.removeEventListener("inputsourceschange",D);for(let se=0;se<x.length;se++){const me=E[se];me!==null&&(E[se]=null,x[se].disconnect(me))}F=null,K=null,m.reset(),e.setRenderTarget(A),f=null,d=null,u=null,s=null,_=null,Me.stop(),n.isPresenting=!1,e.setPixelRatio(w),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(se){r=se,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(se){o=se,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(se){l=se},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(se){if(s=se,s!==null){if(A=e.getRenderTarget(),s.addEventListener("select",q),s.addEventListener("selectstart",q),s.addEventListener("selectend",q),s.addEventListener("squeeze",q),s.addEventListener("squeezestart",q),s.addEventListener("squeezeend",q),s.addEventListener("end",$),s.addEventListener("inputsourceschange",D),g.xrCompatible!==!0&&await t.makeXRCompatible(),w=e.getPixelRatio(),e.getSize(S),typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype){let xe=null,be=null,Ue=null;g.depth&&(Ue=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,xe=g.stencil?ao:ro,be=g.stencil?so:rr);const et={colorFormat:t.RGBA8,depthFormat:Ue,scaleFactor:r};u=new XRWebGLBinding(s,t),d=u.createProjectionLayer(et),s.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),_=new or(d.textureWidth,d.textureHeight,{format:hn,type:cn,depthTexture:new tg(d.textureWidth,d.textureHeight,be,void 0,void 0,void 0,void 0,void 0,void 0,xe),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const xe={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,xe),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new or(f.framebufferWidth,f.framebufferHeight,{format:hn,type:cn,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(c),l=null,a=await s.requestReferenceSpace(o),Me.setContext(s),Me.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function D(se){for(let me=0;me<se.removed.length;me++){const xe=se.removed[me],be=E.indexOf(xe);be>=0&&(E[be]=null,x[be].disconnect(xe))}for(let me=0;me<se.added.length;me++){const xe=se.added[me];let be=E.indexOf(xe);if(be===-1){for(let et=0;et<x.length;et++)if(et>=E.length){E.push(xe),be=et;break}else if(E[et]===null){E[et]=xe,be=et;break}if(be===-1)break}const Ue=x[be];Ue&&Ue.connect(xe)}}const O=new G,Y=new G;function Q(se,me,xe){O.setFromMatrixPosition(me.matrixWorld),Y.setFromMatrixPosition(xe.matrixWorld);const be=O.distanceTo(Y),Ue=me.projectionMatrix.elements,et=xe.projectionMatrix.elements,He=Ue[14]/(Ue[10]-1),Mt=Ue[14]/(Ue[10]+1),ft=(Ue[9]+1)/Ue[5],$e=(Ue[9]-1)/Ue[5],H=(Ue[8]-1)/Ue[0],wn=(et[8]+1)/et[0],pt=He*H,mt=He*wn,We=be/(-H+wn),Dt=We*-H;if(me.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(Dt),se.translateZ(We),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert(),Ue[10]===-1)se.projectionMatrix.copy(me.projectionMatrix),se.projectionMatrixInverse.copy(me.projectionMatrixInverse);else{const ze=He+We,L=Mt+We,M=pt-Dt,Z=mt+(be-Dt),le=ft*Mt/L*ze,Ae=$e*Mt/L*ze;se.projectionMatrix.makePerspective(M,Z,le,Ae,ze,L),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}}function J(se,me){me===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(me.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(s===null)return;let me=se.near,xe=se.far;m.texture!==null&&(m.depthNear>0&&(me=m.depthNear),m.depthFar>0&&(xe=m.depthFar)),v.near=T.near=I.near=me,v.far=T.far=I.far=xe,(F!==v.near||K!==v.far)&&(s.updateRenderState({depthNear:v.near,depthFar:v.far}),F=v.near,K=v.far),I.layers.mask=se.layers.mask|2,T.layers.mask=se.layers.mask|4,v.layers.mask=I.layers.mask|T.layers.mask;const be=se.parent,Ue=v.cameras;J(v,be);for(let et=0;et<Ue.length;et++)J(Ue[et],be);Ue.length===2?Q(v,I,T):v.projectionMatrix.copy(I.projectionMatrix),ee(se,v,be)};function ee(se,me,xe){xe===null?se.matrix.copy(me.matrixWorld):(se.matrix.copy(xe.matrixWorld),se.matrix.invert(),se.matrix.multiply(me.matrixWorld)),se.matrix.decompose(se.position,se.quaternion,se.scale),se.updateMatrixWorld(!0),se.projectionMatrix.copy(me.projectionMatrix),se.projectionMatrixInverse.copy(me.projectionMatrixInverse),se.isPerspectiveCamera&&(se.fov=ea*2*Math.atan(1/se.projectionMatrix.elements[5]),se.zoom=1)}this.getCamera=function(){return v},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(se){c=se,d!==null&&(d.fixedFoveation=se),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=se)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(v)};let ae=null;function _e(se,me){if(h=me.getViewerPose(l||a),p=me,h!==null){const xe=h.views;f!==null&&(e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_));let be=!1;xe.length!==v.cameras.length&&(v.cameras.length=0,be=!0);for(let He=0;He<xe.length;He++){const Mt=xe[He];let ft=null;if(f!==null)ft=f.getViewport(Mt);else{const H=u.getViewSubImage(d,Mt);ft=H.viewport,He===0&&(e.setRenderTargetTextures(_,H.colorTexture,H.depthStencilTexture),e.setRenderTarget(_))}let $e=C[He];$e===void 0&&($e=new Bn,$e.layers.enable(He),$e.viewport=new gt,C[He]=$e),$e.matrix.fromArray(Mt.transform.matrix),$e.matrix.decompose($e.position,$e.quaternion,$e.scale),$e.projectionMatrix.fromArray(Mt.projectionMatrix),$e.projectionMatrixInverse.copy($e.projectionMatrix).invert(),$e.viewport.set(ft.x,ft.y,ft.width,ft.height),He===0&&(v.matrix.copy($e.matrix),v.matrix.decompose(v.position,v.quaternion,v.scale)),be===!0&&v.cameras.push($e)}const Ue=s.enabledFeatures;if(Ue&&Ue.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&u){const He=u.getDepthInformation(xe[0]);He&&He.isValid&&He.texture&&m.init(e,He,s.renderState)}}for(let xe=0;xe<x.length;xe++){const be=E[xe],Ue=x[xe];be!==null&&Ue!==void 0&&Ue.update(be,me,l||a)}ae&&ae(se,me),me.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:me}),p=null}const Me=new Cg;Me.setAnimationLoop(_e),this.setAnimationLoop=function(se){ae=se},this.dispose=function(){}}}const br=new dn,i1=new Re;function s1(i,e){function t(g,A){g.matrixAutoUpdate===!0&&g.updateMatrix(),A.value.copy(g.matrix)}function n(g,A){A.color.getRGB(g.fogColor.value,DA(i)),A.isFog?(g.fogNear.value=A.near,g.fogFar.value=A.far):A.isFogExp2&&(g.fogDensity.value=A.density)}function s(g,A,_,x,E){A.isMeshBasicMaterial||A.isMeshLambertMaterial?r(g,A):A.isMeshToonMaterial?(r(g,A),u(g,A)):A.isMeshPhongMaterial?(r(g,A),h(g,A)):A.isMeshStandardMaterial?(r(g,A),d(g,A),A.isMeshPhysicalMaterial&&f(g,A,E)):A.isMeshMatcapMaterial?(r(g,A),p(g,A)):A.isMeshDepthMaterial?r(g,A):A.isMeshDistanceMaterial?(r(g,A),m(g,A)):A.isMeshNormalMaterial?r(g,A):A.isLineBasicMaterial?(a(g,A),A.isLineDashedMaterial&&o(g,A)):A.isPointsMaterial?c(g,A,_,x):A.isSpriteMaterial?l(g,A):A.isShadowMaterial?(g.color.value.copy(A.color),g.opacity.value=A.opacity):A.isShaderMaterial&&(A.uniformsNeedUpdate=!1)}function r(g,A){g.opacity.value=A.opacity,A.color&&g.diffuse.value.copy(A.color),A.emissive&&g.emissive.value.copy(A.emissive).multiplyScalar(A.emissiveIntensity),A.map&&(g.map.value=A.map,t(A.map,g.mapTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.bumpMap&&(g.bumpMap.value=A.bumpMap,t(A.bumpMap,g.bumpMapTransform),g.bumpScale.value=A.bumpScale,A.side===Ln&&(g.bumpScale.value*=-1)),A.normalMap&&(g.normalMap.value=A.normalMap,t(A.normalMap,g.normalMapTransform),g.normalScale.value.copy(A.normalScale),A.side===Ln&&g.normalScale.value.negate()),A.displacementMap&&(g.displacementMap.value=A.displacementMap,t(A.displacementMap,g.displacementMapTransform),g.displacementScale.value=A.displacementScale,g.displacementBias.value=A.displacementBias),A.emissiveMap&&(g.emissiveMap.value=A.emissiveMap,t(A.emissiveMap,g.emissiveMapTransform)),A.specularMap&&(g.specularMap.value=A.specularMap,t(A.specularMap,g.specularMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest);const _=e.get(A),x=_.envMap,E=_.envMapRotation;x&&(g.envMap.value=x,br.copy(E),br.x*=-1,br.y*=-1,br.z*=-1,x.isCubeTexture&&x.isRenderTargetTexture===!1&&(br.y*=-1,br.z*=-1),g.envMapRotation.value.setFromMatrix4(i1.makeRotationFromEuler(br)),g.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=A.reflectivity,g.ior.value=A.ior,g.refractionRatio.value=A.refractionRatio),A.lightMap&&(g.lightMap.value=A.lightMap,g.lightMapIntensity.value=A.lightMapIntensity,t(A.lightMap,g.lightMapTransform)),A.aoMap&&(g.aoMap.value=A.aoMap,g.aoMapIntensity.value=A.aoMapIntensity,t(A.aoMap,g.aoMapTransform))}function a(g,A){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,A.map&&(g.map.value=A.map,t(A.map,g.mapTransform))}function o(g,A){g.dashSize.value=A.dashSize,g.totalSize.value=A.dashSize+A.gapSize,g.scale.value=A.scale}function c(g,A,_,x){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,g.size.value=A.size*_,g.scale.value=x*.5,A.map&&(g.map.value=A.map,t(A.map,g.uvTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest)}function l(g,A){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,g.rotation.value=A.rotation,A.map&&(g.map.value=A.map,t(A.map,g.mapTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest)}function h(g,A){g.specular.value.copy(A.specular),g.shininess.value=Math.max(A.shininess,1e-4)}function u(g,A){A.gradientMap&&(g.gradientMap.value=A.gradientMap)}function d(g,A){g.metalness.value=A.metalness,A.metalnessMap&&(g.metalnessMap.value=A.metalnessMap,t(A.metalnessMap,g.metalnessMapTransform)),g.roughness.value=A.roughness,A.roughnessMap&&(g.roughnessMap.value=A.roughnessMap,t(A.roughnessMap,g.roughnessMapTransform)),A.envMap&&(g.envMapIntensity.value=A.envMapIntensity)}function f(g,A,_){g.ior.value=A.ior,A.sheen>0&&(g.sheenColor.value.copy(A.sheenColor).multiplyScalar(A.sheen),g.sheenRoughness.value=A.sheenRoughness,A.sheenColorMap&&(g.sheenColorMap.value=A.sheenColorMap,t(A.sheenColorMap,g.sheenColorMapTransform)),A.sheenRoughnessMap&&(g.sheenRoughnessMap.value=A.sheenRoughnessMap,t(A.sheenRoughnessMap,g.sheenRoughnessMapTransform))),A.clearcoat>0&&(g.clearcoat.value=A.clearcoat,g.clearcoatRoughness.value=A.clearcoatRoughness,A.clearcoatMap&&(g.clearcoatMap.value=A.clearcoatMap,t(A.clearcoatMap,g.clearcoatMapTransform)),A.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=A.clearcoatRoughnessMap,t(A.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),A.clearcoatNormalMap&&(g.clearcoatNormalMap.value=A.clearcoatNormalMap,t(A.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(A.clearcoatNormalScale),A.side===Ln&&g.clearcoatNormalScale.value.negate())),A.dispersion>0&&(g.dispersion.value=A.dispersion),A.iridescence>0&&(g.iridescence.value=A.iridescence,g.iridescenceIOR.value=A.iridescenceIOR,g.iridescenceThicknessMinimum.value=A.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=A.iridescenceThicknessRange[1],A.iridescenceMap&&(g.iridescenceMap.value=A.iridescenceMap,t(A.iridescenceMap,g.iridescenceMapTransform)),A.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=A.iridescenceThicknessMap,t(A.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),A.transmission>0&&(g.transmission.value=A.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),A.transmissionMap&&(g.transmissionMap.value=A.transmissionMap,t(A.transmissionMap,g.transmissionMapTransform)),g.thickness.value=A.thickness,A.thicknessMap&&(g.thicknessMap.value=A.thicknessMap,t(A.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=A.attenuationDistance,g.attenuationColor.value.copy(A.attenuationColor)),A.anisotropy>0&&(g.anisotropyVector.value.set(A.anisotropy*Math.cos(A.anisotropyRotation),A.anisotropy*Math.sin(A.anisotropyRotation)),A.anisotropyMap&&(g.anisotropyMap.value=A.anisotropyMap,t(A.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=A.specularIntensity,g.specularColor.value.copy(A.specularColor),A.specularColorMap&&(g.specularColorMap.value=A.specularColorMap,t(A.specularColorMap,g.specularColorMapTransform)),A.specularIntensityMap&&(g.specularIntensityMap.value=A.specularIntensityMap,t(A.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,A){A.matcap&&(g.matcap.value=A.matcap)}function m(g,A){const _=e.get(A).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function r1(i,e,t,n){let s={},r={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(_,x){const E=x.program;n.uniformBlockBinding(_,E)}function l(_,x){let E=s[_.id];E===void 0&&(p(_),E=h(_),s[_.id]=E,_.addEventListener("dispose",g));const S=x.program;n.updateUBOMapping(_,S);const w=e.render.frame;r[_.id]!==w&&(d(_),r[_.id]=w)}function h(_){const x=u();_.__bindingPointIndex=x;const E=i.createBuffer(),S=_.__size,w=_.usage;return i.bindBuffer(i.UNIFORM_BUFFER,E),i.bufferData(i.UNIFORM_BUFFER,S,w),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,x,E),E}function u(){for(let _=0;_<o;_++)if(a.indexOf(_)===-1)return a.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(_){const x=s[_.id],E=_.uniforms,S=_.__cache;i.bindBuffer(i.UNIFORM_BUFFER,x);for(let w=0,I=E.length;w<I;w++){const T=Array.isArray(E[w])?E[w]:[E[w]];for(let C=0,v=T.length;C<v;C++){const F=T[C];if(f(F,w,C,S)===!0){const K=F.__offset,q=Array.isArray(F.value)?F.value:[F.value];let $=0;for(let D=0;D<q.length;D++){const O=q[D],Y=m(O);typeof O=="number"||typeof O=="boolean"?(F.__data[0]=O,i.bufferSubData(i.UNIFORM_BUFFER,K+$,F.__data)):O.isMatrix3?(F.__data[0]=O.elements[0],F.__data[1]=O.elements[1],F.__data[2]=O.elements[2],F.__data[3]=0,F.__data[4]=O.elements[3],F.__data[5]=O.elements[4],F.__data[6]=O.elements[5],F.__data[7]=0,F.__data[8]=O.elements[6],F.__data[9]=O.elements[7],F.__data[10]=O.elements[8],F.__data[11]=0):(O.toArray(F.__data,$),$+=Y.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,K,F.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(_,x,E,S){const w=_.value,I=x+"_"+E;if(S[I]===void 0)return typeof w=="number"||typeof w=="boolean"?S[I]=w:S[I]=w.clone(),!0;{const T=S[I];if(typeof w=="number"||typeof w=="boolean"){if(T!==w)return S[I]=w,!0}else if(T.equals(w)===!1)return T.copy(w),!0}return!1}function p(_){const x=_.uniforms;let E=0;const S=16;for(let I=0,T=x.length;I<T;I++){const C=Array.isArray(x[I])?x[I]:[x[I]];for(let v=0,F=C.length;v<F;v++){const K=C[v],q=Array.isArray(K.value)?K.value:[K.value];for(let $=0,D=q.length;$<D;$++){const O=q[$],Y=m(O),Q=E%S,J=Q%Y.boundary,ee=Q+J;E+=J,ee!==0&&S-ee<Y.storage&&(E+=S-ee),K.__data=new Float32Array(Y.storage/Float32Array.BYTES_PER_ELEMENT),K.__offset=E,E+=Y.storage}}}const w=E%S;return w>0&&(E+=S-w),_.__size=E,_.__cache={},this}function m(_){const x={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(x.boundary=4,x.storage=4):_.isVector2?(x.boundary=8,x.storage=8):_.isVector3||_.isColor?(x.boundary=16,x.storage=12):_.isVector4?(x.boundary=16,x.storage=16):_.isMatrix3?(x.boundary=48,x.storage=48):_.isMatrix4?(x.boundary=64,x.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),x}function g(_){const x=_.target;x.removeEventListener("dispose",g);const E=a.indexOf(x.__bindingPointIndex);a.splice(E,1),i.deleteBuffer(s[x.id]),delete s[x.id],delete r[x.id]}function A(){for(const _ in s)i.deleteBuffer(s[_]);a=[],s={},r={}}return{bind:c,update:l,dispose:A}}class $g{constructor(e={}){const{canvas:t=x_(),context:n=null,depth:s=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let f;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=n.getContextAttributes().alpha}else f=a;const p=new Uint32Array(4),m=new Int32Array(4);let g=null,A=null;const _=[],x=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Is,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let S=!1;this._outputColorSpace=yt;let w=0,I=0,T=null,C=-1,v=null;const F=new gt,K=new gt;let q=null;const $=new Fe(0);let D=0,O=t.width,Y=t.height,Q=1,J=null,ee=null;const ae=new gt(0,0,O,Y),_e=new gt(0,0,O,Y);let Me=!1;const se=new rd;let me=!1,xe=!1;const be=new Re,Ue=new Re,et=new G,He=new gt,Mt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ft=!1;function $e(){return T===null?Q:1}let H=n;function wn(y,R){return t.getContext(y,R)}try{const y={alpha:!0,depth:s,stencil:r,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Ic}`),t.addEventListener("webglcontextlost",de,!1),t.addEventListener("webglcontextrestored",Se,!1),t.addEventListener("webglcontextcreationerror",Ie,!1),H===null){const R="webgl2";if(H=wn(R,y),H===null)throw wn(R)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(y){throw console.error("THREE.WebGLRenderer: "+y.message),y}let pt,mt,We,Dt,ze,L,M,Z,le,Ae,oe,Qe,ve,qe,Ze,Ee,De,Oe,Ge,Te,nt,Ke,it,W;function ne(){pt=new gI(H),pt.init(),Ke=new ZS(H,pt),mt=new lI(H,pt,e,Ke),We=new YS(H,pt),mt.reverseDepthBuffer&&d&&We.buffers.depth.setReversed(!0),Dt=new bI(H),ze=new kS,L=new JS(H,pt,We,ze,mt,Ke,Dt),M=new uI(E),Z=new AI(E),le=new rv(H),it=new oI(H,le),Ae=new mI(H,le,Dt,it),oe=new yI(H,Ae,le,Dt),Ge=new EI(H,mt,L),Ee=new hI(ze),Qe=new PS(E,M,Z,pt,mt,it,Ee),ve=new s1(E,ze),qe=new OS,Ze=new WS(pt),Oe=new aI(E,M,Z,We,oe,f,c),De=new jS(E,oe,mt),W=new r1(H,Dt,mt,We),Te=new cI(H,pt,Dt),nt=new xI(H,pt,Dt),Dt.programs=Qe.programs,E.capabilities=mt,E.extensions=pt,E.properties=ze,E.renderLists=qe,E.shadowMap=De,E.state=We,E.info=Dt}ne();const re=new n1(E,H);this.xr=re,this.getContext=function(){return H},this.getContextAttributes=function(){return H.getContextAttributes()},this.forceContextLoss=function(){const y=pt.get("WEBGL_lose_context");y&&y.loseContext()},this.forceContextRestore=function(){const y=pt.get("WEBGL_lose_context");y&&y.restoreContext()},this.getPixelRatio=function(){return Q},this.setPixelRatio=function(y){y!==void 0&&(Q=y,this.setSize(O,Y,!1))},this.getSize=function(y){return y.set(O,Y)},this.setSize=function(y,R,N=!0){if(re.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}O=y,Y=R,t.width=Math.floor(y*Q),t.height=Math.floor(R*Q),N===!0&&(t.style.width=y+"px",t.style.height=R+"px"),this.setViewport(0,0,y,R)},this.getDrawingBufferSize=function(y){return y.set(O*Q,Y*Q).floor()},this.setDrawingBufferSize=function(y,R,N){O=y,Y=R,Q=N,t.width=Math.floor(y*N),t.height=Math.floor(R*N),this.setViewport(0,0,y,R)},this.getCurrentViewport=function(y){return y.copy(F)},this.getViewport=function(y){return y.copy(ae)},this.setViewport=function(y,R,N,U){y.isVector4?ae.set(y.x,y.y,y.z,y.w):ae.set(y,R,N,U),We.viewport(F.copy(ae).multiplyScalar(Q).round())},this.getScissor=function(y){return y.copy(_e)},this.setScissor=function(y,R,N,U){y.isVector4?_e.set(y.x,y.y,y.z,y.w):_e.set(y,R,N,U),We.scissor(K.copy(_e).multiplyScalar(Q).round())},this.getScissorTest=function(){return Me},this.setScissorTest=function(y){We.setScissorTest(Me=y)},this.setOpaqueSort=function(y){J=y},this.setTransparentSort=function(y){ee=y},this.getClearColor=function(y){return y.copy(Oe.getClearColor())},this.setClearColor=function(){Oe.setClearColor(...arguments)},this.getClearAlpha=function(){return Oe.getClearAlpha()},this.setClearAlpha=function(){Oe.setClearAlpha(...arguments)},this.clear=function(y=!0,R=!0,N=!0){let U=0;if(y){let P=!1;if(T!==null){const z=T.texture.format;P=z===ou||z===au||z===ru}if(P){const z=T.texture.type,j=z===cn||z===rr||z===io||z===so||z===iu||z===su,X=Oe.getClearColor(),ie=Oe.getClearAlpha(),he=X.r,ce=X.g,fe=X.b;j?(p[0]=he,p[1]=ce,p[2]=fe,p[3]=ie,H.clearBufferuiv(H.COLOR,0,p)):(m[0]=he,m[1]=ce,m[2]=fe,m[3]=ie,H.clearBufferiv(H.COLOR,0,m))}else U|=H.COLOR_BUFFER_BIT}R&&(U|=H.DEPTH_BUFFER_BIT),N&&(U|=H.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),H.clear(U)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",de,!1),t.removeEventListener("webglcontextrestored",Se,!1),t.removeEventListener("webglcontextcreationerror",Ie,!1),Oe.dispose(),qe.dispose(),Ze.dispose(),ze.dispose(),M.dispose(),Z.dispose(),oe.dispose(),it.dispose(),W.dispose(),Qe.dispose(),re.dispose(),re.removeEventListener("sessionstart",Gh),re.removeEventListener("sessionend",Hh),ws.stop()};function de(y){y.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function Se(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const y=Dt.autoReset,R=De.enabled,N=De.autoUpdate,U=De.needsUpdate,P=De.type;ne(),Dt.autoReset=y,De.enabled=R,De.autoUpdate=N,De.needsUpdate=U,De.type=P}function Ie(y){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",y.statusMessage)}function st(y){const R=y.target;R.removeEventListener("dispose",st),Ht(R)}function Ht(y){vn(y),ze.remove(y)}function vn(y){const R=ze.get(y).programs;R!==void 0&&(R.forEach(function(N){Qe.releaseProgram(N)}),y.isShaderMaterial&&Qe.releaseShaderCache(y))}this.renderBufferDirect=function(y,R,N,U,P,z){R===null&&(R=Mt);const j=P.isMesh&&P.matrixWorld.determinant()<0,X=Hp(y,R,N,U,P);We.setMaterial(U,j);let ie=N.index,he=1;if(U.wireframe===!0){if(ie=Ae.getWireframeAttribute(N),ie===void 0)return;he=2}const ce=N.drawRange,fe=N.attributes.position;let ge=ce.start*he,ye=(ce.start+ce.count)*he;z!==null&&(ge=Math.max(ge,z.start*he),ye=Math.min(ye,(z.start+z.count)*he)),ie!==null?(ge=Math.max(ge,0),ye=Math.min(ye,ie.count)):fe!=null&&(ge=Math.max(ge,0),ye=Math.min(ye,fe.count));const Pe=ye-ge;if(Pe<0||Pe===1/0)return;it.setup(P,U,X,N,ie);let je,Ve=Te;if(ie!==null&&(je=le.get(ie),Ve=nt,Ve.setIndex(je)),P.isMesh)U.wireframe===!0?(We.setLineWidth(U.wireframeLinewidth*$e()),Ve.setMode(H.LINES)):Ve.setMode(H.TRIANGLES);else if(P.isLine){let Le=U.linewidth;Le===void 0&&(Le=1),We.setLineWidth(Le*$e()),P.isLineSegments?Ve.setMode(H.LINES):P.isLineLoop?Ve.setMode(H.LINE_LOOP):Ve.setMode(H.LINE_STRIP)}else P.isPoints?Ve.setMode(H.POINTS):P.isSprite&&Ve.setMode(H.TRIANGLES);if(P.isBatchedMesh)if(P._multiDrawInstances!==null)Vc("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Ve.renderMultiDrawInstances(P._multiDrawStarts,P._multiDrawCounts,P._multiDrawCount,P._multiDrawInstances);else if(pt.get("WEBGL_multi_draw"))Ve.renderMultiDraw(P._multiDrawStarts,P._multiDrawCounts,P._multiDrawCount);else{const Le=P._multiDrawStarts,rt=P._multiDrawCounts,ke=P._multiDrawCount,It=ie?le.get(ie).bytesPerElement:1,mn=ze.get(U).currentProgram.getUniforms();for(let vt=0;vt<ke;vt++)mn.setValue(H,"_gl_DrawID",vt),Ve.render(Le[vt]/It,rt[vt])}else if(P.isInstancedMesh)Ve.renderInstances(ge,Pe,P.count);else if(N.isInstancedBufferGeometry){const Le=N._maxInstanceCount!==void 0?N._maxInstanceCount:1/0,rt=Math.min(N.instanceCount,Le);Ve.renderInstances(ge,Pe,rt)}else Ve.render(ge,Pe)};function Ct(y,R,N){y.transparent===!0&&y.side===Pi&&y.forceSinglePass===!1?(y.side=Ln,y.needsUpdate=!0,to(y,R,N),y.side=ji,y.needsUpdate=!0,to(y,R,N),y.side=Pi):to(y,R,N)}this.compile=function(y,R,N=null){N===null&&(N=y),A=Ze.get(N),A.init(R),x.push(A),N.traverseVisible(function(P){P.isLight&&P.layers.test(R.layers)&&(A.pushLight(P),P.castShadow&&A.pushShadow(P))}),y!==N&&y.traverseVisible(function(P){P.isLight&&P.layers.test(R.layers)&&(A.pushLight(P),P.castShadow&&A.pushShadow(P))}),A.setupLights();const U=new Set;return y.traverse(function(P){if(!(P.isMesh||P.isPoints||P.isLine||P.isSprite))return;const z=P.material;if(z)if(Array.isArray(z))for(let j=0;j<z.length;j++){const X=z[j];Ct(X,N,P),U.add(X)}else Ct(z,N,P),U.add(z)}),A=x.pop(),U},this.compileAsync=function(y,R,N=null){const U=this.compile(y,R,N);return new Promise(P=>{function z(){if(U.forEach(function(j){ze.get(j).currentProgram.isReady()&&U.delete(j)}),U.size===0){P(y);return}setTimeout(z,10)}pt.get("KHR_parallel_shader_compile")!==null?z():setTimeout(z,10)})};let si=null;function Li(y){si&&si(y)}function Gh(){ws.stop()}function Hh(){ws.start()}const ws=new Cg;ws.setAnimationLoop(Li),typeof self<"u"&&ws.setContext(self),this.setAnimationLoop=function(y){si=y,re.setAnimationLoop(y),y===null?ws.stop():ws.start()},re.addEventListener("sessionstart",Gh),re.addEventListener("sessionend",Hh),this.render=function(y,R){if(R!==void 0&&R.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(y.matrixWorldAutoUpdate===!0&&y.updateMatrixWorld(),R.parent===null&&R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),re.enabled===!0&&re.isPresenting===!0&&(re.cameraAutoUpdate===!0&&re.updateCamera(R),R=re.getCamera()),y.isScene===!0&&y.onBeforeRender(E,y,R,T),A=Ze.get(y,x.length),A.init(R),x.push(A),Ue.multiplyMatrices(R.projectionMatrix,R.matrixWorldInverse),se.setFromProjectionMatrix(Ue),xe=this.localClippingEnabled,me=Ee.init(this.clippingPlanes,xe),g=qe.get(y,_.length),g.init(),_.push(g),re.enabled===!0&&re.isPresenting===!0){const z=E.xr.getDepthSensingMesh();z!==null&&_c(z,R,-1/0,E.sortObjects)}_c(y,R,0,E.sortObjects),g.finish(),E.sortObjects===!0&&g.sort(J,ee),ft=re.enabled===!1||re.isPresenting===!1||re.hasDepthSensing()===!1,ft&&Oe.addToRenderList(g,y),this.info.render.frame++,me===!0&&Ee.beginShadows();const N=A.state.shadowsArray;De.render(N,y,R),me===!0&&Ee.endShadows(),this.info.autoReset===!0&&this.info.reset();const U=g.opaque,P=g.transmissive;if(A.setupLights(),R.isArrayCamera){const z=R.cameras;if(P.length>0)for(let j=0,X=z.length;j<X;j++){const ie=z[j];zh(U,P,y,ie)}ft&&Oe.render(y);for(let j=0,X=z.length;j<X;j++){const ie=z[j];wc(g,y,ie,ie.viewport)}}else P.length>0&&zh(U,P,y,R),ft&&Oe.render(y),wc(g,y,R);T!==null&&I===0&&(L.updateMultisampleRenderTarget(T),L.updateRenderTargetMipmap(T)),y.isScene===!0&&y.onAfterRender(E,y,R),it.resetDefaultState(),C=-1,v=null,x.pop(),x.length>0?(A=x[x.length-1],me===!0&&Ee.setGlobalState(E.clippingPlanes,A.state.camera)):A=null,_.pop(),_.length>0?g=_[_.length-1]:g=null};function _c(y,R,N,U){if(y.visible===!1)return;if(y.layers.test(R.layers)){if(y.isGroup)N=y.renderOrder;else if(y.isLOD)y.autoUpdate===!0&&y.update(R);else if(y.isLight)A.pushLight(y),y.castShadow&&A.pushShadow(y);else if(y.isSprite){if(!y.frustumCulled||se.intersectsSprite(y)){U&&He.setFromMatrixPosition(y.matrixWorld).applyMatrix4(Ue);const j=oe.update(y),X=y.material;X.visible&&g.push(y,j,X,N,He.z,null)}}else if((y.isMesh||y.isLine||y.isPoints)&&(!y.frustumCulled||se.intersectsObject(y))){const j=oe.update(y),X=y.material;if(U&&(y.boundingSphere!==void 0?(y.boundingSphere===null&&y.computeBoundingSphere(),He.copy(y.boundingSphere.center)):(j.boundingSphere===null&&j.computeBoundingSphere(),He.copy(j.boundingSphere.center)),He.applyMatrix4(y.matrixWorld).applyMatrix4(Ue)),Array.isArray(X)){const ie=j.groups;for(let he=0,ce=ie.length;he<ce;he++){const fe=ie[he],ge=X[fe.materialIndex];ge&&ge.visible&&g.push(y,j,ge,N,He.z,fe)}}else X.visible&&g.push(y,j,X,N,He.z,null)}}const z=y.children;for(let j=0,X=z.length;j<X;j++)_c(z[j],R,N,U)}function wc(y,R,N,U){const P=y.opaque,z=y.transmissive,j=y.transparent;A.setupLightsView(N),me===!0&&Ee.setGlobalState(E.clippingPlanes,N),U&&We.viewport(F.copy(U)),P.length>0&&eo(P,R,N),z.length>0&&eo(z,R,N),j.length>0&&eo(j,R,N),We.buffers.depth.setTest(!0),We.buffers.depth.setMask(!0),We.buffers.color.setMask(!0),We.setPolygonOffset(!1)}function zh(y,R,N,U){if((N.isScene===!0?N.overrideMaterial:null)!==null)return;A.state.transmissionRenderTarget[U.id]===void 0&&(A.state.transmissionRenderTarget[U.id]=new or(1,1,{generateMipmaps:!0,type:pt.has("EXT_color_buffer_half_float")||pt.has("EXT_color_buffer_float")?kn:cn,minFilter:ri,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:tt.workingColorSpace}));const z=A.state.transmissionRenderTarget[U.id],j=U.viewport||F;z.setSize(j.z*E.transmissionResolutionScale,j.w*E.transmissionResolutionScale);const X=E.getRenderTarget();E.setRenderTarget(z),E.getClearColor($),D=E.getClearAlpha(),D<1&&E.setClearColor(16777215,.5),E.clear(),ft&&Oe.render(N);const ie=E.toneMapping;E.toneMapping=Is;const he=U.viewport;if(U.viewport!==void 0&&(U.viewport=void 0),A.setupLightsView(U),me===!0&&Ee.setGlobalState(E.clippingPlanes,U),eo(y,N,U),L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z),pt.has("WEBGL_multisampled_render_to_texture")===!1){let ce=!1;for(let fe=0,ge=R.length;fe<ge;fe++){const ye=R[fe],Pe=ye.object,je=ye.geometry,Ve=ye.material,Le=ye.group;if(Ve.side===Pi&&Pe.layers.test(U.layers)){const rt=Ve.side;Ve.side=Ln,Ve.needsUpdate=!0,Vh(Pe,N,U,je,Ve,Le),Ve.side=rt,Ve.needsUpdate=!0,ce=!0}}ce===!0&&(L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z))}E.setRenderTarget(X),E.setClearColor($,D),he!==void 0&&(U.viewport=he),E.toneMapping=ie}function eo(y,R,N){const U=R.isScene===!0?R.overrideMaterial:null;for(let P=0,z=y.length;P<z;P++){const j=y[P],X=j.object,ie=j.geometry,he=j.group;let ce=j.material;ce.allowOverride===!0&&U!==null&&(ce=U),X.layers.test(N.layers)&&Vh(X,R,N,ie,ce,he)}}function Vh(y,R,N,U,P,z){y.onBeforeRender(E,R,N,U,P,z),y.modelViewMatrix.multiplyMatrices(N.matrixWorldInverse,y.matrixWorld),y.normalMatrix.getNormalMatrix(y.modelViewMatrix),P.onBeforeRender(E,R,N,U,y,z),P.transparent===!0&&P.side===Pi&&P.forceSinglePass===!1?(P.side=Ln,P.needsUpdate=!0,E.renderBufferDirect(N,R,U,P,y,z),P.side=ji,P.needsUpdate=!0,E.renderBufferDirect(N,R,U,P,y,z),P.side=Pi):E.renderBufferDirect(N,R,U,P,y,z),y.onAfterRender(E,R,N,U,P,z)}function to(y,R,N){R.isScene!==!0&&(R=Mt);const U=ze.get(y),P=A.state.lights,z=A.state.shadowsArray,j=P.state.version,X=Qe.getParameters(y,P.state,z,R,N),ie=Qe.getProgramCacheKey(X);let he=U.programs;U.environment=y.isMeshStandardMaterial?R.environment:null,U.fog=R.fog,U.envMap=(y.isMeshStandardMaterial?Z:M).get(y.envMap||U.environment),U.envMapRotation=U.environment!==null&&y.envMap===null?R.environmentRotation:y.envMapRotation,he===void 0&&(y.addEventListener("dispose",st),he=new Map,U.programs=he);let ce=he.get(ie);if(ce!==void 0){if(U.currentProgram===ce&&U.lightsStateVersion===j)return Cc(y,X),ce}else X.uniforms=Qe.getUniforms(y),y.onBeforeCompile(X,E),ce=Qe.acquireProgram(X,ie),he.set(ie,ce),U.uniforms=X.uniforms;const fe=U.uniforms;return(!y.isShaderMaterial&&!y.isRawShaderMaterial||y.clipping===!0)&&(fe.clippingPlanes=Ee.uniform),Cc(y,X),U.needsLights=tr(y),U.lightsStateVersion=j,U.needsLights&&(fe.ambientLightColor.value=P.state.ambient,fe.lightProbe.value=P.state.probe,fe.directionalLights.value=P.state.directional,fe.directionalLightShadows.value=P.state.directionalShadow,fe.spotLights.value=P.state.spot,fe.spotLightShadows.value=P.state.spotShadow,fe.rectAreaLights.value=P.state.rectArea,fe.ltc_1.value=P.state.rectAreaLTC1,fe.ltc_2.value=P.state.rectAreaLTC2,fe.pointLights.value=P.state.point,fe.pointLightShadows.value=P.state.pointShadow,fe.hemisphereLights.value=P.state.hemi,fe.directionalShadowMap.value=P.state.directionalShadowMap,fe.directionalShadowMatrix.value=P.state.directionalShadowMatrix,fe.spotShadowMap.value=P.state.spotShadowMap,fe.spotLightMatrix.value=P.state.spotLightMatrix,fe.spotLightMap.value=P.state.spotLightMap,fe.pointShadowMap.value=P.state.pointShadowMap,fe.pointShadowMatrix.value=P.state.pointShadowMatrix),U.currentProgram=ce,U.uniformsList=null,ce}function vc(y){if(y.uniformsList===null){const R=y.currentProgram.getUniforms();y.uniformsList=Nl.seqWithValue(R.seq,y.uniforms)}return y.uniformsList}function Cc(y,R){const N=ze.get(y);N.outputColorSpace=R.outputColorSpace,N.batching=R.batching,N.batchingColor=R.batchingColor,N.instancing=R.instancing,N.instancingColor=R.instancingColor,N.instancingMorph=R.instancingMorph,N.skinning=R.skinning,N.morphTargets=R.morphTargets,N.morphNormals=R.morphNormals,N.morphColors=R.morphColors,N.morphTargetsCount=R.morphTargetsCount,N.numClippingPlanes=R.numClippingPlanes,N.numIntersection=R.numClipIntersection,N.vertexAlphas=R.vertexAlphas,N.vertexTangents=R.vertexTangents,N.toneMapping=R.toneMapping}function Hp(y,R,N,U,P){R.isScene!==!0&&(R=Mt),L.resetTextureUnits();const z=R.fog,j=U.isMeshStandardMaterial?R.environment:null,X=T===null?E.outputColorSpace:T.isXRRenderTarget===!0?T.texture.colorSpace:un,ie=(U.isMeshStandardMaterial?Z:M).get(U.envMap||j),he=U.vertexColors===!0&&!!N.attributes.color&&N.attributes.color.itemSize===4,ce=!!N.attributes.tangent&&(!!U.normalMap||U.anisotropy>0),fe=!!N.morphAttributes.position,ge=!!N.morphAttributes.normal,ye=!!N.morphAttributes.color;let Pe=Is;U.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(Pe=E.toneMapping);const je=N.morphAttributes.position||N.morphAttributes.normal||N.morphAttributes.color,Ve=je!==void 0?je.length:0,Le=ze.get(U),rt=A.state.lights;if(me===!0&&(xe===!0||y!==v)){const Ut=y===v&&U.id===C;Ee.setState(U,y,Ut)}let ke=!1;U.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==rt.state.version||Le.outputColorSpace!==X||P.isBatchedMesh&&Le.batching===!1||!P.isBatchedMesh&&Le.batching===!0||P.isBatchedMesh&&Le.batchingColor===!0&&P.colorTexture===null||P.isBatchedMesh&&Le.batchingColor===!1&&P.colorTexture!==null||P.isInstancedMesh&&Le.instancing===!1||!P.isInstancedMesh&&Le.instancing===!0||P.isSkinnedMesh&&Le.skinning===!1||!P.isSkinnedMesh&&Le.skinning===!0||P.isInstancedMesh&&Le.instancingColor===!0&&P.instanceColor===null||P.isInstancedMesh&&Le.instancingColor===!1&&P.instanceColor!==null||P.isInstancedMesh&&Le.instancingMorph===!0&&P.morphTexture===null||P.isInstancedMesh&&Le.instancingMorph===!1&&P.morphTexture!==null||Le.envMap!==ie||U.fog===!0&&Le.fog!==z||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Ee.numPlanes||Le.numIntersection!==Ee.numIntersection)||Le.vertexAlphas!==he||Le.vertexTangents!==ce||Le.morphTargets!==fe||Le.morphNormals!==ge||Le.morphColors!==ye||Le.toneMapping!==Pe||Le.morphTargetsCount!==Ve)&&(ke=!0):(ke=!0,Le.__version=U.version);let It=Le.currentProgram;ke===!0&&(It=to(U,R,P));let mn=!1,vt=!1,Et=!1;const Xe=It.getUniforms(),Xt=Le.uniforms;if(We.useProgram(It.program)&&(mn=!0,vt=!0,Et=!0),U.id!==C&&(C=U.id,vt=!0),mn||v!==y){We.buffers.depth.getReversed()?(be.copy(y.projectionMatrix),E_(be),y_(be),Xe.setValue(H,"projectionMatrix",be)):Xe.setValue(H,"projectionMatrix",y.projectionMatrix),Xe.setValue(H,"viewMatrix",y.matrixWorldInverse);const xn=Xe.map.cameraPosition;xn!==void 0&&xn.setValue(H,et.setFromMatrixPosition(y.matrixWorld)),mt.logarithmicDepthBuffer&&Xe.setValue(H,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2)),(U.isMeshPhongMaterial||U.isMeshToonMaterial||U.isMeshLambertMaterial||U.isMeshBasicMaterial||U.isMeshStandardMaterial||U.isShaderMaterial)&&Xe.setValue(H,"isOrthographic",y.isOrthographicCamera===!0),v!==y&&(v=y,vt=!0,Et=!0)}if(P.isSkinnedMesh){Xe.setOptional(H,P,"bindMatrix"),Xe.setOptional(H,P,"bindMatrixInverse");const Ut=P.skeleton;Ut&&(Ut.boneTexture===null&&Ut.computeBoneTexture(),Xe.setValue(H,"boneTexture",Ut.boneTexture,L))}P.isBatchedMesh&&(Xe.setOptional(H,P,"batchingTexture"),Xe.setValue(H,"batchingTexture",P._matricesTexture,L),Xe.setOptional(H,P,"batchingIdTexture"),Xe.setValue(H,"batchingIdTexture",P._indirectTexture,L),Xe.setOptional(H,P,"batchingColorTexture"),P._colorsTexture!==null&&Xe.setValue(H,"batchingColorTexture",P._colorsTexture,L));const Cn=N.morphAttributes;if((Cn.position!==void 0||Cn.normal!==void 0||Cn.color!==void 0)&&Ge.update(P,N,It),(vt||Le.receiveShadow!==P.receiveShadow)&&(Le.receiveShadow=P.receiveShadow,Xe.setValue(H,"receiveShadow",P.receiveShadow)),U.isMeshGouraudMaterial&&U.envMap!==null&&(Xt.envMap.value=ie,Xt.flipEnvMap.value=ie.isCubeTexture&&ie.isRenderTargetTexture===!1?-1:1),U.isMeshStandardMaterial&&U.envMap===null&&R.environment!==null&&(Xt.envMapIntensity.value=R.environmentIntensity),vt&&(Xe.setValue(H,"toneMappingExposure",E.toneMappingExposure),Le.needsLights&&vs(Xt,Et),z&&U.fog===!0&&ve.refreshFogUniforms(Xt,z),ve.refreshMaterialUniforms(Xt,U,Q,Y,A.state.transmissionRenderTarget[y.id]),Nl.upload(H,vc(Le),Xt,L)),U.isShaderMaterial&&U.uniformsNeedUpdate===!0&&(Nl.upload(H,vc(Le),Xt,L),U.uniformsNeedUpdate=!1),U.isSpriteMaterial&&Xe.setValue(H,"center",P.center),Xe.setValue(H,"modelViewMatrix",P.modelViewMatrix),Xe.setValue(H,"normalMatrix",P.normalMatrix),Xe.setValue(H,"modelMatrix",P.matrixWorld),U.isShaderMaterial||U.isRawShaderMaterial){const Ut=U.uniformsGroups;for(let xn=0,zp=Ut.length;xn<zp;xn++){const Wr=Ut[xn];W.update(Wr,It),W.bind(Wr,It)}}return It}function vs(y,R){y.ambientLightColor.needsUpdate=R,y.lightProbe.needsUpdate=R,y.directionalLights.needsUpdate=R,y.directionalLightShadows.needsUpdate=R,y.pointLights.needsUpdate=R,y.pointLightShadows.needsUpdate=R,y.spotLights.needsUpdate=R,y.spotLightShadows.needsUpdate=R,y.rectAreaLights.needsUpdate=R,y.hemisphereLights.needsUpdate=R}function tr(y){return y.isMeshLambertMaterial||y.isMeshToonMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isShadowMaterial||y.isShaderMaterial&&y.lights===!0}this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return I},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(y,R,N){const U=ze.get(y);U.__autoAllocateDepthBuffer=y.resolveDepthBuffer===!1,U.__autoAllocateDepthBuffer===!1&&(U.__useRenderToTexture=!1),ze.get(y.texture).__webglTexture=R,ze.get(y.depthTexture).__webglTexture=U.__autoAllocateDepthBuffer?void 0:N,U.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(y,R){const N=ze.get(y);N.__webglFramebuffer=R,N.__useDefaultFramebuffer=R===void 0};const b=H.createFramebuffer();this.setRenderTarget=function(y,R=0,N=0){T=y,w=R,I=N;let U=!0,P=null,z=!1,j=!1;if(y){const ie=ze.get(y);if(ie.__useDefaultFramebuffer!==void 0)We.bindFramebuffer(H.FRAMEBUFFER,null),U=!1;else if(ie.__webglFramebuffer===void 0)L.setupRenderTarget(y);else if(ie.__hasExternalTextures)L.rebindTextures(y,ze.get(y.texture).__webglTexture,ze.get(y.depthTexture).__webglTexture);else if(y.depthBuffer){const fe=y.depthTexture;if(ie.__boundDepthTexture!==fe){if(fe!==null&&ze.has(fe)&&(y.width!==fe.image.width||y.height!==fe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(y)}}const he=y.texture;(he.isData3DTexture||he.isDataArrayTexture||he.isCompressedArrayTexture)&&(j=!0);const ce=ze.get(y).__webglFramebuffer;y.isWebGLCubeRenderTarget?(Array.isArray(ce[R])?P=ce[R][N]:P=ce[R],z=!0):y.samples>0&&L.useMultisampledRTT(y)===!1?P=ze.get(y).__webglMultisampledFramebuffer:Array.isArray(ce)?P=ce[N]:P=ce,F.copy(y.viewport),K.copy(y.scissor),q=y.scissorTest}else F.copy(ae).multiplyScalar(Q).floor(),K.copy(_e).multiplyScalar(Q).floor(),q=Me;if(N!==0&&(P=b),We.bindFramebuffer(H.FRAMEBUFFER,P)&&U&&We.drawBuffers(y,P),We.viewport(F),We.scissor(K),We.setScissorTest(q),z){const ie=ze.get(y.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+R,ie.__webglTexture,N)}else if(j){const ie=ze.get(y.texture),he=R;H.framebufferTextureLayer(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,ie.__webglTexture,N,he)}else if(y!==null&&N!==0){const ie=ze.get(y.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,ie.__webglTexture,N)}C=-1},this.readRenderTargetPixels=function(y,R,N,U,P,z,j){if(!(y&&y.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let X=ze.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&j!==void 0&&(X=X[j]),X){We.bindFramebuffer(H.FRAMEBUFFER,X);try{const ie=y.texture,he=ie.format,ce=ie.type;if(!mt.textureFormatReadable(he)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!mt.textureTypeReadable(ce)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}R>=0&&R<=y.width-U&&N>=0&&N<=y.height-P&&H.readPixels(R,N,U,P,Ke.convert(he),Ke.convert(ce),z)}finally{const ie=T!==null?ze.get(T).__webglFramebuffer:null;We.bindFramebuffer(H.FRAMEBUFFER,ie)}}},this.readRenderTargetPixelsAsync=async function(y,R,N,U,P,z,j){if(!(y&&y.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let X=ze.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&j!==void 0&&(X=X[j]),X)if(R>=0&&R<=y.width-U&&N>=0&&N<=y.height-P){We.bindFramebuffer(H.FRAMEBUFFER,X);const ie=y.texture,he=ie.format,ce=ie.type;if(!mt.textureFormatReadable(he))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!mt.textureTypeReadable(ce))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const fe=H.createBuffer();H.bindBuffer(H.PIXEL_PACK_BUFFER,fe),H.bufferData(H.PIXEL_PACK_BUFFER,z.byteLength,H.STREAM_READ),H.readPixels(R,N,U,P,Ke.convert(he),Ke.convert(ce),0);const ge=T!==null?ze.get(T).__webglFramebuffer:null;We.bindFramebuffer(H.FRAMEBUFFER,ge);const ye=H.fenceSync(H.SYNC_GPU_COMMANDS_COMPLETE,0);return H.flush(),await b_(H,ye,4),H.bindBuffer(H.PIXEL_PACK_BUFFER,fe),H.getBufferSubData(H.PIXEL_PACK_BUFFER,0,z),H.deleteBuffer(fe),H.deleteSync(ye),z}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(y,R=null,N=0){const U=Math.pow(2,-N),P=Math.floor(y.image.width*U),z=Math.floor(y.image.height*U),j=R!==null?R.x:0,X=R!==null?R.y:0;L.setTexture2D(y,0),H.copyTexSubImage2D(H.TEXTURE_2D,N,0,0,j,X,P,z),We.unbindTexture()};const B=H.createFramebuffer(),k=H.createFramebuffer();this.copyTextureToTexture=function(y,R,N=null,U=null,P=0,z=null){z===null&&(P!==0?(Vc("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),z=P,P=0):z=0);let j,X,ie,he,ce,fe,ge,ye,Pe;const je=y.isCompressedTexture?y.mipmaps[z]:y.image;if(N!==null)j=N.max.x-N.min.x,X=N.max.y-N.min.y,ie=N.isBox3?N.max.z-N.min.z:1,he=N.min.x,ce=N.min.y,fe=N.isBox3?N.min.z:0;else{const Cn=Math.pow(2,-P);j=Math.floor(je.width*Cn),X=Math.floor(je.height*Cn),y.isDataArrayTexture?ie=je.depth:y.isData3DTexture?ie=Math.floor(je.depth*Cn):ie=1,he=0,ce=0,fe=0}U!==null?(ge=U.x,ye=U.y,Pe=U.z):(ge=0,ye=0,Pe=0);const Ve=Ke.convert(R.format),Le=Ke.convert(R.type);let rt;R.isData3DTexture?(L.setTexture3D(R,0),rt=H.TEXTURE_3D):R.isDataArrayTexture||R.isCompressedArrayTexture?(L.setTexture2DArray(R,0),rt=H.TEXTURE_2D_ARRAY):(L.setTexture2D(R,0),rt=H.TEXTURE_2D),H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,R.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,R.unpackAlignment);const ke=H.getParameter(H.UNPACK_ROW_LENGTH),It=H.getParameter(H.UNPACK_IMAGE_HEIGHT),mn=H.getParameter(H.UNPACK_SKIP_PIXELS),vt=H.getParameter(H.UNPACK_SKIP_ROWS),Et=H.getParameter(H.UNPACK_SKIP_IMAGES);H.pixelStorei(H.UNPACK_ROW_LENGTH,je.width),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,je.height),H.pixelStorei(H.UNPACK_SKIP_PIXELS,he),H.pixelStorei(H.UNPACK_SKIP_ROWS,ce),H.pixelStorei(H.UNPACK_SKIP_IMAGES,fe);const Xe=y.isDataArrayTexture||y.isData3DTexture,Xt=R.isDataArrayTexture||R.isData3DTexture;if(y.isDepthTexture){const Cn=ze.get(y),Ut=ze.get(R),xn=ze.get(Cn.__renderTarget),zp=ze.get(Ut.__renderTarget);We.bindFramebuffer(H.READ_FRAMEBUFFER,xn.__webglFramebuffer),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,zp.__webglFramebuffer);for(let Wr=0;Wr<ie;Wr++)Xe&&(H.framebufferTextureLayer(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,ze.get(y).__webglTexture,P,fe+Wr),H.framebufferTextureLayer(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,ze.get(R).__webglTexture,z,Pe+Wr)),H.blitFramebuffer(he,ce,j,X,ge,ye,j,X,H.DEPTH_BUFFER_BIT,H.NEAREST);We.bindFramebuffer(H.READ_FRAMEBUFFER,null),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,null)}else if(P!==0||y.isRenderTargetTexture||ze.has(y)){const Cn=ze.get(y),Ut=ze.get(R);We.bindFramebuffer(H.READ_FRAMEBUFFER,B),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,k);for(let xn=0;xn<ie;xn++)Xe?H.framebufferTextureLayer(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,Cn.__webglTexture,P,fe+xn):H.framebufferTexture2D(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,Cn.__webglTexture,P),Xt?H.framebufferTextureLayer(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,Ut.__webglTexture,z,Pe+xn):H.framebufferTexture2D(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,Ut.__webglTexture,z),P!==0?H.blitFramebuffer(he,ce,j,X,ge,ye,j,X,H.COLOR_BUFFER_BIT,H.NEAREST):Xt?H.copyTexSubImage3D(rt,z,ge,ye,Pe+xn,he,ce,j,X):H.copyTexSubImage2D(rt,z,ge,ye,he,ce,j,X);We.bindFramebuffer(H.READ_FRAMEBUFFER,null),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,null)}else Xt?y.isDataTexture||y.isData3DTexture?H.texSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,Le,je.data):R.isCompressedArrayTexture?H.compressedTexSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,je.data):H.texSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,Le,je):y.isDataTexture?H.texSubImage2D(H.TEXTURE_2D,z,ge,ye,j,X,Ve,Le,je.data):y.isCompressedTexture?H.compressedTexSubImage2D(H.TEXTURE_2D,z,ge,ye,je.width,je.height,Ve,je.data):H.texSubImage2D(H.TEXTURE_2D,z,ge,ye,j,X,Ve,Le,je);H.pixelStorei(H.UNPACK_ROW_LENGTH,ke),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,It),H.pixelStorei(H.UNPACK_SKIP_PIXELS,mn),H.pixelStorei(H.UNPACK_SKIP_ROWS,vt),H.pixelStorei(H.UNPACK_SKIP_IMAGES,Et),z===0&&R.generateMipmaps&&H.generateMipmap(rt),We.unbindTexture()},this.copyTextureToTexture3D=function(y,R,N=null,U=null,P=0){return Vc('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(y,R,N,U,P)},this.initRenderTarget=function(y){ze.get(y).__webglFramebuffer===void 0&&L.setupRenderTarget(y)},this.initTexture=function(y){y.isCubeTexture?L.setTextureCube(y,0):y.isData3DTexture?L.setTexture3D(y,0):y.isDataArrayTexture||y.isCompressedArrayTexture?L.setTexture2DArray(y,0):L.setTexture2D(y,0),We.unbindTexture()},this.resetState=function(){w=0,I=0,T=null,We.reset(),it.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Yi}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=tt._getDrawingBufferColorSpace(e),t.unpackColorSpace=tt._getUnpackColorSpace()}}var Lo=function(){var i=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(h){h.preventDefault(),n(++i%e.children.length)},!1);function t(h){return e.appendChild(h.dom),h}function n(h){for(var u=0;u<e.children.length;u++)e.children[u].style.display=u===h?"block":"none";i=h}var s=(performance||Date).now(),r=s,a=0,o=t(new Lo.Panel("FPS","#0ff","#002")),c=t(new Lo.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var l=t(new Lo.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:e,addPanel:t,showPanel:n,begin:function(){s=(performance||Date).now()},end:function(){a++;var h=(performance||Date).now();if(c.update(h-s,200),h>=r+1e3&&(o.update(a*1e3/(h-r),100),r=h,a=0,l)){var u=performance.memory;l.update(u.usedJSHeapSize/1048576,u.jsHeapSizeLimit/1048576)}return h},update:function(){s=this.end()},domElement:e,setMode:n}};Lo.Panel=function(i,e,t){var n=1/0,s=0,r=Math.round,a=r(window.devicePixelRatio||1),o=80*a,c=48*a,l=3*a,h=2*a,u=3*a,d=15*a,f=74*a,p=30*a,m=document.createElement("canvas");m.width=o,m.height=c,m.style.cssText="width:80px;height:48px";var g=m.getContext("2d");return g.font="bold "+9*a+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=t,g.fillRect(0,0,o,c),g.fillStyle=e,g.fillText(i,l,h),g.fillRect(u,d,f,p),g.fillStyle=t,g.globalAlpha=.9,g.fillRect(u,d,f,p),{dom:m,update:function(A,_){n=Math.min(n,A),s=Math.max(s,A),g.fillStyle=t,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=e,g.fillText(r(A)+" "+i+" ("+r(n)+"-"+r(s)+")",l,h),g.drawImage(m,u+a,d,f-a,p,u,d,f-a,p),g.fillRect(u+f-a,d,a,p),g.fillStyle=t,g.globalAlpha=.9,g.fillRect(u+f-a,d,a,r((1-A/_)*p))}}};function em(i,e){if(e===Wy)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===Mu||e===oA){let t=i.getIndex();if(t===null){const a=[],o=i.getAttribute("position");if(o!==void 0){for(let c=0;c<o.count;c++)a.push(c);i.setIndex(a),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===Mu)for(let a=1;a<=n;a++)s.push(t.getX(0)),s.push(t.getX(a)),s.push(t.getX(a+1));else for(let a=0;a<n;a++)a%2===0?(s.push(t.getX(a)),s.push(t.getX(a+1)),s.push(t.getX(a+2))):(s.push(t.getX(a+2)),s.push(t.getX(a+1)),s.push(t.getX(a)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}class Bd extends ci{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new h1(t)}),this.register(function(t){return new u1(t)}),this.register(function(t){return new E1(t)}),this.register(function(t){return new y1(t)}),this.register(function(t){return new _1(t)}),this.register(function(t){return new f1(t)}),this.register(function(t){return new p1(t)}),this.register(function(t){return new A1(t)}),this.register(function(t){return new g1(t)}),this.register(function(t){return new l1(t)}),this.register(function(t){return new m1(t)}),this.register(function(t){return new d1(t)}),this.register(function(t){return new b1(t)}),this.register(function(t){return new x1(t)}),this.register(function(t){return new o1(t)}),this.register(function(t){return new w1(t)}),this.register(function(t){return new v1(t)})}load(e,t,n,s){const r=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const l=Ar.extractUrlBase(e);a=Ar.resolveURL(l,this.path)}else a=Ar.extractUrlBase(e);this.manager.itemStart(e);const o=function(l){s?s(l):console.error(l),r.manager.itemError(e),r.manager.itemEnd(e)},c=new os(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(l){try{r.parse(l,a,function(h){t(h),r.manager.itemEnd(e)},o)}catch(h){o(h)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const a={},o={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===tm){try{a[At.KHR_BINARY_GLTF]=new C1(e)}catch(u){s&&s(u);return}r=JSON.parse(a[At.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new U1(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const u=this.pluginCallbacks[h](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[u.name]=u,a[u.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){const u=r.extensionsUsed[h],d=r.extensionsRequired||[];switch(u){case At.KHR_MATERIALS_UNLIT:a[u]=new c1;break;case At.KHR_DRACO_MESH_COMPRESSION:a[u]=new I1(r,this.dracoLoader);break;case At.KHR_TEXTURE_TRANSFORM:a[u]=new S1;break;case At.KHR_MESH_QUANTIZATION:a[u]=new M1;break;default:d.indexOf(u)>=0&&o[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(a),l.setPlugins(o),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function a1(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}const At={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class o1{constructor(e){this.parser=e,this.name=At.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let l;const h=new Fe(16777215);c.color!==void 0&&h.setRGB(c.color[0],c.color[1],c.color[2],un);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new gd(h),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new Ml(h),l.distance=u;break;case"spot":l=new mg(h),l.distance=u,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,l.angle=c.spot.outerConeAngle,l.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return l.position.set(0,0,0),cs(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],o=(r.extensions&&r.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(c){return n._getNodeRef(t.cache,o,c)})}}class c1{constructor(){this.name=At.KHR_MATERIALS_UNLIT}getMaterialType(){return Ds}extendParams(e,t,n){const s=[];e.color=new Fe(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const a=r.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],un),e.opacity=a[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,yt))}return Promise.all(s)}}class l1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}}class h1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(r.push(n.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Je(o,o)}return Promise.all(r)}}class u1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}}class d1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(r)}}class f1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new Fe(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=s.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],un)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&r.push(n.assignTexture(t,"sheenColorMap",a.sheenColorTexture,yt)),a.sheenRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(r)}}class p1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&r.push(n.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(r)}}class A1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&r.push(n.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new Fe().setRGB(o[0],o[1],o[2],un),Promise.all(r)}}class g1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}}class m1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&r.push(n.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new Fe().setRGB(o[0],o[1],o[2],un),a.specularColorTexture!==void 0&&r.push(n.assignTexture(t,"specularColorMap",a.specularColorTexture,yt)),Promise.all(r)}}class x1{constructor(e){this.parser=e,this.name=At.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&r.push(n.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(r)}}class b1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&r.push(n.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(r)}}class E1{constructor(e){this.parser=e,this.name=At.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,a)}}class y1{constructor(e){this.parser=e,this.name=At.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=s.images[a.source];let c=n.textureLoader;if(o.uri){const l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}}class _1{constructor(e){this.parser=e,this.name=At.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=s.images[a.source];let c=n.textureLoader;if(o.uri){const l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}}class w1{constructor(e){this.name=At.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(o){const c=s.byteOffset||0,l=s.byteLength||0,h=s.count,u=s.byteStride,d=new Uint8Array(o,c,l);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,s.mode,s.filter).then(function(f){return f.buffer}):a.ready.then(function(){const f=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(f),h,u,d,s.mode,s.filter),f})})}else return null}}class v1{constructor(e){this.name=At.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const l of s.primitives)if(l.mode!==li.TRIANGLES&&l.mode!==li.TRIANGLE_STRIP&&l.mode!==li.TRIANGLE_FAN&&l.mode!==void 0)return null;const a=n.extensions[this.name].attributes,o=[],c={};for(const l in a)o.push(this.parser.getDependency("accessor",a[l]).then(h=>(c[l]=h,c[l])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(l=>{const h=l.pop(),u=h.isGroup?h.children:[h],d=l[0].count,f=[];for(const p of u){const m=new Re,g=new G,A=new Yt,_=new G(1,1,1),x=new jA(p.geometry,p.material,d);for(let E=0;E<d;E++)c.TRANSLATION&&g.fromBufferAttribute(c.TRANSLATION,E),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,E),c.SCALE&&_.fromBufferAttribute(c.SCALE,E),x.setMatrixAt(E,m.compose(g,A,_));for(const E in c)if(E==="_COLOR_0"){const S=c[E];x.instanceColor=new id(S.array,S.itemSize,S.normalized)}else E!=="TRANSLATION"&&E!=="ROTATION"&&E!=="SCALE"&&p.geometry.setAttribute(E,c[E]);Tt.prototype.copy.call(x,p),this.parser.assignFinalMaterial(x),f.push(x)}return h.isGroup?(h.clear(),h.add(...f),h):f[0]}))}}const tm="glTF",Po=12,nm={JSON:1313821514,BIN:5130562};class C1{constructor(e){this.name=At.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Po),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==tm)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-Po,r=new DataView(e,Po);let a=0;for(;a<s;){const o=r.getUint32(a,!0);a+=4;const c=r.getUint32(a,!0);if(a+=4,c===nm.JSON){const l=new Uint8Array(e,Po+a,o);this.content=n.decode(l)}else if(c===nm.BIN){const l=Po+a;this.body=e.slice(l,l+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class I1{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=At.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},c={},l={};for(const h in a){const u=Rd[h]||h.toLowerCase();o[u]=a[h]}for(const h in e.attributes){const u=Rd[h]||h.toLowerCase();if(a[h]!==void 0){const d=n.accessors[e.attributes[h]],f=va[d.componentType];l[u]=f.name,c[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(u,d){s.decodeDracoFile(h,function(f){for(const p in f.attributes){const m=f.attributes[p],g=c[p];g!==void 0&&(m.normalized=g)}u(f)},o,l,un,d)})})}}class S1{constructor(){this.name=At.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class M1{constructor(){this.name=At.KHR_MESH_QUANTIZATION}}class im extends Ro{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let a=0;a!==s;a++)t[a]=n[r+a];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=o*2,l=o*3,h=s-t,u=(n-t)/h,d=u*u,f=d*u,p=e*l,m=p-l,g=-2*f+3*d,A=f-d,_=1-g,x=A-d+u;for(let E=0;E!==o;E++){const S=a[m+E+o],w=a[m+E+c]*h,I=a[p+E+o],T=a[p+E]*h;r[E]=_*S+x*w+g*I+A*T}return r}}const B1=new Yt;class T1 extends im{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return B1.fromArray(r).normalize().toArray(r),r}}const li={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},va={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},sm={9728:Pn,9729:qt,9984:Zp,9985:Rc,9986:no,9987:ri},rm={33071:Zn,33648:Tc,10497:Ss},Td={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Rd={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Qs={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},R1={CUBICSPLINE:void 0,LINEAR:po,STEP:fo},Fd={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function F1(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new To({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:ji})),i.DefaultMaterial}function Er(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function cs(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function N1(i,e,t){let n=!1,s=!1,r=!1;for(let l=0,h=e.length;l<h;l++){const u=e[l];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(s=!0),u.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const a=[],o=[],c=[];for(let l=0,h=e.length;l<h;l++){const u=e[l];if(n){const d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):i.attributes.position;a.push(d)}if(s){const d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):i.attributes.normal;o.push(d)}if(r){const d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):i.attributes.color;c.push(d)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c)]).then(function(l){const h=l[0],u=l[1],d=l[2];return n&&(i.morphAttributes.position=h),s&&(i.morphAttributes.normal=u),r&&(i.morphAttributes.color=d),i.morphTargetsRelative=!0,i})}function D1(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function L1(i){let e;const t=i.extensions&&i.extensions[At.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Nd(t.attributes):e=i.indices+":"+Nd(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Nd(i.targets[n]);return e}function Nd(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function Dd(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function P1(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const k1=new Re;class U1{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new a1,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,a=-1;if(typeof navigator<"u"){const o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;const c=o.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=o.indexOf("Firefox")>-1,a=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&a<98?this.textureLoader=new pg(this.options.manager):this.textureLoader=new Gw(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new os(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(a){const o={scene:a[0][s.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:s.asset,parser:n,userData:{}};return Er(r,o,s),cs(o,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(o)})).then(function(){for(const c of o.scenes)c.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const a=t[s].joints;for(let o=0,c=a.length;o<c;o++)e[a[o]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const a=e[s];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(n[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(a,o)=>{const c=this.associations.get(a);c!=null&&this.associations.set(o,c);for(const[l,h]of a.children.entries())r(h,o.children[l])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,a){return n.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[At.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,a){n.load(Ar.resolveURL(t.uri,s.path),r,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const a=Td[s.type],o=va[s.componentType],c=s.normalized===!0,l=new o(s.count*a);return Promise.resolve(new Sn(l,a,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(a){const o=a[0],c=Td[s.type],l=va[s.componentType],h=l.BYTES_PER_ELEMENT,u=h*c,d=s.byteOffset||0,f=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,p=s.normalized===!0;let m,g;if(f&&f!==u){const A=Math.floor(d/f),_="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let x=t.cache.get(_);x||(m=new l(o,A*f,s.count*f/h),x=new j_(m,f/h),t.cache.add(_,x)),g=new ed(x,c,d%f/h,p)}else o===null?m=new l(s.count*c):m=new l(o,d,s.count*c),g=new Sn(m,c,p);if(s.sparse!==void 0){const A=Td.SCALAR,_=va[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,E=s.sparse.values.byteOffset||0,S=new _(a[1],x,s.sparse.count*A),w=new l(a[2],E,s.sparse.count*c);o!==null&&(g=new Sn(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let I=0,T=S.length;I<T;I++){const C=S[I];if(g.setX(C,w[I*c]),c>=2&&g.setY(C,w[I*c+1]),c>=3&&g.setZ(C,w[I*c+2]),c>=4&&g.setW(C,w[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=p}return g})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,a=t.images[r];let o=this.textureLoader;if(a.uri){const c=n.manager.getHandler(a.uri);c!==null&&(o=c)}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,n){const s=this,r=this.json,a=r.textures[e],o=r.images[t],c=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[c])return this.textureCache[c];const l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(r.samplers||{})[a.sampler]||{};return h.magFilter=sm[d.magFilter]||qt,h.minFilter=sm[d.minFilter]||ri,h.wrapS=rm[d.wrapS]||Ss,h.wrapT=rm[d.wrapT]||Ss,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Pn&&h.minFilter!==qt,s.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const a=s.images[e],o=self.URL||self.webkitURL;let c=a.uri||"",l=!1;if(a.bufferView!==void 0)c=n.getDependency("bufferView",a.bufferView).then(function(u){l=!0;const d=new Blob([u],{type:a.mimeType});return c=o.createObjectURL(d),c});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(c).then(function(u){return new Promise(function(d,f){let p=d;t.isImageBitmapLoader===!0&&(p=function(m){const g=new nn(m);g.needsUpdate=!0,d(g)}),t.load(Ar.resolveURL(u,r.path),p,void 0,f)})}).then(function(u){return l===!0&&o.revokeObjectURL(c),cs(u,a),u.userData.mimeType=a.mimeType||P1(a.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),r.extensions[At.KHR_TEXTURE_TRANSFORM]){const o=n.extensions!==void 0?n.extensions[At.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const c=r.associations.get(a);a=r.extensions[At.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),r.associations.set(a,c)}}return s!==void 0&&(a.colorSpace=s),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+n.uuid;let c=this.cache.get(o);c||(c=new od,ai.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(o,c)),n=c}else if(e.isLine){const o="LineBasicMaterial:"+n.uuid;let c=this.cache.get(o);c||(c=new ma,ai.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(o,c)),n=c}if(s||r||a){let o="ClonedMaterial:"+n.uuid+":";s&&(o+="derivative-tangents:"),r&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let c=this.cache.get(o);c||(c=n.clone(),r&&(c.vertexColors=!0),a&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(o,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return To}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let a;const o={},c=r.extensions||{},l=[];if(c[At.KHR_MATERIALS_UNLIT]){const u=s[At.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),l.push(u.extendParams(o,r,t))}else{const u=r.pbrMetallicRoughness||{};if(o.color=new Fe(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){const d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],un),o.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(o,"map",u.baseColorTexture,yt)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}r.doubleSided===!0&&(o.side=Pi);const h=r.alphaMode||Fd.OPAQUE;if(h===Fd.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===Fd.MASK&&(o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&a!==Ds&&(l.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new Je(1,1),r.normalTexture.scale!==void 0)){const u=r.normalTexture.scale;o.normalScale.set(u,u)}if(r.occlusionTexture!==void 0&&a!==Ds&&(l.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&a!==Ds){const u=r.emissiveFactor;o.emissive=new Fe().setRGB(u[0],u[1],u[2],un)}return r.emissiveTexture!==void 0&&a!==Ds&&l.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,yt)),Promise.all(l).then(function(){const u=new a(o);return r.name&&(u.name=r.name),cs(u,r),t.associations.set(u,{materials:e}),r.extensions&&Er(s,u,r),u})}createUniqueName(e){const t=_t.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(o){return n[At.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(c){return am(c,o,t)})}const a=[];for(let o=0,c=e.length;o<c;o++){const l=e[o],h=L1(l),u=s[h];if(u)a.push(u.promise);else{let d;l.extensions&&l.extensions[At.KHR_DRACO_MESH_COMPRESSION]?d=r(l):d=am(new Mn,l,t),s[h]={primitive:l,promise:d},a.push(d)}}return Promise.all(a)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],a=r.primitives,o=[];for(let c=0,l=a.length;c<l;c++){const h=a[c].material===void 0?F1(this.cache):this.getDependency("material",a[c].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(c){const l=c.slice(0,c.length-1),h=c[c.length-1],u=[];for(let f=0,p=h.length;f<p;f++){const m=h[f],g=a[f];let A;const _=l[f];if(g.mode===li.TRIANGLES||g.mode===li.TRIANGLE_STRIP||g.mode===li.TRIANGLE_FAN||g.mode===void 0)A=r.isSkinnedMesh===!0?new VA(m,_):new Zt(m,_),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),g.mode===li.TRIANGLE_STRIP?A.geometry=em(A.geometry,oA):g.mode===li.TRIANGLE_FAN&&(A.geometry=em(A.geometry,Mu));else if(g.mode===li.LINES)A=new xl(m,_);else if(g.mode===li.LINE_STRIP)A=new gl(m,_);else if(g.mode===li.LINE_LOOP)A=new ew(m,_);else if(g.mode===li.POINTS)A=new tw(m,_);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(A.geometry.morphAttributes).length>0&&D1(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),cs(A,r),g.extensions&&Er(s,A,g),t.assignFinalMaterial(A),u.push(A)}for(let f=0,p=u.length;f<p;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1)return r.extensions&&Er(s,u[0],r),u[0];const d=new ss;r.extensions&&Er(s,d,r),t.associations.set(d,{meshes:e});for(let f=0,p=u.length;f<p;f++)d.add(u[f]);return d})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new Bn(In.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new Ad(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),cs(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),a=s,o=[],c=[];for(let l=0,h=a.length;l<h;l++){const u=a[l];if(u){o.push(u);const d=new Re;r!==null&&d.fromArray(r.array,l*16),c.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new hl(o,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,a=[],o=[],c=[],l=[],h=[];for(let u=0,d=s.channels.length;u<d;u++){const f=s.channels[u],p=s.samplers[f.sampler],m=f.target,g=m.node,A=s.parameters!==void 0?s.parameters[p.input]:p.input,_=s.parameters!==void 0?s.parameters[p.output]:p.output;m.node!==void 0&&(a.push(this.getDependency("node",g)),o.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",_)),l.push(p),h.push(m))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c),Promise.all(l),Promise.all(h)]).then(function(u){const d=u[0],f=u[1],p=u[2],m=u[3],g=u[4],A=[];for(let _=0,x=d.length;_<x;_++){const E=d[_],S=f[_],w=p[_],I=m[_],T=g[_];if(E===void 0)continue;E.updateMatrix&&E.updateMatrix();const C=n._createAnimationTracks(E,S,w,I,T);if(C)for(let v=0;v<C.length;v++)A.push(C[v])}return new Sl(r,void 0,A)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const a=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let c=0,l=s.weights.length;c<l;c++)o.morphTargetInfluences[c]=s.weights[c]}),a})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),a=[],o=s.children||[];for(let l=0,h=o.length;l<h;l++)a.push(n.getDependency("node",o[l]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(a),c]).then(function(l){const h=l[0],u=l[1],d=l[2];d!==null&&h.traverse(function(f){f.isSkinnedMesh&&f.bind(d,k1)});for(let f=0,p=u.length;f<p;f++)h.add(u[f]);return h})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],a=r.name?s.createUniqueName(r.name):"",o=[],c=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&o.push(c),r.camera!==void 0&&o.push(s.getDependency("camera",r.camera).then(function(l){return s._getNodeRef(s.cameraCache,r.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){o.push(l)}),this.nodeCache[e]=Promise.all(o).then(function(l){let h;if(r.isBone===!0?h=new cl:l.length>1?h=new ss:l.length===1?h=l[0]:h=new Tt,h!==l[0])for(let u=0,d=l.length;u<d;u++)h.add(l[u]);if(r.name&&(h.userData.name=r.name,h.name=a),cs(h,r),r.extensions&&Er(n,h,r),r.matrix!==void 0){const u=new Re;u.fromArray(r.matrix),h.applyMatrix4(u)}else r.translation!==void 0&&h.position.fromArray(r.translation),r.rotation!==void 0&&h.quaternion.fromArray(r.rotation),r.scale!==void 0&&h.scale.fromArray(r.scale);return s.associations.has(h)||s.associations.set(h,{}),s.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new ss;n.name&&(r.name=s.createUniqueName(n.name)),cs(r,n),n.extensions&&Er(t,r,n);const a=n.nodes||[],o=[];for(let c=0,l=a.length;c<l;c++)o.push(s.getDependency("node",a[c]));return Promise.all(o).then(function(c){for(let h=0,u=c.length;h<u;h++)r.add(c[h]);const l=h=>{const u=new Map;for(const[d,f]of s.associations)(d instanceof ai||d instanceof nn)&&u.set(d,f);return h.traverse(d=>{const f=s.associations.get(d);f!=null&&u.set(d,f)}),u};return s.associations=l(r),r})}_createAnimationTracks(e,t,n,s,r){const a=[],o=e.name?e.name:e.uuid,c=[];Qs[r.path]===Qs.weights?e.traverse(function(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}):c.push(o);let l;switch(Qs[r.path]){case Qs.weights:l=fr;break;case Qs.rotation:l=Us;break;case Qs.translation:case Qs.scale:l=pr;break;default:n.itemSize===1?l=fr:l=pr;break}const h=s.interpolation!==void 0?R1[s.interpolation]:po,u=this._getArrayFromAccessor(n);for(let d=0,f=c.length;d<f;d++){const p=new l(c[d]+"."+Qs[r.path],t.array,u,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(p),a.push(p)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Dd(t.constructor),s=new Float32Array(t.length);for(let r=0,a=t.length;r<a;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof Us?T1:im;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function O1(i,e,t){const n=e.attributes,s=new ki;if(n.POSITION!==void 0){const o=t.json.accessors[n.POSITION],c=o.min,l=o.max;if(c!==void 0&&l!==void 0){if(s.set(new G(c[0],c[1],c[2]),new G(l[0],l[1],l[2])),o.normalized){const h=Dd(va[o.componentType]);s.min.multiplyScalar(h),s.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const o=new G,c=new G;for(let l=0,h=r.length;l<h;l++){const u=r[l];if(u.POSITION!==void 0){const d=t.json.accessors[u.POSITION],f=d.min,p=d.max;if(f!==void 0&&p!==void 0){if(c.setX(Math.max(Math.abs(f[0]),Math.abs(p[0]))),c.setY(Math.max(Math.abs(f[1]),Math.abs(p[1]))),c.setZ(Math.max(Math.abs(f[2]),Math.abs(p[2]))),d.normalized){const m=Dd(va[d.componentType]);c.multiplyScalar(m)}o.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(o)}i.boundingBox=s;const a=new Ui;s.getCenter(a.center),a.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=a}function am(i,e,t){const n=e.attributes,s=[];function r(a,o){return t.getDependency("accessor",a).then(function(c){i.setAttribute(o,c)})}for(const a in n){const o=Rd[a]||a.toLowerCase();o in i.attributes||s.push(r(n[a],o))}if(e.indices!==void 0&&!i.index){const a=t.getDependency("accessor",e.indices).then(function(o){i.setIndex(o)});s.push(a)}return tt.workingColorSpace!==un&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${tt.workingColorSpace}" not supported.`),cs(i,e),O1(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?N1(i,e.targets,t):i})}var Q1=(function(){var i="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaoc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ak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),n=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var s=WebAssembly.validate(t)?e:i,r,a=WebAssembly.instantiate(o(s),{}).then(function(A){r=A.instance,r.exports.__wasm_call_ctors()});function o(A){for(var _=new Uint8Array(A.length),x=0;x<A.length;++x){var E=A.charCodeAt(x);_[x]=E>96?E-97:E>64?E-39:E+4}for(var S=0,x=0;x<A.length;++x)_[S++]=_[x]<60?n[_[x]]:(_[x]-60)*64+_[++x];return _.buffer.slice(0,S)}function c(A,_,x,E,S,w){var I=r.exports.sbrk,T=x+3&-4,C=I(T*E),v=I(S.length),F=new Uint8Array(r.exports.memory.buffer);F.set(S,v);var K=A(C,x,E,v,S.length);if(K==0&&w&&w(C,T,E),_.set(F.subarray(C,C+x*E)),I(C-I(0)),K!=0)throw new Error("Malformed buffer data: "+K)}var l={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},h={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},u=[],d=0;function f(A){var _={object:new Worker(A),pending:0,requests:{}};return _.object.onmessage=function(x){var E=x.data;_.pending-=E.count,_.requests[E.id][E.action](E.value),delete _.requests[E.id]},_}function p(A){for(var _="var instance; var ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(o(s))+"]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;"+c.toString()+g.toString(),x=new Blob([_],{type:"text/javascript"}),E=URL.createObjectURL(x),S=0;S<A;++S)u[S]=f(E);URL.revokeObjectURL(E)}function m(A,_,x,E,S){for(var w=u[0],I=1;I<u.length;++I)u[I].pending<w.pending&&(w=u[I]);return new Promise(function(T,C){var v=new Uint8Array(x),F=d++;w.pending+=A,w.requests[F]={resolve:T,reject:C},w.object.postMessage({id:F,count:A,size:_,source:v,mode:E,filter:S},[v.buffer])})}function g(A){a.then(function(){var _=A.data;try{var x=new Uint8Array(_.count*_.size);c(r.exports[_.mode],x,_.count,_.size,_.source,r.exports[_.filter]),self.postMessage({id:_.id,count:_.count,action:"resolve",value:x},[x.buffer])}catch(E){self.postMessage({id:_.id,count:_.count,action:"reject",value:E})}})}return{ready:a,supported:!0,useWorkers:function(A){p(A)},decodeVertexBuffer:function(A,_,x,E,S){c(r.exports.meshopt_decodeVertexBuffer,A,_,x,E,r.exports[l[S]])},decodeIndexBuffer:function(A,_,x,E){c(r.exports.meshopt_decodeIndexBuffer,A,_,x,E)},decodeIndexSequence:function(A,_,x,E){c(r.exports.meshopt_decodeIndexSequence,A,_,x,E)},decodeGltfBuffer:function(A,_,x,E,S,w){c(r.exports[h[S]],A,_,x,E,r.exports[l[w]])},decodeGltfBufferAsync:function(A,_,x,E,S){return u.length>0?m(A,_,x,h[E],l[S]):a.then(function(){var w=new Uint8Array(A*_);return c(r.exports[h[E]],w,A,_,x,r.exports[l[S]]),w})}}})();const om={type:"change"},Ld={type:"start"},cm={type:"end"},Ll=new Eo,lm=new ks,G1=Math.cos(70*In.DEG2RAD),An=new G,jn=2*Math.PI,Ft={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Pd=1e-6;class H1 extends iv{constructor(e,t=null){super(e,t),this.state=Ft.NONE,this.target=new G,this.cursor=new G,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:qr.ROTATE,MIDDLE:qr.DOLLY,RIGHT:qr.PAN},this.touches={ONE:Kr.ROTATE,TWO:Kr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new G,this._lastQuaternion=new Yt,this._lastTargetPosition=new G,this._quat=new Yt().setFromUnitVectors(e.up,new G(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new yg,this._sphericalDelta=new yg,this._scale=1,this._panOffset=new G,this._rotateStart=new Je,this._rotateEnd=new Je,this._rotateDelta=new Je,this._panStart=new Je,this._panEnd=new Je,this._panDelta=new Je,this._dollyStart=new Je,this._dollyEnd=new Je,this._dollyDelta=new Je,this._dollyDirection=new G,this._mouse=new Je,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=V1.bind(this),this._onPointerDown=z1.bind(this),this._onPointerUp=W1.bind(this),this._onContextMenu=Z1.bind(this),this._onMouseWheel=j1.bind(this),this._onKeyDown=X1.bind(this),this._onTouchStart=Y1.bind(this),this._onTouchMove=J1.bind(this),this._onMouseDown=q1.bind(this),this._onMouseMove=K1.bind(this),this._interceptControlDown=$1.bind(this),this._interceptControlUp=eM.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(om),this.update(),this.state=Ft.NONE}update(e=null){const t=this.object.position;An.copy(t).sub(this.target),An.applyQuaternion(this._quat),this._spherical.setFromVector3(An),this.autoRotate&&this.state===Ft.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=jn:n>Math.PI&&(n-=jn),s<-Math.PI?s+=jn:s>Math.PI&&(s-=jn),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=a!=this._spherical.radius}if(An.setFromSpherical(this._spherical),An.applyQuaternion(this._quatInverse),t.copy(this.target).add(An),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){const o=An.length();a=this._clampDistance(o*this._scale);const c=o-a;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const o=new G(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const l=new G(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(o),this.object.updateMatrixWorld(),a=An.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(Ll.origin.copy(this.object.position),Ll.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ll.direction))<G1?this.object.lookAt(this.target):(lm.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ll.intersectPlane(lm,this.target))))}else if(this.object.isOrthographicCamera){const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Pd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Pd||this._lastTargetPosition.distanceToSquared(this.target)>Pd?(this.dispatchEvent(om),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?jn/60*this.autoRotateSpeed*e:jn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){An.setFromMatrixColumn(t,0),An.multiplyScalar(-e),this._panOffset.add(An)}_panUp(e,t){this.screenSpacePanning===!0?An.setFromMatrixColumn(t,1):(An.setFromMatrixColumn(t,0),An.crossVectors(this.object.up,An)),An.multiplyScalar(e),this._panOffset.add(An)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;An.copy(s).sub(this.target);let r=An.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,a=n.width,o=n.height;this._mouse.x=s/a*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new Je,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function z1(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function V1(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function W1(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(cm),this.state=Ft.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function q1(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case qr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Ft.DOLLY;break;case qr.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ft.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ft.ROTATE}break;case qr.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ft.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ft.PAN}break;default:this.state=Ft.NONE}this.state!==Ft.NONE&&this.dispatchEvent(Ld)}function K1(i){switch(this.state){case Ft.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ft.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ft.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function j1(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ft.NONE||(i.preventDefault(),this.dispatchEvent(Ld),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(cm))}function X1(i){this.enabled!==!1&&this._handleKeyDown(i)}function Y1(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case Kr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Ft.TOUCH_ROTATE;break;case Kr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ft.TOUCH_PAN;break;default:this.state=Ft.NONE}break;case 2:switch(this.touches.TWO){case Kr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Ft.TOUCH_DOLLY_PAN;break;case Kr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ft.TOUCH_DOLLY_ROTATE;break;default:this.state=Ft.NONE}break;default:this.state=Ft.NONE}this.state!==Ft.NONE&&this.dispatchEvent(Ld)}function J1(i){switch(this._trackPointer(i),this.state){case Ft.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ft.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ft.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ft.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ft.NONE}}function Z1(i){this.enabled!==!1&&i.preventDefault()}function $1(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function eM(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class tM extends $u{constructor(){super();const e=new da;e.deleteAttribute("uv");const t=new To({side:Ln}),n=new To,s=new Ml(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const r=new Zt(e,t);r.position.set(-.757,13.219,.717),r.scale.set(31.713,28.305,28.591),this.add(r);const a=new jA(e,n,6),o=new Tt;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);const c=new Zt(e,Ca(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const l=new Zt(e,Ca(50));l.position.set(-16.109,18.021,-8.207),l.scale.set(.1,2.425,2.751),this.add(l);const h=new Zt(e,Ca(17));h.position.set(14.904,12.198,-1.832),h.scale.set(.15,4.265,6.331),this.add(h);const u=new Zt(e,Ca(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);const d=new Zt(e,Ca(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,.1),this.add(d);const f=new Zt(e,Ca(100));f.position.set(0,20,0),f.scale.set(1,.1,1),this.add(f)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Ca(i){const e=new Ds;return e.color.setScalar(i),e}function nM(i){if(!(typeof window>"u")){var e=document.createElement("style");return e.setAttribute("type","text/css"),e.innerHTML=i,document.head.appendChild(e),i}}function Ia(i,e){var t=i.__state.conversionName.toString(),n=Math.round(i.r),s=Math.round(i.g),r=Math.round(i.b),a=i.a,o=Math.round(i.h),c=i.s.toFixed(1),l=i.v.toFixed(1);if(e||t==="THREE_CHAR_HEX"||t==="SIX_CHAR_HEX"){for(var h=i.hex.toString(16);h.length<6;)h="0"+h;return"#"+h}else{if(t==="CSS_RGB")return"rgb("+n+","+s+","+r+")";if(t==="CSS_RGBA")return"rgba("+n+","+s+","+r+","+a+")";if(t==="HEX")return"0x"+i.hex.toString(16);if(t==="RGB_ARRAY")return"["+n+","+s+","+r+"]";if(t==="RGBA_ARRAY")return"["+n+","+s+","+r+","+a+"]";if(t==="RGB_OBJ")return"{r:"+n+",g:"+s+",b:"+r+"}";if(t==="RGBA_OBJ")return"{r:"+n+",g:"+s+",b:"+r+",a:"+a+"}";if(t==="HSV_OBJ")return"{h:"+o+",s:"+c+",v:"+l+"}";if(t==="HSVA_OBJ")return"{h:"+o+",s:"+c+",v:"+l+",a:"+a+"}"}return"unknown format"}var hm=Array.prototype.forEach,ko=Array.prototype.slice,ue={BREAK:{},extend:function(e){return this.each(ko.call(arguments,1),function(t){var n=this.isObject(t)?Object.keys(t):[];n.forEach((function(s){this.isUndefined(t[s])||(e[s]=t[s])}).bind(this))},this),e},defaults:function(e){return this.each(ko.call(arguments,1),function(t){var n=this.isObject(t)?Object.keys(t):[];n.forEach((function(s){this.isUndefined(e[s])&&(e[s]=t[s])}).bind(this))},this),e},compose:function(){var e=ko.call(arguments);return function(){for(var t=ko.call(arguments),n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},each:function(e,t,n){if(e){if(hm&&e.forEach&&e.forEach===hm)e.forEach(t,n);else if(e.length===e.length+0){var s=void 0,r=void 0;for(s=0,r=e.length;s<r;s++)if(s in e&&t.call(n,e[s],s)===this.BREAK)return}else for(var a in e)if(t.call(n,e[a],a)===this.BREAK)return}},defer:function(e){setTimeout(e,0)},debounce:function(e,t,n){var s=void 0;return function(){var r=this,a=arguments;function o(){s=null,n||e.apply(r,a)}var c=n||!s;clearTimeout(s),s=setTimeout(o,t),c&&e.apply(r,a)}},toArray:function(e){return e.toArray?e.toArray():ko.call(e)},isUndefined:function(e){return e===void 0},isNull:function(e){return e===null},isNaN:(function(i){function e(t){return i.apply(this,arguments)}return e.toString=function(){return i.toString()},e})(function(i){return isNaN(i)}),isArray:Array.isArray||function(i){return i.constructor===Array},isObject:function(e){return e===Object(e)},isNumber:function(e){return e===e+0},isString:function(e){return e===e+""},isBoolean:function(e){return e===!1||e===!0},isFunction:function(e){return e instanceof Function}},iM=[{litmus:ue.isString,conversions:{THREE_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);return t===null?!1:{space:"HEX",hex:parseInt("0x"+t[1].toString()+t[1].toString()+t[2].toString()+t[2].toString()+t[3].toString()+t[3].toString(),0)}},write:Ia},SIX_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9]{6})$/i);return t===null?!1:{space:"HEX",hex:parseInt("0x"+t[1].toString(),0)}},write:Ia},CSS_RGB:{read:function(e){var t=e.match(/^rgb\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3])}},write:Ia},CSS_RGBA:{read:function(e){var t=e.match(/^rgba\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3]),a:parseFloat(t[4])}},write:Ia}}},{litmus:ue.isNumber,conversions:{HEX:{read:function(e){return{space:"HEX",hex:e,conversionName:"HEX"}},write:function(e){return e.hex}}}},{litmus:ue.isArray,conversions:{RGB_ARRAY:{read:function(e){return e.length!==3?!1:{space:"RGB",r:e[0],g:e[1],b:e[2]}},write:function(e){return[e.r,e.g,e.b]}},RGBA_ARRAY:{read:function(e){return e.length!==4?!1:{space:"RGB",r:e[0],g:e[1],b:e[2],a:e[3]}},write:function(e){return[e.r,e.g,e.b,e.a]}}}},{litmus:ue.isObject,conversions:{RGBA_OBJ:{read:function(e){return ue.isNumber(e.r)&&ue.isNumber(e.g)&&ue.isNumber(e.b)&&ue.isNumber(e.a)?{space:"RGB",r:e.r,g:e.g,b:e.b,a:e.a}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b,a:e.a}}},RGB_OBJ:{read:function(e){return ue.isNumber(e.r)&&ue.isNumber(e.g)&&ue.isNumber(e.b)?{space:"RGB",r:e.r,g:e.g,b:e.b}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b}}},HSVA_OBJ:{read:function(e){return ue.isNumber(e.h)&&ue.isNumber(e.s)&&ue.isNumber(e.v)&&ue.isNumber(e.a)?{space:"HSV",h:e.h,s:e.s,v:e.v,a:e.a}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v,a:e.a}}},HSV_OBJ:{read:function(e){return ue.isNumber(e.h)&&ue.isNumber(e.s)&&ue.isNumber(e.v)?{space:"HSV",h:e.h,s:e.s,v:e.v}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v}}}}}],Uo=void 0,Pl=void 0,kd=function(){Pl=!1;var e=arguments.length>1?ue.toArray(arguments):arguments[0];return ue.each(iM,function(t){if(t.litmus(e))return ue.each(t.conversions,function(n,s){if(Uo=n.read(e),Pl===!1&&Uo!==!1)return Pl=Uo,Uo.conversionName=s,Uo.conversion=n,ue.BREAK}),ue.BREAK}),Pl},um=void 0,kl={hsv_to_rgb:function(e,t,n){var s=Math.floor(e/60)%6,r=e/60-Math.floor(e/60),a=n*(1-t),o=n*(1-r*t),c=n*(1-(1-r)*t),l=[[n,c,a],[o,n,a],[a,n,c],[a,o,n],[c,a,n],[n,a,o]][s];return{r:l[0]*255,g:l[1]*255,b:l[2]*255}},rgb_to_hsv:function(e,t,n){var s=Math.min(e,t,n),r=Math.max(e,t,n),a=r-s,o=void 0,c=void 0;if(r!==0)c=a/r;else return{h:NaN,s:0,v:0};return e===r?o=(t-n)/a:t===r?o=2+(n-e)/a:o=4+(e-t)/a,o/=6,o<0&&(o+=1),{h:o*360,s:c,v:r/255}},rgb_to_hex:function(e,t,n){var s=this.hex_with_component(0,2,e);return s=this.hex_with_component(s,1,t),s=this.hex_with_component(s,0,n),s},component_from_hex:function(e,t){return e>>t*8&255},hex_with_component:function(e,t,n){return n<<(um=t*8)|e&~(255<<um)}},sM=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},Ci=function(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")},Ii=(function(){function i(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}})(),Gs=function i(e,t,n){e===null&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(s===void 0){var r=Object.getPrototypeOf(e);return r===null?void 0:i(r,t,n)}else{if("value"in s)return s.value;var a=s.get;return a===void 0?void 0:a.call(n)}},Hs=function(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof e);i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(i,e):i.__proto__=e)},zs=function(i,e){if(!i)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e&&(typeof e=="object"||typeof e=="function")?e:i},En=(function(){function i(){if(Ci(this,i),this.__state=kd.apply(this,arguments),this.__state===!1)throw new Error("Failed to interpret color arguments");this.__state.a=this.__state.a||1}return Ii(i,[{key:"toString",value:function(){return Ia(this)}},{key:"toHexString",value:function(){return Ia(this,!0)}},{key:"toOriginal",value:function(){return this.__state.conversion.write(this)}}]),i})();function Ud(i,e,t){Object.defineProperty(i,e,{get:function(){return this.__state.space==="RGB"?this.__state[e]:(En.recalculateRGB(this,e,t),this.__state[e])},set:function(s){this.__state.space!=="RGB"&&(En.recalculateRGB(this,e,t),this.__state.space="RGB"),this.__state[e]=s}})}function Od(i,e){Object.defineProperty(i,e,{get:function(){return this.__state.space==="HSV"?this.__state[e]:(En.recalculateHSV(this),this.__state[e])},set:function(n){this.__state.space!=="HSV"&&(En.recalculateHSV(this),this.__state.space="HSV"),this.__state[e]=n}})}En.recalculateRGB=function(i,e,t){if(i.__state.space==="HEX")i.__state[e]=kl.component_from_hex(i.__state.hex,t);else if(i.__state.space==="HSV")ue.extend(i.__state,kl.hsv_to_rgb(i.__state.h,i.__state.s,i.__state.v));else throw new Error("Corrupted color state")},En.recalculateHSV=function(i){var e=kl.rgb_to_hsv(i.r,i.g,i.b);ue.extend(i.__state,{s:e.s,v:e.v}),ue.isNaN(e.h)?ue.isUndefined(i.__state.h)&&(i.__state.h=0):i.__state.h=e.h},En.COMPONENTS=["r","g","b","h","s","v","hex","a"],Ud(En.prototype,"r",2),Ud(En.prototype,"g",1),Ud(En.prototype,"b",0),Od(En.prototype,"h"),Od(En.prototype,"s"),Od(En.prototype,"v"),Object.defineProperty(En.prototype,"a",{get:function(){return this.__state.a},set:function(e){this.__state.a=e}}),Object.defineProperty(En.prototype,"hex",{get:function(){return this.__state.space!=="HEX"&&(this.__state.hex=kl.rgb_to_hex(this.r,this.g,this.b),this.__state.space="HEX"),this.__state.hex},set:function(e){this.__state.space="HEX",this.__state.hex=e}});var yr=(function(){function i(e,t){Ci(this,i),this.initialValue=e[t],this.domElement=document.createElement("div"),this.object=e,this.property=t,this.__onChange=void 0,this.__onFinishChange=void 0}return Ii(i,[{key:"onChange",value:function(t){return this.__onChange=t,this}},{key:"onFinishChange",value:function(t){return this.__onFinishChange=t,this}},{key:"setValue",value:function(t){return this.object[this.property]=t,this.__onChange&&this.__onChange.call(this,t),this.updateDisplay(),this}},{key:"getValue",value:function(){return this.object[this.property]}},{key:"updateDisplay",value:function(){return this}},{key:"isModified",value:function(){return this.initialValue!==this.getValue()}}]),i})(),rM={HTMLEvents:["change"],MouseEvents:["click","mousemove","mousedown","mouseup","mouseover"],KeyboardEvents:["keydown"]},dm={};ue.each(rM,function(i,e){ue.each(i,function(t){dm[t]=e})});var aM=/(\d+(\.\d+)?)px/;function Gi(i){if(i==="0"||ue.isUndefined(i))return 0;var e=i.match(aM);return ue.isNull(e)?0:parseFloat(e[1])}var te={makeSelectable:function(e,t){e===void 0||e.style===void 0||(e.onselectstart=t?function(){return!1}:function(){},e.style.MozUserSelect=t?"auto":"none",e.style.KhtmlUserSelect=t?"auto":"none",e.unselectable=t?"on":"off")},makeFullscreen:function(e,t,n){var s=n,r=t;ue.isUndefined(r)&&(r=!0),ue.isUndefined(s)&&(s=!0),e.style.position="absolute",r&&(e.style.left=0,e.style.right=0),s&&(e.style.top=0,e.style.bottom=0)},fakeEvent:function(e,t,n,s){var r=n||{},a=dm[t];if(!a)throw new Error("Event type "+t+" not supported.");var o=document.createEvent(a);switch(a){case"MouseEvents":{var c=r.x||r.clientX||0,l=r.y||r.clientY||0;o.initMouseEvent(t,r.bubbles||!1,r.cancelable||!0,window,r.clickCount||1,0,0,c,l,!1,!1,!1,!1,0,null);break}case"KeyboardEvents":{var h=o.initKeyboardEvent||o.initKeyEvent;ue.defaults(r,{cancelable:!0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,keyCode:void 0,charCode:void 0}),h(t,r.bubbles||!1,r.cancelable,window,r.ctrlKey,r.altKey,r.shiftKey,r.metaKey,r.keyCode,r.charCode);break}default:{o.initEvent(t,r.bubbles||!1,r.cancelable||!0);break}}ue.defaults(o,s),e.dispatchEvent(o)},bind:function(e,t,n,s){var r=s||!1;return e.addEventListener?e.addEventListener(t,n,r):e.attachEvent&&e.attachEvent("on"+t,n),te},unbind:function(e,t,n,s){var r=s||!1;return e.removeEventListener?e.removeEventListener(t,n,r):e.detachEvent&&e.detachEvent("on"+t,n),te},addClass:function(e,t){if(e.className===void 0)e.className=t;else if(e.className!==t){var n=e.className.split(/ +/);n.indexOf(t)===-1&&(n.push(t),e.className=n.join(" ").replace(/^\s+/,"").replace(/\s+$/,""))}return te},removeClass:function(e,t){if(t)if(e.className===t)e.removeAttribute("class");else{var n=e.className.split(/ +/),s=n.indexOf(t);s!==-1&&(n.splice(s,1),e.className=n.join(" "))}else e.className=void 0;return te},hasClass:function(e,t){return new RegExp("(?:^|\\s+)"+t+"(?:\\s+|$)").test(e.className)||!1},getWidth:function(e){var t=getComputedStyle(e);return Gi(t["border-left-width"])+Gi(t["border-right-width"])+Gi(t["padding-left"])+Gi(t["padding-right"])+Gi(t.width)},getHeight:function(e){var t=getComputedStyle(e);return Gi(t["border-top-width"])+Gi(t["border-bottom-width"])+Gi(t["padding-top"])+Gi(t["padding-bottom"])+Gi(t.height)},getOffset:function(e){var t=e,n={left:0,top:0};if(t.offsetParent)do n.left+=t.offsetLeft,n.top+=t.offsetTop,t=t.offsetParent;while(t);return n},isActive:function(e){return e===document.activeElement&&(e.type||e.href)}},fm=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),r=s;s.__prev=s.getValue(),s.__checkbox=document.createElement("input"),s.__checkbox.setAttribute("type","checkbox");function a(){r.setValue(!r.__prev)}return te.bind(s.__checkbox,"change",a,!1),s.domElement.appendChild(s.__checkbox),s.updateDisplay(),s}return Ii(e,[{key:"setValue",value:function(n){var s=Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,n);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),this.__prev=this.getValue(),s}},{key:"updateDisplay",value:function(){return this.getValue()===!0?(this.__checkbox.setAttribute("checked","checked"),this.__checkbox.checked=!0,this.__prev=!0):(this.__checkbox.checked=!1,this.__prev=!1),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(yr),oM=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=s,o=r;if(r.__select=document.createElement("select"),ue.isArray(a)){var c={};ue.each(a,function(l){c[l]=l}),a=c}return ue.each(a,function(l,h){var u=document.createElement("option");u.innerHTML=h,u.setAttribute("value",l),o.__select.appendChild(u)}),r.updateDisplay(),te.bind(r.__select,"change",function(){var l=this.options[this.selectedIndex].value;o.setValue(l)}),r.domElement.appendChild(r.__select),r}return Ii(e,[{key:"setValue",value:function(n){var s=Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,n);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),s}},{key:"updateDisplay",value:function(){return te.isActive(this.__select)?this:(this.__select.value=this.getValue(),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this))}}]),e})(yr),cM=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),r=s;function a(){r.setValue(r.__input.value)}function o(){r.__onFinishChange&&r.__onFinishChange.call(r,r.getValue())}return s.__input=document.createElement("input"),s.__input.setAttribute("type","text"),te.bind(s.__input,"keyup",a),te.bind(s.__input,"change",a),te.bind(s.__input,"blur",o),te.bind(s.__input,"keydown",function(c){c.keyCode===13&&this.blur()}),s.updateDisplay(),s.domElement.appendChild(s.__input),s}return Ii(e,[{key:"updateDisplay",value:function(){return te.isActive(this.__input)||(this.__input.value=this.getValue()),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(yr);function pm(i){var e=i.toString();return e.indexOf(".")>-1?e.length-e.indexOf(".")-1:0}var Am=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=s||{};return r.__min=a.min,r.__max=a.max,r.__step=a.step,ue.isUndefined(r.__step)?r.initialValue===0?r.__impliedStep=1:r.__impliedStep=Math.pow(10,Math.floor(Math.log(Math.abs(r.initialValue))/Math.LN10))/10:r.__impliedStep=r.__step,r.__precision=pm(r.__impliedStep),r}return Ii(e,[{key:"setValue",value:function(n){var s=n;return this.__min!==void 0&&s<this.__min?s=this.__min:this.__max!==void 0&&s>this.__max&&(s=this.__max),this.__step!==void 0&&s%this.__step!==0&&(s=Math.round(s/this.__step)*this.__step),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,s)}},{key:"min",value:function(n){return this.__min=n,this}},{key:"max",value:function(n){return this.__max=n,this}},{key:"step",value:function(n){return this.__step=n,this.__impliedStep=n,this.__precision=pm(n),this}}]),e})(yr);function lM(i,e){var t=Math.pow(10,e);return Math.round(i*t)/t}var Ul=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n,s));r.__truncationSuspended=!1;var a=r,o=void 0;function c(){var p=parseFloat(a.__input.value);ue.isNaN(p)||a.setValue(p)}function l(){a.__onFinishChange&&a.__onFinishChange.call(a,a.getValue())}function h(){l()}function u(p){var m=o-p.clientY;a.setValue(a.getValue()+m*a.__impliedStep),o=p.clientY}function d(){te.unbind(window,"mousemove",u),te.unbind(window,"mouseup",d),l()}function f(p){te.bind(window,"mousemove",u),te.bind(window,"mouseup",d),o=p.clientY}return r.__input=document.createElement("input"),r.__input.setAttribute("type","text"),te.bind(r.__input,"change",c),te.bind(r.__input,"blur",h),te.bind(r.__input,"mousedown",f),te.bind(r.__input,"keydown",function(p){p.keyCode===13&&(a.__truncationSuspended=!0,this.blur(),a.__truncationSuspended=!1,l())}),r.updateDisplay(),r.domElement.appendChild(r.__input),r}return Ii(e,[{key:"updateDisplay",value:function(){return this.__input.value=this.__truncationSuspended?this.getValue():lM(this.getValue(),this.__precision),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(Am);function gm(i,e,t,n,s){return n+(s-n)*((i-e)/(t-e))}var Qd=(function(i){Hs(e,i);function e(t,n,s,r,a){Ci(this,e);var o=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n,{min:s,max:r,step:a})),c=o;o.__background=document.createElement("div"),o.__foreground=document.createElement("div"),te.bind(o.__background,"mousedown",l),te.bind(o.__background,"touchstart",d),te.addClass(o.__background,"slider"),te.addClass(o.__foreground,"slider-fg");function l(m){document.activeElement.blur(),te.bind(window,"mousemove",h),te.bind(window,"mouseup",u),h(m)}function h(m){m.preventDefault();var g=c.__background.getBoundingClientRect();return c.setValue(gm(m.clientX,g.left,g.right,c.__min,c.__max)),!1}function u(){te.unbind(window,"mousemove",h),te.unbind(window,"mouseup",u),c.__onFinishChange&&c.__onFinishChange.call(c,c.getValue())}function d(m){m.touches.length===1&&(te.bind(window,"touchmove",f),te.bind(window,"touchend",p),f(m))}function f(m){var g=m.touches[0].clientX,A=c.__background.getBoundingClientRect();c.setValue(gm(g,A.left,A.right,c.__min,c.__max))}function p(){te.unbind(window,"touchmove",f),te.unbind(window,"touchend",p),c.__onFinishChange&&c.__onFinishChange.call(c,c.getValue())}return o.updateDisplay(),o.__background.appendChild(o.__foreground),o.domElement.appendChild(o.__background),o}return Ii(e,[{key:"updateDisplay",value:function(){var n=(this.getValue()-this.__min)/(this.__max-this.__min);return this.__foreground.style.width=n*100+"%",Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(Am),mm=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=r;return r.__button=document.createElement("div"),r.__button.innerHTML=s===void 0?"Fire":s,te.bind(r.__button,"click",function(o){return o.preventDefault(),a.fire(),!1}),te.addClass(r.__button,"button"),r.domElement.appendChild(r.__button),r}return Ii(e,[{key:"fire",value:function(){this.__onChange&&this.__onChange.call(this),this.getValue().call(this.object),this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue())}}]),e})(yr),Gd=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));s.__color=new En(s.getValue()),s.__temp=new En(0);var r=s;s.domElement=document.createElement("div"),te.makeSelectable(s.domElement,!1),s.__selector=document.createElement("div"),s.__selector.className="selector",s.__saturation_field=document.createElement("div"),s.__saturation_field.className="saturation-field",s.__field_knob=document.createElement("div"),s.__field_knob.className="field-knob",s.__field_knob_border="2px solid ",s.__hue_knob=document.createElement("div"),s.__hue_knob.className="hue-knob",s.__hue_field=document.createElement("div"),s.__hue_field.className="hue-field",s.__input=document.createElement("input"),s.__input.type="text",s.__input_textShadow="0 1px 1px ",te.bind(s.__input,"keydown",function(m){m.keyCode===13&&u.call(this)}),te.bind(s.__input,"blur",u),te.bind(s.__selector,"mousedown",function(){te.addClass(this,"drag").bind(window,"mouseup",function(){te.removeClass(r.__selector,"drag")})}),te.bind(s.__selector,"touchstart",function(){te.addClass(this,"drag").bind(window,"touchend",function(){te.removeClass(r.__selector,"drag")})});var a=document.createElement("div");ue.extend(s.__selector.style,{width:"122px",height:"102px",padding:"3px",backgroundColor:"#222",boxShadow:"0px 1px 3px rgba(0,0,0,0.3)"}),ue.extend(s.__field_knob.style,{position:"absolute",width:"12px",height:"12px",border:s.__field_knob_border+(s.__color.v<.5?"#fff":"#000"),boxShadow:"0px 1px 3px rgba(0,0,0,0.5)",borderRadius:"12px",zIndex:1}),ue.extend(s.__hue_knob.style,{position:"absolute",width:"15px",height:"2px",borderRight:"4px solid #fff",zIndex:1}),ue.extend(s.__saturation_field.style,{width:"100px",height:"100px",border:"1px solid #555",marginRight:"3px",display:"inline-block",cursor:"pointer"}),ue.extend(a.style,{width:"100%",height:"100%",background:"none"}),xm(a,"top","rgba(0,0,0,0)","#000"),ue.extend(s.__hue_field.style,{width:"15px",height:"100px",border:"1px solid #555",cursor:"ns-resize",position:"absolute",top:"3px",right:"3px"}),uM(s.__hue_field),ue.extend(s.__input.style,{outline:"none",textAlign:"center",color:"#fff",border:0,fontWeight:"bold",textShadow:s.__input_textShadow+"rgba(0,0,0,0.7)"}),te.bind(s.__saturation_field,"mousedown",o),te.bind(s.__saturation_field,"touchstart",o),te.bind(s.__field_knob,"mousedown",o),te.bind(s.__field_knob,"touchstart",o),te.bind(s.__hue_field,"mousedown",c),te.bind(s.__hue_field,"touchstart",c);function o(m){f(m),te.bind(window,"mousemove",f),te.bind(window,"touchmove",f),te.bind(window,"mouseup",l),te.bind(window,"touchend",l)}function c(m){p(m),te.bind(window,"mousemove",p),te.bind(window,"touchmove",p),te.bind(window,"mouseup",h),te.bind(window,"touchend",h)}function l(){te.unbind(window,"mousemove",f),te.unbind(window,"touchmove",f),te.unbind(window,"mouseup",l),te.unbind(window,"touchend",l),d()}function h(){te.unbind(window,"mousemove",p),te.unbind(window,"touchmove",p),te.unbind(window,"mouseup",h),te.unbind(window,"touchend",h),d()}function u(){var m=kd(this.value);m!==!1?(r.__color.__state=m,r.setValue(r.__color.toOriginal())):this.value=r.__color.toString()}function d(){r.__onFinishChange&&r.__onFinishChange.call(r,r.__color.toOriginal())}s.__saturation_field.appendChild(a),s.__selector.appendChild(s.__field_knob),s.__selector.appendChild(s.__saturation_field),s.__selector.appendChild(s.__hue_field),s.__hue_field.appendChild(s.__hue_knob),s.domElement.appendChild(s.__input),s.domElement.appendChild(s.__selector),s.updateDisplay();function f(m){m.type.indexOf("touch")===-1&&m.preventDefault();var g=r.__saturation_field.getBoundingClientRect(),A=m.touches&&m.touches[0]||m,_=A.clientX,x=A.clientY,E=(_-g.left)/(g.right-g.left),S=1-(x-g.top)/(g.bottom-g.top);return S>1?S=1:S<0&&(S=0),E>1?E=1:E<0&&(E=0),r.__color.v=S,r.__color.s=E,r.setValue(r.__color.toOriginal()),!1}function p(m){m.type.indexOf("touch")===-1&&m.preventDefault();var g=r.__hue_field.getBoundingClientRect(),A=m.touches&&m.touches[0]||m,_=A.clientY,x=1-(_-g.top)/(g.bottom-g.top);return x>1?x=1:x<0&&(x=0),r.__color.h=x*360,r.setValue(r.__color.toOriginal()),!1}return s}return Ii(e,[{key:"updateDisplay",value:function(){var n=kd(this.getValue());if(n!==!1){var s=!1;ue.each(En.COMPONENTS,function(o){if(!ue.isUndefined(n[o])&&!ue.isUndefined(this.__color.__state[o])&&n[o]!==this.__color.__state[o])return s=!0,{}},this),s&&ue.extend(this.__color.__state,n)}ue.extend(this.__temp.__state,this.__color.__state),this.__temp.a=1;var r=this.__color.v<.5||this.__color.s>.5?255:0,a=255-r;ue.extend(this.__field_knob.style,{marginLeft:100*this.__color.s-7+"px",marginTop:100*(1-this.__color.v)-7+"px",backgroundColor:this.__temp.toHexString(),border:this.__field_knob_border+"rgb("+r+","+r+","+r+")"}),this.__hue_knob.style.marginTop=(1-this.__color.h/360)*100+"px",this.__temp.s=1,this.__temp.v=1,xm(this.__saturation_field,"left","#fff",this.__temp.toHexString()),this.__input.value=this.__color.toString(),ue.extend(this.__input.style,{backgroundColor:this.__color.toHexString(),color:"rgb("+r+","+r+","+r+")",textShadow:this.__input_textShadow+"rgba("+a+","+a+","+a+",.7)"})}}]),e})(yr),hM=["-moz-","-o-","-webkit-","-ms-",""];function xm(i,e,t,n){i.style.background="",ue.each(hM,function(s){i.style.cssText+="background: "+s+"linear-gradient("+e+", "+t+" 0%, "+n+" 100%); "})}function uM(i){i.style.background="",i.style.cssText+="background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);",i.style.cssText+="background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);"}var dM={load:function(e,t){var n=t||document,s=n.createElement("link");s.type="text/css",s.rel="stylesheet",s.href=e,n.getElementsByTagName("head")[0].appendChild(s)},inject:function(e,t){var n=t||document,s=document.createElement("style");s.type="text/css",s.innerHTML=e;var r=n.getElementsByTagName("head")[0];try{r.appendChild(s)}catch{}}},fM=`<div id="dg-save" class="dg dialogue">
+}`;class e1{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){const s=new nn,r=e.properties.get(s);r.__webglTexture=t.texture,(t.depthNear!==n.depthNear||t.depthFar!==n.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=s}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Ls({vertexShader:ZS,fragmentShader:$S,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Zt(new vl(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class t1 extends Ms{constructor(e,t){super();const n=this;let s=null,r=1,a=null,o="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,p=null;const m=new e1,g=t.getContextAttributes();let A=null,_=null;const x=[],E=[],S=new Je;let w=null;const I=new Bn;I.viewport=new gt;const T=new Bn;T.viewport=new gt;const C=[I,T],v=new Gw;let F=null,K=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getTargetRaySpace()},this.getControllerGrip=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getGripSpace()},this.getHand=function(se){let me=x[se];return me===void 0&&(me=new Zu,x[se]=me),me.getHandSpace()};function q(se){const me=E.indexOf(se.inputSource);if(me===-1)return;const xe=x[me];xe!==void 0&&(xe.update(se.inputSource,se.frame,l||a),xe.dispatchEvent({type:se.type,data:se.inputSource}))}function $(){s.removeEventListener("select",q),s.removeEventListener("selectstart",q),s.removeEventListener("selectend",q),s.removeEventListener("squeeze",q),s.removeEventListener("squeezestart",q),s.removeEventListener("squeezeend",q),s.removeEventListener("end",$),s.removeEventListener("inputsourceschange",D);for(let se=0;se<x.length;se++){const me=E[se];me!==null&&(E[se]=null,x[se].disconnect(me))}F=null,K=null,m.reset(),e.setRenderTarget(A),f=null,d=null,u=null,s=null,_=null,Me.stop(),n.isPresenting=!1,e.setPixelRatio(w),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(se){r=se,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(se){o=se,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(se){l=se},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(se){if(s=se,s!==null){if(A=e.getRenderTarget(),s.addEventListener("select",q),s.addEventListener("selectstart",q),s.addEventListener("selectend",q),s.addEventListener("squeeze",q),s.addEventListener("squeezestart",q),s.addEventListener("squeezeend",q),s.addEventListener("end",$),s.addEventListener("inputsourceschange",D),g.xrCompatible!==!0&&await t.makeXRCompatible(),w=e.getPixelRatio(),e.getSize(S),typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype){let xe=null,be=null,Ue=null;g.depth&&(Ue=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,xe=g.stencil?ao:ro,be=g.stencil?so:rr);const et={colorFormat:t.RGBA8,depthFormat:Ue,scaleFactor:r};u=new XRWebGLBinding(s,t),d=u.createProjectionLayer(et),s.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),_=new or(d.textureWidth,d.textureHeight,{format:hn,type:cn,depthTexture:new tg(d.textureWidth,d.textureHeight,be,void 0,void 0,void 0,void 0,void 0,void 0,xe),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const xe={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,xe),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new or(f.framebufferWidth,f.framebufferHeight,{format:hn,type:cn,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(c),l=null,a=await s.requestReferenceSpace(o),Me.setContext(s),Me.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function D(se){for(let me=0;me<se.removed.length;me++){const xe=se.removed[me],be=E.indexOf(xe);be>=0&&(E[be]=null,x[be].disconnect(xe))}for(let me=0;me<se.added.length;me++){const xe=se.added[me];let be=E.indexOf(xe);if(be===-1){for(let et=0;et<x.length;et++)if(et>=E.length){E.push(xe),be=et;break}else if(E[et]===null){E[et]=xe,be=et;break}if(be===-1)break}const Ue=x[be];Ue&&Ue.connect(xe)}}const O=new G,Y=new G;function Q(se,me,xe){O.setFromMatrixPosition(me.matrixWorld),Y.setFromMatrixPosition(xe.matrixWorld);const be=O.distanceTo(Y),Ue=me.projectionMatrix.elements,et=xe.projectionMatrix.elements,He=Ue[14]/(Ue[10]-1),Mt=Ue[14]/(Ue[10]+1),ft=(Ue[9]+1)/Ue[5],$e=(Ue[9]-1)/Ue[5],H=(Ue[8]-1)/Ue[0],wn=(et[8]+1)/et[0],pt=He*H,mt=He*wn,We=be/(-H+wn),Dt=We*-H;if(me.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(Dt),se.translateZ(We),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert(),Ue[10]===-1)se.projectionMatrix.copy(me.projectionMatrix),se.projectionMatrixInverse.copy(me.projectionMatrixInverse);else{const ze=He+We,L=Mt+We,M=pt-Dt,Z=mt+(be-Dt),le=ft*Mt/L*ze,Ae=$e*Mt/L*ze;se.projectionMatrix.makePerspective(M,Z,le,Ae,ze,L),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}}function J(se,me){me===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(me.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(s===null)return;let me=se.near,xe=se.far;m.texture!==null&&(m.depthNear>0&&(me=m.depthNear),m.depthFar>0&&(xe=m.depthFar)),v.near=T.near=I.near=me,v.far=T.far=I.far=xe,(F!==v.near||K!==v.far)&&(s.updateRenderState({depthNear:v.near,depthFar:v.far}),F=v.near,K=v.far),I.layers.mask=se.layers.mask|2,T.layers.mask=se.layers.mask|4,v.layers.mask=I.layers.mask|T.layers.mask;const be=se.parent,Ue=v.cameras;J(v,be);for(let et=0;et<Ue.length;et++)J(Ue[et],be);Ue.length===2?Q(v,I,T):v.projectionMatrix.copy(I.projectionMatrix),ee(se,v,be)};function ee(se,me,xe){xe===null?se.matrix.copy(me.matrixWorld):(se.matrix.copy(xe.matrixWorld),se.matrix.invert(),se.matrix.multiply(me.matrixWorld)),se.matrix.decompose(se.position,se.quaternion,se.scale),se.updateMatrixWorld(!0),se.projectionMatrix.copy(me.projectionMatrix),se.projectionMatrixInverse.copy(me.projectionMatrixInverse),se.isPerspectiveCamera&&(se.fov=ea*2*Math.atan(1/se.projectionMatrix.elements[5]),se.zoom=1)}this.getCamera=function(){return v},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(se){c=se,d!==null&&(d.fixedFoveation=se),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=se)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(v)};let ae=null;function _e(se,me){if(h=me.getViewerPose(l||a),p=me,h!==null){const xe=h.views;f!==null&&(e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_));let be=!1;xe.length!==v.cameras.length&&(v.cameras.length=0,be=!0);for(let He=0;He<xe.length;He++){const Mt=xe[He];let ft=null;if(f!==null)ft=f.getViewport(Mt);else{const H=u.getViewSubImage(d,Mt);ft=H.viewport,He===0&&(e.setRenderTargetTextures(_,H.colorTexture,H.depthStencilTexture),e.setRenderTarget(_))}let $e=C[He];$e===void 0&&($e=new Bn,$e.layers.enable(He),$e.viewport=new gt,C[He]=$e),$e.matrix.fromArray(Mt.transform.matrix),$e.matrix.decompose($e.position,$e.quaternion,$e.scale),$e.projectionMatrix.fromArray(Mt.projectionMatrix),$e.projectionMatrixInverse.copy($e.projectionMatrix).invert(),$e.viewport.set(ft.x,ft.y,ft.width,ft.height),He===0&&(v.matrix.copy($e.matrix),v.matrix.decompose(v.position,v.quaternion,v.scale)),be===!0&&v.cameras.push($e)}const Ue=s.enabledFeatures;if(Ue&&Ue.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&u){const He=u.getDepthInformation(xe[0]);He&&He.isValid&&He.texture&&m.init(e,He,s.renderState)}}for(let xe=0;xe<x.length;xe++){const be=E[xe],Ue=x[xe];be!==null&&Ue!==void 0&&Ue.update(be,me,l||a)}ae&&ae(se,me),me.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:me}),p=null}const Me=new Cg;Me.setAnimationLoop(_e),this.setAnimationLoop=function(se){ae=se},this.dispose=function(){}}}const br=new dn,n1=new Re;function i1(i,e){function t(g,A){g.matrixAutoUpdate===!0&&g.updateMatrix(),A.value.copy(g.matrix)}function n(g,A){A.color.getRGB(g.fogColor.value,DA(i)),A.isFog?(g.fogNear.value=A.near,g.fogFar.value=A.far):A.isFogExp2&&(g.fogDensity.value=A.density)}function s(g,A,_,x,E){A.isMeshBasicMaterial||A.isMeshLambertMaterial?r(g,A):A.isMeshToonMaterial?(r(g,A),u(g,A)):A.isMeshPhongMaterial?(r(g,A),h(g,A)):A.isMeshStandardMaterial?(r(g,A),d(g,A),A.isMeshPhysicalMaterial&&f(g,A,E)):A.isMeshMatcapMaterial?(r(g,A),p(g,A)):A.isMeshDepthMaterial?r(g,A):A.isMeshDistanceMaterial?(r(g,A),m(g,A)):A.isMeshNormalMaterial?r(g,A):A.isLineBasicMaterial?(a(g,A),A.isLineDashedMaterial&&o(g,A)):A.isPointsMaterial?c(g,A,_,x):A.isSpriteMaterial?l(g,A):A.isShadowMaterial?(g.color.value.copy(A.color),g.opacity.value=A.opacity):A.isShaderMaterial&&(A.uniformsNeedUpdate=!1)}function r(g,A){g.opacity.value=A.opacity,A.color&&g.diffuse.value.copy(A.color),A.emissive&&g.emissive.value.copy(A.emissive).multiplyScalar(A.emissiveIntensity),A.map&&(g.map.value=A.map,t(A.map,g.mapTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.bumpMap&&(g.bumpMap.value=A.bumpMap,t(A.bumpMap,g.bumpMapTransform),g.bumpScale.value=A.bumpScale,A.side===Ln&&(g.bumpScale.value*=-1)),A.normalMap&&(g.normalMap.value=A.normalMap,t(A.normalMap,g.normalMapTransform),g.normalScale.value.copy(A.normalScale),A.side===Ln&&g.normalScale.value.negate()),A.displacementMap&&(g.displacementMap.value=A.displacementMap,t(A.displacementMap,g.displacementMapTransform),g.displacementScale.value=A.displacementScale,g.displacementBias.value=A.displacementBias),A.emissiveMap&&(g.emissiveMap.value=A.emissiveMap,t(A.emissiveMap,g.emissiveMapTransform)),A.specularMap&&(g.specularMap.value=A.specularMap,t(A.specularMap,g.specularMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest);const _=e.get(A),x=_.envMap,E=_.envMapRotation;x&&(g.envMap.value=x,br.copy(E),br.x*=-1,br.y*=-1,br.z*=-1,x.isCubeTexture&&x.isRenderTargetTexture===!1&&(br.y*=-1,br.z*=-1),g.envMapRotation.value.setFromMatrix4(n1.makeRotationFromEuler(br)),g.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=A.reflectivity,g.ior.value=A.ior,g.refractionRatio.value=A.refractionRatio),A.lightMap&&(g.lightMap.value=A.lightMap,g.lightMapIntensity.value=A.lightMapIntensity,t(A.lightMap,g.lightMapTransform)),A.aoMap&&(g.aoMap.value=A.aoMap,g.aoMapIntensity.value=A.aoMapIntensity,t(A.aoMap,g.aoMapTransform))}function a(g,A){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,A.map&&(g.map.value=A.map,t(A.map,g.mapTransform))}function o(g,A){g.dashSize.value=A.dashSize,g.totalSize.value=A.dashSize+A.gapSize,g.scale.value=A.scale}function c(g,A,_,x){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,g.size.value=A.size*_,g.scale.value=x*.5,A.map&&(g.map.value=A.map,t(A.map,g.uvTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest)}function l(g,A){g.diffuse.value.copy(A.color),g.opacity.value=A.opacity,g.rotation.value=A.rotation,A.map&&(g.map.value=A.map,t(A.map,g.mapTransform)),A.alphaMap&&(g.alphaMap.value=A.alphaMap,t(A.alphaMap,g.alphaMapTransform)),A.alphaTest>0&&(g.alphaTest.value=A.alphaTest)}function h(g,A){g.specular.value.copy(A.specular),g.shininess.value=Math.max(A.shininess,1e-4)}function u(g,A){A.gradientMap&&(g.gradientMap.value=A.gradientMap)}function d(g,A){g.metalness.value=A.metalness,A.metalnessMap&&(g.metalnessMap.value=A.metalnessMap,t(A.metalnessMap,g.metalnessMapTransform)),g.roughness.value=A.roughness,A.roughnessMap&&(g.roughnessMap.value=A.roughnessMap,t(A.roughnessMap,g.roughnessMapTransform)),A.envMap&&(g.envMapIntensity.value=A.envMapIntensity)}function f(g,A,_){g.ior.value=A.ior,A.sheen>0&&(g.sheenColor.value.copy(A.sheenColor).multiplyScalar(A.sheen),g.sheenRoughness.value=A.sheenRoughness,A.sheenColorMap&&(g.sheenColorMap.value=A.sheenColorMap,t(A.sheenColorMap,g.sheenColorMapTransform)),A.sheenRoughnessMap&&(g.sheenRoughnessMap.value=A.sheenRoughnessMap,t(A.sheenRoughnessMap,g.sheenRoughnessMapTransform))),A.clearcoat>0&&(g.clearcoat.value=A.clearcoat,g.clearcoatRoughness.value=A.clearcoatRoughness,A.clearcoatMap&&(g.clearcoatMap.value=A.clearcoatMap,t(A.clearcoatMap,g.clearcoatMapTransform)),A.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=A.clearcoatRoughnessMap,t(A.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),A.clearcoatNormalMap&&(g.clearcoatNormalMap.value=A.clearcoatNormalMap,t(A.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(A.clearcoatNormalScale),A.side===Ln&&g.clearcoatNormalScale.value.negate())),A.dispersion>0&&(g.dispersion.value=A.dispersion),A.iridescence>0&&(g.iridescence.value=A.iridescence,g.iridescenceIOR.value=A.iridescenceIOR,g.iridescenceThicknessMinimum.value=A.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=A.iridescenceThicknessRange[1],A.iridescenceMap&&(g.iridescenceMap.value=A.iridescenceMap,t(A.iridescenceMap,g.iridescenceMapTransform)),A.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=A.iridescenceThicknessMap,t(A.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),A.transmission>0&&(g.transmission.value=A.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),A.transmissionMap&&(g.transmissionMap.value=A.transmissionMap,t(A.transmissionMap,g.transmissionMapTransform)),g.thickness.value=A.thickness,A.thicknessMap&&(g.thicknessMap.value=A.thicknessMap,t(A.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=A.attenuationDistance,g.attenuationColor.value.copy(A.attenuationColor)),A.anisotropy>0&&(g.anisotropyVector.value.set(A.anisotropy*Math.cos(A.anisotropyRotation),A.anisotropy*Math.sin(A.anisotropyRotation)),A.anisotropyMap&&(g.anisotropyMap.value=A.anisotropyMap,t(A.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=A.specularIntensity,g.specularColor.value.copy(A.specularColor),A.specularColorMap&&(g.specularColorMap.value=A.specularColorMap,t(A.specularColorMap,g.specularColorMapTransform)),A.specularIntensityMap&&(g.specularIntensityMap.value=A.specularIntensityMap,t(A.specularIntensityMap,g.specularIntensityMapTransform))}function p(g,A){A.matcap&&(g.matcap.value=A.matcap)}function m(g,A){const _=e.get(A).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function s1(i,e,t,n){let s={},r={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(_,x){const E=x.program;n.uniformBlockBinding(_,E)}function l(_,x){let E=s[_.id];E===void 0&&(p(_),E=h(_),s[_.id]=E,_.addEventListener("dispose",g));const S=x.program;n.updateUBOMapping(_,S);const w=e.render.frame;r[_.id]!==w&&(d(_),r[_.id]=w)}function h(_){const x=u();_.__bindingPointIndex=x;const E=i.createBuffer(),S=_.__size,w=_.usage;return i.bindBuffer(i.UNIFORM_BUFFER,E),i.bufferData(i.UNIFORM_BUFFER,S,w),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,x,E),E}function u(){for(let _=0;_<o;_++)if(a.indexOf(_)===-1)return a.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(_){const x=s[_.id],E=_.uniforms,S=_.__cache;i.bindBuffer(i.UNIFORM_BUFFER,x);for(let w=0,I=E.length;w<I;w++){const T=Array.isArray(E[w])?E[w]:[E[w]];for(let C=0,v=T.length;C<v;C++){const F=T[C];if(f(F,w,C,S)===!0){const K=F.__offset,q=Array.isArray(F.value)?F.value:[F.value];let $=0;for(let D=0;D<q.length;D++){const O=q[D],Y=m(O);typeof O=="number"||typeof O=="boolean"?(F.__data[0]=O,i.bufferSubData(i.UNIFORM_BUFFER,K+$,F.__data)):O.isMatrix3?(F.__data[0]=O.elements[0],F.__data[1]=O.elements[1],F.__data[2]=O.elements[2],F.__data[3]=0,F.__data[4]=O.elements[3],F.__data[5]=O.elements[4],F.__data[6]=O.elements[5],F.__data[7]=0,F.__data[8]=O.elements[6],F.__data[9]=O.elements[7],F.__data[10]=O.elements[8],F.__data[11]=0):(O.toArray(F.__data,$),$+=Y.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,K,F.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(_,x,E,S){const w=_.value,I=x+"_"+E;if(S[I]===void 0)return typeof w=="number"||typeof w=="boolean"?S[I]=w:S[I]=w.clone(),!0;{const T=S[I];if(typeof w=="number"||typeof w=="boolean"){if(T!==w)return S[I]=w,!0}else if(T.equals(w)===!1)return T.copy(w),!0}return!1}function p(_){const x=_.uniforms;let E=0;const S=16;for(let I=0,T=x.length;I<T;I++){const C=Array.isArray(x[I])?x[I]:[x[I]];for(let v=0,F=C.length;v<F;v++){const K=C[v],q=Array.isArray(K.value)?K.value:[K.value];for(let $=0,D=q.length;$<D;$++){const O=q[$],Y=m(O),Q=E%S,J=Q%Y.boundary,ee=Q+J;E+=J,ee!==0&&S-ee<Y.storage&&(E+=S-ee),K.__data=new Float32Array(Y.storage/Float32Array.BYTES_PER_ELEMENT),K.__offset=E,E+=Y.storage}}}const w=E%S;return w>0&&(E+=S-w),_.__size=E,_.__cache={},this}function m(_){const x={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(x.boundary=4,x.storage=4):_.isVector2?(x.boundary=8,x.storage=8):_.isVector3||_.isColor?(x.boundary=16,x.storage=12):_.isVector4?(x.boundary=16,x.storage=16):_.isMatrix3?(x.boundary=48,x.storage=48):_.isMatrix4?(x.boundary=64,x.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),x}function g(_){const x=_.target;x.removeEventListener("dispose",g);const E=a.indexOf(x.__bindingPointIndex);a.splice(E,1),i.deleteBuffer(s[x.id]),delete s[x.id],delete r[x.id]}function A(){for(const _ in s)i.deleteBuffer(s[_]);a=[],s={},r={}}return{bind:c,update:l,dispose:A}}class $g{constructor(e={}){const{canvas:t=m_(),context:n=null,depth:s=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let f;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=n.getContextAttributes().alpha}else f=a;const p=new Uint32Array(4),m=new Int32Array(4);let g=null,A=null;const _=[],x=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Is,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let S=!1;this._outputColorSpace=yt;let w=0,I=0,T=null,C=-1,v=null;const F=new gt,K=new gt;let q=null;const $=new Fe(0);let D=0,O=t.width,Y=t.height,Q=1,J=null,ee=null;const ae=new gt(0,0,O,Y),_e=new gt(0,0,O,Y);let Me=!1;const se=new rd;let me=!1,xe=!1;const be=new Re,Ue=new Re,et=new G,He=new gt,Mt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ft=!1;function $e(){return T===null?Q:1}let H=n;function wn(y,R){return t.getContext(y,R)}try{const y={alpha:!0,depth:s,stencil:r,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Ic}`),t.addEventListener("webglcontextlost",de,!1),t.addEventListener("webglcontextrestored",Se,!1),t.addEventListener("webglcontextcreationerror",Ie,!1),H===null){const R="webgl2";if(H=wn(R,y),H===null)throw wn(R)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(y){throw console.error("THREE.WebGLRenderer: "+y.message),y}let pt,mt,We,Dt,ze,L,M,Z,le,Ae,oe,Qe,ve,qe,Ze,Ee,De,Oe,Ge,Te,nt,Ke,it,W;function ne(){pt=new AI(H),pt.init(),Ke=new JS(H,pt),mt=new cI(H,pt,e,Ke),We=new XS(H,pt),mt.reverseDepthBuffer&&d&&We.buffers.depth.setReversed(!0),Dt=new xI(H),ze=new PS,L=new YS(H,pt,We,ze,mt,Ke,Dt),M=new hI(E),Z=new pI(E),le=new sv(H),it=new aI(H,le),Ae=new gI(H,le,Dt,it),oe=new EI(H,Ae,le,Dt),Ge=new bI(H,mt,L),Ee=new lI(ze),Qe=new LS(E,M,Z,pt,mt,it,Ee),ve=new i1(E,ze),qe=new US,Ze=new VS(pt),Oe=new rI(E,M,Z,We,oe,f,c),De=new KS(E,oe,mt),W=new s1(H,Dt,mt,We),Te=new oI(H,pt,Dt),nt=new mI(H,pt,Dt),Dt.programs=Qe.programs,E.capabilities=mt,E.extensions=pt,E.properties=ze,E.renderLists=qe,E.shadowMap=De,E.state=We,E.info=Dt}ne();const re=new t1(E,H);this.xr=re,this.getContext=function(){return H},this.getContextAttributes=function(){return H.getContextAttributes()},this.forceContextLoss=function(){const y=pt.get("WEBGL_lose_context");y&&y.loseContext()},this.forceContextRestore=function(){const y=pt.get("WEBGL_lose_context");y&&y.restoreContext()},this.getPixelRatio=function(){return Q},this.setPixelRatio=function(y){y!==void 0&&(Q=y,this.setSize(O,Y,!1))},this.getSize=function(y){return y.set(O,Y)},this.setSize=function(y,R,N=!0){if(re.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}O=y,Y=R,t.width=Math.floor(y*Q),t.height=Math.floor(R*Q),N===!0&&(t.style.width=y+"px",t.style.height=R+"px"),this.setViewport(0,0,y,R)},this.getDrawingBufferSize=function(y){return y.set(O*Q,Y*Q).floor()},this.setDrawingBufferSize=function(y,R,N){O=y,Y=R,Q=N,t.width=Math.floor(y*N),t.height=Math.floor(R*N),this.setViewport(0,0,y,R)},this.getCurrentViewport=function(y){return y.copy(F)},this.getViewport=function(y){return y.copy(ae)},this.setViewport=function(y,R,N,U){y.isVector4?ae.set(y.x,y.y,y.z,y.w):ae.set(y,R,N,U),We.viewport(F.copy(ae).multiplyScalar(Q).round())},this.getScissor=function(y){return y.copy(_e)},this.setScissor=function(y,R,N,U){y.isVector4?_e.set(y.x,y.y,y.z,y.w):_e.set(y,R,N,U),We.scissor(K.copy(_e).multiplyScalar(Q).round())},this.getScissorTest=function(){return Me},this.setScissorTest=function(y){We.setScissorTest(Me=y)},this.setOpaqueSort=function(y){J=y},this.setTransparentSort=function(y){ee=y},this.getClearColor=function(y){return y.copy(Oe.getClearColor())},this.setClearColor=function(){Oe.setClearColor(...arguments)},this.getClearAlpha=function(){return Oe.getClearAlpha()},this.setClearAlpha=function(){Oe.setClearAlpha(...arguments)},this.clear=function(y=!0,R=!0,N=!0){let U=0;if(y){let P=!1;if(T!==null){const z=T.texture.format;P=z===ou||z===au||z===ru}if(P){const z=T.texture.type,j=z===cn||z===rr||z===io||z===so||z===iu||z===su,X=Oe.getClearColor(),ie=Oe.getClearAlpha(),he=X.r,ce=X.g,fe=X.b;j?(p[0]=he,p[1]=ce,p[2]=fe,p[3]=ie,H.clearBufferuiv(H.COLOR,0,p)):(m[0]=he,m[1]=ce,m[2]=fe,m[3]=ie,H.clearBufferiv(H.COLOR,0,m))}else U|=H.COLOR_BUFFER_BIT}R&&(U|=H.DEPTH_BUFFER_BIT),N&&(U|=H.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),H.clear(U)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",de,!1),t.removeEventListener("webglcontextrestored",Se,!1),t.removeEventListener("webglcontextcreationerror",Ie,!1),Oe.dispose(),qe.dispose(),Ze.dispose(),ze.dispose(),M.dispose(),Z.dispose(),oe.dispose(),it.dispose(),W.dispose(),Qe.dispose(),re.dispose(),re.removeEventListener("sessionstart",Gh),re.removeEventListener("sessionend",Hh),ws.stop()};function de(y){y.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),S=!0}function Se(){console.log("THREE.WebGLRenderer: Context Restored."),S=!1;const y=Dt.autoReset,R=De.enabled,N=De.autoUpdate,U=De.needsUpdate,P=De.type;ne(),Dt.autoReset=y,De.enabled=R,De.autoUpdate=N,De.needsUpdate=U,De.type=P}function Ie(y){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",y.statusMessage)}function st(y){const R=y.target;R.removeEventListener("dispose",st),Ht(R)}function Ht(y){vn(y),ze.remove(y)}function vn(y){const R=ze.get(y).programs;R!==void 0&&(R.forEach(function(N){Qe.releaseProgram(N)}),y.isShaderMaterial&&Qe.releaseShaderCache(y))}this.renderBufferDirect=function(y,R,N,U,P,z){R===null&&(R=Mt);const j=P.isMesh&&P.matrixWorld.determinant()<0,X=Hp(y,R,N,U,P);We.setMaterial(U,j);let ie=N.index,he=1;if(U.wireframe===!0){if(ie=Ae.getWireframeAttribute(N),ie===void 0)return;he=2}const ce=N.drawRange,fe=N.attributes.position;let ge=ce.start*he,ye=(ce.start+ce.count)*he;z!==null&&(ge=Math.max(ge,z.start*he),ye=Math.min(ye,(z.start+z.count)*he)),ie!==null?(ge=Math.max(ge,0),ye=Math.min(ye,ie.count)):fe!=null&&(ge=Math.max(ge,0),ye=Math.min(ye,fe.count));const Pe=ye-ge;if(Pe<0||Pe===1/0)return;it.setup(P,U,X,N,ie);let je,Ve=Te;if(ie!==null&&(je=le.get(ie),Ve=nt,Ve.setIndex(je)),P.isMesh)U.wireframe===!0?(We.setLineWidth(U.wireframeLinewidth*$e()),Ve.setMode(H.LINES)):Ve.setMode(H.TRIANGLES);else if(P.isLine){let Le=U.linewidth;Le===void 0&&(Le=1),We.setLineWidth(Le*$e()),P.isLineSegments?Ve.setMode(H.LINES):P.isLineLoop?Ve.setMode(H.LINE_LOOP):Ve.setMode(H.LINE_STRIP)}else P.isPoints?Ve.setMode(H.POINTS):P.isSprite&&Ve.setMode(H.TRIANGLES);if(P.isBatchedMesh)if(P._multiDrawInstances!==null)Vc("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Ve.renderMultiDrawInstances(P._multiDrawStarts,P._multiDrawCounts,P._multiDrawCount,P._multiDrawInstances);else if(pt.get("WEBGL_multi_draw"))Ve.renderMultiDraw(P._multiDrawStarts,P._multiDrawCounts,P._multiDrawCount);else{const Le=P._multiDrawStarts,rt=P._multiDrawCounts,ke=P._multiDrawCount,It=ie?le.get(ie).bytesPerElement:1,mn=ze.get(U).currentProgram.getUniforms();for(let vt=0;vt<ke;vt++)mn.setValue(H,"_gl_DrawID",vt),Ve.render(Le[vt]/It,rt[vt])}else if(P.isInstancedMesh)Ve.renderInstances(ge,Pe,P.count);else if(N.isInstancedBufferGeometry){const Le=N._maxInstanceCount!==void 0?N._maxInstanceCount:1/0,rt=Math.min(N.instanceCount,Le);Ve.renderInstances(ge,Pe,rt)}else Ve.render(ge,Pe)};function Ct(y,R,N){y.transparent===!0&&y.side===Pi&&y.forceSinglePass===!1?(y.side=Ln,y.needsUpdate=!0,to(y,R,N),y.side=ji,y.needsUpdate=!0,to(y,R,N),y.side=Pi):to(y,R,N)}this.compile=function(y,R,N=null){N===null&&(N=y),A=Ze.get(N),A.init(R),x.push(A),N.traverseVisible(function(P){P.isLight&&P.layers.test(R.layers)&&(A.pushLight(P),P.castShadow&&A.pushShadow(P))}),y!==N&&y.traverseVisible(function(P){P.isLight&&P.layers.test(R.layers)&&(A.pushLight(P),P.castShadow&&A.pushShadow(P))}),A.setupLights();const U=new Set;return y.traverse(function(P){if(!(P.isMesh||P.isPoints||P.isLine||P.isSprite))return;const z=P.material;if(z)if(Array.isArray(z))for(let j=0;j<z.length;j++){const X=z[j];Ct(X,N,P),U.add(X)}else Ct(z,N,P),U.add(z)}),A=x.pop(),U},this.compileAsync=function(y,R,N=null){const U=this.compile(y,R,N);return new Promise(P=>{function z(){if(U.forEach(function(j){ze.get(j).currentProgram.isReady()&&U.delete(j)}),U.size===0){P(y);return}setTimeout(z,10)}pt.get("KHR_parallel_shader_compile")!==null?z():setTimeout(z,10)})};let si=null;function Li(y){si&&si(y)}function Gh(){ws.stop()}function Hh(){ws.start()}const ws=new Cg;ws.setAnimationLoop(Li),typeof self<"u"&&ws.setContext(self),this.setAnimationLoop=function(y){si=y,re.setAnimationLoop(y),y===null?ws.stop():ws.start()},re.addEventListener("sessionstart",Gh),re.addEventListener("sessionend",Hh),this.render=function(y,R){if(R!==void 0&&R.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(S===!0)return;if(y.matrixWorldAutoUpdate===!0&&y.updateMatrixWorld(),R.parent===null&&R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),re.enabled===!0&&re.isPresenting===!0&&(re.cameraAutoUpdate===!0&&re.updateCamera(R),R=re.getCamera()),y.isScene===!0&&y.onBeforeRender(E,y,R,T),A=Ze.get(y,x.length),A.init(R),x.push(A),Ue.multiplyMatrices(R.projectionMatrix,R.matrixWorldInverse),se.setFromProjectionMatrix(Ue),xe=this.localClippingEnabled,me=Ee.init(this.clippingPlanes,xe),g=qe.get(y,_.length),g.init(),_.push(g),re.enabled===!0&&re.isPresenting===!0){const z=E.xr.getDepthSensingMesh();z!==null&&_c(z,R,-1/0,E.sortObjects)}_c(y,R,0,E.sortObjects),g.finish(),E.sortObjects===!0&&g.sort(J,ee),ft=re.enabled===!1||re.isPresenting===!1||re.hasDepthSensing()===!1,ft&&Oe.addToRenderList(g,y),this.info.render.frame++,me===!0&&Ee.beginShadows();const N=A.state.shadowsArray;De.render(N,y,R),me===!0&&Ee.endShadows(),this.info.autoReset===!0&&this.info.reset();const U=g.opaque,P=g.transmissive;if(A.setupLights(),R.isArrayCamera){const z=R.cameras;if(P.length>0)for(let j=0,X=z.length;j<X;j++){const ie=z[j];zh(U,P,y,ie)}ft&&Oe.render(y);for(let j=0,X=z.length;j<X;j++){const ie=z[j];wc(g,y,ie,ie.viewport)}}else P.length>0&&zh(U,P,y,R),ft&&Oe.render(y),wc(g,y,R);T!==null&&I===0&&(L.updateMultisampleRenderTarget(T),L.updateRenderTargetMipmap(T)),y.isScene===!0&&y.onAfterRender(E,y,R),it.resetDefaultState(),C=-1,v=null,x.pop(),x.length>0?(A=x[x.length-1],me===!0&&Ee.setGlobalState(E.clippingPlanes,A.state.camera)):A=null,_.pop(),_.length>0?g=_[_.length-1]:g=null};function _c(y,R,N,U){if(y.visible===!1)return;if(y.layers.test(R.layers)){if(y.isGroup)N=y.renderOrder;else if(y.isLOD)y.autoUpdate===!0&&y.update(R);else if(y.isLight)A.pushLight(y),y.castShadow&&A.pushShadow(y);else if(y.isSprite){if(!y.frustumCulled||se.intersectsSprite(y)){U&&He.setFromMatrixPosition(y.matrixWorld).applyMatrix4(Ue);const j=oe.update(y),X=y.material;X.visible&&g.push(y,j,X,N,He.z,null)}}else if((y.isMesh||y.isLine||y.isPoints)&&(!y.frustumCulled||se.intersectsObject(y))){const j=oe.update(y),X=y.material;if(U&&(y.boundingSphere!==void 0?(y.boundingSphere===null&&y.computeBoundingSphere(),He.copy(y.boundingSphere.center)):(j.boundingSphere===null&&j.computeBoundingSphere(),He.copy(j.boundingSphere.center)),He.applyMatrix4(y.matrixWorld).applyMatrix4(Ue)),Array.isArray(X)){const ie=j.groups;for(let he=0,ce=ie.length;he<ce;he++){const fe=ie[he],ge=X[fe.materialIndex];ge&&ge.visible&&g.push(y,j,ge,N,He.z,fe)}}else X.visible&&g.push(y,j,X,N,He.z,null)}}const z=y.children;for(let j=0,X=z.length;j<X;j++)_c(z[j],R,N,U)}function wc(y,R,N,U){const P=y.opaque,z=y.transmissive,j=y.transparent;A.setupLightsView(N),me===!0&&Ee.setGlobalState(E.clippingPlanes,N),U&&We.viewport(F.copy(U)),P.length>0&&eo(P,R,N),z.length>0&&eo(z,R,N),j.length>0&&eo(j,R,N),We.buffers.depth.setTest(!0),We.buffers.depth.setMask(!0),We.buffers.color.setMask(!0),We.setPolygonOffset(!1)}function zh(y,R,N,U){if((N.isScene===!0?N.overrideMaterial:null)!==null)return;A.state.transmissionRenderTarget[U.id]===void 0&&(A.state.transmissionRenderTarget[U.id]=new or(1,1,{generateMipmaps:!0,type:pt.has("EXT_color_buffer_half_float")||pt.has("EXT_color_buffer_float")?kn:cn,minFilter:ri,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:tt.workingColorSpace}));const z=A.state.transmissionRenderTarget[U.id],j=U.viewport||F;z.setSize(j.z*E.transmissionResolutionScale,j.w*E.transmissionResolutionScale);const X=E.getRenderTarget();E.setRenderTarget(z),E.getClearColor($),D=E.getClearAlpha(),D<1&&E.setClearColor(16777215,.5),E.clear(),ft&&Oe.render(N);const ie=E.toneMapping;E.toneMapping=Is;const he=U.viewport;if(U.viewport!==void 0&&(U.viewport=void 0),A.setupLightsView(U),me===!0&&Ee.setGlobalState(E.clippingPlanes,U),eo(y,N,U),L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z),pt.has("WEBGL_multisampled_render_to_texture")===!1){let ce=!1;for(let fe=0,ge=R.length;fe<ge;fe++){const ye=R[fe],Pe=ye.object,je=ye.geometry,Ve=ye.material,Le=ye.group;if(Ve.side===Pi&&Pe.layers.test(U.layers)){const rt=Ve.side;Ve.side=Ln,Ve.needsUpdate=!0,Vh(Pe,N,U,je,Ve,Le),Ve.side=rt,Ve.needsUpdate=!0,ce=!0}}ce===!0&&(L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z))}E.setRenderTarget(X),E.setClearColor($,D),he!==void 0&&(U.viewport=he),E.toneMapping=ie}function eo(y,R,N){const U=R.isScene===!0?R.overrideMaterial:null;for(let P=0,z=y.length;P<z;P++){const j=y[P],X=j.object,ie=j.geometry,he=j.group;let ce=j.material;ce.allowOverride===!0&&U!==null&&(ce=U),X.layers.test(N.layers)&&Vh(X,R,N,ie,ce,he)}}function Vh(y,R,N,U,P,z){y.onBeforeRender(E,R,N,U,P,z),y.modelViewMatrix.multiplyMatrices(N.matrixWorldInverse,y.matrixWorld),y.normalMatrix.getNormalMatrix(y.modelViewMatrix),P.onBeforeRender(E,R,N,U,y,z),P.transparent===!0&&P.side===Pi&&P.forceSinglePass===!1?(P.side=Ln,P.needsUpdate=!0,E.renderBufferDirect(N,R,U,P,y,z),P.side=ji,P.needsUpdate=!0,E.renderBufferDirect(N,R,U,P,y,z),P.side=Pi):E.renderBufferDirect(N,R,U,P,y,z),y.onAfterRender(E,R,N,U,P,z)}function to(y,R,N){R.isScene!==!0&&(R=Mt);const U=ze.get(y),P=A.state.lights,z=A.state.shadowsArray,j=P.state.version,X=Qe.getParameters(y,P.state,z,R,N),ie=Qe.getProgramCacheKey(X);let he=U.programs;U.environment=y.isMeshStandardMaterial?R.environment:null,U.fog=R.fog,U.envMap=(y.isMeshStandardMaterial?Z:M).get(y.envMap||U.environment),U.envMapRotation=U.environment!==null&&y.envMap===null?R.environmentRotation:y.envMapRotation,he===void 0&&(y.addEventListener("dispose",st),he=new Map,U.programs=he);let ce=he.get(ie);if(ce!==void 0){if(U.currentProgram===ce&&U.lightsStateVersion===j)return Cc(y,X),ce}else X.uniforms=Qe.getUniforms(y),y.onBeforeCompile(X,E),ce=Qe.acquireProgram(X,ie),he.set(ie,ce),U.uniforms=X.uniforms;const fe=U.uniforms;return(!y.isShaderMaterial&&!y.isRawShaderMaterial||y.clipping===!0)&&(fe.clippingPlanes=Ee.uniform),Cc(y,X),U.needsLights=tr(y),U.lightsStateVersion=j,U.needsLights&&(fe.ambientLightColor.value=P.state.ambient,fe.lightProbe.value=P.state.probe,fe.directionalLights.value=P.state.directional,fe.directionalLightShadows.value=P.state.directionalShadow,fe.spotLights.value=P.state.spot,fe.spotLightShadows.value=P.state.spotShadow,fe.rectAreaLights.value=P.state.rectArea,fe.ltc_1.value=P.state.rectAreaLTC1,fe.ltc_2.value=P.state.rectAreaLTC2,fe.pointLights.value=P.state.point,fe.pointLightShadows.value=P.state.pointShadow,fe.hemisphereLights.value=P.state.hemi,fe.directionalShadowMap.value=P.state.directionalShadowMap,fe.directionalShadowMatrix.value=P.state.directionalShadowMatrix,fe.spotShadowMap.value=P.state.spotShadowMap,fe.spotLightMatrix.value=P.state.spotLightMatrix,fe.spotLightMap.value=P.state.spotLightMap,fe.pointShadowMap.value=P.state.pointShadowMap,fe.pointShadowMatrix.value=P.state.pointShadowMatrix),U.currentProgram=ce,U.uniformsList=null,ce}function vc(y){if(y.uniformsList===null){const R=y.currentProgram.getUniforms();y.uniformsList=Nl.seqWithValue(R.seq,y.uniforms)}return y.uniformsList}function Cc(y,R){const N=ze.get(y);N.outputColorSpace=R.outputColorSpace,N.batching=R.batching,N.batchingColor=R.batchingColor,N.instancing=R.instancing,N.instancingColor=R.instancingColor,N.instancingMorph=R.instancingMorph,N.skinning=R.skinning,N.morphTargets=R.morphTargets,N.morphNormals=R.morphNormals,N.morphColors=R.morphColors,N.morphTargetsCount=R.morphTargetsCount,N.numClippingPlanes=R.numClippingPlanes,N.numIntersection=R.numClipIntersection,N.vertexAlphas=R.vertexAlphas,N.vertexTangents=R.vertexTangents,N.toneMapping=R.toneMapping}function Hp(y,R,N,U,P){R.isScene!==!0&&(R=Mt),L.resetTextureUnits();const z=R.fog,j=U.isMeshStandardMaterial?R.environment:null,X=T===null?E.outputColorSpace:T.isXRRenderTarget===!0?T.texture.colorSpace:un,ie=(U.isMeshStandardMaterial?Z:M).get(U.envMap||j),he=U.vertexColors===!0&&!!N.attributes.color&&N.attributes.color.itemSize===4,ce=!!N.attributes.tangent&&(!!U.normalMap||U.anisotropy>0),fe=!!N.morphAttributes.position,ge=!!N.morphAttributes.normal,ye=!!N.morphAttributes.color;let Pe=Is;U.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(Pe=E.toneMapping);const je=N.morphAttributes.position||N.morphAttributes.normal||N.morphAttributes.color,Ve=je!==void 0?je.length:0,Le=ze.get(U),rt=A.state.lights;if(me===!0&&(xe===!0||y!==v)){const Ut=y===v&&U.id===C;Ee.setState(U,y,Ut)}let ke=!1;U.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==rt.state.version||Le.outputColorSpace!==X||P.isBatchedMesh&&Le.batching===!1||!P.isBatchedMesh&&Le.batching===!0||P.isBatchedMesh&&Le.batchingColor===!0&&P.colorTexture===null||P.isBatchedMesh&&Le.batchingColor===!1&&P.colorTexture!==null||P.isInstancedMesh&&Le.instancing===!1||!P.isInstancedMesh&&Le.instancing===!0||P.isSkinnedMesh&&Le.skinning===!1||!P.isSkinnedMesh&&Le.skinning===!0||P.isInstancedMesh&&Le.instancingColor===!0&&P.instanceColor===null||P.isInstancedMesh&&Le.instancingColor===!1&&P.instanceColor!==null||P.isInstancedMesh&&Le.instancingMorph===!0&&P.morphTexture===null||P.isInstancedMesh&&Le.instancingMorph===!1&&P.morphTexture!==null||Le.envMap!==ie||U.fog===!0&&Le.fog!==z||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Ee.numPlanes||Le.numIntersection!==Ee.numIntersection)||Le.vertexAlphas!==he||Le.vertexTangents!==ce||Le.morphTargets!==fe||Le.morphNormals!==ge||Le.morphColors!==ye||Le.toneMapping!==Pe||Le.morphTargetsCount!==Ve)&&(ke=!0):(ke=!0,Le.__version=U.version);let It=Le.currentProgram;ke===!0&&(It=to(U,R,P));let mn=!1,vt=!1,Et=!1;const Xe=It.getUniforms(),Xt=Le.uniforms;if(We.useProgram(It.program)&&(mn=!0,vt=!0,Et=!0),U.id!==C&&(C=U.id,vt=!0),mn||v!==y){We.buffers.depth.getReversed()?(be.copy(y.projectionMatrix),b_(be),E_(be),Xe.setValue(H,"projectionMatrix",be)):Xe.setValue(H,"projectionMatrix",y.projectionMatrix),Xe.setValue(H,"viewMatrix",y.matrixWorldInverse);const xn=Xe.map.cameraPosition;xn!==void 0&&xn.setValue(H,et.setFromMatrixPosition(y.matrixWorld)),mt.logarithmicDepthBuffer&&Xe.setValue(H,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2)),(U.isMeshPhongMaterial||U.isMeshToonMaterial||U.isMeshLambertMaterial||U.isMeshBasicMaterial||U.isMeshStandardMaterial||U.isShaderMaterial)&&Xe.setValue(H,"isOrthographic",y.isOrthographicCamera===!0),v!==y&&(v=y,vt=!0,Et=!0)}if(P.isSkinnedMesh){Xe.setOptional(H,P,"bindMatrix"),Xe.setOptional(H,P,"bindMatrixInverse");const Ut=P.skeleton;Ut&&(Ut.boneTexture===null&&Ut.computeBoneTexture(),Xe.setValue(H,"boneTexture",Ut.boneTexture,L))}P.isBatchedMesh&&(Xe.setOptional(H,P,"batchingTexture"),Xe.setValue(H,"batchingTexture",P._matricesTexture,L),Xe.setOptional(H,P,"batchingIdTexture"),Xe.setValue(H,"batchingIdTexture",P._indirectTexture,L),Xe.setOptional(H,P,"batchingColorTexture"),P._colorsTexture!==null&&Xe.setValue(H,"batchingColorTexture",P._colorsTexture,L));const Cn=N.morphAttributes;if((Cn.position!==void 0||Cn.normal!==void 0||Cn.color!==void 0)&&Ge.update(P,N,It),(vt||Le.receiveShadow!==P.receiveShadow)&&(Le.receiveShadow=P.receiveShadow,Xe.setValue(H,"receiveShadow",P.receiveShadow)),U.isMeshGouraudMaterial&&U.envMap!==null&&(Xt.envMap.value=ie,Xt.flipEnvMap.value=ie.isCubeTexture&&ie.isRenderTargetTexture===!1?-1:1),U.isMeshStandardMaterial&&U.envMap===null&&R.environment!==null&&(Xt.envMapIntensity.value=R.environmentIntensity),vt&&(Xe.setValue(H,"toneMappingExposure",E.toneMappingExposure),Le.needsLights&&vs(Xt,Et),z&&U.fog===!0&&ve.refreshFogUniforms(Xt,z),ve.refreshMaterialUniforms(Xt,U,Q,Y,A.state.transmissionRenderTarget[y.id]),Nl.upload(H,vc(Le),Xt,L)),U.isShaderMaterial&&U.uniformsNeedUpdate===!0&&(Nl.upload(H,vc(Le),Xt,L),U.uniformsNeedUpdate=!1),U.isSpriteMaterial&&Xe.setValue(H,"center",P.center),Xe.setValue(H,"modelViewMatrix",P.modelViewMatrix),Xe.setValue(H,"normalMatrix",P.normalMatrix),Xe.setValue(H,"modelMatrix",P.matrixWorld),U.isShaderMaterial||U.isRawShaderMaterial){const Ut=U.uniformsGroups;for(let xn=0,zp=Ut.length;xn<zp;xn++){const Wr=Ut[xn];W.update(Wr,It),W.bind(Wr,It)}}return It}function vs(y,R){y.ambientLightColor.needsUpdate=R,y.lightProbe.needsUpdate=R,y.directionalLights.needsUpdate=R,y.directionalLightShadows.needsUpdate=R,y.pointLights.needsUpdate=R,y.pointLightShadows.needsUpdate=R,y.spotLights.needsUpdate=R,y.spotLightShadows.needsUpdate=R,y.rectAreaLights.needsUpdate=R,y.hemisphereLights.needsUpdate=R}function tr(y){return y.isMeshLambertMaterial||y.isMeshToonMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isShadowMaterial||y.isShaderMaterial&&y.lights===!0}this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return I},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(y,R,N){const U=ze.get(y);U.__autoAllocateDepthBuffer=y.resolveDepthBuffer===!1,U.__autoAllocateDepthBuffer===!1&&(U.__useRenderToTexture=!1),ze.get(y.texture).__webglTexture=R,ze.get(y.depthTexture).__webglTexture=U.__autoAllocateDepthBuffer?void 0:N,U.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(y,R){const N=ze.get(y);N.__webglFramebuffer=R,N.__useDefaultFramebuffer=R===void 0};const b=H.createFramebuffer();this.setRenderTarget=function(y,R=0,N=0){T=y,w=R,I=N;let U=!0,P=null,z=!1,j=!1;if(y){const ie=ze.get(y);if(ie.__useDefaultFramebuffer!==void 0)We.bindFramebuffer(H.FRAMEBUFFER,null),U=!1;else if(ie.__webglFramebuffer===void 0)L.setupRenderTarget(y);else if(ie.__hasExternalTextures)L.rebindTextures(y,ze.get(y.texture).__webglTexture,ze.get(y.depthTexture).__webglTexture);else if(y.depthBuffer){const fe=y.depthTexture;if(ie.__boundDepthTexture!==fe){if(fe!==null&&ze.has(fe)&&(y.width!==fe.image.width||y.height!==fe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(y)}}const he=y.texture;(he.isData3DTexture||he.isDataArrayTexture||he.isCompressedArrayTexture)&&(j=!0);const ce=ze.get(y).__webglFramebuffer;y.isWebGLCubeRenderTarget?(Array.isArray(ce[R])?P=ce[R][N]:P=ce[R],z=!0):y.samples>0&&L.useMultisampledRTT(y)===!1?P=ze.get(y).__webglMultisampledFramebuffer:Array.isArray(ce)?P=ce[N]:P=ce,F.copy(y.viewport),K.copy(y.scissor),q=y.scissorTest}else F.copy(ae).multiplyScalar(Q).floor(),K.copy(_e).multiplyScalar(Q).floor(),q=Me;if(N!==0&&(P=b),We.bindFramebuffer(H.FRAMEBUFFER,P)&&U&&We.drawBuffers(y,P),We.viewport(F),We.scissor(K),We.setScissorTest(q),z){const ie=ze.get(y.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+R,ie.__webglTexture,N)}else if(j){const ie=ze.get(y.texture),he=R;H.framebufferTextureLayer(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,ie.__webglTexture,N,he)}else if(y!==null&&N!==0){const ie=ze.get(y.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,ie.__webglTexture,N)}C=-1},this.readRenderTargetPixels=function(y,R,N,U,P,z,j){if(!(y&&y.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let X=ze.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&j!==void 0&&(X=X[j]),X){We.bindFramebuffer(H.FRAMEBUFFER,X);try{const ie=y.texture,he=ie.format,ce=ie.type;if(!mt.textureFormatReadable(he)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!mt.textureTypeReadable(ce)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}R>=0&&R<=y.width-U&&N>=0&&N<=y.height-P&&H.readPixels(R,N,U,P,Ke.convert(he),Ke.convert(ce),z)}finally{const ie=T!==null?ze.get(T).__webglFramebuffer:null;We.bindFramebuffer(H.FRAMEBUFFER,ie)}}},this.readRenderTargetPixelsAsync=async function(y,R,N,U,P,z,j){if(!(y&&y.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let X=ze.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&j!==void 0&&(X=X[j]),X)if(R>=0&&R<=y.width-U&&N>=0&&N<=y.height-P){We.bindFramebuffer(H.FRAMEBUFFER,X);const ie=y.texture,he=ie.format,ce=ie.type;if(!mt.textureFormatReadable(he))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!mt.textureTypeReadable(ce))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const fe=H.createBuffer();H.bindBuffer(H.PIXEL_PACK_BUFFER,fe),H.bufferData(H.PIXEL_PACK_BUFFER,z.byteLength,H.STREAM_READ),H.readPixels(R,N,U,P,Ke.convert(he),Ke.convert(ce),0);const ge=T!==null?ze.get(T).__webglFramebuffer:null;We.bindFramebuffer(H.FRAMEBUFFER,ge);const ye=H.fenceSync(H.SYNC_GPU_COMMANDS_COMPLETE,0);return H.flush(),await x_(H,ye,4),H.bindBuffer(H.PIXEL_PACK_BUFFER,fe),H.getBufferSubData(H.PIXEL_PACK_BUFFER,0,z),H.deleteBuffer(fe),H.deleteSync(ye),z}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(y,R=null,N=0){const U=Math.pow(2,-N),P=Math.floor(y.image.width*U),z=Math.floor(y.image.height*U),j=R!==null?R.x:0,X=R!==null?R.y:0;L.setTexture2D(y,0),H.copyTexSubImage2D(H.TEXTURE_2D,N,0,0,j,X,P,z),We.unbindTexture()};const B=H.createFramebuffer(),k=H.createFramebuffer();this.copyTextureToTexture=function(y,R,N=null,U=null,P=0,z=null){z===null&&(P!==0?(Vc("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),z=P,P=0):z=0);let j,X,ie,he,ce,fe,ge,ye,Pe;const je=y.isCompressedTexture?y.mipmaps[z]:y.image;if(N!==null)j=N.max.x-N.min.x,X=N.max.y-N.min.y,ie=N.isBox3?N.max.z-N.min.z:1,he=N.min.x,ce=N.min.y,fe=N.isBox3?N.min.z:0;else{const Cn=Math.pow(2,-P);j=Math.floor(je.width*Cn),X=Math.floor(je.height*Cn),y.isDataArrayTexture?ie=je.depth:y.isData3DTexture?ie=Math.floor(je.depth*Cn):ie=1,he=0,ce=0,fe=0}U!==null?(ge=U.x,ye=U.y,Pe=U.z):(ge=0,ye=0,Pe=0);const Ve=Ke.convert(R.format),Le=Ke.convert(R.type);let rt;R.isData3DTexture?(L.setTexture3D(R,0),rt=H.TEXTURE_3D):R.isDataArrayTexture||R.isCompressedArrayTexture?(L.setTexture2DArray(R,0),rt=H.TEXTURE_2D_ARRAY):(L.setTexture2D(R,0),rt=H.TEXTURE_2D),H.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,R.flipY),H.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),H.pixelStorei(H.UNPACK_ALIGNMENT,R.unpackAlignment);const ke=H.getParameter(H.UNPACK_ROW_LENGTH),It=H.getParameter(H.UNPACK_IMAGE_HEIGHT),mn=H.getParameter(H.UNPACK_SKIP_PIXELS),vt=H.getParameter(H.UNPACK_SKIP_ROWS),Et=H.getParameter(H.UNPACK_SKIP_IMAGES);H.pixelStorei(H.UNPACK_ROW_LENGTH,je.width),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,je.height),H.pixelStorei(H.UNPACK_SKIP_PIXELS,he),H.pixelStorei(H.UNPACK_SKIP_ROWS,ce),H.pixelStorei(H.UNPACK_SKIP_IMAGES,fe);const Xe=y.isDataArrayTexture||y.isData3DTexture,Xt=R.isDataArrayTexture||R.isData3DTexture;if(y.isDepthTexture){const Cn=ze.get(y),Ut=ze.get(R),xn=ze.get(Cn.__renderTarget),zp=ze.get(Ut.__renderTarget);We.bindFramebuffer(H.READ_FRAMEBUFFER,xn.__webglFramebuffer),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,zp.__webglFramebuffer);for(let Wr=0;Wr<ie;Wr++)Xe&&(H.framebufferTextureLayer(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,ze.get(y).__webglTexture,P,fe+Wr),H.framebufferTextureLayer(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,ze.get(R).__webglTexture,z,Pe+Wr)),H.blitFramebuffer(he,ce,j,X,ge,ye,j,X,H.DEPTH_BUFFER_BIT,H.NEAREST);We.bindFramebuffer(H.READ_FRAMEBUFFER,null),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,null)}else if(P!==0||y.isRenderTargetTexture||ze.has(y)){const Cn=ze.get(y),Ut=ze.get(R);We.bindFramebuffer(H.READ_FRAMEBUFFER,B),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,k);for(let xn=0;xn<ie;xn++)Xe?H.framebufferTextureLayer(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,Cn.__webglTexture,P,fe+xn):H.framebufferTexture2D(H.READ_FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,Cn.__webglTexture,P),Xt?H.framebufferTextureLayer(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,Ut.__webglTexture,z,Pe+xn):H.framebufferTexture2D(H.DRAW_FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,Ut.__webglTexture,z),P!==0?H.blitFramebuffer(he,ce,j,X,ge,ye,j,X,H.COLOR_BUFFER_BIT,H.NEAREST):Xt?H.copyTexSubImage3D(rt,z,ge,ye,Pe+xn,he,ce,j,X):H.copyTexSubImage2D(rt,z,ge,ye,he,ce,j,X);We.bindFramebuffer(H.READ_FRAMEBUFFER,null),We.bindFramebuffer(H.DRAW_FRAMEBUFFER,null)}else Xt?y.isDataTexture||y.isData3DTexture?H.texSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,Le,je.data):R.isCompressedArrayTexture?H.compressedTexSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,je.data):H.texSubImage3D(rt,z,ge,ye,Pe,j,X,ie,Ve,Le,je):y.isDataTexture?H.texSubImage2D(H.TEXTURE_2D,z,ge,ye,j,X,Ve,Le,je.data):y.isCompressedTexture?H.compressedTexSubImage2D(H.TEXTURE_2D,z,ge,ye,je.width,je.height,Ve,je.data):H.texSubImage2D(H.TEXTURE_2D,z,ge,ye,j,X,Ve,Le,je);H.pixelStorei(H.UNPACK_ROW_LENGTH,ke),H.pixelStorei(H.UNPACK_IMAGE_HEIGHT,It),H.pixelStorei(H.UNPACK_SKIP_PIXELS,mn),H.pixelStorei(H.UNPACK_SKIP_ROWS,vt),H.pixelStorei(H.UNPACK_SKIP_IMAGES,Et),z===0&&R.generateMipmaps&&H.generateMipmap(rt),We.unbindTexture()},this.copyTextureToTexture3D=function(y,R,N=null,U=null,P=0){return Vc('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(y,R,N,U,P)},this.initRenderTarget=function(y){ze.get(y).__webglFramebuffer===void 0&&L.setupRenderTarget(y)},this.initTexture=function(y){y.isCubeTexture?L.setTextureCube(y,0):y.isData3DTexture?L.setTexture3D(y,0):y.isDataArrayTexture||y.isCompressedArrayTexture?L.setTexture2DArray(y,0):L.setTexture2D(y,0),We.unbindTexture()},this.resetState=function(){w=0,I=0,T=null,We.reset(),it.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Yi}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=tt._getDrawingBufferColorSpace(e),t.unpackColorSpace=tt._getUnpackColorSpace()}}var Lo=function(){var i=0,e=document.createElement("div");e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",function(h){h.preventDefault(),n(++i%e.children.length)},!1);function t(h){return e.appendChild(h.dom),h}function n(h){for(var u=0;u<e.children.length;u++)e.children[u].style.display=u===h?"block":"none";i=h}var s=(performance||Date).now(),r=s,a=0,o=t(new Lo.Panel("FPS","#0ff","#002")),c=t(new Lo.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var l=t(new Lo.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:e,addPanel:t,showPanel:n,begin:function(){s=(performance||Date).now()},end:function(){a++;var h=(performance||Date).now();if(c.update(h-s,200),h>=r+1e3&&(o.update(a*1e3/(h-r),100),r=h,a=0,l)){var u=performance.memory;l.update(u.usedJSHeapSize/1048576,u.jsHeapSizeLimit/1048576)}return h},update:function(){s=this.end()},domElement:e,setMode:n}};Lo.Panel=function(i,e,t){var n=1/0,s=0,r=Math.round,a=r(window.devicePixelRatio||1),o=80*a,c=48*a,l=3*a,h=2*a,u=3*a,d=15*a,f=74*a,p=30*a,m=document.createElement("canvas");m.width=o,m.height=c,m.style.cssText="width:80px;height:48px";var g=m.getContext("2d");return g.font="bold "+9*a+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=t,g.fillRect(0,0,o,c),g.fillStyle=e,g.fillText(i,l,h),g.fillRect(u,d,f,p),g.fillStyle=t,g.globalAlpha=.9,g.fillRect(u,d,f,p),{dom:m,update:function(A,_){n=Math.min(n,A),s=Math.max(s,A),g.fillStyle=t,g.globalAlpha=1,g.fillRect(0,0,o,d),g.fillStyle=e,g.fillText(r(A)+" "+i+" ("+r(n)+"-"+r(s)+")",l,h),g.drawImage(m,u+a,d,f-a,p,u,d,f-a,p),g.fillRect(u+f-a,d,a,p),g.fillStyle=t,g.globalAlpha=.9,g.fillRect(u+f-a,d,a,r((1-A/_)*p))}}};function em(i,e){if(e===Vy)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===Mu||e===oA){let t=i.getIndex();if(t===null){const a=[],o=i.getAttribute("position");if(o!==void 0){for(let c=0;c<o.count;c++)a.push(c);i.setIndex(a),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}const n=t.count-2,s=[];if(e===Mu)for(let a=1;a<=n;a++)s.push(t.getX(0)),s.push(t.getX(a)),s.push(t.getX(a+1));else for(let a=0;a<n;a++)a%2===0?(s.push(t.getX(a)),s.push(t.getX(a+1)),s.push(t.getX(a+2))):(s.push(t.getX(a+2)),s.push(t.getX(a+1)),s.push(t.getX(a)));s.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const r=i.clone();return r.setIndex(s),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}class Bd extends ci{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new l1(t)}),this.register(function(t){return new h1(t)}),this.register(function(t){return new b1(t)}),this.register(function(t){return new E1(t)}),this.register(function(t){return new y1(t)}),this.register(function(t){return new d1(t)}),this.register(function(t){return new f1(t)}),this.register(function(t){return new p1(t)}),this.register(function(t){return new A1(t)}),this.register(function(t){return new c1(t)}),this.register(function(t){return new g1(t)}),this.register(function(t){return new u1(t)}),this.register(function(t){return new x1(t)}),this.register(function(t){return new m1(t)}),this.register(function(t){return new a1(t)}),this.register(function(t){return new _1(t)}),this.register(function(t){return new w1(t)})}load(e,t,n,s){const r=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const l=Ar.extractUrlBase(e);a=Ar.resolveURL(l,this.path)}else a=Ar.extractUrlBase(e);this.manager.itemStart(e);const o=function(l){s?s(l):console.error(l),r.manager.itemError(e),r.manager.itemEnd(e)},c=new os(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(l){try{r.parse(l,a,function(h){t(h),r.manager.itemEnd(e)},o)}catch(h){o(h)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,s){let r;const a={},o={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===tm){try{a[At.KHR_BINARY_GLTF]=new v1(e)}catch(u){s&&s(u);return}r=JSON.parse(a[At.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){s&&s(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const l=new k1(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const u=this.pluginCallbacks[h](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[u.name]=u,a[u.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){const u=r.extensionsUsed[h],d=r.extensionsRequired||[];switch(u){case At.KHR_MATERIALS_UNLIT:a[u]=new o1;break;case At.KHR_DRACO_MESH_COMPRESSION:a[u]=new C1(r,this.dracoLoader);break;case At.KHR_TEXTURE_TRANSFORM:a[u]=new I1;break;case At.KHR_MESH_QUANTIZATION:a[u]=new S1;break;default:d.indexOf(u)>=0&&o[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(a),l.setPlugins(o),l.parse(n,s)}parseAsync(e,t){const n=this;return new Promise(function(s,r){n.parse(e,t,s,r)})}}function r1(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}const At={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class a1{constructor(e){this.parser=e,this.name=At.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,s=t.length;n<s;n++){const r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let s=t.cache.get(n);if(s)return s;const r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let l;const h=new Fe(16777215);c.color!==void 0&&h.setRGB(c.color[0],c.color[1],c.color[2],un);const u=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new gd(h),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new Ml(h),l.distance=u;break;case"spot":l=new mg(h),l.distance=u,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,l.angle=c.spot.outerConeAngle,l.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return l.position.set(0,0,0),cs(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),s=Promise.resolve(l),t.cache.add(n,s),s}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,r=n.json.nodes[e],o=(r.extensions&&r.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(c){return n._getNodeRef(t.cache,o,c)})}}class o1{constructor(){this.name=At.KHR_MATERIALS_UNLIT}getMaterialType(){return Ds}extendParams(e,t,n){const s=[];e.color=new Fe(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const a=r.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],un),e.opacity=a[3]}r.baseColorTexture!==void 0&&s.push(n.assignTexture(e,"map",r.baseColorTexture,yt))}return Promise.all(s)}}class c1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}}class l1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(r.push(n.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Je(o,o)}return Promise.all(r)}}class h1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}}class u1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(r)}}class d1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new Fe(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=s.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],un)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&r.push(n.assignTexture(t,"sheenColorMap",a.sheenColorTexture,yt)),a.sheenRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(r)}}class f1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&r.push(n.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(r)}}class p1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&r.push(n.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new Fe().setRGB(o[0],o[1],o[2],un),Promise.all(r)}}class A1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const s=this.parser.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=s.extensions[this.name];return t.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}}class g1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&r.push(n.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new Fe().setRGB(o[0],o[1],o[2],un),a.specularColorTexture!==void 0&&r.push(n.assignTexture(t,"specularColorMap",a.specularColorTexture,yt)),Promise.all(r)}}class m1{constructor(e){this.parser=e,this.name=At.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&r.push(n.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(r)}}class x1{constructor(e){this.parser=e,this.name=At.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Oi}extendMaterialParams(e,t){const n=this.parser,s=n.json.materials[e];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const r=[],a=s.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&r.push(n.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(r)}}class b1{constructor(e){this.parser=e,this.name=At.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,s=n.textures[e];if(!s.extensions||!s.extensions[this.name])return null;const r=s.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,a)}}class E1{constructor(e){this.parser=e,this.name=At.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=s.images[a.source];let c=n.textureLoader;if(o.uri){const l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}}class y1{constructor(e){this.parser=e,this.name=At.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,s=n.json,r=s.textures[e];if(!r.extensions||!r.extensions[t])return null;const a=r.extensions[t],o=s.images[a.source];let c=n.textureLoader;if(o.uri){const l=n.options.manager.getHandler(o.uri);l!==null&&(c=l)}return n.loadTextureImage(e,a.source,c)}}class _1{constructor(e){this.name=At.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const s=n.extensions[this.name],r=this.parser.getDependency("buffer",s.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(o){const c=s.byteOffset||0,l=s.byteLength||0,h=s.count,u=s.byteStride,d=new Uint8Array(o,c,l);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,s.mode,s.filter).then(function(f){return f.buffer}):a.ready.then(function(){const f=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(f),h,u,d,s.mode,s.filter),f})})}else return null}}class w1{constructor(e){this.name=At.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const s=t.meshes[n.mesh];for(const l of s.primitives)if(l.mode!==li.TRIANGLES&&l.mode!==li.TRIANGLE_STRIP&&l.mode!==li.TRIANGLE_FAN&&l.mode!==void 0)return null;const a=n.extensions[this.name].attributes,o=[],c={};for(const l in a)o.push(this.parser.getDependency("accessor",a[l]).then(h=>(c[l]=h,c[l])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(l=>{const h=l.pop(),u=h.isGroup?h.children:[h],d=l[0].count,f=[];for(const p of u){const m=new Re,g=new G,A=new Yt,_=new G(1,1,1),x=new jA(p.geometry,p.material,d);for(let E=0;E<d;E++)c.TRANSLATION&&g.fromBufferAttribute(c.TRANSLATION,E),c.ROTATION&&A.fromBufferAttribute(c.ROTATION,E),c.SCALE&&_.fromBufferAttribute(c.SCALE,E),x.setMatrixAt(E,m.compose(g,A,_));for(const E in c)if(E==="_COLOR_0"){const S=c[E];x.instanceColor=new id(S.array,S.itemSize,S.normalized)}else E!=="TRANSLATION"&&E!=="ROTATION"&&E!=="SCALE"&&p.geometry.setAttribute(E,c[E]);Tt.prototype.copy.call(x,p),this.parser.assignFinalMaterial(x),f.push(x)}return h.isGroup?(h.clear(),h.add(...f),h):f[0]}))}}const tm="glTF",Po=12,nm={JSON:1313821514,BIN:5130562};class v1{constructor(e){this.name=At.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Po),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==tm)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const s=this.header.length-Po,r=new DataView(e,Po);let a=0;for(;a<s;){const o=r.getUint32(a,!0);a+=4;const c=r.getUint32(a,!0);if(a+=4,c===nm.JSON){const l=new Uint8Array(e,Po+a,o);this.content=n.decode(l)}else if(c===nm.BIN){const l=Po+a;this.body=e.slice(l,l+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class C1{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=At.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,s=this.dracoLoader,r=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},c={},l={};for(const h in a){const u=Rd[h]||h.toLowerCase();o[u]=a[h]}for(const h in e.attributes){const u=Rd[h]||h.toLowerCase();if(a[h]!==void 0){const d=n.accessors[e.attributes[h]],f=va[d.componentType];l[u]=f.name,c[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(u,d){s.decodeDracoFile(h,function(f){for(const p in f.attributes){const m=f.attributes[p],g=c[p];g!==void 0&&(m.normalized=g)}u(f)},o,l,un,d)})})}}class I1{constructor(){this.name=At.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class S1{constructor(){this.name=At.KHR_MESH_QUANTIZATION}}class im extends Ro{constructor(e,t,n,s){super(e,t,n,s)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=e*s*3+s;for(let a=0;a!==s;a++)t[a]=n[r+a];return t}interpolate_(e,t,n,s){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,c=o*2,l=o*3,h=s-t,u=(n-t)/h,d=u*u,f=d*u,p=e*l,m=p-l,g=-2*f+3*d,A=f-d,_=1-g,x=A-d+u;for(let E=0;E!==o;E++){const S=a[m+E+o],w=a[m+E+c]*h,I=a[p+E+o],T=a[p+E]*h;r[E]=_*S+x*w+g*I+A*T}return r}}const M1=new Yt;class B1 extends im{interpolate_(e,t,n,s){const r=super.interpolate_(e,t,n,s);return M1.fromArray(r).normalize().toArray(r),r}}const li={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},va={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},sm={9728:Pn,9729:qt,9984:Zp,9985:Rc,9986:no,9987:ri},rm={33071:Zn,33648:Tc,10497:Ss},Td={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Rd={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Qs={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},T1={CUBICSPLINE:void 0,LINEAR:po,STEP:fo},Fd={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function R1(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new To({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:ji})),i.DefaultMaterial}function Er(i,e,t){for(const n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function cs(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function F1(i,e,t){let n=!1,s=!1,r=!1;for(let l=0,h=e.length;l<h;l++){const u=e[l];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(s=!0),u.COLOR_0!==void 0&&(r=!0),n&&s&&r)break}if(!n&&!s&&!r)return Promise.resolve(i);const a=[],o=[],c=[];for(let l=0,h=e.length;l<h;l++){const u=e[l];if(n){const d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):i.attributes.position;a.push(d)}if(s){const d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):i.attributes.normal;o.push(d)}if(r){const d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):i.attributes.color;c.push(d)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c)]).then(function(l){const h=l[0],u=l[1],d=l[2];return n&&(i.morphAttributes.position=h),s&&(i.morphAttributes.normal=u),r&&(i.morphAttributes.color=d),i.morphTargetsRelative=!0,i})}function N1(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,s=t.length;n<s;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function D1(i){let e;const t=i.extensions&&i.extensions[At.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Nd(t.attributes):e=i.indices+":"+Nd(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,s=i.targets.length;n<s;n++)e+=":"+Nd(i.targets[n]);return e}function Nd(i){let e="";const t=Object.keys(i).sort();for(let n=0,s=t.length;n<s;n++)e+=t[n]+":"+i[t[n]]+";";return e}function Dd(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function L1(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const P1=new Re;class k1{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new r1,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,s=-1,r=!1,a=-1;if(typeof navigator<"u"){const o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;const c=o.match(/Version\/(\d+)/);s=n&&c?parseInt(c[1],10):-1,r=o.indexOf("Firefox")>-1,a=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&s<17||r&&a<98?this.textureLoader=new pg(this.options.manager):this.textureLoader=new Qw(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new os(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,s=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(a){const o={scene:a[0][s.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:s.asset,parser:n,userData:{}};return Er(r,o,s),cs(o,s),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(o)})).then(function(){for(const c of o.scenes)c.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let s=0,r=t.length;s<r;s++){const a=t[s].joints;for(let o=0,c=a.length;o<c;o++)e[a[o]].isBone=!0}for(let s=0,r=e.length;s<r;s++){const a=e[s];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(n[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const s=n.clone(),r=(a,o)=>{const c=this.associations.get(a);c!=null&&this.associations.set(o,c);for(const[l,h]of a.children.entries())r(h,o.children[l])};return r(n,s),s.name+="_instance_"+e.uses[t]++,s}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const s=e(t[n]);if(s)return s}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let s=0;s<t.length;s++){const r=e(t[s]);r&&n.push(r)}return n}getDependency(e,t){const n=e+":"+t;let s=this.cache.get(n);if(!s){switch(e){case"scene":s=this.loadScene(t);break;case"node":s=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":s=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":s=this.loadAccessor(t);break;case"bufferView":s=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":s=this.loadBuffer(t);break;case"material":s=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":s=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":s=this.loadSkin(t);break;case"animation":s=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":s=this.loadCamera(t);break;default:if(s=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!s)throw new Error("Unknown type: "+e);break}this.cache.add(n,s)}return s}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,s=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(s.map(function(r,a){return n.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[At.KHR_BINARY_GLTF].body);const s=this.options;return new Promise(function(r,a){n.load(Ar.resolveURL(t.uri,s.path),r,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const s=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+s)})}loadAccessor(e){const t=this,n=this.json,s=this.json.accessors[e];if(s.bufferView===void 0&&s.sparse===void 0){const a=Td[s.type],o=va[s.componentType],c=s.normalized===!0,l=new o(s.count*a);return Promise.resolve(new Sn(l,a,c))}const r=[];return s.bufferView!==void 0?r.push(this.getDependency("bufferView",s.bufferView)):r.push(null),s.sparse!==void 0&&(r.push(this.getDependency("bufferView",s.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",s.sparse.values.bufferView))),Promise.all(r).then(function(a){const o=a[0],c=Td[s.type],l=va[s.componentType],h=l.BYTES_PER_ELEMENT,u=h*c,d=s.byteOffset||0,f=s.bufferView!==void 0?n.bufferViews[s.bufferView].byteStride:void 0,p=s.normalized===!0;let m,g;if(f&&f!==u){const A=Math.floor(d/f),_="InterleavedBuffer:"+s.bufferView+":"+s.componentType+":"+A+":"+s.count;let x=t.cache.get(_);x||(m=new l(o,A*f,s.count*f/h),x=new K_(m,f/h),t.cache.add(_,x)),g=new ed(x,c,d%f/h,p)}else o===null?m=new l(s.count*c):m=new l(o,d,s.count*c),g=new Sn(m,c,p);if(s.sparse!==void 0){const A=Td.SCALAR,_=va[s.sparse.indices.componentType],x=s.sparse.indices.byteOffset||0,E=s.sparse.values.byteOffset||0,S=new _(a[1],x,s.sparse.count*A),w=new l(a[2],E,s.sparse.count*c);o!==null&&(g=new Sn(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let I=0,T=S.length;I<T;I++){const C=S[I];if(g.setX(C,w[I*c]),c>=2&&g.setY(C,w[I*c+1]),c>=3&&g.setZ(C,w[I*c+2]),c>=4&&g.setW(C,w[I*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=p}return g})}loadTexture(e){const t=this.json,n=this.options,r=t.textures[e].source,a=t.images[r];let o=this.textureLoader;if(a.uri){const c=n.manager.getHandler(a.uri);c!==null&&(o=c)}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,n){const s=this,r=this.json,a=r.textures[e],o=r.images[t],c=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[c])return this.textureCache[c];const l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(r.samplers||{})[a.sampler]||{};return h.magFilter=sm[d.magFilter]||qt,h.minFilter=sm[d.minFilter]||ri,h.wrapS=rm[d.wrapS]||Ss,h.wrapT=rm[d.wrapT]||Ss,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Pn&&h.minFilter!==qt,s.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){const n=this,s=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());const a=s.images[e],o=self.URL||self.webkitURL;let c=a.uri||"",l=!1;if(a.bufferView!==void 0)c=n.getDependency("bufferView",a.bufferView).then(function(u){l=!0;const d=new Blob([u],{type:a.mimeType});return c=o.createObjectURL(d),c});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(c).then(function(u){return new Promise(function(d,f){let p=d;t.isImageBitmapLoader===!0&&(p=function(m){const g=new nn(m);g.needsUpdate=!0,d(g)}),t.load(Ar.resolveURL(u,r.path),p,void 0,f)})}).then(function(u){return l===!0&&o.revokeObjectURL(c),cs(u,a),u.userData.mimeType=a.mimeType||L1(a.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,s){const r=this;return this.getDependency("texture",n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),r.extensions[At.KHR_TEXTURE_TRANSFORM]){const o=n.extensions!==void 0?n.extensions[At.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const c=r.associations.get(a);a=r.extensions[At.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),r.associations.set(a,c)}}return s!==void 0&&(a.colorSpace=s),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const s=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+n.uuid;let c=this.cache.get(o);c||(c=new od,ai.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(o,c)),n=c}else if(e.isLine){const o="LineBasicMaterial:"+n.uuid;let c=this.cache.get(o);c||(c=new ma,ai.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(o,c)),n=c}if(s||r||a){let o="ClonedMaterial:"+n.uuid+":";s&&(o+="derivative-tangents:"),r&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let c=this.cache.get(o);c||(c=n.clone(),r&&(c.vertexColors=!0),a&&(c.flatShading=!0),s&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(o,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return To}loadMaterial(e){const t=this,n=this.json,s=this.extensions,r=n.materials[e];let a;const o={},c=r.extensions||{},l=[];if(c[At.KHR_MATERIALS_UNLIT]){const u=s[At.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),l.push(u.extendParams(o,r,t))}else{const u=r.pbrMetallicRoughness||{};if(o.color=new Fe(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){const d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],un),o.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(o,"map",u.baseColorTexture,yt)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}r.doubleSided===!0&&(o.side=Pi);const h=r.alphaMode||Fd.OPAQUE;if(h===Fd.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===Fd.MASK&&(o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&a!==Ds&&(l.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new Je(1,1),r.normalTexture.scale!==void 0)){const u=r.normalTexture.scale;o.normalScale.set(u,u)}if(r.occlusionTexture!==void 0&&a!==Ds&&(l.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&a!==Ds){const u=r.emissiveFactor;o.emissive=new Fe().setRGB(u[0],u[1],u[2],un)}return r.emissiveTexture!==void 0&&a!==Ds&&l.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,yt)),Promise.all(l).then(function(){const u=new a(o);return r.name&&(u.name=r.name),cs(u,r),t.associations.set(u,{materials:e}),r.extensions&&Er(s,u,r),u})}createUniqueName(e){const t=_t.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,s=this.primitiveCache;function r(o){return n[At.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(c){return am(c,o,t)})}const a=[];for(let o=0,c=e.length;o<c;o++){const l=e[o],h=D1(l),u=s[h];if(u)a.push(u.promise);else{let d;l.extensions&&l.extensions[At.KHR_DRACO_MESH_COMPRESSION]?d=r(l):d=am(new Mn,l,t),s[h]={primitive:l,promise:d},a.push(d)}}return Promise.all(a)}loadMesh(e){const t=this,n=this.json,s=this.extensions,r=n.meshes[e],a=r.primitives,o=[];for(let c=0,l=a.length;c<l;c++){const h=a[c].material===void 0?R1(this.cache):this.getDependency("material",a[c].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(c){const l=c.slice(0,c.length-1),h=c[c.length-1],u=[];for(let f=0,p=h.length;f<p;f++){const m=h[f],g=a[f];let A;const _=l[f];if(g.mode===li.TRIANGLES||g.mode===li.TRIANGLE_STRIP||g.mode===li.TRIANGLE_FAN||g.mode===void 0)A=r.isSkinnedMesh===!0?new VA(m,_):new Zt(m,_),A.isSkinnedMesh===!0&&A.normalizeSkinWeights(),g.mode===li.TRIANGLE_STRIP?A.geometry=em(A.geometry,oA):g.mode===li.TRIANGLE_FAN&&(A.geometry=em(A.geometry,Mu));else if(g.mode===li.LINES)A=new xl(m,_);else if(g.mode===li.LINE_STRIP)A=new gl(m,_);else if(g.mode===li.LINE_LOOP)A=new $_(m,_);else if(g.mode===li.POINTS)A=new ew(m,_);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(A.geometry.morphAttributes).length>0&&N1(A,r),A.name=t.createUniqueName(r.name||"mesh_"+e),cs(A,r),g.extensions&&Er(s,A,g),t.assignFinalMaterial(A),u.push(A)}for(let f=0,p=u.length;f<p;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1)return r.extensions&&Er(s,u[0],r),u[0];const d=new ss;r.extensions&&Er(s,d,r),t.associations.set(d,{meshes:e});for(let f=0,p=u.length;f<p;f++)d.add(u[f]);return d})}loadCamera(e){let t;const n=this.json.cameras[e],s=n[n.type];if(!s){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new Bn(In.radToDeg(s.yfov),s.aspectRatio||1,s.znear||1,s.zfar||2e6):n.type==="orthographic"&&(t=new Ad(-s.xmag,s.xmag,s.ymag,-s.ymag,s.znear,s.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),cs(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let s=0,r=t.joints.length;s<r;s++)n.push(this._loadNodeShallow(t.joints[s]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(s){const r=s.pop(),a=s,o=[],c=[];for(let l=0,h=a.length;l<h;l++){const u=a[l];if(u){o.push(u);const d=new Re;r!==null&&d.fromArray(r.array,l*16),c.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new hl(o,c)})}loadAnimation(e){const t=this.json,n=this,s=t.animations[e],r=s.name?s.name:"animation_"+e,a=[],o=[],c=[],l=[],h=[];for(let u=0,d=s.channels.length;u<d;u++){const f=s.channels[u],p=s.samplers[f.sampler],m=f.target,g=m.node,A=s.parameters!==void 0?s.parameters[p.input]:p.input,_=s.parameters!==void 0?s.parameters[p.output]:p.output;m.node!==void 0&&(a.push(this.getDependency("node",g)),o.push(this.getDependency("accessor",A)),c.push(this.getDependency("accessor",_)),l.push(p),h.push(m))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c),Promise.all(l),Promise.all(h)]).then(function(u){const d=u[0],f=u[1],p=u[2],m=u[3],g=u[4],A=[];for(let _=0,x=d.length;_<x;_++){const E=d[_],S=f[_],w=p[_],I=m[_],T=g[_];if(E===void 0)continue;E.updateMatrix&&E.updateMatrix();const C=n._createAnimationTracks(E,S,w,I,T);if(C)for(let v=0;v<C.length;v++)A.push(C[v])}return new Sl(r,void 0,A)})}createNodeMesh(e){const t=this.json,n=this,s=t.nodes[e];return s.mesh===void 0?null:n.getDependency("mesh",s.mesh).then(function(r){const a=n._getNodeRef(n.meshCache,s.mesh,r);return s.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let c=0,l=s.weights.length;c<l;c++)o.morphTargetInfluences[c]=s.weights[c]}),a})}loadNode(e){const t=this.json,n=this,s=t.nodes[e],r=n._loadNodeShallow(e),a=[],o=s.children||[];for(let l=0,h=o.length;l<h;l++)a.push(n.getDependency("node",o[l]));const c=s.skin===void 0?Promise.resolve(null):n.getDependency("skin",s.skin);return Promise.all([r,Promise.all(a),c]).then(function(l){const h=l[0],u=l[1],d=l[2];d!==null&&h.traverse(function(f){f.isSkinnedMesh&&f.bind(d,P1)});for(let f=0,p=u.length;f<p;f++)h.add(u[f]);return h})}_loadNodeShallow(e){const t=this.json,n=this.extensions,s=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const r=t.nodes[e],a=r.name?s.createUniqueName(r.name):"",o=[],c=s._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&o.push(c),r.camera!==void 0&&o.push(s.getDependency("camera",r.camera).then(function(l){return s._getNodeRef(s.cameraCache,r.camera,l)})),s._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){o.push(l)}),this.nodeCache[e]=Promise.all(o).then(function(l){let h;if(r.isBone===!0?h=new cl:l.length>1?h=new ss:l.length===1?h=l[0]:h=new Tt,h!==l[0])for(let u=0,d=l.length;u<d;u++)h.add(l[u]);if(r.name&&(h.userData.name=r.name,h.name=a),cs(h,r),r.extensions&&Er(n,h,r),r.matrix!==void 0){const u=new Re;u.fromArray(r.matrix),h.applyMatrix4(u)}else r.translation!==void 0&&h.position.fromArray(r.translation),r.rotation!==void 0&&h.quaternion.fromArray(r.rotation),r.scale!==void 0&&h.scale.fromArray(r.scale);return s.associations.has(h)||s.associations.set(h,{}),s.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],s=this,r=new ss;n.name&&(r.name=s.createUniqueName(n.name)),cs(r,n),n.extensions&&Er(t,r,n);const a=n.nodes||[],o=[];for(let c=0,l=a.length;c<l;c++)o.push(s.getDependency("node",a[c]));return Promise.all(o).then(function(c){for(let h=0,u=c.length;h<u;h++)r.add(c[h]);const l=h=>{const u=new Map;for(const[d,f]of s.associations)(d instanceof ai||d instanceof nn)&&u.set(d,f);return h.traverse(d=>{const f=s.associations.get(d);f!=null&&u.set(d,f)}),u};return s.associations=l(r),r})}_createAnimationTracks(e,t,n,s,r){const a=[],o=e.name?e.name:e.uuid,c=[];Qs[r.path]===Qs.weights?e.traverse(function(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}):c.push(o);let l;switch(Qs[r.path]){case Qs.weights:l=fr;break;case Qs.rotation:l=Us;break;case Qs.translation:case Qs.scale:l=pr;break;default:n.itemSize===1?l=fr:l=pr;break}const h=s.interpolation!==void 0?T1[s.interpolation]:po,u=this._getArrayFromAccessor(n);for(let d=0,f=c.length;d<f;d++){const p=new l(c[d]+"."+Qs[r.path],t.array,u,h);s.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(p),a.push(p)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Dd(t.constructor),s=new Float32Array(t.length);for(let r=0,a=t.length;r<a;r++)s[r]=t[r]*n;t=s}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const s=this instanceof Us?B1:im;return new s(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function U1(i,e,t){const n=e.attributes,s=new ki;if(n.POSITION!==void 0){const o=t.json.accessors[n.POSITION],c=o.min,l=o.max;if(c!==void 0&&l!==void 0){if(s.set(new G(c[0],c[1],c[2]),new G(l[0],l[1],l[2])),o.normalized){const h=Dd(va[o.componentType]);s.min.multiplyScalar(h),s.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const r=e.targets;if(r!==void 0){const o=new G,c=new G;for(let l=0,h=r.length;l<h;l++){const u=r[l];if(u.POSITION!==void 0){const d=t.json.accessors[u.POSITION],f=d.min,p=d.max;if(f!==void 0&&p!==void 0){if(c.setX(Math.max(Math.abs(f[0]),Math.abs(p[0]))),c.setY(Math.max(Math.abs(f[1]),Math.abs(p[1]))),c.setZ(Math.max(Math.abs(f[2]),Math.abs(p[2]))),d.normalized){const m=Dd(va[d.componentType]);c.multiplyScalar(m)}o.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}s.expandByVector(o)}i.boundingBox=s;const a=new Ui;s.getCenter(a.center),a.radius=s.min.distanceTo(s.max)/2,i.boundingSphere=a}function am(i,e,t){const n=e.attributes,s=[];function r(a,o){return t.getDependency("accessor",a).then(function(c){i.setAttribute(o,c)})}for(const a in n){const o=Rd[a]||a.toLowerCase();o in i.attributes||s.push(r(n[a],o))}if(e.indices!==void 0&&!i.index){const a=t.getDependency("accessor",e.indices).then(function(o){i.setIndex(o)});s.push(a)}return tt.workingColorSpace!==un&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${tt.workingColorSpace}" not supported.`),cs(i,e),U1(i,e,t),Promise.all(s).then(function(){return e.targets!==void 0?F1(i,e.targets,t):i})}var O1=(function(){var i="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdx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fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),n=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var s=WebAssembly.validate(t)?e:i,r,a=WebAssembly.instantiate(o(s),{}).then(function(A){r=A.instance,r.exports.__wasm_call_ctors()});function o(A){for(var _=new Uint8Array(A.length),x=0;x<A.length;++x){var E=A.charCodeAt(x);_[x]=E>96?E-97:E>64?E-39:E+4}for(var S=0,x=0;x<A.length;++x)_[S++]=_[x]<60?n[_[x]]:(_[x]-60)*64+_[++x];return _.buffer.slice(0,S)}function c(A,_,x,E,S,w){var I=r.exports.sbrk,T=x+3&-4,C=I(T*E),v=I(S.length),F=new Uint8Array(r.exports.memory.buffer);F.set(S,v);var K=A(C,x,E,v,S.length);if(K==0&&w&&w(C,T,E),_.set(F.subarray(C,C+x*E)),I(C-I(0)),K!=0)throw new Error("Malformed buffer data: "+K)}var l={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},h={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},u=[],d=0;function f(A){var _={object:new Worker(A),pending:0,requests:{}};return _.object.onmessage=function(x){var E=x.data;_.pending-=E.count,_.requests[E.id][E.action](E.value),delete _.requests[E.id]},_}function p(A){for(var _="var instance; var ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(o(s))+"]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;"+c.toString()+g.toString(),x=new Blob([_],{type:"text/javascript"}),E=URL.createObjectURL(x),S=0;S<A;++S)u[S]=f(E);URL.revokeObjectURL(E)}function m(A,_,x,E,S){for(var w=u[0],I=1;I<u.length;++I)u[I].pending<w.pending&&(w=u[I]);return new Promise(function(T,C){var v=new Uint8Array(x),F=d++;w.pending+=A,w.requests[F]={resolve:T,reject:C},w.object.postMessage({id:F,count:A,size:_,source:v,mode:E,filter:S},[v.buffer])})}function g(A){a.then(function(){var _=A.data;try{var x=new Uint8Array(_.count*_.size);c(r.exports[_.mode],x,_.count,_.size,_.source,r.exports[_.filter]),self.postMessage({id:_.id,count:_.count,action:"resolve",value:x},[x.buffer])}catch(E){self.postMessage({id:_.id,count:_.count,action:"reject",value:E})}})}return{ready:a,supported:!0,useWorkers:function(A){p(A)},decodeVertexBuffer:function(A,_,x,E,S){c(r.exports.meshopt_decodeVertexBuffer,A,_,x,E,r.exports[l[S]])},decodeIndexBuffer:function(A,_,x,E){c(r.exports.meshopt_decodeIndexBuffer,A,_,x,E)},decodeIndexSequence:function(A,_,x,E){c(r.exports.meshopt_decodeIndexSequence,A,_,x,E)},decodeGltfBuffer:function(A,_,x,E,S,w){c(r.exports[h[S]],A,_,x,E,r.exports[l[w]])},decodeGltfBufferAsync:function(A,_,x,E,S){return u.length>0?m(A,_,x,h[E],l[S]):a.then(function(){var w=new Uint8Array(A*_);return c(r.exports[h[E]],w,A,_,x,r.exports[l[S]]),w})}}})();const om={type:"change"},Ld={type:"start"},cm={type:"end"},Ll=new Eo,lm=new ks,Q1=Math.cos(70*In.DEG2RAD),An=new G,jn=2*Math.PI,Ft={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Pd=1e-6;class G1 extends nv{constructor(e,t=null){super(e,t),this.state=Ft.NONE,this.target=new G,this.cursor=new G,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:qr.ROTATE,MIDDLE:qr.DOLLY,RIGHT:qr.PAN},this.touches={ONE:Kr.ROTATE,TWO:Kr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new G,this._lastQuaternion=new Yt,this._lastTargetPosition=new G,this._quat=new Yt().setFromUnitVectors(e.up,new G(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new yg,this._sphericalDelta=new yg,this._scale=1,this._panOffset=new G,this._rotateStart=new Je,this._rotateEnd=new Je,this._rotateDelta=new Je,this._panStart=new Je,this._panEnd=new Je,this._panDelta=new Je,this._dollyStart=new Je,this._dollyEnd=new Je,this._dollyDelta=new Je,this._dollyDirection=new G,this._mouse=new Je,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=z1.bind(this),this._onPointerDown=H1.bind(this),this._onPointerUp=V1.bind(this),this._onContextMenu=J1.bind(this),this._onMouseWheel=K1.bind(this),this._onKeyDown=j1.bind(this),this._onTouchStart=X1.bind(this),this._onTouchMove=Y1.bind(this),this._onMouseDown=W1.bind(this),this._onMouseMove=q1.bind(this),this._interceptControlDown=Z1.bind(this),this._interceptControlUp=$1.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(om),this.update(),this.state=Ft.NONE}update(e=null){const t=this.object.position;An.copy(t).sub(this.target),An.applyQuaternion(this._quat),this._spherical.setFromVector3(An),this.autoRotate&&this.state===Ft.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=jn:n>Math.PI&&(n-=jn),s<-Math.PI?s+=jn:s>Math.PI&&(s-=jn),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=a!=this._spherical.radius}if(An.setFromSpherical(this._spherical),An.applyQuaternion(this._quatInverse),t.copy(this.target).add(An),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let a=null;if(this.object.isPerspectiveCamera){const o=An.length();a=this._clampDistance(o*this._scale);const c=o-a;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){const o=new G(this._mouse.x,this._mouse.y,0);o.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;const l=new G(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(o),this.object.updateMatrixWorld(),a=An.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(Ll.origin.copy(this.object.position),Ll.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Ll.direction))<Q1?this.object.lookAt(this.target):(lm.setFromNormalAndCoplanarPoint(this.object.up,this.target),Ll.intersectPlane(lm,this.target))))}else if(this.object.isOrthographicCamera){const a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Pd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Pd||this._lastTargetPosition.distanceToSquared(this.target)>Pd?(this.dispatchEvent(om),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?jn/60*this.autoRotateSpeed*e:jn/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){An.setFromMatrixColumn(t,0),An.multiplyScalar(-e),this._panOffset.add(An)}_panUp(e,t){this.screenSpacePanning===!0?An.setFromMatrixColumn(t,1):(An.setFromMatrixColumn(t,0),An.crossVectors(this.object.up,An)),An.multiplyScalar(e),this._panOffset.add(An)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const s=this.object.position;An.copy(s).sub(this.target);let r=An.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),s=e-n.left,r=t-n.top,a=n.width,o=n.height;this._mouse.x=s/a*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-jn*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panStart.set(n,s)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),s=.5*(e.pageX+n.x),r=.5*(e.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(jn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),s=.5*(e.pageY+t.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,s=e.pageY-t.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new Je,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function H1(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i)))}function z1(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function V1(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(cm),this.state=Ft.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function W1(i){let e;switch(i.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case qr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=Ft.DOLLY;break;case qr.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ft.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ft.ROTATE}break;case qr.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=Ft.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=Ft.PAN}break;default:this.state=Ft.NONE}this.state!==Ft.NONE&&this.dispatchEvent(Ld)}function q1(i){switch(this.state){case Ft.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case Ft.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case Ft.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function K1(i){this.enabled===!1||this.enableZoom===!1||this.state!==Ft.NONE||(i.preventDefault(),this.dispatchEvent(Ld),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(cm))}function j1(i){this.enabled!==!1&&this._handleKeyDown(i)}function X1(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case Kr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=Ft.TOUCH_ROTATE;break;case Kr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=Ft.TOUCH_PAN;break;default:this.state=Ft.NONE}break;case 2:switch(this.touches.TWO){case Kr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=Ft.TOUCH_DOLLY_PAN;break;case Kr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=Ft.TOUCH_DOLLY_ROTATE;break;default:this.state=Ft.NONE}break;default:this.state=Ft.NONE}this.state!==Ft.NONE&&this.dispatchEvent(Ld)}function Y1(i){switch(this._trackPointer(i),this.state){case Ft.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case Ft.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case Ft.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case Ft.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=Ft.NONE}}function J1(i){this.enabled!==!1&&i.preventDefault()}function Z1(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function $1(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}class eM extends $u{constructor(){super();const e=new da;e.deleteAttribute("uv");const t=new To({side:Ln}),n=new To,s=new Ml(16777215,900,28,2);s.position.set(.418,16.199,.3),this.add(s);const r=new Zt(e,t);r.position.set(-.757,13.219,.717),r.scale.set(31.713,28.305,28.591),this.add(r);const a=new jA(e,n,6),o=new Tt;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);const c=new Zt(e,Ca(50));c.position.set(-16.116,14.37,8.208),c.scale.set(.1,2.428,2.739),this.add(c);const l=new Zt(e,Ca(50));l.position.set(-16.109,18.021,-8.207),l.scale.set(.1,2.425,2.751),this.add(l);const h=new Zt(e,Ca(17));h.position.set(14.904,12.198,-1.832),h.scale.set(.15,4.265,6.331),this.add(h);const u=new Zt(e,Ca(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);const d=new Zt(e,Ca(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,.1),this.add(d);const f=new Zt(e,Ca(100));f.position.set(0,20,0),f.scale.set(1,.1,1),this.add(f)}dispose(){const e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(const t of e)t.dispose()}}function Ca(i){const e=new Ds;return e.color.setScalar(i),e}function tM(i){if(!(typeof window>"u")){var e=document.createElement("style");return e.setAttribute("type","text/css"),e.innerHTML=i,document.head.appendChild(e),i}}function Ia(i,e){var t=i.__state.conversionName.toString(),n=Math.round(i.r),s=Math.round(i.g),r=Math.round(i.b),a=i.a,o=Math.round(i.h),c=i.s.toFixed(1),l=i.v.toFixed(1);if(e||t==="THREE_CHAR_HEX"||t==="SIX_CHAR_HEX"){for(var h=i.hex.toString(16);h.length<6;)h="0"+h;return"#"+h}else{if(t==="CSS_RGB")return"rgb("+n+","+s+","+r+")";if(t==="CSS_RGBA")return"rgba("+n+","+s+","+r+","+a+")";if(t==="HEX")return"0x"+i.hex.toString(16);if(t==="RGB_ARRAY")return"["+n+","+s+","+r+"]";if(t==="RGBA_ARRAY")return"["+n+","+s+","+r+","+a+"]";if(t==="RGB_OBJ")return"{r:"+n+",g:"+s+",b:"+r+"}";if(t==="RGBA_OBJ")return"{r:"+n+",g:"+s+",b:"+r+",a:"+a+"}";if(t==="HSV_OBJ")return"{h:"+o+",s:"+c+",v:"+l+"}";if(t==="HSVA_OBJ")return"{h:"+o+",s:"+c+",v:"+l+",a:"+a+"}"}return"unknown format"}var hm=Array.prototype.forEach,ko=Array.prototype.slice,ue={BREAK:{},extend:function(e){return this.each(ko.call(arguments,1),function(t){var n=this.isObject(t)?Object.keys(t):[];n.forEach((function(s){this.isUndefined(t[s])||(e[s]=t[s])}).bind(this))},this),e},defaults:function(e){return this.each(ko.call(arguments,1),function(t){var n=this.isObject(t)?Object.keys(t):[];n.forEach((function(s){this.isUndefined(e[s])&&(e[s]=t[s])}).bind(this))},this),e},compose:function(){var e=ko.call(arguments);return function(){for(var t=ko.call(arguments),n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},each:function(e,t,n){if(e){if(hm&&e.forEach&&e.forEach===hm)e.forEach(t,n);else if(e.length===e.length+0){var s=void 0,r=void 0;for(s=0,r=e.length;s<r;s++)if(s in e&&t.call(n,e[s],s)===this.BREAK)return}else for(var a in e)if(t.call(n,e[a],a)===this.BREAK)return}},defer:function(e){setTimeout(e,0)},debounce:function(e,t,n){var s=void 0;return function(){var r=this,a=arguments;function o(){s=null,n||e.apply(r,a)}var c=n||!s;clearTimeout(s),s=setTimeout(o,t),c&&e.apply(r,a)}},toArray:function(e){return e.toArray?e.toArray():ko.call(e)},isUndefined:function(e){return e===void 0},isNull:function(e){return e===null},isNaN:(function(i){function e(t){return i.apply(this,arguments)}return e.toString=function(){return i.toString()},e})(function(i){return isNaN(i)}),isArray:Array.isArray||function(i){return i.constructor===Array},isObject:function(e){return e===Object(e)},isNumber:function(e){return e===e+0},isString:function(e){return e===e+""},isBoolean:function(e){return e===!1||e===!0},isFunction:function(e){return e instanceof Function}},nM=[{litmus:ue.isString,conversions:{THREE_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);return t===null?!1:{space:"HEX",hex:parseInt("0x"+t[1].toString()+t[1].toString()+t[2].toString()+t[2].toString()+t[3].toString()+t[3].toString(),0)}},write:Ia},SIX_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9]{6})$/i);return t===null?!1:{space:"HEX",hex:parseInt("0x"+t[1].toString(),0)}},write:Ia},CSS_RGB:{read:function(e){var t=e.match(/^rgb\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3])}},write:Ia},CSS_RGBA:{read:function(e){var t=e.match(/^rgba\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3]),a:parseFloat(t[4])}},write:Ia}}},{litmus:ue.isNumber,conversions:{HEX:{read:function(e){return{space:"HEX",hex:e,conversionName:"HEX"}},write:function(e){return e.hex}}}},{litmus:ue.isArray,conversions:{RGB_ARRAY:{read:function(e){return e.length!==3?!1:{space:"RGB",r:e[0],g:e[1],b:e[2]}},write:function(e){return[e.r,e.g,e.b]}},RGBA_ARRAY:{read:function(e){return e.length!==4?!1:{space:"RGB",r:e[0],g:e[1],b:e[2],a:e[3]}},write:function(e){return[e.r,e.g,e.b,e.a]}}}},{litmus:ue.isObject,conversions:{RGBA_OBJ:{read:function(e){return ue.isNumber(e.r)&&ue.isNumber(e.g)&&ue.isNumber(e.b)&&ue.isNumber(e.a)?{space:"RGB",r:e.r,g:e.g,b:e.b,a:e.a}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b,a:e.a}}},RGB_OBJ:{read:function(e){return ue.isNumber(e.r)&&ue.isNumber(e.g)&&ue.isNumber(e.b)?{space:"RGB",r:e.r,g:e.g,b:e.b}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b}}},HSVA_OBJ:{read:function(e){return ue.isNumber(e.h)&&ue.isNumber(e.s)&&ue.isNumber(e.v)&&ue.isNumber(e.a)?{space:"HSV",h:e.h,s:e.s,v:e.v,a:e.a}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v,a:e.a}}},HSV_OBJ:{read:function(e){return ue.isNumber(e.h)&&ue.isNumber(e.s)&&ue.isNumber(e.v)?{space:"HSV",h:e.h,s:e.s,v:e.v}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v}}}}}],Uo=void 0,Pl=void 0,kd=function(){Pl=!1;var e=arguments.length>1?ue.toArray(arguments):arguments[0];return ue.each(nM,function(t){if(t.litmus(e))return ue.each(t.conversions,function(n,s){if(Uo=n.read(e),Pl===!1&&Uo!==!1)return Pl=Uo,Uo.conversionName=s,Uo.conversion=n,ue.BREAK}),ue.BREAK}),Pl},um=void 0,kl={hsv_to_rgb:function(e,t,n){var s=Math.floor(e/60)%6,r=e/60-Math.floor(e/60),a=n*(1-t),o=n*(1-r*t),c=n*(1-(1-r)*t),l=[[n,c,a],[o,n,a],[a,n,c],[a,o,n],[c,a,n],[n,a,o]][s];return{r:l[0]*255,g:l[1]*255,b:l[2]*255}},rgb_to_hsv:function(e,t,n){var s=Math.min(e,t,n),r=Math.max(e,t,n),a=r-s,o=void 0,c=void 0;if(r!==0)c=a/r;else return{h:NaN,s:0,v:0};return e===r?o=(t-n)/a:t===r?o=2+(n-e)/a:o=4+(e-t)/a,o/=6,o<0&&(o+=1),{h:o*360,s:c,v:r/255}},rgb_to_hex:function(e,t,n){var s=this.hex_with_component(0,2,e);return s=this.hex_with_component(s,1,t),s=this.hex_with_component(s,0,n),s},component_from_hex:function(e,t){return e>>t*8&255},hex_with_component:function(e,t,n){return n<<(um=t*8)|e&~(255<<um)}},iM=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},Ci=function(i,e){if(!(i instanceof e))throw new TypeError("Cannot call a class as a function")},Ii=(function(){function i(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}})(),Gs=function i(e,t,n){e===null&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,t);if(s===void 0){var r=Object.getPrototypeOf(e);return r===null?void 0:i(r,t,n)}else{if("value"in s)return s.value;var a=s.get;return a===void 0?void 0:a.call(n)}},Hs=function(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof e);i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(i,e):i.__proto__=e)},zs=function(i,e){if(!i)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e&&(typeof e=="object"||typeof e=="function")?e:i},En=(function(){function i(){if(Ci(this,i),this.__state=kd.apply(this,arguments),this.__state===!1)throw new Error("Failed to interpret color arguments");this.__state.a=this.__state.a||1}return Ii(i,[{key:"toString",value:function(){return Ia(this)}},{key:"toHexString",value:function(){return Ia(this,!0)}},{key:"toOriginal",value:function(){return this.__state.conversion.write(this)}}]),i})();function Ud(i,e,t){Object.defineProperty(i,e,{get:function(){return this.__state.space==="RGB"?this.__state[e]:(En.recalculateRGB(this,e,t),this.__state[e])},set:function(s){this.__state.space!=="RGB"&&(En.recalculateRGB(this,e,t),this.__state.space="RGB"),this.__state[e]=s}})}function Od(i,e){Object.defineProperty(i,e,{get:function(){return this.__state.space==="HSV"?this.__state[e]:(En.recalculateHSV(this),this.__state[e])},set:function(n){this.__state.space!=="HSV"&&(En.recalculateHSV(this),this.__state.space="HSV"),this.__state[e]=n}})}En.recalculateRGB=function(i,e,t){if(i.__state.space==="HEX")i.__state[e]=kl.component_from_hex(i.__state.hex,t);else if(i.__state.space==="HSV")ue.extend(i.__state,kl.hsv_to_rgb(i.__state.h,i.__state.s,i.__state.v));else throw new Error("Corrupted color state")},En.recalculateHSV=function(i){var e=kl.rgb_to_hsv(i.r,i.g,i.b);ue.extend(i.__state,{s:e.s,v:e.v}),ue.isNaN(e.h)?ue.isUndefined(i.__state.h)&&(i.__state.h=0):i.__state.h=e.h},En.COMPONENTS=["r","g","b","h","s","v","hex","a"],Ud(En.prototype,"r",2),Ud(En.prototype,"g",1),Ud(En.prototype,"b",0),Od(En.prototype,"h"),Od(En.prototype,"s"),Od(En.prototype,"v"),Object.defineProperty(En.prototype,"a",{get:function(){return this.__state.a},set:function(e){this.__state.a=e}}),Object.defineProperty(En.prototype,"hex",{get:function(){return this.__state.space!=="HEX"&&(this.__state.hex=kl.rgb_to_hex(this.r,this.g,this.b),this.__state.space="HEX"),this.__state.hex},set:function(e){this.__state.space="HEX",this.__state.hex=e}});var yr=(function(){function i(e,t){Ci(this,i),this.initialValue=e[t],this.domElement=document.createElement("div"),this.object=e,this.property=t,this.__onChange=void 0,this.__onFinishChange=void 0}return Ii(i,[{key:"onChange",value:function(t){return this.__onChange=t,this}},{key:"onFinishChange",value:function(t){return this.__onFinishChange=t,this}},{key:"setValue",value:function(t){return this.object[this.property]=t,this.__onChange&&this.__onChange.call(this,t),this.updateDisplay(),this}},{key:"getValue",value:function(){return this.object[this.property]}},{key:"updateDisplay",value:function(){return this}},{key:"isModified",value:function(){return this.initialValue!==this.getValue()}}]),i})(),sM={HTMLEvents:["change"],MouseEvents:["click","mousemove","mousedown","mouseup","mouseover"],KeyboardEvents:["keydown"]},dm={};ue.each(sM,function(i,e){ue.each(i,function(t){dm[t]=e})});var rM=/(\d+(\.\d+)?)px/;function Gi(i){if(i==="0"||ue.isUndefined(i))return 0;var e=i.match(rM);return ue.isNull(e)?0:parseFloat(e[1])}var te={makeSelectable:function(e,t){e===void 0||e.style===void 0||(e.onselectstart=t?function(){return!1}:function(){},e.style.MozUserSelect=t?"auto":"none",e.style.KhtmlUserSelect=t?"auto":"none",e.unselectable=t?"on":"off")},makeFullscreen:function(e,t,n){var s=n,r=t;ue.isUndefined(r)&&(r=!0),ue.isUndefined(s)&&(s=!0),e.style.position="absolute",r&&(e.style.left=0,e.style.right=0),s&&(e.style.top=0,e.style.bottom=0)},fakeEvent:function(e,t,n,s){var r=n||{},a=dm[t];if(!a)throw new Error("Event type "+t+" not supported.");var o=document.createEvent(a);switch(a){case"MouseEvents":{var c=r.x||r.clientX||0,l=r.y||r.clientY||0;o.initMouseEvent(t,r.bubbles||!1,r.cancelable||!0,window,r.clickCount||1,0,0,c,l,!1,!1,!1,!1,0,null);break}case"KeyboardEvents":{var h=o.initKeyboardEvent||o.initKeyEvent;ue.defaults(r,{cancelable:!0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,keyCode:void 0,charCode:void 0}),h(t,r.bubbles||!1,r.cancelable,window,r.ctrlKey,r.altKey,r.shiftKey,r.metaKey,r.keyCode,r.charCode);break}default:{o.initEvent(t,r.bubbles||!1,r.cancelable||!0);break}}ue.defaults(o,s),e.dispatchEvent(o)},bind:function(e,t,n,s){var r=s||!1;return e.addEventListener?e.addEventListener(t,n,r):e.attachEvent&&e.attachEvent("on"+t,n),te},unbind:function(e,t,n,s){var r=s||!1;return e.removeEventListener?e.removeEventListener(t,n,r):e.detachEvent&&e.detachEvent("on"+t,n),te},addClass:function(e,t){if(e.className===void 0)e.className=t;else if(e.className!==t){var n=e.className.split(/ +/);n.indexOf(t)===-1&&(n.push(t),e.className=n.join(" ").replace(/^\s+/,"").replace(/\s+$/,""))}return te},removeClass:function(e,t){if(t)if(e.className===t)e.removeAttribute("class");else{var n=e.className.split(/ +/),s=n.indexOf(t);s!==-1&&(n.splice(s,1),e.className=n.join(" "))}else e.className=void 0;return te},hasClass:function(e,t){return new RegExp("(?:^|\\s+)"+t+"(?:\\s+|$)").test(e.className)||!1},getWidth:function(e){var t=getComputedStyle(e);return Gi(t["border-left-width"])+Gi(t["border-right-width"])+Gi(t["padding-left"])+Gi(t["padding-right"])+Gi(t.width)},getHeight:function(e){var t=getComputedStyle(e);return Gi(t["border-top-width"])+Gi(t["border-bottom-width"])+Gi(t["padding-top"])+Gi(t["padding-bottom"])+Gi(t.height)},getOffset:function(e){var t=e,n={left:0,top:0};if(t.offsetParent)do n.left+=t.offsetLeft,n.top+=t.offsetTop,t=t.offsetParent;while(t);return n},isActive:function(e){return e===document.activeElement&&(e.type||e.href)}},fm=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),r=s;s.__prev=s.getValue(),s.__checkbox=document.createElement("input"),s.__checkbox.setAttribute("type","checkbox");function a(){r.setValue(!r.__prev)}return te.bind(s.__checkbox,"change",a,!1),s.domElement.appendChild(s.__checkbox),s.updateDisplay(),s}return Ii(e,[{key:"setValue",value:function(n){var s=Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,n);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),this.__prev=this.getValue(),s}},{key:"updateDisplay",value:function(){return this.getValue()===!0?(this.__checkbox.setAttribute("checked","checked"),this.__checkbox.checked=!0,this.__prev=!0):(this.__checkbox.checked=!1,this.__prev=!1),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(yr),aM=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=s,o=r;if(r.__select=document.createElement("select"),ue.isArray(a)){var c={};ue.each(a,function(l){c[l]=l}),a=c}return ue.each(a,function(l,h){var u=document.createElement("option");u.innerHTML=h,u.setAttribute("value",l),o.__select.appendChild(u)}),r.updateDisplay(),te.bind(r.__select,"change",function(){var l=this.options[this.selectedIndex].value;o.setValue(l)}),r.domElement.appendChild(r.__select),r}return Ii(e,[{key:"setValue",value:function(n){var s=Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,n);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),s}},{key:"updateDisplay",value:function(){return te.isActive(this.__select)?this:(this.__select.value=this.getValue(),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this))}}]),e})(yr),oM=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),r=s;function a(){r.setValue(r.__input.value)}function o(){r.__onFinishChange&&r.__onFinishChange.call(r,r.getValue())}return s.__input=document.createElement("input"),s.__input.setAttribute("type","text"),te.bind(s.__input,"keyup",a),te.bind(s.__input,"change",a),te.bind(s.__input,"blur",o),te.bind(s.__input,"keydown",function(c){c.keyCode===13&&this.blur()}),s.updateDisplay(),s.domElement.appendChild(s.__input),s}return Ii(e,[{key:"updateDisplay",value:function(){return te.isActive(this.__input)||(this.__input.value=this.getValue()),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(yr);function pm(i){var e=i.toString();return e.indexOf(".")>-1?e.length-e.indexOf(".")-1:0}var Am=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=s||{};return r.__min=a.min,r.__max=a.max,r.__step=a.step,ue.isUndefined(r.__step)?r.initialValue===0?r.__impliedStep=1:r.__impliedStep=Math.pow(10,Math.floor(Math.log(Math.abs(r.initialValue))/Math.LN10))/10:r.__impliedStep=r.__step,r.__precision=pm(r.__impliedStep),r}return Ii(e,[{key:"setValue",value:function(n){var s=n;return this.__min!==void 0&&s<this.__min?s=this.__min:this.__max!==void 0&&s>this.__max&&(s=this.__max),this.__step!==void 0&&s%this.__step!==0&&(s=Math.round(s/this.__step)*this.__step),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"setValue",this).call(this,s)}},{key:"min",value:function(n){return this.__min=n,this}},{key:"max",value:function(n){return this.__max=n,this}},{key:"step",value:function(n){return this.__step=n,this.__impliedStep=n,this.__precision=pm(n),this}}]),e})(yr);function cM(i,e){var t=Math.pow(10,e);return Math.round(i*t)/t}var Ul=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n,s));r.__truncationSuspended=!1;var a=r,o=void 0;function c(){var p=parseFloat(a.__input.value);ue.isNaN(p)||a.setValue(p)}function l(){a.__onFinishChange&&a.__onFinishChange.call(a,a.getValue())}function h(){l()}function u(p){var m=o-p.clientY;a.setValue(a.getValue()+m*a.__impliedStep),o=p.clientY}function d(){te.unbind(window,"mousemove",u),te.unbind(window,"mouseup",d),l()}function f(p){te.bind(window,"mousemove",u),te.bind(window,"mouseup",d),o=p.clientY}return r.__input=document.createElement("input"),r.__input.setAttribute("type","text"),te.bind(r.__input,"change",c),te.bind(r.__input,"blur",h),te.bind(r.__input,"mousedown",f),te.bind(r.__input,"keydown",function(p){p.keyCode===13&&(a.__truncationSuspended=!0,this.blur(),a.__truncationSuspended=!1,l())}),r.updateDisplay(),r.domElement.appendChild(r.__input),r}return Ii(e,[{key:"updateDisplay",value:function(){return this.__input.value=this.__truncationSuspended?this.getValue():cM(this.getValue(),this.__precision),Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(Am);function gm(i,e,t,n,s){return n+(s-n)*((i-e)/(t-e))}var Qd=(function(i){Hs(e,i);function e(t,n,s,r,a){Ci(this,e);var o=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n,{min:s,max:r,step:a})),c=o;o.__background=document.createElement("div"),o.__foreground=document.createElement("div"),te.bind(o.__background,"mousedown",l),te.bind(o.__background,"touchstart",d),te.addClass(o.__background,"slider"),te.addClass(o.__foreground,"slider-fg");function l(m){document.activeElement.blur(),te.bind(window,"mousemove",h),te.bind(window,"mouseup",u),h(m)}function h(m){m.preventDefault();var g=c.__background.getBoundingClientRect();return c.setValue(gm(m.clientX,g.left,g.right,c.__min,c.__max)),!1}function u(){te.unbind(window,"mousemove",h),te.unbind(window,"mouseup",u),c.__onFinishChange&&c.__onFinishChange.call(c,c.getValue())}function d(m){m.touches.length===1&&(te.bind(window,"touchmove",f),te.bind(window,"touchend",p),f(m))}function f(m){var g=m.touches[0].clientX,A=c.__background.getBoundingClientRect();c.setValue(gm(g,A.left,A.right,c.__min,c.__max))}function p(){te.unbind(window,"touchmove",f),te.unbind(window,"touchend",p),c.__onFinishChange&&c.__onFinishChange.call(c,c.getValue())}return o.updateDisplay(),o.__background.appendChild(o.__foreground),o.domElement.appendChild(o.__background),o}return Ii(e,[{key:"updateDisplay",value:function(){var n=(this.getValue()-this.__min)/(this.__max-this.__min);return this.__foreground.style.width=n*100+"%",Gs(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"updateDisplay",this).call(this)}}]),e})(Am),mm=(function(i){Hs(e,i);function e(t,n,s){Ci(this,e);var r=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n)),a=r;return r.__button=document.createElement("div"),r.__button.innerHTML=s===void 0?"Fire":s,te.bind(r.__button,"click",function(o){return o.preventDefault(),a.fire(),!1}),te.addClass(r.__button,"button"),r.domElement.appendChild(r.__button),r}return Ii(e,[{key:"fire",value:function(){this.__onChange&&this.__onChange.call(this),this.getValue().call(this.object),this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue())}}]),e})(yr),Gd=(function(i){Hs(e,i);function e(t,n){Ci(this,e);var s=zs(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));s.__color=new En(s.getValue()),s.__temp=new En(0);var r=s;s.domElement=document.createElement("div"),te.makeSelectable(s.domElement,!1),s.__selector=document.createElement("div"),s.__selector.className="selector",s.__saturation_field=document.createElement("div"),s.__saturation_field.className="saturation-field",s.__field_knob=document.createElement("div"),s.__field_knob.className="field-knob",s.__field_knob_border="2px solid ",s.__hue_knob=document.createElement("div"),s.__hue_knob.className="hue-knob",s.__hue_field=document.createElement("div"),s.__hue_field.className="hue-field",s.__input=document.createElement("input"),s.__input.type="text",s.__input_textShadow="0 1px 1px ",te.bind(s.__input,"keydown",function(m){m.keyCode===13&&u.call(this)}),te.bind(s.__input,"blur",u),te.bind(s.__selector,"mousedown",function(){te.addClass(this,"drag").bind(window,"mouseup",function(){te.removeClass(r.__selector,"drag")})}),te.bind(s.__selector,"touchstart",function(){te.addClass(this,"drag").bind(window,"touchend",function(){te.removeClass(r.__selector,"drag")})});var a=document.createElement("div");ue.extend(s.__selector.style,{width:"122px",height:"102px",padding:"3px",backgroundColor:"#222",boxShadow:"0px 1px 3px rgba(0,0,0,0.3)"}),ue.extend(s.__field_knob.style,{position:"absolute",width:"12px",height:"12px",border:s.__field_knob_border+(s.__color.v<.5?"#fff":"#000"),boxShadow:"0px 1px 3px rgba(0,0,0,0.5)",borderRadius:"12px",zIndex:1}),ue.extend(s.__hue_knob.style,{position:"absolute",width:"15px",height:"2px",borderRight:"4px solid #fff",zIndex:1}),ue.extend(s.__saturation_field.style,{width:"100px",height:"100px",border:"1px solid #555",marginRight:"3px",display:"inline-block",cursor:"pointer"}),ue.extend(a.style,{width:"100%",height:"100%",background:"none"}),xm(a,"top","rgba(0,0,0,0)","#000"),ue.extend(s.__hue_field.style,{width:"15px",height:"100px",border:"1px solid #555",cursor:"ns-resize",position:"absolute",top:"3px",right:"3px"}),hM(s.__hue_field),ue.extend(s.__input.style,{outline:"none",textAlign:"center",color:"#fff",border:0,fontWeight:"bold",textShadow:s.__input_textShadow+"rgba(0,0,0,0.7)"}),te.bind(s.__saturation_field,"mousedown",o),te.bind(s.__saturation_field,"touchstart",o),te.bind(s.__field_knob,"mousedown",o),te.bind(s.__field_knob,"touchstart",o),te.bind(s.__hue_field,"mousedown",c),te.bind(s.__hue_field,"touchstart",c);function o(m){f(m),te.bind(window,"mousemove",f),te.bind(window,"touchmove",f),te.bind(window,"mouseup",l),te.bind(window,"touchend",l)}function c(m){p(m),te.bind(window,"mousemove",p),te.bind(window,"touchmove",p),te.bind(window,"mouseup",h),te.bind(window,"touchend",h)}function l(){te.unbind(window,"mousemove",f),te.unbind(window,"touchmove",f),te.unbind(window,"mouseup",l),te.unbind(window,"touchend",l),d()}function h(){te.unbind(window,"mousemove",p),te.unbind(window,"touchmove",p),te.unbind(window,"mouseup",h),te.unbind(window,"touchend",h),d()}function u(){var m=kd(this.value);m!==!1?(r.__color.__state=m,r.setValue(r.__color.toOriginal())):this.value=r.__color.toString()}function d(){r.__onFinishChange&&r.__onFinishChange.call(r,r.__color.toOriginal())}s.__saturation_field.appendChild(a),s.__selector.appendChild(s.__field_knob),s.__selector.appendChild(s.__saturation_field),s.__selector.appendChild(s.__hue_field),s.__hue_field.appendChild(s.__hue_knob),s.domElement.appendChild(s.__input),s.domElement.appendChild(s.__selector),s.updateDisplay();function f(m){m.type.indexOf("touch")===-1&&m.preventDefault();var g=r.__saturation_field.getBoundingClientRect(),A=m.touches&&m.touches[0]||m,_=A.clientX,x=A.clientY,E=(_-g.left)/(g.right-g.left),S=1-(x-g.top)/(g.bottom-g.top);return S>1?S=1:S<0&&(S=0),E>1?E=1:E<0&&(E=0),r.__color.v=S,r.__color.s=E,r.setValue(r.__color.toOriginal()),!1}function p(m){m.type.indexOf("touch")===-1&&m.preventDefault();var g=r.__hue_field.getBoundingClientRect(),A=m.touches&&m.touches[0]||m,_=A.clientY,x=1-(_-g.top)/(g.bottom-g.top);return x>1?x=1:x<0&&(x=0),r.__color.h=x*360,r.setValue(r.__color.toOriginal()),!1}return s}return Ii(e,[{key:"updateDisplay",value:function(){var n=kd(this.getValue());if(n!==!1){var s=!1;ue.each(En.COMPONENTS,function(o){if(!ue.isUndefined(n[o])&&!ue.isUndefined(this.__color.__state[o])&&n[o]!==this.__color.__state[o])return s=!0,{}},this),s&&ue.extend(this.__color.__state,n)}ue.extend(this.__temp.__state,this.__color.__state),this.__temp.a=1;var r=this.__color.v<.5||this.__color.s>.5?255:0,a=255-r;ue.extend(this.__field_knob.style,{marginLeft:100*this.__color.s-7+"px",marginTop:100*(1-this.__color.v)-7+"px",backgroundColor:this.__temp.toHexString(),border:this.__field_knob_border+"rgb("+r+","+r+","+r+")"}),this.__hue_knob.style.marginTop=(1-this.__color.h/360)*100+"px",this.__temp.s=1,this.__temp.v=1,xm(this.__saturation_field,"left","#fff",this.__temp.toHexString()),this.__input.value=this.__color.toString(),ue.extend(this.__input.style,{backgroundColor:this.__color.toHexString(),color:"rgb("+r+","+r+","+r+")",textShadow:this.__input_textShadow+"rgba("+a+","+a+","+a+",.7)"})}}]),e})(yr),lM=["-moz-","-o-","-webkit-","-ms-",""];function xm(i,e,t,n){i.style.background="",ue.each(lM,function(s){i.style.cssText+="background: "+s+"linear-gradient("+e+", "+t+" 0%, "+n+" 100%); "})}function hM(i){i.style.background="",i.style.cssText+="background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);",i.style.cssText+="background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",i.style.cssText+="background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);"}var uM={load:function(e,t){var n=t||document,s=n.createElement("link");s.type="text/css",s.rel="stylesheet",s.href=e,n.getElementsByTagName("head")[0].appendChild(s)},inject:function(e,t){var n=t||document,s=document.createElement("style");s.type="text/css",s.innerHTML=e;var r=n.getElementsByTagName("head")[0];try{r.appendChild(s)}catch{}}},dM=`<div id="dg-save" class="dg dialogue">
Here's the new load parameter for your <code>GUI</code>'s constructor:
@@ -3836,18 +3836,18 @@ void main() {
</div>
-</div>`,pM=function(e,t){var n=e[t];return ue.isArray(arguments[2])||ue.isObject(arguments[2])?new oM(e,t,arguments[2]):ue.isNumber(n)?ue.isNumber(arguments[2])&&ue.isNumber(arguments[3])?ue.isNumber(arguments[4])?new Qd(e,t,arguments[2],arguments[3],arguments[4]):new Qd(e,t,arguments[2],arguments[3]):ue.isNumber(arguments[4])?new Ul(e,t,{min:arguments[2],max:arguments[3],step:arguments[4]}):new Ul(e,t,{min:arguments[2],max:arguments[3]}):ue.isString(n)?new cM(e,t):ue.isFunction(n)?new mm(e,t,""):ue.isBoolean(n)?new fm(e,t):null};function AM(i){setTimeout(i,1e3/60)}var gM=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||AM,mM=(function(){function i(){Ci(this,i),this.backgroundElement=document.createElement("div"),ue.extend(this.backgroundElement.style,{backgroundColor:"rgba(0,0,0,0.8)",top:0,left:0,display:"none",zIndex:"1000",opacity:0,WebkitTransition:"opacity 0.2s linear",transition:"opacity 0.2s linear"}),te.makeFullscreen(this.backgroundElement),this.backgroundElement.style.position="fixed",this.domElement=document.createElement("div"),ue.extend(this.domElement.style,{position:"fixed",display:"none",zIndex:"1001",opacity:0,WebkitTransition:"-webkit-transform 0.2s ease-out, opacity 0.2s linear",transition:"transform 0.2s ease-out, opacity 0.2s linear"}),document.body.appendChild(this.backgroundElement),document.body.appendChild(this.domElement);var e=this;te.bind(this.backgroundElement,"click",function(){e.hide()})}return Ii(i,[{key:"show",value:function(){var t=this;this.backgroundElement.style.display="block",this.domElement.style.display="block",this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)",this.layout(),ue.defer(function(){t.backgroundElement.style.opacity=1,t.domElement.style.opacity=1,t.domElement.style.webkitTransform="scale(1)"})}},{key:"hide",value:function(){var t=this,n=function s(){t.domElement.style.display="none",t.backgroundElement.style.display="none",te.unbind(t.domElement,"webkitTransitionEnd",s),te.unbind(t.domElement,"transitionend",s),te.unbind(t.domElement,"oTransitionEnd",s)};te.bind(this.domElement,"webkitTransitionEnd",n),te.bind(this.domElement,"transitionend",n),te.bind(this.domElement,"oTransitionEnd",n),this.backgroundElement.style.opacity=0,this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)"}},{key:"layout",value:function(){this.domElement.style.left=window.innerWidth/2-te.getWidth(this.domElement)/2+"px",this.domElement.style.top=window.innerHeight/2-te.getHeight(this.domElement)/2+"px"}}]),i})(),xM=nM(`.dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}
-`);dM.inject(xM);var bm="dg",Em=72,ym=20,Oo="Default",Qo=(function(){try{return!!window.localStorage}catch{return!1}})(),Go=void 0,_m=!0,Sa=void 0,Hd=!1,wm=[],Lt=function i(e){var t=this,n=e||{};this.domElement=document.createElement("div"),this.__ul=document.createElement("ul"),this.domElement.appendChild(this.__ul),te.addClass(this.domElement,bm),this.__folders={},this.__controllers=[],this.__rememberedObjects=[],this.__rememberedObjectIndecesToControllers=[],this.__listening=[],n=ue.defaults(n,{closeOnTop:!1,autoPlace:!0,width:i.DEFAULT_WIDTH}),n=ue.defaults(n,{resizable:n.autoPlace,hideable:n.autoPlace}),ue.isUndefined(n.load)?n.load={preset:Oo}:n.preset&&(n.load.preset=n.preset),ue.isUndefined(n.parent)&&n.hideable&&wm.push(this),n.resizable=ue.isUndefined(n.parent)&&n.resizable,n.autoPlace&&ue.isUndefined(n.scrollable)&&(n.scrollable=!0);var s=Qo&&localStorage.getItem(Ma(this,"isLocal"))==="true",r=void 0,a=void 0;if(Object.defineProperties(this,{parent:{get:function(){return n.parent}},scrollable:{get:function(){return n.scrollable}},autoPlace:{get:function(){return n.autoPlace}},closeOnTop:{get:function(){return n.closeOnTop}},preset:{get:function(){return t.parent?t.getRoot().preset:n.load.preset},set:function(d){t.parent?t.getRoot().preset=d:n.load.preset=d,_M(this),t.revert()}},width:{get:function(){return n.width},set:function(d){n.width=d,qd(t,d)}},name:{get:function(){return n.name},set:function(d){n.name=d,a&&(a.innerHTML=n.name)}},closed:{get:function(){return n.closed},set:function(d){n.closed=d,n.closed?te.addClass(t.__ul,i.CLASS_CLOSED):te.removeClass(t.__ul,i.CLASS_CLOSED),this.onResize(),t.__closeButton&&(t.__closeButton.innerHTML=d?i.TEXT_OPEN:i.TEXT_CLOSED)}},load:{get:function(){return n.load}},useLocalStorage:{get:function(){return s},set:function(d){Qo&&(s=d,d?te.bind(window,"unload",r):te.unbind(window,"unload",r),localStorage.setItem(Ma(t,"isLocal"),d))}}}),ue.isUndefined(n.parent)){if(this.closed=n.closed||!1,te.addClass(this.domElement,i.CLASS_MAIN),te.makeSelectable(this.domElement,!1),Qo&&s){t.useLocalStorage=!0;var o=localStorage.getItem(Ma(this,"gui"));o&&(n.load=JSON.parse(o))}this.__closeButton=document.createElement("div"),this.__closeButton.innerHTML=i.TEXT_CLOSED,te.addClass(this.__closeButton,i.CLASS_CLOSE_BUTTON),n.closeOnTop?(te.addClass(this.__closeButton,i.CLASS_CLOSE_TOP),this.domElement.insertBefore(this.__closeButton,this.domElement.childNodes[0])):(te.addClass(this.__closeButton,i.CLASS_CLOSE_BOTTOM),this.domElement.appendChild(this.__closeButton)),te.bind(this.__closeButton,"click",function(){t.closed=!t.closed})}else{n.closed===void 0&&(n.closed=!0);var c=document.createTextNode(n.name);te.addClass(c,"controller-name"),a=zd(t,c);var l=function(d){return d.preventDefault(),t.closed=!t.closed,!1};te.addClass(this.__ul,i.CLASS_CLOSED),te.addClass(a,"title"),te.bind(a,"click",l),n.closed||(this.closed=!1)}n.autoPlace&&(ue.isUndefined(n.parent)&&(_m&&(Sa=document.createElement("div"),te.addClass(Sa,bm),te.addClass(Sa,i.CLASS_AUTO_PLACE_CONTAINER),document.body.appendChild(Sa),_m=!1),Sa.appendChild(this.domElement),te.addClass(this.domElement,i.CLASS_AUTO_PLACE)),this.parent||qd(t,n.width)),this.__resizeHandler=function(){t.onResizeDebounced()},te.bind(window,"resize",this.__resizeHandler),te.bind(this.__ul,"webkitTransitionEnd",this.__resizeHandler),te.bind(this.__ul,"transitionend",this.__resizeHandler),te.bind(this.__ul,"oTransitionEnd",this.__resizeHandler),this.onResize(),n.resizable&&yM(this),r=function(){Qo&&localStorage.getItem(Ma(t,"isLocal"))==="true"&&localStorage.setItem(Ma(t,"gui"),JSON.stringify(t.getSaveObject()))},this.saveToLocalStorageIfPossible=r;function h(){var u=t.getRoot();u.width+=1,ue.defer(function(){u.width-=1})}n.parent||h()};Lt.toggleHide=function(){Hd=!Hd,ue.each(wm,function(i){i.domElement.style.display=Hd?"none":""})},Lt.CLASS_AUTO_PLACE="a",Lt.CLASS_AUTO_PLACE_CONTAINER="ac",Lt.CLASS_MAIN="main",Lt.CLASS_CONTROLLER_ROW="cr",Lt.CLASS_TOO_TALL="taller-than-window",Lt.CLASS_CLOSED="closed",Lt.CLASS_CLOSE_BUTTON="close-button",Lt.CLASS_CLOSE_TOP="close-top",Lt.CLASS_CLOSE_BOTTOM="close-bottom",Lt.CLASS_DRAG="drag",Lt.DEFAULT_WIDTH=245,Lt.TEXT_CLOSED="Close Controls",Lt.TEXT_OPEN="Open Controls",Lt._keydownHandler=function(i){document.activeElement.type!=="text"&&(i.which===Em||i.keyCode===Em)&&Lt.toggleHide()},te.bind(window,"keydown",Lt._keydownHandler,!1),ue.extend(Lt.prototype,{add:function(e,t){return Ho(this,e,t,{factoryArgs:Array.prototype.slice.call(arguments,2)})},addColor:function(e,t){return Ho(this,e,t,{color:!0})},remove:function(e){this.__ul.removeChild(e.__li),this.__controllers.splice(this.__controllers.indexOf(e),1);var t=this;ue.defer(function(){t.onResize()})},destroy:function(){if(this.parent)throw new Error("Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.");this.autoPlace&&Sa.removeChild(this.domElement);var e=this;ue.each(this.__folders,function(t){e.removeFolder(t)}),te.unbind(window,"keydown",Lt._keydownHandler,!1),vm(this)},addFolder:function(e){if(this.__folders[e]!==void 0)throw new Error('You already have a folder in this GUI by the name "'+e+'"');var t={name:e,parent:this};t.autoPlace=this.autoPlace,this.load&&this.load.folders&&this.load.folders[e]&&(t.closed=this.load.folders[e].closed,t.load=this.load.folders[e]);var n=new Lt(t);this.__folders[e]=n;var s=zd(this,n.domElement);return te.addClass(s,"folder"),n},removeFolder:function(e){this.__ul.removeChild(e.domElement.parentElement),delete this.__folders[e.name],this.load&&this.load.folders&&this.load.folders[e.name]&&delete this.load.folders[e.name],vm(e);var t=this;ue.each(e.__folders,function(n){e.removeFolder(n)}),ue.defer(function(){t.onResize()})},open:function(){this.closed=!1},close:function(){this.closed=!0},hide:function(){this.domElement.style.display="none"},show:function(){this.domElement.style.display=""},onResize:function(){var e=this.getRoot();if(e.scrollable){var t=te.getOffset(e.__ul).top,n=0;ue.each(e.__ul.childNodes,function(s){e.autoPlace&&s===e.__save_row||(n+=te.getHeight(s))}),window.innerHeight-t-ym<n?(te.addClass(e.domElement,Lt.CLASS_TOO_TALL),e.__ul.style.height=window.innerHeight-t-ym+"px"):(te.removeClass(e.domElement,Lt.CLASS_TOO_TALL),e.__ul.style.height="auto")}e.__resize_handle&&ue.defer(function(){e.__resize_handle.style.height=e.__ul.offsetHeight+"px"}),e.__closeButton&&(e.__closeButton.style.width=e.width+"px")},onResizeDebounced:ue.debounce(function(){this.onResize()},50),remember:function(){if(ue.isUndefined(Go)&&(Go=new mM,Go.domElement.innerHTML=fM),this.parent)throw new Error("You can only call remember on a top level GUI.");var e=this;ue.each(Array.prototype.slice.call(arguments),function(t){e.__rememberedObjects.length===0&&EM(e),e.__rememberedObjects.indexOf(t)===-1&&e.__rememberedObjects.push(t)}),this.autoPlace&&qd(this,this.width)},getRoot:function(){for(var e=this;e.parent;)e=e.parent;return e},getSaveObject:function(){var e=this.load;return e.closed=this.closed,this.__rememberedObjects.length>0&&(e.preset=this.preset,e.remembered||(e.remembered={}),e.remembered[this.preset]=Ol(this)),e.folders={},ue.each(this.__folders,function(t,n){e.folders[n]=t.getSaveObject()}),e},save:function(){this.load.remembered||(this.load.remembered={}),this.load.remembered[this.preset]=Ol(this),Vd(this,!1),this.saveToLocalStorageIfPossible()},saveAs:function(e){this.load.remembered||(this.load.remembered={},this.load.remembered[Oo]=Ol(this,!0)),this.load.remembered[e]=Ol(this),this.preset=e,Wd(this,e,!0),this.saveToLocalStorageIfPossible()},revert:function(e){ue.each(this.__controllers,function(t){this.getRoot().load.remembered?Cm(e||this.getRoot(),t):t.setValue(t.initialValue),t.__onFinishChange&&t.__onFinishChange.call(t,t.getValue())},this),ue.each(this.__folders,function(t){t.revert(t)}),e||Vd(this.getRoot(),!1)},listen:function(e){var t=this.__listening.length===0;this.__listening.push(e),t&&Sm(this.__listening)},updateDisplay:function(){ue.each(this.__controllers,function(e){e.updateDisplay()}),ue.each(this.__folders,function(e){e.updateDisplay()})}});function zd(i,e,t){var n=document.createElement("li");return e&&n.appendChild(e),t?i.__ul.insertBefore(n,t):i.__ul.appendChild(n),i.onResize(),n}function vm(i){te.unbind(window,"resize",i.__resizeHandler),i.saveToLocalStorageIfPossible&&te.unbind(window,"unload",i.saveToLocalStorageIfPossible)}function Vd(i,e){var t=i.__preset_select[i.__preset_select.selectedIndex];e?t.innerHTML=t.value+"*":t.innerHTML=t.value}function bM(i,e,t){if(t.__li=e,t.__gui=i,ue.extend(t,{options:function(a){if(arguments.length>1){var o=t.__li.nextElementSibling;return t.remove(),Ho(i,t.object,t.property,{before:o,factoryArgs:[ue.toArray(arguments)]})}if(ue.isArray(a)||ue.isObject(a)){var c=t.__li.nextElementSibling;return t.remove(),Ho(i,t.object,t.property,{before:c,factoryArgs:[a]})}},name:function(a){return t.__li.firstElementChild.firstElementChild.innerHTML=a,t},listen:function(){return t.__gui.listen(t),t},remove:function(){return t.__gui.remove(t),t}}),t instanceof Qd){var n=new Ul(t.object,t.property,{min:t.__min,max:t.__max,step:t.__step});ue.each(["updateDisplay","onChange","onFinishChange","step","min","max"],function(r){var a=t[r],o=n[r];t[r]=n[r]=function(){var c=Array.prototype.slice.call(arguments);return o.apply(n,c),a.apply(t,c)}}),te.addClass(e,"has-slider"),t.domElement.insertBefore(n.domElement,t.domElement.firstElementChild)}else if(t instanceof Ul){var s=function(a){if(ue.isNumber(t.__min)&&ue.isNumber(t.__max)){var o=t.__li.firstElementChild.firstElementChild.innerHTML,c=t.__gui.__listening.indexOf(t)>-1;t.remove();var l=Ho(i,t.object,t.property,{before:t.__li.nextElementSibling,factoryArgs:[t.__min,t.__max,t.__step]});return l.name(o),c&&l.listen(),l}return a};t.min=ue.compose(s,t.min),t.max=ue.compose(s,t.max)}else t instanceof fm?(te.bind(e,"click",function(){te.fakeEvent(t.__checkbox,"click")}),te.bind(t.__checkbox,"click",function(r){r.stopPropagation()})):t instanceof mm?(te.bind(e,"click",function(){te.fakeEvent(t.__button,"click")}),te.bind(e,"mouseover",function(){te.addClass(t.__button,"hover")}),te.bind(e,"mouseout",function(){te.removeClass(t.__button,"hover")})):t instanceof Gd&&(te.addClass(e,"color"),t.updateDisplay=ue.compose(function(r){return e.style.borderLeftColor=t.__color.toString(),r},t.updateDisplay),t.updateDisplay());t.setValue=ue.compose(function(r){return i.getRoot().__preset_select&&t.isModified()&&Vd(i.getRoot(),!0),r},t.setValue)}function Cm(i,e){var t=i.getRoot(),n=t.__rememberedObjects.indexOf(e.object);if(n!==-1){var s=t.__rememberedObjectIndecesToControllers[n];if(s===void 0&&(s={},t.__rememberedObjectIndecesToControllers[n]=s),s[e.property]=e,t.load&&t.load.remembered){var r=t.load.remembered,a=void 0;if(r[i.preset])a=r[i.preset];else if(r[Oo])a=r[Oo];else return;if(a[n]&&a[n][e.property]!==void 0){var o=a[n][e.property];e.initialValue=o,e.setValue(o)}}}}function Ho(i,e,t,n){if(e[t]===void 0)throw new Error('Object "'+e+'" has no property "'+t+'"');var s=void 0;if(n.color)s=new Gd(e,t);else{var r=[e,t].concat(n.factoryArgs);s=pM.apply(i,r)}n.before instanceof yr&&(n.before=n.before.__li),Cm(i,s),te.addClass(s.domElement,"c");var a=document.createElement("span");te.addClass(a,"property-name"),a.innerHTML=s.property;var o=document.createElement("div");o.appendChild(a),o.appendChild(s.domElement);var c=zd(i,o,n.before);return te.addClass(c,Lt.CLASS_CONTROLLER_ROW),s instanceof Gd?te.addClass(c,"color"):te.addClass(c,sM(s.getValue())),bM(i,c,s),i.__controllers.push(s),s}function Ma(i,e){return document.location.href+"."+e}function Wd(i,e,t){var n=document.createElement("option");n.innerHTML=e,n.value=e,i.__preset_select.appendChild(n),t&&(i.__preset_select.selectedIndex=i.__preset_select.length-1)}function Im(i,e){e.style.display=i.useLocalStorage?"block":"none"}function EM(i){var e=i.__save_row=document.createElement("li");te.addClass(i.domElement,"has-save"),i.__ul.insertBefore(e,i.__ul.firstChild),te.addClass(e,"save-row");var t=document.createElement("span");t.innerHTML="&nbsp;",te.addClass(t,"button gears");var n=document.createElement("span");n.innerHTML="Save",te.addClass(n,"button"),te.addClass(n,"save");var s=document.createElement("span");s.innerHTML="New",te.addClass(s,"button"),te.addClass(s,"save-as");var r=document.createElement("span");r.innerHTML="Revert",te.addClass(r,"button"),te.addClass(r,"revert");var a=i.__preset_select=document.createElement("select");if(i.load&&i.load.remembered?ue.each(i.load.remembered,function(u,d){Wd(i,d,d===i.preset)}):Wd(i,Oo,!1),te.bind(a,"change",function(){for(var u=0;u<i.__preset_select.length;u++)i.__preset_select[u].innerHTML=i.__preset_select[u].value;i.preset=this.value}),e.appendChild(a),e.appendChild(t),e.appendChild(n),e.appendChild(s),e.appendChild(r),Qo){var o=document.getElementById("dg-local-explain"),c=document.getElementById("dg-local-storage"),l=document.getElementById("dg-save-locally");l.style.display="block",localStorage.getItem(Ma(i,"isLocal"))==="true"&&c.setAttribute("checked","checked"),Im(i,o),te.bind(c,"change",function(){i.useLocalStorage=!i.useLocalStorage,Im(i,o)})}var h=document.getElementById("dg-new-constructor");te.bind(h,"keydown",function(u){u.metaKey&&(u.which===67||u.keyCode===67)&&Go.hide()}),te.bind(t,"click",function(){h.innerHTML=JSON.stringify(i.getSaveObject(),void 0,2),Go.show(),h.focus(),h.select()}),te.bind(n,"click",function(){i.save()}),te.bind(s,"click",function(){var u=prompt("Enter a new preset name.");u&&i.saveAs(u)}),te.bind(r,"click",function(){i.revert()})}function yM(i){var e=void 0;i.__resize_handle=document.createElement("div"),ue.extend(i.__resize_handle.style,{width:"6px",marginLeft:"-3px",height:"200px",cursor:"ew-resize",position:"absolute"});function t(r){return r.preventDefault(),i.width+=e-r.clientX,i.onResize(),e=r.clientX,!1}function n(){te.removeClass(i.__closeButton,Lt.CLASS_DRAG),te.unbind(window,"mousemove",t),te.unbind(window,"mouseup",n)}function s(r){return r.preventDefault(),e=r.clientX,te.addClass(i.__closeButton,Lt.CLASS_DRAG),te.bind(window,"mousemove",t),te.bind(window,"mouseup",n),!1}te.bind(i.__resize_handle,"mousedown",s),te.bind(i.__closeButton,"mousedown",s),i.domElement.insertBefore(i.__resize_handle,i.domElement.firstElementChild)}function qd(i,e){i.domElement.style.width=e+"px",i.__save_row&&i.autoPlace&&(i.__save_row.style.width=e+"px"),i.__closeButton&&(i.__closeButton.style.width=e+"px")}function Ol(i,e){var t={};return ue.each(i.__rememberedObjects,function(n,s){var r={},a=i.__rememberedObjectIndecesToControllers[s];ue.each(a,function(o,c){r[c]=e?o.initialValue:o.getValue()}),t[s]=r}),t}function _M(i){for(var e=0;e<i.__preset_select.length;e++)i.__preset_select[e].value===i.preset&&(i.__preset_select.selectedIndex=e)}function Sm(i){i.length!==0&&gM.call(window,function(){Sm(i)}),ue.each(i,function(e){e.updateDisplay()})}var wM=Lt;const Ql=[{id:"",name:"None",path:null},{id:"neutral",name:"Neutral",path:null},{id:"venice-sunset",name:"Venice Sunset",path:"https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr",format:".exr"},{id:"footprint-court",name:"Footprint Court (HDR Labs)",path:"https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr",format:".exr"}],vM=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],Mm=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function CM(i){if(i<=255)return vM[i];let e=0,t=Mm.length-1;for(;e<=t;){const n=e+t>>1,s=Mm[n];if(i<s[0]){t=n-1;continue}if(i>s[1]){e=n+1;continue}return s[2]}return"L"}function IM(i){const e=i.length;if(e===0)return null;const t=new Array(e);let n=!1;for(let l=0;l<e;){const h=i.charCodeAt(l);let u=h,d=1;if(h>=55296&&h<=56319&&l+1<e){const p=i.charCodeAt(l+1);p>=56320&&p<=57343&&(u=(h-55296<<10)+(p-56320)+65536,d=2)}const f=CM(u);(f==="R"||f==="AL"||f==="AN")&&(n=!0);for(let p=0;p<d;p++)t[l+p]=f;l+=d}if(!n)return null;let s=0;for(let l=0;l<e;l++){const h=t[l];if(h==="L"){s=0;break}if(h==="R"||h==="AL"){s=1;break}}const r=new Int8Array(e);for(let l=0;l<e;l++)r[l]=s;const a=s&1?"R":"L",o=a;let c=o;for(let l=0;l<e;l++)t[l]==="NSM"?t[l]=c:c=t[l];c=o;for(let l=0;l<e;l++){const h=t[l];h==="EN"?t[l]=c==="AL"?"AN":"EN":(h==="R"||h==="L"||h==="AL")&&(c=h)}for(let l=0;l<e;l++)t[l]==="AL"&&(t[l]="R");for(let l=1;l<e-1;l++)t[l]==="ES"&&t[l-1]==="EN"&&t[l+1]==="EN"&&(t[l]="EN"),t[l]==="CS"&&(t[l-1]==="EN"||t[l-1]==="AN")&&t[l+1]===t[l-1]&&(t[l]=t[l-1]);for(let l=0;l<e;l++){if(t[l]!=="EN")continue;let h;for(h=l-1;h>=0&&t[h]==="ET";h--)t[h]="EN";for(h=l+1;h<e&&t[h]==="ET";h++)t[h]="EN"}for(let l=0;l<e;l++){const h=t[l];(h==="WS"||h==="ES"||h==="ET"||h==="CS")&&(t[l]="ON")}c=o;for(let l=0;l<e;l++){const h=t[l];h==="EN"?t[l]=c==="L"?"L":"EN":(h==="R"||h==="L")&&(c=h)}for(let l=0;l<e;l++){if(t[l]!=="ON")continue;let h=l+1;for(;h<e&&t[h]==="ON";)h++;const u=l>0?t[l-1]:o,d=h<e?t[h]:o,f=u!=="L"?"R":"L";if(f===(d!=="L"?"R":"L"))for(let m=l;m<h;m++)t[m]=f;l=h-1}for(let l=0;l<e;l++)t[l]==="ON"&&(t[l]=a);for(let l=0;l<e;l++){const h=t[l];(r[l]&1)===0?h==="R"?r[l]++:(h==="AN"||h==="EN")&&(r[l]+=2):(h==="L"||h==="AN"||h==="EN")&&r[l]++}return r}function SM(i,e){const t=IM(i);if(t===null)return null;const n=new Int8Array(e.length);for(let s=0;s<e.length;s++)n[s]=t[e[s]];return n}const MM=/[ \t\n\r\f]+/g,BM=/[\t\n\r\f]| {2,}|^ | $/;function TM(i){const e=i??"normal";return e==="pre-wrap"?{mode:e,preserveOrdinarySpaces:!0,preserveHardBreaks:!0}:{mode:e,preserveOrdinarySpaces:!1,preserveHardBreaks:!1}}function RM(i){if(!BM.test(i))return i;let e=i.replace(MM," ");return e.charCodeAt(0)===32&&(e=e.slice(1)),e.length>0&&e.charCodeAt(e.length-1)===32&&(e=e.slice(0,-1)),e}function FM(i){return/[\r\f]/.test(i)?i.replace(/\r\n/g,`
+</div>`,fM=function(e,t){var n=e[t];return ue.isArray(arguments[2])||ue.isObject(arguments[2])?new aM(e,t,arguments[2]):ue.isNumber(n)?ue.isNumber(arguments[2])&&ue.isNumber(arguments[3])?ue.isNumber(arguments[4])?new Qd(e,t,arguments[2],arguments[3],arguments[4]):new Qd(e,t,arguments[2],arguments[3]):ue.isNumber(arguments[4])?new Ul(e,t,{min:arguments[2],max:arguments[3],step:arguments[4]}):new Ul(e,t,{min:arguments[2],max:arguments[3]}):ue.isString(n)?new oM(e,t):ue.isFunction(n)?new mm(e,t,""):ue.isBoolean(n)?new fm(e,t):null};function pM(i){setTimeout(i,1e3/60)}var AM=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||pM,gM=(function(){function i(){Ci(this,i),this.backgroundElement=document.createElement("div"),ue.extend(this.backgroundElement.style,{backgroundColor:"rgba(0,0,0,0.8)",top:0,left:0,display:"none",zIndex:"1000",opacity:0,WebkitTransition:"opacity 0.2s linear",transition:"opacity 0.2s linear"}),te.makeFullscreen(this.backgroundElement),this.backgroundElement.style.position="fixed",this.domElement=document.createElement("div"),ue.extend(this.domElement.style,{position:"fixed",display:"none",zIndex:"1001",opacity:0,WebkitTransition:"-webkit-transform 0.2s ease-out, opacity 0.2s linear",transition:"transform 0.2s ease-out, opacity 0.2s linear"}),document.body.appendChild(this.backgroundElement),document.body.appendChild(this.domElement);var e=this;te.bind(this.backgroundElement,"click",function(){e.hide()})}return Ii(i,[{key:"show",value:function(){var t=this;this.backgroundElement.style.display="block",this.domElement.style.display="block",this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)",this.layout(),ue.defer(function(){t.backgroundElement.style.opacity=1,t.domElement.style.opacity=1,t.domElement.style.webkitTransform="scale(1)"})}},{key:"hide",value:function(){var t=this,n=function s(){t.domElement.style.display="none",t.backgroundElement.style.display="none",te.unbind(t.domElement,"webkitTransitionEnd",s),te.unbind(t.domElement,"transitionend",s),te.unbind(t.domElement,"oTransitionEnd",s)};te.bind(this.domElement,"webkitTransitionEnd",n),te.bind(this.domElement,"transitionend",n),te.bind(this.domElement,"oTransitionEnd",n),this.backgroundElement.style.opacity=0,this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)"}},{key:"layout",value:function(){this.domElement.style.left=window.innerWidth/2-te.getWidth(this.domElement)/2+"px",this.domElement.style.top=window.innerHeight/2-te.getHeight(this.domElement)/2+"px"}}]),i})(),mM=tM(`.dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}
+`);uM.inject(mM);var bm="dg",Em=72,ym=20,Oo="Default",Qo=(function(){try{return!!window.localStorage}catch{return!1}})(),Go=void 0,_m=!0,Sa=void 0,Hd=!1,wm=[],Lt=function i(e){var t=this,n=e||{};this.domElement=document.createElement("div"),this.__ul=document.createElement("ul"),this.domElement.appendChild(this.__ul),te.addClass(this.domElement,bm),this.__folders={},this.__controllers=[],this.__rememberedObjects=[],this.__rememberedObjectIndecesToControllers=[],this.__listening=[],n=ue.defaults(n,{closeOnTop:!1,autoPlace:!0,width:i.DEFAULT_WIDTH}),n=ue.defaults(n,{resizable:n.autoPlace,hideable:n.autoPlace}),ue.isUndefined(n.load)?n.load={preset:Oo}:n.preset&&(n.load.preset=n.preset),ue.isUndefined(n.parent)&&n.hideable&&wm.push(this),n.resizable=ue.isUndefined(n.parent)&&n.resizable,n.autoPlace&&ue.isUndefined(n.scrollable)&&(n.scrollable=!0);var s=Qo&&localStorage.getItem(Ma(this,"isLocal"))==="true",r=void 0,a=void 0;if(Object.defineProperties(this,{parent:{get:function(){return n.parent}},scrollable:{get:function(){return n.scrollable}},autoPlace:{get:function(){return n.autoPlace}},closeOnTop:{get:function(){return n.closeOnTop}},preset:{get:function(){return t.parent?t.getRoot().preset:n.load.preset},set:function(d){t.parent?t.getRoot().preset=d:n.load.preset=d,yM(this),t.revert()}},width:{get:function(){return n.width},set:function(d){n.width=d,qd(t,d)}},name:{get:function(){return n.name},set:function(d){n.name=d,a&&(a.innerHTML=n.name)}},closed:{get:function(){return n.closed},set:function(d){n.closed=d,n.closed?te.addClass(t.__ul,i.CLASS_CLOSED):te.removeClass(t.__ul,i.CLASS_CLOSED),this.onResize(),t.__closeButton&&(t.__closeButton.innerHTML=d?i.TEXT_OPEN:i.TEXT_CLOSED)}},load:{get:function(){return n.load}},useLocalStorage:{get:function(){return s},set:function(d){Qo&&(s=d,d?te.bind(window,"unload",r):te.unbind(window,"unload",r),localStorage.setItem(Ma(t,"isLocal"),d))}}}),ue.isUndefined(n.parent)){if(this.closed=n.closed||!1,te.addClass(this.domElement,i.CLASS_MAIN),te.makeSelectable(this.domElement,!1),Qo&&s){t.useLocalStorage=!0;var o=localStorage.getItem(Ma(this,"gui"));o&&(n.load=JSON.parse(o))}this.__closeButton=document.createElement("div"),this.__closeButton.innerHTML=i.TEXT_CLOSED,te.addClass(this.__closeButton,i.CLASS_CLOSE_BUTTON),n.closeOnTop?(te.addClass(this.__closeButton,i.CLASS_CLOSE_TOP),this.domElement.insertBefore(this.__closeButton,this.domElement.childNodes[0])):(te.addClass(this.__closeButton,i.CLASS_CLOSE_BOTTOM),this.domElement.appendChild(this.__closeButton)),te.bind(this.__closeButton,"click",function(){t.closed=!t.closed})}else{n.closed===void 0&&(n.closed=!0);var c=document.createTextNode(n.name);te.addClass(c,"controller-name"),a=zd(t,c);var l=function(d){return d.preventDefault(),t.closed=!t.closed,!1};te.addClass(this.__ul,i.CLASS_CLOSED),te.addClass(a,"title"),te.bind(a,"click",l),n.closed||(this.closed=!1)}n.autoPlace&&(ue.isUndefined(n.parent)&&(_m&&(Sa=document.createElement("div"),te.addClass(Sa,bm),te.addClass(Sa,i.CLASS_AUTO_PLACE_CONTAINER),document.body.appendChild(Sa),_m=!1),Sa.appendChild(this.domElement),te.addClass(this.domElement,i.CLASS_AUTO_PLACE)),this.parent||qd(t,n.width)),this.__resizeHandler=function(){t.onResizeDebounced()},te.bind(window,"resize",this.__resizeHandler),te.bind(this.__ul,"webkitTransitionEnd",this.__resizeHandler),te.bind(this.__ul,"transitionend",this.__resizeHandler),te.bind(this.__ul,"oTransitionEnd",this.__resizeHandler),this.onResize(),n.resizable&&EM(this),r=function(){Qo&&localStorage.getItem(Ma(t,"isLocal"))==="true"&&localStorage.setItem(Ma(t,"gui"),JSON.stringify(t.getSaveObject()))},this.saveToLocalStorageIfPossible=r;function h(){var u=t.getRoot();u.width+=1,ue.defer(function(){u.width-=1})}n.parent||h()};Lt.toggleHide=function(){Hd=!Hd,ue.each(wm,function(i){i.domElement.style.display=Hd?"none":""})},Lt.CLASS_AUTO_PLACE="a",Lt.CLASS_AUTO_PLACE_CONTAINER="ac",Lt.CLASS_MAIN="main",Lt.CLASS_CONTROLLER_ROW="cr",Lt.CLASS_TOO_TALL="taller-than-window",Lt.CLASS_CLOSED="closed",Lt.CLASS_CLOSE_BUTTON="close-button",Lt.CLASS_CLOSE_TOP="close-top",Lt.CLASS_CLOSE_BOTTOM="close-bottom",Lt.CLASS_DRAG="drag",Lt.DEFAULT_WIDTH=245,Lt.TEXT_CLOSED="Close Controls",Lt.TEXT_OPEN="Open Controls",Lt._keydownHandler=function(i){document.activeElement.type!=="text"&&(i.which===Em||i.keyCode===Em)&&Lt.toggleHide()},te.bind(window,"keydown",Lt._keydownHandler,!1),ue.extend(Lt.prototype,{add:function(e,t){return Ho(this,e,t,{factoryArgs:Array.prototype.slice.call(arguments,2)})},addColor:function(e,t){return Ho(this,e,t,{color:!0})},remove:function(e){this.__ul.removeChild(e.__li),this.__controllers.splice(this.__controllers.indexOf(e),1);var t=this;ue.defer(function(){t.onResize()})},destroy:function(){if(this.parent)throw new Error("Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.");this.autoPlace&&Sa.removeChild(this.domElement);var e=this;ue.each(this.__folders,function(t){e.removeFolder(t)}),te.unbind(window,"keydown",Lt._keydownHandler,!1),vm(this)},addFolder:function(e){if(this.__folders[e]!==void 0)throw new Error('You already have a folder in this GUI by the name "'+e+'"');var t={name:e,parent:this};t.autoPlace=this.autoPlace,this.load&&this.load.folders&&this.load.folders[e]&&(t.closed=this.load.folders[e].closed,t.load=this.load.folders[e]);var n=new Lt(t);this.__folders[e]=n;var s=zd(this,n.domElement);return te.addClass(s,"folder"),n},removeFolder:function(e){this.__ul.removeChild(e.domElement.parentElement),delete this.__folders[e.name],this.load&&this.load.folders&&this.load.folders[e.name]&&delete this.load.folders[e.name],vm(e);var t=this;ue.each(e.__folders,function(n){e.removeFolder(n)}),ue.defer(function(){t.onResize()})},open:function(){this.closed=!1},close:function(){this.closed=!0},hide:function(){this.domElement.style.display="none"},show:function(){this.domElement.style.display=""},onResize:function(){var e=this.getRoot();if(e.scrollable){var t=te.getOffset(e.__ul).top,n=0;ue.each(e.__ul.childNodes,function(s){e.autoPlace&&s===e.__save_row||(n+=te.getHeight(s))}),window.innerHeight-t-ym<n?(te.addClass(e.domElement,Lt.CLASS_TOO_TALL),e.__ul.style.height=window.innerHeight-t-ym+"px"):(te.removeClass(e.domElement,Lt.CLASS_TOO_TALL),e.__ul.style.height="auto")}e.__resize_handle&&ue.defer(function(){e.__resize_handle.style.height=e.__ul.offsetHeight+"px"}),e.__closeButton&&(e.__closeButton.style.width=e.width+"px")},onResizeDebounced:ue.debounce(function(){this.onResize()},50),remember:function(){if(ue.isUndefined(Go)&&(Go=new gM,Go.domElement.innerHTML=dM),this.parent)throw new Error("You can only call remember on a top level GUI.");var e=this;ue.each(Array.prototype.slice.call(arguments),function(t){e.__rememberedObjects.length===0&&bM(e),e.__rememberedObjects.indexOf(t)===-1&&e.__rememberedObjects.push(t)}),this.autoPlace&&qd(this,this.width)},getRoot:function(){for(var e=this;e.parent;)e=e.parent;return e},getSaveObject:function(){var e=this.load;return e.closed=this.closed,this.__rememberedObjects.length>0&&(e.preset=this.preset,e.remembered||(e.remembered={}),e.remembered[this.preset]=Ol(this)),e.folders={},ue.each(this.__folders,function(t,n){e.folders[n]=t.getSaveObject()}),e},save:function(){this.load.remembered||(this.load.remembered={}),this.load.remembered[this.preset]=Ol(this),Vd(this,!1),this.saveToLocalStorageIfPossible()},saveAs:function(e){this.load.remembered||(this.load.remembered={},this.load.remembered[Oo]=Ol(this,!0)),this.load.remembered[e]=Ol(this),this.preset=e,Wd(this,e,!0),this.saveToLocalStorageIfPossible()},revert:function(e){ue.each(this.__controllers,function(t){this.getRoot().load.remembered?Cm(e||this.getRoot(),t):t.setValue(t.initialValue),t.__onFinishChange&&t.__onFinishChange.call(t,t.getValue())},this),ue.each(this.__folders,function(t){t.revert(t)}),e||Vd(this.getRoot(),!1)},listen:function(e){var t=this.__listening.length===0;this.__listening.push(e),t&&Sm(this.__listening)},updateDisplay:function(){ue.each(this.__controllers,function(e){e.updateDisplay()}),ue.each(this.__folders,function(e){e.updateDisplay()})}});function zd(i,e,t){var n=document.createElement("li");return e&&n.appendChild(e),t?i.__ul.insertBefore(n,t):i.__ul.appendChild(n),i.onResize(),n}function vm(i){te.unbind(window,"resize",i.__resizeHandler),i.saveToLocalStorageIfPossible&&te.unbind(window,"unload",i.saveToLocalStorageIfPossible)}function Vd(i,e){var t=i.__preset_select[i.__preset_select.selectedIndex];e?t.innerHTML=t.value+"*":t.innerHTML=t.value}function xM(i,e,t){if(t.__li=e,t.__gui=i,ue.extend(t,{options:function(a){if(arguments.length>1){var o=t.__li.nextElementSibling;return t.remove(),Ho(i,t.object,t.property,{before:o,factoryArgs:[ue.toArray(arguments)]})}if(ue.isArray(a)||ue.isObject(a)){var c=t.__li.nextElementSibling;return t.remove(),Ho(i,t.object,t.property,{before:c,factoryArgs:[a]})}},name:function(a){return t.__li.firstElementChild.firstElementChild.innerHTML=a,t},listen:function(){return t.__gui.listen(t),t},remove:function(){return t.__gui.remove(t),t}}),t instanceof Qd){var n=new Ul(t.object,t.property,{min:t.__min,max:t.__max,step:t.__step});ue.each(["updateDisplay","onChange","onFinishChange","step","min","max"],function(r){var a=t[r],o=n[r];t[r]=n[r]=function(){var c=Array.prototype.slice.call(arguments);return o.apply(n,c),a.apply(t,c)}}),te.addClass(e,"has-slider"),t.domElement.insertBefore(n.domElement,t.domElement.firstElementChild)}else if(t instanceof Ul){var s=function(a){if(ue.isNumber(t.__min)&&ue.isNumber(t.__max)){var o=t.__li.firstElementChild.firstElementChild.innerHTML,c=t.__gui.__listening.indexOf(t)>-1;t.remove();var l=Ho(i,t.object,t.property,{before:t.__li.nextElementSibling,factoryArgs:[t.__min,t.__max,t.__step]});return l.name(o),c&&l.listen(),l}return a};t.min=ue.compose(s,t.min),t.max=ue.compose(s,t.max)}else t instanceof fm?(te.bind(e,"click",function(){te.fakeEvent(t.__checkbox,"click")}),te.bind(t.__checkbox,"click",function(r){r.stopPropagation()})):t instanceof mm?(te.bind(e,"click",function(){te.fakeEvent(t.__button,"click")}),te.bind(e,"mouseover",function(){te.addClass(t.__button,"hover")}),te.bind(e,"mouseout",function(){te.removeClass(t.__button,"hover")})):t instanceof Gd&&(te.addClass(e,"color"),t.updateDisplay=ue.compose(function(r){return e.style.borderLeftColor=t.__color.toString(),r},t.updateDisplay),t.updateDisplay());t.setValue=ue.compose(function(r){return i.getRoot().__preset_select&&t.isModified()&&Vd(i.getRoot(),!0),r},t.setValue)}function Cm(i,e){var t=i.getRoot(),n=t.__rememberedObjects.indexOf(e.object);if(n!==-1){var s=t.__rememberedObjectIndecesToControllers[n];if(s===void 0&&(s={},t.__rememberedObjectIndecesToControllers[n]=s),s[e.property]=e,t.load&&t.load.remembered){var r=t.load.remembered,a=void 0;if(r[i.preset])a=r[i.preset];else if(r[Oo])a=r[Oo];else return;if(a[n]&&a[n][e.property]!==void 0){var o=a[n][e.property];e.initialValue=o,e.setValue(o)}}}}function Ho(i,e,t,n){if(e[t]===void 0)throw new Error('Object "'+e+'" has no property "'+t+'"');var s=void 0;if(n.color)s=new Gd(e,t);else{var r=[e,t].concat(n.factoryArgs);s=fM.apply(i,r)}n.before instanceof yr&&(n.before=n.before.__li),Cm(i,s),te.addClass(s.domElement,"c");var a=document.createElement("span");te.addClass(a,"property-name"),a.innerHTML=s.property;var o=document.createElement("div");o.appendChild(a),o.appendChild(s.domElement);var c=zd(i,o,n.before);return te.addClass(c,Lt.CLASS_CONTROLLER_ROW),s instanceof Gd?te.addClass(c,"color"):te.addClass(c,iM(s.getValue())),xM(i,c,s),i.__controllers.push(s),s}function Ma(i,e){return document.location.href+"."+e}function Wd(i,e,t){var n=document.createElement("option");n.innerHTML=e,n.value=e,i.__preset_select.appendChild(n),t&&(i.__preset_select.selectedIndex=i.__preset_select.length-1)}function Im(i,e){e.style.display=i.useLocalStorage?"block":"none"}function bM(i){var e=i.__save_row=document.createElement("li");te.addClass(i.domElement,"has-save"),i.__ul.insertBefore(e,i.__ul.firstChild),te.addClass(e,"save-row");var t=document.createElement("span");t.innerHTML="&nbsp;",te.addClass(t,"button gears");var n=document.createElement("span");n.innerHTML="Save",te.addClass(n,"button"),te.addClass(n,"save");var s=document.createElement("span");s.innerHTML="New",te.addClass(s,"button"),te.addClass(s,"save-as");var r=document.createElement("span");r.innerHTML="Revert",te.addClass(r,"button"),te.addClass(r,"revert");var a=i.__preset_select=document.createElement("select");if(i.load&&i.load.remembered?ue.each(i.load.remembered,function(u,d){Wd(i,d,d===i.preset)}):Wd(i,Oo,!1),te.bind(a,"change",function(){for(var u=0;u<i.__preset_select.length;u++)i.__preset_select[u].innerHTML=i.__preset_select[u].value;i.preset=this.value}),e.appendChild(a),e.appendChild(t),e.appendChild(n),e.appendChild(s),e.appendChild(r),Qo){var o=document.getElementById("dg-local-explain"),c=document.getElementById("dg-local-storage"),l=document.getElementById("dg-save-locally");l.style.display="block",localStorage.getItem(Ma(i,"isLocal"))==="true"&&c.setAttribute("checked","checked"),Im(i,o),te.bind(c,"change",function(){i.useLocalStorage=!i.useLocalStorage,Im(i,o)})}var h=document.getElementById("dg-new-constructor");te.bind(h,"keydown",function(u){u.metaKey&&(u.which===67||u.keyCode===67)&&Go.hide()}),te.bind(t,"click",function(){h.innerHTML=JSON.stringify(i.getSaveObject(),void 0,2),Go.show(),h.focus(),h.select()}),te.bind(n,"click",function(){i.save()}),te.bind(s,"click",function(){var u=prompt("Enter a new preset name.");u&&i.saveAs(u)}),te.bind(r,"click",function(){i.revert()})}function EM(i){var e=void 0;i.__resize_handle=document.createElement("div"),ue.extend(i.__resize_handle.style,{width:"6px",marginLeft:"-3px",height:"200px",cursor:"ew-resize",position:"absolute"});function t(r){return r.preventDefault(),i.width+=e-r.clientX,i.onResize(),e=r.clientX,!1}function n(){te.removeClass(i.__closeButton,Lt.CLASS_DRAG),te.unbind(window,"mousemove",t),te.unbind(window,"mouseup",n)}function s(r){return r.preventDefault(),e=r.clientX,te.addClass(i.__closeButton,Lt.CLASS_DRAG),te.bind(window,"mousemove",t),te.bind(window,"mouseup",n),!1}te.bind(i.__resize_handle,"mousedown",s),te.bind(i.__closeButton,"mousedown",s),i.domElement.insertBefore(i.__resize_handle,i.domElement.firstElementChild)}function qd(i,e){i.domElement.style.width=e+"px",i.__save_row&&i.autoPlace&&(i.__save_row.style.width=e+"px"),i.__closeButton&&(i.__closeButton.style.width=e+"px")}function Ol(i,e){var t={};return ue.each(i.__rememberedObjects,function(n,s){var r={},a=i.__rememberedObjectIndecesToControllers[s];ue.each(a,function(o,c){r[c]=e?o.initialValue:o.getValue()}),t[s]=r}),t}function yM(i){for(var e=0;e<i.__preset_select.length;e++)i.__preset_select[e].value===i.preset&&(i.__preset_select.selectedIndex=e)}function Sm(i){i.length!==0&&AM.call(window,function(){Sm(i)}),ue.each(i,function(e){e.updateDisplay()})}var _M=Lt;const Ql=[{id:"",name:"None",path:null},{id:"neutral",name:"Neutral",path:null},{id:"venice-sunset",name:"Venice Sunset",path:"https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr",format:".exr"},{id:"footprint-court",name:"Footprint Court (HDR Labs)",path:"https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr",format:".exr"}],wM=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],Mm=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function vM(i){if(i<=255)return wM[i];let e=0,t=Mm.length-1;for(;e<=t;){const n=e+t>>1,s=Mm[n];if(i<s[0]){t=n-1;continue}if(i>s[1]){e=n+1;continue}return s[2]}return"L"}function CM(i){const e=i.length;if(e===0)return null;const t=new Array(e);let n=!1;for(let l=0;l<e;){const h=i.charCodeAt(l);let u=h,d=1;if(h>=55296&&h<=56319&&l+1<e){const p=i.charCodeAt(l+1);p>=56320&&p<=57343&&(u=(h-55296<<10)+(p-56320)+65536,d=2)}const f=vM(u);(f==="R"||f==="AL"||f==="AN")&&(n=!0);for(let p=0;p<d;p++)t[l+p]=f;l+=d}if(!n)return null;let s=0;for(let l=0;l<e;l++){const h=t[l];if(h==="L"){s=0;break}if(h==="R"||h==="AL"){s=1;break}}const r=new Int8Array(e);for(let l=0;l<e;l++)r[l]=s;const a=s&1?"R":"L",o=a;let c=o;for(let l=0;l<e;l++)t[l]==="NSM"?t[l]=c:c=t[l];c=o;for(let l=0;l<e;l++){const h=t[l];h==="EN"?t[l]=c==="AL"?"AN":"EN":(h==="R"||h==="L"||h==="AL")&&(c=h)}for(let l=0;l<e;l++)t[l]==="AL"&&(t[l]="R");for(let l=1;l<e-1;l++)t[l]==="ES"&&t[l-1]==="EN"&&t[l+1]==="EN"&&(t[l]="EN"),t[l]==="CS"&&(t[l-1]==="EN"||t[l-1]==="AN")&&t[l+1]===t[l-1]&&(t[l]=t[l-1]);for(let l=0;l<e;l++){if(t[l]!=="EN")continue;let h;for(h=l-1;h>=0&&t[h]==="ET";h--)t[h]="EN";for(h=l+1;h<e&&t[h]==="ET";h++)t[h]="EN"}for(let l=0;l<e;l++){const h=t[l];(h==="WS"||h==="ES"||h==="ET"||h==="CS")&&(t[l]="ON")}c=o;for(let l=0;l<e;l++){const h=t[l];h==="EN"?t[l]=c==="L"?"L":"EN":(h==="R"||h==="L")&&(c=h)}for(let l=0;l<e;l++){if(t[l]!=="ON")continue;let h=l+1;for(;h<e&&t[h]==="ON";)h++;const u=l>0?t[l-1]:o,d=h<e?t[h]:o,f=u!=="L"?"R":"L";if(f===(d!=="L"?"R":"L"))for(let m=l;m<h;m++)t[m]=f;l=h-1}for(let l=0;l<e;l++)t[l]==="ON"&&(t[l]=a);for(let l=0;l<e;l++){const h=t[l];(r[l]&1)===0?h==="R"?r[l]++:(h==="AN"||h==="EN")&&(r[l]+=2):(h==="L"||h==="AN"||h==="EN")&&r[l]++}return r}function IM(i,e){const t=CM(i);if(t===null)return null;const n=new Int8Array(e.length);for(let s=0;s<e.length;s++)n[s]=t[e[s]];return n}const SM=/[ \t\n\r\f]+/g,MM=/[\t\n\r\f]| {2,}|^ | $/;function BM(i){const e=i??"normal";return e==="pre-wrap"?{mode:e,preserveOrdinarySpaces:!0,preserveHardBreaks:!0}:{mode:e,preserveOrdinarySpaces:!1,preserveHardBreaks:!1}}function TM(i){if(!MM.test(i))return i;let e=i.replace(SM," ");return e.charCodeAt(0)===32&&(e=e.slice(1)),e.length>0&&e.charCodeAt(e.length-1)===32&&(e=e.slice(0,-1)),e}function RM(i){return/[\r\f]/.test(i)?i.replace(/\r\n/g,`
`).replace(/[\r\f]/g,`
`):i.replace(/\r\n/g,`
-`)}let Kd=null,NM;function DM(){return Kd===null&&(Kd=new Intl.Segmenter(NM,{granularity:"word"})),Kd}const LM=new RegExp("\\p{Script=Arabic}","u"),Gl=new RegExp("\\p{M}","u"),Bm=new RegExp("\\p{Nd}","u");function Tm(i){return LM.test(i)}function Rm(i){return i>=19968&&i<=40959||i>=13312&&i<=19903||i>=131072&&i<=173791||i>=173824&&i<=177983||i>=177984&&i<=178207||i>=178208&&i<=183983||i>=183984&&i<=191471||i>=191472&&i<=192093||i>=194560&&i<=195103||i>=196608&&i<=201551||i>=201552&&i<=205743||i>=205744&&i<=210041||i>=63744&&i<=64255||i>=12288&&i<=12351||i>=12352&&i<=12447||i>=12448&&i<=12543||i>=44032&&i<=55215||i>=65280&&i<=65519}function _r(i){for(let e=0;e<i.length;e++){const t=i.charCodeAt(e);if(!(t<12288)){if(t>=55296&&t<=56319&&e+1<i.length){const n=i.charCodeAt(e+1);if(n>=56320&&n<=57343){const s=(t-55296<<10)+(n-56320)+65536;if(Rm(s))return!0;e++;continue}}if(Rm(t))return!0}}return!1}function PM(i){const e=zl(i);return e!==null&&(jd.has(e)||wr.has(e))}const kM=new Set([" "," ","⁠","\uFEFF"]);function UM(i){return _r(i)}function OM(i){const e=zl(i);return e!==null&&kM.has(e)}function QM(i){return!PM(i)&&!OM(i)}const jd=new Set([",",".","!",":",";","?","、","。","・",")","〕","〉","》","」","』","】","〗","〙","〛","ー","々","〻","ゝ","ゞ","ヽ","ヾ"]),Hl=new Set(['"',"(","[","{","“","‘","«","‹","(","〔","〈","《","「","『","【","〖","〘","〚"]),Xd=new Set(["'","’"]),wr=new Set([".",",","!","?",":",";","،","؛","؟","।","॥","၊","။","၌","၍","၏",")","]","}","%",'"',"”","’","»","›","…"]),GM=new Set([":",".","،","؛"]),HM=new Set(["၏"]),zM=new Set(["”","’","»","›","」","』","】","》","〉","〕",")"]);function VM(i){if(Yd(i))return!0;let e=!1;for(const t of i){if(wr.has(t)){e=!0;continue}if(!(e&&Gl.test(t)))return!1}return e}function WM(i){for(const e of i)if(!jd.has(e)&&!wr.has(e))return!1;return i.length>0}function qM(i){if(Yd(i))return!0;for(const e of i)if(!Hl.has(e)&&!Xd.has(e)&&!Gl.test(e))return!1;return i.length>0}function Yd(i){let e=!1;for(const t of i)if(!(t==="\\"||Gl.test(t))){if(Hl.has(t)||wr.has(t)||Xd.has(t)){e=!0;continue}return!1}return e}function Fm(i,e){const t=e-1;if(t<=0)return Math.max(t,0);const n=i.charCodeAt(t);if(n<56320||n>57343)return t;const s=t-1;if(s<0)return t;const r=i.charCodeAt(s);return r>=55296&&r<=56319?s:t}function zl(i){if(i.length===0)return null;const e=Fm(i,i.length);return i.slice(e)}function KM(i){const e=Array.from(i);let t=e.length;for(;t>0;){const n=e[t-1];if(Gl.test(n)){t--;continue}if(Hl.has(n)||Xd.has(n)){t--;continue}break}return t<=0||t===e.length?null:{head:e.slice(0,t).join(""),tail:e.slice(t).join("")}}function jM(i,e,t){return t==="text"&&!e&&i.length===1&&i!=="-"&&i!=="—"?i:null}function Nm(i,e,t,n){const s=e[n],r=i[n];if(s==null)return r;const a=t[n];if(r.length===a)return r;const o=s.repeat(a);return i[n]=o,o}function Dm(i,e){return i&&e!==null&&GM.has(e)}function XM(i){const e=zl(i);return e!==null&&HM.has(e)}function YM(i){if(i.length<2||i[0]!==" ")return null;const e=i.slice(1);return new RegExp("^\\p{M}+$","u").test(e)?{space:" ",marks:e}:null}function Jd(i){let e=i.length;for(;e>0;){const t=Fm(i,e),n=i.slice(t,e);if(zM.has(n))return!0;if(!wr.has(n))return!1;e=t}return!1}function JM(i,e){if(e.preserveOrdinarySpaces||e.preserveHardBreaks){if(i===" ")return"preserved-space";if(i===" ")return"tab";if(e.preserveHardBreaks&&i===`
-`)return"hard-break"}return i===" "?"space":i===" "||i===" "||i==="⁠"||i==="\uFEFF"?"glue":i==="​"?"zero-width-break":i==="­"?"soft-hyphen":"text"}const ZM=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function hi(i){return i.length===1?i[0]:i.join("")}function $M(i,e){const t=[];for(let n=i.length-1;n>=0;n--)t.push(i[n]);return t.push(e),hi(t)}function eB(i,e,t,n){if(!ZM.test(i))return[{text:i,isWordLike:e,kind:"text",start:t}];const s=[];let r=null,a=[],o=t,c=!1,l=0;for(const h of i){const u=JM(h,n),d=u==="text"&&e;if(r!==null&&u===r&&d===c){a.push(h),l+=h.length;continue}r!==null&&s.push({text:hi(a),isWordLike:c,kind:r,start:o}),r=u,a=[h],o=t+l,c=d,l+=h.length}return r!==null&&s.push({text:hi(a),isWordLike:c,kind:r,start:o}),s}function Zd(i){return i==="space"||i==="preserved-space"||i==="zero-width-break"||i==="hard-break"}const tB=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function nB(i,e){const t=i.texts[e];return t.startsWith("www.")?!0:tB.test(t)&&e+1<i.len&&i.kinds[e+1]==="text"&&i.texts[e+1]==="//"}function iB(i){return i.includes("?")&&(i.includes("://")||i.startsWith("www."))}function sB(i){const e=i.texts.slice(),t=i.isWordLike.slice(),n=i.kinds.slice(),s=i.starts.slice();for(let a=0;a<i.len;a++){if(n[a]!=="text"||!nB(i,a))continue;const o=[e[a]];let c=a+1;for(;c<i.len&&!Zd(n[c]);){o.push(e[c]),t[a]=!0;const l=e[c].includes("?");if(n[c]="text",e[c]="",c++,l)break}e[a]=hi(o)}let r=0;for(let a=0;a<e.length;a++){const o=e[a];o.length!==0&&(r!==a&&(e[r]=o,t[r]=t[a],n[r]=n[a],s[r]=s[a]),r++)}return e.length=r,t.length=r,n.length=r,s.length=r,{len:r,texts:e,isWordLike:t,kinds:n,starts:s}}function rB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r];if(e.push(a),t.push(i.isWordLike[r]),n.push(i.kinds[r]),s.push(i.starts[r]),!iB(a))continue;const o=r+1;if(o>=i.len||Zd(i.kinds[o]))continue;const c=[],l=i.starts[o];let h=o;for(;h<i.len&&!Zd(i.kinds[h]);)c.push(i.texts[h]),h++;c.length>0&&(e.push(hi(c)),t.push(!0),n.push("text"),s.push(l),r=h-1)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}const aB=new Set([":","-","/","×",",",".","+","–","—"]),Lm=/^[A-Za-z0-9_]+[,:;]*$/,Pm=/[,:;]+$/;function km(i){for(const e of i)if(Bm.test(e))return!0;return!1}function Vl(i){if(i.length===0)return!1;for(const e of i)if(!(Bm.test(e)||aB.has(e)))return!1;return!0}function oB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r],o=i.kinds[r];if(o==="text"&&Vl(a)&&km(a)){const c=[a];let l=r+1;for(;l<i.len&&i.kinds[l]==="text"&&Vl(i.texts[l]);)c.push(i.texts[l]),l++;e.push(hi(c)),t.push(!0),n.push("text"),s.push(i.starts[r]),r=l-1;continue}e.push(a),t.push(i.isWordLike[r]),n.push(o),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function cB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r],o=i.kinds[r],c=i.isWordLike[r];if(o==="text"&&c&&Lm.test(a)){const l=[a];let h=Pm.test(a),u=r+1;for(;h&&u<i.len&&i.kinds[u]==="text"&&i.isWordLike[u]&&Lm.test(i.texts[u]);){const d=i.texts[u];l.push(d),h=Pm.test(d),u++}e.push(hi(l)),t.push(!0),n.push("text"),s.push(i.starts[r]),r=u-1;continue}e.push(a),t.push(c),n.push(o),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function lB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r];if(i.kinds[r]==="text"&&a.includes("-")){const o=a.split("-");let c=o.length>1;for(let l=0;l<o.length;l++){const h=o[l];if(!c)break;(h.length===0||!km(h)||!Vl(h))&&(c=!1)}if(c){let l=0;for(let h=0;h<o.length;h++){const u=o[h],d=h<o.length-1?`${u}-`:u;e.push(d),t.push(!0),n.push("text"),s.push(i.starts[r]+l),l+=d.length}continue}}e.push(a),t.push(i.isWordLike[r]),n.push(i.kinds[r]),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function hB(i){const e=[],t=[],n=[],s=[];let r=0;for(;r<i.len;){const a=[i.texts[r]];let o=i.isWordLike[r],c=i.kinds[r],l=i.starts[r];if(c==="glue"){const h=[a[0]],u=l;for(r++;r<i.len&&i.kinds[r]==="glue";)h.push(i.texts[r]),r++;const d=hi(h);if(r<i.len&&i.kinds[r]==="text")a[0]=d,a.push(i.texts[r]),o=i.isWordLike[r],c="text",l=u,r++;else{e.push(d),t.push(!1),n.push("glue"),s.push(u);continue}}else r++;if(c==="text")for(;r<i.len&&i.kinds[r]==="glue";){const h=[];for(;r<i.len&&i.kinds[r]==="glue";)h.push(i.texts[r]),r++;const u=hi(h);if(r<i.len&&i.kinds[r]==="text"){a.push(u,i.texts[r]),o=o||i.isWordLike[r],r++;continue}a.push(u)}e.push(hi(a)),t.push(o),n.push(c),s.push(l)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function uB(i){const e=i.texts.slice(),t=i.isWordLike.slice(),n=i.kinds.slice(),s=i.starts.slice();for(let r=0;r<e.length-1;r++){if(n[r]!=="text"||n[r+1]!=="text"||!_r(e[r])||!_r(e[r+1]))continue;const a=KM(e[r]);a!==null&&(e[r]=a.head,e[r+1]=a.tail+e[r+1],s[r+1]=s[r]+a.head.length)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function Um(i,e,t){const n=DM();let s=0;const r=[],a=[],o=[],c=[],l=[],h=[],u=[],d=[],f=[],p=[],m=[],g=[];for(const w of n.segment(i))for(const I of eB(w.segment,w.isWordLike??!1,w.index,t)){let O=function(){h[D]!==null&&(a[D]=[Nm(r,h,u,D)],h[D]=null),a[D].push(I.text),o[D]=o[D]||I.isWordLike,d[D]=d[D]||v,f[D]=f[D]||F,p[D]=q,m[D]=$,g[D]=Dm(f[D],K)};const T=I.kind==="text",C=jM(I.text,I.isWordLike,I.kind),v=_r(I.text),F=Tm(I.text),K=zl(I.text),q=Jd(I.text),$=XM(I.text),D=s-1;e.carryCJKAfterClosingQuote&&T&&s>0&&c[D]==="text"&&v&&d[D]&&p[D]||T&&s>0&&c[D]==="text"&&WM(I.text)&&d[D]||T&&s>0&&c[D]==="text"&&m[D]?O():T&&s>0&&c[D]==="text"&&I.isWordLike&&F&&g[D]?(O(),o[D]=!0):C!==null&&s>0&&c[D]==="text"&&h[D]===C?u[D]=(u[D]??1)+1:T&&!I.isWordLike&&s>0&&c[D]==="text"&&(VM(I.text)||I.text==="-"&&o[D])?O():(r[s]=I.text,a[s]=[I.text],o[s]=I.isWordLike,c[s]=I.kind,l[s]=I.start,h[s]=C,u[s]=C===null?0:1,d[s]=v,f[s]=F,p[s]=q,m[s]=$,g[s]=Dm(F,K),s++)}for(let w=0;w<s;w++){if(h[w]!==null){r[w]=Nm(r,h,u,w);continue}r[w]=hi(a[w])}for(let w=1;w<s;w++)c[w]==="text"&&!o[w]&&Yd(r[w])&&c[w-1]==="text"&&(r[w-1]+=r[w],o[w-1]=o[w-1]||o[w],r[w]="");const A=Array.from({length:s},()=>null);let _=-1;for(let w=s-1;w>=0;w--){const I=r[w];if(I.length!==0){if(c[w]==="text"&&!o[w]&&qM(I)&&_>=0&&c[_]==="text"){const T=A[_]??[];T.push(I),A[_]=T,l[_]=l[w],r[w]="";continue}_=w}}for(let w=0;w<s;w++){const I=A[w];I!=null&&(r[w]=$M(I,r[w]))}let x=0;for(let w=0;w<s;w++){const I=r[w];I.length!==0&&(x!==w&&(r[x]=I,o[x]=o[w],c[x]=c[w],l[x]=l[w]),x++)}r.length=x,o.length=x,c.length=x,l.length=x;const E=hB({len:x,texts:r,isWordLike:o,kinds:c,starts:l}),S=uB(cB(lB(oB(rB(sB(E))))));for(let w=0;w<S.len-1;w++){const I=YM(S.texts[w]);I!==null&&(S.kinds[w]!=="space"&&S.kinds[w]!=="preserved-space"||S.kinds[w+1]!=="text"||!Tm(S.texts[w+1])||(S.texts[w]=I.space,S.isWordLike[w]=!1,S.kinds[w]=S.kinds[w]==="preserved-space"?"preserved-space":"space",S.texts[w+1]=I.marks+S.texts[w+1],S.starts[w+1]=S.starts[w]+I.space.length))}return S}function dB(i,e){if(i.len===0)return[];if(!e.preserveHardBreaks)return[{startSegmentIndex:0,endSegmentIndex:i.len,consumedEndSegmentIndex:i.len}];const t=[];let n=0;for(let s=0;s<i.len;s++)i.kinds[s]==="hard-break"&&(t.push({startSegmentIndex:n,endSegmentIndex:s,consumedEndSegmentIndex:s+1}),n=s+1);return n<i.len&&t.push({startSegmentIndex:n,endSegmentIndex:i.len,consumedEndSegmentIndex:i.len}),t}function fB(i){if(i.len<=1)return i;const e=[],t=[],n=[],s=[];let r=null,a=!1,o=0,c=!1,l=!1;function h(){r!==null&&(e.push(hi(r)),t.push(a),n.push("text"),s.push(o),r=null)}for(let u=0;u<i.len;u++){const d=i.texts[u],f=i.kinds[u],p=i.isWordLike[u],m=i.starts[u];if(f==="text"){const g=UM(d),A=QM(d);if(r!==null&&c&&l){r.push(d),a=a||p,c=c||g,l=A;continue}h(),r=[d],a=p,o=m,c=g,l=A;continue}h(),e.push(d),t.push(p),n.push(f),s.push(m)}return h(),{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function pB(i,e,t="normal",n="normal"){const s=TM(t),r=s.mode==="pre-wrap"?FM(i):RM(i);if(r.length===0)return{normalized:r,chunks:[],len:0,texts:[],isWordLike:[],kinds:[],starts:[]};const a=n==="keep-all"?fB(Um(r,e,s)):Um(r,e,s);return{normalized:r,chunks:dB(a,s),...a}}let Ba=null;const Om=new Map;let Ta=null;const AB=96,gB=new RegExp("\\p{Emoji_Presentation}","u"),mB=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;let $d=null;const Qm=new Map;function ef(){if(Ba!==null)return Ba;if(typeof OffscreenCanvas<"u")return Ba=new OffscreenCanvas(1,1).getContext("2d"),Ba;if(typeof document<"u")return Ba=document.createElement("canvas").getContext("2d"),Ba;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function xB(i){let e=Om.get(i);return e||(e=new Map,Om.set(i,e)),e}function Vs(i,e){let t=e.get(i);return t===void 0&&(t={width:ef().measureText(i).width,containsCJK:_r(i)},e.set(i,t)),t}function Ra(){if(Ta!==null)return Ta;if(typeof navigator>"u")return Ta={lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,preferPrefixWidthsForBreakableRuns:!1,preferEarlySoftHyphenBreak:!1},Ta;const i=navigator.userAgent,t=navigator.vendor==="Apple Computer, Inc."&&i.includes("Safari/")&&!i.includes("Chrome/")&&!i.includes("Chromium/")&&!i.includes("CriOS/")&&!i.includes("FxiOS/")&&!i.includes("EdgiOS/"),n=i.includes("Chrome/")||i.includes("Chromium/")||i.includes("CriOS/")||i.includes("Edg/");return Ta={lineFitEpsilon:t?1/64:.005,carryCJKAfterClosingQuote:n,preferPrefixWidthsForBreakableRuns:t,preferEarlySoftHyphenBreak:t},Ta}function bB(i){const e=i.match(/(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function Gm(){return $d===null&&($d=new Intl.Segmenter(void 0,{granularity:"grapheme"})),$d}function EB(i){return gB.test(i)||i.includes("️")}function yB(i){return mB.test(i)}function _B(i,e){let t=Qm.get(i);if(t!==void 0)return t;const n=ef();n.font=i;const s=n.measureText("😀").width;if(t=0,s>e+.5&&typeof document<"u"&&document.body!==null){const r=document.createElement("span");r.style.font=i,r.style.display="inline-block",r.style.visibility="hidden",r.style.position="absolute",r.textContent="😀",document.body.appendChild(r);const a=r.getBoundingClientRect().width;document.body.removeChild(r),s-a>.5&&(t=s-a)}return Qm.set(i,t),t}function wB(i){let e=0;const t=Gm();for(const n of t.segment(i))EB(n.segment)&&e++;return e}function vB(i,e){return e.emojiCount===void 0&&(e.emojiCount=wB(i)),e.emojiCount}function vr(i,e,t){return t===0?e.width:e.width-vB(i,e)*t}function CB(i,e,t,n,s){if(e.breakableFitAdvances!==void 0)return e.breakableFitAdvances;const r=Gm(),a=[];for(const h of r.segment(i))a.push(h.segment);if(a.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(s==="sum-graphemes"){const h=[];for(const u of a){const d=Vs(u,t);h.push(vr(u,d,n))}return e.breakableFitAdvances=h,e.breakableFitAdvances}if(s==="pair-context"||a.length>AB){const h=[];let u=null,d=0;for(const f of a){const p=Vs(f,t),m=vr(f,p,n);if(u===null)h.push(m);else{const g=u+f,A=Vs(g,t);h.push(vr(g,A,n)-d)}u=f,d=m}return e.breakableFitAdvances=h,e.breakableFitAdvances}const o=[];let c="",l=0;for(const h of a){c+=h;const u=Vs(c,t),d=vr(c,u,n);o.push(d-l),l=d}return e.breakableFitAdvances=o,e.breakableFitAdvances}function IB(i,e){const t=ef();t.font=i;const n=xB(i),s=bB(i),r=e?_B(i,s):0;return{cache:n,fontSize:s,emojiCorrection:r}}function SB(i,e){for(;e<i.widths.length;){const t=i.kinds[e];if(t!=="space"&&t!=="zero-width-break"&&t!=="soft-hyphen")break;e++}return e}function Hm(i,e){if(e<=0)return 0;const t=i%e;return Math.abs(t)<=1e-6?e:e-t}function zm(i,e,t,n,s){let r=0,a=e;for(;r<i.length;){const o=a+i[r];if((r+1<i.length?o+s:o)>t+n)break;a=o,r++}return{fitCount:r,fittedWidth:a}}function MB(i,e){let t=0,n=i.chunks.length;for(;t<n;){const s=Math.floor((t+n)/2);e<i.chunks[s].consumedEndSegmentIndex?n=s:t=s+1}return t<i.chunks.length?t:-1}function Vm(i,e,t){let n=t.segmentIndex;if(t.graphemeIndex>0)return e;const s=i.chunks[e];if(s.startSegmentIndex===s.endSegmentIndex&&n===s.startSegmentIndex)return t.segmentIndex=n,t.graphemeIndex=0,e;for(n<s.startSegmentIndex&&(n=s.startSegmentIndex);n<s.endSegmentIndex;){const r=i.kinds[n];if(r!=="space"&&r!=="zero-width-break"&&r!=="soft-hyphen")return t.segmentIndex=n,t.graphemeIndex=0,e;n++}return s.consumedEndSegmentIndex>=i.widths.length?-1:(t.segmentIndex=s.consumedEndSegmentIndex,t.graphemeIndex=0,e+1)}function tf(i,e){if(e.segmentIndex>=i.widths.length)return-1;const t=MB(i,e.segmentIndex);return t<0?-1:Vm(i,t,e)}function BB(i,e,t){if(t.segmentIndex>=i.widths.length)return-1;let n=e;for(;n<i.chunks.length&&t.segmentIndex>=i.chunks[n].consumedEndSegmentIndex;)n++;return n>=i.chunks.length?-1:Vm(i,n,t)}function TB(i,e){return i.simpleLineWalkFastPath?Wm(i,e):nf(i,e)}function Wm(i,e,t){const{widths:n,kinds:s,breakableFitAdvances:r}=i;if(n.length===0)return 0;const o=Ra().lineFitEpsilon,c=e+o;let l=0,h=0,u=!1,d=0,f=0,p=0,m=0,g=-1,A=0;function _(){g=-1,A=0}function x(C=p,v=m,F=h){l++,t?.({startSegmentIndex:d,startGraphemeIndex:f,endSegmentIndex:C,endGraphemeIndex:v,width:F}),h=0,u=!1,_()}function E(C,v){u=!0,d=C,f=0,p=C+1,m=0,h=v}function S(C,v,F){u=!0,d=C,f=v,p=C,m=v+1,h=F}function w(C,v){if(!u){E(C,v);return}h+=v,p=C+1,m=0}function I(C,v){const F=r[C];for(let K=v;K<F.length;K++){const q=F[K];u?h+q>c?(x(),S(C,K,q)):(h+=q,p=C,m=K+1):S(C,K,q)}u&&p===C&&m===F.length&&(p=C+1,m=0)}let T=0;for(;T<n.length&&!(!u&&(T=SB(i,T),T>=n.length));){const C=n[T],v=s[T],F=v==="space"||v==="preserved-space"||v==="tab"||v==="zero-width-break"||v==="soft-hyphen";if(!u){C>e&&r[T]!==null?I(T,0):E(T,C),F&&(g=T+1,A=h-C),T++;continue}if(h+C>c){if(F){w(T,C),x(T+1,0,h-C),T++;continue}if(g>=0){if(p>g||p===g&&m>0){x();continue}x(g,0,A);continue}if(C>e&&r[T]!==null){x(),I(T,0),T++;continue}x();continue}w(T,C),F&&(g=T+1,A=h-C),T++}return u&&x(),l}function nf(i,e,t){if(i.simpleLineWalkFastPath)return Wm(i,e,t);const{widths:n,lineEndFitAdvances:s,lineEndPaintAdvances:r,kinds:a,breakableFitAdvances:o,discretionaryHyphenWidth:c,tabStopAdvance:l,chunks:h}=i;if(n.length===0||h.length===0)return 0;const u=Ra(),d=u.lineFitEpsilon,f=e+d;let p=0,m=0,g=!1,A=0,_=0,x=0,E=0,S=-1,w=0,I=0,T=null;function C(){S=-1,w=0,I=0,T=null}function v(Q=x,J=E,ee=m){p++,t?.({startSegmentIndex:A,startGraphemeIndex:_,endSegmentIndex:Q,endGraphemeIndex:J,width:ee}),m=0,g=!1,C()}function F(Q,J){g=!0,A=Q,_=0,x=Q+1,E=0,m=J}function K(Q,J,ee){g=!0,A=Q,_=J,x=Q,E=J+1,m=ee}function q(Q,J){if(!g){F(Q,J);return}m+=J,x=Q+1,E=0}function $(Q,J,ee,ae){if(!J)return;const _e=Q==="tab"?0:s[ee],Me=Q==="tab"?ae:r[ee];S=ee+1,w=m-ae+_e,I=m-ae+Me,T=Q}function D(Q,J){const ee=o[Q];for(let ae=J;ae<ee.length;ae++){const _e=ee[ae];g?m+_e>f?(v(),K(Q,ae,_e)):(m+=_e,x=Q,E=ae+1):K(Q,ae,_e)}g&&x===Q&&E===ee.length&&(x=Q+1,E=0)}function O(Q){if(T!=="soft-hyphen")return!1;const J=o[Q];if(J==null)return!1;const{fitCount:ee,fittedWidth:ae}=zm(J,m,e,d,c);return ee===0?!1:(m=ae,x=Q,E=ee,C(),ee===J.length?(x=Q+1,E=0,!0):(v(Q,ee,ae+c),D(Q,ee),!0))}function Y(Q){p++,t?.({startSegmentIndex:Q.startSegmentIndex,startGraphemeIndex:0,endSegmentIndex:Q.consumedEndSegmentIndex,endGraphemeIndex:0,width:0}),C()}for(let Q=0;Q<h.length;Q++){const J=h[Q];if(J.startSegmentIndex===J.endSegmentIndex){Y(J);continue}g=!1,m=0,A=J.startSegmentIndex,_=0,x=J.startSegmentIndex,E=0,C();let ee=J.startSegmentIndex;for(;ee<J.endSegmentIndex;){const ae=a[ee],_e=ae==="space"||ae==="preserved-space"||ae==="tab"||ae==="zero-width-break"||ae==="soft-hyphen",Me=ae==="tab"?Hm(m,l):n[ee];if(ae==="soft-hyphen"){g&&(x=ee+1,E=0,S=ee+1,w=m+c,I=m+c,T=ae),ee++;continue}if(!g){Me>e&&o[ee]!==null?D(ee,0):F(ee,Me),$(ae,_e,ee,Me),ee++;continue}if(m+Me>f){const me=m+(ae==="tab"?0:s[ee]),xe=m+(ae==="tab"?Me:r[ee]);if(T==="soft-hyphen"&&u.preferEarlySoftHyphenBreak&&w<=f){v(S,0,I);continue}if(T==="soft-hyphen"&&O(ee)){ee++;continue}if(_e&&me<=f){q(ee,Me),v(ee+1,0,xe),ee++;continue}if(S>=0&&w<=f){if(x>S||x===S&&E>0){v();continue}const be=S;v(be,0,I),ee=be;continue}if(Me>e&&o[ee]!==null){v(),D(ee,0),ee++;continue}v();continue}q(ee,Me),$(ae,_e,ee,Me),ee++}if(g){const ae=S===J.consumedEndSegmentIndex?I:m;v(J.consumedEndSegmentIndex,0,ae)}}return p}function sf(i,e,t,n){const s=i.chunks[t];if(s.startSegmentIndex===s.endSegmentIndex)return e.segmentIndex=s.consumedEndSegmentIndex,e.graphemeIndex=0,0;const{widths:r,lineEndFitAdvances:a,lineEndPaintAdvances:o,kinds:c,breakableFitAdvances:l,discretionaryHyphenWidth:h,tabStopAdvance:u}=i,d=Ra(),f=d.lineFitEpsilon,p=n+f;let m=0,g=!1,A=e.segmentIndex,_=e.graphemeIndex,x=-1,E=0,S=0,w=null;function I(){x=-1,E=0,S=0,w=null}function T(D=A,O=_,Y=m){return g?(e.segmentIndex=D,e.graphemeIndex=O,Y):null}function C(D,O){g=!0,A=D+1,_=0,m=O}function v(D,O,Y){g=!0,A=D,_=O+1,m=Y}function F(D,O){if(!g){C(D,O);return}m+=O,A=D+1,_=0}function K(D,O,Y,Q){if(!O)return;const J=D==="tab"?0:a[Y],ee=D==="tab"?Q:o[Y];x=Y+1,E=m-Q+J,S=m-Q+ee,w=D}function q(D,O){const Y=l[D];for(let Q=O;Q<Y.length;Q++){const J=Y[Q];if(!g)v(D,Q,J);else{if(m+J>p)return T();m+=J,A=D,_=Q+1}}return g&&A===D&&_===Y.length&&(A=D+1,_=0),null}function $(D){if(w!=="soft-hyphen"||x<0)return null;const O=l[D]??null;if(O!==null){const{fitCount:Y,fittedWidth:Q}=zm(O,m,n,f,h);if(Y===O.length)return m=Q,A=D+1,_=0,I(),null;if(Y>0)return T(D,Y,Q+h)}return E<=p?T(x,0,S):null}for(let D=e.segmentIndex;D<s.endSegmentIndex;D++){const O=c[D],Y=O==="space"||O==="preserved-space"||O==="tab"||O==="zero-width-break"||O==="soft-hyphen",Q=D===e.segmentIndex?e.graphemeIndex:0,J=O==="tab"?Hm(m,u):r[D];if(O==="soft-hyphen"&&Q===0){g&&(A=D+1,_=0,x=D+1,E=m+h,S=m+h,w=O);continue}if(!g){if(Q>0){const ae=q(D,Q);if(ae!==null)return ae}else if(J>n&&l[D]!==null){const ae=q(D,0);if(ae!==null)return ae}else C(D,J);K(O,Y,D,J);continue}if(m+J>p){const ae=m+(O==="tab"?0:a[D]),_e=m+(O==="tab"?J:o[D]);if(w==="soft-hyphen"&&d.preferEarlySoftHyphenBreak&&E<=p)return T(x,0,S);const Me=$(D);if(Me!==null)return Me;if(Y&&ae<=p)return F(D,J),T(D+1,0,_e);if(x>=0&&E<=p)return A>x||A===x&&_>0?T():T(x,0,S);if(J>n&&l[D]!==null){const se=T();if(se!==null)return se;const me=q(D,0);if(me!==null)return me}return T()}F(D,J),K(O,Y,D,J)}return x===s.consumedEndSegmentIndex&&_===0?T(s.consumedEndSegmentIndex,0,S):T(s.consumedEndSegmentIndex,0,m)}function qm(i,e,t){const{widths:n,kinds:s,breakableFitAdvances:r}=i,o=Ra().lineFitEpsilon,c=t+o;let l=0,h=!1,u=e.segmentIndex,d=e.graphemeIndex,f=-1,p=0;for(let m=e.segmentIndex;m<n.length;m++){const g=n[m],A=s[m],_=A==="space"||A==="preserved-space"||A==="tab"||A==="zero-width-break"||A==="soft-hyphen",x=m===e.segmentIndex?e.graphemeIndex:0,E=r[m];if(!h){if(x>0||g>t&&E!==null){const S=E,w=S[x];h=!0,l=w,u=m,d=x+1;for(let I=x+1;I<S.length;I++){const T=S[I];if(l+T>c)return e.segmentIndex=u,e.graphemeIndex=d,l;l+=T,u=m,d=I+1}u===m&&d===S.length&&(u=m+1,d=0)}else h=!0,l=g,u=m+1,d=0;_&&(f=m+1,p=l-g);continue}if(l+g>c)return _?(e.segmentIndex=m+1,e.graphemeIndex=0,l):f>=0?u>f||u===f&&d>0?(e.segmentIndex=u,e.graphemeIndex=d,l):(e.segmentIndex=f,e.graphemeIndex=0,p):(e.segmentIndex=u,e.graphemeIndex=d,l);l+=g,u=m+1,d=0,_&&(f=m+1,p=l-g)}return h?(e.segmentIndex=u,e.graphemeIndex=d,l):null}function rf(i,e,t){const n={segmentIndex:e.segmentIndex,graphemeIndex:e.graphemeIndex},s=tf(i,n);if(s<0)return null;const r=n.segmentIndex,a=n.graphemeIndex,o=i.simpleLineWalkFastPath?qm(i,n,t):sf(i,n,s,t);return o===null?null:{startSegmentIndex:r,startGraphemeIndex:a,endSegmentIndex:n.segmentIndex,endGraphemeIndex:n.graphemeIndex,width:o}}function RB(i,e,t){const n=tf(i,e);return n<0?null:i.simpleLineWalkFastPath?qm(i,e,t):sf(i,e,n,t)}function FB(i,e){if(i.widths.length===0)return{lineCount:0,maxLineWidth:0};const t={segmentIndex:0,graphemeIndex:0};let n=0,s=0;if(!i.simpleLineWalkFastPath){let r=tf(i,t);for(;r>=0;){const a=sf(i,t,r,e);if(a===null)return{lineCount:n,maxLineWidth:s};n++,a>s&&(s=a),r=BB(i,r,t)}return{lineCount:n,maxLineWidth:s}}for(;;){const r=RB(i,t,e);if(r===null)return{lineCount:n,maxLineWidth:s};n++,r>s&&(s=r)}}let af=null,Km=new WeakMap;function jm(){return af===null&&(af=new Intl.Segmenter(void 0,{granularity:"grapheme"})),af}function NB(i){return i?{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[],segments:[]}:{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[]}}function DB(i,e){const t=[];let n=[],s=0,r=!1,a=!1,o=!1;function c(){n.length!==0&&(t.push({text:n.length===1?n[0]:n.join(""),start:s}),n=[],r=!1,a=!1,o=!1)}function l(u,d,f){n=[u],s=d,r=f,a=Jd(u),o=Hl.has(u)}function h(u,d){n.push(u),r=r||d;const f=Jd(u);u.length===1&&wr.has(u)?a=a||f:a=f,o=!1}for(const u of jm().segment(i)){const d=u.segment,f=_r(d);if(n.length===0){l(d,u.index,f);continue}if(o||jd.has(d)||wr.has(d)||e.carryCJKAfterClosingQuote&&f&&a){h(d,f);continue}if(!r&&!f){h(d,f);continue}c(),l(d,u.index,f)}return c(),t}function LB(i,e,t,n){const s=Ra(),{cache:r,emojiCorrection:a}=IB(e,yB(i.normalized)),o=vr("-",Vs("-",r),a),l=vr(" ",Vs(" ",r),a)*8;if(i.len===0)return NB(t);const h=[],u=[],d=[],f=[];let p=i.chunks.length<=1;const m=t?[]:null,g=[],A=t?[]:null,_=Array.from({length:i.len});function x(I,T,C,v,F,K,q){F!=="text"&&F!=="space"&&F!=="zero-width-break"&&(p=!1),h.push(T),u.push(C),d.push(v),f.push(F),m?.push(K),g.push(q),A!==null&&A.push(I)}function E(I,T,C,v,F){const K=Vs(I,r),q=vr(I,K,a),$=T==="space"||T==="preserved-space"||T==="zero-width-break"?0:q,D=T==="space"||T==="zero-width-break"?0:q;if(F&&v&&I.length>1){let O="sum-graphemes";Vl(I)?O="pair-context":s.preferPrefixWidthsForBreakableRuns&&(O="segment-prefixes");const Y=CB(I,K,r,a,O);x(I,q,$,D,T,C,Y);return}x(I,q,$,D,T,C,null)}for(let I=0;I<i.len;I++){_[I]=h.length;const T=i.texts[I],C=i.isWordLike[I],v=i.kinds[I],F=i.starts[I];if(v==="soft-hyphen"){x(T,0,o,o,v,F,null);continue}if(v==="hard-break"){x(T,0,0,0,v,F,null);continue}if(v==="tab"){x(T,0,0,0,v,F,null);continue}const K=Vs(T,r);if(v==="text"&&K.containsCJK){const $=DB(T,s);for(let D=0;D<$.length;D++){const O=$[D];E(O.text,"text",F+O.start,C,!_r(O.text))}continue}E(T,v,F,C,!0)}const S=PB(i.chunks,_,h.length),w=m===null?null:SM(i.normalized,m);return A!==null?{widths:h,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:w,breakableFitAdvances:g,discretionaryHyphenWidth:o,tabStopAdvance:l,chunks:S,segments:A}:{widths:h,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:w,breakableFitAdvances:g,discretionaryHyphenWidth:o,tabStopAdvance:l,chunks:S}}function PB(i,e,t){const n=[];for(let s=0;s<i.length;s++){const r=i[s],a=r.startSegmentIndex<e.length?e[r.startSegmentIndex]:t,o=r.endSegmentIndex<e.length?e[r.endSegmentIndex]:t,c=r.consumedEndSegmentIndex<e.length?e[r.consumedEndSegmentIndex]:t;n.push({startSegmentIndex:a,endSegmentIndex:o,consumedEndSegmentIndex:c})}return n}function Xm(i,e,t,n){const r=pB(i,Ra(),n?.whiteSpace,"normal");return LB(r,e,t)}function Wl(i,e,t){return Xm(i,e,!1,t)}function ql(i,e,t){return Xm(i,e,!0,t)}function MP(i){return i}function kB(i,e,t){const n=TB(i,e);return{lineCount:n,height:n*t}}function Ym(i,e,t){let n=t.get(i);if(n!==void 0)return n;n=[];const s=jm();for(const r of s.segment(e[i]))n.push(r.segment);return t.set(i,n),n}function Jm(i){let e=Km.get(i);return e!==void 0||(e=new Map,Km.set(i,e)),e}function UB(i,e,t,n){return n>0&&i[n-1]==="soft-hyphen"&&!(e===n&&t>0)}function OB(i,e,t,n,s,r,a){let o="";const c=UB(e,n,s,r);for(let l=n;l<r;l++)e[l]==="soft-hyphen"||e[l]==="hard-break"||(l===n&&s>0?o+=Ym(l,i,t).slice(s).join(""):o+=i[l]);return a>0?(c&&(o+="-"),o+=Ym(r,i,t).slice(n===r?s:0,a).join("")):c&&(o+="-"),o}function Zm(i,e,t,n,s,r,a){return{text:OB(i.segments,i.kinds,e,n,s,r,a),width:t,start:{segmentIndex:n,graphemeIndex:s},end:{segmentIndex:r,graphemeIndex:a}}}function QB(i,e,t){return Zm(i,e,t.width,t.startSegmentIndex,t.startGraphemeIndex,t.endSegmentIndex,t.endGraphemeIndex)}function GB(i){return{width:i.width,start:{segmentIndex:i.startSegmentIndex,graphemeIndex:i.startGraphemeIndex},end:{segmentIndex:i.endSegmentIndex,graphemeIndex:i.endGraphemeIndex}}}function HB(i,e){return Zm(i,Jm(i),e.width,e.start.segmentIndex,e.start.graphemeIndex,e.end.segmentIndex,e.end.graphemeIndex)}function zB(i,e,t){return i.widths.length===0?0:nf(i,e,n=>{t(GB(n))})}function of(i,e){return FB(i,e)}function $m(i){let e=0;return zB(i,Number.POSITIVE_INFINITY,t=>{t.width>e&&(e=t.width)}),e}function VB(i,e,t){const n=[];if(i.widths.length===0)return{lineCount:0,height:0,lines:n};const s=Jm(i),r=nf(i,e,a=>{n.push(QB(i,s,a))});return{lineCount:r,height:r*t,lines:n}}const WB=/[ \t\n\f\r]+/,e0=/^[ \t\n\f\r]+/,t0=/[ \t\n\f\r]+$/,Kl={segmentIndex:0,graphemeIndex:0},n0={itemIndex:0,segmentIndex:0,graphemeIndex:0};function BP(i){return i}function cf(i){return{segmentIndex:i.segmentIndex,graphemeIndex:i.graphemeIndex}}function i0(i){return i.segmentIndex===0&&i.graphemeIndex===0}function jl(i,e){const t=e.get(i);if(t!==void 0)return t;const n=$m(ql("A A",i)),s=$m(ql("AA",i)),r=Math.max(0,n-s);return e.set(i,r),r}function qB(i){const e=rf(i,Kl,Number.POSITIVE_INFINITY);return e===null?null:{endGraphemeIndex:e.endGraphemeIndex,endSegmentIndex:e.endSegmentIndex,width:e.width}}function KB(i,e){return i===0&&e>0}function s0(i){const e=[],t=Array.from({length:i.length}),n=new Map;let s=0;for(let r=0;r<i.length;r++){const a=i[r],o=e0.test(a.text),c=t0.test(a.text),l=a.text.replace(e0,"").replace(t0,"");if(l.length===0){WB.test(a.text)&&s===0&&(s=jl(a.font,n));continue}const h=s>0?s:o?jl(a.font,n):0,u=ql(l,a.font),d=qB(u);if(d===null){s=c?jl(a.font,n):0;continue}const f={break:a.break??"normal",endGraphemeIndex:d.endGraphemeIndex,endSegmentIndex:d.endSegmentIndex,extraWidth:a.extraWidth??0,gapBefore:h,naturalWidth:d.width,prepared:u,sourceItemIndex:r};e.push(f),t[r]=f,s=c?jl(a.font,n):0}return{items:e,itemsBySourceItemIndex:t}}function jB(i,e,t,n){if(i.items.length===0||t.itemIndex>=i.items.length)return null;const s=Math.max(1,e);let r=0,a=s,o=t.itemIndex;const c={segmentIndex:t.segmentIndex,graphemeIndex:t.graphemeIndex};e:for(;o<i.items.length;){const l=i.items[o];if(!i0(c)&&c.segmentIndex===l.endSegmentIndex&&c.graphemeIndex===l.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const h=r===0?0:l.gapBefore,u=i0(c);if(l.break==="never"){if(!u){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const m=l.naturalWidth+l.extraWidth,g=h+m;if(r>0&&g>a)break e;n?.(l,h,m,cf(Kl),{segmentIndex:l.endSegmentIndex,graphemeIndex:l.endGraphemeIndex}),r+=g,a=Math.max(0,s-r),o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const d=h+l.extraWidth;if(r>0&&d>=a)break e;if(u){const m=d+l.naturalWidth;if(m<=a){n?.(l,h,l.naturalWidth+l.extraWidth,cf(Kl),{segmentIndex:l.endSegmentIndex,graphemeIndex:l.endGraphemeIndex}),r+=m,a=Math.max(0,s-r),o++,c.segmentIndex=0,c.graphemeIndex=0;continue}}const f=Math.max(1,a-d),p=rf(l.prepared,c,f);if(p===null){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(c.segmentIndex===p.endSegmentIndex&&c.graphemeIndex===p.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(r>0&&u&&h>0&&KB(p.endSegmentIndex,p.endGraphemeIndex)){const m=rf(l.prepared,Kl,Math.max(1,s-l.extraWidth));if(m!==null&&(m.endSegmentIndex>p.endSegmentIndex||m.endSegmentIndex===p.endSegmentIndex&&m.endGraphemeIndex>p.endGraphemeIndex))break e}if(n?.(l,h,p.width+l.extraWidth,cf(c),{segmentIndex:p.endSegmentIndex,graphemeIndex:p.endGraphemeIndex}),r+=h+p.width+l.extraWidth,a=Math.max(0,s-r),p.endSegmentIndex===l.endSegmentIndex&&p.endGraphemeIndex===l.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}c.segmentIndex=p.endSegmentIndex,c.graphemeIndex=p.endGraphemeIndex;break}return r===0?null:(t.itemIndex=o,t.segmentIndex=c.segmentIndex,t.graphemeIndex=c.graphemeIndex,r)}function XB(i,e,t=n0){const n=i,s={itemIndex:t.itemIndex,segmentIndex:t.segmentIndex,graphemeIndex:t.graphemeIndex},r=[],a=jB(n,e,s,(o,c,l,h,u)=>{r.push({itemIndex:o.sourceItemIndex,gapBefore:c,occupiedWidth:l,start:h,end:u})});return a===null?null:{fragments:r,width:a,end:s}}function YB(i,e){return HB(i.prepared,{width:e.occupiedWidth-i.extraWidth,start:e.start,end:e.end}).text}function r0(i,e){const t=i;return{fragments:e.fragments.map(n=>{const s=t.itemsBySourceItemIndex[n.itemIndex];if(s===void 0)throw new Error("Missing rich-text inline item for fragment");return{...n,text:YB(s,n)}}),width:e.width,end:e.end}}function a0(i,e,t){let n=0,s=n0;for(;;){const r=XB(i,e,s);if(r===null)return n;t(r),n++,s=r.end}}const o0="500 14px Inter, sans-serif",lf="600 10px Inter, sans-serif",hf="300 13px Inter, sans-serif",c0="600 10px Inter, sans-serif",l0="300 12px Inter, sans-serif",zo=18,Xl=16,gn=16,Hi=6,h0=12,Yl=Math.min(window.devicePixelRatio||1,2),JB="rgba(0, 0, 0, 0.75)",ZB="rgba(255, 255, 255, 0.08)",$B="rgba(255, 255, 255, 0.9)",eT="rgba(255, 255, 255, 0.30)",tT="rgba(255, 255, 255, 0.85)",u0="rgba(255, 255, 255, 0.08)",nT="rgba(255, 255, 255, 0.45)",iT="rgba(255, 255, 255, 0.08)",sT="rgba(255, 255, 255, 0.7)";function rT(i){let e=0,t=0,n=0;const s=new Set,r=new Set,a=new Set;let o=!1,c=!1;return i.traverse(l=>{if(l.isMesh||l.isPoints||l.isLine){n++;const h=l.geometry;h&&(h.index?t+=h.index.count/3:h.attributes.position&&(t+=h.attributes.position.count/3),h.attributes.position&&(e+=h.attributes.position.count)),l.skeleton&&(o=!0),l.morphTargetInfluences&&l.morphTargetInfluences.length>0&&(c=!0),(Array.isArray(l.material)?l.material:[l.material]).forEach(d=>{if(d){s.add(d.uuid),a.add(d.type.replace("Material",""));for(const f in d)d[f]&&d[f].isTexture&&r.add(d[f].uuid)}})}}),{vertices:e,triangles:Math.floor(t),meshes:n,materials:s.size,textures:r.size,materialTypes:Array.from(a),hasSkinning:o,hasMorphs:c}}function Vo(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":i.toString()}function aT(i,e){const t=[];return i.hasSkinning&&t.push("skinned"),i.hasMorphs&&t.push("morph targets"),e&&e.length>0&&t.push(`${e.length} animation${e.length>1?"s":""}`),i.materialTypes.length>0&&t.push(i.materialTypes.join(", ")),t.length>0?t.join(" · "):""}function oT(i,e,t){const n=rT(e),s=aT(n,t),r=[{label:"MESHES",value:Vo(n.meshes)},{label:"VERTICES",value:Vo(n.vertices)},{label:"TRIANGLES",value:Vo(n.triangles)},{label:"MATERIALS",value:Vo(n.materials)},{label:"TEXTURES",value:Vo(n.textures)}];t&&t.length>0&&r.push({label:"ANIMATIONS",value:t.length.toString()});const a=[];n.materialTypes.forEach(w=>a.push(w)),n.hasSkinning&&a.push("Skinned"),n.hasMorphs&&a.push("Morph"),t&&t.length>0&&a.push("Animated");const o=200,c=Wl("Model Info",o0),l=kB(c,o,zo+2),h=r.map(w=>{const I=[{text:w.label+" ",font:lf},{text:w.value,font:hf}],T=s0(I),C=Wl(w.label,lf),v=of(C,o),F=Wl(w.value,hf),K=of(F,o);return{...w,labelWidth:v.maxLineWidth,valueWidth:K.maxLineWidth,richPrepared:T}}),u=a.map(w=>{const I=Wl(w,c0),T=of(I,300);return{text:w,width:T.maxLineWidth+h0}});let d=[],f=0;if(s){const w=ql(s,l0),I=VB(w,o-gn,zo);d=I.lines,f=I.height}const p=Math.max(l.width+gn*2,...h.map(w=>w.labelWidth+w.valueWidth+gn*3)),m=Math.max(p,180);let g=0;if(u.length>0){let w=0,I=1;u.forEach(T=>{w>0&&w+T.width>m-gn*2&&(I++,w=0),w+=T.width+6}),g=I*(Xl+6)+Hi}const A=gn+l.height+Hi+Hi+h.length*(zo+Hi)+g+(f>0?Hi+f:0)+gn,_=document.createElement("canvas");_.width=m*Yl,_.height=A*Yl,_.style.width=m+"px",_.style.height=A+"px";const x=_.getContext("2d");x.scale(Yl,Yl),x.fillStyle=JB,uf(x,0,0,m,A,10),x.fill(),x.strokeStyle=ZB,x.lineWidth=1,uf(x,.5,.5,m-1,A-1,10),x.stroke();let E=gn;if(x.font=o0,x.fillStyle=$B,x.textBaseline="top",x.fillText("Model Info",gn,E),E+=l.height+Hi,x.strokeStyle=u0,x.beginPath(),x.moveTo(gn,E),x.lineTo(m-gn,E),x.stroke(),E+=Hi,h.forEach(w=>{x.font=lf,x.fillStyle=eT,x.textAlign="left",x.fillText(w.label,gn,E),x.font=hf,x.fillStyle=tT,x.textAlign="right",x.fillText(w.value,m-gn,E),x.textAlign="left",E+=zo+Hi}),u.length>0){let w=gn;u.forEach(I=>{w>gn&&w+I.width>m-gn&&(w=gn,E+=Xl+6),x.fillStyle=iT,uf(x,w,E,I.width,Xl,4),x.fill(),x.font=c0,x.fillStyle=sT,x.textBaseline="top",x.fillText(I.text,w+h0/2,E+3),w+=I.width+6}),E+=Xl+Hi+4}d.length>0&&(x.strokeStyle=u0,x.beginPath(),x.moveTo(gn,E),x.lineTo(m-gn,E),x.stroke(),E+=Hi,x.font=l0,x.fillStyle=nT,x.textBaseline="top",d.forEach(w=>{x.fillText(w.text,gn,E),E+=zo}));const S=document.createElement("div");return S.classList.add("model-info"),S.appendChild(_),i.appendChild(S),{el:S,canvas:_,remove(){S.remove()}}}function uf(i,e,t,n,s,r){i.beginPath(),i.moveTo(e+r,t),i.lineTo(e+n-r,t),i.quadraticCurveTo(e+n,t,e+n,t+r),i.lineTo(e+n,t+s-r),i.quadraticCurveTo(e+n,t+s,e+n-r,t+s),i.lineTo(e+r,t+s),i.quadraticCurveTo(e,t+s,e,t+s-r),i.lineTo(e,t+r),i.quadraticCurveTo(e,t,e+r,t),i.closePath()}const cT="500 11px Inter, sans-serif",d0="300 10px Inter, sans-serif",df=10,f0=6,p0=14,Jl=Math.min(window.devicePixelRatio||1,2),lT=8;function hT(i){const e=[];return i.traverse(t=>{if(e.length>=lT||!t.isMesh||!t.name||t.name.startsWith("_"))return;const n=t.geometry,s=Array.isArray(t.material)?t.material[0]:t.material,r=n&&n.attributes.position?n.attributes.position.count:0,a=s?s.type.replace("Material",""):"",o=[{text:t.name,font:cT}];r>0&&o.push({text:" "+dT(r)+" verts",font:d0}),a&&o.push({text:" "+a,font:d0});const c=s0(o);let l=0,h=0;a0(c,300,m=>{const g=r0(c,m);l=Math.max(l,g.width),h++});const u=l+df*2,d=h*p0+f0*2;n&&n.computeBoundingBox();const f=n?n.boundingBox:null,p=new G;f?(f.getCenter(p),p.applyMatrix4(t.matrixWorld)):t.getWorldPosition(p),e.push({name:t.name,items:o,prepared:c,labelWidth:u,labelHeight:d,position:p,vertCount:r,matType:a})}),e}function uT(i){const{labelWidth:e,labelHeight:t,items:n,prepared:s}=i,r=document.createElement("canvas");r.width=e*Jl,r.height=t*Jl,r.style.width=e+"px",r.style.height=t+"px";const a=r.getContext("2d");a.scale(Jl,Jl),a.fillStyle="rgba(0, 0, 0, 0.8)",A0(a,0,0,e,t,6),a.fill(),a.strokeStyle="rgba(255, 255, 255, 0.1)",a.lineWidth=1,A0(a,.5,.5,e-1,t-1,6),a.stroke(),a.textBaseline="top";let o=f0;return a0(s,e-df*2,c=>{const l=r0(s,c);let h=df;l.fragments.forEach(u=>{h+=u.gapBefore;const d=n[u.itemIndex];a.font=d.font,a.fillStyle=u.itemIndex===0?"rgba(255, 255, 255, 0.9)":"rgba(255, 255, 255, 0.45)",a.fillText(u.text,h,o),h+=u.occupiedWidth}),o+=p0}),r}function dT(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":i.toString()}function A0(i,e,t,n,s,r){i.beginPath(),i.moveTo(e+r,t),i.lineTo(e+n-r,t),i.quadraticCurveTo(e+n,t,e+n,t+r),i.lineTo(e+n,t+s-r),i.quadraticCurveTo(e+n,t+s,e+n-r,t+s),i.lineTo(e+r,t+s),i.quadraticCurveTo(e,t+s,e,t+s-r),i.lineTo(e,t+r),i.quadraticCurveTo(e,t,e+r,t),i.closePath()}const ff=new WeakMap;class fT extends ci{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,s){const r=new os(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,a=>{this.parse(a,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,yt,n).catch(n)}decodeDracoFile(e,t,n,s,r=un,a=()=>{}){const o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:r};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ff.has(e)){const c=ff.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const r=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(r,a).then(c=>(s=c,new Promise((l,h)=>{s._callbacks[r]={resolve:l,reject:h},s.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return o.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),ff.set(e,{key:n,promise:o}),o}_createGeometry(e){const t=new Mn;e.index&&t.setIndex(new Sn(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],r=s.name,a=s.array,o=s.itemSize,c=new Sn(a,o);r==="color"&&(this._assignVertexColorSpace(c,s.vertexColorSpace),c.normalized=!(a instanceof Float32Array)),t.setAttribute(r,c)}return t}_assignVertexColorSpace(e,t){if(t!==yt)return;const n=new Fe;for(let s=0,r=e.count;s<r;s++)n.fromBufferAttribute(e,s),tt.toWorkingColorSpace(n,yt),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new os(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,r)=>{n.load(e,s,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const r=pT.toString(),a=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
-`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(r){const a=r.data;switch(a.type){case"decode":s._callbacks[a.id].resolve(a);break;case"error":s._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,r){return s._taskLoad>r._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function pT(){let i,e;onmessage=function(a){const o=a.data;switch(o.type){case"init":i=o.decoderConfig,e=new Promise(function(h){i.onModuleLoaded=function(u){h({draco:u})},DracoDecoderModule(i)});break;case"decode":const c=o.buffer,l=o.taskConfig;e.then(h=>{const u=h.draco,d=new u.Decoder;try{const f=t(u,d,new Int8Array(c),l),p=f.attributes.map(m=>m.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{u.destroy(d)}});break}};function t(a,o,c,l){const h=l.attributeIDs,u=l.attributeTypes;let d,f;const p=o.GetEncodedGeometryType(c);if(p===a.TRIANGULAR_MESH)d=new a.Mesh,f=o.DecodeArrayToMesh(c,c.byteLength,d);else if(p===a.POINT_CLOUD)d=new a.PointCloud,f=o.DecodeArrayToPointCloud(c,c.byteLength,d);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||d.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const m={index:null,attributes:[]};for(const g in h){const A=self[u[g]];let _,x;if(l.useUniqueIDs)x=h[g],_=o.GetAttributeByUniqueId(d,x);else{if(x=o.GetAttributeId(d,a[h[g]]),x===-1)continue;_=o.GetAttribute(d,x)}const E=s(a,o,d,g,A,_);g==="color"&&(E.vertexColorSpace=l.vertexColorSpace),m.attributes.push(E)}return p===a.TRIANGULAR_MESH&&(m.index=n(a,o,d)),a.destroy(d),m}function n(a,o,c){const h=c.num_faces()*3,u=h*4,d=a._malloc(u);o.GetTrianglesUInt32Array(c,u,d);const f=new Uint32Array(a.HEAPF32.buffer,d,h).slice();return a._free(d),{array:f,itemSize:1}}function s(a,o,c,l,h,u){const d=u.num_components(),p=c.num_points()*d,m=p*h.BYTES_PER_ELEMENT,g=r(a,h),A=a._malloc(m);o.GetAttributeDataArrayForAllPoints(c,u,g,m,A);const _=new h(a.HEAPF32.buffer,A,p).slice();return a._free(A),{name:l,array:_,itemSize:d}}function r(a,o){switch(o){case Float32Array:return a.DT_FLOAT32;case Int8Array:return a.DT_INT8;case Int16Array:return a.DT_INT16;case Int32Array:return a.DT_INT32;case Uint8Array:return a.DT_UINT8;case Uint16Array:return a.DT_UINT16;case Uint32Array:return a.DT_UINT32}}}class AT{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:s,msg:r,transfer:a}=this.queue.shift();this.workersResolve[e]=s,this.workers[e].postMessage(r,a)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(n=>{const s=this._getIdleWorker();s!==-1?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=n,this.workers[s].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const gT=0,g0=2,mT=1,m0=2,xT=0,bT=1,ET=10,yT=0,x0=9,b0=15,E0=16,y0=22,_0=37,w0=43,v0=76,C0=83,I0=97,S0=100,M0=103,B0=109,T0=165,R0=166,pf=1000066e3;class _T{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class Wo{constructor(e,t,n,s){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=s,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+4294967296*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t){t===void 0&&(t=0);const n=this._offset;let s=0;for(;this._dataView.getUint8(this._offset)!==t&&s<e;)s++,this._offset++;return s<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,s)}}const Qn=[171,75,84,88,32,50,48,187,13,10,26,10];function F0(i){return new TextDecoder().decode(i)}function wT(i){const e=new Uint8Array(i.buffer,i.byteOffset,Qn.length);if(e[0]!==Qn[0]||e[1]!==Qn[1]||e[2]!==Qn[2]||e[3]!==Qn[3]||e[4]!==Qn[4]||e[5]!==Qn[5]||e[6]!==Qn[6]||e[7]!==Qn[7]||e[8]!==Qn[8]||e[9]!==Qn[9]||e[10]!==Qn[10]||e[11]!==Qn[11])throw new Error("Missing KTX 2.0 identifier.");const t=new _T,n=17*Uint32Array.BYTES_PER_ELEMENT,s=new Wo(i,Qn.length,n,!0);t.vkFormat=s._nextUint32(),t.typeSize=s._nextUint32(),t.pixelWidth=s._nextUint32(),t.pixelHeight=s._nextUint32(),t.pixelDepth=s._nextUint32(),t.layerCount=s._nextUint32(),t.faceCount=s._nextUint32();const r=s._nextUint32();t.supercompressionScheme=s._nextUint32();const a=s._nextUint32(),o=s._nextUint32(),c=s._nextUint32(),l=s._nextUint32(),h=s._nextUint64(),u=s._nextUint64(),d=new Wo(i,Qn.length+n,3*r*8,!0);for(let Y=0;Y<r;Y++)t.levels.push({levelData:new Uint8Array(i.buffer,i.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const f=new Wo(i,a,o,!0),p={vendorId:f._skip(4)._nextUint16(),descriptorType:f._nextUint16(),versionNumber:f._nextUint16(),descriptorBlockSize:f._nextUint16(),colorModel:f._nextUint8(),colorPrimaries:f._nextUint8(),transferFunction:f._nextUint8(),flags:f._nextUint8(),texelBlockDimension:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],bytesPlane:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],samples:[]},m=(p.descriptorBlockSize/4-6)/4;for(let Y=0;Y<m;Y++){const Q={bitOffset:f._nextUint16(),bitLength:f._nextUint8(),channelType:f._nextUint8(),samplePosition:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};64&Q.channelType?(Q.sampleLower=f._nextInt32(),Q.sampleUpper=f._nextInt32()):(Q.sampleLower=f._nextUint32(),Q.sampleUpper=f._nextUint32()),p.samples[Y]=Q}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(p);const g=new Wo(i,c,l,!0);for(;g._offset<l;){const Y=g._nextUint32(),Q=g._scan(Y),J=F0(Q);if(t.keyValue[J]=g._nextUint8Array(Y-Q.byteLength-1),J.match(/^ktx/i)){const ee=F0(t.keyValue[J]);t.keyValue[J]=ee.substring(0,ee.lastIndexOf("\0"))}g._skip(Y%4?4-Y%4:0)}if(u<=0)return t;const A=new Wo(i,h,u,!0),_=A._nextUint16(),x=A._nextUint16(),E=A._nextUint32(),S=A._nextUint32(),w=A._nextUint32(),I=A._nextUint32(),T=[];for(let Y=0;Y<r;Y++)T.push({imageFlags:A._nextUint32(),rgbSliceByteOffset:A._nextUint32(),rgbSliceByteLength:A._nextUint32(),alphaSliceByteOffset:A._nextUint32(),alphaSliceByteLength:A._nextUint32()});const C=h+A._offset,v=C+E,F=v+S,K=F+w,q=new Uint8Array(i.buffer,i.byteOffset+C,E),$=new Uint8Array(i.buffer,i.byteOffset+v,S),D=new Uint8Array(i.buffer,i.byteOffset+F,w),O=new Uint8Array(i.buffer,i.byteOffset+K,I);return t.globalData={endpointCount:_,selectorCount:x,imageDescs:T,endpointsData:q,selectorsData:$,tablesData:D,extendedData:O},t}let Af,ls,gf;const mf={env:{emscripten_notify_memory_growth:function(i){gf=new Uint8Array(ls.exports.memory.buffer)}}};class vT{init(){return Af||(Af=typeof fetch<"u"?fetch("data:application/wasm;base64,"+N0).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,mf)).then(this._init):WebAssembly.instantiate(Buffer.from(N0,"base64"),mf).then(this._init),Af)}_init(e){ls=e.instance,mf.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!ls)throw new Error("ZSTDDecoder: Await .init() before decoding.");const n=e.byteLength,s=ls.exports.malloc(n);gf.set(e,s),t=t||Number(ls.exports.ZSTD_findDecompressedSize(s,n));const r=ls.exports.malloc(t),a=ls.exports.ZSTD_decompress(r,t,s,n),o=gf.slice(r,r+a);return ls.exports.free(s),ls.exports.free(r),o}}const N0="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDB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ADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZB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ARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEEC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B4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAd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IQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADE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wAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ",CT="display-p3",IT="display-p3-linear",xf=new WeakMap;let bf=0,Ef;class ui extends ci{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new AT,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return this.workerConfig={astcSupported:await e.hasFeatureAsync("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:await e.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await e.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await e.hasFeatureAsync("texture-compression-bc"),bptcSupported:await e.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await e.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-bc"),bptcSupported:e.hasFeature("texture-compression-bptc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},this}init(){if(!this.transcoderPending){const e=new os(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),n=new os(this.manager);n.setPath(this.transcoderPath),n.setResponseType("arraybuffer"),n.setWithCredentials(this.withCredentials);const s=n.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,s]).then(([r,a])=>{const o=ui.BasisWorker.toString(),c=["/* constants */","let _EngineFormat = "+JSON.stringify(ui.EngineFormat),"let _EngineType = "+JSON.stringify(ui.EngineType),"let _TranscoderFormat = "+JSON.stringify(ui.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ui.BasisFormat),"/* basis_transcoder.js */",r,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
-`);this.workerSourceURL=URL.createObjectURL(new Blob([c])),this.transcoderBinary=a,this.workerPool.setWorkerCreator(()=>{const l=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return l.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),l})}),bf>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),bf++}return this.transcoderPending}load(e,t,n,s){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new os(this.manager);r.setResponseType("arraybuffer"),r.setWithCredentials(this.withCredentials),r.load(e,a=>{this.parse(a,t,s)},n,s)}parse(e,t,n){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(xf.has(e))return xf.get(e).promise.then(t).catch(n);this._createTexture(e).then(s=>t?t(s):null).catch(n)}_createTextureFrom(e,t){const{type:n,error:s,data:{faces:r,width:a,height:o,format:c,type:l,dfdFlags:h}}=e;if(n==="error")return Promise.reject(s);let u;if(t.faceCount===6)u=new iw(r,c,l);else{const d=r[0].mipmaps;u=t.layerCount>1?new nw(d,a,o,t.layerCount,c,l):new yl(d,a,o,c,l)}return u.minFilter=r[0].mipmaps.length===1?qt:ri,u.magFilter=qt,u.generateMipmaps=!1,u.needsUpdate=!0,u.colorSpace=D0(t),u.premultiplyAlpha=!!(h&mT),u}async _createTexture(e,t={}){const n=wT(new Uint8Array(e)),s=n.vkFormat===pf&&n.dataFormatDescriptor[0].colorModel===167;if(!(n.vkFormat===yT||s&&!this.workerConfig.astcHDRSupported))return MT(n);const a=t,o=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:a},[e])).then(c=>this._createTextureFrom(c.data,n));return xf.set(e,{promise:o}),o}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),bf--}}ui.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},ui.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},ui.EngineFormat={RGBAFormat:hn,RGBA_ASTC_4x4_Format:lo,RGB_BPTC_UNSIGNED_Format:Oc,RGBA_BPTC_Format:uo,RGBA_ETC2_EAC_Format:Uc,RGBA_PVRTC_4BPPV1_Format:Lc,RGBA_S3TC_DXT5_Format:co,RGB_ETC1_Format:Pc,RGB_ETC2_Format:kc,RGB_PVRTC_4BPPV1_Format:Dc,RGBA_S3TC_DXT1_Format:oo},ui.EngineType={UnsignedByteType:cn,HalfFloatType:kn,FloatType:ln},ui.BasisWorker=function(){let i,e,t;const n=_EngineFormat,s=_EngineType,r=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",function(p){const m=p.data;switch(m.type){case"init":i=m.config,o(m.transcoderBinary);break;case"transcode":e.then(()=>{try{const{faces:g,buffers:A,width:_,height:x,hasAlpha:E,format:S,type:w,dfdFlags:I}=c(m.buffer);self.postMessage({type:"transcode",id:m.id,data:{faces:g,width:_,height:x,hasAlpha:E,format:S,type:w,dfdFlags:I}},A)}catch(g){console.error(g),self.postMessage({type:"error",id:m.id,error:g.message})}});break}});function o(p){e=new Promise(m=>{t={wasmBinary:p,onRuntimeInitialized:m},BASIS(t)}).then(()=>{t.initializeBasis(),t.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function c(p){const m=new t.KTX2File(new Uint8Array(p));function g(){m.close(),m.delete()}if(!m.isValid())throw g(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");let A;if(m.isUASTC())A=a.UASTC;else if(m.isETC1S())A=a.ETC1S;else if(m.isHDR())A=a.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");const _=m.getWidth(),x=m.getHeight(),E=m.getLayers()||1,S=m.getLevels(),w=m.getFaces(),I=m.getHasAlpha(),T=m.getDFDFlags(),{transcoderFormat:C,engineFormat:v,engineType:F}=u(A,_,x,I);if(!_||!x||!S)throw g(),new Error("THREE.KTX2Loader: Invalid texture");if(!m.startTranscoding())throw g(),new Error("THREE.KTX2Loader: .startTranscoding failed");const K=[],q=[];for(let $=0;$<w;$++){const D=[];for(let O=0;O<S;O++){const Y=[];let Q,J;for(let ae=0;ae<E;ae++){const _e=m.getImageLevelInfo(O,ae,$);$===0&&O===0&&ae===0&&(_e.origWidth%4!==0||_e.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),S>1?(Q=_e.origWidth,J=_e.origHeight):(Q=_e.width,J=_e.height);let Me=new Uint8Array(m.getImageTranscodedSizeInBytes(O,ae,0,C));const se=m.transcodeImage(Me,O,ae,$,C,0,-1,-1);if(F===s.HalfFloatType&&(Me=new Uint16Array(Me.buffer,Me.byteOffset,Me.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!se)throw g(),new Error("THREE.KTX2Loader: .transcodeImage failed.");Y.push(Me)}const ee=f(Y);D.push({data:ee,width:Q,height:J}),q.push(ee.buffer)}K.push({mipmaps:D,width:_,height:x,format:v,type:F})}return g(),{faces:K,buffers:q,width:_,height:x,hasAlpha:I,dfdFlags:T,format:v,type:F}}const l=[{if:"astcSupported",basisFormat:[a.UASTC],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],engineType:[s.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],engineType:[s.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.BC1,r.BC3],engineFormat:[n.RGBA_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],engineType:[s.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.ETC1],engineFormat:[n.RGB_ETC1_Format],engineType:[s.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[r.BC6H],engineFormat:[n.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.RGBA32,r.RGBA32],engineFormat:[n.RGBAFormat,n.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[r.RGBA_HALF],engineFormat:[n.RGBAFormat],engineType:[s.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],h={[a.ETC1S]:l.filter(p=>p.basisFormat.includes(a.ETC1S)).sort((p,m)=>p.priorityUASTC-m.priorityUASTC),[a.UASTC]:l.filter(p=>p.basisFormat.includes(a.UASTC)).sort((p,m)=>p.priorityUASTC-m.priorityUASTC),[a.UASTC_HDR]:l.filter(p=>p.basisFormat.includes(a.UASTC_HDR)).sort((p,m)=>p.priorityHDR-m.priorityHDR)};function u(p,m,g,A){const _=h[p];for(let x=0;x<_.length;x++){const E=_[x];if(E.if&&!i[E.if]||!E.basisFormat.includes(p)||A&&E.transcoderFormat.length<2||E.needsPowerOfTwo&&!(d(m)&&d(g)))continue;const S=E.transcoderFormat[A?1:0],w=E.engineFormat[A?1:0],I=E.engineType[0];return{transcoderFormat:S,engineFormat:w,engineType:I}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}function d(p){return p<=2?!0:(p&p-1)===0&&p!==0}function f(p){if(p.length===1)return p[0];let m=0;for(let _=0;_<p.length;_++){const x=p[_];m+=x.byteLength}const g=new Uint8Array(m);let A=0;for(let _=0;_<p.length;_++){const x=p[_];g.set(x,A),A+=x.byteLength}return g}};const ST=new Set([hn,ar,Xi]),yf={[B0]:hn,[I0]:hn,[_0]:hn,[w0]:hn,[M0]:ar,[C0]:ar,[E0]:ar,[y0]:ar,[S0]:Xi,[v0]:Xi,[b0]:Xi,[x0]:Xi,[pf]:lo,[R0]:ho,[T0]:ho},_f={[B0]:ln,[I0]:kn,[_0]:cn,[w0]:cn,[M0]:ln,[C0]:kn,[E0]:cn,[y0]:cn,[S0]:ln,[v0]:kn,[b0]:cn,[x0]:cn,[pf]:kn,[R0]:cn,[T0]:cn};async function MT(i){const{vkFormat:e}=i;if(yf[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let t;i.supercompressionScheme===g0&&(Ef||(Ef=new Promise(async r=>{const a=new vT;await a.init(),r(a)})),t=await Ef);const n=[];for(let r=0;r<i.levels.length;r++){const a=Math.max(1,i.pixelWidth>>r),o=Math.max(1,i.pixelHeight>>r),c=i.pixelDepth?Math.max(1,i.pixelDepth>>r):0,l=i.levels[r];let h;if(i.supercompressionScheme===gT)h=l.levelData;else if(i.supercompressionScheme===g0)h=t.decode(l.levelData,l.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let u;_f[e]===ln?u=new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):_f[e]===kn?u=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):u=h,n.push({data:u,width:a,height:o,depth:c})}let s;if(ST.has(yf[e]))s=i.pixelDepth===0?new ll(n[0].data,i.pixelWidth,i.pixelHeight):new mA(n[0].data,i.pixelWidth,i.pixelHeight,i.pixelDepth);else{if(i.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");s=new yl(n,i.pixelWidth,i.pixelHeight),s.minFilter=n.length===1?qt:ri,s.magFilter=qt}return s.mipmaps=n,s.type=_f[e],s.format=yf[e],s.colorSpace=D0(i),s.needsUpdate=!0,Promise.resolve(s)}function D0(i){const e=i.dataFormatDescriptor[0];return e.colorPrimaries===bT?e.transferFunction===m0?yt:un:e.colorPrimaries===ET?e.transferFunction===m0?CT:IT:(e.colorPrimaries===xT||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),mi)}const Zl="[default]",wf={ASSET_GENERATOR:"assetgenerator"},$l=new fg,L0=`https://unpkg.com/three@0.${Ic}.x`,BT=new fT($l).setDecoderPath(`${L0}/examples/jsm/libs/draco/gltf/`),TT=new ui($l).setTranscoderPath(`${L0}/examples/jsm/libs/basis/`);function P0(i,e){const t=new Set;i.traverse(n=>{if(!n.geometry)return;(Array.isArray(n.material)?n.material:[n.material]).forEach(r=>{r&&!t.has(r.uuid)&&(t.add(r.uuid),e(r))})})}function RT(i){const{state:e,options:t}=i;if(t.preset===wf.ASSET_GENERATOR){const r=new kw;r.name="hemi_light",i.scene.add(r),i.lights.push(r);return}const n=new bg(e.ambientColor,e.ambientIntensity);n.name="ambient_light",i.defaultCamera.add(n);const s=new gd(e.directColor,e.directIntensity);s.position.set(.5,0,.866),s.name="main_light",i.defaultCamera.add(s),i.lights.push(n,s)}function FT(i){i.lights.forEach(e=>e.parent.remove(e)),i.lights.length=0}var di=Uint8Array,Fa=Uint16Array,NT=Int32Array,k0=new di([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),U0=new di([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),DT=new di([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),O0=function(i,e){for(var t=new Fa(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new NT(t[30]),n=1;n<30;++n)for(var r=t[n];r<t[n+1];++r)s[r]=r-t[n]<<5|n;return{b:t,r:s}},Q0=O0(k0,2),G0=Q0.b,LT=Q0.r;G0[28]=258,LT[258]=28;for(var PT=O0(U0,0),kT=PT.b,vf=new Fa(32768),Ot=0;Ot<32768;++Ot){var Ws=(Ot&43690)>>1|(Ot&21845)<<1;Ws=(Ws&52428)>>2|(Ws&13107)<<2,Ws=(Ws&61680)>>4|(Ws&3855)<<4,vf[Ot]=((Ws&65280)>>8|(Ws&255)<<8)>>1}for(var qo=(function(i,e,t){for(var n=i.length,s=0,r=new Fa(e);s<n;++s)i[s]&&++r[i[s]-1];var a=new Fa(e);for(s=1;s<e;++s)a[s]=a[s-1]+r[s-1]<<1;var o;if(t){o=new Fa(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var l=s<<4|i[s],h=e-i[s],u=a[i[s]-1]++<<h,d=u|(1<<h)-1;u<=d;++u)o[vf[u]>>c]=l}else for(o=new Fa(n),s=0;s<n;++s)i[s]&&(o[s]=vf[a[i[s]-1]++]>>15-i[s]);return o}),Ko=new di(288),Ot=0;Ot<144;++Ot)Ko[Ot]=8;for(var Ot=144;Ot<256;++Ot)Ko[Ot]=9;for(var Ot=256;Ot<280;++Ot)Ko[Ot]=7;for(var Ot=280;Ot<288;++Ot)Ko[Ot]=8;for(var H0=new di(32),Ot=0;Ot<32;++Ot)H0[Ot]=5;var UT=qo(Ko,9,1),OT=qo(H0,5,1),Cf=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},Si=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},If=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},QT=function(i){return(i+7)/8|0},GT=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new di(i.subarray(e,t))},HT=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Mi=function(i,e,t){var n=new Error(e||HT[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,Mi),!t)throw n;return n},zT=function(i,e,t,n){var s=i.length,r=0;if(!s||e.f&&!e.l)return t||new di(0);var a=!t,o=a||e.i!=2,c=e.i;a&&(t=new di(s*3));var l=function(Mt){var ft=t.length;if(Mt>ft){var $e=new di(Math.max(ft*2,Mt));$e.set(t),t=$e}},h=e.f||0,u=e.p||0,d=e.b||0,f=e.l,p=e.d,m=e.m,g=e.n,A=s*8;do{if(!f){h=Si(i,u,1);var _=Si(i,u+1,3);if(u+=3,_)if(_==1)f=UT,p=OT,m=9,g=5;else if(_==2){var w=Si(i,u,31)+257,I=Si(i,u+10,15)+4,T=w+Si(i,u+5,31)+1;u+=14;for(var C=new di(T),v=new di(19),F=0;F<I;++F)v[DT[F]]=Si(i,u+F*3,7);u+=I*3;for(var K=Cf(v),q=(1<<K)-1,$=qo(v,K,1),F=0;F<T;){var D=$[Si(i,u,q)];u+=D&15;var x=D>>4;if(x<16)C[F++]=x;else{var O=0,Y=0;for(x==16?(Y=3+Si(i,u,3),u+=2,O=C[F-1]):x==17?(Y=3+Si(i,u,7),u+=3):x==18&&(Y=11+Si(i,u,127),u+=7);Y--;)C[F++]=O}}var Q=C.subarray(0,w),J=C.subarray(w);m=Cf(Q),g=Cf(J),f=qo(Q,m,1),p=qo(J,g,1)}else Mi(1);else{var x=QT(u)+4,E=i[x-4]|i[x-3]<<8,S=x+E;if(S>s){c&&Mi(0);break}o&&l(d+E),t.set(i.subarray(x,S),d),e.b=d+=E,e.p=u=S*8,e.f=h;continue}if(u>A){c&&Mi(0);break}}o&&l(d+131072);for(var ee=(1<<m)-1,ae=(1<<g)-1,_e=u;;_e=u){var O=f[If(i,u)&ee],Me=O>>4;if(u+=O&15,u>A){c&&Mi(0);break}if(O||Mi(2),Me<256)t[d++]=Me;else if(Me==256){_e=u,f=null;break}else{var se=Me-254;if(Me>264){var F=Me-257,me=k0[F];se=Si(i,u,(1<<me)-1)+G0[F],u+=me}var xe=p[If(i,u)&ae],be=xe>>4;xe||Mi(3),u+=xe&15;var J=kT[be];if(be>3){var me=U0[be];J+=If(i,u)&(1<<me)-1,u+=me}if(u>A){c&&Mi(0);break}o&&l(d+131072);var Ue=d+se;if(d<J){var et=r-J,He=Math.min(J,Ue);for(et+d<0&&Mi(3);d<He;++d)t[d]=n[et+d]}for(;d<Ue;++d)t[d]=t[d-J]}}e.l=f,e.p=_e,e.b=d,e.f=h,f&&(h=1,e.m=m,e.d=p,e.n=g)}while(!h);return d!=t.length&&a?GT(t,0,d):t.subarray(0,d)},VT=new di(0),WT=function(i,e){return((i[0]&15)!=8||i[0]>>4>7||(i[0]<<8|i[1])%31)&&Mi(6,"invalid zlib data"),(i[1]>>5&1)==1&&Mi(6,"invalid zlib data: "+(i[1]&32?"need":"unexpected")+" dictionary"),(i[1]>>3&4)+2};function jo(i,e){return zT(i.subarray(WT(i),-4),{i:2},e,e)}var qT=typeof TextDecoder<"u"&&new TextDecoder,KT=0;try{qT.decode(VT,{stream:!0}),KT=1}catch{}class jT extends Pw{constructor(e){super(e),this.type=kn}parse(e){const C=Math.pow(2.7182818,2.2);function v(b,B){let k=0;for(let R=0;R<65536;++R)(R==0||b[R>>3]&1<<(R&7))&&(B[k++]=R);const y=k-1;for(;k<65536;)B[k++]=0;return y}function F(b){for(let B=0;B<16384;B++)b[B]={},b[B].len=0,b[B].lit=0,b[B].p=null}const K={l:0,c:0,lc:0};function q(b,B,k,y,R){for(;k<b;)B=B<<8|Te(y,R),k+=8;k-=b,K.l=B>>k&(1<<b)-1,K.c=B,K.lc=k}const $=new Array(59);function D(b){for(let k=0;k<=58;++k)$[k]=0;for(let k=0;k<65537;++k)$[b[k]]+=1;let B=0;for(let k=58;k>0;--k){const y=B+$[k]>>1;$[k]=B,B=y}for(let k=0;k<65537;++k){const y=b[k];y>0&&(b[k]=y|$[y]++<<6)}}function O(b,B,k,y,R,N){const U=B;let P=0,z=0;for(;y<=R;y++){if(U.value-B.value>k)return!1;q(6,P,z,b,U);const j=K.l;if(P=K.c,z=K.lc,N[y]=j,j==63){if(U.value-B.value>k)throw new Error("Something wrong with hufUnpackEncTable");q(8,P,z,b,U);let X=K.l+6;if(P=K.c,z=K.lc,y+X>R+1)throw new Error("Something wrong with hufUnpackEncTable");for(;X--;)N[y++]=0;y--}else if(j>=59){let X=j-59+2;if(y+X>R+1)throw new Error("Something wrong with hufUnpackEncTable");for(;X--;)N[y++]=0;y--}}D(N)}function Y(b){return b&63}function Q(b){return b>>6}function J(b,B,k,y){for(;B<=k;B++){const R=Q(b[B]),N=Y(b[B]);if(R>>N)throw new Error("Invalid table entry");if(N>14){const U=y[R>>N-14];if(U.len)throw new Error("Invalid table entry");if(U.lit++,U.p){const P=U.p;U.p=new Array(U.lit);for(let z=0;z<U.lit-1;++z)U.p[z]=P[z]}else U.p=new Array(1);U.p[U.lit-1]=B}else if(N){let U=0;for(let P=1<<14-N;P>0;P--){const z=y[(R<<14-N)+U];if(z.len||z.p)throw new Error("Invalid table entry");z.len=N,z.lit=B,U++}}}return!0}const ee={c:0,lc:0};function ae(b,B,k,y){b=b<<8|Te(k,y),B+=8,ee.c=b,ee.lc=B}const _e={c:0,lc:0};function Me(b,B,k,y,R,N,U,P,z){if(b==B){y<8&&(ae(k,y,R,N),k=ee.c,y=ee.lc),y-=8;let j=k>>y;if(j=new Uint8Array([j])[0],P.value+j>z)return!1;const X=U[P.value-1];for(;j-- >0;)U[P.value++]=X}else if(P.value<z)U[P.value++]=b;else return!1;_e.c=k,_e.lc=y}function se(b){return b&65535}function me(b){const B=se(b);return B>32767?B-65536:B}const xe={a:0,b:0};function be(b,B){const k=me(b),R=me(B),N=k+(R&1)+(R>>1),U=N,P=N-R;xe.a=U,xe.b=P}function Ue(b,B){const k=se(b),y=se(B),R=k-(y>>1)&65535,N=y+R-32768&65535;xe.a=N,xe.b=R}function et(b,B,k,y,R,N,U){const P=U<16384,z=k>R?R:k;let j=1,X,ie;for(;j<=z;)j<<=1;for(j>>=1,X=j,j>>=1;j>=1;){ie=0;const he=ie+N*(R-X),ce=N*j,fe=N*X,ge=y*j,ye=y*X;let Pe,je,Ve,Le;for(;ie<=he;ie+=fe){let rt=ie;const ke=ie+y*(k-X);for(;rt<=ke;rt+=ye){const It=rt+ge,mn=rt+ce,vt=mn+ge;P?(be(b[rt+B],b[mn+B]),Pe=xe.a,Ve=xe.b,be(b[It+B],b[vt+B]),je=xe.a,Le=xe.b,be(Pe,je),b[rt+B]=xe.a,b[It+B]=xe.b,be(Ve,Le),b[mn+B]=xe.a,b[vt+B]=xe.b):(Ue(b[rt+B],b[mn+B]),Pe=xe.a,Ve=xe.b,Ue(b[It+B],b[vt+B]),je=xe.a,Le=xe.b,Ue(Pe,je),b[rt+B]=xe.a,b[It+B]=xe.b,Ue(Ve,Le),b[mn+B]=xe.a,b[vt+B]=xe.b)}if(k&j){const It=rt+ce;P?be(b[rt+B],b[It+B]):Ue(b[rt+B],b[It+B]),Pe=xe.a,b[It+B]=xe.b,b[rt+B]=Pe}}if(R&j){let rt=ie;const ke=ie+y*(k-X);for(;rt<=ke;rt+=ye){const It=rt+ge;P?be(b[rt+B],b[It+B]):Ue(b[rt+B],b[It+B]),Pe=xe.a,b[It+B]=xe.b,b[rt+B]=Pe}}X=j,j>>=1}return ie}function He(b,B,k,y,R,N,U,P,z){let j=0,X=0;const ie=U,he=Math.trunc(y.value+(R+7)/8);for(;y.value<he;)for(ae(j,X,k,y),j=ee.c,X=ee.lc;X>=14;){const fe=j>>X-14&16383,ge=B[fe];if(ge.len)X-=ge.len,Me(ge.lit,N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;else{if(!ge.p)throw new Error("hufDecode issues");let ye;for(ye=0;ye<ge.lit;ye++){const Pe=Y(b[ge.p[ye]]);for(;X<Pe&&y.value<he;)ae(j,X,k,y),j=ee.c,X=ee.lc;if(X>=Pe&&Q(b[ge.p[ye]])==(j>>X-Pe&(1<<Pe)-1)){X-=Pe,Me(ge.p[ye],N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;break}}if(ye==ge.lit)throw new Error("hufDecode issues")}}const ce=8-R&7;for(j>>=ce,X-=ce;X>0;){const fe=B[j<<14-X&16383];if(fe.len)X-=fe.len,Me(fe.lit,N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;else throw new Error("hufDecode issues")}return!0}function Mt(b,B,k,y,R,N){const U={value:0},P=k.value,z=Ge(B,k),j=Ge(B,k);k.value+=4;const X=Ge(B,k);if(k.value+=4,z<0||z>=65537||j<0||j>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const ie=new Array(65537),he=new Array(16384);F(he);const ce=y-(k.value-P);if(O(b,k,ce,z,j,ie),X>8*(y-(k.value-P)))throw new Error("Something wrong with hufUncompress");J(ie,z,j,he),He(ie,he,b,k,X,j,N,R,U)}function ft(b,B,k){for(let y=0;y<k;++y)B[y]=b[B[y]]}function $e(b){for(let B=1;B<b.length;B++){const k=b[B-1]+b[B]-128;b[B]=k}}function H(b,B){let k=0,y=Math.floor((b.length+1)/2),R=0;const N=b.length-1;for(;!(R>N||(B[R++]=b[k++],R>N));)B[R++]=b[y++]}function wn(b){let B=b.byteLength;const k=new Array;let y=0;const R=new DataView(b);for(;B>0;){const N=R.getInt8(y++);if(N<0){const U=-N;B-=U+1;for(let P=0;P<U;P++)k.push(R.getUint8(y++))}else{const U=N;B-=2;const P=R.getUint8(y++);for(let z=0;z<U+1;z++)k.push(P)}}return k}function pt(b,B,k,y,R,N){let U=new DataView(N.buffer);const P=k[b.idx[0]].width,z=k[b.idx[0]].height,j=3,X=Math.floor(P/8),ie=Math.ceil(P/8),he=Math.ceil(z/8),ce=P-(ie-1)*8,fe=z-(he-1)*8,ge={value:0},ye=new Array(j),Pe=new Array(j),je=new Array(j),Ve=new Array(j),Le=new Array(j);for(let ke=0;ke<j;++ke)Le[ke]=B[b.idx[ke]],ye[ke]=ke<1?0:ye[ke-1]+ie*he,Pe[ke]=new Float32Array(64),je[ke]=new Uint16Array(64),Ve[ke]=new Uint16Array(ie*64);for(let ke=0;ke<he;++ke){let It=8;ke==he-1&&(It=fe);let mn=8;for(let Et=0;Et<ie;++Et){Et==ie-1&&(mn=ce);for(let Xe=0;Xe<j;++Xe)je[Xe].fill(0),je[Xe][0]=R[ye[Xe]++],mt(ge,y,je[Xe]),We(je[Xe],Pe[Xe]),Dt(Pe[Xe]);ze(Pe);for(let Xe=0;Xe<j;++Xe)L(Pe[Xe],Ve[Xe],Et*64)}let vt=0;for(let Et=0;Et<j;++Et){const Xe=k[b.idx[Et]].type;for(let Xt=8*ke;Xt<8*ke+It;++Xt){vt=Le[Et][Xt];for(let Cn=0;Cn<X;++Cn){const Ut=Cn*64+(Xt&7)*8;U.setUint16(vt+0*Xe,Ve[Et][Ut+0],!0),U.setUint16(vt+2*Xe,Ve[Et][Ut+1],!0),U.setUint16(vt+4*Xe,Ve[Et][Ut+2],!0),U.setUint16(vt+6*Xe,Ve[Et][Ut+3],!0),U.setUint16(vt+8*Xe,Ve[Et][Ut+4],!0),U.setUint16(vt+10*Xe,Ve[Et][Ut+5],!0),U.setUint16(vt+12*Xe,Ve[Et][Ut+6],!0),U.setUint16(vt+14*Xe,Ve[Et][Ut+7],!0),vt+=16*Xe}}if(X!=ie)for(let Xt=8*ke;Xt<8*ke+It;++Xt){const Cn=Le[Et][Xt]+8*X*2*Xe,Ut=X*64+(Xt&7)*8;for(let xn=0;xn<mn;++xn)U.setUint16(Cn+xn*2*Xe,Ve[Et][Ut+xn],!0)}}}const rt=new Uint16Array(P);U=new DataView(N.buffer);for(let ke=0;ke<j;++ke){k[b.idx[ke]].decoded=!0;const It=k[b.idx[ke]].type;if(k[ke].type==2)for(let mn=0;mn<z;++mn){const vt=Le[ke][mn];for(let Et=0;Et<P;++Et)rt[Et]=U.getUint16(vt+Et*2*It,!0);for(let Et=0;Et<P;++Et)U.setFloat32(vt+Et*2*It,ne(rt[Et]),!0)}}}function mt(b,B,k){let y,R=1;for(;R<64;)y=B[b.value],y==65280?R=64:y>>8==255?R+=y&255:(k[R]=y,R++),b.value++}function We(b,B){B[0]=ne(b[0]),B[1]=ne(b[1]),B[2]=ne(b[5]),B[3]=ne(b[6]),B[4]=ne(b[14]),B[5]=ne(b[15]),B[6]=ne(b[27]),B[7]=ne(b[28]),B[8]=ne(b[2]),B[9]=ne(b[4]),B[10]=ne(b[7]),B[11]=ne(b[13]),B[12]=ne(b[16]),B[13]=ne(b[26]),B[14]=ne(b[29]),B[15]=ne(b[42]),B[16]=ne(b[3]),B[17]=ne(b[8]),B[18]=ne(b[12]),B[19]=ne(b[17]),B[20]=ne(b[25]),B[21]=ne(b[30]),B[22]=ne(b[41]),B[23]=ne(b[43]),B[24]=ne(b[9]),B[25]=ne(b[11]),B[26]=ne(b[18]),B[27]=ne(b[24]),B[28]=ne(b[31]),B[29]=ne(b[40]),B[30]=ne(b[44]),B[31]=ne(b[53]),B[32]=ne(b[10]),B[33]=ne(b[19]),B[34]=ne(b[23]),B[35]=ne(b[32]),B[36]=ne(b[39]),B[37]=ne(b[45]),B[38]=ne(b[52]),B[39]=ne(b[54]),B[40]=ne(b[20]),B[41]=ne(b[22]),B[42]=ne(b[33]),B[43]=ne(b[38]),B[44]=ne(b[46]),B[45]=ne(b[51]),B[46]=ne(b[55]),B[47]=ne(b[60]),B[48]=ne(b[21]),B[49]=ne(b[34]),B[50]=ne(b[37]),B[51]=ne(b[47]),B[52]=ne(b[50]),B[53]=ne(b[56]),B[54]=ne(b[59]),B[55]=ne(b[61]),B[56]=ne(b[35]),B[57]=ne(b[36]),B[58]=ne(b[48]),B[59]=ne(b[49]),B[60]=ne(b[57]),B[61]=ne(b[58]),B[62]=ne(b[62]),B[63]=ne(b[63])}function Dt(b){const B=.5*Math.cos(.7853975),k=.5*Math.cos(3.14159/16),y=.5*Math.cos(3.14159/8),R=.5*Math.cos(3*3.14159/16),N=.5*Math.cos(5*3.14159/16),U=.5*Math.cos(3*3.14159/8),P=.5*Math.cos(7*3.14159/16),z=new Array(4),j=new Array(4),X=new Array(4),ie=new Array(4);for(let he=0;he<8;++he){const ce=he*8;z[0]=y*b[ce+2],z[1]=U*b[ce+2],z[2]=y*b[ce+6],z[3]=U*b[ce+6],j[0]=k*b[ce+1]+R*b[ce+3]+N*b[ce+5]+P*b[ce+7],j[1]=R*b[ce+1]-P*b[ce+3]-k*b[ce+5]-N*b[ce+7],j[2]=N*b[ce+1]-k*b[ce+3]+P*b[ce+5]+R*b[ce+7],j[3]=P*b[ce+1]-N*b[ce+3]+R*b[ce+5]-k*b[ce+7],X[0]=B*(b[ce+0]+b[ce+4]),X[3]=B*(b[ce+0]-b[ce+4]),X[1]=z[0]+z[3],X[2]=z[1]-z[2],ie[0]=X[0]+X[1],ie[1]=X[3]+X[2],ie[2]=X[3]-X[2],ie[3]=X[0]-X[1],b[ce+0]=ie[0]+j[0],b[ce+1]=ie[1]+j[1],b[ce+2]=ie[2]+j[2],b[ce+3]=ie[3]+j[3],b[ce+4]=ie[3]-j[3],b[ce+5]=ie[2]-j[2],b[ce+6]=ie[1]-j[1],b[ce+7]=ie[0]-j[0]}for(let he=0;he<8;++he)z[0]=y*b[16+he],z[1]=U*b[16+he],z[2]=y*b[48+he],z[3]=U*b[48+he],j[0]=k*b[8+he]+R*b[24+he]+N*b[40+he]+P*b[56+he],j[1]=R*b[8+he]-P*b[24+he]-k*b[40+he]-N*b[56+he],j[2]=N*b[8+he]-k*b[24+he]+P*b[40+he]+R*b[56+he],j[3]=P*b[8+he]-N*b[24+he]+R*b[40+he]-k*b[56+he],X[0]=B*(b[he]+b[32+he]),X[3]=B*(b[he]-b[32+he]),X[1]=z[0]+z[3],X[2]=z[1]-z[2],ie[0]=X[0]+X[1],ie[1]=X[3]+X[2],ie[2]=X[3]-X[2],ie[3]=X[0]-X[1],b[0+he]=ie[0]+j[0],b[8+he]=ie[1]+j[1],b[16+he]=ie[2]+j[2],b[24+he]=ie[3]+j[3],b[32+he]=ie[3]-j[3],b[40+he]=ie[2]-j[2],b[48+he]=ie[1]-j[1],b[56+he]=ie[0]-j[0]}function ze(b){for(let B=0;B<64;++B){const k=b[0][B],y=b[1][B],R=b[2][B];b[0][B]=k+1.5747*R,b[1][B]=k-.1873*y-.4682*R,b[2][B]=k+1.8556*y}}function L(b,B,k){for(let y=0;y<64;++y)B[k+y]=BA.toHalfFloat(M(b[y]))}function M(b){return b<=1?Math.sign(b)*Math.pow(Math.abs(b),2.2):Math.sign(b)*Math.pow(C,Math.abs(b)-1)}function Z(b){return new DataView(b.array.buffer,b.offset.value,b.size)}function le(b){const B=b.viewer.buffer.slice(b.offset.value,b.offset.value+b.size),k=new Uint8Array(wn(B)),y=new Uint8Array(k.length);return $e(k),H(k,y),new DataView(y.buffer)}function Ae(b){const B=b.array.slice(b.offset.value,b.offset.value+b.size),k=jo(B),y=new Uint8Array(k.length);return $e(k),H(k,y),new DataView(y.buffer)}function oe(b){const B=b.viewer,k={value:b.offset.value},y=new Uint16Array(b.columns*b.lines*(b.inputChannels.length*b.type)),R=new Uint8Array(8192);let N=0;const U=new Array(b.inputChannels.length);for(let fe=0,ge=b.inputChannels.length;fe<ge;fe++)U[fe]={},U[fe].start=N,U[fe].end=U[fe].start,U[fe].nx=b.columns,U[fe].ny=b.lines,U[fe].size=b.type,N+=U[fe].nx*U[fe].ny*U[fe].size;const P=re(B,k),z=re(B,k);if(z>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(P<=z)for(let fe=0;fe<z-P+1;fe++)R[fe+P]=nt(B,k);const j=new Uint16Array(65536),X=v(R,j),ie=Ge(B,k);Mt(b.array,B,k,ie,y,N);for(let fe=0;fe<b.inputChannels.length;++fe){const ge=U[fe];for(let ye=0;ye<U[fe].size;++ye)et(y,ge.start+ye,ge.nx,ge.size,ge.ny,ge.nx*ge.size,X)}ft(j,y,N);let he=0;const ce=new Uint8Array(y.buffer.byteLength);for(let fe=0;fe<b.lines;fe++)for(let ge=0;ge<b.inputChannels.length;ge++){const ye=U[ge],Pe=ye.nx*ye.size,je=new Uint8Array(y.buffer,ye.end*2,Pe*2);ce.set(je,he),he+=Pe*2,ye.end+=Pe}return new DataView(ce.buffer)}function Qe(b){const B=b.array.slice(b.offset.value,b.offset.value+b.size),k=jo(B),y=b.inputChannels.length*b.lines*b.columns*b.totalBytes,R=new ArrayBuffer(y),N=new DataView(R);let U=0,P=0;const z=new Array(4);for(let j=0;j<b.lines;j++)for(let X=0;X<b.inputChannels.length;X++){let ie=0;switch(b.inputChannels[X].pixelType){case 1:z[0]=U,z[1]=z[0]+b.columns,U=z[1]+b.columns;for(let ce=0;ce<b.columns;++ce){const fe=k[z[0]++]<<8|k[z[1]++];ie+=fe,N.setUint16(P,ie,!0),P+=2}break;case 2:z[0]=U,z[1]=z[0]+b.columns,z[2]=z[1]+b.columns,U=z[2]+b.columns;for(let ce=0;ce<b.columns;++ce){const fe=k[z[0]++]<<24|k[z[1]++]<<16|k[z[2]++]<<8;ie+=fe,N.setUint32(P,ie,!0),P+=4}break}}return N}function ve(b){const B=b.viewer,k={value:b.offset.value},y=new Uint8Array(b.columns*b.lines*(b.inputChannels.length*b.type*2)),R={version:Ke(B,k),unknownUncompressedSize:Ke(B,k),unknownCompressedSize:Ke(B,k),acCompressedSize:Ke(B,k),dcCompressedSize:Ke(B,k),rleCompressedSize:Ke(B,k),rleUncompressedSize:Ke(B,k),rleRawSize:Ke(B,k),totalAcUncompressedCount:Ke(B,k),totalDcUncompressedCount:Ke(B,k),acCompression:Ke(B,k)};if(R.version<2)throw new Error("EXRLoader.parse: "+vs.compression+" version "+R.version+" is unsupported");const N=new Array;let U=re(B,k)-2;for(;U>0;){const ge=qe(B.buffer,k),ye=nt(B,k),Pe=ye>>2&3,je=(ye>>4)-1,Ve=new Int8Array([je])[0],Le=nt(B,k);N.push({name:ge,index:Ve,type:Le,compression:Pe}),U-=ge.length+3}const P=vs.channels,z=new Array(b.inputChannels.length);for(let ge=0;ge<b.inputChannels.length;++ge){const ye=z[ge]={},Pe=P[ge];ye.name=Pe.name,ye.compression=0,ye.decoded=!1,ye.type=Pe.pixelType,ye.pLinear=Pe.pLinear,ye.width=b.columns,ye.height=b.lines}const j={idx:new Array(3)};for(let ge=0;ge<b.inputChannels.length;++ge){const ye=z[ge];for(let Pe=0;Pe<N.length;++Pe){const je=N[Pe];ye.name==je.name&&(ye.compression=je.compression,je.index>=0&&(j.idx[je.index]=ge),ye.offset=ge)}}let X,ie,he;if(R.acCompressedSize>0)switch(R.acCompression){case 0:X=new Uint16Array(R.totalAcUncompressedCount),Mt(b.array,B,k,R.acCompressedSize,X,R.totalAcUncompressedCount);break;case 1:const ge=b.array.slice(k.value,k.value+R.totalAcUncompressedCount),ye=jo(ge);X=new Uint16Array(ye.buffer),k.value+=R.totalAcUncompressedCount;break}if(R.dcCompressedSize>0){const ge={array:b.array,offset:k,size:R.dcCompressedSize};ie=new Uint16Array(Ae(ge).buffer),k.value+=R.dcCompressedSize}if(R.rleRawSize>0){const ge=b.array.slice(k.value,k.value+R.rleCompressedSize),ye=jo(ge);he=wn(ye.buffer),k.value+=R.rleCompressedSize}let ce=0;const fe=new Array(z.length);for(let ge=0;ge<fe.length;++ge)fe[ge]=new Array;for(let ge=0;ge<b.lines;++ge)for(let ye=0;ye<z.length;++ye)fe[ye].push(ce),ce+=z[ye].width*b.type*2;pt(j,fe,z,X,ie,y);for(let ge=0;ge<z.length;++ge){const ye=z[ge];if(!ye.decoded)switch(ye.compression){case 2:let Pe=0,je=0;for(let Ve=0;Ve<b.lines;++Ve){let Le=fe[ge][Pe];for(let rt=0;rt<ye.width;++rt){for(let ke=0;ke<2*ye.type;++ke)y[Le++]=he[je+ke*ye.width*ye.height];je++}Pe++}break;default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(y.buffer)}function qe(b,B){const k=new Uint8Array(b);let y=0;for(;k[B.value+y]!=0;)y+=1;const R=new TextDecoder().decode(k.slice(B.value,B.value+y));return B.value=B.value+y+1,R}function Ze(b,B,k){const y=new TextDecoder().decode(new Uint8Array(b).slice(B.value,B.value+k));return B.value=B.value+k,y}function Ee(b,B){const k=Oe(b,B),y=Ge(b,B);return[k,y]}function De(b,B){const k=Ge(b,B),y=Ge(b,B);return[k,y]}function Oe(b,B){const k=b.getInt32(B.value,!0);return B.value=B.value+4,k}function Ge(b,B){const k=b.getUint32(B.value,!0);return B.value=B.value+4,k}function Te(b,B){const k=b[B.value];return B.value=B.value+1,k}function nt(b,B){const k=b.getUint8(B.value);return B.value=B.value+1,k}const Ke=function(b,B){let k;return"getBigInt64"in DataView.prototype?k=Number(b.getBigInt64(B.value,!0)):k=b.getUint32(B.value+4,!0)+Number(b.getUint32(B.value,!0)<<32),B.value+=8,k};function it(b,B){const k=b.getFloat32(B.value,!0);return B.value+=4,k}function W(b,B){return BA.toHalfFloat(it(b,B))}function ne(b){const B=(b&31744)>>10,k=b&1023;return(b>>15?-1:1)*(B?B===31?k?NaN:1/0:Math.pow(2,B-15)*(1+k/1024):6103515625e-14*(k/1024))}function re(b,B){const k=b.getUint16(B.value,!0);return B.value+=2,k}function de(b,B){return ne(re(b,B))}function Se(b,B,k,y){const R=k.value,N=[];for(;k.value<R+y-1;){const U=qe(B,k),P=Oe(b,k),z=nt(b,k);k.value+=3;const j=Oe(b,k),X=Oe(b,k);N.push({name:U,pixelType:P,pLinear:z,xSampling:j,ySampling:X})}return k.value+=1,N}function Ie(b,B){const k=it(b,B),y=it(b,B),R=it(b,B),N=it(b,B),U=it(b,B),P=it(b,B),z=it(b,B),j=it(b,B);return{redX:k,redY:y,greenX:R,greenY:N,blueX:U,blueY:P,whiteX:z,whiteY:j}}function st(b,B){const k=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],y=nt(b,B);return k[y]}function Ht(b,B){const k=Oe(b,B),y=Oe(b,B),R=Oe(b,B),N=Oe(b,B);return{xMin:k,yMin:y,xMax:R,yMax:N}}function vn(b,B){const k=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],y=nt(b,B);return k[y]}function Ct(b,B){const k=["ENVMAP_LATLONG","ENVMAP_CUBE"],y=nt(b,B);return k[y]}function si(b,B){const k=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],y=["ROUND_DOWN","ROUND_UP"],R=Ge(b,B),N=Ge(b,B),U=nt(b,B);return{xSize:R,ySize:N,levelMode:k[U&15],roundingMode:y[U>>4]}}function Li(b,B){const k=it(b,B),y=it(b,B);return[k,y]}function Gh(b,B){const k=it(b,B),y=it(b,B),R=it(b,B);return[k,y,R]}function Hh(b,B,k,y,R){if(y==="string"||y==="stringvector"||y==="iccProfile")return Ze(B,k,R);if(y==="chlist")return Se(b,B,k,R);if(y==="chromaticities")return Ie(b,k);if(y==="compression")return st(b,k);if(y==="box2i")return Ht(b,k);if(y==="envmap")return Ct(b,k);if(y==="tiledesc")return si(b,k);if(y==="lineOrder")return vn(b,k);if(y==="float")return it(b,k);if(y==="v2f")return Li(b,k);if(y==="v3f")return Gh(b,k);if(y==="int")return Oe(b,k);if(y==="rational")return Ee(b,k);if(y==="timecode")return De(b,k);if(y==="preview")return k.value+=R,"skipped";k.value+=R}function ws(b,B){const k=Math.log2(b);return B=="ROUND_DOWN"?Math.floor(k):Math.ceil(k)}function _c(b,B,k){let y=0;switch(b.levelMode){case"ONE_LEVEL":y=1;break;case"MIPMAP_LEVELS":y=ws(Math.max(B,k),b.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return y}function wc(b,B,k,y){const R=new Array(b);for(let N=0;N<b;N++){const U=1<<N;let P=B/U|0;y=="ROUND_UP"&&P*U<B&&(P+=1);const z=Math.max(P,1);R[N]=(z+k-1)/k|0}return R}function zh(){const b=this,B=b.offset,k={value:0};for(let y=0;y<b.tileCount;y++){const R=Oe(b.viewer,B),N=Oe(b.viewer,B);B.value+=8,b.size=Ge(b.viewer,B);const U=R*b.blockWidth,P=N*b.blockHeight;b.columns=U+b.blockWidth>b.width?b.width-U:b.blockWidth,b.lines=P+b.blockHeight>b.height?b.height-P:b.blockHeight;const z=b.columns*b.totalBytes,X=b.size<b.lines*z?b.uncompress(b):Z(b);B.value+=b.size;for(let ie=0;ie<b.lines;ie++){const he=ie*b.columns*b.totalBytes;for(let ce=0;ce<b.inputChannels.length;ce++){const fe=vs.channels[ce].name,ge=b.channelByteOffsets[fe]*b.columns,ye=b.decodeChannels[fe];if(ye===void 0)continue;k.value=he+ge;const Pe=(b.height-(1+P+ie))*b.outLineWidth;for(let je=0;je<b.columns;je++){const Ve=Pe+(je+U)*b.outputChannels+ye;b.byteArray[Ve]=b.getter(X,k)}}}}}function eo(){const b=this,B=b.offset,k={value:0};for(let y=0;y<b.height/b.blockHeight;y++){const R=Oe(b.viewer,B)-vs.dataWindow.yMin;b.size=Ge(b.viewer,B),b.lines=R+b.blockHeight>b.height?b.height-R:b.blockHeight;const N=b.columns*b.totalBytes,P=b.size<b.lines*N?b.uncompress(b):Z(b);B.value+=b.size;for(let z=0;z<b.blockHeight;z++){const j=y*b.blockHeight,X=z+b.scanOrder(j);if(X>=b.height)continue;const ie=z*N,he=(b.height-1-X)*b.outLineWidth;for(let ce=0;ce<b.inputChannels.length;ce++){const fe=vs.channels[ce].name,ge=b.channelByteOffsets[fe]*b.columns,ye=b.decodeChannels[fe];if(ye!==void 0){k.value=ie+ge;for(let Pe=0;Pe<b.columns;Pe++){const je=he+Pe*b.outputChannels+ye;b.byteArray[je]=b.getter(P,k)}}}}}}function Vh(b,B,k){const y={};if(b.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");y.version=b.getUint8(4);const R=b.getUint8(5);y.spec={singleTile:!!(R&2),longName:!!(R&4),deepFormat:!!(R&8),multiPart:!!(R&16)},k.value=8;let N=!0;for(;N;){const U=qe(B,k);if(U==="")N=!1;else{const P=qe(B,k),z=Ge(b,k),j=Hh(b,B,k,P,z);j===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${P}'.`):y[U]=j}}if((R&-7)!=0)throw console.error("THREE.EXRHeader:",y),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return y}function to(b,B,k,y,R){const N={size:0,viewer:B,array:k,offset:y,width:b.dataWindow.xMax-b.dataWindow.xMin+1,height:b.dataWindow.yMax-b.dataWindow.yMin+1,inputChannels:b.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:un};switch(b.compression){case"NO_COMPRESSION":N.blockHeight=1,N.uncompress=Z;break;case"RLE_COMPRESSION":N.blockHeight=1,N.uncompress=le;break;case"ZIPS_COMPRESSION":N.blockHeight=1,N.uncompress=Ae;break;case"ZIP_COMPRESSION":N.blockHeight=16,N.uncompress=Ae;break;case"PIZ_COMPRESSION":N.blockHeight=32,N.uncompress=oe;break;case"PXR24_COMPRESSION":N.blockHeight=16,N.uncompress=Qe;break;case"DWAA_COMPRESSION":N.blockHeight=32,N.uncompress=ve;break;case"DWAB_COMPRESSION":N.blockHeight=256,N.uncompress=ve;break;default:throw new Error("EXRLoader.parse: "+b.compression+" is unsupported")}const U={};for(const X of b.channels)switch(X.name){case"Y":case"R":case"G":case"B":case"A":U[X.name]=!0,N.type=X.pixelType}let P=!1;if(U.R&&U.G&&U.B)P=!U.A,N.outputChannels=4,N.decodeChannels={R:0,G:1,B:2,A:3};else if(U.Y)N.outputChannels=1,N.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(N.type==1)switch(R){case ln:N.getter=de;break;case kn:N.getter=re;break}else if(N.type==2)switch(R){case ln:N.getter=it;break;case kn:N.getter=W}else throw new Error("EXRLoader.parse: unsupported pixelType "+N.type+" for "+b.compression+".");N.columns=N.width;const z=N.width*N.height*N.outputChannels;switch(R){case ln:N.byteArray=new Float32Array(z),P&&N.byteArray.fill(1,0,z);break;case kn:N.byteArray=new Uint16Array(z),P&&N.byteArray.fill(15360,0,z);break;default:console.error("THREE.EXRLoader: unsupported type: ",R);break}let j=0;for(const X of b.channels)N.decodeChannels[X.name]!==void 0&&(N.channelByteOffsets[X.name]=j),j+=X.pixelType*2;if(N.totalBytes=j,N.outLineWidth=N.width*N.outputChannels,b.lineOrder==="INCREASING_Y"?N.scanOrder=X=>X:N.scanOrder=X=>N.height-1-X,N.outputChannels==4?(N.format=hn,N.colorSpace=un):(N.format=Xi,N.colorSpace=mi),b.spec.singleTile){N.blockHeight=b.tiles.ySize,N.blockWidth=b.tiles.xSize;const X=_c(b.tiles,N.width,N.height),ie=wc(X,N.width,b.tiles.xSize,b.tiles.roundingMode),he=wc(X,N.height,b.tiles.ySize,b.tiles.roundingMode);N.tileCount=ie[0]*he[0];for(let ce=0;ce<X;ce++)for(let fe=0;fe<he[ce];fe++)for(let ge=0;ge<ie[ce];ge++)Ke(B,y);N.decode=zh.bind(N)}else{N.blockWidth=N.width;const X=Math.ceil(N.height/N.blockHeight);for(let ie=0;ie<X;ie++)Ke(B,y);N.decode=eo.bind(N)}return N}const vc={value:0},Cc=new DataView(e),Hp=new Uint8Array(e),vs=Vh(Cc,e,vc),tr=to(vs,Cc,Hp,vc,this.type);return tr.decode(),{header:vs,width:tr.width,height:tr.height,data:tr.byteArray,format:tr.format,colorSpace:tr.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,s){function r(a,o){a.colorSpace=o.colorSpace,a.minFilter=qt,a.magFilter=qt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,o)}return super.load(e,r,n,s)}}function XT(i,e){const{id:t,path:n}=e;return t==="neutral"?Promise.resolve({envMap:i.neutralEnvironment}):t===""?Promise.resolve({envMap:null}):new Promise((s,r)=>{new jT().load(n,a=>{const o=i.pmremGenerator.fromEquirectangular(a).texture;a.dispose(),i._loadedEnvironment&&i._loadedEnvironment!==o&&i._loadedEnvironment.dispose(),i._loadedEnvironment=o,s({envMap:o})},void 0,r)})}function YT(i){i.renderer.render(i.scene,i.activeCamera),i.renderer.domElement.toBlob(e=>{if(!e)return;const t=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),n=URL.createObjectURL(e),s=document.createElement("a");s.download=`3d-screenshot-${t}.png`,s.href=n,s.click(),URL.revokeObjectURL(n)},"image/png"),JT(i)}function JT(i){const e=document.createElement("div");e.className="screenshot-flash",i.el.appendChild(e),e.addEventListener("animationend",()=>e.remove())}function ZT(i,e){i.mixer&&(i.mixer.stopAllAction(),i.mixer.uncacheRoot(i.mixer.getRoot()),i.mixer=null),i.clips=e,e.length&&(i.mixer=new Eg(i.content))}function $T(i){i.clips.forEach(e=>{i.mixer.clipAction(e).reset().play(),i.state.actionStates[e.name]=!0}),i.invalidate()}function z0(i,e,t){const n=t.length-i-1;if(e>=t[n])return n-1;if(e<=t[i])return i;let s=i,r=n,a=Math.floor((s+r)/2);for(;e<t[a]||e>=t[a+1];)e<t[a]?r=a:s=a,a=Math.floor((s+r)/2);return a}function eR(i,e,t,n){const s=[],r=[],a=[];s[0]=1;for(let o=1;o<=t;++o){r[o]=e-n[i+1-o],a[o]=n[i+o]-e;let c=0;for(let l=0;l<o;++l){const h=a[l+1],u=r[o-l],d=s[l]/(h+u);s[l]=c+h*d,c=u*d}s[o]=c}return s}function tR(i,e,t,n){const s=z0(i,n,e),r=eR(s,n,i,e),a=new gt(0,0,0,0);for(let o=0;o<=i;++o){const c=t[s-i+o],l=r[o],h=c.w*l;a.x+=c.x*h,a.y+=c.y*h,a.z+=c.z*h,a.w+=c.w*l}return a}function nR(i,e,t,n,s){const r=[];for(let u=0;u<=t;++u)r[u]=0;const a=[];for(let u=0;u<=n;++u)a[u]=r.slice(0);const o=[];for(let u=0;u<=t;++u)o[u]=r.slice(0);o[0][0]=1;const c=r.slice(0),l=r.slice(0);for(let u=1;u<=t;++u){c[u]=e-s[i+1-u],l[u]=s[i+u]-e;let d=0;for(let f=0;f<u;++f){const p=l[f+1],m=c[u-f];o[u][f]=p+m;const g=o[f][u-1]/o[u][f];o[f][u]=d+p*g,d=m*g}o[u][u]=d}for(let u=0;u<=t;++u)a[0][u]=o[u][t];for(let u=0;u<=t;++u){let d=0,f=1;const p=[];for(let m=0;m<=t;++m)p[m]=r.slice(0);p[0][0]=1;for(let m=1;m<=n;++m){let g=0;const A=u-m,_=t-m;u>=m&&(p[f][0]=p[d][0]/o[_+1][A],g=p[f][0]*o[A][_]);const x=A>=-1?1:-A,E=u-1<=_?m-1:t-u;for(let w=x;w<=E;++w)p[f][w]=(p[d][w]-p[d][w-1])/o[_+1][A+w],g+=p[f][w]*o[A+w][_];u<=_&&(p[f][m]=-p[d][m-1]/o[_+1][u],g+=p[f][m]*o[u][_]),a[m][u]=g;const S=d;d=f,f=S}}let h=t;for(let u=1;u<=n;++u){for(let d=0;d<=t;++d)a[u][d]*=h;h*=t-u}return a}function iR(i,e,t,n,s){const r=s<i?s:i,a=[],o=z0(i,n,e),c=nR(o,n,i,r,e),l=[];for(let h=0;h<t.length;++h){const u=t[h].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,l[h]=u}for(let h=0;h<=r;++h){const u=l[o-i].clone().multiplyScalar(c[h][0]);for(let d=1;d<=i;++d)u.add(l[o-i+d].clone().multiplyScalar(c[h][d]));a[h]=u}for(let h=r+1;h<=s+1;++h)a[h]=new gt(0,0,0);return a}function sR(i,e){let t=1;for(let s=2;s<=i;++s)t*=s;let n=1;for(let s=2;s<=e;++s)n*=s;for(let s=2;s<=i-e;++s)n*=s;return t/n}function rR(i){const e=i.length,t=[],n=[];for(let r=0;r<e;++r){const a=i[r];t[r]=new G(a.x,a.y,a.z),n[r]=a.w}const s=[];for(let r=0;r<e;++r){const a=t[r].clone();for(let o=1;o<=r;++o)a.sub(s[r-o].clone().multiplyScalar(sR(r,o)*n[o]));s[r]=a.divideScalar(n[0])}return s}function aR(i,e,t,n,s){const r=iR(i,e,t,n,s);return rR(r)}class oR extends sw{constructor(e,t,n,s,r){super();const a=t?t.length-1:0,o=n?n.length:0;this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=s||0,this.endKnot=r||a;for(let c=0;c<o;++c){const l=n[c];this.controlPoints[c]=new gt(l.x,l.y,l.z,l.w)}}getPoint(e,t=new G){const n=t,s=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=tR(this.degree,this.knots,this.controlPoints,s);return r.w!==1&&r.divideScalar(r.w),n.set(r.x,r.y,r.z)}getTangent(e,t=new G){const n=t,s=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),r=aR(this.degree,this.knots,this.controlPoints,s,1);return n.copy(r[1]).normalize(),n}toJSON(){const e=super.toJSON();return e.degree=this.degree,e.knots=[...this.knots],e.controlPoints=this.controlPoints.map(t=>t.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new gt(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let ht,$t,Gn;class cR extends ci{constructor(e){super(e)}load(e,t,n,s){const r=this,a=r.path===""?Ar.extractUrlBase(e):r.path,o=new os(this.manager);o.setPath(r.path),o.setResponseType("arraybuffer"),o.setRequestHeader(r.requestHeader),o.setWithCredentials(r.withCredentials),o.load(e,function(c){try{t(r.parse(c,a))}catch(l){s?s(l):console.error(l),r.manager.itemError(e)}},n,s)}parse(e,t){if(pR(e))ht=new fR().parse(e);else{const s=j0(e);if(!AR(s))throw new Error("THREE.FBXLoader: Unknown format.");if(q0(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+q0(s));ht=new dR().parse(s)}const n=new pg(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new lR(n,this.manager).parse(ht)}}class lR{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){$t=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),n=this.parseMaterials(t),s=this.parseDeformers(),r=new hR().parse(s);return this.parseScene(s,r,n),Gn}parseConnections(){const e=new Map;return"Connections"in ht&&ht.Connections.connections.forEach(function(n){const s=n[0],r=n[1],a=n[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:r,relationship:a};e.get(s).parents.push(o),e.has(r)||e.set(r,{parents:[],children:[]});const c={ID:s,relationship:a};e.get(r).children.push(c)}),e}parseImages(){const e={},t={};if("Video"in ht.Objects){const n=ht.Objects.Video;for(const s in n){const r=n[s],a=parseInt(s);if(e[a]=r.RelativeFilename||r.Filename,"Content"in r){const o=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,c=typeof r.Content=="string"&&r.Content!=="";if(o||c){const l=this.parseImage(n[s]);t[r.RelativeFilename||r.Filename]=l}}}}for(const n in e){const s=e[n];t[s]!==void 0?e[n]=t[s]:e[n]=e[n].split("\\").pop()}return e}parseImage(e){const t=e.Content,n=e.RelativeFilename||e.Filename,s=n.slice(n.lastIndexOf(".")+1).toLowerCase();let r;switch(s){case"bmp":r="image/bmp";break;case"jpg":case"jpeg":r="image/jpeg";break;case"png":r="image/png";break;case"tif":r="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",n),r="image/tga";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+r+";base64,"+t;{const a=new Uint8Array(t);return window.URL.createObjectURL(new Blob([a],{type:r}))}}parseTextures(e){const t=new Map;if("Texture"in ht.Objects){const n=ht.Objects.Texture;for(const s in n){const r=this.parseTexture(n[s],e);t.set(parseInt(s),r)}}return t}parseTexture(e,t){const n=this.loadTexture(e,t);n.ID=e.id,n.name=e.attrName;const s=e.WrapModeU,r=e.WrapModeV,a=s!==void 0?s.value:0,o=r!==void 0?r.value:0;if(n.wrapS=a===0?Ss:Zn,n.wrapT=o===0?Ss:Zn,"Scaling"in e){const c=e.Scaling.value;n.repeat.x=c[0],n.repeat.y=c[1]}if("Translation"in e){const c=e.Translation.value;n.offset.x=c[0],n.offset.y=c[1]}return n}loadTexture(e,t){const n=new Set(["tga","tif","tiff","exr","dds","hdr","ktx2"]),s=e.FileName.split(".").pop().toLowerCase(),r=n.has(s)?this.manager.getHandler(`.${s}`):this.textureLoader;if(!r)return console.warn(`FBXLoader: ${s.toUpperCase()} loader not found, creating placeholder texture for`,e.RelativeFilename),new nn;const a=r.path;a||r.setPath(this.textureLoader.path);const o=$t.get(e.id).children;let c;o!==void 0&&o.length>0&&t[o[0].ID]!==void 0&&(c=t[o[0].ID],(c.indexOf("blob:")===0||c.indexOf("data:")===0)&&r.setPath(void 0));const l=r.load(c);return r.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in ht.Objects){const n=ht.Objects.Material;for(const s in n){const r=this.parseMaterial(n[s],e);r!==null&&t.set(parseInt(s),r)}}return t}parseMaterial(e,t){const n=e.id,s=e.attrName;let r=e.ShadingModel;if(typeof r=="object"&&(r=r.value),!$t.has(n))return null;const a=this.parseParameters(e,t,n);let o;switch(r.toLowerCase()){case"phong":o=new Cl;break;case"lambert":o=new ww;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),o=new Cl;break}return o.setValues(a),o.name=s,o}parseParameters(e,t,n){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=tt.toWorkingColorSpace(new Fe().fromArray(e.Diffuse.value),yt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=tt.toWorkingColorSpace(new Fe().fromArray(e.DiffuseColor.value),yt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=tt.toWorkingColorSpace(new Fe().fromArray(e.Emissive.value),yt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=tt.toWorkingColorSpace(new Fe().fromArray(e.EmissiveColor.value),yt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=tt.toWorkingColorSpace(new Fe().fromArray(e.Specular.value),yt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=tt.toWorkingColorSpace(new Fe().fromArray(e.SpecularColor.value),yt));const r=this;return $t.get(n).children.forEach(function(a){const o=a.relationship;switch(o){case"Bump":s.bumpMap=r.getTexture(t,a.ID);break;case"Maya|TEX_ao_map":s.aoMap=r.getTexture(t,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=r.getTexture(t,a.ID),s.map!==void 0&&(s.map.colorSpace=yt);break;case"DisplacementColor":s.displacementMap=r.getTexture(t,a.ID);break;case"EmissiveColor":s.emissiveMap=r.getTexture(t,a.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=yt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=r.getTexture(t,a.ID);break;case"ReflectionColor":s.envMap=r.getTexture(t,a.ID),s.envMap!==void 0&&(s.envMap.mapping=Mc,s.envMap.colorSpace=yt);break;case"SpecularColor":s.specularMap=r.getTexture(t,a.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=yt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=r.getTexture(t,a.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in ht.Objects&&t in ht.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=$t.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in ht.Objects){const n=ht.Objects.Deformer;for(const s in n){const r=n[s],a=$t.get(parseInt(s));if(r.attrType==="Skin"){const o=this.parseSkeleton(a,n);o.ID=s,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,e[s]=o}else if(r.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(a,n),o.id=s,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const n=[];return e.children.forEach(function(s){const r=t[s.ID];if(r.attrType!=="Cluster")return;const a={ID:s.ID,indices:[],weights:[],transformLink:new Re().fromArray(r.TransformLink.a)};"Indexes"in r&&(a.indices=r.Indexes.a,a.weights=r.Weights.a),n.push(a)}),{rawBones:n,bones:[]}}parseMorphTargets(e,t){const n=[];for(let s=0;s<e.children.length;s++){const r=e.children[s],a=t[r.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=$t.get(parseInt(r.ID)).children.filter(function(c){return c.relationship===void 0})[0].ID,n.push(o)}return n}parseScene(e,t,n){Gn=new ss;const s=this.parseModels(e.skeletons,t,n),r=ht.Objects.Model,a=this;s.forEach(function(c){const l=r[c.ID];a.setLookAtProperties(c,l),$t.get(c.ID).parents.forEach(function(u){const d=s.get(u.ID);d!==void 0&&d.add(c)}),c.parent===null&&Gn.add(c)}),this.bindSkeleton(e.skeletons,t,s),this.addGlobalSceneSettings(),Gn.traverse(function(c){if(c.userData.transformData){c.parent&&(c.userData.transformData.parentMatrix=c.parent.matrix,c.userData.transformData.parentMatrixWorld=c.parent.matrixWorld);const l=K0(c.userData.transformData);c.applyMatrix4(l),c.updateWorldMatrix()}});const o=new uR().parse();Gn.children.length===1&&Gn.children[0].isGroup&&(Gn.children[0].animations=o,Gn=Gn.children[0]),Gn.animations=o}parseModels(e,t,n){const s=new Map,r=ht.Objects.Model;for(const a in r){const o=parseInt(a),c=r[a],l=$t.get(o);let h=this.buildSkeleton(l,e,o,c.attrName);if(!h){switch(c.attrType){case"Camera":h=this.createCamera(l);break;case"Light":h=this.createLight(l);break;case"Mesh":h=this.createMesh(l,t,n);break;case"NurbsCurve":h=this.createCurve(l,t);break;case"LimbNode":case"Root":h=new cl;break;default:h=new ss;break}h.name=c.attrName?_t.sanitizeNodeName(c.attrName):"",h.userData.originalName=c.attrName,h.ID=o}this.getTransformData(h,c),s.set(o,h)}return s}buildSkeleton(e,t,n,s){let r=null;return e.parents.forEach(function(a){for(const o in t){const c=t[o];c.rawBones.forEach(function(l,h){if(l.ID===a.ID){const u=r;r=new cl,r.matrixWorld.copy(l.transformLink),r.name=s?_t.sanitizeNodeName(s):"",r.userData.originalName=s,r.ID=n,c.bones[h]=r,u!==null&&r.add(u)}})}}),r}createCamera(e){let t,n;if(e.children.forEach(function(s){const r=ht.Objects.NodeAttribute[s.ID];r!==void 0&&(n=r)}),n===void 0)t=new Tt;else{let s=0;n.CameraProjectionType!==void 0&&n.CameraProjectionType.value===1&&(s=1);let r=1;n.NearPlane!==void 0&&(r=n.NearPlane.value/1e3);let a=1e3;n.FarPlane!==void 0&&(a=n.FarPlane.value/1e3);let o=window.innerWidth,c=window.innerHeight;n.AspectWidth!==void 0&&n.AspectHeight!==void 0&&(o=n.AspectWidth.value,c=n.AspectHeight.value);const l=o/c;let h=45;n.FieldOfView!==void 0&&(h=n.FieldOfView.value);const u=n.FocalLength?n.FocalLength.value:null;switch(s){case 0:t=new Bn(h,l,r,a),u!==null&&t.setFocalLength(u);break;case 1:console.warn("THREE.FBXLoader: Orthographic cameras not supported yet."),t=new Tt;break;default:console.warn("THREE.FBXLoader: Unknown camera type "+s+"."),t=new Tt;break}}return t}createLight(e){let t,n;if(e.children.forEach(function(s){const r=ht.Objects.NodeAttribute[s.ID];r!==void 0&&(n=r)}),n===void 0)t=new Tt;else{let s;n.LightType===void 0?s=0:s=n.LightType.value;let r=16777215;n.Color!==void 0&&(r=tt.toWorkingColorSpace(new Fe().fromArray(n.Color.value),yt));let a=n.Intensity===void 0?1:n.Intensity.value/100;n.CastLightOnObject!==void 0&&n.CastLightOnObject.value===0&&(a=0);let o=0;n.FarAttenuationEnd!==void 0&&(n.EnableFarAttenuation!==void 0&&n.EnableFarAttenuation.value===0?o=0:o=n.FarAttenuationEnd.value);const c=1;switch(s){case 0:t=new Ml(r,a,o,c);break;case 1:t=new gd(r,a);break;case 2:let l=Math.PI/3;n.InnerAngle!==void 0&&(l=In.degToRad(n.InnerAngle.value));let h=0;n.OuterAngle!==void 0&&(h=In.degToRad(n.OuterAngle.value),h=Math.max(h,1)),t=new mg(r,a,o,l,h,c);break;default:console.warn("THREE.FBXLoader: Unknown light type "+n.LightType.value+", defaulting to a PointLight."),t=new Ml(r,a);break}n.CastShadows!==void 0&&n.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,n){let s,r=null,a=null;const o=[];if(e.children.forEach(function(c){t.has(c.ID)&&(r=t.get(c.ID)),n.has(c.ID)&&o.push(n.get(c.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new Cl({name:ci.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),"color"in r.attributes&&o.forEach(function(c){c.vertexColors=!0}),r.groups.length>0){let c=!1;for(let l=0,h=r.groups.length;l<h;l++){const u=r.groups[l];(u.materialIndex<0||u.materialIndex>=o.length)&&(u.materialIndex=o.length,c=!0)}if(c){const l=new Cl;o.push(l)}}return r.FBX_Deformer?(s=new VA(r,a),s.normalizeSkinWeights()):s=new Zt(r,a),s}createCurve(e,t){const n=e.children.reduce(function(r,a){return t.has(a.ID)&&(r=t.get(a.ID)),r},null),s=new ma({name:ci.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new gl(n,s)}getTransformData(e,t){const n={};"InheritType"in t&&(n.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?n.eulerOrder=Xo(t.RotationOrder.value):n.eulerOrder=Xo(0),"Lcl_Translation"in t&&(n.translation=t.Lcl_Translation.value),"PreRotation"in t&&(n.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(n.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(n.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(n.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(n.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(n.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(n.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(n.rotationPivot=t.RotationPivot.value),e.userData.transformData=n}setLookAtProperties(e,t){"LookAtProperty"in t&&$t.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const r=ht.Objects.Model[s.ID];if("Lcl_Translation"in r){const a=r.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(a),Gn.add(e.target)):e.lookAt(new G().fromArray(a))}}})}bindSkeleton(e,t,n){const s=this.parsePoseNodes();for(const r in e){const a=e[r];$t.get(parseInt(a.ID)).parents.forEach(function(c){if(t.has(c.ID)){const l=c.ID;$t.get(l).parents.forEach(function(u){n.has(u.ID)&&n.get(u.ID).bind(new hl(a.bones),s[u.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in ht.Objects){const t=ht.Objects.Pose;for(const n in t)if(t[n].attrType==="BindPose"&&t[n].NbPoseNodes>0){const s=t[n].PoseNode;Array.isArray(s)?s.forEach(function(r){e[r.Node]=new Re().fromArray(r.Matrix.a)}):e[s.Node]=new Re().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in ht){if("AmbientColor"in ht.GlobalSettings){const e=ht.GlobalSettings.AmbientColor.value,t=e[0],n=e[1],s=e[2];if(t!==0||n!==0||s!==0){const r=new Fe().setRGB(t,n,s,yt);Gn.add(new bg(r,1))}}"UnitScaleFactor"in ht.GlobalSettings&&(Gn.userData.unitScaleFactor=ht.GlobalSettings.UnitScaleFactor.value)}}}class hR{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in ht.Objects){const n=ht.Objects.Geometry;for(const s in n){const r=$t.get(parseInt(s)),a=this.parseGeometry(r,n[s],e);t.set(parseInt(s),a)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,n){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,n);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,n){const s=n.skeletons,r=[],a=e.parents.map(function(u){return ht.Objects.Model[u.ID]});if(a.length===0)return;const o=e.children.reduce(function(u,d){return s[d.ID]!==void 0&&(u=s[d.ID]),u},null);e.children.forEach(function(u){n.morphTargets[u.ID]!==void 0&&r.push(n.morphTargets[u.ID])});const c=a[0],l={};"RotationOrder"in c&&(l.eulerOrder=Xo(c.RotationOrder.value)),"InheritType"in c&&(l.inheritType=parseInt(c.InheritType.value)),"GeometricTranslation"in c&&(l.translation=c.GeometricTranslation.value),"GeometricRotation"in c&&(l.rotation=c.GeometricRotation.value),"GeometricScaling"in c&&(l.scale=c.GeometricScaling.value);const h=K0(l);return this.genGeometry(t,o,r,h)}genGeometry(e,t,n,s){const r=new Mn;e.attrName&&(r.name=e.attrName);const a=this.parseGeoNode(e,t),o=this.genBuffers(a),c=new Jt(o.vertex,3);if(c.applyMatrix4(s),r.setAttribute("position",c),o.colors.length>0&&r.setAttribute("color",new Jt(o.colors,3)),t&&(r.setAttribute("skinIndex",new Xu(o.weightsIndices,4)),r.setAttribute("skinWeight",new Jt(o.vertexWeights,4)),r.FBX_Deformer=t),o.normal.length>0){const l=new ot().getNormalMatrix(s),h=new Jt(o.normal,3);h.applyNormalMatrix(l),r.setAttribute("normal",h)}if(o.uvs.forEach(function(l,h){const u=h===0?"uv":`uv${h}`;r.setAttribute(u,new Jt(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let l=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,d){u!==l&&(r.addGroup(h,d-h,l),l=u,h=d)}),r.groups.length>0){const u=r.groups[r.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&r.addGroup(d,o.materialIndex.length-d,l)}r.groups.length===0&&r.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(r,e,n,s),r}parseGeoNode(e,t){const n={};if(n.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],n.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&(n.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(n.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(n.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){n.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&n.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return n.weightTable={},t!==null&&(n.skeleton=t,t.rawBones.forEach(function(s,r){s.indices.forEach(function(a,o){n.weightTable[a]===void 0&&(n.weightTable[a]=[]),n.weightTable[a].push({id:r,weight:s.weights[o]})})})),n}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let n=0,s=0,r=!1,a=[],o=[],c=[],l=[],h=[],u=[];const d=this;return e.vertexIndices.forEach(function(f,p){let m,g=!1;f<0&&(f=f^-1,g=!0);let A=[],_=[];if(a.push(f*3,f*3+1,f*3+2),e.color){const x=eh(p,n,f,e.color);c.push(x[0],x[1],x[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(x){_.push(x.weight),A.push(x.id)}),_.length>4){r||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),r=!0);const x=[0,0,0,0],E=[0,0,0,0];_.forEach(function(S,w){let I=S,T=A[w];E.forEach(function(C,v,F){if(I>C){F[v]=I,I=C;const K=x[v];x[v]=T,T=K}})}),A=x,_=E}for(;_.length<4;)_.push(0),A.push(0);for(let x=0;x<4;++x)h.push(_[x]),u.push(A[x])}if(e.normal){const x=eh(p,n,f,e.normal);o.push(x[0],x[1],x[2])}e.material&&e.material.mappingType!=="AllSame"&&(m=eh(p,n,f,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach(function(x,E){const S=eh(p,n,f,x);l[E]===void 0&&(l[E]=[]),l[E].push(S[0]),l[E].push(S[1])}),s++,g&&(d.genFace(t,e,a,m,o,c,l,h,u,s),n++,s=0,a=[],o=[],c=[],l=[],h=[],u=[])}),t}getNormalNewell(e){const t=new G(0,0,0);for(let n=0;n<e.length;n++){const s=e[n],r=e[(n+1)%e.length];t.x+=(s.y-r.y)*(s.z+r.z),t.y+=(s.z-r.z)*(s.x+r.x),t.z+=(s.x-r.x)*(s.y+r.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){const t=this.getNormalNewell(e),s=(Math.abs(t.z)>.5?new G(0,1,0):new G(0,0,1)).cross(t).normalize(),r=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:r}}flattenVertex(e,t,n){return new Je(e.dot(t),e.dot(n))}genFace(e,t,n,s,r,a,o,c,l,h){let u;if(h>3){const d=[],f=t.baseVertexPositions||t.vertexPositions;for(let A=0;A<n.length;A+=3)d.push(new G(f[n[A]],f[n[A+1]],f[n[A+2]]));const{tangent:p,bitangent:m}=this.getNormalTangentAndBitangent(d),g=[];for(const A of d)g.push(this.flattenVertex(A,p,m));u=ud.triangulateShape(g,[])}else u=[[0,1,2]];for(const[d,f,p]of u)e.vertex.push(t.vertexPositions[n[d*3]]),e.vertex.push(t.vertexPositions[n[d*3+1]]),e.vertex.push(t.vertexPositions[n[d*3+2]]),e.vertex.push(t.vertexPositions[n[f*3]]),e.vertex.push(t.vertexPositions[n[f*3+1]]),e.vertex.push(t.vertexPositions[n[f*3+2]]),e.vertex.push(t.vertexPositions[n[p*3]]),e.vertex.push(t.vertexPositions[n[p*3+1]]),e.vertex.push(t.vertexPositions[n[p*3+2]]),t.skeleton&&(e.vertexWeights.push(c[d*4]),e.vertexWeights.push(c[d*4+1]),e.vertexWeights.push(c[d*4+2]),e.vertexWeights.push(c[d*4+3]),e.vertexWeights.push(c[f*4]),e.vertexWeights.push(c[f*4+1]),e.vertexWeights.push(c[f*4+2]),e.vertexWeights.push(c[f*4+3]),e.vertexWeights.push(c[p*4]),e.vertexWeights.push(c[p*4+1]),e.vertexWeights.push(c[p*4+2]),e.vertexWeights.push(c[p*4+3]),e.weightsIndices.push(l[d*4]),e.weightsIndices.push(l[d*4+1]),e.weightsIndices.push(l[d*4+2]),e.weightsIndices.push(l[d*4+3]),e.weightsIndices.push(l[f*4]),e.weightsIndices.push(l[f*4+1]),e.weightsIndices.push(l[f*4+2]),e.weightsIndices.push(l[f*4+3]),e.weightsIndices.push(l[p*4]),e.weightsIndices.push(l[p*4+1]),e.weightsIndices.push(l[p*4+2]),e.weightsIndices.push(l[p*4+3])),t.color&&(e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[f*3]),e.colors.push(a[f*3+1]),e.colors.push(a[f*3+2]),e.colors.push(a[p*3]),e.colors.push(a[p*3+1]),e.colors.push(a[p*3+2])),t.material&&t.material.mappingType!=="AllSame"&&(e.materialIndex.push(s),e.materialIndex.push(s),e.materialIndex.push(s)),t.normal&&(e.normal.push(r[d*3]),e.normal.push(r[d*3+1]),e.normal.push(r[d*3+2]),e.normal.push(r[f*3]),e.normal.push(r[f*3+1]),e.normal.push(r[f*3+2]),e.normal.push(r[p*3]),e.normal.push(r[p*3+1]),e.normal.push(r[p*3+2])),t.uv&&t.uv.forEach(function(m,g){e.uvs[g]===void 0&&(e.uvs[g]=[]),e.uvs[g].push(o[g][d*2]),e.uvs[g].push(o[g][d*2+1]),e.uvs[g].push(o[g][f*2]),e.uvs[g].push(o[g][f*2+1]),e.uvs[g].push(o[g][p*2]),e.uvs[g].push(o[g][p*2+1])})}addMorphTargets(e,t,n,s){if(n.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const r=this;n.forEach(function(a){a.rawTargets.forEach(function(o){const c=ht.Objects.Geometry[o.geoID];c!==void 0&&r.genMorphGeometry(e,t,c,s,o.name)})})}genMorphGeometry(e,t,n,s,r){const a=t.Vertices!==void 0?t.Vertices.a:[],o=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],c=n.Vertices!==void 0?n.Vertices.a:[],l=n.Indexes!==void 0?n.Indexes.a:[],h=e.attributes.position.count*3,u=new Float32Array(h);for(let m=0;m<l.length;m++){const g=l[m]*3;u[g]=c[m*3],u[g+1]=c[m*3+1],u[g+2]=c[m*3+2]}const d={vertexIndices:o,vertexPositions:u,baseVertexPositions:a},f=this.genBuffers(d),p=new Jt(f.vertex,3);p.name=r||n.attrName,p.applyMatrix4(s),e.morphAttributes.position.push(p)}parseNormals(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.Normals.a;let r=[];return n==="IndexToDirect"&&("NormalIndex"in e?r=e.NormalIndex.a:"NormalsIndex"in e&&(r=e.NormalsIndex.a)),{dataSize:3,buffer:s,indices:r,mappingType:t,referenceType:n}}parseUVs(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.UV.a;let r=[];return n==="IndexToDirect"&&(r=e.UVIndex.a),{dataSize:2,buffer:s,indices:r,mappingType:t,referenceType:n}}parseVertexColors(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.Colors.a;let r=[];n==="IndexToDirect"&&(r=e.ColorIndex.a);for(let a=0,o=new Fe;a<s.length;a+=4)o.fromArray(s,a),tt.toWorkingColorSpace(o,yt),o.toArray(s,a);return{dataSize:4,buffer:s,indices:r,mappingType:t,referenceType:n}}parseMaterialIndices(e){const t=e.MappingInformationType,n=e.ReferenceInformationType;if(t==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:n};const s=e.Materials.a,r=[];for(let a=0;a<s.length;++a)r.push(a);return{dataSize:1,buffer:s,indices:r,mappingType:t,referenceType:n}}parseNurbsGeometry(e){const t=parseInt(e.Order);if(isNaN(t))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",e.Order,e.id),new Mn;const n=t-1,s=e.KnotVector.a,r=[],a=e.Points.a;for(let u=0,d=a.length;u<d;u+=4)r.push(new gt().fromArray(a,u));let o,c;if(e.Form==="Closed")r.push(r[0]);else if(e.Form==="Periodic"){o=n,c=s.length-1-o;for(let u=0;u<n;++u)r.push(r[u])}const h=new oR(n,s,r,o,c).getPoints(r.length*12);return new Mn().setFromPoints(h)}}class uR{parse(){const e=[],t=this.parseClips();if(t!==void 0)for(const n in t){const s=t[n],r=this.addClip(s);e.push(r)}return e}parseClips(){if(ht.Objects.AnimationCurve===void 0)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=ht.Objects.AnimationCurveNode,t=new Map;for(const n in e){const s=e[n];if(s.attrName.match(/S|R|T|DeformPercent/)!==null){const r={id:s.id,attr:s.attrName,curves:{}};t.set(r.id,r)}}return t}parseAnimationCurves(e){const t=ht.Objects.AnimationCurve;for(const n in t){const s={id:t[n].id,times:t[n].KeyTime.a.map(gR),values:t[n].KeyValueFloat.a},r=$t.get(s.id);if(r!==void 0){const a=r.parents[0].ID,o=r.parents[0].relationship;o.match(/X/)?e.get(a).curves.x=s:o.match(/Y/)?e.get(a).curves.y=s:o.match(/Z/)?e.get(a).curves.z=s:o.match(/DeformPercent/)&&e.has(a)&&(e.get(a).curves.morph=s)}}}parseAnimationLayers(e){const t=ht.Objects.AnimationLayer,n=new Map;for(const s in t){const r=[],a=$t.get(parseInt(s));a!==void 0&&(a.children.forEach(function(c,l){if(e.has(c.ID)){const h=e.get(c.ID);if(h.curves.x!==void 0||h.curves.y!==void 0||h.curves.z!==void 0){if(r[l]===void 0){const u=$t.get(c.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=ht.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",c);return}const f={modelName:d.attrName?_t.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};Gn.traverse(function(p){p.ID===d.id&&(f.transform=p.matrix,p.userData.transformData&&(f.eulerOrder=p.userData.transformData.eulerOrder))}),f.transform||(f.transform=new Re),"PreRotation"in d&&(f.preRotation=d.PreRotation.value),"PostRotation"in d&&(f.postRotation=d.PostRotation.value),r[l]=f}}r[l]&&(r[l][h.attr]=h)}else if(h.curves.morph!==void 0){if(r[l]===void 0){const u=$t.get(c.ID).parents.filter(function(A){return A.relationship!==void 0})[0].ID,d=$t.get(u).parents[0].ID,f=$t.get(d).parents[0].ID,p=$t.get(f).parents[0].ID,m=ht.Objects.Model[p],g={modelName:m.attrName?_t.sanitizeNodeName(m.attrName):"",morphName:ht.Objects.Deformer[u].attrName};r[l]=g}r[l][h.attr]=h}}}),n.set(parseInt(s),r))}return n}parseAnimStacks(e){const t=ht.Objects.AnimationStack,n={};for(const s in t){const r=$t.get(parseInt(s)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const a=e.get(r[0].ID);n[s]={name:t[s].attrName,layer:a}}return n}addClip(e){let t=[];const n=this;return e.layer.forEach(function(s){t=t.concat(n.generateTracks(s))}),new Sl(e.name,-1,t)}generateTracks(e){const t=[];let n=new G,s=new G;if(e.transform&&e.transform.decompose(n,new Yt,s),n=n.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const r=this.generateVectorTrack(e.modelName,e.T.curves,n,"position");r!==void 0&&t.push(r)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const r=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);r!==void 0&&t.push(r)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const r=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");r!==void 0&&t.push(r)}if(e.DeformPercent!==void 0){const r=this.generateMorphTrack(e);r!==void 0&&t.push(r)}return t}generateVectorTrack(e,t,n,s){const r=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(r,t,n);return new pr(e+"."+s,r,a)}generateRotationTrack(e,t,n,s,r){let a,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const d=this.interpolateRotations(t.x,t.y,t.z,r);a=d[0],o=d[1]}const c=Xo(0);n!==void 0&&(n=n.map(In.degToRad),n.push(c),n=new dn().fromArray(n),n=new Yt().setFromEuler(n)),s!==void 0&&(s=s.map(In.degToRad),s.push(c),s=new dn().fromArray(s),s=new Yt().setFromEuler(s).invert());const l=new Yt,h=new dn,u=[];if(!o||!a)return new Us(e+".quaternion",[0],[0]);for(let d=0;d<o.length;d+=3)h.set(o[d],o[d+1],o[d+2],r),l.setFromEuler(h),n!==void 0&&l.premultiply(n),s!==void 0&&l.multiply(s),d>2&&new Yt().fromArray(u,(d-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(u,d/3*4);return new Us(e+".quaternion",a,u)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,n=t.values.map(function(r){return r/100}),s=Gn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new fr(e.modelName+".morphTargetInfluences["+s+"]",t.times,n)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(n,s){return n-s}),t.length>1){let n=1,s=t[0];for(let r=1;r<t.length;r++){const a=t[r];a!==s&&(t[n]=a,s=a,n++)}t=t.slice(0,n)}return t}getKeyframeTrackValues(e,t,n){const s=n,r=[];let a=-1,o=-1,c=-1;return e.forEach(function(l){if(t.x&&(a=t.x.times.indexOf(l)),t.y&&(o=t.y.times.indexOf(l)),t.z&&(c=t.z.times.indexOf(l)),a!==-1){const h=t.x.values[a];r.push(h),s[0]=h}else r.push(s[0]);if(o!==-1){const h=t.y.values[o];r.push(h),s[1]=h}else r.push(s[1]);if(c!==-1){const h=t.z.values[c];r.push(h),s[2]=h}else r.push(s[2])}),r}interpolateRotations(e,t,n,s){const r=[],a=[];r.push(e.times[0]),a.push(In.degToRad(e.values[0])),a.push(In.degToRad(t.values[0])),a.push(In.degToRad(n.values[0]));for(let o=1;o<e.values.length;o++){const c=[e.values[o-1],t.values[o-1],n.values[o-1]];if(isNaN(c[0])||isNaN(c[1])||isNaN(c[2]))continue;const l=c.map(In.degToRad),h=[e.values[o],t.values[o],n.values[o]];if(isNaN(h[0])||isNaN(h[1])||isNaN(h[2]))continue;const u=h.map(In.degToRad),d=[h[0]-c[0],h[1]-c[1],h[2]-c[2]],f=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(f[0]>=180||f[1]>=180||f[2]>=180){const m=Math.max(...f)/180,g=new dn(...l,s),A=new dn(...u,s),_=new Yt().setFromEuler(g),x=new Yt().setFromEuler(A);_.dot(x)&&x.set(-x.x,-x.y,-x.z,-x.w);const E=e.times[o-1],S=e.times[o]-E,w=new Yt,I=new dn;for(let T=0;T<1;T+=1/m)w.copy(_.clone().slerp(x.clone(),T)),r.push(E+T*S),I.setFromQuaternion(w,s),a.push(I.x),a.push(I.y),a.push(I.z)}else r.push(e.times[o]),a.push(In.degToRad(e.values[o])),a.push(In.degToRad(t.values[o])),a.push(In.degToRad(n.values[o]))}return[r,a]}}class dR{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new W0,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,n=e.split(/[\r\n]+/);return n.forEach(function(s,r){const a=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(a||o)return;const c=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),l=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=s.match("^\\t{"+(t.currentIndent-1)+"}}");c?t.parseNodeBegin(s,c):l?t.parseNodeProperty(s,l,n[++r]):h?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const n=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(c){return c.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:n},a=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(n,r):n in o?(n==="PoseNode"?o.PoseNode.push(r):o[n].id!==void 0&&(o[n]={},o[n][o[n].id]=o[n]),a.id!==""&&(o[n][a.id]=r)):typeof a.id=="number"?(o[n]={},o[n][a.id]=r):n!=="Properties70"&&(n==="PoseNode"?o[n]=[r]:o[n]=r),typeof a.id=="number"&&(r.id=a.id),a.name!==""&&(r.attrName=a.name),a.type!==""&&(r.attrType=a.type),this.pushStack(r)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let n="",s="";return e.length>1&&(n=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:n,type:s}}parseNodeProperty(e,t,n){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),r=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&r===","&&(r=n.replace(/"/g,"").replace(/,$/,"").trim());const a=this.getCurrentNode();if(a.name==="Properties70"){this.parseNodeSpecialProperty(e,s,r);return}if(s==="C"){const c=r.split(",").slice(1),l=parseInt(c[0]),h=parseInt(c[1]);let u=r.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),s="connections",r=[l,h],xR(r,u),a[s]===void 0&&(a[s]=[])}s==="Node"&&(a.id=r),s in a&&Array.isArray(a[s])?a[s].push(r):s!=="a"?a[s]=r:a.a=r,this.setCurrentProp(a,s),s==="a"&&r.slice(-1)!==","&&(a.a=Mf(r))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=Mf(t.a))}parseNodeSpecialProperty(e,t,n){const s=n.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=s[0],a=s[1],o=s[2],c=s[3];let l=s[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":l=parseFloat(l);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":l=Mf(l);break}this.getPrevNode()[r]={type:a,type2:o,flag:c,value:l},this.setCurrentProp(this.getPrevNode(),r)}}class fR{parse(e){const t=new V0(e);t.skip(23);const n=t.getUint32();if(n<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+n);const s=new W0;for(;!this.endOfContent(t);){const r=this.parseNode(t,n);r!==null&&s.add(r.name,r)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const n={},s=t>=7500?e.getUint64():e.getUint32(),r=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const a=e.getUint8(),o=e.getString(a);if(s===0)return null;const c=[];for(let d=0;d<r;d++)c.push(this.parseProperty(e));const l=c.length>0?c[0]:"",h=c.length>1?c[1]:"",u=c.length>2?c[2]:"";for(n.singleProperty=r===1&&e.getOffset()===s;s>e.getOffset();){const d=this.parseNode(e,t);d!==null&&this.parseSubNode(o,n,d)}return n.propertyList=c,typeof l=="number"&&(n.id=l),h!==""&&(n.attrName=h),u!==""&&(n.attrType=u),o!==""&&(n.name=o),n}parseSubNode(e,t,n){if(n.singleProperty===!0){const s=n.propertyList[0];Array.isArray(s)?(t[n.name]=n,n.a=s):t[n.name]=s}else if(e==="Connections"&&n.name==="C"){const s=[];n.propertyList.forEach(function(r,a){a!==0&&s.push(r)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(n.name==="Properties70")Object.keys(n).forEach(function(r){t[r]=n[r]});else if(e==="Properties70"&&n.name==="P"){let s=n.propertyList[0],r=n.propertyList[1];const a=n.propertyList[2],o=n.propertyList[3];let c;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),r.indexOf("Lcl ")===0&&(r=r.replace("Lcl ","Lcl_")),r==="Color"||r==="ColorRGB"||r==="Vector"||r==="Vector3D"||r.indexOf("Lcl_")===0?c=[n.propertyList[4],n.propertyList[5],n.propertyList[6]]:c=n.propertyList[4],t[s]={type:r,type2:a,flag:o,value:c}}else t[n.name]===void 0?typeof n.id=="number"?(t[n.name]={},t[n.name][n.id]=n):t[n.name]=n:n.name==="PoseNode"?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(n)):t[n.name][n.id]===void 0&&(t[n.name][n.id]=n)}parseProperty(e){const t=e.getString(1);let n;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return n=e.getUint32(),e.getArrayBuffer(n);case"S":return n=e.getUint32(),e.getString(n);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),r=e.getUint32(),a=e.getUint32();if(r===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=jo(new Uint8Array(e.getArrayBuffer(a))),c=new V0(o.buffer);switch(t){case"b":case"c":return c.getBooleanArray(s);case"d":return c.getFloat64Array(s);case"f":return c.getFloat32Array(s);case"i":return c.getInt32Array(s);case"l":return c.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class V0{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let n=0;n<e;n++)t.push(this.getBoolean());return t}getUint8(){const e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){const e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){const e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getInt32());return t}getUint32(){const e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){const e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getFloat32());return t}getFloat64(){const e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getFloat64());return t}getArrayBuffer(e){const t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){const t=this.offset;let n=new Uint8Array(this.dv.buffer,t,e);this.skip(e);const s=n.indexOf(0);return s>=0&&(n=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(n)}}class W0{add(e,t){this[e]=t}}function pR(i){const e="Kaydara FBX Binary \0";return i.byteLength>=e.length&&e===j0(i,0,e.length)}function AR(i){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function n(s){const r=i[s-1];return i=i.slice(t+s),t++,r}for(let s=0;s<e.length;++s)if(n(1)===e[s])return!1;return!0}function q0(i){const e=/FBXVersion: (\d+)/,t=i.match(e);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function gR(i){return i/46186158e3}const mR=[];function eh(i,e,t,n){let s;switch(n.mappingType){case"ByPolygonVertex":s=i;break;case"ByPolygon":s=e;break;case"ByVertice":s=t;break;case"AllSame":s=n.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+n.mappingType)}n.referenceType==="IndexToDirect"&&(s=n.indices[s]);const r=s*n.dataSize,a=r+n.dataSize;return bR(mR,n.buffer,r,a)}const Sf=new dn,Na=new G;function K0(i){const e=new Re,t=new Re,n=new Re,s=new Re,r=new Re,a=new Re,o=new Re,c=new Re,l=new Re,h=new Re,u=new Re,d=new Re,f=i.inheritType?i.inheritType:0;i.translation&&e.setPosition(Na.fromArray(i.translation));const p=Xo(0);if(i.preRotation){const F=i.preRotation.map(In.degToRad);F.push(p),t.makeRotationFromEuler(Sf.fromArray(F))}if(i.rotation){const F=i.rotation.map(In.degToRad);F.push(i.eulerOrder||p),n.makeRotationFromEuler(Sf.fromArray(F))}if(i.postRotation){const F=i.postRotation.map(In.degToRad);F.push(p),s.makeRotationFromEuler(Sf.fromArray(F)),s.invert()}i.scale&&r.scale(Na.fromArray(i.scale)),i.scalingOffset&&o.setPosition(Na.fromArray(i.scalingOffset)),i.scalingPivot&&a.setPosition(Na.fromArray(i.scalingPivot)),i.rotationOffset&&c.setPosition(Na.fromArray(i.rotationOffset)),i.rotationPivot&&l.setPosition(Na.fromArray(i.rotationPivot)),i.parentMatrixWorld&&(u.copy(i.parentMatrix),h.copy(i.parentMatrixWorld));const m=t.clone().multiply(n).multiply(s),g=new Re;g.extractRotation(h);const A=new Re;A.copyPosition(h);const _=A.clone().invert().multiply(h),x=g.clone().invert().multiply(_),E=r,S=new Re;if(f===0)S.copy(g).multiply(m).multiply(x).multiply(E);else if(f===1)S.copy(g).multiply(x).multiply(m).multiply(E);else{const K=new Re().scale(new G().setFromMatrixScale(u)).clone().invert(),q=x.clone().multiply(K);S.copy(g).multiply(m).multiply(q).multiply(E)}const w=l.clone().invert(),I=a.clone().invert();let T=e.clone().multiply(c).multiply(l).multiply(t).multiply(n).multiply(s).multiply(w).multiply(o).multiply(a).multiply(r).multiply(I);const C=new Re().copyPosition(T),v=h.clone().multiply(C);return d.copyPosition(v),T=d.clone().multiply(S),T.premultiply(h.invert()),T}function Xo(i){i=i||0;const e=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return i===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),e[0]):e[i]}function Mf(i){return i.split(",").map(function(t){return parseFloat(t)})}function j0(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=i.byteLength),new TextDecoder().decode(new Uint8Array(i,e,t))}function xR(i,e){for(let t=0,n=i.length,s=e.length;t<s;t++,n++)i[n]=e[t]}function bR(i,e,t,n){for(let s=t,r=0;s<n;s++,r++)i[r]=e[s];return i}const ER=.35;class yR{constructor(){this.model=null,this.mixer=null,this.clips=new Map,this.actions=new Map,this.currentName=null,this.currentAction=null,this.loader=new Bd,this.fbxLoader=new cR,this.onChange=null,this._gltfCache=new Map,this._animationDefs=[]}attach(e){this.detach(),this.model=e,this.mixer=new Eg(e),this.actions.clear(),this.currentAction=null,this.currentName=null;for(const[t,n]of this.clips){const s=this._retargetClip(n,t),r=this.mixer.clipAction(s);r.enabled=!0,this.actions.set(t,r)}}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot()),this.mixer=null),this.model=null,this.actions.clear(),this.currentAction=null,this.currentName=null}setAnimationDefs(e){this._animationDefs=e}getAnimationDefs(){return this._animationDefs}async loadAnimation(e,t,n={}){if(this.clips.has(e))return this.clips.get(e);let s;if(this._gltfCache.has(t))s=this._gltfCache.get(t);else{const a=t.toLowerCase().endsWith(".fbx");s=(await new Promise((c,l)=>{(a?this.fbxLoader:this.loader).load(t,c,void 0,l)})).animations||[],this._gltfCache.set(t,s)}let r;if(n.clipName?(r=s.find(a=>a.name===n.clipName),r||(console.warn(`[AnimationManager] Clip "${n.clipName}" not found in ${t}, using first clip`),r=s[0])):r=s[0],!r)throw new Error(`No animation found in ${t}`);if(r=r.clone(),r.name=e,this.clips.set(e,r),this.model&&this.mixer){const a=this._retargetClip(r,e),o=this.mixer.clipAction(a);o.enabled=!0,o.setLoop(n.loop===!1?rA:aA),n.loop===!1&&(o.clampWhenFinished=!0),this.actions.set(e,o)}return r}async loadAll(){const e=this._animationDefs.map(async t=>{try{await this.loadAnimation(t.name,t.url,{loop:t.loop!==!1,clipName:t.clipName})}catch(n){console.warn(`[AnimationManager] Failed to load "${t.name}" from ${t.url}:`,n)}});await Promise.all(e)}play(e){const t=this.actions.get(e);if(!t){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}this.currentAction&&this.currentAction!==t&&this.currentAction.fadeOut(.01),t.reset().fadeIn(.01).play(),this.currentAction=t,this.currentName=e,this.onChange&&this.onChange(e)}crossfadeTo(e,t=ER){if(e===this.currentName)return;const n=this.actions.get(e);if(!n){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}n.reset(),n.play(),this.currentAction?this.currentAction.crossFadeTo(n,t,!0):n.fadeIn(t),this.currentAction=n,this.currentName=e,this.onChange&&this.onChange(e)}stopAll(){this.mixer&&this.mixer.stopAllAction(),this.currentAction=null,this.currentName=null,this.onChange&&this.onChange(null)}update(e){this.mixer&&this.mixer.update(e)}_retargetClip(e,t){if(!this.model)return e;const n=new Set;if(this.model.traverse(l=>{l.isBone&&n.add(l.name)}),n.size===0)return e;const s=new Set;for(const l of e.tracks){const h=l.name.split(".")[0];s.add(h)}let r=0;for(const l of s)n.has(l)&&r++;if(r/s.size>.5)return e;const a=this._buildBoneNameMap(n,s);if(!a)return e;const o=e.tracks.map(l=>{const h=l.name.split("."),u=h[0],d=h.slice(1).join("."),f=a.get(u);if(!f)return null;const p=l.clone();return p.name=`${f}.${d}`,p}).filter(Boolean),c=e.clone();return c.tracks=o,c}_buildBoneNameMap(e,t){const n=new Map,s=[...e],r=[...t],a=h=>h.replace(/^mixamorig\d*[_:]?/i,"").replace(/^Armature[_/]?/i,""),o=new Map(s.map(h=>[a(h),h]));let c=0;for(const h of r){const u=a(h);o.has(u)&&(n.set(h,o.get(u)),c++)}if(c/r.length>.5)return n;const l=new Map(s.map(h=>[h.toLowerCase(),h]));n.clear(),c=0;for(const h of r)l.has(h.toLowerCase())&&(n.set(h,l.get(h.toLowerCase())),c++);return c/r.length>.5?n:null}getLoadedNames(){return[...this.clips.keys()]}isLoaded(e){return this.clips.has(e)}dispose(){this.detach(),this.clips.clear(),this._gltfCache.clear(),this._animationDefs=[]}}rs.enabled=!0;class Bf{constructor(e,t){this.el=e,this.options=t,this.lights=[],this.content=null,this.mixer=null,this.clips=[],this.gui=null,this.animationManager=new yR,this._animPanelEl=null,this.state={environment:t.preset===wf.ASSET_GENERATOR?Ql.find(r=>r.id==="footprint-court").name:Ql[1].name,background:!1,playbackSpeed:1,actionStates:{},camera:Zl,wireframe:!1,skeleton:!1,grid:!1,autoRotate:!1,punctualLights:!0,exposure:0,toneMapping:eu,ambientIntensity:.3,ambientColor:"#FFFFFF",directIntensity:.8*Math.PI,directColor:"#FFFFFF",bgColor:"#000000",transparentBg:!1,pointSize:1,showInfo:!0,showLabels:!1,followMode:"mouse"},this.prevTime=0,this.stats=new Lo,this.stats.dom.height="48px",[].forEach.call(this.stats.dom.children,r=>r.style.display=""),this.backgroundColor=new Fe(this.state.bgColor),this.scene=new $u,this.scene.background=this.backgroundColor;const n=t.preset===wf.ASSET_GENERATOR?.8*180/Math.PI:60,s=e.clientWidth/e.clientHeight;this.defaultCamera=new Bn(n,s,.01,1e3),this.activeCamera=this.defaultCamera,this.scene.add(this.defaultCamera),this.renderer=window.renderer=new $g({antialias:!0,alpha:!0}),this.renderer.setClearColor(0,1),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(e.clientWidth,e.clientHeight),this.pmremGenerator=new Cd(this.renderer),this.pmremGenerator.compileEquirectangularShader(),this.neutralEnvironment=this.pmremGenerator.fromScene(new tM).texture,this.controls=new H1(this.defaultCamera,this.renderer.domElement),this.controls.screenSpacePanning=!0,this._onControlsChange=()=>this.invalidate(),this.controls.addEventListener("change",this._onControlsChange),this.el.appendChild(this.renderer.domElement),this.cameraCtrl=null,this.cameraFolder=null,this.animFolder=null,this.animCtrls=[],this.morphFolder=null,this.morphCtrls=[],this.skeletonHelpers=[],this.gridHelper=null,this.axesHelper=null,this.modelInfo=null,this.annotationEls=[],this._tempVec=new G,this.addAxesHelper(),this.addGUI(),t.kiosk&&this.gui.close(),this.animate=this.animate.bind(this),this._rafId=null,this._visible=!0,this._tabVisible=!document.hidden,this._disposed=!1,this._loadedEnvironment=null,this._guiWrap=null,this._needsRender=!0,this._animating=!1,this._onVisibilityChange=()=>{const r=!this._tabVisible;this._tabVisible=!document.hidden,r&&this._tabVisible&&(this._needsRender=!0),this._updateRenderLoop()},document.addEventListener("visibilitychange",this._onVisibilityChange),typeof IntersectionObserver<"u"&&(this._intersectionObserver=new IntersectionObserver(r=>{const a=!this._visible;this._visible=r[r.length-1].isIntersecting,a&&this._visible&&(this._needsRender=!0),this._updateRenderLoop()},{threshold:0}),this._intersectionObserver.observe(this.el)),this._onResize=this.resize.bind(this),this._onKeyDown=r=>{(r.key==="p"||r.key==="P")&&!this.isInputFocused()&&this.takeScreenshot()},this._updateRenderLoop(),window.addEventListener("resize",this._onResize,!1),window.addEventListener("keydown",this._onKeyDown)}invalidate(){this._disposed||(this._needsRender=!0,this._updateRenderLoop())}_recomputeAnimating(){let e=!1;if(this.state&&this.state.autoRotate&&(e=!0),!e&&this.mixer&&this.state){for(const t in this.state.actionStates)if(this.state.actionStates[t]){e=!0;break}}!e&&this.animationManager.currentAction&&(e=!0),this._animating=e}_updateRenderLoop(){if(this._disposed)return;const e=this._visible&&this._tabVisible;e&&(this._needsRender||this._animating)&&this._rafId===null?(this.prevTime=performance.now(),this._rafId=requestAnimationFrame(this.animate)):!e&&this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}animate(e){const t=(e-this.prevTime)/1e3;if(this.prevTime=e,this._recomputeAnimating(),this.controls.update(),this.stats.update(),this.mixer&&this.mixer.update(t),this.animationManager.update(t),this._afterAnimateHooks)for(let n=0;n<this._afterAnimateHooks.length;n++)this._afterAnimateHooks[n](t);this.render(),this._needsRender=!1,this._animating&&this._visible&&this._tabVisible&&!this._disposed?this._rafId=requestAnimationFrame(this.animate):this._rafId=null}isInputFocused(){const e=document.activeElement;return e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable)}render(){this.renderer.render(this.scene,this.activeCamera),this.state.grid&&(this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesRenderer.render(this.axesScene,this.axesCamera)),this.projectAnnotations()}takeScreenshot(){YT(this)}resize(){const{clientHeight:e,clientWidth:t}=this.el;this.defaultCamera.aspect=t/e,this.defaultCamera.updateProjectionMatrix(),this.renderer.setSize(t,e),this.axesCamera.aspect=this.axesDiv.clientWidth/this.axesDiv.clientHeight,this.axesCamera.updateProjectionMatrix(),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.invalidate()}load(e,t,n){const s=Ar.extractUrlBase(e);return new Promise((r,a)=>{$l.setURLModifier((l,h)=>{const u=t+decodeURI(l).replace(s,"").replace(/^(\.?\/)/,"");if(n.has(u)){const d=n.get(u),f=URL.createObjectURL(d);return c.push(f),f}return(h||"")+l});const o=new Bd($l).setCrossOrigin("anonymous").setDRACOLoader(BT).setKTX2Loader(TT.detectSupport(this.renderer)).setMeshoptDecoder(Q1),c=[];o.load(e,l=>{window.VIEWER.json=l;const h=l.scene||l.scenes[0],u=l.animations||[];if(!h)throw new Error("This model contains no scene, and cannot be viewed here. However, it may contain individual 3D resources.");this.setContent(h,u),c.forEach(URL.revokeObjectURL),r(l)},void 0,a)})}setContent(e,t){this.clear(),e.updateMatrixWorld();const n=new ki().setFromObject(e),s=n.getSize(new G).length(),r=n.getCenter(new G);this.controls.reset(),e.position.x-=r.x,e.position.y-=r.y,e.position.z-=r.z,this.controls.maxDistance=s*10,this.defaultCamera.near=s/100,this.defaultCamera.far=s*100,this.defaultCamera.updateProjectionMatrix(),this.options.cameraPosition?(this.defaultCamera.position.fromArray(this.options.cameraPosition),this.defaultCamera.lookAt(new G)):(this.defaultCamera.position.copy(r),this.defaultCamera.position.x+=s/2,this.defaultCamera.position.y+=s/5,this.defaultCamera.position.z+=s/2,this.defaultCamera.lookAt(r)),this.setCamera(Zl),this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesCamera.near=s/100,this.axesCamera.far=s*100,this.axesCamera.updateProjectionMatrix(),this.axesCorner.scale.set(s,s,s),this.controls.saveState(),this.scene.add(e),this.content=e,this.state.punctualLights=!0,this.content.traverse(a=>{a.isLight&&(this.state.punctualLights=!1)}),this.setClips(t),this.animationManager.attach(this.content),this._setupAnimationPanel(),this.updateLights(),this.updateGUI(),this.updateEnvironment(),this.updateDisplay(),this.updateModelInfo(e,t),this.updateAnnotations(),window.VIEWER.scene=this.content,this.invalidate()}setClips(e){ZT(this,e)}playAllClips(){$T(this)}setCamera(e){e===Zl?(this.controls.enabled=!0,this.activeCamera=this.defaultCamera):(this.controls.enabled=!1,this.content.traverse(t=>{t.isCamera&&t.name===e&&(this.activeCamera=t)})),this.invalidate()}updateLights(){const e=this.state,t=this.lights;e.punctualLights&&!t.length?RT(this):!e.punctualLights&&t.length&&FT(this),this.renderer.toneMapping=Number(e.toneMapping),this.renderer.toneMappingExposure=Math.pow(2,e.exposure),t.length===2&&(t[0].intensity=e.ambientIntensity,t[0].color.set(e.ambientColor),t[1].intensity=e.directIntensity,t[1].color.set(e.directColor)),this.invalidate()}updateEnvironment(){const e=Ql.filter(t=>t.name===this.state.environment)[0];XT(this,e).then(({envMap:t})=>{this._disposed||!this.scene||(this.scene.environment=t,this.scene.background=this.state.transparentBg?null:this.state.background?t:this.backgroundColor,this.invalidate())})}updateDisplay(){this.skeletonHelpers.length&&this.skeletonHelpers.forEach(e=>this.scene.remove(e)),P0(this.content,e=>{e.wireframe=this.state.wireframe,e instanceof od&&(e.size=this.state.pointSize)}),this.content.traverse(e=>{if(e.geometry&&e.skeleton&&this.state.skeleton){const t=new tv(e.skeleton.bones[0].parent);t.material.linewidth=3,this.scene.add(t),this.skeletonHelpers.push(t)}}),this.state.grid!==!!this.gridHelper&&(this.state.grid?(this.gridHelper=new nv,this.axesHelper=new wg,this.axesHelper.renderOrder=999,this.axesHelper.onBeforeRender=e=>e.clearDepth(),this.scene.add(this.gridHelper),this.scene.add(this.axesHelper)):(this.scene.remove(this.gridHelper),this.scene.remove(this.axesHelper),this.gridHelper=null,this.axesHelper=null,this.axesRenderer.clear())),this.controls.autoRotate=this.state.autoRotate,this.invalidate()}updateBackground(){this.backgroundColor.set(this.state.bgColor),this.state.transparentBg?(this.scene.background=null,this.renderer.setClearColor(0,0)):(this.scene.background=this.backgroundColor,this.renderer.setClearColor(0,1),this.updateEnvironment()),this.invalidate()}setBackgroundColor(e){this.state.bgColor=typeof e=="string"?e:"#"+e.toString(16).padStart(6,"0"),this.state.transparentBg=!1,this.updateBackground()}updateModelInfo(e,t){this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.state.showInfo&&e&&(this.modelInfo=oT(this.el,e,t))}updateAnnotations(){if(this.annotationEls.forEach(t=>t.el.remove()),this.annotationEls=[],!this.state.showLabels||!this.content)return;hT(this.content).forEach(t=>{const n=uT(t),s=document.createElement("div");s.classList.add("annotation-label"),s.appendChild(n),this.el.appendChild(s),this.annotationEls.push({el:s,position:t.position})}),this.invalidate()}projectAnnotations(){if(this.annotationEls.length===0)return;const e=this.el.clientWidth,t=this.el.clientHeight,n=e/2,s=t/2,r=this._tempVec;this.annotationEls.forEach(({el:a,position:o})=>{if(r.copy(o),r.project(this.activeCamera),r.z>1){a.style.display="none";return}const c=r.x*n+n,l=-(r.y*s)+s;a.style.display="",a.style.left=c+"px",a.style.top=l+"px"})}addAxesHelper(){this.axesDiv=document.createElement("div"),this.el.appendChild(this.axesDiv),this.axesDiv.classList.add("axes");const{clientWidth:e,clientHeight:t}=this.axesDiv;this.axesScene=new $u,this.axesCamera=new Bn(50,e/t,.1,10),this.axesScene.add(this.axesCamera),this.axesRenderer=new $g({alpha:!0}),this.axesRenderer.setPixelRatio(window.devicePixelRatio),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.axesCamera.up=this.defaultCamera.up,this.axesCorner=new wg(5),this.axesScene.add(this.axesCorner),this.axesDiv.appendChild(this.axesRenderer.domElement)}addGUI(){const e=window.innerWidth<=700,t=this.gui=new wM({autoPlace:!1,width:e?220:260,hideable:!0}),n=t.addFolder("Display");n.add(this.state,"background").onChange(()=>this.updateEnvironment()),n.add(this.state,"autoRotate").onChange(()=>this.updateDisplay()),n.add(this.state,"wireframe").onChange(()=>this.updateDisplay()),n.add(this.state,"skeleton").onChange(()=>this.updateDisplay()),n.add(this.state,"grid").onChange(()=>this.updateDisplay()),n.add(this.controls,"screenSpacePanning"),n.add(this.state,"pointSize",1,16).onChange(()=>this.updateDisplay()),n.add(this.state,"transparentBg").name("transparent bg").onChange(()=>this.updateBackground()),n.addColor(this.state,"bgColor").onChange(()=>this.updateBackground()),n.add({screenshot:()=>this.takeScreenshot()},"screenshot").name("Screenshot [P]"),n.add(this.state,"showInfo").name("model info").onChange(()=>this.updateModelInfo(this.content,this.clips)),n.add(this.state,"showLabels").name("mesh labels").onChange(()=>this.updateAnnotations());const p=t.addFolder("Lighting");p.add(this.state,"environment",Ql.map(w=>w.name)).onChange(()=>this.updateEnvironment()),[p.add(this.state,"toneMapping",{Linear:eu,"ACES Filmic":Xp}),p.add(this.state,"exposure",-10,10,.01),p.add(this.state,"punctualLights").listen(),p.add(this.state,"ambientIntensity",0,2),p.addColor(this.state,"ambientColor"),p.add(this.state,"directIntensity",0,4),p.addColor(this.state,"directColor")].forEach(w=>w.onChange(()=>this.updateLights())),this.animFolder=t.addFolder("Animation"),this.animFolder.domElement.style.display="none",this.animFolder.add(this.state,"playbackSpeed",0,1).onChange(w=>{this.mixer&&(this.mixer.timeScale=w)}),this.animFolder.add({playAll:()=>this.playAllClips()},"playAll"),this.morphFolder=t.addFolder("Morph Targets"),this.morphFolder.domElement.style.display="none",this.cameraFolder=t.addFolder("Cameras"),this.cameraFolder.domElement.style.display="none",t.addFolder("Agent").add(this.state,"followMode",{None:"none","Follow Mouse":"mouse","Follow Keystrokes":"keystrokes"}).name("follow mode");const _=t.addFolder("Performance"),x=document.createElement("li");this.stats.dom.style.position="static",x.appendChild(this.stats.dom),x.classList.add("gui-stats"),_.__ul.appendChild(x);const E=document.createElement("div");this.el.appendChild(E),E.classList.add("gui-wrap"),E.classList.add("gui-wrap--hidden"),E.appendChild(t.domElement),this._guiWrap=E;const S=document.createElement("button");S.className="gui-toggle",S.setAttribute("title","Toggle advanced controls"),S.setAttribute("aria-label","Toggle advanced controls"),S.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg><span class="gui-toggle__label">Controls</span>',S.addEventListener("click",()=>{const w=E.classList.toggle("gui-wrap--hidden");S.classList.toggle("gui-toggle--active",!w)}),this.el.appendChild(S),this._guiToggle=S,e?t.close():t.open()}updateGUI(){this.cameraFolder.domElement.style.display="none",this.morphCtrls.forEach(n=>n.remove()),this.morphCtrls.length=0,this.morphFolder.domElement.style.display="none",this.animCtrls.forEach(n=>n.remove()),this.animCtrls.length=0,this.animFolder.domElement.style.display="none";const e=[],t=[];if(this.content.traverse(n=>{n.geometry&&n.morphTargetInfluences&&t.push(n),n.isCamera&&(n.name=n.name||`VIEWER__camera_${e.length+1}`,e.push(n.name))}),e.length){this.cameraFolder.domElement.style.display="",this.cameraCtrl&&this.cameraCtrl.remove();const n=[Zl].concat(e);this.cameraCtrl=this.cameraFolder.add(this.state,"camera",n),this.cameraCtrl.onChange(s=>this.setCamera(s))}if(t.length&&(this.morphFolder.domElement.style.display="",t.forEach(n=>{if(n.morphTargetInfluences.length){const s=this.morphFolder.add({name:n.name||"Untitled"},"name");this.morphCtrls.push(s)}for(let s=0;s<n.morphTargetInfluences.length;s++){const r=this.morphFolder.add(n.morphTargetInfluences,s,0,1,.01).listen();Object.keys(n.morphTargetDictionary).forEach(a=>{a&&n.morphTargetDictionary[a]===s&&r.name(a)}),this.morphCtrls.push(r)}})),this.clips.length){this.animFolder.domElement.style.display="";const n=this.state.actionStates={};this.clips.forEach((s,r)=>{s.name=`${r+1}. ${s.name}`;let a;r===0?(n[s.name]=!0,a=this.mixer.clipAction(s),a.play()):n[s.name]=!1;const o=this.animFolder.add(n,s.name).listen();o.onChange(c=>{a=a||this.mixer.clipAction(s),a.setEffectiveTimeScale(1),c?a.play():a.stop(),this.invalidate()}),this.animCtrls.push(o)})}}setAnimationDefs(e){this.animationManager.setAnimationDefs(e),this.content&&this._setupAnimationPanel()}_setupAnimationPanel(){this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null);const e=this.animationManager.getAnimationDefs();if(e.length===0)return;let t=!1;if(this.content.traverse(s=>{s.isSkinnedMesh&&(t=!0)}),!t)return;const n=document.createElement("div");n.className="anim-panel",n.innerHTML='<div class="anim-panel__header"><span class="anim-panel__title">Animations</span><button class="anim-panel__stop" title="Stop all">⏹</button></div><div class="anim-panel__grid"></div>',this.el.appendChild(n),this._animPanelEl=n,this._renderAnimButtons(),this.animationManager.loadAll().then(()=>{if(this._renderAnimButtons(),!this.animationManager.currentName&&e.length>0){const s=e[0].name;this.animationManager.isLoaded(s)&&(this.animationManager.play(s),this._renderAnimButtons(),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop())}}),n.querySelector(".anim-panel__stop").addEventListener("click",()=>{this.animationManager.stopAll(),this._renderAnimButtons(),this.invalidate()}),this.animationManager.onChange=()=>{this._renderAnimButtons()}}_renderAnimButtons(){if(!this._animPanelEl)return;const e=this._animPanelEl.querySelector(".anim-panel__grid"),t=this.animationManager.getAnimationDefs(),n=this.animationManager.currentName,s={idle:"🧍",breathing:"🧍",standing:"🧍",walking:"🚶",walk:"🚶",running:"🏃",run:"🏃",waving:"👋",wave:"👋",dancing:"💃",dance:"💃",sitting:"🪑",sit:"🪑",jumping:"🦘",jump:"🦘",talking:"🗣️",talk:"🗣️",clapping:"👏",clap:"👏",punching:"👊",punch:"👊",kicking:"🦵",kick:"🦵"};e.innerHTML=t.map((r,a)=>{const o=this.animationManager.isLoaded(r.name),c=n===r.name,l=r.icon||s[r.name.toLowerCase()]||"▶",h=r.label||r.name.charAt(0).toUpperCase()+r.name.slice(1),u=a<9?a+1:"";return'<button class="anim-btn'+(c?" anim-btn--active":"")+(o?"":" anim-btn--loading")+'" data-anim="'+r.name+'" title="'+h+(u?" — press "+u:"")+'"'+(o?"":" disabled")+">"+(u?'<span class="anim-btn__key">'+u+"</span>":"")+'<span class="anim-btn__icon">'+l+'</span><span class="anim-btn__label">'+h+"</span></button>"}).join(""),e.querySelectorAll(".anim-btn:not([disabled])").forEach(r=>{r.addEventListener("click",()=>{const a=r.dataset.anim;this.animationManager.crossfadeTo(a),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop()})}),this._onAnimHotkey||(this._onAnimHotkey=r=>{if(r.target&&/INPUT|TEXTAREA|SELECT/.test(r.target.tagName)||r.metaKey||r.ctrlKey||r.altKey)return;const a=parseInt(r.key,10);if(!a||a<1||a>9)return;const c=this.animationManager.getAnimationDefs()[a-1];!c||!this.animationManager.isLoaded(c.name)||(this.animationManager.crossfadeTo(c.name),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop())},document.addEventListener("keydown",this._onAnimHotkey))}clear(){this.content&&(this.animationManager.detach(),this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null),this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[],this.scene.remove(this.content),this.content.traverse(e=>{e.geometry&&e.geometry.dispose()}),P0(this.content,e=>{for(const t in e)t!=="envMap"&&e[t]&&e[t].isTexture&&e[t].dispose()}),this.content=null,this._disposed||this.invalidate())}dispose(){if(!this._disposed){if(this._disposed=!0,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("resize",this._onResize,!1),window.removeEventListener("keydown",this._onKeyDown),this._onAnimHotkey&&(document.removeEventListener("keydown",this._onAnimHotkey),this._onAnimHotkey=null),this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=null),this.clear(),this.mixer){this.mixer.stopAllAction();const e=this.mixer.getRoot();e&&this.mixer.uncacheRoot(e),this.mixer=null}this.clips=[],this.animationManager.dispose(),this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null),this.skeletonHelpers.length&&(this.skeletonHelpers.forEach(e=>{this.scene.remove(e),e.dispose?.()}),this.skeletonHelpers.length=0),this.gridHelper&&(this.scene.remove(this.gridHelper),this.gridHelper.geometry?.dispose(),this.gridHelper.material?.dispose(),this.gridHelper=null),this.axesHelper&&(this.scene.remove(this.axesHelper),this.axesHelper.geometry?.dispose(),this.axesHelper.material?.dispose(),this.axesHelper=null),this.axesCorner&&(this.axesScene?.remove(this.axesCorner),this.axesCorner.geometry?.dispose(),this.axesCorner.material?.dispose(),this.axesCorner=null),this.lights.forEach(e=>e.parent?.remove(e)),this.lights=[],this.annotationEls.length&&(this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[]),this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.gui&&(this.gui.destroy(),this.gui=null),this._guiWrap&&(this._guiWrap.remove(),this._guiWrap=null),this._guiToggle&&(this._guiToggle.remove(),this._guiToggle=null),this.stats?.dom&&this.stats.dom.remove(),this.controls&&(this._onControlsChange&&(this.controls.removeEventListener("change",this._onControlsChange),this._onControlsChange=null),this.controls.dispose(),this.controls=null),this._loadedEnvironment&&(this._loadedEnvironment.dispose(),this._loadedEnvironment=null),this.neutralEnvironment&&(this.neutralEnvironment.dispose(),this.neutralEnvironment=null),this.scene&&(this.scene.environment=null,this.scene.background=null),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null),this.axesRenderer&&(this.axesRenderer.dispose(),this.axesRenderer.forceContextLoss?.(),this.axesRenderer.domElement?.remove(),this.axesRenderer=null),this.axesDiv&&(this.axesDiv.remove(),this.axesDiv=null),this.axesScene=null,this.axesCamera=null,this.renderer&&(this.renderer.dispose(),this.renderer.forceContextLoss?.(),this.renderer.domElement?.remove(),window.renderer===this.renderer&&(window.renderer=null),this.renderer=null),this.scene=null,this.content=null,this.activeCamera=null,this.defaultCamera=null,this._afterAnimateHooks=null}}}class _R{constructor({model:e="claude-opus-4-6",proxyURL:t,apiKey:n,agentId:s,apiOrigin:r,temperature:a=.7,maxTokens:o=4096,thinking:c="auto"}={}){this.model=e,this.apiKey=n,this.temperature=a,this.maxTokens=o,this.thinking=c,t?this.proxyURL=t:!n&&s&&r?this.proxyURL=`${r}/api/llm/anthropic?agent=${encodeURIComponent(s)}`:this.proxyURL=null}async complete({system:e,messages:t,tools:n}){const s={model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,system:e,messages:t};n&&n.length&&(s.tools=n),this.thinking==="always"&&(s.thinking={type:"enabled",budget_tokens:2048});const r=this.proxyURL||"https://api.anthropic.com/v1/messages",a={"content-type":"application/json"};this.apiKey&&(a["x-api-key"]=this.apiKey,a["anthropic-version"]="2023-06-01",a["anthropic-dangerous-direct-browser-access"]="true");const o=await fetch(r,{method:"POST",headers:a,body:JSON.stringify(s)});if(!o.ok){const l=await o.text();throw new Error(`Anthropic ${o.status}: ${l}`)}const c=await o.json();return this._normalize(c)}_normalize(e){const t={text:"",toolCalls:[],thinking:"",stopReason:e.stop_reason};for(const n of e.content||[])n.type==="text"?t.text+=n.text:n.type==="thinking"?t.thinking+=n.thinking||"":n.type==="tool_use"&&t.toolCalls.push({id:n.id,name:n.name,input:n.input});return t}formatToolResults(e){return{role:"user",content:e.map(t=>({type:"tool_result",tool_use_id:t.id,content:typeof t.output=="string"?t.output:JSON.stringify(t.output),is_error:!!t.isError}))}}formatAssistantWithToolCalls(e,t){const n=[];e&&n.push({type:"text",text:e});for(const s of t)n.push({type:"tool_use",id:s.id,name:s.name,input:s.input});return{role:"assistant",content:n}}}class wR{async complete(){return{text:"",toolCalls:[],stopReason:"end_turn"}}formatToolResults(){return{role:"user",content:[]}}formatAssistantWithToolCalls(e){return{role:"assistant",content:e||""}}}function vR(i={}){const e=i.provider||"anthropic";if(e==="anthropic")return new _R(i);if(e==="none")return new wR;throw new Error(`Unsupported provider: ${e}. Supported: anthropic, none`)}class CR{constructor({voiceId:e="default",rate:t=1,pitch:n=1,lang:s="en-US"}={}){this.voiceId=e,this.rate=t,this.pitch=n,this.lang=s,this._queue=[],this._speaking=!1}async speak(e,{onStart:t,onEnd:n}={}){if("speechSynthesis"in window)return new Promise(s=>{const r=new SpeechSynthesisUtterance(e);r.rate=this.rate,r.pitch=this.pitch,r.lang=this.lang;const a=this._pickVoice();a&&(r.voice=a),r.onstart=()=>{this._speaking=!0,t?.()},r.onend=()=>{this._speaking=!1,n?.(),s()},r.onerror=()=>{this._speaking=!1,s()},window.speechSynthesis.speak(r)})}cancel(){"speechSynthesis"in window&&window.speechSynthesis.cancel(),this._speaking=!1}get speaking(){return this._speaking}_pickVoice(){if(!("speechSynthesis"in window))return null;const e=window.speechSynthesis.getVoices();if(this.voiceId&&this.voiceId!=="default"){const t=e.find(n=>n.name===this.voiceId||n.voiceURI===this.voiceId);if(t)return t}return e.find(t=>t.lang?.startsWith(this.lang.slice(0,2)))||null}}class IR{constructor({language:e="en-US",continuous:t=!1,interimResults:n=!0}={}){this.language=e,this.continuous=t,this.interimResults=n,this._recognition=null,this._listening=!1}_ensure(){if(this._recognition)return this._recognition;const e=window.SpeechRecognition||window.webkitSpeechRecognition;if(!e)return null;const t=new e;return t.lang=this.language,t.continuous=this.continuous,t.interimResults=this.interimResults,this._recognition=t,t}async listen({onInterim:e,onFinal:t}={}){const n=this._ensure();if(!n)throw new Error("SpeechRecognition unavailable in this browser");return new Promise((s,r)=>{let a="";n.onresult=o=>{for(let c=o.resultIndex;c<o.results.length;c++){const l=o.results[c],h=l[0].transcript;l.isFinal?(a+=h,t?.(h)):e?.(h)}},n.onerror=o=>{this._listening=!1,r(o.error)},n.onend=()=>{this._listening=!1,s(a.trim())},this._listening=!0;try{n.start()}catch(o){this._listening=!1,r(o)}})}stop(){this._recognition&&this._listening&&this._recognition.stop()}get listening(){return this._listening}}class SR{constructor({voiceId:e,modelId:t="eleven_turbo_v2_5",apiKey:n=null,proxyURL:s=null,rate:r=1,pitch:a=1,lang:o="en-US",stability:c=.5,similarityBoost:l=.75,useSpeakerBoost:h=!0}={}){if(!e)throw new Error("ElevenLabsTTS requires voiceId");this.voiceId=e,this.modelId=t,this.apiKey=n,this.proxyURL=s,this.rate=r,this.pitch=a,this.lang=o,this.stability=c,this.similarityBoost=l,this.useSpeakerBoost=h,this._speaking=!1,this._abort=null,this._audio=null,this._mediaSourceURL=null,this._onEnd=null}async speak(e,{onStart:t,onEnd:n}={}){if(this.cancel(),!e)return;this._abort=new AbortController,this._speaking=!0;const s=this.proxyURL||`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(this.voiceId)}/stream`,r={"content-type":"application/json",accept:"audio/mpeg"};!this.proxyURL&&this.apiKey&&(r["xi-api-key"]=this.apiKey);const a=Math.min(1.5,Math.max(.5,this.rate)),o=Math.min(1,Math.max(0,(a-.5)/1)),c=JSON.stringify({text:e,model_id:this.modelId,voice_settings:{stability:this.stability,similarity_boost:this.similarityBoost,style:o,use_speaker_boost:this.useSpeakerBoost},voiceId:this.voiceId,modelId:this.modelId});let l;try{l=await fetch(s,{method:"POST",headers:r,body:c,signal:this._abort.signal})}catch(d){if(this._speaking=!1,d.name==="AbortError")return;throw d}if(!l.ok)throw this._speaking=!1,new Error(`ElevenLabs TTS HTTP ${l.status}`);const h=typeof MediaSource<"u"&&MediaSource.isTypeSupported("audio/mpeg"),u=d=>{this._startedFired||(this._startedFired=!0,d?.())};return this._startedFired=!1,new Promise(d=>{this._onEnd=()=>{this._speaking=!1,this._cleanupAudio(),n?.(),this._onEnd=null,d()};const f=()=>{this._onEnd&&this._onEnd()};h&&l.body?this._playStreamingMSE(l.body,()=>u(t),f):this._playBuffered(l,()=>u(t),f)})}cancel(){if(this._abort){try{this._abort.abort()}catch{}this._abort=null}this._cleanupAudio(),this._speaking=!1,this._onEnd&&this._onEnd()}get speaking(){return this._speaking}_playStreamingMSE(e,t,n){const s=new MediaSource;this._mediaSourceURL=URL.createObjectURL(s);const r=new Audio(this._mediaSourceURL);this._audio=r,r.preload="auto",r.addEventListener("playing",t,{once:!0}),r.addEventListener("ended",()=>this._onEnd?.(),{once:!0}),r.addEventListener("error",()=>n?.(),{once:!0}),s.addEventListener("sourceopen",async()=>{let a;try{a=s.addSourceBuffer("audio/mpeg")}catch{n?.();return}const o=e.getReader(),c=[];let l=!0;const h=()=>{if(!l||a.updating)return;const u=c.shift();if(u)try{a.appendBuffer(u)}catch{l=!1;try{s.endOfStream()}catch{}}};a.addEventListener("updateend",h);try{for(;l;){const{value:u,done:d}=await o.read();if(d){l=!1;const f=()=>{if(a.updating||c.length)setTimeout(f,30);else try{s.endOfStream()}catch{}};f();break}c.push(u),h()}}catch(u){u.name!=="AbortError"&&n?.()}}),r.play().catch(n)}async _playBuffered(e,t,n){try{const s=await e.blob(),r=URL.createObjectURL(s);this._mediaSourceURL=r;const a=new Audio(r);this._audio=a,a.addEventListener("playing",t,{once:!0}),a.addEventListener("ended",()=>this._onEnd?.(),{once:!0}),a.addEventListener("error",()=>n?.(),{once:!0}),await a.play()}catch(s){s.name!=="AbortError"&&n?.()}}_cleanupAudio(){if(this._audio){try{this._audio.pause()}catch{}this._audio.src="",this._audio=null}if(this._mediaSourceURL){try{URL.revokeObjectURL(this._mediaSourceURL)}catch{}this._mediaSourceURL=null}this._startedFired=!1}}function MR(i={}){const e=i.provider||"browser";if(e==="none")return null;if(e==="browser")return new CR(i);if(e==="elevenlabs")return new SR(i);throw new Error(`TTS provider "${e}" not implemented yet`)}function BR(i={}){const e=i.provider||"browser";if(e==="none")return null;if(e==="browser")return new IR(i);throw new Error(`STT provider "${e}" not implemented yet`)}const X0=[{name:"wave",description:"Wave at the user. Use for greetings, farewells, or acknowledgments.",input_schema:{type:"object",properties:{duration_ms:{type:"integer",minimum:500,maximum:5e3,default:1500}}}},{name:"lookAt",description:"Direct the agent's gaze toward a target.",input_schema:{type:"object",properties:{target:{type:"string",enum:["user","camera","center"],description:"Where to look"}},required:["target"]}},{name:"play_clip",description:"Play a named animation clip from the loaded body.",input_schema:{type:"object",properties:{name:{type:"string"},loop:{type:"boolean",default:!1},fade_ms:{type:"integer",default:200}},required:["name"]}},{name:"setExpression",description:"Set facial expression via morph target preset.",input_schema:{type:"object",properties:{preset:{type:"string",enum:["neutral","happy","sad","surprised","confused","focused"]},intensity:{type:"number",minimum:0,maximum:1,default:1}},required:["preset"]}},{name:"speak",description:"Say something out loud via TTS. Use this instead of plain text when voice is on.",input_schema:{type:"object",properties:{text:{type:"string"}},required:["text"]}},{name:"remember",description:"Save a durable memory about the user, a feedback rule, a project fact, or a reference.",input_schema:{type:"object",properties:{key:{type:"string",description:'short snake_case filename, e.g. "user_role"'},name:{type:"string"},description:{type:"string"},type:{type:"string",enum:["user","feedback","project","reference"]},body:{type:"string"}},required:["key","name","description","type","body"]}}],TR=[{name:"observe_agents",description:"List the other agents currently sharing this stage, with their names and positions.",input_schema:{type:"object",properties:{}}},{name:"say_to_agent",description:"Send a message to another agent on the same stage. The target agent will receive it as a user turn and reply in their own chat chrome.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"Target agent id as returned by observe_agents."},text:{type:"string"}},required:["agentId","text"]}}],RR={async wave(i,e){const t=i.duration_ms||1500;return await e.viewer.playAnimationByHint?.("wave",{duration:t}),e.memory.note("waved",{duration_ms:t}),{ok:!0}},async lookAt(i,e){const t=i.target||"user";return e.viewer.lookAt?.(t),{ok:!0,target:t}},async play_clip(i,e){const{name:t,loop:n=!1,fade_ms:s=200}=i,r=e.viewer.resolveAnimationSlot?.(t)??t;return e.viewer.playClipByName?.(r,{loop:n,fade_ms:s})?{ok:!0,name:t,resolved:r}:(r!==t&&console.warn(`[play_clip] slot "${t}" → "${r}" not found in library`),{ok:!1,error:`No clip named "${r}"`})},async setExpression(i,e){const{preset:t,intensity:n=1}=i;return e.viewer.setExpression?.(t,n),{ok:!0,preset:t}},async speak(i,e){return await e.speak(i.text),{ok:!0}},async remember(i,e){const{key:t,name:n,description:s,type:r,body:a}=i;return e.memory.write(t,{name:n,description:s,type:r,body:a}),{ok:!0,saved:t}},async observe_agents(i,e){return e.stage?{ok:!0,agents:e.stage.getAgents().filter(n=>n.agentId!==e.agentId).map(({agentId:n,name:s,position:r})=>({agentId:n,name:s,position:r}))}:{ok:!1,error:"not on a stage"}},async say_to_agent(i,e){if(!e.stage)return{ok:!1,error:"not on a stage"};const{agentId:t,text:n}=i;if(!t||!n)return{ok:!1,error:"agentId and text required"};const s=e.agentId||"anon";return e.stage.broadcast(s,{kind:"direct",to:t,text:n}),e.stage.routeMessage(s,t,n)}},FR=8;class Y0 extends EventTarget{constructor({manifest:e,viewer:t,memory:n,skills:s,providerConfig:r={},voiceConfig:a={},stage:o=null,agentId:c=null}={}){super(),this.manifest=e||{},this.viewer=t,this.memory=n,this.skills=s,this.stage=o,this.agentId=c,this.provider=vR({...this.manifest.brain,...r}),this.tts=MR({...this.manifest.voice?.tts,...a.tts}),this.stt=BR({...this.manifest.voice?.stt,...a.stt}),this.messages=[],this._busy=!1}get systemPrompt(){const e=[];return this.manifest.instructions&&e.push(this.manifest.instructions),this.memory&&e.push(`
+`)}let Kd=null,FM;function NM(){return Kd===null&&(Kd=new Intl.Segmenter(FM,{granularity:"word"})),Kd}const DM=new RegExp("\\p{Script=Arabic}","u"),Gl=new RegExp("\\p{M}","u"),Bm=new RegExp("\\p{Nd}","u");function Tm(i){return DM.test(i)}function Rm(i){return i>=19968&&i<=40959||i>=13312&&i<=19903||i>=131072&&i<=173791||i>=173824&&i<=177983||i>=177984&&i<=178207||i>=178208&&i<=183983||i>=183984&&i<=191471||i>=191472&&i<=192093||i>=194560&&i<=195103||i>=196608&&i<=201551||i>=201552&&i<=205743||i>=205744&&i<=210041||i>=63744&&i<=64255||i>=12288&&i<=12351||i>=12352&&i<=12447||i>=12448&&i<=12543||i>=44032&&i<=55215||i>=65280&&i<=65519}function _r(i){for(let e=0;e<i.length;e++){const t=i.charCodeAt(e);if(!(t<12288)){if(t>=55296&&t<=56319&&e+1<i.length){const n=i.charCodeAt(e+1);if(n>=56320&&n<=57343){const s=(t-55296<<10)+(n-56320)+65536;if(Rm(s))return!0;e++;continue}}if(Rm(t))return!0}}return!1}function LM(i){const e=zl(i);return e!==null&&(jd.has(e)||wr.has(e))}const PM=new Set([" "," ","⁠","\uFEFF"]);function kM(i){return _r(i)}function UM(i){const e=zl(i);return e!==null&&PM.has(e)}function OM(i){return!LM(i)&&!UM(i)}const jd=new Set([",",".","!",":",";","?","、","。","・",")","〕","〉","》","」","』","】","〗","〙","〛","ー","々","〻","ゝ","ゞ","ヽ","ヾ"]),Hl=new Set(['"',"(","[","{","“","‘","«","‹","(","〔","〈","《","「","『","【","〖","〘","〚"]),Xd=new Set(["'","’"]),wr=new Set([".",",","!","?",":",";","،","؛","؟","।","॥","၊","။","၌","၍","၏",")","]","}","%",'"',"”","’","»","›","…"]),QM=new Set([":",".","،","؛"]),GM=new Set(["၏"]),HM=new Set(["”","’","»","›","」","』","】","》","〉","〕",")"]);function zM(i){if(Yd(i))return!0;let e=!1;for(const t of i){if(wr.has(t)){e=!0;continue}if(!(e&&Gl.test(t)))return!1}return e}function VM(i){for(const e of i)if(!jd.has(e)&&!wr.has(e))return!1;return i.length>0}function WM(i){if(Yd(i))return!0;for(const e of i)if(!Hl.has(e)&&!Xd.has(e)&&!Gl.test(e))return!1;return i.length>0}function Yd(i){let e=!1;for(const t of i)if(!(t==="\\"||Gl.test(t))){if(Hl.has(t)||wr.has(t)||Xd.has(t)){e=!0;continue}return!1}return e}function Fm(i,e){const t=e-1;if(t<=0)return Math.max(t,0);const n=i.charCodeAt(t);if(n<56320||n>57343)return t;const s=t-1;if(s<0)return t;const r=i.charCodeAt(s);return r>=55296&&r<=56319?s:t}function zl(i){if(i.length===0)return null;const e=Fm(i,i.length);return i.slice(e)}function qM(i){const e=Array.from(i);let t=e.length;for(;t>0;){const n=e[t-1];if(Gl.test(n)){t--;continue}if(Hl.has(n)||Xd.has(n)){t--;continue}break}return t<=0||t===e.length?null:{head:e.slice(0,t).join(""),tail:e.slice(t).join("")}}function KM(i,e,t){return t==="text"&&!e&&i.length===1&&i!=="-"&&i!=="—"?i:null}function Nm(i,e,t,n){const s=e[n],r=i[n];if(s==null)return r;const a=t[n];if(r.length===a)return r;const o=s.repeat(a);return i[n]=o,o}function Dm(i,e){return i&&e!==null&&QM.has(e)}function jM(i){const e=zl(i);return e!==null&&GM.has(e)}function XM(i){if(i.length<2||i[0]!==" ")return null;const e=i.slice(1);return new RegExp("^\\p{M}+$","u").test(e)?{space:" ",marks:e}:null}function Jd(i){let e=i.length;for(;e>0;){const t=Fm(i,e),n=i.slice(t,e);if(HM.has(n))return!0;if(!wr.has(n))return!1;e=t}return!1}function YM(i,e){if(e.preserveOrdinarySpaces||e.preserveHardBreaks){if(i===" ")return"preserved-space";if(i===" ")return"tab";if(e.preserveHardBreaks&&i===`
+`)return"hard-break"}return i===" "?"space":i===" "||i===" "||i==="⁠"||i==="\uFEFF"?"glue":i==="​"?"zero-width-break":i==="­"?"soft-hyphen":"text"}const JM=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function hi(i){return i.length===1?i[0]:i.join("")}function ZM(i,e){const t=[];for(let n=i.length-1;n>=0;n--)t.push(i[n]);return t.push(e),hi(t)}function $M(i,e,t,n){if(!JM.test(i))return[{text:i,isWordLike:e,kind:"text",start:t}];const s=[];let r=null,a=[],o=t,c=!1,l=0;for(const h of i){const u=YM(h,n),d=u==="text"&&e;if(r!==null&&u===r&&d===c){a.push(h),l+=h.length;continue}r!==null&&s.push({text:hi(a),isWordLike:c,kind:r,start:o}),r=u,a=[h],o=t+l,c=d,l+=h.length}return r!==null&&s.push({text:hi(a),isWordLike:c,kind:r,start:o}),s}function Zd(i){return i==="space"||i==="preserved-space"||i==="zero-width-break"||i==="hard-break"}const eB=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function tB(i,e){const t=i.texts[e];return t.startsWith("www.")?!0:eB.test(t)&&e+1<i.len&&i.kinds[e+1]==="text"&&i.texts[e+1]==="//"}function nB(i){return i.includes("?")&&(i.includes("://")||i.startsWith("www."))}function iB(i){const e=i.texts.slice(),t=i.isWordLike.slice(),n=i.kinds.slice(),s=i.starts.slice();for(let a=0;a<i.len;a++){if(n[a]!=="text"||!tB(i,a))continue;const o=[e[a]];let c=a+1;for(;c<i.len&&!Zd(n[c]);){o.push(e[c]),t[a]=!0;const l=e[c].includes("?");if(n[c]="text",e[c]="",c++,l)break}e[a]=hi(o)}let r=0;for(let a=0;a<e.length;a++){const o=e[a];o.length!==0&&(r!==a&&(e[r]=o,t[r]=t[a],n[r]=n[a],s[r]=s[a]),r++)}return e.length=r,t.length=r,n.length=r,s.length=r,{len:r,texts:e,isWordLike:t,kinds:n,starts:s}}function sB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r];if(e.push(a),t.push(i.isWordLike[r]),n.push(i.kinds[r]),s.push(i.starts[r]),!nB(a))continue;const o=r+1;if(o>=i.len||Zd(i.kinds[o]))continue;const c=[],l=i.starts[o];let h=o;for(;h<i.len&&!Zd(i.kinds[h]);)c.push(i.texts[h]),h++;c.length>0&&(e.push(hi(c)),t.push(!0),n.push("text"),s.push(l),r=h-1)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}const rB=new Set([":","-","/","×",",",".","+","–","—"]),Lm=/^[A-Za-z0-9_]+[,:;]*$/,Pm=/[,:;]+$/;function km(i){for(const e of i)if(Bm.test(e))return!0;return!1}function Vl(i){if(i.length===0)return!1;for(const e of i)if(!(Bm.test(e)||rB.has(e)))return!1;return!0}function aB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r],o=i.kinds[r];if(o==="text"&&Vl(a)&&km(a)){const c=[a];let l=r+1;for(;l<i.len&&i.kinds[l]==="text"&&Vl(i.texts[l]);)c.push(i.texts[l]),l++;e.push(hi(c)),t.push(!0),n.push("text"),s.push(i.starts[r]),r=l-1;continue}e.push(a),t.push(i.isWordLike[r]),n.push(o),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function oB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r],o=i.kinds[r],c=i.isWordLike[r];if(o==="text"&&c&&Lm.test(a)){const l=[a];let h=Pm.test(a),u=r+1;for(;h&&u<i.len&&i.kinds[u]==="text"&&i.isWordLike[u]&&Lm.test(i.texts[u]);){const d=i.texts[u];l.push(d),h=Pm.test(d),u++}e.push(hi(l)),t.push(!0),n.push("text"),s.push(i.starts[r]),r=u-1;continue}e.push(a),t.push(c),n.push(o),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function cB(i){const e=[],t=[],n=[],s=[];for(let r=0;r<i.len;r++){const a=i.texts[r];if(i.kinds[r]==="text"&&a.includes("-")){const o=a.split("-");let c=o.length>1;for(let l=0;l<o.length;l++){const h=o[l];if(!c)break;(h.length===0||!km(h)||!Vl(h))&&(c=!1)}if(c){let l=0;for(let h=0;h<o.length;h++){const u=o[h],d=h<o.length-1?`${u}-`:u;e.push(d),t.push(!0),n.push("text"),s.push(i.starts[r]+l),l+=d.length}continue}}e.push(a),t.push(i.isWordLike[r]),n.push(i.kinds[r]),s.push(i.starts[r])}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function lB(i){const e=[],t=[],n=[],s=[];let r=0;for(;r<i.len;){const a=[i.texts[r]];let o=i.isWordLike[r],c=i.kinds[r],l=i.starts[r];if(c==="glue"){const h=[a[0]],u=l;for(r++;r<i.len&&i.kinds[r]==="glue";)h.push(i.texts[r]),r++;const d=hi(h);if(r<i.len&&i.kinds[r]==="text")a[0]=d,a.push(i.texts[r]),o=i.isWordLike[r],c="text",l=u,r++;else{e.push(d),t.push(!1),n.push("glue"),s.push(u);continue}}else r++;if(c==="text")for(;r<i.len&&i.kinds[r]==="glue";){const h=[];for(;r<i.len&&i.kinds[r]==="glue";)h.push(i.texts[r]),r++;const u=hi(h);if(r<i.len&&i.kinds[r]==="text"){a.push(u,i.texts[r]),o=o||i.isWordLike[r],r++;continue}a.push(u)}e.push(hi(a)),t.push(o),n.push(c),s.push(l)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function hB(i){const e=i.texts.slice(),t=i.isWordLike.slice(),n=i.kinds.slice(),s=i.starts.slice();for(let r=0;r<e.length-1;r++){if(n[r]!=="text"||n[r+1]!=="text"||!_r(e[r])||!_r(e[r+1]))continue;const a=qM(e[r]);a!==null&&(e[r]=a.head,e[r+1]=a.tail+e[r+1],s[r+1]=s[r]+a.head.length)}return{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function Um(i,e,t){const n=NM();let s=0;const r=[],a=[],o=[],c=[],l=[],h=[],u=[],d=[],f=[],p=[],m=[],g=[];for(const w of n.segment(i))for(const I of $M(w.segment,w.isWordLike??!1,w.index,t)){let O=function(){h[D]!==null&&(a[D]=[Nm(r,h,u,D)],h[D]=null),a[D].push(I.text),o[D]=o[D]||I.isWordLike,d[D]=d[D]||v,f[D]=f[D]||F,p[D]=q,m[D]=$,g[D]=Dm(f[D],K)};const T=I.kind==="text",C=KM(I.text,I.isWordLike,I.kind),v=_r(I.text),F=Tm(I.text),K=zl(I.text),q=Jd(I.text),$=jM(I.text),D=s-1;e.carryCJKAfterClosingQuote&&T&&s>0&&c[D]==="text"&&v&&d[D]&&p[D]||T&&s>0&&c[D]==="text"&&VM(I.text)&&d[D]||T&&s>0&&c[D]==="text"&&m[D]?O():T&&s>0&&c[D]==="text"&&I.isWordLike&&F&&g[D]?(O(),o[D]=!0):C!==null&&s>0&&c[D]==="text"&&h[D]===C?u[D]=(u[D]??1)+1:T&&!I.isWordLike&&s>0&&c[D]==="text"&&(zM(I.text)||I.text==="-"&&o[D])?O():(r[s]=I.text,a[s]=[I.text],o[s]=I.isWordLike,c[s]=I.kind,l[s]=I.start,h[s]=C,u[s]=C===null?0:1,d[s]=v,f[s]=F,p[s]=q,m[s]=$,g[s]=Dm(F,K),s++)}for(let w=0;w<s;w++){if(h[w]!==null){r[w]=Nm(r,h,u,w);continue}r[w]=hi(a[w])}for(let w=1;w<s;w++)c[w]==="text"&&!o[w]&&Yd(r[w])&&c[w-1]==="text"&&(r[w-1]+=r[w],o[w-1]=o[w-1]||o[w],r[w]="");const A=Array.from({length:s},()=>null);let _=-1;for(let w=s-1;w>=0;w--){const I=r[w];if(I.length!==0){if(c[w]==="text"&&!o[w]&&WM(I)&&_>=0&&c[_]==="text"){const T=A[_]??[];T.push(I),A[_]=T,l[_]=l[w],r[w]="";continue}_=w}}for(let w=0;w<s;w++){const I=A[w];I!=null&&(r[w]=ZM(I,r[w]))}let x=0;for(let w=0;w<s;w++){const I=r[w];I.length!==0&&(x!==w&&(r[x]=I,o[x]=o[w],c[x]=c[w],l[x]=l[w]),x++)}r.length=x,o.length=x,c.length=x,l.length=x;const E=lB({len:x,texts:r,isWordLike:o,kinds:c,starts:l}),S=hB(oB(cB(aB(sB(iB(E))))));for(let w=0;w<S.len-1;w++){const I=XM(S.texts[w]);I!==null&&(S.kinds[w]!=="space"&&S.kinds[w]!=="preserved-space"||S.kinds[w+1]!=="text"||!Tm(S.texts[w+1])||(S.texts[w]=I.space,S.isWordLike[w]=!1,S.kinds[w]=S.kinds[w]==="preserved-space"?"preserved-space":"space",S.texts[w+1]=I.marks+S.texts[w+1],S.starts[w+1]=S.starts[w]+I.space.length))}return S}function uB(i,e){if(i.len===0)return[];if(!e.preserveHardBreaks)return[{startSegmentIndex:0,endSegmentIndex:i.len,consumedEndSegmentIndex:i.len}];const t=[];let n=0;for(let s=0;s<i.len;s++)i.kinds[s]==="hard-break"&&(t.push({startSegmentIndex:n,endSegmentIndex:s,consumedEndSegmentIndex:s+1}),n=s+1);return n<i.len&&t.push({startSegmentIndex:n,endSegmentIndex:i.len,consumedEndSegmentIndex:i.len}),t}function dB(i){if(i.len<=1)return i;const e=[],t=[],n=[],s=[];let r=null,a=!1,o=0,c=!1,l=!1;function h(){r!==null&&(e.push(hi(r)),t.push(a),n.push("text"),s.push(o),r=null)}for(let u=0;u<i.len;u++){const d=i.texts[u],f=i.kinds[u],p=i.isWordLike[u],m=i.starts[u];if(f==="text"){const g=kM(d),A=OM(d);if(r!==null&&c&&l){r.push(d),a=a||p,c=c||g,l=A;continue}h(),r=[d],a=p,o=m,c=g,l=A;continue}h(),e.push(d),t.push(p),n.push(f),s.push(m)}return h(),{len:e.length,texts:e,isWordLike:t,kinds:n,starts:s}}function fB(i,e,t="normal",n="normal"){const s=BM(t),r=s.mode==="pre-wrap"?RM(i):TM(i);if(r.length===0)return{normalized:r,chunks:[],len:0,texts:[],isWordLike:[],kinds:[],starts:[]};const a=n==="keep-all"?dB(Um(r,e,s)):Um(r,e,s);return{normalized:r,chunks:uB(a,s),...a}}let Ba=null;const Om=new Map;let Ta=null;const pB=96,AB=new RegExp("\\p{Emoji_Presentation}","u"),gB=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u;let $d=null;const Qm=new Map;function ef(){if(Ba!==null)return Ba;if(typeof OffscreenCanvas<"u")return Ba=new OffscreenCanvas(1,1).getContext("2d"),Ba;if(typeof document<"u")return Ba=document.createElement("canvas").getContext("2d"),Ba;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function mB(i){let e=Om.get(i);return e||(e=new Map,Om.set(i,e)),e}function Vs(i,e){let t=e.get(i);return t===void 0&&(t={width:ef().measureText(i).width,containsCJK:_r(i)},e.set(i,t)),t}function Ra(){if(Ta!==null)return Ta;if(typeof navigator>"u")return Ta={lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,preferPrefixWidthsForBreakableRuns:!1,preferEarlySoftHyphenBreak:!1},Ta;const i=navigator.userAgent,t=navigator.vendor==="Apple Computer, Inc."&&i.includes("Safari/")&&!i.includes("Chrome/")&&!i.includes("Chromium/")&&!i.includes("CriOS/")&&!i.includes("FxiOS/")&&!i.includes("EdgiOS/"),n=i.includes("Chrome/")||i.includes("Chromium/")||i.includes("CriOS/")||i.includes("Edg/");return Ta={lineFitEpsilon:t?1/64:.005,carryCJKAfterClosingQuote:n,preferPrefixWidthsForBreakableRuns:t,preferEarlySoftHyphenBreak:t},Ta}function xB(i){const e=i.match(/(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function Gm(){return $d===null&&($d=new Intl.Segmenter(void 0,{granularity:"grapheme"})),$d}function bB(i){return AB.test(i)||i.includes("️")}function EB(i){return gB.test(i)}function yB(i,e){let t=Qm.get(i);if(t!==void 0)return t;const n=ef();n.font=i;const s=n.measureText("😀").width;if(t=0,s>e+.5&&typeof document<"u"&&document.body!==null){const r=document.createElement("span");r.style.font=i,r.style.display="inline-block",r.style.visibility="hidden",r.style.position="absolute",r.textContent="😀",document.body.appendChild(r);const a=r.getBoundingClientRect().width;document.body.removeChild(r),s-a>.5&&(t=s-a)}return Qm.set(i,t),t}function _B(i){let e=0;const t=Gm();for(const n of t.segment(i))bB(n.segment)&&e++;return e}function wB(i,e){return e.emojiCount===void 0&&(e.emojiCount=_B(i)),e.emojiCount}function vr(i,e,t){return t===0?e.width:e.width-wB(i,e)*t}function vB(i,e,t,n,s){if(e.breakableFitAdvances!==void 0)return e.breakableFitAdvances;const r=Gm(),a=[];for(const h of r.segment(i))a.push(h.segment);if(a.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(s==="sum-graphemes"){const h=[];for(const u of a){const d=Vs(u,t);h.push(vr(u,d,n))}return e.breakableFitAdvances=h,e.breakableFitAdvances}if(s==="pair-context"||a.length>pB){const h=[];let u=null,d=0;for(const f of a){const p=Vs(f,t),m=vr(f,p,n);if(u===null)h.push(m);else{const g=u+f,A=Vs(g,t);h.push(vr(g,A,n)-d)}u=f,d=m}return e.breakableFitAdvances=h,e.breakableFitAdvances}const o=[];let c="",l=0;for(const h of a){c+=h;const u=Vs(c,t),d=vr(c,u,n);o.push(d-l),l=d}return e.breakableFitAdvances=o,e.breakableFitAdvances}function CB(i,e){const t=ef();t.font=i;const n=mB(i),s=xB(i),r=e?yB(i,s):0;return{cache:n,fontSize:s,emojiCorrection:r}}function IB(i,e){for(;e<i.widths.length;){const t=i.kinds[e];if(t!=="space"&&t!=="zero-width-break"&&t!=="soft-hyphen")break;e++}return e}function Hm(i,e){if(e<=0)return 0;const t=i%e;return Math.abs(t)<=1e-6?e:e-t}function zm(i,e,t,n,s){let r=0,a=e;for(;r<i.length;){const o=a+i[r];if((r+1<i.length?o+s:o)>t+n)break;a=o,r++}return{fitCount:r,fittedWidth:a}}function SB(i,e){let t=0,n=i.chunks.length;for(;t<n;){const s=Math.floor((t+n)/2);e<i.chunks[s].consumedEndSegmentIndex?n=s:t=s+1}return t<i.chunks.length?t:-1}function Vm(i,e,t){let n=t.segmentIndex;if(t.graphemeIndex>0)return e;const s=i.chunks[e];if(s.startSegmentIndex===s.endSegmentIndex&&n===s.startSegmentIndex)return t.segmentIndex=n,t.graphemeIndex=0,e;for(n<s.startSegmentIndex&&(n=s.startSegmentIndex);n<s.endSegmentIndex;){const r=i.kinds[n];if(r!=="space"&&r!=="zero-width-break"&&r!=="soft-hyphen")return t.segmentIndex=n,t.graphemeIndex=0,e;n++}return s.consumedEndSegmentIndex>=i.widths.length?-1:(t.segmentIndex=s.consumedEndSegmentIndex,t.graphemeIndex=0,e+1)}function tf(i,e){if(e.segmentIndex>=i.widths.length)return-1;const t=SB(i,e.segmentIndex);return t<0?-1:Vm(i,t,e)}function MB(i,e,t){if(t.segmentIndex>=i.widths.length)return-1;let n=e;for(;n<i.chunks.length&&t.segmentIndex>=i.chunks[n].consumedEndSegmentIndex;)n++;return n>=i.chunks.length?-1:Vm(i,n,t)}function BB(i,e){return i.simpleLineWalkFastPath?Wm(i,e):nf(i,e)}function Wm(i,e,t){const{widths:n,kinds:s,breakableFitAdvances:r}=i;if(n.length===0)return 0;const o=Ra().lineFitEpsilon,c=e+o;let l=0,h=0,u=!1,d=0,f=0,p=0,m=0,g=-1,A=0;function _(){g=-1,A=0}function x(C=p,v=m,F=h){l++,t?.({startSegmentIndex:d,startGraphemeIndex:f,endSegmentIndex:C,endGraphemeIndex:v,width:F}),h=0,u=!1,_()}function E(C,v){u=!0,d=C,f=0,p=C+1,m=0,h=v}function S(C,v,F){u=!0,d=C,f=v,p=C,m=v+1,h=F}function w(C,v){if(!u){E(C,v);return}h+=v,p=C+1,m=0}function I(C,v){const F=r[C];for(let K=v;K<F.length;K++){const q=F[K];u?h+q>c?(x(),S(C,K,q)):(h+=q,p=C,m=K+1):S(C,K,q)}u&&p===C&&m===F.length&&(p=C+1,m=0)}let T=0;for(;T<n.length&&!(!u&&(T=IB(i,T),T>=n.length));){const C=n[T],v=s[T],F=v==="space"||v==="preserved-space"||v==="tab"||v==="zero-width-break"||v==="soft-hyphen";if(!u){C>e&&r[T]!==null?I(T,0):E(T,C),F&&(g=T+1,A=h-C),T++;continue}if(h+C>c){if(F){w(T,C),x(T+1,0,h-C),T++;continue}if(g>=0){if(p>g||p===g&&m>0){x();continue}x(g,0,A);continue}if(C>e&&r[T]!==null){x(),I(T,0),T++;continue}x();continue}w(T,C),F&&(g=T+1,A=h-C),T++}return u&&x(),l}function nf(i,e,t){if(i.simpleLineWalkFastPath)return Wm(i,e,t);const{widths:n,lineEndFitAdvances:s,lineEndPaintAdvances:r,kinds:a,breakableFitAdvances:o,discretionaryHyphenWidth:c,tabStopAdvance:l,chunks:h}=i;if(n.length===0||h.length===0)return 0;const u=Ra(),d=u.lineFitEpsilon,f=e+d;let p=0,m=0,g=!1,A=0,_=0,x=0,E=0,S=-1,w=0,I=0,T=null;function C(){S=-1,w=0,I=0,T=null}function v(Q=x,J=E,ee=m){p++,t?.({startSegmentIndex:A,startGraphemeIndex:_,endSegmentIndex:Q,endGraphemeIndex:J,width:ee}),m=0,g=!1,C()}function F(Q,J){g=!0,A=Q,_=0,x=Q+1,E=0,m=J}function K(Q,J,ee){g=!0,A=Q,_=J,x=Q,E=J+1,m=ee}function q(Q,J){if(!g){F(Q,J);return}m+=J,x=Q+1,E=0}function $(Q,J,ee,ae){if(!J)return;const _e=Q==="tab"?0:s[ee],Me=Q==="tab"?ae:r[ee];S=ee+1,w=m-ae+_e,I=m-ae+Me,T=Q}function D(Q,J){const ee=o[Q];for(let ae=J;ae<ee.length;ae++){const _e=ee[ae];g?m+_e>f?(v(),K(Q,ae,_e)):(m+=_e,x=Q,E=ae+1):K(Q,ae,_e)}g&&x===Q&&E===ee.length&&(x=Q+1,E=0)}function O(Q){if(T!=="soft-hyphen")return!1;const J=o[Q];if(J==null)return!1;const{fitCount:ee,fittedWidth:ae}=zm(J,m,e,d,c);return ee===0?!1:(m=ae,x=Q,E=ee,C(),ee===J.length?(x=Q+1,E=0,!0):(v(Q,ee,ae+c),D(Q,ee),!0))}function Y(Q){p++,t?.({startSegmentIndex:Q.startSegmentIndex,startGraphemeIndex:0,endSegmentIndex:Q.consumedEndSegmentIndex,endGraphemeIndex:0,width:0}),C()}for(let Q=0;Q<h.length;Q++){const J=h[Q];if(J.startSegmentIndex===J.endSegmentIndex){Y(J);continue}g=!1,m=0,A=J.startSegmentIndex,_=0,x=J.startSegmentIndex,E=0,C();let ee=J.startSegmentIndex;for(;ee<J.endSegmentIndex;){const ae=a[ee],_e=ae==="space"||ae==="preserved-space"||ae==="tab"||ae==="zero-width-break"||ae==="soft-hyphen",Me=ae==="tab"?Hm(m,l):n[ee];if(ae==="soft-hyphen"){g&&(x=ee+1,E=0,S=ee+1,w=m+c,I=m+c,T=ae),ee++;continue}if(!g){Me>e&&o[ee]!==null?D(ee,0):F(ee,Me),$(ae,_e,ee,Me),ee++;continue}if(m+Me>f){const me=m+(ae==="tab"?0:s[ee]),xe=m+(ae==="tab"?Me:r[ee]);if(T==="soft-hyphen"&&u.preferEarlySoftHyphenBreak&&w<=f){v(S,0,I);continue}if(T==="soft-hyphen"&&O(ee)){ee++;continue}if(_e&&me<=f){q(ee,Me),v(ee+1,0,xe),ee++;continue}if(S>=0&&w<=f){if(x>S||x===S&&E>0){v();continue}const be=S;v(be,0,I),ee=be;continue}if(Me>e&&o[ee]!==null){v(),D(ee,0),ee++;continue}v();continue}q(ee,Me),$(ae,_e,ee,Me),ee++}if(g){const ae=S===J.consumedEndSegmentIndex?I:m;v(J.consumedEndSegmentIndex,0,ae)}}return p}function sf(i,e,t,n){const s=i.chunks[t];if(s.startSegmentIndex===s.endSegmentIndex)return e.segmentIndex=s.consumedEndSegmentIndex,e.graphemeIndex=0,0;const{widths:r,lineEndFitAdvances:a,lineEndPaintAdvances:o,kinds:c,breakableFitAdvances:l,discretionaryHyphenWidth:h,tabStopAdvance:u}=i,d=Ra(),f=d.lineFitEpsilon,p=n+f;let m=0,g=!1,A=e.segmentIndex,_=e.graphemeIndex,x=-1,E=0,S=0,w=null;function I(){x=-1,E=0,S=0,w=null}function T(D=A,O=_,Y=m){return g?(e.segmentIndex=D,e.graphemeIndex=O,Y):null}function C(D,O){g=!0,A=D+1,_=0,m=O}function v(D,O,Y){g=!0,A=D,_=O+1,m=Y}function F(D,O){if(!g){C(D,O);return}m+=O,A=D+1,_=0}function K(D,O,Y,Q){if(!O)return;const J=D==="tab"?0:a[Y],ee=D==="tab"?Q:o[Y];x=Y+1,E=m-Q+J,S=m-Q+ee,w=D}function q(D,O){const Y=l[D];for(let Q=O;Q<Y.length;Q++){const J=Y[Q];if(!g)v(D,Q,J);else{if(m+J>p)return T();m+=J,A=D,_=Q+1}}return g&&A===D&&_===Y.length&&(A=D+1,_=0),null}function $(D){if(w!=="soft-hyphen"||x<0)return null;const O=l[D]??null;if(O!==null){const{fitCount:Y,fittedWidth:Q}=zm(O,m,n,f,h);if(Y===O.length)return m=Q,A=D+1,_=0,I(),null;if(Y>0)return T(D,Y,Q+h)}return E<=p?T(x,0,S):null}for(let D=e.segmentIndex;D<s.endSegmentIndex;D++){const O=c[D],Y=O==="space"||O==="preserved-space"||O==="tab"||O==="zero-width-break"||O==="soft-hyphen",Q=D===e.segmentIndex?e.graphemeIndex:0,J=O==="tab"?Hm(m,u):r[D];if(O==="soft-hyphen"&&Q===0){g&&(A=D+1,_=0,x=D+1,E=m+h,S=m+h,w=O);continue}if(!g){if(Q>0){const ae=q(D,Q);if(ae!==null)return ae}else if(J>n&&l[D]!==null){const ae=q(D,0);if(ae!==null)return ae}else C(D,J);K(O,Y,D,J);continue}if(m+J>p){const ae=m+(O==="tab"?0:a[D]),_e=m+(O==="tab"?J:o[D]);if(w==="soft-hyphen"&&d.preferEarlySoftHyphenBreak&&E<=p)return T(x,0,S);const Me=$(D);if(Me!==null)return Me;if(Y&&ae<=p)return F(D,J),T(D+1,0,_e);if(x>=0&&E<=p)return A>x||A===x&&_>0?T():T(x,0,S);if(J>n&&l[D]!==null){const se=T();if(se!==null)return se;const me=q(D,0);if(me!==null)return me}return T()}F(D,J),K(O,Y,D,J)}return x===s.consumedEndSegmentIndex&&_===0?T(s.consumedEndSegmentIndex,0,S):T(s.consumedEndSegmentIndex,0,m)}function qm(i,e,t){const{widths:n,kinds:s,breakableFitAdvances:r}=i,o=Ra().lineFitEpsilon,c=t+o;let l=0,h=!1,u=e.segmentIndex,d=e.graphemeIndex,f=-1,p=0;for(let m=e.segmentIndex;m<n.length;m++){const g=n[m],A=s[m],_=A==="space"||A==="preserved-space"||A==="tab"||A==="zero-width-break"||A==="soft-hyphen",x=m===e.segmentIndex?e.graphemeIndex:0,E=r[m];if(!h){if(x>0||g>t&&E!==null){const S=E,w=S[x];h=!0,l=w,u=m,d=x+1;for(let I=x+1;I<S.length;I++){const T=S[I];if(l+T>c)return e.segmentIndex=u,e.graphemeIndex=d,l;l+=T,u=m,d=I+1}u===m&&d===S.length&&(u=m+1,d=0)}else h=!0,l=g,u=m+1,d=0;_&&(f=m+1,p=l-g);continue}if(l+g>c)return _?(e.segmentIndex=m+1,e.graphemeIndex=0,l):f>=0?u>f||u===f&&d>0?(e.segmentIndex=u,e.graphemeIndex=d,l):(e.segmentIndex=f,e.graphemeIndex=0,p):(e.segmentIndex=u,e.graphemeIndex=d,l);l+=g,u=m+1,d=0,_&&(f=m+1,p=l-g)}return h?(e.segmentIndex=u,e.graphemeIndex=d,l):null}function rf(i,e,t){const n={segmentIndex:e.segmentIndex,graphemeIndex:e.graphemeIndex},s=tf(i,n);if(s<0)return null;const r=n.segmentIndex,a=n.graphemeIndex,o=i.simpleLineWalkFastPath?qm(i,n,t):sf(i,n,s,t);return o===null?null:{startSegmentIndex:r,startGraphemeIndex:a,endSegmentIndex:n.segmentIndex,endGraphemeIndex:n.graphemeIndex,width:o}}function TB(i,e,t){const n=tf(i,e);return n<0?null:i.simpleLineWalkFastPath?qm(i,e,t):sf(i,e,n,t)}function RB(i,e){if(i.widths.length===0)return{lineCount:0,maxLineWidth:0};const t={segmentIndex:0,graphemeIndex:0};let n=0,s=0;if(!i.simpleLineWalkFastPath){let r=tf(i,t);for(;r>=0;){const a=sf(i,t,r,e);if(a===null)return{lineCount:n,maxLineWidth:s};n++,a>s&&(s=a),r=MB(i,r,t)}return{lineCount:n,maxLineWidth:s}}for(;;){const r=TB(i,t,e);if(r===null)return{lineCount:n,maxLineWidth:s};n++,r>s&&(s=r)}}let af=null,Km=new WeakMap;function jm(){return af===null&&(af=new Intl.Segmenter(void 0,{granularity:"grapheme"})),af}function FB(i){return i?{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[],segments:[]}:{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[]}}function NB(i,e){const t=[];let n=[],s=0,r=!1,a=!1,o=!1;function c(){n.length!==0&&(t.push({text:n.length===1?n[0]:n.join(""),start:s}),n=[],r=!1,a=!1,o=!1)}function l(u,d,f){n=[u],s=d,r=f,a=Jd(u),o=Hl.has(u)}function h(u,d){n.push(u),r=r||d;const f=Jd(u);u.length===1&&wr.has(u)?a=a||f:a=f,o=!1}for(const u of jm().segment(i)){const d=u.segment,f=_r(d);if(n.length===0){l(d,u.index,f);continue}if(o||jd.has(d)||wr.has(d)||e.carryCJKAfterClosingQuote&&f&&a){h(d,f);continue}if(!r&&!f){h(d,f);continue}c(),l(d,u.index,f)}return c(),t}function DB(i,e,t,n){const s=Ra(),{cache:r,emojiCorrection:a}=CB(e,EB(i.normalized)),o=vr("-",Vs("-",r),a),l=vr(" ",Vs(" ",r),a)*8;if(i.len===0)return FB(t);const h=[],u=[],d=[],f=[];let p=i.chunks.length<=1;const m=t?[]:null,g=[],A=t?[]:null,_=Array.from({length:i.len});function x(I,T,C,v,F,K,q){F!=="text"&&F!=="space"&&F!=="zero-width-break"&&(p=!1),h.push(T),u.push(C),d.push(v),f.push(F),m?.push(K),g.push(q),A!==null&&A.push(I)}function E(I,T,C,v,F){const K=Vs(I,r),q=vr(I,K,a),$=T==="space"||T==="preserved-space"||T==="zero-width-break"?0:q,D=T==="space"||T==="zero-width-break"?0:q;if(F&&v&&I.length>1){let O="sum-graphemes";Vl(I)?O="pair-context":s.preferPrefixWidthsForBreakableRuns&&(O="segment-prefixes");const Y=vB(I,K,r,a,O);x(I,q,$,D,T,C,Y);return}x(I,q,$,D,T,C,null)}for(let I=0;I<i.len;I++){_[I]=h.length;const T=i.texts[I],C=i.isWordLike[I],v=i.kinds[I],F=i.starts[I];if(v==="soft-hyphen"){x(T,0,o,o,v,F,null);continue}if(v==="hard-break"){x(T,0,0,0,v,F,null);continue}if(v==="tab"){x(T,0,0,0,v,F,null);continue}const K=Vs(T,r);if(v==="text"&&K.containsCJK){const $=NB(T,s);for(let D=0;D<$.length;D++){const O=$[D];E(O.text,"text",F+O.start,C,!_r(O.text))}continue}E(T,v,F,C,!0)}const S=LB(i.chunks,_,h.length),w=m===null?null:IM(i.normalized,m);return A!==null?{widths:h,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:w,breakableFitAdvances:g,discretionaryHyphenWidth:o,tabStopAdvance:l,chunks:S,segments:A}:{widths:h,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:w,breakableFitAdvances:g,discretionaryHyphenWidth:o,tabStopAdvance:l,chunks:S}}function LB(i,e,t){const n=[];for(let s=0;s<i.length;s++){const r=i[s],a=r.startSegmentIndex<e.length?e[r.startSegmentIndex]:t,o=r.endSegmentIndex<e.length?e[r.endSegmentIndex]:t,c=r.consumedEndSegmentIndex<e.length?e[r.consumedEndSegmentIndex]:t;n.push({startSegmentIndex:a,endSegmentIndex:o,consumedEndSegmentIndex:c})}return n}function Xm(i,e,t,n){const r=fB(i,Ra(),n?.whiteSpace,"normal");return DB(r,e,t)}function Wl(i,e,t){return Xm(i,e,!1,t)}function ql(i,e,t){return Xm(i,e,!0,t)}function SP(i){return i}function PB(i,e,t){const n=BB(i,e);return{lineCount:n,height:n*t}}function Ym(i,e,t){let n=t.get(i);if(n!==void 0)return n;n=[];const s=jm();for(const r of s.segment(e[i]))n.push(r.segment);return t.set(i,n),n}function Jm(i){let e=Km.get(i);return e!==void 0||(e=new Map,Km.set(i,e)),e}function kB(i,e,t,n){return n>0&&i[n-1]==="soft-hyphen"&&!(e===n&&t>0)}function UB(i,e,t,n,s,r,a){let o="";const c=kB(e,n,s,r);for(let l=n;l<r;l++)e[l]==="soft-hyphen"||e[l]==="hard-break"||(l===n&&s>0?o+=Ym(l,i,t).slice(s).join(""):o+=i[l]);return a>0?(c&&(o+="-"),o+=Ym(r,i,t).slice(n===r?s:0,a).join("")):c&&(o+="-"),o}function Zm(i,e,t,n,s,r,a){return{text:UB(i.segments,i.kinds,e,n,s,r,a),width:t,start:{segmentIndex:n,graphemeIndex:s},end:{segmentIndex:r,graphemeIndex:a}}}function OB(i,e,t){return Zm(i,e,t.width,t.startSegmentIndex,t.startGraphemeIndex,t.endSegmentIndex,t.endGraphemeIndex)}function QB(i){return{width:i.width,start:{segmentIndex:i.startSegmentIndex,graphemeIndex:i.startGraphemeIndex},end:{segmentIndex:i.endSegmentIndex,graphemeIndex:i.endGraphemeIndex}}}function GB(i,e){return Zm(i,Jm(i),e.width,e.start.segmentIndex,e.start.graphemeIndex,e.end.segmentIndex,e.end.graphemeIndex)}function HB(i,e,t){return i.widths.length===0?0:nf(i,e,n=>{t(QB(n))})}function of(i,e){return RB(i,e)}function $m(i){let e=0;return HB(i,Number.POSITIVE_INFINITY,t=>{t.width>e&&(e=t.width)}),e}function zB(i,e,t){const n=[];if(i.widths.length===0)return{lineCount:0,height:0,lines:n};const s=Jm(i),r=nf(i,e,a=>{n.push(OB(i,s,a))});return{lineCount:r,height:r*t,lines:n}}const VB=/[ \t\n\f\r]+/,e0=/^[ \t\n\f\r]+/,t0=/[ \t\n\f\r]+$/,Kl={segmentIndex:0,graphemeIndex:0},n0={itemIndex:0,segmentIndex:0,graphemeIndex:0};function MP(i){return i}function cf(i){return{segmentIndex:i.segmentIndex,graphemeIndex:i.graphemeIndex}}function i0(i){return i.segmentIndex===0&&i.graphemeIndex===0}function jl(i,e){const t=e.get(i);if(t!==void 0)return t;const n=$m(ql("A A",i)),s=$m(ql("AA",i)),r=Math.max(0,n-s);return e.set(i,r),r}function WB(i){const e=rf(i,Kl,Number.POSITIVE_INFINITY);return e===null?null:{endGraphemeIndex:e.endGraphemeIndex,endSegmentIndex:e.endSegmentIndex,width:e.width}}function qB(i,e){return i===0&&e>0}function s0(i){const e=[],t=Array.from({length:i.length}),n=new Map;let s=0;for(let r=0;r<i.length;r++){const a=i[r],o=e0.test(a.text),c=t0.test(a.text),l=a.text.replace(e0,"").replace(t0,"");if(l.length===0){VB.test(a.text)&&s===0&&(s=jl(a.font,n));continue}const h=s>0?s:o?jl(a.font,n):0,u=ql(l,a.font),d=WB(u);if(d===null){s=c?jl(a.font,n):0;continue}const f={break:a.break??"normal",endGraphemeIndex:d.endGraphemeIndex,endSegmentIndex:d.endSegmentIndex,extraWidth:a.extraWidth??0,gapBefore:h,naturalWidth:d.width,prepared:u,sourceItemIndex:r};e.push(f),t[r]=f,s=c?jl(a.font,n):0}return{items:e,itemsBySourceItemIndex:t}}function KB(i,e,t,n){if(i.items.length===0||t.itemIndex>=i.items.length)return null;const s=Math.max(1,e);let r=0,a=s,o=t.itemIndex;const c={segmentIndex:t.segmentIndex,graphemeIndex:t.graphemeIndex};e:for(;o<i.items.length;){const l=i.items[o];if(!i0(c)&&c.segmentIndex===l.endSegmentIndex&&c.graphemeIndex===l.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const h=r===0?0:l.gapBefore,u=i0(c);if(l.break==="never"){if(!u){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const m=l.naturalWidth+l.extraWidth,g=h+m;if(r>0&&g>a)break e;n?.(l,h,m,cf(Kl),{segmentIndex:l.endSegmentIndex,graphemeIndex:l.endGraphemeIndex}),r+=g,a=Math.max(0,s-r),o++,c.segmentIndex=0,c.graphemeIndex=0;continue}const d=h+l.extraWidth;if(r>0&&d>=a)break e;if(u){const m=d+l.naturalWidth;if(m<=a){n?.(l,h,l.naturalWidth+l.extraWidth,cf(Kl),{segmentIndex:l.endSegmentIndex,graphemeIndex:l.endGraphemeIndex}),r+=m,a=Math.max(0,s-r),o++,c.segmentIndex=0,c.graphemeIndex=0;continue}}const f=Math.max(1,a-d),p=rf(l.prepared,c,f);if(p===null){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(c.segmentIndex===p.endSegmentIndex&&c.graphemeIndex===p.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(r>0&&u&&h>0&&qB(p.endSegmentIndex,p.endGraphemeIndex)){const m=rf(l.prepared,Kl,Math.max(1,s-l.extraWidth));if(m!==null&&(m.endSegmentIndex>p.endSegmentIndex||m.endSegmentIndex===p.endSegmentIndex&&m.endGraphemeIndex>p.endGraphemeIndex))break e}if(n?.(l,h,p.width+l.extraWidth,cf(c),{segmentIndex:p.endSegmentIndex,graphemeIndex:p.endGraphemeIndex}),r+=h+p.width+l.extraWidth,a=Math.max(0,s-r),p.endSegmentIndex===l.endSegmentIndex&&p.endGraphemeIndex===l.endGraphemeIndex){o++,c.segmentIndex=0,c.graphemeIndex=0;continue}c.segmentIndex=p.endSegmentIndex,c.graphemeIndex=p.endGraphemeIndex;break}return r===0?null:(t.itemIndex=o,t.segmentIndex=c.segmentIndex,t.graphemeIndex=c.graphemeIndex,r)}function jB(i,e,t=n0){const n=i,s={itemIndex:t.itemIndex,segmentIndex:t.segmentIndex,graphemeIndex:t.graphemeIndex},r=[],a=KB(n,e,s,(o,c,l,h,u)=>{r.push({itemIndex:o.sourceItemIndex,gapBefore:c,occupiedWidth:l,start:h,end:u})});return a===null?null:{fragments:r,width:a,end:s}}function XB(i,e){return GB(i.prepared,{width:e.occupiedWidth-i.extraWidth,start:e.start,end:e.end}).text}function r0(i,e){const t=i;return{fragments:e.fragments.map(n=>{const s=t.itemsBySourceItemIndex[n.itemIndex];if(s===void 0)throw new Error("Missing rich-text inline item for fragment");return{...n,text:XB(s,n)}}),width:e.width,end:e.end}}function a0(i,e,t){let n=0,s=n0;for(;;){const r=jB(i,e,s);if(r===null)return n;t(r),n++,s=r.end}}const o0="500 14px Inter, sans-serif",lf="600 10px Inter, sans-serif",hf="300 13px Inter, sans-serif",c0="600 10px Inter, sans-serif",l0="300 12px Inter, sans-serif",zo=18,Xl=16,gn=16,Hi=6,h0=12,Yl=Math.min(window.devicePixelRatio||1,2),YB="rgba(0, 0, 0, 0.75)",JB="rgba(255, 255, 255, 0.08)",ZB="rgba(255, 255, 255, 0.9)",$B="rgba(255, 255, 255, 0.30)",eT="rgba(255, 255, 255, 0.85)",u0="rgba(255, 255, 255, 0.08)",tT="rgba(255, 255, 255, 0.45)",nT="rgba(255, 255, 255, 0.08)",iT="rgba(255, 255, 255, 0.7)";function sT(i){let e=0,t=0,n=0;const s=new Set,r=new Set,a=new Set;let o=!1,c=!1;return i.traverse(l=>{if(l.isMesh||l.isPoints||l.isLine){n++;const h=l.geometry;h&&(h.index?t+=h.index.count/3:h.attributes.position&&(t+=h.attributes.position.count/3),h.attributes.position&&(e+=h.attributes.position.count)),l.skeleton&&(o=!0),l.morphTargetInfluences&&l.morphTargetInfluences.length>0&&(c=!0),(Array.isArray(l.material)?l.material:[l.material]).forEach(d=>{if(d){s.add(d.uuid),a.add(d.type.replace("Material",""));for(const f in d)d[f]&&d[f].isTexture&&r.add(d[f].uuid)}})}}),{vertices:e,triangles:Math.floor(t),meshes:n,materials:s.size,textures:r.size,materialTypes:Array.from(a),hasSkinning:o,hasMorphs:c}}function Vo(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":i.toString()}function rT(i,e){const t=[];return i.hasSkinning&&t.push("skinned"),i.hasMorphs&&t.push("morph targets"),e&&e.length>0&&t.push(`${e.length} animation${e.length>1?"s":""}`),i.materialTypes.length>0&&t.push(i.materialTypes.join(", ")),t.length>0?t.join(" · "):""}function aT(i,e,t){const n=sT(e),s=rT(n,t),r=[{label:"MESHES",value:Vo(n.meshes)},{label:"VERTICES",value:Vo(n.vertices)},{label:"TRIANGLES",value:Vo(n.triangles)},{label:"MATERIALS",value:Vo(n.materials)},{label:"TEXTURES",value:Vo(n.textures)}];t&&t.length>0&&r.push({label:"ANIMATIONS",value:t.length.toString()});const a=[];n.materialTypes.forEach(w=>a.push(w)),n.hasSkinning&&a.push("Skinned"),n.hasMorphs&&a.push("Morph"),t&&t.length>0&&a.push("Animated");const o=200,c=Wl("Model Info",o0),l=PB(c,o,zo+2),h=r.map(w=>{const I=[{text:w.label+" ",font:lf},{text:w.value,font:hf}],T=s0(I),C=Wl(w.label,lf),v=of(C,o),F=Wl(w.value,hf),K=of(F,o);return{...w,labelWidth:v.maxLineWidth,valueWidth:K.maxLineWidth,richPrepared:T}}),u=a.map(w=>{const I=Wl(w,c0),T=of(I,300);return{text:w,width:T.maxLineWidth+h0}});let d=[],f=0;if(s){const w=ql(s,l0),I=zB(w,o-gn,zo);d=I.lines,f=I.height}const p=Math.max(l.width+gn*2,...h.map(w=>w.labelWidth+w.valueWidth+gn*3)),m=Math.max(p,180);let g=0;if(u.length>0){let w=0,I=1;u.forEach(T=>{w>0&&w+T.width>m-gn*2&&(I++,w=0),w+=T.width+6}),g=I*(Xl+6)+Hi}const A=gn+l.height+Hi+Hi+h.length*(zo+Hi)+g+(f>0?Hi+f:0)+gn,_=document.createElement("canvas");_.width=m*Yl,_.height=A*Yl,_.style.width=m+"px",_.style.height=A+"px";const x=_.getContext("2d");x.scale(Yl,Yl),x.fillStyle=YB,uf(x,0,0,m,A,10),x.fill(),x.strokeStyle=JB,x.lineWidth=1,uf(x,.5,.5,m-1,A-1,10),x.stroke();let E=gn;if(x.font=o0,x.fillStyle=ZB,x.textBaseline="top",x.fillText("Model Info",gn,E),E+=l.height+Hi,x.strokeStyle=u0,x.beginPath(),x.moveTo(gn,E),x.lineTo(m-gn,E),x.stroke(),E+=Hi,h.forEach(w=>{x.font=lf,x.fillStyle=$B,x.textAlign="left",x.fillText(w.label,gn,E),x.font=hf,x.fillStyle=eT,x.textAlign="right",x.fillText(w.value,m-gn,E),x.textAlign="left",E+=zo+Hi}),u.length>0){let w=gn;u.forEach(I=>{w>gn&&w+I.width>m-gn&&(w=gn,E+=Xl+6),x.fillStyle=nT,uf(x,w,E,I.width,Xl,4),x.fill(),x.font=c0,x.fillStyle=iT,x.textBaseline="top",x.fillText(I.text,w+h0/2,E+3),w+=I.width+6}),E+=Xl+Hi+4}d.length>0&&(x.strokeStyle=u0,x.beginPath(),x.moveTo(gn,E),x.lineTo(m-gn,E),x.stroke(),E+=Hi,x.font=l0,x.fillStyle=tT,x.textBaseline="top",d.forEach(w=>{x.fillText(w.text,gn,E),E+=zo}));const S=document.createElement("div");return S.classList.add("model-info"),S.appendChild(_),i.appendChild(S),{el:S,canvas:_,remove(){S.remove()}}}function uf(i,e,t,n,s,r){i.beginPath(),i.moveTo(e+r,t),i.lineTo(e+n-r,t),i.quadraticCurveTo(e+n,t,e+n,t+r),i.lineTo(e+n,t+s-r),i.quadraticCurveTo(e+n,t+s,e+n-r,t+s),i.lineTo(e+r,t+s),i.quadraticCurveTo(e,t+s,e,t+s-r),i.lineTo(e,t+r),i.quadraticCurveTo(e,t,e+r,t),i.closePath()}const oT="500 11px Inter, sans-serif",d0="300 10px Inter, sans-serif",df=10,f0=6,p0=14,Jl=Math.min(window.devicePixelRatio||1,2),cT=8;function lT(i){const e=[];return i.traverse(t=>{if(e.length>=cT||!t.isMesh||!t.name||t.name.startsWith("_"))return;const n=t.geometry,s=Array.isArray(t.material)?t.material[0]:t.material,r=n&&n.attributes.position?n.attributes.position.count:0,a=s?s.type.replace("Material",""):"",o=[{text:t.name,font:oT}];r>0&&o.push({text:" "+uT(r)+" verts",font:d0}),a&&o.push({text:" "+a,font:d0});const c=s0(o);let l=0,h=0;a0(c,300,m=>{const g=r0(c,m);l=Math.max(l,g.width),h++});const u=l+df*2,d=h*p0+f0*2;n&&n.computeBoundingBox();const f=n?n.boundingBox:null,p=new G;f?(f.getCenter(p),p.applyMatrix4(t.matrixWorld)):t.getWorldPosition(p),e.push({name:t.name,items:o,prepared:c,labelWidth:u,labelHeight:d,position:p,vertCount:r,matType:a})}),e}function hT(i){const{labelWidth:e,labelHeight:t,items:n,prepared:s}=i,r=document.createElement("canvas");r.width=e*Jl,r.height=t*Jl,r.style.width=e+"px",r.style.height=t+"px";const a=r.getContext("2d");a.scale(Jl,Jl),a.fillStyle="rgba(0, 0, 0, 0.8)",A0(a,0,0,e,t,6),a.fill(),a.strokeStyle="rgba(255, 255, 255, 0.1)",a.lineWidth=1,A0(a,.5,.5,e-1,t-1,6),a.stroke(),a.textBaseline="top";let o=f0;return a0(s,e-df*2,c=>{const l=r0(s,c);let h=df;l.fragments.forEach(u=>{h+=u.gapBefore;const d=n[u.itemIndex];a.font=d.font,a.fillStyle=u.itemIndex===0?"rgba(255, 255, 255, 0.9)":"rgba(255, 255, 255, 0.45)",a.fillText(u.text,h,o),h+=u.occupiedWidth}),o+=p0}),r}function uT(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":i.toString()}function A0(i,e,t,n,s,r){i.beginPath(),i.moveTo(e+r,t),i.lineTo(e+n-r,t),i.quadraticCurveTo(e+n,t,e+n,t+r),i.lineTo(e+n,t+s-r),i.quadraticCurveTo(e+n,t+s,e+n-r,t+s),i.lineTo(e+r,t+s),i.quadraticCurveTo(e,t+s,e,t+s-r),i.lineTo(e,t+r),i.quadraticCurveTo(e,t,e+r,t),i.closePath()}const ff=new WeakMap;class dT extends ci{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,s){const r=new os(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,a=>{this.parse(a,t,s)},n,s)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,yt,n).catch(n)}decodeDracoFile(e,t,n,s,r=un,a=()=>{}){const o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:s||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:r};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ff.has(e)){const c=ff.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let s;const r=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(r,a).then(c=>(s=c,new Promise((l,h)=>{s._callbacks[r]={resolve:l,reject:h},s.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return o.catch(()=>!0).then(()=>{s&&r&&this._releaseTask(s,r)}),ff.set(e,{key:n,promise:o}),o}_createGeometry(e){const t=new Mn;e.index&&t.setIndex(new Sn(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const s=e.attributes[n],r=s.name,a=s.array,o=s.itemSize,c=new Sn(a,o);r==="color"&&(this._assignVertexColorSpace(c,s.vertexColorSpace),c.normalized=!(a instanceof Float32Array)),t.setAttribute(r,c)}return t}_assignVertexColorSpace(e,t){if(t!==yt)return;const n=new Fe;for(let s=0,r=e.count;s<r;s++)n.fromBufferAttribute(e,s),tt.toWorkingColorSpace(n,yt),e.setXYZ(s,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new os(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((s,r)=>{n.load(e,s,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const s=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const r=fT.toString(),a=["/* draco decoder */",s,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(`
+`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const s=new Worker(this.workerSourceURL);s._callbacks={},s._taskCosts={},s._taskLoad=0,s.postMessage({type:"init",decoderConfig:this.decoderConfig}),s.onmessage=function(r){const a=r.data;switch(a.type){case"decode":s._callbacks[a.id].resolve(a);break;case"error":s._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(s)}else this.workerPool.sort(function(s,r){return s._taskLoad>r._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function fT(){let i,e;onmessage=function(a){const o=a.data;switch(o.type){case"init":i=o.decoderConfig,e=new Promise(function(h){i.onModuleLoaded=function(u){h({draco:u})},DracoDecoderModule(i)});break;case"decode":const c=o.buffer,l=o.taskConfig;e.then(h=>{const u=h.draco,d=new u.Decoder;try{const f=t(u,d,new Int8Array(c),l),p=f.attributes.map(m=>m.array.buffer);f.index&&p.push(f.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:f},p)}catch(f){console.error(f),self.postMessage({type:"error",id:o.id,error:f.message})}finally{u.destroy(d)}});break}};function t(a,o,c,l){const h=l.attributeIDs,u=l.attributeTypes;let d,f;const p=o.GetEncodedGeometryType(c);if(p===a.TRIANGULAR_MESH)d=new a.Mesh,f=o.DecodeArrayToMesh(c,c.byteLength,d);else if(p===a.POINT_CLOUD)d=new a.PointCloud,f=o.DecodeArrayToPointCloud(c,c.byteLength,d);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!f.ok()||d.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+f.error_msg());const m={index:null,attributes:[]};for(const g in h){const A=self[u[g]];let _,x;if(l.useUniqueIDs)x=h[g],_=o.GetAttributeByUniqueId(d,x);else{if(x=o.GetAttributeId(d,a[h[g]]),x===-1)continue;_=o.GetAttribute(d,x)}const E=s(a,o,d,g,A,_);g==="color"&&(E.vertexColorSpace=l.vertexColorSpace),m.attributes.push(E)}return p===a.TRIANGULAR_MESH&&(m.index=n(a,o,d)),a.destroy(d),m}function n(a,o,c){const h=c.num_faces()*3,u=h*4,d=a._malloc(u);o.GetTrianglesUInt32Array(c,u,d);const f=new Uint32Array(a.HEAPF32.buffer,d,h).slice();return a._free(d),{array:f,itemSize:1}}function s(a,o,c,l,h,u){const d=u.num_components(),p=c.num_points()*d,m=p*h.BYTES_PER_ELEMENT,g=r(a,h),A=a._malloc(m);o.GetAttributeDataArrayForAllPoints(c,u,g,m,A);const _=new h(a.HEAPF32.buffer,A,p).slice();return a._free(A),{name:l,array:_,itemSize:d}}function r(a,o){switch(o){case Float32Array:return a.DT_FLOAT32;case Int8Array:return a.DT_INT8;case Int16Array:return a.DT_INT16;case Int32Array:return a.DT_INT32;case Uint8Array:return a.DT_UINT8;case Uint16Array:return a.DT_UINT16;case Uint32Array:return a.DT_UINT32}}}class pT{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const n=this.workersResolve[e];if(n&&n(t),this.queue.length){const{resolve:s,msg:r,transfer:a}=this.queue.shift();this.workersResolve[e]=s,this.workers[e].postMessage(r,a)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(n=>{const s=this._getIdleWorker();s!==-1?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=n,this.workers[s].postMessage(e,t)):this.queue.push({resolve:n,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const AT=0,g0=2,gT=1,m0=2,mT=0,xT=1,bT=10,ET=0,x0=9,b0=15,E0=16,y0=22,_0=37,w0=43,v0=76,C0=83,I0=97,S0=100,M0=103,B0=109,T0=165,R0=166,pf=1000066e3;class yT{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class Wo{constructor(e,t,n,s){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=s,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+4294967296*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t){t===void 0&&(t=0);const n=this._offset;let s=0;for(;this._dataView.getUint8(this._offset)!==t&&s<e;)s++,this._offset++;return s<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,s)}}const Qn=[171,75,84,88,32,50,48,187,13,10,26,10];function F0(i){return new TextDecoder().decode(i)}function _T(i){const e=new Uint8Array(i.buffer,i.byteOffset,Qn.length);if(e[0]!==Qn[0]||e[1]!==Qn[1]||e[2]!==Qn[2]||e[3]!==Qn[3]||e[4]!==Qn[4]||e[5]!==Qn[5]||e[6]!==Qn[6]||e[7]!==Qn[7]||e[8]!==Qn[8]||e[9]!==Qn[9]||e[10]!==Qn[10]||e[11]!==Qn[11])throw new Error("Missing KTX 2.0 identifier.");const t=new yT,n=17*Uint32Array.BYTES_PER_ELEMENT,s=new Wo(i,Qn.length,n,!0);t.vkFormat=s._nextUint32(),t.typeSize=s._nextUint32(),t.pixelWidth=s._nextUint32(),t.pixelHeight=s._nextUint32(),t.pixelDepth=s._nextUint32(),t.layerCount=s._nextUint32(),t.faceCount=s._nextUint32();const r=s._nextUint32();t.supercompressionScheme=s._nextUint32();const a=s._nextUint32(),o=s._nextUint32(),c=s._nextUint32(),l=s._nextUint32(),h=s._nextUint64(),u=s._nextUint64(),d=new Wo(i,Qn.length+n,3*r*8,!0);for(let Y=0;Y<r;Y++)t.levels.push({levelData:new Uint8Array(i.buffer,i.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const f=new Wo(i,a,o,!0),p={vendorId:f._skip(4)._nextUint16(),descriptorType:f._nextUint16(),versionNumber:f._nextUint16(),descriptorBlockSize:f._nextUint16(),colorModel:f._nextUint8(),colorPrimaries:f._nextUint8(),transferFunction:f._nextUint8(),flags:f._nextUint8(),texelBlockDimension:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],bytesPlane:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],samples:[]},m=(p.descriptorBlockSize/4-6)/4;for(let Y=0;Y<m;Y++){const Q={bitOffset:f._nextUint16(),bitLength:f._nextUint8(),channelType:f._nextUint8(),samplePosition:[f._nextUint8(),f._nextUint8(),f._nextUint8(),f._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};64&Q.channelType?(Q.sampleLower=f._nextInt32(),Q.sampleUpper=f._nextInt32()):(Q.sampleLower=f._nextUint32(),Q.sampleUpper=f._nextUint32()),p.samples[Y]=Q}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(p);const g=new Wo(i,c,l,!0);for(;g._offset<l;){const Y=g._nextUint32(),Q=g._scan(Y),J=F0(Q);if(t.keyValue[J]=g._nextUint8Array(Y-Q.byteLength-1),J.match(/^ktx/i)){const ee=F0(t.keyValue[J]);t.keyValue[J]=ee.substring(0,ee.lastIndexOf("\0"))}g._skip(Y%4?4-Y%4:0)}if(u<=0)return t;const A=new Wo(i,h,u,!0),_=A._nextUint16(),x=A._nextUint16(),E=A._nextUint32(),S=A._nextUint32(),w=A._nextUint32(),I=A._nextUint32(),T=[];for(let Y=0;Y<r;Y++)T.push({imageFlags:A._nextUint32(),rgbSliceByteOffset:A._nextUint32(),rgbSliceByteLength:A._nextUint32(),alphaSliceByteOffset:A._nextUint32(),alphaSliceByteLength:A._nextUint32()});const C=h+A._offset,v=C+E,F=v+S,K=F+w,q=new Uint8Array(i.buffer,i.byteOffset+C,E),$=new Uint8Array(i.buffer,i.byteOffset+v,S),D=new Uint8Array(i.buffer,i.byteOffset+F,w),O=new Uint8Array(i.buffer,i.byteOffset+K,I);return t.globalData={endpointCount:_,selectorCount:x,imageDescs:T,endpointsData:q,selectorsData:$,tablesData:D,extendedData:O},t}let Af,ls,gf;const mf={env:{emscripten_notify_memory_growth:function(i){gf=new Uint8Array(ls.exports.memory.buffer)}}};class wT{init(){return Af||(Af=typeof fetch<"u"?fetch("data:application/wasm;base64,"+N0).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,mf)).then(this._init):WebAssembly.instantiate(Buffer.from(N0,"base64"),mf).then(this._init),Af)}_init(e){ls=e.instance,mf.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!ls)throw new Error("ZSTDDecoder: Await .init() before decoding.");const n=e.byteLength,s=ls.exports.malloc(n);gf.set(e,s),t=t||Number(ls.exports.ZSTD_findDecompressedSize(s,n));const r=ls.exports.malloc(t),a=ls.exports.ZSTD_decompress(r,t,s,n),o=gf.slice(r,r+a);return ls.exports.free(s),ls.exports.free(r),o}}const N0="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn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CCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpB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GBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQ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FwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiAD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Map;let bf=0,Ef;class ui extends ci{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new pT,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return this.workerConfig={astcSupported:await e.hasFeatureAsync("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:await e.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await e.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await e.hasFeatureAsync("texture-compression-bc"),bptcSupported:await e.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await e.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-bc"),bptcSupported:e.hasFeature("texture-compression-bptc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:e.extensions.has("WEBGL_compressed_texture_astc")&&e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},this}init(){if(!this.transcoderPending){const e=new os(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),n=new os(this.manager);n.setPath(this.transcoderPath),n.setResponseType("arraybuffer"),n.setWithCredentials(this.withCredentials);const s=n.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,s]).then(([r,a])=>{const o=ui.BasisWorker.toString(),c=["/* constants */","let _EngineFormat = "+JSON.stringify(ui.EngineFormat),"let _EngineType = "+JSON.stringify(ui.EngineType),"let _TranscoderFormat = "+JSON.stringify(ui.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ui.BasisFormat),"/* basis_transcoder.js */",r,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
+`);this.workerSourceURL=URL.createObjectURL(new Blob([c])),this.transcoderBinary=a,this.workerPool.setWorkerCreator(()=>{const l=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return l.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),l})}),bf>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),bf++}return this.transcoderPending}load(e,t,n,s){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new os(this.manager);r.setResponseType("arraybuffer"),r.setWithCredentials(this.withCredentials),r.load(e,a=>{this.parse(a,t,s)},n,s)}parse(e,t,n){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(xf.has(e))return xf.get(e).promise.then(t).catch(n);this._createTexture(e).then(s=>t?t(s):null).catch(n)}_createTextureFrom(e,t){const{type:n,error:s,data:{faces:r,width:a,height:o,format:c,type:l,dfdFlags:h}}=e;if(n==="error")return Promise.reject(s);let u;if(t.faceCount===6)u=new nw(r,c,l);else{const d=r[0].mipmaps;u=t.layerCount>1?new tw(d,a,o,t.layerCount,c,l):new yl(d,a,o,c,l)}return u.minFilter=r[0].mipmaps.length===1?qt:ri,u.magFilter=qt,u.generateMipmaps=!1,u.needsUpdate=!0,u.colorSpace=D0(t),u.premultiplyAlpha=!!(h&gT),u}async _createTexture(e,t={}){const n=_T(new Uint8Array(e)),s=n.vkFormat===pf&&n.dataFormatDescriptor[0].colorModel===167;if(!(n.vkFormat===ET||s&&!this.workerConfig.astcHDRSupported))return ST(n);const a=t,o=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:a},[e])).then(c=>this._createTextureFrom(c.data,n));return xf.set(e,{promise:o}),o}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),bf--}}ui.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},ui.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},ui.EngineFormat={RGBAFormat:hn,RGBA_ASTC_4x4_Format:lo,RGB_BPTC_UNSIGNED_Format:Oc,RGBA_BPTC_Format:uo,RGBA_ETC2_EAC_Format:Uc,RGBA_PVRTC_4BPPV1_Format:Lc,RGBA_S3TC_DXT5_Format:co,RGB_ETC1_Format:Pc,RGB_ETC2_Format:kc,RGB_PVRTC_4BPPV1_Format:Dc,RGBA_S3TC_DXT1_Format:oo},ui.EngineType={UnsignedByteType:cn,HalfFloatType:kn,FloatType:ln},ui.BasisWorker=function(){let i,e,t;const n=_EngineFormat,s=_EngineType,r=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",function(p){const m=p.data;switch(m.type){case"init":i=m.config,o(m.transcoderBinary);break;case"transcode":e.then(()=>{try{const{faces:g,buffers:A,width:_,height:x,hasAlpha:E,format:S,type:w,dfdFlags:I}=c(m.buffer);self.postMessage({type:"transcode",id:m.id,data:{faces:g,width:_,height:x,hasAlpha:E,format:S,type:w,dfdFlags:I}},A)}catch(g){console.error(g),self.postMessage({type:"error",id:m.id,error:g.message})}});break}});function o(p){e=new Promise(m=>{t={wasmBinary:p,onRuntimeInitialized:m},BASIS(t)}).then(()=>{t.initializeBasis(),t.KTX2File===void 0&&console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function c(p){const m=new t.KTX2File(new Uint8Array(p));function g(){m.close(),m.delete()}if(!m.isValid())throw g(),new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");let A;if(m.isUASTC())A=a.UASTC;else if(m.isETC1S())A=a.ETC1S;else if(m.isHDR())A=a.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");const _=m.getWidth(),x=m.getHeight(),E=m.getLayers()||1,S=m.getLevels(),w=m.getFaces(),I=m.getHasAlpha(),T=m.getDFDFlags(),{transcoderFormat:C,engineFormat:v,engineType:F}=u(A,_,x,I);if(!_||!x||!S)throw g(),new Error("THREE.KTX2Loader: Invalid texture");if(!m.startTranscoding())throw g(),new Error("THREE.KTX2Loader: .startTranscoding failed");const K=[],q=[];for(let $=0;$<w;$++){const D=[];for(let O=0;O<S;O++){const Y=[];let Q,J;for(let ae=0;ae<E;ae++){const _e=m.getImageLevelInfo(O,ae,$);$===0&&O===0&&ae===0&&(_e.origWidth%4!==0||_e.origHeight%4!==0)&&console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."),S>1?(Q=_e.origWidth,J=_e.origHeight):(Q=_e.width,J=_e.height);let Me=new Uint8Array(m.getImageTranscodedSizeInBytes(O,ae,0,C));const se=m.transcodeImage(Me,O,ae,$,C,0,-1,-1);if(F===s.HalfFloatType&&(Me=new Uint16Array(Me.buffer,Me.byteOffset,Me.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!se)throw g(),new Error("THREE.KTX2Loader: .transcodeImage failed.");Y.push(Me)}const ee=f(Y);D.push({data:ee,width:Q,height:J}),q.push(ee.buffer)}K.push({mipmaps:D,width:_,height:x,format:v,type:F})}return g(),{faces:K,buffers:q,width:_,height:x,hasAlpha:I,dfdFlags:T,format:v,type:F}}const l=[{if:"astcSupported",basisFormat:[a.UASTC],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],engineType:[s.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],engineType:[s.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.BC1,r.BC3],engineFormat:[n.RGBA_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],engineType:[s.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],engineType:[s.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.ETC1],engineFormat:[n.RGB_ETC1_Format],engineType:[s.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],engineType:[s.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[a.UASTC_HDR],transcoderFormat:[r.BC6H],engineFormat:[n.RGB_BPTC_UNSIGNED_Format],engineType:[s.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[a.ETC1S,a.UASTC],transcoderFormat:[r.RGBA32,r.RGBA32],engineFormat:[n.RGBAFormat,n.RGBAFormat],engineType:[s.UnsignedByteType,s.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[a.UASTC_HDR],transcoderFormat:[r.RGBA_HALF],engineFormat:[n.RGBAFormat],engineType:[s.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],h={[a.ETC1S]:l.filter(p=>p.basisFormat.includes(a.ETC1S)).sort((p,m)=>p.priorityUASTC-m.priorityUASTC),[a.UASTC]:l.filter(p=>p.basisFormat.includes(a.UASTC)).sort((p,m)=>p.priorityUASTC-m.priorityUASTC),[a.UASTC_HDR]:l.filter(p=>p.basisFormat.includes(a.UASTC_HDR)).sort((p,m)=>p.priorityHDR-m.priorityHDR)};function u(p,m,g,A){const _=h[p];for(let x=0;x<_.length;x++){const E=_[x];if(E.if&&!i[E.if]||!E.basisFormat.includes(p)||A&&E.transcoderFormat.length<2||E.needsPowerOfTwo&&!(d(m)&&d(g)))continue;const S=E.transcoderFormat[A?1:0],w=E.engineFormat[A?1:0],I=E.engineType[0];return{transcoderFormat:S,engineFormat:w,engineType:I}}throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.")}function d(p){return p<=2?!0:(p&p-1)===0&&p!==0}function f(p){if(p.length===1)return p[0];let m=0;for(let _=0;_<p.length;_++){const x=p[_];m+=x.byteLength}const g=new Uint8Array(m);let A=0;for(let _=0;_<p.length;_++){const x=p[_];g.set(x,A),A+=x.byteLength}return g}};const IT=new Set([hn,ar,Xi]),yf={[B0]:hn,[I0]:hn,[_0]:hn,[w0]:hn,[M0]:ar,[C0]:ar,[E0]:ar,[y0]:ar,[S0]:Xi,[v0]:Xi,[b0]:Xi,[x0]:Xi,[pf]:lo,[R0]:ho,[T0]:ho},_f={[B0]:ln,[I0]:kn,[_0]:cn,[w0]:cn,[M0]:ln,[C0]:kn,[E0]:cn,[y0]:cn,[S0]:ln,[v0]:kn,[b0]:cn,[x0]:cn,[pf]:kn,[R0]:cn,[T0]:cn};async function ST(i){const{vkFormat:e}=i;if(yf[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let t;i.supercompressionScheme===g0&&(Ef||(Ef=new Promise(async r=>{const a=new wT;await a.init(),r(a)})),t=await Ef);const n=[];for(let r=0;r<i.levels.length;r++){const a=Math.max(1,i.pixelWidth>>r),o=Math.max(1,i.pixelHeight>>r),c=i.pixelDepth?Math.max(1,i.pixelDepth>>r):0,l=i.levels[r];let h;if(i.supercompressionScheme===AT)h=l.levelData;else if(i.supercompressionScheme===g0)h=t.decode(l.levelData,l.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let u;_f[e]===ln?u=new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):_f[e]===kn?u=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):u=h,n.push({data:u,width:a,height:o,depth:c})}let s;if(IT.has(yf[e]))s=i.pixelDepth===0?new ll(n[0].data,i.pixelWidth,i.pixelHeight):new mA(n[0].data,i.pixelWidth,i.pixelHeight,i.pixelDepth);else{if(i.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");s=new yl(n,i.pixelWidth,i.pixelHeight),s.minFilter=n.length===1?qt:ri,s.magFilter=qt}return s.mipmaps=n,s.type=_f[e],s.format=yf[e],s.colorSpace=D0(i),s.needsUpdate=!0,Promise.resolve(s)}function D0(i){const e=i.dataFormatDescriptor[0];return e.colorPrimaries===xT?e.transferFunction===m0?yt:un:e.colorPrimaries===bT?e.transferFunction===m0?vT:CT:(e.colorPrimaries===mT||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),mi)}const Zl="[default]",wf={ASSET_GENERATOR:"assetgenerator"},$l=new fg,L0=`https://unpkg.com/three@0.${Ic}.x`,MT=new dT($l).setDecoderPath(`${L0}/examples/jsm/libs/draco/gltf/`),BT=new ui($l).setTranscoderPath(`${L0}/examples/jsm/libs/basis/`);function P0(i,e){const t=new Set;i.traverse(n=>{if(!n.geometry)return;(Array.isArray(n.material)?n.material:[n.material]).forEach(r=>{r&&!t.has(r.uuid)&&(t.add(r.uuid),e(r))})})}function TT(i){const{state:e,options:t}=i;if(t.preset===wf.ASSET_GENERATOR){const r=new Pw;r.name="hemi_light",i.scene.add(r),i.lights.push(r);return}const n=new bg(e.ambientColor,e.ambientIntensity);n.name="ambient_light",i.defaultCamera.add(n);const s=new gd(e.directColor,e.directIntensity);s.position.set(.5,0,.866),s.name="main_light",i.defaultCamera.add(s),i.lights.push(n,s)}function RT(i){i.lights.forEach(e=>e.parent.remove(e)),i.lights.length=0}var di=Uint8Array,Fa=Uint16Array,FT=Int32Array,k0=new di([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),U0=new di([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),NT=new di([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),O0=function(i,e){for(var t=new Fa(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var s=new FT(t[30]),n=1;n<30;++n)for(var r=t[n];r<t[n+1];++r)s[r]=r-t[n]<<5|n;return{b:t,r:s}},Q0=O0(k0,2),G0=Q0.b,DT=Q0.r;G0[28]=258,DT[258]=28;for(var LT=O0(U0,0),PT=LT.b,vf=new Fa(32768),Ot=0;Ot<32768;++Ot){var Ws=(Ot&43690)>>1|(Ot&21845)<<1;Ws=(Ws&52428)>>2|(Ws&13107)<<2,Ws=(Ws&61680)>>4|(Ws&3855)<<4,vf[Ot]=((Ws&65280)>>8|(Ws&255)<<8)>>1}for(var qo=(function(i,e,t){for(var n=i.length,s=0,r=new Fa(e);s<n;++s)i[s]&&++r[i[s]-1];var a=new Fa(e);for(s=1;s<e;++s)a[s]=a[s-1]+r[s-1]<<1;var o;if(t){o=new Fa(1<<e);var c=15-e;for(s=0;s<n;++s)if(i[s])for(var l=s<<4|i[s],h=e-i[s],u=a[i[s]-1]++<<h,d=u|(1<<h)-1;u<=d;++u)o[vf[u]>>c]=l}else for(o=new Fa(n),s=0;s<n;++s)i[s]&&(o[s]=vf[a[i[s]-1]++]>>15-i[s]);return o}),Ko=new di(288),Ot=0;Ot<144;++Ot)Ko[Ot]=8;for(var Ot=144;Ot<256;++Ot)Ko[Ot]=9;for(var Ot=256;Ot<280;++Ot)Ko[Ot]=7;for(var Ot=280;Ot<288;++Ot)Ko[Ot]=8;for(var H0=new di(32),Ot=0;Ot<32;++Ot)H0[Ot]=5;var kT=qo(Ko,9,1),UT=qo(H0,5,1),Cf=function(i){for(var e=i[0],t=1;t<i.length;++t)i[t]>e&&(e=i[t]);return e},Si=function(i,e,t){var n=e/8|0;return(i[n]|i[n+1]<<8)>>(e&7)&t},If=function(i,e){var t=e/8|0;return(i[t]|i[t+1]<<8|i[t+2]<<16)>>(e&7)},OT=function(i){return(i+7)/8|0},QT=function(i,e,t){return(t==null||t>i.length)&&(t=i.length),new di(i.subarray(e,t))},GT=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Mi=function(i,e,t){var n=new Error(e||GT[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,Mi),!t)throw n;return n},HT=function(i,e,t,n){var s=i.length,r=0;if(!s||e.f&&!e.l)return t||new di(0);var a=!t,o=a||e.i!=2,c=e.i;a&&(t=new di(s*3));var l=function(Mt){var ft=t.length;if(Mt>ft){var $e=new di(Math.max(ft*2,Mt));$e.set(t),t=$e}},h=e.f||0,u=e.p||0,d=e.b||0,f=e.l,p=e.d,m=e.m,g=e.n,A=s*8;do{if(!f){h=Si(i,u,1);var _=Si(i,u+1,3);if(u+=3,_)if(_==1)f=kT,p=UT,m=9,g=5;else if(_==2){var w=Si(i,u,31)+257,I=Si(i,u+10,15)+4,T=w+Si(i,u+5,31)+1;u+=14;for(var C=new di(T),v=new di(19),F=0;F<I;++F)v[NT[F]]=Si(i,u+F*3,7);u+=I*3;for(var K=Cf(v),q=(1<<K)-1,$=qo(v,K,1),F=0;F<T;){var D=$[Si(i,u,q)];u+=D&15;var x=D>>4;if(x<16)C[F++]=x;else{var O=0,Y=0;for(x==16?(Y=3+Si(i,u,3),u+=2,O=C[F-1]):x==17?(Y=3+Si(i,u,7),u+=3):x==18&&(Y=11+Si(i,u,127),u+=7);Y--;)C[F++]=O}}var Q=C.subarray(0,w),J=C.subarray(w);m=Cf(Q),g=Cf(J),f=qo(Q,m,1),p=qo(J,g,1)}else Mi(1);else{var x=OT(u)+4,E=i[x-4]|i[x-3]<<8,S=x+E;if(S>s){c&&Mi(0);break}o&&l(d+E),t.set(i.subarray(x,S),d),e.b=d+=E,e.p=u=S*8,e.f=h;continue}if(u>A){c&&Mi(0);break}}o&&l(d+131072);for(var ee=(1<<m)-1,ae=(1<<g)-1,_e=u;;_e=u){var O=f[If(i,u)&ee],Me=O>>4;if(u+=O&15,u>A){c&&Mi(0);break}if(O||Mi(2),Me<256)t[d++]=Me;else if(Me==256){_e=u,f=null;break}else{var se=Me-254;if(Me>264){var F=Me-257,me=k0[F];se=Si(i,u,(1<<me)-1)+G0[F],u+=me}var xe=p[If(i,u)&ae],be=xe>>4;xe||Mi(3),u+=xe&15;var J=PT[be];if(be>3){var me=U0[be];J+=If(i,u)&(1<<me)-1,u+=me}if(u>A){c&&Mi(0);break}o&&l(d+131072);var Ue=d+se;if(d<J){var et=r-J,He=Math.min(J,Ue);for(et+d<0&&Mi(3);d<He;++d)t[d]=n[et+d]}for(;d<Ue;++d)t[d]=t[d-J]}}e.l=f,e.p=_e,e.b=d,e.f=h,f&&(h=1,e.m=m,e.d=p,e.n=g)}while(!h);return d!=t.length&&a?QT(t,0,d):t.subarray(0,d)},zT=new di(0),VT=function(i,e){return((i[0]&15)!=8||i[0]>>4>7||(i[0]<<8|i[1])%31)&&Mi(6,"invalid zlib data"),(i[1]>>5&1)==1&&Mi(6,"invalid zlib data: "+(i[1]&32?"need":"unexpected")+" dictionary"),(i[1]>>3&4)+2};function jo(i,e){return HT(i.subarray(VT(i),-4),{i:2},e,e)}var WT=typeof TextDecoder<"u"&&new TextDecoder,qT=0;try{WT.decode(zT,{stream:!0}),qT=1}catch{}class KT extends Lw{constructor(e){super(e),this.type=kn}parse(e){const C=Math.pow(2.7182818,2.2);function v(b,B){let k=0;for(let R=0;R<65536;++R)(R==0||b[R>>3]&1<<(R&7))&&(B[k++]=R);const y=k-1;for(;k<65536;)B[k++]=0;return y}function F(b){for(let B=0;B<16384;B++)b[B]={},b[B].len=0,b[B].lit=0,b[B].p=null}const K={l:0,c:0,lc:0};function q(b,B,k,y,R){for(;k<b;)B=B<<8|Te(y,R),k+=8;k-=b,K.l=B>>k&(1<<b)-1,K.c=B,K.lc=k}const $=new Array(59);function D(b){for(let k=0;k<=58;++k)$[k]=0;for(let k=0;k<65537;++k)$[b[k]]+=1;let B=0;for(let k=58;k>0;--k){const y=B+$[k]>>1;$[k]=B,B=y}for(let k=0;k<65537;++k){const y=b[k];y>0&&(b[k]=y|$[y]++<<6)}}function O(b,B,k,y,R,N){const U=B;let P=0,z=0;for(;y<=R;y++){if(U.value-B.value>k)return!1;q(6,P,z,b,U);const j=K.l;if(P=K.c,z=K.lc,N[y]=j,j==63){if(U.value-B.value>k)throw new Error("Something wrong with hufUnpackEncTable");q(8,P,z,b,U);let X=K.l+6;if(P=K.c,z=K.lc,y+X>R+1)throw new Error("Something wrong with hufUnpackEncTable");for(;X--;)N[y++]=0;y--}else if(j>=59){let X=j-59+2;if(y+X>R+1)throw new Error("Something wrong with hufUnpackEncTable");for(;X--;)N[y++]=0;y--}}D(N)}function Y(b){return b&63}function Q(b){return b>>6}function J(b,B,k,y){for(;B<=k;B++){const R=Q(b[B]),N=Y(b[B]);if(R>>N)throw new Error("Invalid table entry");if(N>14){const U=y[R>>N-14];if(U.len)throw new Error("Invalid table entry");if(U.lit++,U.p){const P=U.p;U.p=new Array(U.lit);for(let z=0;z<U.lit-1;++z)U.p[z]=P[z]}else U.p=new Array(1);U.p[U.lit-1]=B}else if(N){let U=0;for(let P=1<<14-N;P>0;P--){const z=y[(R<<14-N)+U];if(z.len||z.p)throw new Error("Invalid table entry");z.len=N,z.lit=B,U++}}}return!0}const ee={c:0,lc:0};function ae(b,B,k,y){b=b<<8|Te(k,y),B+=8,ee.c=b,ee.lc=B}const _e={c:0,lc:0};function Me(b,B,k,y,R,N,U,P,z){if(b==B){y<8&&(ae(k,y,R,N),k=ee.c,y=ee.lc),y-=8;let j=k>>y;if(j=new Uint8Array([j])[0],P.value+j>z)return!1;const X=U[P.value-1];for(;j-- >0;)U[P.value++]=X}else if(P.value<z)U[P.value++]=b;else return!1;_e.c=k,_e.lc=y}function se(b){return b&65535}function me(b){const B=se(b);return B>32767?B-65536:B}const xe={a:0,b:0};function be(b,B){const k=me(b),R=me(B),N=k+(R&1)+(R>>1),U=N,P=N-R;xe.a=U,xe.b=P}function Ue(b,B){const k=se(b),y=se(B),R=k-(y>>1)&65535,N=y+R-32768&65535;xe.a=N,xe.b=R}function et(b,B,k,y,R,N,U){const P=U<16384,z=k>R?R:k;let j=1,X,ie;for(;j<=z;)j<<=1;for(j>>=1,X=j,j>>=1;j>=1;){ie=0;const he=ie+N*(R-X),ce=N*j,fe=N*X,ge=y*j,ye=y*X;let Pe,je,Ve,Le;for(;ie<=he;ie+=fe){let rt=ie;const ke=ie+y*(k-X);for(;rt<=ke;rt+=ye){const It=rt+ge,mn=rt+ce,vt=mn+ge;P?(be(b[rt+B],b[mn+B]),Pe=xe.a,Ve=xe.b,be(b[It+B],b[vt+B]),je=xe.a,Le=xe.b,be(Pe,je),b[rt+B]=xe.a,b[It+B]=xe.b,be(Ve,Le),b[mn+B]=xe.a,b[vt+B]=xe.b):(Ue(b[rt+B],b[mn+B]),Pe=xe.a,Ve=xe.b,Ue(b[It+B],b[vt+B]),je=xe.a,Le=xe.b,Ue(Pe,je),b[rt+B]=xe.a,b[It+B]=xe.b,Ue(Ve,Le),b[mn+B]=xe.a,b[vt+B]=xe.b)}if(k&j){const It=rt+ce;P?be(b[rt+B],b[It+B]):Ue(b[rt+B],b[It+B]),Pe=xe.a,b[It+B]=xe.b,b[rt+B]=Pe}}if(R&j){let rt=ie;const ke=ie+y*(k-X);for(;rt<=ke;rt+=ye){const It=rt+ge;P?be(b[rt+B],b[It+B]):Ue(b[rt+B],b[It+B]),Pe=xe.a,b[It+B]=xe.b,b[rt+B]=Pe}}X=j,j>>=1}return ie}function He(b,B,k,y,R,N,U,P,z){let j=0,X=0;const ie=U,he=Math.trunc(y.value+(R+7)/8);for(;y.value<he;)for(ae(j,X,k,y),j=ee.c,X=ee.lc;X>=14;){const fe=j>>X-14&16383,ge=B[fe];if(ge.len)X-=ge.len,Me(ge.lit,N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;else{if(!ge.p)throw new Error("hufDecode issues");let ye;for(ye=0;ye<ge.lit;ye++){const Pe=Y(b[ge.p[ye]]);for(;X<Pe&&y.value<he;)ae(j,X,k,y),j=ee.c,X=ee.lc;if(X>=Pe&&Q(b[ge.p[ye]])==(j>>X-Pe&(1<<Pe)-1)){X-=Pe,Me(ge.p[ye],N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;break}}if(ye==ge.lit)throw new Error("hufDecode issues")}}const ce=8-R&7;for(j>>=ce,X-=ce;X>0;){const fe=B[j<<14-X&16383];if(fe.len)X-=fe.len,Me(fe.lit,N,j,X,k,y,P,z,ie),j=_e.c,X=_e.lc;else throw new Error("hufDecode issues")}return!0}function Mt(b,B,k,y,R,N){const U={value:0},P=k.value,z=Ge(B,k),j=Ge(B,k);k.value+=4;const X=Ge(B,k);if(k.value+=4,z<0||z>=65537||j<0||j>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const ie=new Array(65537),he=new Array(16384);F(he);const ce=y-(k.value-P);if(O(b,k,ce,z,j,ie),X>8*(y-(k.value-P)))throw new Error("Something wrong with hufUncompress");J(ie,z,j,he),He(ie,he,b,k,X,j,N,R,U)}function ft(b,B,k){for(let y=0;y<k;++y)B[y]=b[B[y]]}function $e(b){for(let B=1;B<b.length;B++){const k=b[B-1]+b[B]-128;b[B]=k}}function H(b,B){let k=0,y=Math.floor((b.length+1)/2),R=0;const N=b.length-1;for(;!(R>N||(B[R++]=b[k++],R>N));)B[R++]=b[y++]}function wn(b){let B=b.byteLength;const k=new Array;let y=0;const R=new DataView(b);for(;B>0;){const N=R.getInt8(y++);if(N<0){const U=-N;B-=U+1;for(let P=0;P<U;P++)k.push(R.getUint8(y++))}else{const U=N;B-=2;const P=R.getUint8(y++);for(let z=0;z<U+1;z++)k.push(P)}}return k}function pt(b,B,k,y,R,N){let U=new DataView(N.buffer);const P=k[b.idx[0]].width,z=k[b.idx[0]].height,j=3,X=Math.floor(P/8),ie=Math.ceil(P/8),he=Math.ceil(z/8),ce=P-(ie-1)*8,fe=z-(he-1)*8,ge={value:0},ye=new Array(j),Pe=new Array(j),je=new Array(j),Ve=new Array(j),Le=new Array(j);for(let ke=0;ke<j;++ke)Le[ke]=B[b.idx[ke]],ye[ke]=ke<1?0:ye[ke-1]+ie*he,Pe[ke]=new Float32Array(64),je[ke]=new Uint16Array(64),Ve[ke]=new Uint16Array(ie*64);for(let ke=0;ke<he;++ke){let It=8;ke==he-1&&(It=fe);let mn=8;for(let Et=0;Et<ie;++Et){Et==ie-1&&(mn=ce);for(let Xe=0;Xe<j;++Xe)je[Xe].fill(0),je[Xe][0]=R[ye[Xe]++],mt(ge,y,je[Xe]),We(je[Xe],Pe[Xe]),Dt(Pe[Xe]);ze(Pe);for(let Xe=0;Xe<j;++Xe)L(Pe[Xe],Ve[Xe],Et*64)}let vt=0;for(let Et=0;Et<j;++Et){const Xe=k[b.idx[Et]].type;for(let Xt=8*ke;Xt<8*ke+It;++Xt){vt=Le[Et][Xt];for(let Cn=0;Cn<X;++Cn){const Ut=Cn*64+(Xt&7)*8;U.setUint16(vt+0*Xe,Ve[Et][Ut+0],!0),U.setUint16(vt+2*Xe,Ve[Et][Ut+1],!0),U.setUint16(vt+4*Xe,Ve[Et][Ut+2],!0),U.setUint16(vt+6*Xe,Ve[Et][Ut+3],!0),U.setUint16(vt+8*Xe,Ve[Et][Ut+4],!0),U.setUint16(vt+10*Xe,Ve[Et][Ut+5],!0),U.setUint16(vt+12*Xe,Ve[Et][Ut+6],!0),U.setUint16(vt+14*Xe,Ve[Et][Ut+7],!0),vt+=16*Xe}}if(X!=ie)for(let Xt=8*ke;Xt<8*ke+It;++Xt){const Cn=Le[Et][Xt]+8*X*2*Xe,Ut=X*64+(Xt&7)*8;for(let xn=0;xn<mn;++xn)U.setUint16(Cn+xn*2*Xe,Ve[Et][Ut+xn],!0)}}}const rt=new Uint16Array(P);U=new DataView(N.buffer);for(let ke=0;ke<j;++ke){k[b.idx[ke]].decoded=!0;const It=k[b.idx[ke]].type;if(k[ke].type==2)for(let mn=0;mn<z;++mn){const vt=Le[ke][mn];for(let Et=0;Et<P;++Et)rt[Et]=U.getUint16(vt+Et*2*It,!0);for(let Et=0;Et<P;++Et)U.setFloat32(vt+Et*2*It,ne(rt[Et]),!0)}}}function mt(b,B,k){let y,R=1;for(;R<64;)y=B[b.value],y==65280?R=64:y>>8==255?R+=y&255:(k[R]=y,R++),b.value++}function We(b,B){B[0]=ne(b[0]),B[1]=ne(b[1]),B[2]=ne(b[5]),B[3]=ne(b[6]),B[4]=ne(b[14]),B[5]=ne(b[15]),B[6]=ne(b[27]),B[7]=ne(b[28]),B[8]=ne(b[2]),B[9]=ne(b[4]),B[10]=ne(b[7]),B[11]=ne(b[13]),B[12]=ne(b[16]),B[13]=ne(b[26]),B[14]=ne(b[29]),B[15]=ne(b[42]),B[16]=ne(b[3]),B[17]=ne(b[8]),B[18]=ne(b[12]),B[19]=ne(b[17]),B[20]=ne(b[25]),B[21]=ne(b[30]),B[22]=ne(b[41]),B[23]=ne(b[43]),B[24]=ne(b[9]),B[25]=ne(b[11]),B[26]=ne(b[18]),B[27]=ne(b[24]),B[28]=ne(b[31]),B[29]=ne(b[40]),B[30]=ne(b[44]),B[31]=ne(b[53]),B[32]=ne(b[10]),B[33]=ne(b[19]),B[34]=ne(b[23]),B[35]=ne(b[32]),B[36]=ne(b[39]),B[37]=ne(b[45]),B[38]=ne(b[52]),B[39]=ne(b[54]),B[40]=ne(b[20]),B[41]=ne(b[22]),B[42]=ne(b[33]),B[43]=ne(b[38]),B[44]=ne(b[46]),B[45]=ne(b[51]),B[46]=ne(b[55]),B[47]=ne(b[60]),B[48]=ne(b[21]),B[49]=ne(b[34]),B[50]=ne(b[37]),B[51]=ne(b[47]),B[52]=ne(b[50]),B[53]=ne(b[56]),B[54]=ne(b[59]),B[55]=ne(b[61]),B[56]=ne(b[35]),B[57]=ne(b[36]),B[58]=ne(b[48]),B[59]=ne(b[49]),B[60]=ne(b[57]),B[61]=ne(b[58]),B[62]=ne(b[62]),B[63]=ne(b[63])}function Dt(b){const B=.5*Math.cos(.7853975),k=.5*Math.cos(3.14159/16),y=.5*Math.cos(3.14159/8),R=.5*Math.cos(3*3.14159/16),N=.5*Math.cos(5*3.14159/16),U=.5*Math.cos(3*3.14159/8),P=.5*Math.cos(7*3.14159/16),z=new Array(4),j=new Array(4),X=new Array(4),ie=new Array(4);for(let he=0;he<8;++he){const ce=he*8;z[0]=y*b[ce+2],z[1]=U*b[ce+2],z[2]=y*b[ce+6],z[3]=U*b[ce+6],j[0]=k*b[ce+1]+R*b[ce+3]+N*b[ce+5]+P*b[ce+7],j[1]=R*b[ce+1]-P*b[ce+3]-k*b[ce+5]-N*b[ce+7],j[2]=N*b[ce+1]-k*b[ce+3]+P*b[ce+5]+R*b[ce+7],j[3]=P*b[ce+1]-N*b[ce+3]+R*b[ce+5]-k*b[ce+7],X[0]=B*(b[ce+0]+b[ce+4]),X[3]=B*(b[ce+0]-b[ce+4]),X[1]=z[0]+z[3],X[2]=z[1]-z[2],ie[0]=X[0]+X[1],ie[1]=X[3]+X[2],ie[2]=X[3]-X[2],ie[3]=X[0]-X[1],b[ce+0]=ie[0]+j[0],b[ce+1]=ie[1]+j[1],b[ce+2]=ie[2]+j[2],b[ce+3]=ie[3]+j[3],b[ce+4]=ie[3]-j[3],b[ce+5]=ie[2]-j[2],b[ce+6]=ie[1]-j[1],b[ce+7]=ie[0]-j[0]}for(let he=0;he<8;++he)z[0]=y*b[16+he],z[1]=U*b[16+he],z[2]=y*b[48+he],z[3]=U*b[48+he],j[0]=k*b[8+he]+R*b[24+he]+N*b[40+he]+P*b[56+he],j[1]=R*b[8+he]-P*b[24+he]-k*b[40+he]-N*b[56+he],j[2]=N*b[8+he]-k*b[24+he]+P*b[40+he]+R*b[56+he],j[3]=P*b[8+he]-N*b[24+he]+R*b[40+he]-k*b[56+he],X[0]=B*(b[he]+b[32+he]),X[3]=B*(b[he]-b[32+he]),X[1]=z[0]+z[3],X[2]=z[1]-z[2],ie[0]=X[0]+X[1],ie[1]=X[3]+X[2],ie[2]=X[3]-X[2],ie[3]=X[0]-X[1],b[0+he]=ie[0]+j[0],b[8+he]=ie[1]+j[1],b[16+he]=ie[2]+j[2],b[24+he]=ie[3]+j[3],b[32+he]=ie[3]-j[3],b[40+he]=ie[2]-j[2],b[48+he]=ie[1]-j[1],b[56+he]=ie[0]-j[0]}function ze(b){for(let B=0;B<64;++B){const k=b[0][B],y=b[1][B],R=b[2][B];b[0][B]=k+1.5747*R,b[1][B]=k-.1873*y-.4682*R,b[2][B]=k+1.8556*y}}function L(b,B,k){for(let y=0;y<64;++y)B[k+y]=BA.toHalfFloat(M(b[y]))}function M(b){return b<=1?Math.sign(b)*Math.pow(Math.abs(b),2.2):Math.sign(b)*Math.pow(C,Math.abs(b)-1)}function Z(b){return new DataView(b.array.buffer,b.offset.value,b.size)}function le(b){const B=b.viewer.buffer.slice(b.offset.value,b.offset.value+b.size),k=new Uint8Array(wn(B)),y=new Uint8Array(k.length);return $e(k),H(k,y),new DataView(y.buffer)}function Ae(b){const B=b.array.slice(b.offset.value,b.offset.value+b.size),k=jo(B),y=new Uint8Array(k.length);return $e(k),H(k,y),new DataView(y.buffer)}function oe(b){const B=b.viewer,k={value:b.offset.value},y=new Uint16Array(b.columns*b.lines*(b.inputChannels.length*b.type)),R=new Uint8Array(8192);let N=0;const U=new Array(b.inputChannels.length);for(let fe=0,ge=b.inputChannels.length;fe<ge;fe++)U[fe]={},U[fe].start=N,U[fe].end=U[fe].start,U[fe].nx=b.columns,U[fe].ny=b.lines,U[fe].size=b.type,N+=U[fe].nx*U[fe].ny*U[fe].size;const P=re(B,k),z=re(B,k);if(z>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(P<=z)for(let fe=0;fe<z-P+1;fe++)R[fe+P]=nt(B,k);const j=new Uint16Array(65536),X=v(R,j),ie=Ge(B,k);Mt(b.array,B,k,ie,y,N);for(let fe=0;fe<b.inputChannels.length;++fe){const ge=U[fe];for(let ye=0;ye<U[fe].size;++ye)et(y,ge.start+ye,ge.nx,ge.size,ge.ny,ge.nx*ge.size,X)}ft(j,y,N);let he=0;const ce=new Uint8Array(y.buffer.byteLength);for(let fe=0;fe<b.lines;fe++)for(let ge=0;ge<b.inputChannels.length;ge++){const ye=U[ge],Pe=ye.nx*ye.size,je=new Uint8Array(y.buffer,ye.end*2,Pe*2);ce.set(je,he),he+=Pe*2,ye.end+=Pe}return new DataView(ce.buffer)}function Qe(b){const B=b.array.slice(b.offset.value,b.offset.value+b.size),k=jo(B),y=b.inputChannels.length*b.lines*b.columns*b.totalBytes,R=new ArrayBuffer(y),N=new DataView(R);let U=0,P=0;const z=new Array(4);for(let j=0;j<b.lines;j++)for(let X=0;X<b.inputChannels.length;X++){let ie=0;switch(b.inputChannels[X].pixelType){case 1:z[0]=U,z[1]=z[0]+b.columns,U=z[1]+b.columns;for(let ce=0;ce<b.columns;++ce){const fe=k[z[0]++]<<8|k[z[1]++];ie+=fe,N.setUint16(P,ie,!0),P+=2}break;case 2:z[0]=U,z[1]=z[0]+b.columns,z[2]=z[1]+b.columns,U=z[2]+b.columns;for(let ce=0;ce<b.columns;++ce){const fe=k[z[0]++]<<24|k[z[1]++]<<16|k[z[2]++]<<8;ie+=fe,N.setUint32(P,ie,!0),P+=4}break}}return N}function ve(b){const B=b.viewer,k={value:b.offset.value},y=new Uint8Array(b.columns*b.lines*(b.inputChannels.length*b.type*2)),R={version:Ke(B,k),unknownUncompressedSize:Ke(B,k),unknownCompressedSize:Ke(B,k),acCompressedSize:Ke(B,k),dcCompressedSize:Ke(B,k),rleCompressedSize:Ke(B,k),rleUncompressedSize:Ke(B,k),rleRawSize:Ke(B,k),totalAcUncompressedCount:Ke(B,k),totalDcUncompressedCount:Ke(B,k),acCompression:Ke(B,k)};if(R.version<2)throw new Error("EXRLoader.parse: "+vs.compression+" version "+R.version+" is unsupported");const N=new Array;let U=re(B,k)-2;for(;U>0;){const ge=qe(B.buffer,k),ye=nt(B,k),Pe=ye>>2&3,je=(ye>>4)-1,Ve=new Int8Array([je])[0],Le=nt(B,k);N.push({name:ge,index:Ve,type:Le,compression:Pe}),U-=ge.length+3}const P=vs.channels,z=new Array(b.inputChannels.length);for(let ge=0;ge<b.inputChannels.length;++ge){const ye=z[ge]={},Pe=P[ge];ye.name=Pe.name,ye.compression=0,ye.decoded=!1,ye.type=Pe.pixelType,ye.pLinear=Pe.pLinear,ye.width=b.columns,ye.height=b.lines}const j={idx:new Array(3)};for(let ge=0;ge<b.inputChannels.length;++ge){const ye=z[ge];for(let Pe=0;Pe<N.length;++Pe){const je=N[Pe];ye.name==je.name&&(ye.compression=je.compression,je.index>=0&&(j.idx[je.index]=ge),ye.offset=ge)}}let X,ie,he;if(R.acCompressedSize>0)switch(R.acCompression){case 0:X=new Uint16Array(R.totalAcUncompressedCount),Mt(b.array,B,k,R.acCompressedSize,X,R.totalAcUncompressedCount);break;case 1:const ge=b.array.slice(k.value,k.value+R.totalAcUncompressedCount),ye=jo(ge);X=new Uint16Array(ye.buffer),k.value+=R.totalAcUncompressedCount;break}if(R.dcCompressedSize>0){const ge={array:b.array,offset:k,size:R.dcCompressedSize};ie=new Uint16Array(Ae(ge).buffer),k.value+=R.dcCompressedSize}if(R.rleRawSize>0){const ge=b.array.slice(k.value,k.value+R.rleCompressedSize),ye=jo(ge);he=wn(ye.buffer),k.value+=R.rleCompressedSize}let ce=0;const fe=new Array(z.length);for(let ge=0;ge<fe.length;++ge)fe[ge]=new Array;for(let ge=0;ge<b.lines;++ge)for(let ye=0;ye<z.length;++ye)fe[ye].push(ce),ce+=z[ye].width*b.type*2;pt(j,fe,z,X,ie,y);for(let ge=0;ge<z.length;++ge){const ye=z[ge];if(!ye.decoded)switch(ye.compression){case 2:let Pe=0,je=0;for(let Ve=0;Ve<b.lines;++Ve){let Le=fe[ge][Pe];for(let rt=0;rt<ye.width;++rt){for(let ke=0;ke<2*ye.type;++ke)y[Le++]=he[je+ke*ye.width*ye.height];je++}Pe++}break;default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(y.buffer)}function qe(b,B){const k=new Uint8Array(b);let y=0;for(;k[B.value+y]!=0;)y+=1;const R=new TextDecoder().decode(k.slice(B.value,B.value+y));return B.value=B.value+y+1,R}function Ze(b,B,k){const y=new TextDecoder().decode(new Uint8Array(b).slice(B.value,B.value+k));return B.value=B.value+k,y}function Ee(b,B){const k=Oe(b,B),y=Ge(b,B);return[k,y]}function De(b,B){const k=Ge(b,B),y=Ge(b,B);return[k,y]}function Oe(b,B){const k=b.getInt32(B.value,!0);return B.value=B.value+4,k}function Ge(b,B){const k=b.getUint32(B.value,!0);return B.value=B.value+4,k}function Te(b,B){const k=b[B.value];return B.value=B.value+1,k}function nt(b,B){const k=b.getUint8(B.value);return B.value=B.value+1,k}const Ke=function(b,B){let k;return"getBigInt64"in DataView.prototype?k=Number(b.getBigInt64(B.value,!0)):k=b.getUint32(B.value+4,!0)+Number(b.getUint32(B.value,!0)<<32),B.value+=8,k};function it(b,B){const k=b.getFloat32(B.value,!0);return B.value+=4,k}function W(b,B){return BA.toHalfFloat(it(b,B))}function ne(b){const B=(b&31744)>>10,k=b&1023;return(b>>15?-1:1)*(B?B===31?k?NaN:1/0:Math.pow(2,B-15)*(1+k/1024):6103515625e-14*(k/1024))}function re(b,B){const k=b.getUint16(B.value,!0);return B.value+=2,k}function de(b,B){return ne(re(b,B))}function Se(b,B,k,y){const R=k.value,N=[];for(;k.value<R+y-1;){const U=qe(B,k),P=Oe(b,k),z=nt(b,k);k.value+=3;const j=Oe(b,k),X=Oe(b,k);N.push({name:U,pixelType:P,pLinear:z,xSampling:j,ySampling:X})}return k.value+=1,N}function Ie(b,B){const k=it(b,B),y=it(b,B),R=it(b,B),N=it(b,B),U=it(b,B),P=it(b,B),z=it(b,B),j=it(b,B);return{redX:k,redY:y,greenX:R,greenY:N,blueX:U,blueY:P,whiteX:z,whiteY:j}}function st(b,B){const k=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],y=nt(b,B);return k[y]}function Ht(b,B){const k=Oe(b,B),y=Oe(b,B),R=Oe(b,B),N=Oe(b,B);return{xMin:k,yMin:y,xMax:R,yMax:N}}function vn(b,B){const k=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],y=nt(b,B);return k[y]}function Ct(b,B){const k=["ENVMAP_LATLONG","ENVMAP_CUBE"],y=nt(b,B);return k[y]}function si(b,B){const k=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],y=["ROUND_DOWN","ROUND_UP"],R=Ge(b,B),N=Ge(b,B),U=nt(b,B);return{xSize:R,ySize:N,levelMode:k[U&15],roundingMode:y[U>>4]}}function Li(b,B){const k=it(b,B),y=it(b,B);return[k,y]}function Gh(b,B){const k=it(b,B),y=it(b,B),R=it(b,B);return[k,y,R]}function Hh(b,B,k,y,R){if(y==="string"||y==="stringvector"||y==="iccProfile")return Ze(B,k,R);if(y==="chlist")return Se(b,B,k,R);if(y==="chromaticities")return Ie(b,k);if(y==="compression")return st(b,k);if(y==="box2i")return Ht(b,k);if(y==="envmap")return Ct(b,k);if(y==="tiledesc")return si(b,k);if(y==="lineOrder")return vn(b,k);if(y==="float")return it(b,k);if(y==="v2f")return Li(b,k);if(y==="v3f")return Gh(b,k);if(y==="int")return Oe(b,k);if(y==="rational")return Ee(b,k);if(y==="timecode")return De(b,k);if(y==="preview")return k.value+=R,"skipped";k.value+=R}function ws(b,B){const k=Math.log2(b);return B=="ROUND_DOWN"?Math.floor(k):Math.ceil(k)}function _c(b,B,k){let y=0;switch(b.levelMode){case"ONE_LEVEL":y=1;break;case"MIPMAP_LEVELS":y=ws(Math.max(B,k),b.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return y}function wc(b,B,k,y){const R=new Array(b);for(let N=0;N<b;N++){const U=1<<N;let P=B/U|0;y=="ROUND_UP"&&P*U<B&&(P+=1);const z=Math.max(P,1);R[N]=(z+k-1)/k|0}return R}function zh(){const b=this,B=b.offset,k={value:0};for(let y=0;y<b.tileCount;y++){const R=Oe(b.viewer,B),N=Oe(b.viewer,B);B.value+=8,b.size=Ge(b.viewer,B);const U=R*b.blockWidth,P=N*b.blockHeight;b.columns=U+b.blockWidth>b.width?b.width-U:b.blockWidth,b.lines=P+b.blockHeight>b.height?b.height-P:b.blockHeight;const z=b.columns*b.totalBytes,X=b.size<b.lines*z?b.uncompress(b):Z(b);B.value+=b.size;for(let ie=0;ie<b.lines;ie++){const he=ie*b.columns*b.totalBytes;for(let ce=0;ce<b.inputChannels.length;ce++){const fe=vs.channels[ce].name,ge=b.channelByteOffsets[fe]*b.columns,ye=b.decodeChannels[fe];if(ye===void 0)continue;k.value=he+ge;const Pe=(b.height-(1+P+ie))*b.outLineWidth;for(let je=0;je<b.columns;je++){const Ve=Pe+(je+U)*b.outputChannels+ye;b.byteArray[Ve]=b.getter(X,k)}}}}}function eo(){const b=this,B=b.offset,k={value:0};for(let y=0;y<b.height/b.blockHeight;y++){const R=Oe(b.viewer,B)-vs.dataWindow.yMin;b.size=Ge(b.viewer,B),b.lines=R+b.blockHeight>b.height?b.height-R:b.blockHeight;const N=b.columns*b.totalBytes,P=b.size<b.lines*N?b.uncompress(b):Z(b);B.value+=b.size;for(let z=0;z<b.blockHeight;z++){const j=y*b.blockHeight,X=z+b.scanOrder(j);if(X>=b.height)continue;const ie=z*N,he=(b.height-1-X)*b.outLineWidth;for(let ce=0;ce<b.inputChannels.length;ce++){const fe=vs.channels[ce].name,ge=b.channelByteOffsets[fe]*b.columns,ye=b.decodeChannels[fe];if(ye!==void 0){k.value=ie+ge;for(let Pe=0;Pe<b.columns;Pe++){const je=he+Pe*b.outputChannels+ye;b.byteArray[je]=b.getter(P,k)}}}}}}function Vh(b,B,k){const y={};if(b.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");y.version=b.getUint8(4);const R=b.getUint8(5);y.spec={singleTile:!!(R&2),longName:!!(R&4),deepFormat:!!(R&8),multiPart:!!(R&16)},k.value=8;let N=!0;for(;N;){const U=qe(B,k);if(U==="")N=!1;else{const P=qe(B,k),z=Ge(b,k),j=Hh(b,B,k,P,z);j===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${P}'.`):y[U]=j}}if((R&-7)!=0)throw console.error("THREE.EXRHeader:",y),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return y}function to(b,B,k,y,R){const N={size:0,viewer:B,array:k,offset:y,width:b.dataWindow.xMax-b.dataWindow.xMin+1,height:b.dataWindow.yMax-b.dataWindow.yMin+1,inputChannels:b.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:un};switch(b.compression){case"NO_COMPRESSION":N.blockHeight=1,N.uncompress=Z;break;case"RLE_COMPRESSION":N.blockHeight=1,N.uncompress=le;break;case"ZIPS_COMPRESSION":N.blockHeight=1,N.uncompress=Ae;break;case"ZIP_COMPRESSION":N.blockHeight=16,N.uncompress=Ae;break;case"PIZ_COMPRESSION":N.blockHeight=32,N.uncompress=oe;break;case"PXR24_COMPRESSION":N.blockHeight=16,N.uncompress=Qe;break;case"DWAA_COMPRESSION":N.blockHeight=32,N.uncompress=ve;break;case"DWAB_COMPRESSION":N.blockHeight=256,N.uncompress=ve;break;default:throw new Error("EXRLoader.parse: "+b.compression+" is unsupported")}const U={};for(const X of b.channels)switch(X.name){case"Y":case"R":case"G":case"B":case"A":U[X.name]=!0,N.type=X.pixelType}let P=!1;if(U.R&&U.G&&U.B)P=!U.A,N.outputChannels=4,N.decodeChannels={R:0,G:1,B:2,A:3};else if(U.Y)N.outputChannels=1,N.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(N.type==1)switch(R){case ln:N.getter=de;break;case kn:N.getter=re;break}else if(N.type==2)switch(R){case ln:N.getter=it;break;case kn:N.getter=W}else throw new Error("EXRLoader.parse: unsupported pixelType "+N.type+" for "+b.compression+".");N.columns=N.width;const z=N.width*N.height*N.outputChannels;switch(R){case ln:N.byteArray=new Float32Array(z),P&&N.byteArray.fill(1,0,z);break;case kn:N.byteArray=new Uint16Array(z),P&&N.byteArray.fill(15360,0,z);break;default:console.error("THREE.EXRLoader: unsupported type: ",R);break}let j=0;for(const X of b.channels)N.decodeChannels[X.name]!==void 0&&(N.channelByteOffsets[X.name]=j),j+=X.pixelType*2;if(N.totalBytes=j,N.outLineWidth=N.width*N.outputChannels,b.lineOrder==="INCREASING_Y"?N.scanOrder=X=>X:N.scanOrder=X=>N.height-1-X,N.outputChannels==4?(N.format=hn,N.colorSpace=un):(N.format=Xi,N.colorSpace=mi),b.spec.singleTile){N.blockHeight=b.tiles.ySize,N.blockWidth=b.tiles.xSize;const X=_c(b.tiles,N.width,N.height),ie=wc(X,N.width,b.tiles.xSize,b.tiles.roundingMode),he=wc(X,N.height,b.tiles.ySize,b.tiles.roundingMode);N.tileCount=ie[0]*he[0];for(let ce=0;ce<X;ce++)for(let fe=0;fe<he[ce];fe++)for(let ge=0;ge<ie[ce];ge++)Ke(B,y);N.decode=zh.bind(N)}else{N.blockWidth=N.width;const X=Math.ceil(N.height/N.blockHeight);for(let ie=0;ie<X;ie++)Ke(B,y);N.decode=eo.bind(N)}return N}const vc={value:0},Cc=new DataView(e),Hp=new Uint8Array(e),vs=Vh(Cc,e,vc),tr=to(vs,Cc,Hp,vc,this.type);return tr.decode(),{header:vs,width:tr.width,height:tr.height,data:tr.byteArray,format:tr.format,colorSpace:tr.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,s){function r(a,o){a.colorSpace=o.colorSpace,a.minFilter=qt,a.magFilter=qt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,o)}return super.load(e,r,n,s)}}function jT(i,e){const{id:t,path:n}=e;return t==="neutral"?Promise.resolve({envMap:i.neutralEnvironment}):t===""?Promise.resolve({envMap:null}):new Promise((s,r)=>{new KT().load(n,a=>{const o=i.pmremGenerator.fromEquirectangular(a).texture;a.dispose(),i._loadedEnvironment&&i._loadedEnvironment!==o&&i._loadedEnvironment.dispose(),i._loadedEnvironment=o,s({envMap:o})},void 0,r)})}function XT(i){i.renderer.render(i.scene,i.activeCamera),i.renderer.domElement.toBlob(e=>{if(!e)return;const t=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),n=URL.createObjectURL(e),s=document.createElement("a");s.download=`3d-screenshot-${t}.png`,s.href=n,s.click(),URL.revokeObjectURL(n)},"image/png"),YT(i)}function YT(i){const e=document.createElement("div");e.className="screenshot-flash",i.el.appendChild(e),e.addEventListener("animationend",()=>e.remove())}function JT(i,e){i.mixer&&(i.mixer.stopAllAction(),i.mixer.uncacheRoot(i.mixer.getRoot()),i.mixer=null),i.clips=e,e.length&&(i.mixer=new Eg(i.content))}function ZT(i){i.clips.forEach(e=>{i.mixer.clipAction(e).reset().play(),i.state.actionStates[e.name]=!0}),i.invalidate()}function z0(i,e,t){const n=t.length-i-1;if(e>=t[n])return n-1;if(e<=t[i])return i;let s=i,r=n,a=Math.floor((s+r)/2);for(;e<t[a]||e>=t[a+1];)e<t[a]?r=a:s=a,a=Math.floor((s+r)/2);return a}function $T(i,e,t,n){const s=[],r=[],a=[];s[0]=1;for(let o=1;o<=t;++o){r[o]=e-n[i+1-o],a[o]=n[i+o]-e;let c=0;for(let l=0;l<o;++l){const h=a[l+1],u=r[o-l],d=s[l]/(h+u);s[l]=c+h*d,c=u*d}s[o]=c}return s}function eR(i,e,t,n){const s=z0(i,n,e),r=$T(s,n,i,e),a=new gt(0,0,0,0);for(let o=0;o<=i;++o){const c=t[s-i+o],l=r[o],h=c.w*l;a.x+=c.x*h,a.y+=c.y*h,a.z+=c.z*h,a.w+=c.w*l}return a}function tR(i,e,t,n,s){const r=[];for(let u=0;u<=t;++u)r[u]=0;const a=[];for(let u=0;u<=n;++u)a[u]=r.slice(0);const o=[];for(let u=0;u<=t;++u)o[u]=r.slice(0);o[0][0]=1;const c=r.slice(0),l=r.slice(0);for(let u=1;u<=t;++u){c[u]=e-s[i+1-u],l[u]=s[i+u]-e;let d=0;for(let f=0;f<u;++f){const p=l[f+1],m=c[u-f];o[u][f]=p+m;const g=o[f][u-1]/o[u][f];o[f][u]=d+p*g,d=m*g}o[u][u]=d}for(let u=0;u<=t;++u)a[0][u]=o[u][t];for(let u=0;u<=t;++u){let d=0,f=1;const p=[];for(let m=0;m<=t;++m)p[m]=r.slice(0);p[0][0]=1;for(let m=1;m<=n;++m){let g=0;const A=u-m,_=t-m;u>=m&&(p[f][0]=p[d][0]/o[_+1][A],g=p[f][0]*o[A][_]);const x=A>=-1?1:-A,E=u-1<=_?m-1:t-u;for(let w=x;w<=E;++w)p[f][w]=(p[d][w]-p[d][w-1])/o[_+1][A+w],g+=p[f][w]*o[A+w][_];u<=_&&(p[f][m]=-p[d][m-1]/o[_+1][u],g+=p[f][m]*o[u][_]),a[m][u]=g;const S=d;d=f,f=S}}let h=t;for(let u=1;u<=n;++u){for(let d=0;d<=t;++d)a[u][d]*=h;h*=t-u}return a}function nR(i,e,t,n,s){const r=s<i?s:i,a=[],o=z0(i,n,e),c=tR(o,n,i,r,e),l=[];for(let h=0;h<t.length;++h){const u=t[h].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,l[h]=u}for(let h=0;h<=r;++h){const u=l[o-i].clone().multiplyScalar(c[h][0]);for(let d=1;d<=i;++d)u.add(l[o-i+d].clone().multiplyScalar(c[h][d]));a[h]=u}for(let h=r+1;h<=s+1;++h)a[h]=new gt(0,0,0);return a}function iR(i,e){let t=1;for(let s=2;s<=i;++s)t*=s;let n=1;for(let s=2;s<=e;++s)n*=s;for(let s=2;s<=i-e;++s)n*=s;return t/n}function sR(i){const e=i.length,t=[],n=[];for(let r=0;r<e;++r){const a=i[r];t[r]=new G(a.x,a.y,a.z),n[r]=a.w}const s=[];for(let r=0;r<e;++r){const a=t[r].clone();for(let o=1;o<=r;++o)a.sub(s[r-o].clone().multiplyScalar(iR(r,o)*n[o]));s[r]=a.divideScalar(n[0])}return s}function rR(i,e,t,n,s){const r=nR(i,e,t,n,s);return sR(r)}class aR extends iw{constructor(e,t,n,s,r){super();const a=t?t.length-1:0,o=n?n.length:0;this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=s||0,this.endKnot=r||a;for(let c=0;c<o;++c){const l=n[c];this.controlPoints[c]=new gt(l.x,l.y,l.z,l.w)}}getPoint(e,t=new G){const n=t,s=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=eR(this.degree,this.knots,this.controlPoints,s);return r.w!==1&&r.divideScalar(r.w),n.set(r.x,r.y,r.z)}getTangent(e,t=new G){const n=t,s=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),r=rR(this.degree,this.knots,this.controlPoints,s,1);return n.copy(r[1]).normalize(),n}toJSON(){const e=super.toJSON();return e.degree=this.degree,e.knots=[...this.knots],e.controlPoints=this.controlPoints.map(t=>t.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(t=>new gt(t[0],t[1],t[2],t[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}}let ht,$t,Gn;class oR extends ci{constructor(e){super(e)}load(e,t,n,s){const r=this,a=r.path===""?Ar.extractUrlBase(e):r.path,o=new os(this.manager);o.setPath(r.path),o.setResponseType("arraybuffer"),o.setRequestHeader(r.requestHeader),o.setWithCredentials(r.withCredentials),o.load(e,function(c){try{t(r.parse(c,a))}catch(l){s?s(l):console.error(l),r.manager.itemError(e)}},n,s)}parse(e,t){if(fR(e))ht=new dR().parse(e);else{const s=j0(e);if(!pR(s))throw new Error("THREE.FBXLoader: Unknown format.");if(q0(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+q0(s));ht=new uR().parse(s)}const n=new pg(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin);return new cR(n,this.manager).parse(ht)}}class cR{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){$t=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),n=this.parseMaterials(t),s=this.parseDeformers(),r=new lR().parse(s);return this.parseScene(s,r,n),Gn}parseConnections(){const e=new Map;return"Connections"in ht&&ht.Connections.connections.forEach(function(n){const s=n[0],r=n[1],a=n[2];e.has(s)||e.set(s,{parents:[],children:[]});const o={ID:r,relationship:a};e.get(s).parents.push(o),e.has(r)||e.set(r,{parents:[],children:[]});const c={ID:s,relationship:a};e.get(r).children.push(c)}),e}parseImages(){const e={},t={};if("Video"in ht.Objects){const n=ht.Objects.Video;for(const s in n){const r=n[s],a=parseInt(s);if(e[a]=r.RelativeFilename||r.Filename,"Content"in r){const o=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,c=typeof r.Content=="string"&&r.Content!=="";if(o||c){const l=this.parseImage(n[s]);t[r.RelativeFilename||r.Filename]=l}}}}for(const n in e){const s=e[n];t[s]!==void 0?e[n]=t[s]:e[n]=e[n].split("\\").pop()}return e}parseImage(e){const t=e.Content,n=e.RelativeFilename||e.Filename,s=n.slice(n.lastIndexOf(".")+1).toLowerCase();let r;switch(s){case"bmp":r="image/bmp";break;case"jpg":case"jpeg":r="image/jpeg";break;case"png":r="image/png";break;case"tif":r="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",n),r="image/tga";break;default:console.warn('FBXLoader: Image type "'+s+'" is not supported.');return}if(typeof t=="string")return"data:"+r+";base64,"+t;{const a=new Uint8Array(t);return window.URL.createObjectURL(new Blob([a],{type:r}))}}parseTextures(e){const t=new Map;if("Texture"in ht.Objects){const n=ht.Objects.Texture;for(const s in n){const r=this.parseTexture(n[s],e);t.set(parseInt(s),r)}}return t}parseTexture(e,t){const n=this.loadTexture(e,t);n.ID=e.id,n.name=e.attrName;const s=e.WrapModeU,r=e.WrapModeV,a=s!==void 0?s.value:0,o=r!==void 0?r.value:0;if(n.wrapS=a===0?Ss:Zn,n.wrapT=o===0?Ss:Zn,"Scaling"in e){const c=e.Scaling.value;n.repeat.x=c[0],n.repeat.y=c[1]}if("Translation"in e){const c=e.Translation.value;n.offset.x=c[0],n.offset.y=c[1]}return n}loadTexture(e,t){const n=new Set(["tga","tif","tiff","exr","dds","hdr","ktx2"]),s=e.FileName.split(".").pop().toLowerCase(),r=n.has(s)?this.manager.getHandler(`.${s}`):this.textureLoader;if(!r)return console.warn(`FBXLoader: ${s.toUpperCase()} loader not found, creating placeholder texture for`,e.RelativeFilename),new nn;const a=r.path;a||r.setPath(this.textureLoader.path);const o=$t.get(e.id).children;let c;o!==void 0&&o.length>0&&t[o[0].ID]!==void 0&&(c=t[o[0].ID],(c.indexOf("blob:")===0||c.indexOf("data:")===0)&&r.setPath(void 0));const l=r.load(c);return r.setPath(a),l}parseMaterials(e){const t=new Map;if("Material"in ht.Objects){const n=ht.Objects.Material;for(const s in n){const r=this.parseMaterial(n[s],e);r!==null&&t.set(parseInt(s),r)}}return t}parseMaterial(e,t){const n=e.id,s=e.attrName;let r=e.ShadingModel;if(typeof r=="object"&&(r=r.value),!$t.has(n))return null;const a=this.parseParameters(e,t,n);let o;switch(r.toLowerCase()){case"phong":o=new Cl;break;case"lambert":o=new _w;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),o=new Cl;break}return o.setValues(a),o.name=s,o}parseParameters(e,t,n){const s={};e.BumpFactor&&(s.bumpScale=e.BumpFactor.value),e.Diffuse?s.color=tt.toWorkingColorSpace(new Fe().fromArray(e.Diffuse.value),yt):e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(s.color=tt.toWorkingColorSpace(new Fe().fromArray(e.DiffuseColor.value),yt)),e.DisplacementFactor&&(s.displacementScale=e.DisplacementFactor.value),e.Emissive?s.emissive=tt.toWorkingColorSpace(new Fe().fromArray(e.Emissive.value),yt):e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(s.emissive=tt.toWorkingColorSpace(new Fe().fromArray(e.EmissiveColor.value),yt)),e.EmissiveFactor&&(s.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),s.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(s.opacity===1||s.opacity===0)&&(s.opacity=e.Opacity?parseFloat(e.Opacity.value):null,s.opacity===null&&(s.opacity=1-(e.TransparentColor?parseFloat(e.TransparentColor.value[0]):0))),s.opacity<1&&(s.transparent=!0),e.ReflectionFactor&&(s.reflectivity=e.ReflectionFactor.value),e.Shininess&&(s.shininess=e.Shininess.value),e.Specular?s.specular=tt.toWorkingColorSpace(new Fe().fromArray(e.Specular.value),yt):e.SpecularColor&&e.SpecularColor.type==="Color"&&(s.specular=tt.toWorkingColorSpace(new Fe().fromArray(e.SpecularColor.value),yt));const r=this;return $t.get(n).children.forEach(function(a){const o=a.relationship;switch(o){case"Bump":s.bumpMap=r.getTexture(t,a.ID);break;case"Maya|TEX_ao_map":s.aoMap=r.getTexture(t,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":s.map=r.getTexture(t,a.ID),s.map!==void 0&&(s.map.colorSpace=yt);break;case"DisplacementColor":s.displacementMap=r.getTexture(t,a.ID);break;case"EmissiveColor":s.emissiveMap=r.getTexture(t,a.ID),s.emissiveMap!==void 0&&(s.emissiveMap.colorSpace=yt);break;case"NormalMap":case"Maya|TEX_normal_map":s.normalMap=r.getTexture(t,a.ID);break;case"ReflectionColor":s.envMap=r.getTexture(t,a.ID),s.envMap!==void 0&&(s.envMap.mapping=Mc,s.envMap.colorSpace=yt);break;case"SpecularColor":s.specularMap=r.getTexture(t,a.ID),s.specularMap!==void 0&&(s.specularMap.colorSpace=yt);break;case"TransparentColor":case"TransparencyFactor":s.alphaMap=r.getTexture(t,a.ID),s.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),s}getTexture(e,t){return"LayeredTexture"in ht.Objects&&t in ht.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=$t.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in ht.Objects){const n=ht.Objects.Deformer;for(const s in n){const r=n[s],a=$t.get(parseInt(s));if(r.attrType==="Skin"){const o=this.parseSkeleton(a,n);o.ID=s,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,e[s]=o}else if(r.attrType==="BlendShape"){const o={id:s};o.rawTargets=this.parseMorphTargets(a,n),o.id=s,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[s]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const n=[];return e.children.forEach(function(s){const r=t[s.ID];if(r.attrType!=="Cluster")return;const a={ID:s.ID,indices:[],weights:[],transformLink:new Re().fromArray(r.TransformLink.a)};"Indexes"in r&&(a.indices=r.Indexes.a,a.weights=r.Weights.a),n.push(a)}),{rawBones:n,bones:[]}}parseMorphTargets(e,t){const n=[];for(let s=0;s<e.children.length;s++){const r=e.children[s],a=t[r.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=$t.get(parseInt(r.ID)).children.filter(function(c){return c.relationship===void 0})[0].ID,n.push(o)}return n}parseScene(e,t,n){Gn=new ss;const s=this.parseModels(e.skeletons,t,n),r=ht.Objects.Model,a=this;s.forEach(function(c){const l=r[c.ID];a.setLookAtProperties(c,l),$t.get(c.ID).parents.forEach(function(u){const d=s.get(u.ID);d!==void 0&&d.add(c)}),c.parent===null&&Gn.add(c)}),this.bindSkeleton(e.skeletons,t,s),this.addGlobalSceneSettings(),Gn.traverse(function(c){if(c.userData.transformData){c.parent&&(c.userData.transformData.parentMatrix=c.parent.matrix,c.userData.transformData.parentMatrixWorld=c.parent.matrixWorld);const l=K0(c.userData.transformData);c.applyMatrix4(l),c.updateWorldMatrix()}});const o=new hR().parse();Gn.children.length===1&&Gn.children[0].isGroup&&(Gn.children[0].animations=o,Gn=Gn.children[0]),Gn.animations=o}parseModels(e,t,n){const s=new Map,r=ht.Objects.Model;for(const a in r){const o=parseInt(a),c=r[a],l=$t.get(o);let h=this.buildSkeleton(l,e,o,c.attrName);if(!h){switch(c.attrType){case"Camera":h=this.createCamera(l);break;case"Light":h=this.createLight(l);break;case"Mesh":h=this.createMesh(l,t,n);break;case"NurbsCurve":h=this.createCurve(l,t);break;case"LimbNode":case"Root":h=new cl;break;default:h=new ss;break}h.name=c.attrName?_t.sanitizeNodeName(c.attrName):"",h.userData.originalName=c.attrName,h.ID=o}this.getTransformData(h,c),s.set(o,h)}return s}buildSkeleton(e,t,n,s){let r=null;return e.parents.forEach(function(a){for(const o in t){const c=t[o];c.rawBones.forEach(function(l,h){if(l.ID===a.ID){const u=r;r=new cl,r.matrixWorld.copy(l.transformLink),r.name=s?_t.sanitizeNodeName(s):"",r.userData.originalName=s,r.ID=n,c.bones[h]=r,u!==null&&r.add(u)}})}}),r}createCamera(e){let t,n;if(e.children.forEach(function(s){const r=ht.Objects.NodeAttribute[s.ID];r!==void 0&&(n=r)}),n===void 0)t=new Tt;else{let s=0;n.CameraProjectionType!==void 0&&n.CameraProjectionType.value===1&&(s=1);let r=1;n.NearPlane!==void 0&&(r=n.NearPlane.value/1e3);let a=1e3;n.FarPlane!==void 0&&(a=n.FarPlane.value/1e3);let o=window.innerWidth,c=window.innerHeight;n.AspectWidth!==void 0&&n.AspectHeight!==void 0&&(o=n.AspectWidth.value,c=n.AspectHeight.value);const l=o/c;let h=45;n.FieldOfView!==void 0&&(h=n.FieldOfView.value);const u=n.FocalLength?n.FocalLength.value:null;switch(s){case 0:t=new Bn(h,l,r,a),u!==null&&t.setFocalLength(u);break;case 1:console.warn("THREE.FBXLoader: Orthographic cameras not supported yet."),t=new Tt;break;default:console.warn("THREE.FBXLoader: Unknown camera type "+s+"."),t=new Tt;break}}return t}createLight(e){let t,n;if(e.children.forEach(function(s){const r=ht.Objects.NodeAttribute[s.ID];r!==void 0&&(n=r)}),n===void 0)t=new Tt;else{let s;n.LightType===void 0?s=0:s=n.LightType.value;let r=16777215;n.Color!==void 0&&(r=tt.toWorkingColorSpace(new Fe().fromArray(n.Color.value),yt));let a=n.Intensity===void 0?1:n.Intensity.value/100;n.CastLightOnObject!==void 0&&n.CastLightOnObject.value===0&&(a=0);let o=0;n.FarAttenuationEnd!==void 0&&(n.EnableFarAttenuation!==void 0&&n.EnableFarAttenuation.value===0?o=0:o=n.FarAttenuationEnd.value);const c=1;switch(s){case 0:t=new Ml(r,a,o,c);break;case 1:t=new gd(r,a);break;case 2:let l=Math.PI/3;n.InnerAngle!==void 0&&(l=In.degToRad(n.InnerAngle.value));let h=0;n.OuterAngle!==void 0&&(h=In.degToRad(n.OuterAngle.value),h=Math.max(h,1)),t=new mg(r,a,o,l,h,c);break;default:console.warn("THREE.FBXLoader: Unknown light type "+n.LightType.value+", defaulting to a PointLight."),t=new Ml(r,a);break}n.CastShadows!==void 0&&n.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,n){let s,r=null,a=null;const o=[];if(e.children.forEach(function(c){t.has(c.ID)&&(r=t.get(c.ID)),n.has(c.ID)&&o.push(n.get(c.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new Cl({name:ci.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),"color"in r.attributes&&o.forEach(function(c){c.vertexColors=!0}),r.groups.length>0){let c=!1;for(let l=0,h=r.groups.length;l<h;l++){const u=r.groups[l];(u.materialIndex<0||u.materialIndex>=o.length)&&(u.materialIndex=o.length,c=!0)}if(c){const l=new Cl;o.push(l)}}return r.FBX_Deformer?(s=new VA(r,a),s.normalizeSkinWeights()):s=new Zt(r,a),s}createCurve(e,t){const n=e.children.reduce(function(r,a){return t.has(a.ID)&&(r=t.get(a.ID)),r},null),s=new ma({name:ci.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new gl(n,s)}getTransformData(e,t){const n={};"InheritType"in t&&(n.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?n.eulerOrder=Xo(t.RotationOrder.value):n.eulerOrder=Xo(0),"Lcl_Translation"in t&&(n.translation=t.Lcl_Translation.value),"PreRotation"in t&&(n.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(n.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(n.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(n.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(n.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(n.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(n.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(n.rotationPivot=t.RotationPivot.value),e.userData.transformData=n}setLookAtProperties(e,t){"LookAtProperty"in t&&$t.get(e.ID).children.forEach(function(s){if(s.relationship==="LookAtProperty"){const r=ht.Objects.Model[s.ID];if("Lcl_Translation"in r){const a=r.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(a),Gn.add(e.target)):e.lookAt(new G().fromArray(a))}}})}bindSkeleton(e,t,n){const s=this.parsePoseNodes();for(const r in e){const a=e[r];$t.get(parseInt(a.ID)).parents.forEach(function(c){if(t.has(c.ID)){const l=c.ID;$t.get(l).parents.forEach(function(u){n.has(u.ID)&&n.get(u.ID).bind(new hl(a.bones),s[u.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in ht.Objects){const t=ht.Objects.Pose;for(const n in t)if(t[n].attrType==="BindPose"&&t[n].NbPoseNodes>0){const s=t[n].PoseNode;Array.isArray(s)?s.forEach(function(r){e[r.Node]=new Re().fromArray(r.Matrix.a)}):e[s.Node]=new Re().fromArray(s.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in ht){if("AmbientColor"in ht.GlobalSettings){const e=ht.GlobalSettings.AmbientColor.value,t=e[0],n=e[1],s=e[2];if(t!==0||n!==0||s!==0){const r=new Fe().setRGB(t,n,s,yt);Gn.add(new bg(r,1))}}"UnitScaleFactor"in ht.GlobalSettings&&(Gn.userData.unitScaleFactor=ht.GlobalSettings.UnitScaleFactor.value)}}}class lR{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in ht.Objects){const n=ht.Objects.Geometry;for(const s in n){const r=$t.get(parseInt(s)),a=this.parseGeometry(r,n[s],e);t.set(parseInt(s),a)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,n){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,n);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,n){const s=n.skeletons,r=[],a=e.parents.map(function(u){return ht.Objects.Model[u.ID]});if(a.length===0)return;const o=e.children.reduce(function(u,d){return s[d.ID]!==void 0&&(u=s[d.ID]),u},null);e.children.forEach(function(u){n.morphTargets[u.ID]!==void 0&&r.push(n.morphTargets[u.ID])});const c=a[0],l={};"RotationOrder"in c&&(l.eulerOrder=Xo(c.RotationOrder.value)),"InheritType"in c&&(l.inheritType=parseInt(c.InheritType.value)),"GeometricTranslation"in c&&(l.translation=c.GeometricTranslation.value),"GeometricRotation"in c&&(l.rotation=c.GeometricRotation.value),"GeometricScaling"in c&&(l.scale=c.GeometricScaling.value);const h=K0(l);return this.genGeometry(t,o,r,h)}genGeometry(e,t,n,s){const r=new Mn;e.attrName&&(r.name=e.attrName);const a=this.parseGeoNode(e,t),o=this.genBuffers(a),c=new Jt(o.vertex,3);if(c.applyMatrix4(s),r.setAttribute("position",c),o.colors.length>0&&r.setAttribute("color",new Jt(o.colors,3)),t&&(r.setAttribute("skinIndex",new Xu(o.weightsIndices,4)),r.setAttribute("skinWeight",new Jt(o.vertexWeights,4)),r.FBX_Deformer=t),o.normal.length>0){const l=new ot().getNormalMatrix(s),h=new Jt(o.normal,3);h.applyNormalMatrix(l),r.setAttribute("normal",h)}if(o.uvs.forEach(function(l,h){const u=h===0?"uv":`uv${h}`;r.setAttribute(u,new Jt(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let l=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,d){u!==l&&(r.addGroup(h,d-h,l),l=u,h=d)}),r.groups.length>0){const u=r.groups[r.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&r.addGroup(d,o.materialIndex.length-d,l)}r.groups.length===0&&r.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(r,e,n,s),r}parseGeoNode(e,t){const n={};if(n.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],n.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&(n.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(n.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(n.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){n.uv=[];let s=0;for(;e.LayerElementUV[s];)e.LayerElementUV[s].UV&&n.uv.push(this.parseUVs(e.LayerElementUV[s])),s++}return n.weightTable={},t!==null&&(n.skeleton=t,t.rawBones.forEach(function(s,r){s.indices.forEach(function(a,o){n.weightTable[a]===void 0&&(n.weightTable[a]=[]),n.weightTable[a].push({id:r,weight:s.weights[o]})})})),n}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let n=0,s=0,r=!1,a=[],o=[],c=[],l=[],h=[],u=[];const d=this;return e.vertexIndices.forEach(function(f,p){let m,g=!1;f<0&&(f=f^-1,g=!0);let A=[],_=[];if(a.push(f*3,f*3+1,f*3+2),e.color){const x=eh(p,n,f,e.color);c.push(x[0],x[1],x[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(x){_.push(x.weight),A.push(x.id)}),_.length>4){r||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),r=!0);const x=[0,0,0,0],E=[0,0,0,0];_.forEach(function(S,w){let I=S,T=A[w];E.forEach(function(C,v,F){if(I>C){F[v]=I,I=C;const K=x[v];x[v]=T,T=K}})}),A=x,_=E}for(;_.length<4;)_.push(0),A.push(0);for(let x=0;x<4;++x)h.push(_[x]),u.push(A[x])}if(e.normal){const x=eh(p,n,f,e.normal);o.push(x[0],x[1],x[2])}e.material&&e.material.mappingType!=="AllSame"&&(m=eh(p,n,f,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach(function(x,E){const S=eh(p,n,f,x);l[E]===void 0&&(l[E]=[]),l[E].push(S[0]),l[E].push(S[1])}),s++,g&&(d.genFace(t,e,a,m,o,c,l,h,u,s),n++,s=0,a=[],o=[],c=[],l=[],h=[],u=[])}),t}getNormalNewell(e){const t=new G(0,0,0);for(let n=0;n<e.length;n++){const s=e[n],r=e[(n+1)%e.length];t.x+=(s.y-r.y)*(s.z+r.z),t.y+=(s.z-r.z)*(s.x+r.x),t.z+=(s.x-r.x)*(s.y+r.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){const t=this.getNormalNewell(e),s=(Math.abs(t.z)>.5?new G(0,1,0):new G(0,0,1)).cross(t).normalize(),r=t.clone().cross(s).normalize();return{normal:t,tangent:s,bitangent:r}}flattenVertex(e,t,n){return new Je(e.dot(t),e.dot(n))}genFace(e,t,n,s,r,a,o,c,l,h){let u;if(h>3){const d=[],f=t.baseVertexPositions||t.vertexPositions;for(let A=0;A<n.length;A+=3)d.push(new G(f[n[A]],f[n[A+1]],f[n[A+2]]));const{tangent:p,bitangent:m}=this.getNormalTangentAndBitangent(d),g=[];for(const A of d)g.push(this.flattenVertex(A,p,m));u=ud.triangulateShape(g,[])}else u=[[0,1,2]];for(const[d,f,p]of u)e.vertex.push(t.vertexPositions[n[d*3]]),e.vertex.push(t.vertexPositions[n[d*3+1]]),e.vertex.push(t.vertexPositions[n[d*3+2]]),e.vertex.push(t.vertexPositions[n[f*3]]),e.vertex.push(t.vertexPositions[n[f*3+1]]),e.vertex.push(t.vertexPositions[n[f*3+2]]),e.vertex.push(t.vertexPositions[n[p*3]]),e.vertex.push(t.vertexPositions[n[p*3+1]]),e.vertex.push(t.vertexPositions[n[p*3+2]]),t.skeleton&&(e.vertexWeights.push(c[d*4]),e.vertexWeights.push(c[d*4+1]),e.vertexWeights.push(c[d*4+2]),e.vertexWeights.push(c[d*4+3]),e.vertexWeights.push(c[f*4]),e.vertexWeights.push(c[f*4+1]),e.vertexWeights.push(c[f*4+2]),e.vertexWeights.push(c[f*4+3]),e.vertexWeights.push(c[p*4]),e.vertexWeights.push(c[p*4+1]),e.vertexWeights.push(c[p*4+2]),e.vertexWeights.push(c[p*4+3]),e.weightsIndices.push(l[d*4]),e.weightsIndices.push(l[d*4+1]),e.weightsIndices.push(l[d*4+2]),e.weightsIndices.push(l[d*4+3]),e.weightsIndices.push(l[f*4]),e.weightsIndices.push(l[f*4+1]),e.weightsIndices.push(l[f*4+2]),e.weightsIndices.push(l[f*4+3]),e.weightsIndices.push(l[p*4]),e.weightsIndices.push(l[p*4+1]),e.weightsIndices.push(l[p*4+2]),e.weightsIndices.push(l[p*4+3])),t.color&&(e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[f*3]),e.colors.push(a[f*3+1]),e.colors.push(a[f*3+2]),e.colors.push(a[p*3]),e.colors.push(a[p*3+1]),e.colors.push(a[p*3+2])),t.material&&t.material.mappingType!=="AllSame"&&(e.materialIndex.push(s),e.materialIndex.push(s),e.materialIndex.push(s)),t.normal&&(e.normal.push(r[d*3]),e.normal.push(r[d*3+1]),e.normal.push(r[d*3+2]),e.normal.push(r[f*3]),e.normal.push(r[f*3+1]),e.normal.push(r[f*3+2]),e.normal.push(r[p*3]),e.normal.push(r[p*3+1]),e.normal.push(r[p*3+2])),t.uv&&t.uv.forEach(function(m,g){e.uvs[g]===void 0&&(e.uvs[g]=[]),e.uvs[g].push(o[g][d*2]),e.uvs[g].push(o[g][d*2+1]),e.uvs[g].push(o[g][f*2]),e.uvs[g].push(o[g][f*2+1]),e.uvs[g].push(o[g][p*2]),e.uvs[g].push(o[g][p*2+1])})}addMorphTargets(e,t,n,s){if(n.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const r=this;n.forEach(function(a){a.rawTargets.forEach(function(o){const c=ht.Objects.Geometry[o.geoID];c!==void 0&&r.genMorphGeometry(e,t,c,s,o.name)})})}genMorphGeometry(e,t,n,s,r){const a=t.Vertices!==void 0?t.Vertices.a:[],o=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],c=n.Vertices!==void 0?n.Vertices.a:[],l=n.Indexes!==void 0?n.Indexes.a:[],h=e.attributes.position.count*3,u=new Float32Array(h);for(let m=0;m<l.length;m++){const g=l[m]*3;u[g]=c[m*3],u[g+1]=c[m*3+1],u[g+2]=c[m*3+2]}const d={vertexIndices:o,vertexPositions:u,baseVertexPositions:a},f=this.genBuffers(d),p=new Jt(f.vertex,3);p.name=r||n.attrName,p.applyMatrix4(s),e.morphAttributes.position.push(p)}parseNormals(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.Normals.a;let r=[];return n==="IndexToDirect"&&("NormalIndex"in e?r=e.NormalIndex.a:"NormalsIndex"in e&&(r=e.NormalsIndex.a)),{dataSize:3,buffer:s,indices:r,mappingType:t,referenceType:n}}parseUVs(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.UV.a;let r=[];return n==="IndexToDirect"&&(r=e.UVIndex.a),{dataSize:2,buffer:s,indices:r,mappingType:t,referenceType:n}}parseVertexColors(e){const t=e.MappingInformationType,n=e.ReferenceInformationType,s=e.Colors.a;let r=[];n==="IndexToDirect"&&(r=e.ColorIndex.a);for(let a=0,o=new Fe;a<s.length;a+=4)o.fromArray(s,a),tt.toWorkingColorSpace(o,yt),o.toArray(s,a);return{dataSize:4,buffer:s,indices:r,mappingType:t,referenceType:n}}parseMaterialIndices(e){const t=e.MappingInformationType,n=e.ReferenceInformationType;if(t==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:n};const s=e.Materials.a,r=[];for(let a=0;a<s.length;++a)r.push(a);return{dataSize:1,buffer:s,indices:r,mappingType:t,referenceType:n}}parseNurbsGeometry(e){const t=parseInt(e.Order);if(isNaN(t))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",e.Order,e.id),new Mn;const n=t-1,s=e.KnotVector.a,r=[],a=e.Points.a;for(let u=0,d=a.length;u<d;u+=4)r.push(new gt().fromArray(a,u));let o,c;if(e.Form==="Closed")r.push(r[0]);else if(e.Form==="Periodic"){o=n,c=s.length-1-o;for(let u=0;u<n;++u)r.push(r[u])}const h=new aR(n,s,r,o,c).getPoints(r.length*12);return new Mn().setFromPoints(h)}}class hR{parse(){const e=[],t=this.parseClips();if(t!==void 0)for(const n in t){const s=t[n],r=this.addClip(s);e.push(r)}return e}parseClips(){if(ht.Objects.AnimationCurve===void 0)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=ht.Objects.AnimationCurveNode,t=new Map;for(const n in e){const s=e[n];if(s.attrName.match(/S|R|T|DeformPercent/)!==null){const r={id:s.id,attr:s.attrName,curves:{}};t.set(r.id,r)}}return t}parseAnimationCurves(e){const t=ht.Objects.AnimationCurve;for(const n in t){const s={id:t[n].id,times:t[n].KeyTime.a.map(AR),values:t[n].KeyValueFloat.a},r=$t.get(s.id);if(r!==void 0){const a=r.parents[0].ID,o=r.parents[0].relationship;o.match(/X/)?e.get(a).curves.x=s:o.match(/Y/)?e.get(a).curves.y=s:o.match(/Z/)?e.get(a).curves.z=s:o.match(/DeformPercent/)&&e.has(a)&&(e.get(a).curves.morph=s)}}}parseAnimationLayers(e){const t=ht.Objects.AnimationLayer,n=new Map;for(const s in t){const r=[],a=$t.get(parseInt(s));a!==void 0&&(a.children.forEach(function(c,l){if(e.has(c.ID)){const h=e.get(c.ID);if(h.curves.x!==void 0||h.curves.y!==void 0||h.curves.z!==void 0){if(r[l]===void 0){const u=$t.get(c.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=ht.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",c);return}const f={modelName:d.attrName?_t.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};Gn.traverse(function(p){p.ID===d.id&&(f.transform=p.matrix,p.userData.transformData&&(f.eulerOrder=p.userData.transformData.eulerOrder))}),f.transform||(f.transform=new Re),"PreRotation"in d&&(f.preRotation=d.PreRotation.value),"PostRotation"in d&&(f.postRotation=d.PostRotation.value),r[l]=f}}r[l]&&(r[l][h.attr]=h)}else if(h.curves.morph!==void 0){if(r[l]===void 0){const u=$t.get(c.ID).parents.filter(function(A){return A.relationship!==void 0})[0].ID,d=$t.get(u).parents[0].ID,f=$t.get(d).parents[0].ID,p=$t.get(f).parents[0].ID,m=ht.Objects.Model[p],g={modelName:m.attrName?_t.sanitizeNodeName(m.attrName):"",morphName:ht.Objects.Deformer[u].attrName};r[l]=g}r[l][h.attr]=h}}}),n.set(parseInt(s),r))}return n}parseAnimStacks(e){const t=ht.Objects.AnimationStack,n={};for(const s in t){const r=$t.get(parseInt(s)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const a=e.get(r[0].ID);n[s]={name:t[s].attrName,layer:a}}return n}addClip(e){let t=[];const n=this;return e.layer.forEach(function(s){t=t.concat(n.generateTracks(s))}),new Sl(e.name,-1,t)}generateTracks(e){const t=[];let n=new G,s=new G;if(e.transform&&e.transform.decompose(n,new Yt,s),n=n.toArray(),s=s.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const r=this.generateVectorTrack(e.modelName,e.T.curves,n,"position");r!==void 0&&t.push(r)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const r=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);r!==void 0&&t.push(r)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const r=this.generateVectorTrack(e.modelName,e.S.curves,s,"scale");r!==void 0&&t.push(r)}if(e.DeformPercent!==void 0){const r=this.generateMorphTrack(e);r!==void 0&&t.push(r)}return t}generateVectorTrack(e,t,n,s){const r=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(r,t,n);return new pr(e+"."+s,r,a)}generateRotationTrack(e,t,n,s,r){let a,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const d=this.interpolateRotations(t.x,t.y,t.z,r);a=d[0],o=d[1]}const c=Xo(0);n!==void 0&&(n=n.map(In.degToRad),n.push(c),n=new dn().fromArray(n),n=new Yt().setFromEuler(n)),s!==void 0&&(s=s.map(In.degToRad),s.push(c),s=new dn().fromArray(s),s=new Yt().setFromEuler(s).invert());const l=new Yt,h=new dn,u=[];if(!o||!a)return new Us(e+".quaternion",[0],[0]);for(let d=0;d<o.length;d+=3)h.set(o[d],o[d+1],o[d+2],r),l.setFromEuler(h),n!==void 0&&l.premultiply(n),s!==void 0&&l.multiply(s),d>2&&new Yt().fromArray(u,(d-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(u,d/3*4);return new Us(e+".quaternion",a,u)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,n=t.values.map(function(r){return r/100}),s=Gn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new fr(e.modelName+".morphTargetInfluences["+s+"]",t.times,n)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(n,s){return n-s}),t.length>1){let n=1,s=t[0];for(let r=1;r<t.length;r++){const a=t[r];a!==s&&(t[n]=a,s=a,n++)}t=t.slice(0,n)}return t}getKeyframeTrackValues(e,t,n){const s=n,r=[];let a=-1,o=-1,c=-1;return e.forEach(function(l){if(t.x&&(a=t.x.times.indexOf(l)),t.y&&(o=t.y.times.indexOf(l)),t.z&&(c=t.z.times.indexOf(l)),a!==-1){const h=t.x.values[a];r.push(h),s[0]=h}else r.push(s[0]);if(o!==-1){const h=t.y.values[o];r.push(h),s[1]=h}else r.push(s[1]);if(c!==-1){const h=t.z.values[c];r.push(h),s[2]=h}else r.push(s[2])}),r}interpolateRotations(e,t,n,s){const r=[],a=[];r.push(e.times[0]),a.push(In.degToRad(e.values[0])),a.push(In.degToRad(t.values[0])),a.push(In.degToRad(n.values[0]));for(let o=1;o<e.values.length;o++){const c=[e.values[o-1],t.values[o-1],n.values[o-1]];if(isNaN(c[0])||isNaN(c[1])||isNaN(c[2]))continue;const l=c.map(In.degToRad),h=[e.values[o],t.values[o],n.values[o]];if(isNaN(h[0])||isNaN(h[1])||isNaN(h[2]))continue;const u=h.map(In.degToRad),d=[h[0]-c[0],h[1]-c[1],h[2]-c[2]],f=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(f[0]>=180||f[1]>=180||f[2]>=180){const m=Math.max(...f)/180,g=new dn(...l,s),A=new dn(...u,s),_=new Yt().setFromEuler(g),x=new Yt().setFromEuler(A);_.dot(x)&&x.set(-x.x,-x.y,-x.z,-x.w);const E=e.times[o-1],S=e.times[o]-E,w=new Yt,I=new dn;for(let T=0;T<1;T+=1/m)w.copy(_.clone().slerp(x.clone(),T)),r.push(E+T*S),I.setFromQuaternion(w,s),a.push(I.x),a.push(I.y),a.push(I.z)}else r.push(e.times[o]),a.push(In.degToRad(e.values[o])),a.push(In.degToRad(t.values[o])),a.push(In.degToRad(n.values[o]))}return[r,a]}}class uR{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new W0,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,n=e.split(/[\r\n]+/);return n.forEach(function(s,r){const a=s.match(/^[\s\t]*;/),o=s.match(/^[\s\t]*$/);if(a||o)return;const c=s.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),l=s.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=s.match("^\\t{"+(t.currentIndent-1)+"}}");c?t.parseNodeBegin(s,c):l?t.parseNodeProperty(s,l,n[++r]):h?t.popStack():s.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(s)}),this.allNodes}parseNodeBegin(e,t){const n=t[1].trim().replace(/^"/,"").replace(/"$/,""),s=t[2].split(",").map(function(c){return c.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:n},a=this.parseNodeAttr(s),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(n,r):n in o?(n==="PoseNode"?o.PoseNode.push(r):o[n].id!==void 0&&(o[n]={},o[n][o[n].id]=o[n]),a.id!==""&&(o[n][a.id]=r)):typeof a.id=="number"?(o[n]={},o[n][a.id]=r):n!=="Properties70"&&(n==="PoseNode"?o[n]=[r]:o[n]=r),typeof a.id=="number"&&(r.id=a.id),a.name!==""&&(r.attrName=a.name),a.type!==""&&(r.attrType=a.type),this.pushStack(r)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let n="",s="";return e.length>1&&(n=e[1].replace(/^(\w+)::/,""),s=e[2]),{id:t,name:n,type:s}}parseNodeProperty(e,t,n){let s=t[1].replace(/^"/,"").replace(/"$/,"").trim(),r=t[2].replace(/^"/,"").replace(/"$/,"").trim();s==="Content"&&r===","&&(r=n.replace(/"/g,"").replace(/,$/,"").trim());const a=this.getCurrentNode();if(a.name==="Properties70"){this.parseNodeSpecialProperty(e,s,r);return}if(s==="C"){const c=r.split(",").slice(1),l=parseInt(c[0]),h=parseInt(c[1]);let u=r.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),s="connections",r=[l,h],mR(r,u),a[s]===void 0&&(a[s]=[])}s==="Node"&&(a.id=r),s in a&&Array.isArray(a[s])?a[s].push(r):s!=="a"?a[s]=r:a.a=r,this.setCurrentProp(a,s),s==="a"&&r.slice(-1)!==","&&(a.a=Mf(r))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=Mf(t.a))}parseNodeSpecialProperty(e,t,n){const s=n.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=s[0],a=s[1],o=s[2],c=s[3];let l=s[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":l=parseFloat(l);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":l=Mf(l);break}this.getPrevNode()[r]={type:a,type2:o,flag:c,value:l},this.setCurrentProp(this.getPrevNode(),r)}}class dR{parse(e){const t=new V0(e);t.skip(23);const n=t.getUint32();if(n<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+n);const s=new W0;for(;!this.endOfContent(t);){const r=this.parseNode(t,n);r!==null&&s.add(r.name,r)}return s}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const n={},s=t>=7500?e.getUint64():e.getUint32(),r=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const a=e.getUint8(),o=e.getString(a);if(s===0)return null;const c=[];for(let d=0;d<r;d++)c.push(this.parseProperty(e));const l=c.length>0?c[0]:"",h=c.length>1?c[1]:"",u=c.length>2?c[2]:"";for(n.singleProperty=r===1&&e.getOffset()===s;s>e.getOffset();){const d=this.parseNode(e,t);d!==null&&this.parseSubNode(o,n,d)}return n.propertyList=c,typeof l=="number"&&(n.id=l),h!==""&&(n.attrName=h),u!==""&&(n.attrType=u),o!==""&&(n.name=o),n}parseSubNode(e,t,n){if(n.singleProperty===!0){const s=n.propertyList[0];Array.isArray(s)?(t[n.name]=n,n.a=s):t[n.name]=s}else if(e==="Connections"&&n.name==="C"){const s=[];n.propertyList.forEach(function(r,a){a!==0&&s.push(r)}),t.connections===void 0&&(t.connections=[]),t.connections.push(s)}else if(n.name==="Properties70")Object.keys(n).forEach(function(r){t[r]=n[r]});else if(e==="Properties70"&&n.name==="P"){let s=n.propertyList[0],r=n.propertyList[1];const a=n.propertyList[2],o=n.propertyList[3];let c;s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),r.indexOf("Lcl ")===0&&(r=r.replace("Lcl ","Lcl_")),r==="Color"||r==="ColorRGB"||r==="Vector"||r==="Vector3D"||r.indexOf("Lcl_")===0?c=[n.propertyList[4],n.propertyList[5],n.propertyList[6]]:c=n.propertyList[4],t[s]={type:r,type2:a,flag:o,value:c}}else t[n.name]===void 0?typeof n.id=="number"?(t[n.name]={},t[n.name][n.id]=n):t[n.name]=n:n.name==="PoseNode"?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(n)):t[n.name][n.id]===void 0&&(t[n.name][n.id]=n)}parseProperty(e){const t=e.getString(1);let n;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return n=e.getUint32(),e.getArrayBuffer(n);case"S":return n=e.getUint32(),e.getString(n);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const s=e.getUint32(),r=e.getUint32(),a=e.getUint32();if(r===0)switch(t){case"b":case"c":return e.getBooleanArray(s);case"d":return e.getFloat64Array(s);case"f":return e.getFloat32Array(s);case"i":return e.getInt32Array(s);case"l":return e.getInt64Array(s)}const o=jo(new Uint8Array(e.getArrayBuffer(a))),c=new V0(o.buffer);switch(t){case"b":case"c":return c.getBooleanArray(s);case"d":return c.getFloat64Array(s);case"f":return c.getFloat32Array(s);case"i":return c.getInt32Array(s);case"l":return c.getInt64Array(s)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class V0{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let n=0;n<e;n++)t.push(this.getBoolean());return t}getUint8(){const e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){const e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){const e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getInt32());return t}getUint32(){const e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){const e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getFloat32());return t}getFloat64(){const e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){const t=[];for(let n=0;n<e;n++)t.push(this.getFloat64());return t}getArrayBuffer(e){const t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){const t=this.offset;let n=new Uint8Array(this.dv.buffer,t,e);this.skip(e);const s=n.indexOf(0);return s>=0&&(n=new Uint8Array(this.dv.buffer,t,s)),this._textDecoder.decode(n)}}class W0{add(e,t){this[e]=t}}function fR(i){const e="Kaydara FBX Binary \0";return i.byteLength>=e.length&&e===j0(i,0,e.length)}function pR(i){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function n(s){const r=i[s-1];return i=i.slice(t+s),t++,r}for(let s=0;s<e.length;++s)if(n(1)===e[s])return!1;return!0}function q0(i){const e=/FBXVersion: (\d+)/,t=i.match(e);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function AR(i){return i/46186158e3}const gR=[];function eh(i,e,t,n){let s;switch(n.mappingType){case"ByPolygonVertex":s=i;break;case"ByPolygon":s=e;break;case"ByVertice":s=t;break;case"AllSame":s=n.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+n.mappingType)}n.referenceType==="IndexToDirect"&&(s=n.indices[s]);const r=s*n.dataSize,a=r+n.dataSize;return xR(gR,n.buffer,r,a)}const Sf=new dn,Na=new G;function K0(i){const e=new Re,t=new Re,n=new Re,s=new Re,r=new Re,a=new Re,o=new Re,c=new Re,l=new Re,h=new Re,u=new Re,d=new Re,f=i.inheritType?i.inheritType:0;i.translation&&e.setPosition(Na.fromArray(i.translation));const p=Xo(0);if(i.preRotation){const F=i.preRotation.map(In.degToRad);F.push(p),t.makeRotationFromEuler(Sf.fromArray(F))}if(i.rotation){const F=i.rotation.map(In.degToRad);F.push(i.eulerOrder||p),n.makeRotationFromEuler(Sf.fromArray(F))}if(i.postRotation){const F=i.postRotation.map(In.degToRad);F.push(p),s.makeRotationFromEuler(Sf.fromArray(F)),s.invert()}i.scale&&r.scale(Na.fromArray(i.scale)),i.scalingOffset&&o.setPosition(Na.fromArray(i.scalingOffset)),i.scalingPivot&&a.setPosition(Na.fromArray(i.scalingPivot)),i.rotationOffset&&c.setPosition(Na.fromArray(i.rotationOffset)),i.rotationPivot&&l.setPosition(Na.fromArray(i.rotationPivot)),i.parentMatrixWorld&&(u.copy(i.parentMatrix),h.copy(i.parentMatrixWorld));const m=t.clone().multiply(n).multiply(s),g=new Re;g.extractRotation(h);const A=new Re;A.copyPosition(h);const _=A.clone().invert().multiply(h),x=g.clone().invert().multiply(_),E=r,S=new Re;if(f===0)S.copy(g).multiply(m).multiply(x).multiply(E);else if(f===1)S.copy(g).multiply(x).multiply(m).multiply(E);else{const K=new Re().scale(new G().setFromMatrixScale(u)).clone().invert(),q=x.clone().multiply(K);S.copy(g).multiply(m).multiply(q).multiply(E)}const w=l.clone().invert(),I=a.clone().invert();let T=e.clone().multiply(c).multiply(l).multiply(t).multiply(n).multiply(s).multiply(w).multiply(o).multiply(a).multiply(r).multiply(I);const C=new Re().copyPosition(T),v=h.clone().multiply(C);return d.copyPosition(v),T=d.clone().multiply(S),T.premultiply(h.invert()),T}function Xo(i){i=i||0;const e=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return i===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),e[0]):e[i]}function Mf(i){return i.split(",").map(function(t){return parseFloat(t)})}function j0(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=i.byteLength),new TextDecoder().decode(new Uint8Array(i,e,t))}function mR(i,e){for(let t=0,n=i.length,s=e.length;t<s;t++,n++)i[n]=e[t]}function xR(i,e,t,n){for(let s=t,r=0;s<n;s++,r++)i[r]=e[s];return i}const bR=.35;class ER{constructor(){this.model=null,this.mixer=null,this.clips=new Map,this.actions=new Map,this.currentName=null,this.currentAction=null,this.loader=new Bd,this.fbxLoader=new oR,this.onChange=null,this._gltfCache=new Map,this._animationDefs=[]}attach(e){this.detach(),this.model=e,this.mixer=new Eg(e),this.actions.clear(),this.currentAction=null,this.currentName=null;for(const[t,n]of this.clips){const s=this._retargetClip(n,t),r=this.mixer.clipAction(s);r.enabled=!0,this.actions.set(t,r)}}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot()),this.mixer=null),this.model=null,this.actions.clear(),this.currentAction=null,this.currentName=null}setAnimationDefs(e){this._animationDefs=e}getAnimationDefs(){return this._animationDefs}async loadAnimation(e,t,n={}){if(this.clips.has(e))return this.clips.get(e);let s;if(this._gltfCache.has(t))s=this._gltfCache.get(t);else{const a=t.toLowerCase().endsWith(".fbx");s=(await new Promise((c,l)=>{(a?this.fbxLoader:this.loader).load(t,c,void 0,l)})).animations||[],this._gltfCache.set(t,s)}let r;if(n.clipName?(r=s.find(a=>a.name===n.clipName),r||(console.warn(`[AnimationManager] Clip "${n.clipName}" not found in ${t}, using first clip`),r=s[0])):r=s[0],!r)throw new Error(`No animation found in ${t}`);if(r=r.clone(),r.name=e,this.clips.set(e,r),this.model&&this.mixer){const a=this._retargetClip(r,e),o=this.mixer.clipAction(a);o.enabled=!0,o.setLoop(n.loop===!1?rA:aA),n.loop===!1&&(o.clampWhenFinished=!0),this.actions.set(e,o)}return r}async loadAll(){const e=this._animationDefs.map(async t=>{try{await this.loadAnimation(t.name,t.url,{loop:t.loop!==!1,clipName:t.clipName})}catch(n){console.warn(`[AnimationManager] Failed to load "${t.name}" from ${t.url}:`,n)}});await Promise.all(e)}play(e){const t=this.actions.get(e);if(!t){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}this.currentAction&&this.currentAction!==t&&this.currentAction.fadeOut(.01),t.reset().fadeIn(.01).play(),this.currentAction=t,this.currentName=e,this.onChange&&this.onChange(e)}crossfadeTo(e,t=bR){if(e===this.currentName)return;const n=this.actions.get(e);if(!n){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}n.reset(),n.play(),this.currentAction?this.currentAction.crossFadeTo(n,t,!0):n.fadeIn(t),this.currentAction=n,this.currentName=e,this.onChange&&this.onChange(e)}stopAll(){this.mixer&&this.mixer.stopAllAction(),this.currentAction=null,this.currentName=null,this.onChange&&this.onChange(null)}update(e){this.mixer&&this.mixer.update(e)}_retargetClip(e,t){if(!this.model)return e;const n=new Set;if(this.model.traverse(l=>{l.isBone&&n.add(l.name)}),n.size===0)return e;const s=new Set;for(const l of e.tracks){const h=l.name.split(".")[0];s.add(h)}let r=0;for(const l of s)n.has(l)&&r++;if(r/s.size>.5)return e;const a=this._buildBoneNameMap(n,s);if(!a)return e;const o=e.tracks.map(l=>{const h=l.name.split("."),u=h[0],d=h.slice(1).join("."),f=a.get(u);if(!f)return null;const p=l.clone();return p.name=`${f}.${d}`,p}).filter(Boolean),c=e.clone();return c.tracks=o,c}_buildBoneNameMap(e,t){const n=new Map,s=[...e],r=[...t],a=h=>h.replace(/^mixamorig\d*[_:]?/i,"").replace(/^Armature[_/]?/i,""),o=new Map(s.map(h=>[a(h),h]));let c=0;for(const h of r){const u=a(h);o.has(u)&&(n.set(h,o.get(u)),c++)}if(c/r.length>.5)return n;const l=new Map(s.map(h=>[h.toLowerCase(),h]));n.clear(),c=0;for(const h of r)l.has(h.toLowerCase())&&(n.set(h,l.get(h.toLowerCase())),c++);return c/r.length>.5?n:null}getLoadedNames(){return[...this.clips.keys()]}isLoaded(e){return this.clips.has(e)}dispose(){this.detach(),this.clips.clear(),this._gltfCache.clear(),this._animationDefs=[]}}rs.enabled=!0;class Bf{constructor(e,t){this.el=e,this.options=t,this.lights=[],this.content=null,this.mixer=null,this.clips=[],this.gui=null,this.animationManager=new ER,this._animPanelEl=null,this.state={environment:t.preset===wf.ASSET_GENERATOR?Ql.find(r=>r.id==="footprint-court").name:Ql[1].name,background:!1,playbackSpeed:1,actionStates:{},camera:Zl,wireframe:!1,skeleton:!1,grid:!1,autoRotate:!1,punctualLights:!0,exposure:0,toneMapping:eu,ambientIntensity:.3,ambientColor:"#FFFFFF",directIntensity:.8*Math.PI,directColor:"#FFFFFF",bgColor:"#000000",transparentBg:!1,pointSize:1,showInfo:!0,showLabels:!1,followMode:"mouse"},this.prevTime=0,this.stats=new Lo,this.stats.dom.height="48px",[].forEach.call(this.stats.dom.children,r=>r.style.display=""),this.backgroundColor=new Fe(this.state.bgColor),this.scene=new $u,this.scene.background=this.backgroundColor;const n=t.preset===wf.ASSET_GENERATOR?.8*180/Math.PI:60,s=e.clientWidth/e.clientHeight;this.defaultCamera=new Bn(n,s,.01,1e3),this.activeCamera=this.defaultCamera,this.scene.add(this.defaultCamera),this.renderer=window.renderer=new $g({antialias:!0,alpha:!0}),this.renderer.setClearColor(0,1),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(e.clientWidth,e.clientHeight),this.pmremGenerator=new Cd(this.renderer),this.pmremGenerator.compileEquirectangularShader(),this.neutralEnvironment=this.pmremGenerator.fromScene(new eM).texture,this.controls=new G1(this.defaultCamera,this.renderer.domElement),this.controls.screenSpacePanning=!0,this._onControlsChange=()=>this.invalidate(),this.controls.addEventListener("change",this._onControlsChange),this.el.appendChild(this.renderer.domElement),this.cameraCtrl=null,this.cameraFolder=null,this.animFolder=null,this.animCtrls=[],this.morphFolder=null,this.morphCtrls=[],this.skeletonHelpers=[],this.gridHelper=null,this.axesHelper=null,this.modelInfo=null,this.annotationEls=[],this._tempVec=new G,this.addAxesHelper(),this.addGUI(),t.kiosk&&this.gui.close(),this.animate=this.animate.bind(this),this._rafId=null,this._visible=!0,this._tabVisible=!document.hidden,this._disposed=!1,this._loadedEnvironment=null,this._guiWrap=null,this._needsRender=!0,this._animating=!1,this._onVisibilityChange=()=>{const r=!this._tabVisible;this._tabVisible=!document.hidden,r&&this._tabVisible&&(this._needsRender=!0),this._updateRenderLoop()},document.addEventListener("visibilitychange",this._onVisibilityChange),typeof IntersectionObserver<"u"&&(this._intersectionObserver=new IntersectionObserver(r=>{const a=!this._visible;this._visible=r[r.length-1].isIntersecting,a&&this._visible&&(this._needsRender=!0),this._updateRenderLoop()},{threshold:0}),this._intersectionObserver.observe(this.el)),this._onResize=this.resize.bind(this),this._onKeyDown=r=>{(r.key==="p"||r.key==="P")&&!this.isInputFocused()&&this.takeScreenshot()},this._updateRenderLoop(),window.addEventListener("resize",this._onResize,!1),window.addEventListener("keydown",this._onKeyDown)}invalidate(){this._disposed||(this._needsRender=!0,this._updateRenderLoop())}_recomputeAnimating(){let e=!1;if(this.state&&this.state.autoRotate&&(e=!0),!e&&this.mixer&&this.state){for(const t in this.state.actionStates)if(this.state.actionStates[t]){e=!0;break}}!e&&this.animationManager.currentAction&&(e=!0),this._animating=e}_updateRenderLoop(){if(this._disposed)return;const e=this._visible&&this._tabVisible;e&&(this._needsRender||this._animating)&&this._rafId===null?(this.prevTime=performance.now(),this._rafId=requestAnimationFrame(this.animate)):!e&&this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}animate(e){const t=(e-this.prevTime)/1e3;if(this.prevTime=e,this._recomputeAnimating(),this.controls.update(),this.stats.update(),this.mixer&&this.mixer.update(t),this.animationManager.update(t),this._afterAnimateHooks)for(let n=0;n<this._afterAnimateHooks.length;n++)this._afterAnimateHooks[n](t);this.render(),this._needsRender=!1,this._animating&&this._visible&&this._tabVisible&&!this._disposed?this._rafId=requestAnimationFrame(this.animate):this._rafId=null}isInputFocused(){const e=document.activeElement;return e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable)}render(){this.renderer.render(this.scene,this.activeCamera),this.state.grid&&(this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesRenderer.render(this.axesScene,this.axesCamera)),this.projectAnnotations()}takeScreenshot(){XT(this)}resize(){const{clientHeight:e,clientWidth:t}=this.el;this.defaultCamera.aspect=t/e,this.defaultCamera.updateProjectionMatrix(),this.renderer.setSize(t,e),this.axesCamera.aspect=this.axesDiv.clientWidth/this.axesDiv.clientHeight,this.axesCamera.updateProjectionMatrix(),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.invalidate()}load(e,t,n){const s=Ar.extractUrlBase(e);return new Promise((r,a)=>{$l.setURLModifier((l,h)=>{const u=t+decodeURI(l).replace(s,"").replace(/^(\.?\/)/,"");if(n.has(u)){const d=n.get(u),f=URL.createObjectURL(d);return c.push(f),f}return(h||"")+l});const o=new Bd($l).setCrossOrigin("anonymous").setDRACOLoader(MT).setKTX2Loader(BT.detectSupport(this.renderer)).setMeshoptDecoder(O1),c=[];o.load(e,l=>{window.VIEWER.json=l;const h=l.scene||l.scenes[0],u=l.animations||[];if(!h)throw new Error("This model contains no scene, and cannot be viewed here. However, it may contain individual 3D resources.");this.setContent(h,u),c.forEach(URL.revokeObjectURL),r(l)},void 0,a)})}setContent(e,t){this.clear(),e.updateMatrixWorld();const n=new ki().setFromObject(e),s=n.getSize(new G).length(),r=n.getCenter(new G);this.controls.reset(),e.position.x-=r.x,e.position.y-=r.y,e.position.z-=r.z,this.controls.maxDistance=s*10,this.defaultCamera.near=s/100,this.defaultCamera.far=s*100,this.defaultCamera.updateProjectionMatrix(),this.options.cameraPosition?(this.defaultCamera.position.fromArray(this.options.cameraPosition),this.defaultCamera.lookAt(new G)):(this.defaultCamera.position.copy(r),this.defaultCamera.position.x+=s/2,this.defaultCamera.position.y+=s/5,this.defaultCamera.position.z+=s/2,this.defaultCamera.lookAt(r)),this.setCamera(Zl),this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesCamera.near=s/100,this.axesCamera.far=s*100,this.axesCamera.updateProjectionMatrix(),this.axesCorner.scale.set(s,s,s),this.controls.saveState(),this.scene.add(e),this.content=e,this.state.punctualLights=!0,this.content.traverse(a=>{a.isLight&&(this.state.punctualLights=!1)}),this.setClips(t),this.animationManager.attach(this.content),this._setupAnimationPanel(),this.updateLights(),this.updateGUI(),this.updateEnvironment(),this.updateDisplay(),this.updateModelInfo(e,t),this.updateAnnotations(),window.VIEWER.scene=this.content,this.invalidate()}setClips(e){JT(this,e)}playAllClips(){ZT(this)}setCamera(e){e===Zl?(this.controls.enabled=!0,this.activeCamera=this.defaultCamera):(this.controls.enabled=!1,this.content.traverse(t=>{t.isCamera&&t.name===e&&(this.activeCamera=t)})),this.invalidate()}updateLights(){const e=this.state,t=this.lights;e.punctualLights&&!t.length?TT(this):!e.punctualLights&&t.length&&RT(this),this.renderer.toneMapping=Number(e.toneMapping),this.renderer.toneMappingExposure=Math.pow(2,e.exposure),t.length===2&&(t[0].intensity=e.ambientIntensity,t[0].color.set(e.ambientColor),t[1].intensity=e.directIntensity,t[1].color.set(e.directColor)),this.invalidate()}updateEnvironment(){const e=Ql.filter(t=>t.name===this.state.environment)[0];jT(this,e).then(({envMap:t})=>{this._disposed||!this.scene||(this.scene.environment=t,this.scene.background=this.state.transparentBg?null:this.state.background?t:this.backgroundColor,this.invalidate())})}updateDisplay(){this.skeletonHelpers.length&&this.skeletonHelpers.forEach(e=>this.scene.remove(e)),P0(this.content,e=>{e.wireframe=this.state.wireframe,e instanceof od&&(e.size=this.state.pointSize)}),this.content.traverse(e=>{if(e.geometry&&e.skeleton&&this.state.skeleton){const t=new ev(e.skeleton.bones[0].parent);t.material.linewidth=3,this.scene.add(t),this.skeletonHelpers.push(t)}}),this.state.grid!==!!this.gridHelper&&(this.state.grid?(this.gridHelper=new tv,this.axesHelper=new wg,this.axesHelper.renderOrder=999,this.axesHelper.onBeforeRender=e=>e.clearDepth(),this.scene.add(this.gridHelper),this.scene.add(this.axesHelper)):(this.scene.remove(this.gridHelper),this.scene.remove(this.axesHelper),this.gridHelper=null,this.axesHelper=null,this.axesRenderer.clear())),this.controls.autoRotate=this.state.autoRotate,this.invalidate()}updateBackground(){this.backgroundColor.set(this.state.bgColor),this.state.transparentBg?(this.scene.background=null,this.renderer.setClearColor(0,0)):(this.scene.background=this.backgroundColor,this.renderer.setClearColor(0,1),this.updateEnvironment()),this.invalidate()}setBackgroundColor(e){this.state.bgColor=typeof e=="string"?e:"#"+e.toString(16).padStart(6,"0"),this.state.transparentBg=!1,this.updateBackground()}updateModelInfo(e,t){this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.state.showInfo&&e&&(this.modelInfo=aT(this.el,e,t))}updateAnnotations(){if(this.annotationEls.forEach(t=>t.el.remove()),this.annotationEls=[],!this.state.showLabels||!this.content)return;lT(this.content).forEach(t=>{const n=hT(t),s=document.createElement("div");s.classList.add("annotation-label"),s.appendChild(n),this.el.appendChild(s),this.annotationEls.push({el:s,position:t.position})}),this.invalidate()}projectAnnotations(){if(this.annotationEls.length===0)return;const e=this.el.clientWidth,t=this.el.clientHeight,n=e/2,s=t/2,r=this._tempVec;this.annotationEls.forEach(({el:a,position:o})=>{if(r.copy(o),r.project(this.activeCamera),r.z>1){a.style.display="none";return}const c=r.x*n+n,l=-(r.y*s)+s;a.style.display="",a.style.left=c+"px",a.style.top=l+"px"})}addAxesHelper(){this.axesDiv=document.createElement("div"),this.el.appendChild(this.axesDiv),this.axesDiv.classList.add("axes");const{clientWidth:e,clientHeight:t}=this.axesDiv;this.axesScene=new $u,this.axesCamera=new Bn(50,e/t,.1,10),this.axesScene.add(this.axesCamera),this.axesRenderer=new $g({alpha:!0}),this.axesRenderer.setPixelRatio(window.devicePixelRatio),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.axesCamera.up=this.defaultCamera.up,this.axesCorner=new wg(5),this.axesScene.add(this.axesCorner),this.axesDiv.appendChild(this.axesRenderer.domElement)}addGUI(){const e=window.innerWidth<=700,t=this.gui=new _M({autoPlace:!1,width:e?220:260,hideable:!0}),n=t.addFolder("Display");n.add(this.state,"background").onChange(()=>this.updateEnvironment()),n.add(this.state,"autoRotate").onChange(()=>this.updateDisplay()),n.add(this.state,"wireframe").onChange(()=>this.updateDisplay()),n.add(this.state,"skeleton").onChange(()=>this.updateDisplay()),n.add(this.state,"grid").onChange(()=>this.updateDisplay()),n.add(this.controls,"screenSpacePanning"),n.add(this.state,"pointSize",1,16).onChange(()=>this.updateDisplay()),n.add(this.state,"transparentBg").name("transparent bg").onChange(()=>this.updateBackground()),n.addColor(this.state,"bgColor").onChange(()=>this.updateBackground()),n.add({screenshot:()=>this.takeScreenshot()},"screenshot").name("Screenshot [P]"),n.add(this.state,"showInfo").name("model info").onChange(()=>this.updateModelInfo(this.content,this.clips)),n.add(this.state,"showLabels").name("mesh labels").onChange(()=>this.updateAnnotations());const p=t.addFolder("Lighting");p.add(this.state,"environment",Ql.map(w=>w.name)).onChange(()=>this.updateEnvironment()),[p.add(this.state,"toneMapping",{Linear:eu,"ACES Filmic":Xp}),p.add(this.state,"exposure",-10,10,.01),p.add(this.state,"punctualLights").listen(),p.add(this.state,"ambientIntensity",0,2),p.addColor(this.state,"ambientColor"),p.add(this.state,"directIntensity",0,4),p.addColor(this.state,"directColor")].forEach(w=>w.onChange(()=>this.updateLights())),this.animFolder=t.addFolder("Animation"),this.animFolder.domElement.style.display="none",this.animFolder.add(this.state,"playbackSpeed",0,1).onChange(w=>{this.mixer&&(this.mixer.timeScale=w)}),this.animFolder.add({playAll:()=>this.playAllClips()},"playAll"),this.morphFolder=t.addFolder("Morph Targets"),this.morphFolder.domElement.style.display="none",this.cameraFolder=t.addFolder("Cameras"),this.cameraFolder.domElement.style.display="none",t.addFolder("Agent").add(this.state,"followMode",{None:"none","Follow Mouse":"mouse","Follow Keystrokes":"keystrokes"}).name("follow mode");const _=t.addFolder("Performance"),x=document.createElement("li");this.stats.dom.style.position="static",x.appendChild(this.stats.dom),x.classList.add("gui-stats"),_.__ul.appendChild(x);const E=document.createElement("div");this.el.appendChild(E),E.classList.add("gui-wrap"),E.classList.add("gui-wrap--hidden"),E.appendChild(t.domElement),this._guiWrap=E;const S=document.createElement("button");S.className="gui-toggle",S.setAttribute("title","Toggle advanced controls"),S.setAttribute("aria-label","Toggle advanced controls"),S.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg><span class="gui-toggle__label">Controls</span>',S.addEventListener("click",()=>{const w=E.classList.toggle("gui-wrap--hidden");S.classList.toggle("gui-toggle--active",!w)}),this.el.appendChild(S),this._guiToggle=S,e?t.close():t.open()}updateGUI(){this.cameraFolder.domElement.style.display="none",this.morphCtrls.forEach(n=>n.remove()),this.morphCtrls.length=0,this.morphFolder.domElement.style.display="none",this.animCtrls.forEach(n=>n.remove()),this.animCtrls.length=0,this.animFolder.domElement.style.display="none";const e=[],t=[];if(this.content.traverse(n=>{n.geometry&&n.morphTargetInfluences&&t.push(n),n.isCamera&&(n.name=n.name||`VIEWER__camera_${e.length+1}`,e.push(n.name))}),e.length){this.cameraFolder.domElement.style.display="",this.cameraCtrl&&this.cameraCtrl.remove();const n=[Zl].concat(e);this.cameraCtrl=this.cameraFolder.add(this.state,"camera",n),this.cameraCtrl.onChange(s=>this.setCamera(s))}if(t.length&&(this.morphFolder.domElement.style.display="",t.forEach(n=>{if(n.morphTargetInfluences.length){const s=this.morphFolder.add({name:n.name||"Untitled"},"name");this.morphCtrls.push(s)}for(let s=0;s<n.morphTargetInfluences.length;s++){const r=this.morphFolder.add(n.morphTargetInfluences,s,0,1,.01).listen();Object.keys(n.morphTargetDictionary).forEach(a=>{a&&n.morphTargetDictionary[a]===s&&r.name(a)}),this.morphCtrls.push(r)}})),this.clips.length){this.animFolder.domElement.style.display="";const n=this.state.actionStates={};this.clips.forEach((s,r)=>{s.name=`${r+1}. ${s.name}`;let a;r===0?(n[s.name]=!0,a=this.mixer.clipAction(s),a.play()):n[s.name]=!1;const o=this.animFolder.add(n,s.name).listen();o.onChange(c=>{a=a||this.mixer.clipAction(s),a.setEffectiveTimeScale(1),c?a.play():a.stop(),this.invalidate()}),this.animCtrls.push(o)})}}setAnimationDefs(e){this.animationManager.setAnimationDefs(e),this.content&&this._setupAnimationPanel()}_setupAnimationPanel(){this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null);const e=this.animationManager.getAnimationDefs();if(e.length===0)return;let t=!1;if(this.content.traverse(s=>{s.isSkinnedMesh&&(t=!0)}),!t)return;const n=document.createElement("div");n.className="anim-panel",n.innerHTML='<div class="anim-panel__header"><span class="anim-panel__title">Animations</span><button class="anim-panel__stop" title="Stop all">⏹</button></div><div class="anim-panel__grid"></div>',this.el.appendChild(n),this._animPanelEl=n,this._renderAnimButtons(),this.animationManager.loadAll().then(()=>{if(this._renderAnimButtons(),!this.animationManager.currentName&&e.length>0){const s=e[0].name;this.animationManager.isLoaded(s)&&(this.animationManager.play(s),this._renderAnimButtons(),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop())}}),n.querySelector(".anim-panel__stop").addEventListener("click",()=>{this.animationManager.stopAll(),this._renderAnimButtons(),this.invalidate()}),this.animationManager.onChange=()=>{this._renderAnimButtons()}}_renderAnimButtons(){if(!this._animPanelEl)return;const e=this._animPanelEl.querySelector(".anim-panel__grid"),t=this.animationManager.getAnimationDefs(),n=this.animationManager.currentName,s={idle:"🧍",breathing:"🧍",standing:"🧍",walking:"🚶",walk:"🚶",running:"🏃",run:"🏃",waving:"👋",wave:"👋",dancing:"💃",dance:"💃",sitting:"🪑",sit:"🪑",jumping:"🦘",jump:"🦘",talking:"🗣️",talk:"🗣️",clapping:"👏",clap:"👏",punching:"👊",punch:"👊",kicking:"🦵",kick:"🦵"};e.innerHTML=t.map((r,a)=>{const o=this.animationManager.isLoaded(r.name),c=n===r.name,l=r.icon||s[r.name.toLowerCase()]||"▶",h=r.label||r.name.charAt(0).toUpperCase()+r.name.slice(1),u=a<9?a+1:"";return'<button class="anim-btn'+(c?" anim-btn--active":"")+(o?"":" anim-btn--loading")+'" data-anim="'+r.name+'" title="'+h+(u?" — press "+u:"")+'"'+(o?"":" disabled")+">"+(u?'<span class="anim-btn__key">'+u+"</span>":"")+'<span class="anim-btn__icon">'+l+'</span><span class="anim-btn__label">'+h+"</span></button>"}).join(""),e.querySelectorAll(".anim-btn:not([disabled])").forEach(r=>{r.addEventListener("click",()=>{const a=r.dataset.anim;this.animationManager.crossfadeTo(a),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop()})}),this._onAnimHotkey||(this._onAnimHotkey=r=>{if(r.target&&/INPUT|TEXTAREA|SELECT/.test(r.target.tagName)||r.metaKey||r.ctrlKey||r.altKey)return;const a=parseInt(r.key,10);if(!a||a<1||a>9)return;const c=this.animationManager.getAnimationDefs()[a-1];!c||!this.animationManager.isLoaded(c.name)||(this.animationManager.crossfadeTo(c.name),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop())},document.addEventListener("keydown",this._onAnimHotkey))}clear(){this.content&&(this.animationManager.detach(),this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null),this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[],this.scene.remove(this.content),this.content.traverse(e=>{e.geometry&&e.geometry.dispose()}),P0(this.content,e=>{for(const t in e)t!=="envMap"&&e[t]&&e[t].isTexture&&e[t].dispose()}),this.content=null,this._disposed||this.invalidate())}dispose(){if(!this._disposed){if(this._disposed=!0,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("resize",this._onResize,!1),window.removeEventListener("keydown",this._onKeyDown),this._onAnimHotkey&&(document.removeEventListener("keydown",this._onAnimHotkey),this._onAnimHotkey=null),this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=null),this.clear(),this.mixer){this.mixer.stopAllAction();const e=this.mixer.getRoot();e&&this.mixer.uncacheRoot(e),this.mixer=null}this.clips=[],this.animationManager.dispose(),this._animPanelEl&&(this._animPanelEl.remove(),this._animPanelEl=null),this.skeletonHelpers.length&&(this.skeletonHelpers.forEach(e=>{this.scene.remove(e),e.dispose?.()}),this.skeletonHelpers.length=0),this.gridHelper&&(this.scene.remove(this.gridHelper),this.gridHelper.geometry?.dispose(),this.gridHelper.material?.dispose(),this.gridHelper=null),this.axesHelper&&(this.scene.remove(this.axesHelper),this.axesHelper.geometry?.dispose(),this.axesHelper.material?.dispose(),this.axesHelper=null),this.axesCorner&&(this.axesScene?.remove(this.axesCorner),this.axesCorner.geometry?.dispose(),this.axesCorner.material?.dispose(),this.axesCorner=null),this.lights.forEach(e=>e.parent?.remove(e)),this.lights=[],this.annotationEls.length&&(this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[]),this.modelInfo&&(this.modelInfo.remove(),this.modelInfo=null),this.gui&&(this.gui.destroy(),this.gui=null),this._guiWrap&&(this._guiWrap.remove(),this._guiWrap=null),this._guiToggle&&(this._guiToggle.remove(),this._guiToggle=null),this.stats?.dom&&this.stats.dom.remove(),this.controls&&(this._onControlsChange&&(this.controls.removeEventListener("change",this._onControlsChange),this._onControlsChange=null),this.controls.dispose(),this.controls=null),this._loadedEnvironment&&(this._loadedEnvironment.dispose(),this._loadedEnvironment=null),this.neutralEnvironment&&(this.neutralEnvironment.dispose(),this.neutralEnvironment=null),this.scene&&(this.scene.environment=null,this.scene.background=null),this.pmremGenerator&&(this.pmremGenerator.dispose(),this.pmremGenerator=null),this.axesRenderer&&(this.axesRenderer.dispose(),this.axesRenderer.forceContextLoss?.(),this.axesRenderer.domElement?.remove(),this.axesRenderer=null),this.axesDiv&&(this.axesDiv.remove(),this.axesDiv=null),this.axesScene=null,this.axesCamera=null,this.renderer&&(this.renderer.dispose(),this.renderer.forceContextLoss?.(),this.renderer.domElement?.remove(),window.renderer===this.renderer&&(window.renderer=null),this.renderer=null),this.scene=null,this.content=null,this.activeCamera=null,this.defaultCamera=null,this._afterAnimateHooks=null}}}class yR{constructor({model:e="claude-opus-4-6",proxyURL:t,apiKey:n,agentId:s,apiOrigin:r,temperature:a=.7,maxTokens:o=4096,thinking:c="auto"}={}){this.model=e,this.apiKey=n,this.temperature=a,this.maxTokens=o,this.thinking=c,t?this.proxyURL=t:!n&&s&&r?this.proxyURL=`${r}/api/llm/anthropic?agent=${encodeURIComponent(s)}`:this.proxyURL=null}async complete({system:e,messages:t,tools:n}){const s={model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,system:e,messages:t};n&&n.length&&(s.tools=n),this.thinking==="always"&&(s.thinking={type:"enabled",budget_tokens:2048});const r=this.proxyURL||"https://api.anthropic.com/v1/messages",a={"content-type":"application/json"};this.apiKey&&(a["x-api-key"]=this.apiKey,a["anthropic-version"]="2023-06-01",a["anthropic-dangerous-direct-browser-access"]="true");const o=await fetch(r,{method:"POST",headers:a,body:JSON.stringify(s)});if(!o.ok){const l=await o.text();throw new Error(`Anthropic ${o.status}: ${l}`)}const c=await o.json();return this._normalize(c)}_normalize(e){const t={text:"",toolCalls:[],thinking:"",stopReason:e.stop_reason};for(const n of e.content||[])n.type==="text"?t.text+=n.text:n.type==="thinking"?t.thinking+=n.thinking||"":n.type==="tool_use"&&t.toolCalls.push({id:n.id,name:n.name,input:n.input});return t}formatToolResults(e){return{role:"user",content:e.map(t=>({type:"tool_result",tool_use_id:t.id,content:typeof t.output=="string"?t.output:JSON.stringify(t.output),is_error:!!t.isError}))}}formatAssistantWithToolCalls(e,t){const n=[];e&&n.push({type:"text",text:e});for(const s of t)n.push({type:"tool_use",id:s.id,name:s.name,input:s.input});return{role:"assistant",content:n}}}class _R{async complete(){return{text:"",toolCalls:[],stopReason:"end_turn"}}formatToolResults(){return{role:"user",content:[]}}formatAssistantWithToolCalls(e){return{role:"assistant",content:e||""}}}function wR(i={}){const e=i.provider||"anthropic";if(e==="anthropic")return new yR(i);if(e==="none")return new _R;throw new Error(`Unsupported provider: ${e}. Supported: anthropic, none`)}class vR{constructor({voiceId:e="default",rate:t=1,pitch:n=1,lang:s="en-US"}={}){this.voiceId=e,this.rate=t,this.pitch=n,this.lang=s,this._queue=[],this._speaking=!1}async speak(e,{onStart:t,onEnd:n}={}){if("speechSynthesis"in window)return new Promise(s=>{const r=new SpeechSynthesisUtterance(e);r.rate=this.rate,r.pitch=this.pitch,r.lang=this.lang;const a=this._pickVoice();a&&(r.voice=a),r.onstart=()=>{this._speaking=!0,t?.()},r.onend=()=>{this._speaking=!1,n?.(),s()},r.onerror=()=>{this._speaking=!1,s()},window.speechSynthesis.speak(r)})}cancel(){"speechSynthesis"in window&&window.speechSynthesis.cancel(),this._speaking=!1}get speaking(){return this._speaking}_pickVoice(){if(!("speechSynthesis"in window))return null;const e=window.speechSynthesis.getVoices();if(this.voiceId&&this.voiceId!=="default"){const t=e.find(n=>n.name===this.voiceId||n.voiceURI===this.voiceId);if(t)return t}return e.find(t=>t.lang?.startsWith(this.lang.slice(0,2)))||null}}class CR{constructor({language:e="en-US",continuous:t=!1,interimResults:n=!0}={}){this.language=e,this.continuous=t,this.interimResults=n,this._recognition=null,this._listening=!1}_ensure(){if(this._recognition)return this._recognition;const e=window.SpeechRecognition||window.webkitSpeechRecognition;if(!e)return null;const t=new e;return t.lang=this.language,t.continuous=this.continuous,t.interimResults=this.interimResults,this._recognition=t,t}async listen({onInterim:e,onFinal:t}={}){const n=this._ensure();if(!n)throw new Error("SpeechRecognition unavailable in this browser");return new Promise((s,r)=>{let a="";n.onresult=o=>{for(let c=o.resultIndex;c<o.results.length;c++){const l=o.results[c],h=l[0].transcript;l.isFinal?(a+=h,t?.(h)):e?.(h)}},n.onerror=o=>{this._listening=!1,r(o.error)},n.onend=()=>{this._listening=!1,s(a.trim())},this._listening=!0;try{n.start()}catch(o){this._listening=!1,r(o)}})}stop(){this._recognition&&this._listening&&this._recognition.stop()}get listening(){return this._listening}}class IR{constructor({voiceId:e,modelId:t="eleven_turbo_v2_5",apiKey:n=null,proxyURL:s=null,rate:r=1,pitch:a=1,lang:o="en-US",stability:c=.5,similarityBoost:l=.75,useSpeakerBoost:h=!0}={}){if(!e)throw new Error("ElevenLabsTTS requires voiceId");this.voiceId=e,this.modelId=t,this.apiKey=n,this.proxyURL=s,this.rate=r,this.pitch=a,this.lang=o,this.stability=c,this.similarityBoost=l,this.useSpeakerBoost=h,this._speaking=!1,this._abort=null,this._audio=null,this._mediaSourceURL=null,this._onEnd=null}async speak(e,{onStart:t,onEnd:n}={}){if(this.cancel(),!e)return;this._abort=new AbortController,this._speaking=!0;const s=this.proxyURL||`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(this.voiceId)}/stream`,r={"content-type":"application/json",accept:"audio/mpeg"};!this.proxyURL&&this.apiKey&&(r["xi-api-key"]=this.apiKey);const a=Math.min(1.5,Math.max(.5,this.rate)),o=Math.min(1,Math.max(0,(a-.5)/1)),c=JSON.stringify({text:e,model_id:this.modelId,voice_settings:{stability:this.stability,similarity_boost:this.similarityBoost,style:o,use_speaker_boost:this.useSpeakerBoost},voiceId:this.voiceId,modelId:this.modelId});let l;try{l=await fetch(s,{method:"POST",headers:r,body:c,signal:this._abort.signal})}catch(d){if(this._speaking=!1,d.name==="AbortError")return;throw d}if(!l.ok)throw this._speaking=!1,new Error(`ElevenLabs TTS HTTP ${l.status}`);const h=typeof MediaSource<"u"&&MediaSource.isTypeSupported("audio/mpeg"),u=d=>{this._startedFired||(this._startedFired=!0,d?.())};return this._startedFired=!1,new Promise(d=>{this._onEnd=()=>{this._speaking=!1,this._cleanupAudio(),n?.(),this._onEnd=null,d()};const f=()=>{this._onEnd&&this._onEnd()};h&&l.body?this._playStreamingMSE(l.body,()=>u(t),f):this._playBuffered(l,()=>u(t),f)})}cancel(){if(this._abort){try{this._abort.abort()}catch{}this._abort=null}this._cleanupAudio(),this._speaking=!1,this._onEnd&&this._onEnd()}get speaking(){return this._speaking}_playStreamingMSE(e,t,n){const s=new MediaSource;this._mediaSourceURL=URL.createObjectURL(s);const r=new Audio(this._mediaSourceURL);this._audio=r,r.preload="auto",r.addEventListener("playing",t,{once:!0}),r.addEventListener("ended",()=>this._onEnd?.(),{once:!0}),r.addEventListener("error",()=>n?.(),{once:!0}),s.addEventListener("sourceopen",async()=>{let a;try{a=s.addSourceBuffer("audio/mpeg")}catch{n?.();return}const o=e.getReader(),c=[];let l=!0;const h=()=>{if(!l||a.updating)return;const u=c.shift();if(u)try{a.appendBuffer(u)}catch{l=!1;try{s.endOfStream()}catch{}}};a.addEventListener("updateend",h);try{for(;l;){const{value:u,done:d}=await o.read();if(d){l=!1;const f=()=>{if(a.updating||c.length)setTimeout(f,30);else try{s.endOfStream()}catch{}};f();break}c.push(u),h()}}catch(u){u.name!=="AbortError"&&n?.()}}),r.play().catch(n)}async _playBuffered(e,t,n){try{const s=await e.blob(),r=URL.createObjectURL(s);this._mediaSourceURL=r;const a=new Audio(r);this._audio=a,a.addEventListener("playing",t,{once:!0}),a.addEventListener("ended",()=>this._onEnd?.(),{once:!0}),a.addEventListener("error",()=>n?.(),{once:!0}),await a.play()}catch(s){s.name!=="AbortError"&&n?.()}}_cleanupAudio(){if(this._audio){try{this._audio.pause()}catch{}this._audio.src="",this._audio=null}if(this._mediaSourceURL){try{URL.revokeObjectURL(this._mediaSourceURL)}catch{}this._mediaSourceURL=null}this._startedFired=!1}}function SR(i={}){const e=i.provider||"browser";if(e==="none")return null;if(e==="browser")return new vR(i);if(e==="elevenlabs")return new IR(i);throw new Error(`TTS provider "${e}" not implemented yet`)}function MR(i={}){const e=i.provider||"browser";if(e==="none")return null;if(e==="browser")return new CR(i);throw new Error(`STT provider "${e}" not implemented yet`)}const X0=[{name:"wave",description:"Wave at the user. Use for greetings, farewells, or acknowledgments.",input_schema:{type:"object",properties:{duration_ms:{type:"integer",minimum:500,maximum:5e3,default:1500}}}},{name:"lookAt",description:"Direct the agent's gaze toward a target.",input_schema:{type:"object",properties:{target:{type:"string",enum:["user","camera","center"],description:"Where to look"}},required:["target"]}},{name:"play_clip",description:"Play a named animation clip from the loaded body.",input_schema:{type:"object",properties:{name:{type:"string"},loop:{type:"boolean",default:!1},fade_ms:{type:"integer",default:200}},required:["name"]}},{name:"setExpression",description:"Set facial expression via morph target preset.",input_schema:{type:"object",properties:{preset:{type:"string",enum:["neutral","happy","sad","surprised","confused","focused"]},intensity:{type:"number",minimum:0,maximum:1,default:1}},required:["preset"]}},{name:"speak",description:"Say something out loud via TTS. Use this instead of plain text when voice is on.",input_schema:{type:"object",properties:{text:{type:"string"}},required:["text"]}},{name:"remember",description:"Save a durable memory about the user, a feedback rule, a project fact, or a reference.",input_schema:{type:"object",properties:{key:{type:"string",description:'short snake_case filename, e.g. "user_role"'},name:{type:"string"},description:{type:"string"},type:{type:"string",enum:["user","feedback","project","reference"]},body:{type:"string"}},required:["key","name","description","type","body"]}}],BR=[{name:"observe_agents",description:"List the other agents currently sharing this stage, with their names and positions.",input_schema:{type:"object",properties:{}}},{name:"say_to_agent",description:"Send a message to another agent on the same stage. The target agent will receive it as a user turn and reply in their own chat chrome.",input_schema:{type:"object",properties:{agentId:{type:"string",description:"Target agent id as returned by observe_agents."},text:{type:"string"}},required:["agentId","text"]}}],TR={async wave(i,e){const t=i.duration_ms||1500;return await e.viewer.playAnimationByHint?.("wave",{duration:t}),e.memory.note("waved",{duration_ms:t}),{ok:!0}},async lookAt(i,e){const t=i.target||"user";return e.viewer.lookAt?.(t),{ok:!0,target:t}},async play_clip(i,e){const{name:t,loop:n=!1,fade_ms:s=200}=i,r=e.viewer.resolveAnimationSlot?.(t)??t;return e.viewer.playClipByName?.(r,{loop:n,fade_ms:s})?{ok:!0,name:t,resolved:r}:(r!==t&&console.warn(`[play_clip] slot "${t}" → "${r}" not found in library`),{ok:!1,error:`No clip named "${r}"`})},async setExpression(i,e){const{preset:t,intensity:n=1}=i;return e.viewer.setExpression?.(t,n),{ok:!0,preset:t}},async speak(i,e){return await e.speak(i.text),{ok:!0}},async remember(i,e){const{key:t,name:n,description:s,type:r,body:a}=i;return e.memory.write(t,{name:n,description:s,type:r,body:a}),{ok:!0,saved:t}},async observe_agents(i,e){return e.stage?{ok:!0,agents:e.stage.getAgents().filter(n=>n.agentId!==e.agentId).map(({agentId:n,name:s,position:r})=>({agentId:n,name:s,position:r}))}:{ok:!1,error:"not on a stage"}},async say_to_agent(i,e){if(!e.stage)return{ok:!1,error:"not on a stage"};const{agentId:t,text:n}=i;if(!t||!n)return{ok:!1,error:"agentId and text required"};const s=e.agentId||"anon";return e.stage.broadcast(s,{kind:"direct",to:t,text:n}),e.stage.routeMessage(s,t,n)}},RR=8;class Y0 extends EventTarget{constructor({manifest:e,viewer:t,memory:n,skills:s,providerConfig:r={},voiceConfig:a={},stage:o=null,agentId:c=null}={}){super(),this.manifest=e||{},this.viewer=t,this.memory=n,this.skills=s,this.stage=o,this.agentId=c,this.provider=wR({...this.manifest.brain,...r}),this.tts=SR({...this.manifest.voice?.tts,...a.tts}),this.stt=MR({...this.manifest.voice?.stt,...a.stt}),this.messages=[],this._busy=!1}get systemPrompt(){const e=[];return this.manifest.instructions&&e.push(this.manifest.instructions),this.memory&&e.push(`
<memory>
`+this.memory.contextBlock({maxTokens:this.manifest.memory?.maxTokens||8192})+`
-</memory>`),this.skills&&e.push(this.skills.systemPrompt()),e.join("")}get tools(){const e=new Set(this.manifest.tools||X0.map(r=>r.name)),t=X0.filter(r=>e.has(r.name)),n=this.skills?this.skills.allTools():[],s=this.stage?TR:[];return[...t,...s,...n]}async send(e,{voice:t=!1}={}){if(this._busy)throw new Error("Runtime busy — wait for current turn to finish");this._busy=!0;try{this.memory?.note("user_said",{text:e}),this.messages.push({role:"user",content:e}),this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"user",content:e}}));const n=await this._loop();return t&&n.text&&this.tts&&(this.dispatchEvent(new CustomEvent("voice:speech-start",{detail:{text:n.text}})),await this.tts.speak(n.text),this.dispatchEvent(new CustomEvent("voice:speech-end",{}))),n}finally{this._busy=!1}}async _loop(){let e=0,t="";for(;e++<FR;){const n=await this.provider.complete({system:this.systemPrompt,messages:this.messages,tools:this.tools});if(n.thinking&&this.dispatchEvent(new CustomEvent("brain:thinking",{detail:{content:n.thinking}})),!n.toolCalls.length){t=n.text,this.messages.push({role:"assistant",content:n.text}),this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"assistant",content:n.text}}));break}this.messages.push(this.provider.formatAssistantWithToolCalls(n.text,n.toolCalls)),n.text&&this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"assistant",content:n.text}}));const s=[];for(const r of n.toolCalls){let a,o=!1;try{a=await this._dispatchTool(r)}catch(c){a={error:c.message||String(c)},o=!0}this.dispatchEvent(new CustomEvent("skill:tool-called",{detail:{tool:r.name,args:r.input,result:a}})),s.push({id:r.id,output:a,isError:o})}this.messages.push(this.provider.formatToolResults(s))}return{text:t}}async _dispatchTool(e){const t=this._context(),n=this.skills?.findSkillForTool(e.name);if(n)return n.invoke(e.name,e.input,t);const s=RR[e.name];if(!s)throw new Error(`Unknown tool: ${e.name}`);return s(e.input,t)}_context(){return this.skills,{viewer:this.viewer,memory:this.memory,llm:{complete:(e,t)=>this.provider.complete({system:t?.system||"",messages:[{role:"user",content:e}],tools:t?.tools})},speak:async e=>{this.tts&&(this.dispatchEvent(new CustomEvent("voice:speech-start",{detail:{text:e}})),await this.tts.speak(e),this.dispatchEvent(new CustomEvent("voice:speech-end",{})))},listen:e=>this.stt?.listen(e),fetch:(e,t)=>fetch(e,t),loadGLB:async e=>this.viewer.loadGLB?.(e),loadClip:async e=>this.viewer.loadClip?.(e),loadJSON:async e=>(await fetch(e)).json(),call:async(e,t)=>this._dispatchTool({name:e,input:t}),stage:this.stage,agentId:this.agentId}}async listen({onInterim:e,onFinal:t}={}){if(!this.stt)throw new Error("STT not configured");return this.dispatchEvent(new CustomEvent("voice:listen-start",{})),await this.stt.listen({onInterim:s=>{this.dispatchEvent(new CustomEvent("voice:transcript",{detail:{text:s,final:!1}})),e?.(s)},onFinal:s=>{this.dispatchEvent(new CustomEvent("voice:transcript",{detail:{text:s,final:!0}})),t?.(s)}})}clearConversation(){this.messages=[]}pause(){this.tts?.cancel(),this.stt?.stop()}destroy(){this.pause(),this.messages=[]}}const Tf=["https://dweb.link/ipfs/","https://cloudflare-ipfs.com/ipfs/","https://ipfs.io/ipfs/"],NR="https://arweave.net/";function hs(i,e=0){if(!i)return i;const t=i.match(/^ipfs:\/\/(.+)$/i);if(t)return Tf[e%Tf.length]+t[1];const n=i.match(/^ar:\/\/(.+)$/i);return n?NR+n[1]:i}async function J0(i){let e;for(let t=0;t<Tf.length;t++){const n=hs(i,t);try{const s=await fetch(n);if(s.ok)return s}catch(s){e=s}}throw e||new Error("All IPFS gateways failed for "+i)}const DR={idle:"idle",wave:"reaction",nod:"reaction",shake:"angry",think:"pray",celebrate:"celebrate",concern:"defeated",bow:"sitclap",point:"reaction",shrug:"defeated"};function LR(i,e){return e&&e[i]?e[i]:DR[i]??i}const Z0={neutral:{},happy:{mouthSmile:1,browInnerUp:.3,cheekSquintL:.4,cheekSquintR:.4},sad:{mouthFrownL:.8,mouthFrownR:.8,browDownL:.6,browDownR:.6},surprised:{jawOpen:.5,eyeWideL:.8,eyeWideR:.8,browInnerUp:.9},confused:{browInnerUp:.5,browOuterUpL:.4,mouthPressL:.3,mouthPressR:.3},focused:{browDownL:.4,browDownR:.4,eyeSquintL:.3,eyeSquintR:.3}};class $0{constructor(e){this.viewer=e,this._loader=new Bd,this._userTarget=new G(0,1.6,2),this._animationMap={},this._group=null,this._groupMixer=null,this._groupClips=null,this._mixerHook=null}get scene(){return this.viewer.scene}get mixer(){return this._groupMixer||this.viewer.mixer}get clips(){return this._groupClips||this.viewer.clips||[]}get content(){return this._group||this.viewer.content}setGroup(e,{mixer:t=null,clips:n=null}={}){this._group=e,this._groupMixer=t,this._groupClips=n,t&&(this._mixerHook=s=>{t.update(s),this.viewer._animating=!0,this.viewer.invalidate()},this._addHook(this._mixerHook))}dispose(){if(this._mixerHook&&this._removeHook(this._mixerHook),this._groupMixer){try{this._groupMixer.stopAllAction()}catch{}try{this._groupMixer.uncacheRoot(this._group)}catch{}}this._mixerHook=null,this._groupMixer=null,this._groupClips=null,this._group=null}setAnimationMap(e){this._animationMap=e||{}}resolveAnimationSlot(e){return LR(e,this._animationMap)}async load(e,t="",n=new Map){return this.viewer.load(e,t,n)}playClipByName(e,{loop:t=!1,fade_ms:n=200}={}){const s=this._findClip(e),r=this.mixer;if(s&&r){const o=r.clipAction(s);return o.reset(),o.setLoop(t?2201:2200),o.clampWhenFinished=!t,o.fadeIn(n/1e3),o.play(),this._group||(this.viewer.state.actionStates[s.name]=!0),this.viewer._animating=!0,this.viewer.invalidate(),!0}const a=this.viewer?.animationManager;return a?.isLoaded(e)?(t?a.crossfadeTo(e,n/1e3):a.play(e),!0):!1}playAnimationByHint(e,t){const n=e.toLowerCase(),s=this.clips.find(a=>a.name.toLowerCase().includes(n));if(s)return this.playClipByName(s.name,t);const r=this.viewer?.animationManager;if(r){for(const a of r.clips.keys())if(a.toLowerCase().includes(n))return this.playClipByName(a,t)}return!1}stopClip(e){const t=this.mixer;if(!t)return;const n=e?this._findClip(e):null;if(n){const s=t.existingAction(n);s&&s.fadeOut(.2),this._group||(this.viewer.state.actionStates[n.name]=!1)}else if(t.stopAllAction(),!this._group)for(const s in this.viewer.state.actionStates)this.viewer.state.actionStates[s]=!1;this.viewer.invalidate()}async play(e,t){if(typeof e=="string")return this.playClipByName(e,t);const n=this.mixer;if(!n||!e)return!1;const s=n.clipAction(e);return s.reset(),s.fadeIn(t?.blend??.2),s.play(),this.viewer._animating=!0,this.viewer.invalidate(),!0}async loadClip(e){const t=hs(e);return new Promise((n,s)=>{this._loader.load(t,r=>n(r.animations?.[0]||null),void 0,s)})}async loadGLB(e){const t=hs(e);return new Promise((n,s)=>{this._loader.load(t,n,void 0,s)})}lookAt(e){const t=this._resolveTarget(e);if(!t||!this.viewer.content)return;const n=this._findBone(["Head","head","mixamorigHead"]);n?n.lookAt(t):this.viewer.content.lookAt(t.x,this.viewer.content.position.y,t.z),this.viewer.invalidate()}_resolveTarget(e){return e instanceof G?e:e==="camera"?this.viewer.activeCamera.position.clone():e==="center"?new G(0,1,0):e==="user"?this.viewer.renderer?.xr?.isPresenting?this.viewer.renderer.xr.getCamera().position.clone():this._userTarget.clone():null}_findBone(e){if(!this.viewer.content)return null;let t=null;return this.viewer.content.traverse(n=>{t||n.isBone&&e.includes(n.name)&&(t=n)}),t}setExpression(e,t=1){const n=Z0[e]||Z0.neutral;this.viewer.content&&(this.viewer.content.traverse(s=>{if(!(!s.morphTargetDictionary||!s.morphTargetInfluences)){for(let r=0;r<s.morphTargetInfluences.length;r++)s.morphTargetInfluences[r]=0;for(const[r,a]of Object.entries(n)){const o=s.morphTargetDictionary[r];o!==void 0&&(s.morphTargetInfluences[o]=a*t)}}}),this.viewer.invalidate())}moveTo(e,{duration:t=600}={}){if(!this.viewer.content)return;const n=this.viewer.content.position.clone(),s=new G(e.x||0,e.y||n.y,e.z||0),r=performance.now(),a=o=>{const c=performance.now()-r,l=Math.min(c/t,1),h=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2;this.viewer.content.position.lerpVectors(n,s,h),this.viewer.invalidate(),l>=1&&this._removeHook(a)};this._addHook(a)}_addHook(e){this.viewer._afterAnimateHooks||(this.viewer._afterAnimateHooks=[]),this.viewer._afterAnimateHooks.push(e),this.viewer._animating=!0,this.viewer.invalidate()}_removeHook(e){const t=this.viewer._afterAnimateHooks;if(!t)return;const n=t.indexOf(e);n>=0&&t.splice(n,1)}_findClip(e){if(!this.clips.length)return null;const t=this.clips.find(s=>s.name===e);if(t)return t;const n=e.toLowerCase();return this.clips.find(s=>s.name.toLowerCase()===n)||this.clips.find(s=>s.name.toLowerCase().includes(n))}}const PR=`// Sandbox worker — executes skill handlers in an isolated Web Worker scope.
+</memory>`),this.skills&&e.push(this.skills.systemPrompt()),e.join("")}get tools(){const e=new Set(this.manifest.tools||X0.map(r=>r.name)),t=X0.filter(r=>e.has(r.name)),n=this.skills?this.skills.allTools():[],s=this.stage?BR:[];return[...t,...s,...n]}async send(e,{voice:t=!1}={}){if(this._busy)throw new Error("Runtime busy — wait for current turn to finish");this._busy=!0;try{this.memory?.note("user_said",{text:e}),this.messages.push({role:"user",content:e}),this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"user",content:e}}));const n=await this._loop();return t&&n.text&&this.tts&&(this.dispatchEvent(new CustomEvent("voice:speech-start",{detail:{text:n.text}})),await this.tts.speak(n.text),this.dispatchEvent(new CustomEvent("voice:speech-end",{}))),n}finally{this._busy=!1}}async _loop(){let e=0,t="";for(;e++<RR;){const n=await this.provider.complete({system:this.systemPrompt,messages:this.messages,tools:this.tools});if(n.thinking&&this.dispatchEvent(new CustomEvent("brain:thinking",{detail:{content:n.thinking}})),!n.toolCalls.length){t=n.text,this.messages.push({role:"assistant",content:n.text}),this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"assistant",content:n.text}}));break}this.messages.push(this.provider.formatAssistantWithToolCalls(n.text,n.toolCalls)),n.text&&this.dispatchEvent(new CustomEvent("brain:message",{detail:{role:"assistant",content:n.text}}));const s=[];for(const r of n.toolCalls){let a,o=!1;try{a=await this._dispatchTool(r)}catch(c){a={error:c.message||String(c)},o=!0}this.dispatchEvent(new CustomEvent("skill:tool-called",{detail:{tool:r.name,args:r.input,result:a}})),s.push({id:r.id,output:a,isError:o})}this.messages.push(this.provider.formatToolResults(s))}return{text:t}}async _dispatchTool(e){const t=this._context(),n=this.skills?.findSkillForTool(e.name);if(n)return n.invoke(e.name,e.input,t);const s=TR[e.name];if(!s)throw new Error(`Unknown tool: ${e.name}`);return s(e.input,t)}_context(){return this.skills,{viewer:this.viewer,memory:this.memory,llm:{complete:(e,t)=>this.provider.complete({system:t?.system||"",messages:[{role:"user",content:e}],tools:t?.tools})},speak:async e=>{this.tts&&(this.dispatchEvent(new CustomEvent("voice:speech-start",{detail:{text:e}})),await this.tts.speak(e),this.dispatchEvent(new CustomEvent("voice:speech-end",{})))},listen:e=>this.stt?.listen(e),fetch:(e,t)=>fetch(e,t),loadGLB:async e=>this.viewer.loadGLB?.(e),loadClip:async e=>this.viewer.loadClip?.(e),loadJSON:async e=>(await fetch(e)).json(),call:async(e,t)=>this._dispatchTool({name:e,input:t}),stage:this.stage,agentId:this.agentId}}async listen({onInterim:e,onFinal:t}={}){if(!this.stt)throw new Error("STT not configured");return this.dispatchEvent(new CustomEvent("voice:listen-start",{})),await this.stt.listen({onInterim:s=>{this.dispatchEvent(new CustomEvent("voice:transcript",{detail:{text:s,final:!1}})),e?.(s)},onFinal:s=>{this.dispatchEvent(new CustomEvent("voice:transcript",{detail:{text:s,final:!0}})),t?.(s)}})}clearConversation(){this.messages=[]}pause(){this.tts?.cancel(),this.stt?.stop()}destroy(){this.pause(),this.messages=[]}}const Tf=["https://dweb.link/ipfs/","https://cloudflare-ipfs.com/ipfs/","https://ipfs.io/ipfs/"],FR="https://arweave.net/";function hs(i,e=0){if(!i)return i;const t=i.match(/^ipfs:\/\/(.+)$/i);if(t)return Tf[e%Tf.length]+t[1];const n=i.match(/^ar:\/\/(.+)$/i);return n?FR+n[1]:i}async function J0(i){let e;for(let t=0;t<Tf.length;t++){const n=hs(i,t);try{const s=await fetch(n);if(s.ok)return s}catch(s){e=s}}throw e||new Error("All IPFS gateways failed for "+i)}const NR={idle:"idle",wave:"reaction",nod:"reaction",shake:"angry",think:"pray",celebrate:"celebrate",concern:"defeated",bow:"sitclap",point:"reaction",shrug:"defeated"};function DR(i,e){return e&&e[i]?e[i]:NR[i]??i}const Z0={neutral:{},happy:{mouthSmile:1,browInnerUp:.3,cheekSquintL:.4,cheekSquintR:.4},sad:{mouthFrownL:.8,mouthFrownR:.8,browDownL:.6,browDownR:.6},surprised:{jawOpen:.5,eyeWideL:.8,eyeWideR:.8,browInnerUp:.9},confused:{browInnerUp:.5,browOuterUpL:.4,mouthPressL:.3,mouthPressR:.3},focused:{browDownL:.4,browDownR:.4,eyeSquintL:.3,eyeSquintR:.3}};class $0{constructor(e){this.viewer=e,this._loader=new Bd,this._userTarget=new G(0,1.6,2),this._animationMap={},this._group=null,this._groupMixer=null,this._groupClips=null,this._mixerHook=null}get scene(){return this.viewer.scene}get mixer(){return this._groupMixer||this.viewer.mixer}get clips(){return this._groupClips||this.viewer.clips||[]}get content(){return this._group||this.viewer.content}setGroup(e,{mixer:t=null,clips:n=null}={}){this._group=e,this._groupMixer=t,this._groupClips=n,t&&(this._mixerHook=s=>{t.update(s),this.viewer._animating=!0,this.viewer.invalidate()},this._addHook(this._mixerHook))}dispose(){if(this._mixerHook&&this._removeHook(this._mixerHook),this._groupMixer){try{this._groupMixer.stopAllAction()}catch{}try{this._groupMixer.uncacheRoot(this._group)}catch{}}this._mixerHook=null,this._groupMixer=null,this._groupClips=null,this._group=null}setAnimationMap(e){this._animationMap=e||{}}resolveAnimationSlot(e){return DR(e,this._animationMap)}async load(e,t="",n=new Map){return this.viewer.load(e,t,n)}playClipByName(e,{loop:t=!1,fade_ms:n=200}={}){const s=this._findClip(e),r=this.mixer;if(s&&r){const o=r.clipAction(s);return o.reset(),o.setLoop(t?2201:2200),o.clampWhenFinished=!t,o.fadeIn(n/1e3),o.play(),this._group||(this.viewer.state.actionStates[s.name]=!0),this.viewer._animating=!0,this.viewer.invalidate(),!0}const a=this.viewer?.animationManager;return a?.isLoaded(e)?(t?a.crossfadeTo(e,n/1e3):a.play(e),!0):!1}playAnimationByHint(e,t){const n=e.toLowerCase(),s=this.clips.find(a=>a.name.toLowerCase().includes(n));if(s)return this.playClipByName(s.name,t);const r=this.viewer?.animationManager;if(r){for(const a of r.clips.keys())if(a.toLowerCase().includes(n))return this.playClipByName(a,t)}return!1}stopClip(e){const t=this.mixer;if(!t)return;const n=e?this._findClip(e):null;if(n){const s=t.existingAction(n);s&&s.fadeOut(.2),this._group||(this.viewer.state.actionStates[n.name]=!1)}else if(t.stopAllAction(),!this._group)for(const s in this.viewer.state.actionStates)this.viewer.state.actionStates[s]=!1;this.viewer.invalidate()}async play(e,t){if(typeof e=="string")return this.playClipByName(e,t);const n=this.mixer;if(!n||!e)return!1;const s=n.clipAction(e);return s.reset(),s.fadeIn(t?.blend??.2),s.play(),this.viewer._animating=!0,this.viewer.invalidate(),!0}async loadClip(e){const t=hs(e);return new Promise((n,s)=>{this._loader.load(t,r=>n(r.animations?.[0]||null),void 0,s)})}async loadGLB(e){const t=hs(e);return new Promise((n,s)=>{this._loader.load(t,n,void 0,s)})}lookAt(e){const t=this._resolveTarget(e);if(!t||!this.viewer.content)return;const n=this._findBone(["Head","head","mixamorigHead"]);n?n.lookAt(t):this.viewer.content.lookAt(t.x,this.viewer.content.position.y,t.z),this.viewer.invalidate()}_resolveTarget(e){return e instanceof G?e:e==="camera"?this.viewer.activeCamera.position.clone():e==="center"?new G(0,1,0):e==="user"?this.viewer.renderer?.xr?.isPresenting?this.viewer.renderer.xr.getCamera().position.clone():this._userTarget.clone():null}_findBone(e){if(!this.viewer.content)return null;let t=null;return this.viewer.content.traverse(n=>{t||n.isBone&&e.includes(n.name)&&(t=n)}),t}setExpression(e,t=1){const n=Z0[e]||Z0.neutral;this.viewer.content&&(this.viewer.content.traverse(s=>{if(!(!s.morphTargetDictionary||!s.morphTargetInfluences)){for(let r=0;r<s.morphTargetInfluences.length;r++)s.morphTargetInfluences[r]=0;for(const[r,a]of Object.entries(n)){const o=s.morphTargetDictionary[r];o!==void 0&&(s.morphTargetInfluences[o]=a*t)}}}),this.viewer.invalidate())}moveTo(e,{duration:t=600}={}){if(!this.viewer.content)return;const n=this.viewer.content.position.clone(),s=new G(e.x||0,e.y||n.y,e.z||0),r=performance.now(),a=o=>{const c=performance.now()-r,l=Math.min(c/t,1),h=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2;this.viewer.content.position.lerpVectors(n,s,h),this.viewer.invalidate(),l>=1&&this._removeHook(a)};this._addHook(a)}_addHook(e){this.viewer._afterAnimateHooks||(this.viewer._afterAnimateHooks=[]),this.viewer._afterAnimateHooks.push(e),this.viewer._animating=!0,this.viewer.invalidate()}_removeHook(e){const t=this.viewer._afterAnimateHooks;if(!t)return;const n=t.indexOf(e);n>=0&&t.splice(n,1)}_findClip(e){if(!this.clips.length)return null;const t=this.clips.find(s=>s.name===e);if(t)return t;const n=e.toLowerCase();return this.clips.find(s=>s.name.toLowerCase()===n)||this.clips.find(s=>s.name.toLowerCase().includes(n))}}const LR=`// Sandbox worker — executes skill handlers in an isolated Web Worker scope.
// No DOM, no window, no document. Only ctx.* and native worker APIs.
/** @type {Map<string, object>} skillURI → module exports */
@@ -4015,17 +4015,17 @@ function _handleResponse({ requestId, result, error }) {
pending.resolve(result);
}
}
-`;let fi=null,Da=null;const La=new Map,Yo=new Map,qs=new Map,th=new Map;let kR=0,UR=0;function ex(i){if(i==null)return null;const e=`@h:${++kR}`;return th.set(e,i),e}function OR(i){return typeof i=="string"&&i.startsWith("@h:")?th.get(i)??i:i}function QR(i){return Array.isArray(i)?i.map(OR):i}function tx(){if(!fi){if(!Da){const i=new Blob([PR],{type:"text/javascript"});Da=URL.createObjectURL(i)}fi=new Worker(Da),fi.onmessage=HR,fi.onerror=GR}return fi}function GR(i){console.error("[sandbox] worker crashed:",i),fi=null,La.clear(),Yo.clear(),th.clear();for(const[,e]of qs)e.reject(new Error("Sandbox worker crashed"));qs.clear()}function HR({data:i}){switch(i.type){case"install-ack":{const e=Yo.get(i.skillURI);Yo.delete(i.skillURI),i.ok?e?.resolve():(La.delete(i.skillURI),e?.reject(new Error(i.error||"Install failed")));break}case"request":{const{invocationId:e,requestId:t,method:n,args:s}=i,r=qs.get(e);if(!r){fi?.postMessage({type:"response",requestId:t,error:"No active invocation"});return}zR(n,s,r.mainCtx).then(a=>fi?.postMessage({type:"response",requestId:t,result:a??null}),a=>fi?.postMessage({type:"response",requestId:t,error:a.message||String(a)}));break}case"invoke-result":{const{invocationId:e,result:t,error:n}=i,s=qs.get(e);if(!s)return;qs.delete(e),n!==void 0?s.reject(new Error(n)):s.resolve(t);break}}}async function zR(i,e,t){const n=QR(e);switch(i){case"viewer.play":return t.viewer?.play?.(n[0],n[1]);case"viewer.stop":return t.viewer?.stop?.(n[0]);case"viewer.setExpression":return t.viewer?.setExpression?.(n[0],n[1]);case"viewer.lookAt":return t.viewer?.lookAt?.(n[0]);case"viewer.moveTo":return t.viewer?.moveTo?.(n[0],n[1]);case"viewer.playAnimationByHint":return t.viewer?.playAnimationByHint?.(n[0],n[1]);case"viewer.playClipByName":return t.viewer?.playClipByName?.(n[0],n[1]);case"memory.read":return t.memory?.read?.(n[0]);case"memory.write":return t.memory?.write?.(n[0],n[1]);case"memory.note":return t.memory?.note?.(n[0],n[1]);case"memory.recall":return t.memory?.recall?.(n[0]);case"llm.complete":return t.llm?.complete?.(n[0],n[1]);case"llm.embed":return t.llm?.embed?.(n[0]);case"loadClip":{const s=await t.loadClip?.(n[0]);return ex(s)}case"loadGLB":{const s=await t.loadGLB?.(n[0]);return ex(s)}case"speak":return t.speak?.(n[0]);case"listen":return t.listen?.(n[0]);case"call":return t.call?.(n[0],n[1]);default:throw new Error(`Unknown ctx method: ${i}`)}}async function VR(i,e){if(La.has(i))return La.get(i);const t=new Promise((n,s)=>{Yo.set(i,{resolve:n,reject:s})});return La.set(i,t),tx().postMessage({type:"install",skillURI:i,handlersSrc:e}),t}async function WR(i,e,t,n,s){await VR(i,n);const r=++UR,a=tx();return new Promise((o,c)=>{qs.set(r,{resolve:o,reject:c,mainCtx:s}),a.postMessage({type:"invoke",invocationId:r,skillURI:i,toolName:e,args:t,skillBaseURI:s.skillBaseURI||i})})}function qR(){if(fi){fi.terminate(),fi=null,Da&&(URL.revokeObjectURL(Da),Da=null),La.clear(),Yo.clear(),th.clear();for(const[,i]of qs)i.reject(new Error("Sandbox terminated"));qs.clear()}}function KR(){return{invoke:WR,terminate:qR}}function jR(i,e){return/^([a-z]+:|\/)/i.test(e)?e:(i.endsWith("/")||(i+="/"),i+e)}class nx{constructor({uri:e,manifest:t,instructions:n,tools:s,handlers:r,handlersSrc:a}){this.uri=e,this.manifest=t,this.name=t.name,this.version=t.version,this.instructions=n,this.tools=s||[],this.handlers=r||{},this.handlersSrc=a||null}async invoke(e,t,n){const s={...n,skillBaseURI:this.uri};if(this.manifest.sandboxPolicy==="trusted-main-thread"){const r=this.handlers[e];if(!r)throw new Error(`Skill "${this.name}" has no handler for tool "${e}"`);return r(t,s)}if(!this.handlersSrc)throw new Error(`Skill "${this.name}" has no handler source for tool "${e}"`);return KR().invoke(this.uri,e,t,this.handlersSrc,s)}systemPromptFragment(){return this.instructions?`
+`;let fi=null,Da=null;const La=new Map,Yo=new Map,qs=new Map,th=new Map;let PR=0,kR=0;function ex(i){if(i==null)return null;const e=`@h:${++PR}`;return th.set(e,i),e}function UR(i){return typeof i=="string"&&i.startsWith("@h:")?th.get(i)??i:i}function OR(i){return Array.isArray(i)?i.map(UR):i}function tx(){if(!fi){if(!Da){const i=new Blob([LR],{type:"text/javascript"});Da=URL.createObjectURL(i)}fi=new Worker(Da),fi.onmessage=GR,fi.onerror=QR}return fi}function QR(i){console.error("[sandbox] worker crashed:",i),fi=null,La.clear(),Yo.clear(),th.clear();for(const[,e]of qs)e.reject(new Error("Sandbox worker crashed"));qs.clear()}function GR({data:i}){switch(i.type){case"install-ack":{const e=Yo.get(i.skillURI);Yo.delete(i.skillURI),i.ok?e?.resolve():(La.delete(i.skillURI),e?.reject(new Error(i.error||"Install failed")));break}case"request":{const{invocationId:e,requestId:t,method:n,args:s}=i,r=qs.get(e);if(!r){fi?.postMessage({type:"response",requestId:t,error:"No active invocation"});return}HR(n,s,r.mainCtx).then(a=>fi?.postMessage({type:"response",requestId:t,result:a??null}),a=>fi?.postMessage({type:"response",requestId:t,error:a.message||String(a)}));break}case"invoke-result":{const{invocationId:e,result:t,error:n}=i,s=qs.get(e);if(!s)return;qs.delete(e),n!==void 0?s.reject(new Error(n)):s.resolve(t);break}}}async function HR(i,e,t){const n=OR(e);switch(i){case"viewer.play":return t.viewer?.play?.(n[0],n[1]);case"viewer.stop":return t.viewer?.stop?.(n[0]);case"viewer.setExpression":return t.viewer?.setExpression?.(n[0],n[1]);case"viewer.lookAt":return t.viewer?.lookAt?.(n[0]);case"viewer.moveTo":return t.viewer?.moveTo?.(n[0],n[1]);case"viewer.playAnimationByHint":return t.viewer?.playAnimationByHint?.(n[0],n[1]);case"viewer.playClipByName":return t.viewer?.playClipByName?.(n[0],n[1]);case"memory.read":return t.memory?.read?.(n[0]);case"memory.write":return t.memory?.write?.(n[0],n[1]);case"memory.note":return t.memory?.note?.(n[0],n[1]);case"memory.recall":return t.memory?.recall?.(n[0]);case"llm.complete":return t.llm?.complete?.(n[0],n[1]);case"llm.embed":return t.llm?.embed?.(n[0]);case"loadClip":{const s=await t.loadClip?.(n[0]);return ex(s)}case"loadGLB":{const s=await t.loadGLB?.(n[0]);return ex(s)}case"speak":return t.speak?.(n[0]);case"listen":return t.listen?.(n[0]);case"call":return t.call?.(n[0],n[1]);default:throw new Error(`Unknown ctx method: ${i}`)}}async function zR(i,e){if(La.has(i))return La.get(i);const t=new Promise((n,s)=>{Yo.set(i,{resolve:n,reject:s})});return La.set(i,t),tx().postMessage({type:"install",skillURI:i,handlersSrc:e}),t}async function VR(i,e,t,n,s){await zR(i,n);const r=++kR,a=tx();return new Promise((o,c)=>{qs.set(r,{resolve:o,reject:c,mainCtx:s}),a.postMessage({type:"invoke",invocationId:r,skillURI:i,toolName:e,args:t,skillBaseURI:s.skillBaseURI||i})})}function WR(){if(fi){fi.terminate(),fi=null,Da&&(URL.revokeObjectURL(Da),Da=null),La.clear(),Yo.clear(),th.clear();for(const[,i]of qs)i.reject(new Error("Sandbox terminated"));qs.clear()}}function qR(){return{invoke:VR,terminate:WR}}function KR(i,e){return/^([a-z]+:|\/)/i.test(e)?e:(i.endsWith("/")||(i+="/"),i+e)}class nx{constructor({uri:e,manifest:t,instructions:n,tools:s,handlers:r,handlersSrc:a}){this.uri=e,this.manifest=t,this.name=t.name,this.version=t.version,this.instructions=n,this.tools=s||[],this.handlers=r||{},this.handlersSrc=a||null}async invoke(e,t,n){const s={...n,skillBaseURI:this.uri};if(this.manifest.sandboxPolicy==="trusted-main-thread"){const r=this.handlers[e];if(!r)throw new Error(`Skill "${this.name}" has no handler for tool "${e}"`);return r(t,s)}if(!this.handlersSrc)throw new Error(`Skill "${this.name}" has no handler source for tool "${e}"`);return qR().invoke(this.uri,e,t,this.handlersSrc,s)}systemPromptFragment(){return this.instructions?`
<skill name="${this.name}" version="${this.version}">
${this.instructions}
-</skill>`:""}}class ix{constructor({fetchFn:e=fetch.bind(globalThis),trust:t="owned-only",ownerAddress:n}={}){this.fetchFn=e,this.trust=t,this.ownerAddress=n?.toLowerCase(),this.skills=new Map}async install(e,{bundleBase:t}={}){const n=this._resolveBundleURI(e.uri,t);if(this.skills.has(n))return this.skills.get(n);const s=await this._fetchJSON(`${n}manifest.json`);this._enforceTrust(s);const r=s.sandboxPolicy==="trusted-main-thread",[a,o,c]=await Promise.all([this._fetchText(`${n}SKILL.md`).catch(()=>""),this._fetchJSON(`${n}tools.json`).catch(()=>({tools:[]})),r?this._fetchHandlers(`${n}handlers.js`).catch(()=>null):this._fetchHandlersSrc(`${n}handlers.js`).catch(()=>null)]),l=new nx({uri:n,manifest:s,instructions:a,tools:o.tools||[],handlers:r?c||{}:{},handlersSrc:r?null:c});if(s.dependencies)for(const[h,u]of Object.entries(s.dependencies))await this.install({uri:h,version:u});return this.skills.set(n,l),l}uninstall(e){for(const[t,n]of this.skills)if(n.name===e)return this.skills.delete(t),!0;return!1}all(){return Array.from(this.skills.values())}allTools(){const e=new Map;for(const t of this.skills.values())for(const n of t.tools)e.has(n.name)&&console.warn(`[skills] tool "${n.name}" overridden by skill "${t.name}"`),e.set(n.name,{...n,_skill:t.name});return Array.from(e.values())}findSkillForTool(e){for(const t of this.skills.values())if(t.tools.some(n=>n.name===e))return t;return null}systemPrompt(){return this.all().map(e=>e.systemPromptFragment()).join("")}_resolveBundleURI(e,t){let n=e;return!/^([a-z]+:|\/)/i.test(e)&&t&&(n=jR(t,e)),n.endsWith("/")||(n+="/"),(n.startsWith("ipfs://")||n.startsWith("ar://"))&&(n=hs(n)),n}async _fetchJSON(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.json()}async _fetchText(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.text()}async _fetchHandlers(e){try{return await import(e)}catch(t){return console.warn(`[skills] handlers load failed: ${e}`,t),null}}async _fetchHandlersSrc(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.text()}_enforceTrust(e){if(this.trust!=="any"){if(this.trust==="owned-only"){const t=(e.author||"").toLowerCase();if(t&&this.ownerAddress&&t!==this.ownerAddress)throw new Error(`Skill "${e.name}" author ${t} not trusted under owned-only policy`)}this.trust}}}const XR=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;function nh(i){const e=i.match(XR);if(!e)return{meta:{},body:i};const t={};for(const n of e[1].split(`
-`)){const[s,...r]=n.split(":");s&&(t[s.trim()]=r.join(":").trim())}return{meta:t,body:e[2]}}function YR(i,e){const t=["---"];for(const[n,s]of Object.entries(i))t.push(`${n}: ${s}`);return t.push("---","",e),t.join(`
-`)}class Bi{constructor({mode:e="local",namespace:t,index:n={},files:s={},timeline:r=[]}={}){this.mode=e,this.namespace=t,this.files=new Map(Object.entries(s)),this.timeline=r,this.indexText=n.text||"",this._dirty=!1}static async load({mode:e="local",namespace:t,manifestURI:n,fetchFn:s}){if(e==="none")return new Bi({mode:"none",namespace:t});if(e==="local")return Bi._loadLocal(t);if(e==="ipfs"||e==="encrypted-ipfs")return Bi._loadIPFS({mode:e,namespace:t,manifestURI:n,fetchFn:s});throw new Error(`Unknown memory mode: ${e}`)}static _loadLocal(e){const t=`agent:${e}:memory`;try{const n=localStorage.getItem(t);if(!n)return new Bi({mode:"local",namespace:e});const s=JSON.parse(n);return new Bi({mode:"local",namespace:e,...s})}catch{return new Bi({mode:"local",namespace:e})}}static async _loadIPFS({mode:e,namespace:t,manifestURI:n,fetchFn:s}){const r=n.replace(/manifest\.json$/,"");try{const a=await s(`${r}memory/MEMORY.md`),o=a.ok?await a.text():"",c={},l=/\[([^\]]+)\]\(([^)]+\.md)\)/g;let h;for(;h=l.exec(o);){const u=h[2];try{const d=await s(`${r}memory/${u}`);d.ok&&(c[u]=await d.text())}catch{}}return new Bi({mode:e,namespace:t,index:{text:o},files:c})}catch{return new Bi({mode:e,namespace:t})}}read(e){const t=e.endsWith(".md")?e:`${e}.md`,n=this.files.get(t);return n?nh(n):null}write(e,{name:t,description:n,type:s,body:r,decay:a}){const o=e.endsWith(".md")?e:`${e}.md`,c=new Date().toISOString().slice(0,10),l=this.files.get(o),h=l&&nh(l).meta.created||c,u={name:t,description:n,type:s,created:h,updated:c};a&&(u.decay=a),this.files.set(o,YR(u,r||"")),this._rebuildIndex(),this._dirty=!0,this._persist()}note(e,t){const n={ts:new Date().toISOString(),type:e,...t};this.timeline.push(n),this.timeline.length>1e3&&(this.timeline=this.timeline.slice(-1e3)),this._dirty=!0,this._persist()}async recall(e,{limit:t=5}={}){const n=e.toLowerCase(),s=[];for(const[r,a]of this.files){const{meta:o,body:c}=nh(a),l=`${o.name||""} ${o.description||""} ${c}`.toLowerCase();l.includes(n)&&s.push({file:r,meta:o,body:c,score:l.split(n).length-1})}return s.sort((r,a)=>a.score-r.score).slice(0,t)}_rebuildIndex(){const e={user:[],feedback:[],project:[],reference:[]};for(const[s,r]of this.files){const{meta:a}=nh(r),o=a.type||"user";e[o]||(e[o]=[]),e[o].push({file:s,name:a.name||s,description:a.description||""})}const t=["# Memory",""],n={user:"## User",feedback:"## Feedback",project:"## Project",reference:"## Reference"};for(const[s,r]of Object.entries(e))if(r.length){t.push(n[s]||`## ${s}`);for(const a of r)t.push(`- [${a.name}](${a.file}) — ${a.description}`);t.push("")}this.indexText=t.join(`
+</skill>`:""}}class ix{constructor({fetchFn:e=fetch.bind(globalThis),trust:t="owned-only",ownerAddress:n}={}){this.fetchFn=e,this.trust=t,this.ownerAddress=n?.toLowerCase(),this.skills=new Map}async install(e,{bundleBase:t}={}){const n=this._resolveBundleURI(e.uri,t);if(this.skills.has(n))return this.skills.get(n);const s=await this._fetchJSON(`${n}manifest.json`);this._enforceTrust(s);const r=s.sandboxPolicy==="trusted-main-thread",[a,o,c]=await Promise.all([this._fetchText(`${n}SKILL.md`).catch(()=>""),this._fetchJSON(`${n}tools.json`).catch(()=>({tools:[]})),r?this._fetchHandlers(`${n}handlers.js`).catch(()=>null):this._fetchHandlersSrc(`${n}handlers.js`).catch(()=>null)]),l=new nx({uri:n,manifest:s,instructions:a,tools:o.tools||[],handlers:r?c||{}:{},handlersSrc:r?null:c});if(s.dependencies)for(const[h,u]of Object.entries(s.dependencies))await this.install({uri:h,version:u});return this.skills.set(n,l),l}uninstall(e){for(const[t,n]of this.skills)if(n.name===e)return this.skills.delete(t),!0;return!1}all(){return Array.from(this.skills.values())}allTools(){const e=new Map;for(const t of this.skills.values())for(const n of t.tools)e.has(n.name)&&console.warn(`[skills] tool "${n.name}" overridden by skill "${t.name}"`),e.set(n.name,{...n,_skill:t.name});return Array.from(e.values())}findSkillForTool(e){for(const t of this.skills.values())if(t.tools.some(n=>n.name===e))return t;return null}systemPrompt(){return this.all().map(e=>e.systemPromptFragment()).join("")}_resolveBundleURI(e,t){let n=e;return!/^([a-z]+:|\/)/i.test(e)&&t&&(n=KR(t,e)),n.endsWith("/")||(n+="/"),(n.startsWith("ipfs://")||n.startsWith("ar://"))&&(n=hs(n)),n}async _fetchJSON(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.json()}async _fetchText(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.text()}async _fetchHandlers(e){try{return await import(e)}catch(t){return console.warn(`[skills] handlers load failed: ${e}`,t),null}}async _fetchHandlersSrc(e){const t=await this.fetchFn(e);if(!t.ok)throw new Error(`Fetch failed: ${e} (${t.status})`);return t.text()}_enforceTrust(e){if(this.trust!=="any"){if(this.trust==="owned-only"){const t=(e.author||"").toLowerCase();if(t&&this.ownerAddress&&t!==this.ownerAddress)throw new Error(`Skill "${e.name}" author ${t} not trusted under owned-only policy`)}this.trust}}}const jR=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;function nh(i){const e=i.match(jR);if(!e)return{meta:{},body:i};const t={};for(const n of e[1].split(`
+`)){const[s,...r]=n.split(":");s&&(t[s.trim()]=r.join(":").trim())}return{meta:t,body:e[2]}}function XR(i,e){const t=["---"];for(const[n,s]of Object.entries(i))t.push(`${n}: ${s}`);return t.push("---","",e),t.join(`
+`)}class Bi{constructor({mode:e="local",namespace:t,index:n={},files:s={},timeline:r=[]}={}){this.mode=e,this.namespace=t,this.files=new Map(Object.entries(s)),this.timeline=r,this.indexText=n.text||"",this._dirty=!1}static async load({mode:e="local",namespace:t,manifestURI:n,fetchFn:s}){if(e==="none")return new Bi({mode:"none",namespace:t});if(e==="local")return Bi._loadLocal(t);if(e==="ipfs"||e==="encrypted-ipfs")return Bi._loadIPFS({mode:e,namespace:t,manifestURI:n,fetchFn:s});throw new Error(`Unknown memory mode: ${e}`)}static _loadLocal(e){const t=`agent:${e}:memory`;try{const n=localStorage.getItem(t);if(!n)return new Bi({mode:"local",namespace:e});const s=JSON.parse(n);return new Bi({mode:"local",namespace:e,...s})}catch{return new Bi({mode:"local",namespace:e})}}static async _loadIPFS({mode:e,namespace:t,manifestURI:n,fetchFn:s}){const r=n.replace(/manifest\.json$/,"");try{const a=await s(`${r}memory/MEMORY.md`),o=a.ok?await a.text():"",c={},l=/\[([^\]]+)\]\(([^)]+\.md)\)/g;let h;for(;h=l.exec(o);){const u=h[2];try{const d=await s(`${r}memory/${u}`);d.ok&&(c[u]=await d.text())}catch{}}return new Bi({mode:e,namespace:t,index:{text:o},files:c})}catch{return new Bi({mode:e,namespace:t})}}read(e){const t=e.endsWith(".md")?e:`${e}.md`,n=this.files.get(t);return n?nh(n):null}write(e,{name:t,description:n,type:s,body:r,decay:a}){const o=e.endsWith(".md")?e:`${e}.md`,c=new Date().toISOString().slice(0,10),l=this.files.get(o),h=l&&nh(l).meta.created||c,u={name:t,description:n,type:s,created:h,updated:c};a&&(u.decay=a),this.files.set(o,XR(u,r||"")),this._rebuildIndex(),this._dirty=!0,this._persist()}note(e,t){const n={ts:new Date().toISOString(),type:e,...t};this.timeline.push(n),this.timeline.length>1e3&&(this.timeline=this.timeline.slice(-1e3)),this._dirty=!0,this._persist()}async recall(e,{limit:t=5}={}){const n=e.toLowerCase(),s=[];for(const[r,a]of this.files){const{meta:o,body:c}=nh(a),l=`${o.name||""} ${o.description||""} ${c}`.toLowerCase();l.includes(n)&&s.push({file:r,meta:o,body:c,score:l.split(n).length-1})}return s.sort((r,a)=>a.score-r.score).slice(0,t)}_rebuildIndex(){const e={user:[],feedback:[],project:[],reference:[]};for(const[s,r]of this.files){const{meta:a}=nh(r),o=a.type||"user";e[o]||(e[o]=[]),e[o].push({file:s,name:a.name||s,description:a.description||""})}const t=["# Memory",""],n={user:"## User",feedback:"## Feedback",project:"## Project",reference:"## Reference"};for(const[s,r]of Object.entries(e))if(r.length){t.push(n[s]||`## ${s}`);for(const a of r)t.push(`- [${a.name}](${a.file}) — ${a.description}`);t.push("")}this.indexText=t.join(`
`)}_persist(){if(this.mode!=="local"||!this.namespace)return;const e=`agent:${this.namespace}:memory`,t={index:{text:this.indexText},files:Object.fromEntries(this.files),timeline:this.timeline.slice(-200)};try{localStorage.setItem(e,JSON.stringify(t))}catch(n){console.warn("[memory] persist failed",n)}}contextBlock({maxTokens:e=8192}={}){const t=e*4,n=["# Agent Memory","",this.indexText];let s=n.join(`
`).length;for(const[r,a]of this.files){if(s+a.length>t)break;n.push("",`## ${r}`,a),s+=a.length}if(this.timeline.length){const a=this.timeline.slice(-20).map(o=>JSON.stringify(o)).join(`
`);s+a.length<t&&n.push("","## Recent timeline","```",a,"```")}return n.join(`
-`)}async export(){return{version:"memory/0.1",index:this.indexText,files:Object.fromEntries(this.files),timeline:this.timeline}}async import(e,{strategy:t="merge"}={}){if(t==="replace")this.files=new Map(Object.entries(e.files||{})),this.timeline=e.timeline||[];else{for(const[n,s]of Object.entries(e.files||{}))this.files.has(n)||this.files.set(n,s);this.timeline=[...this.timeline,...e.timeline||[]].slice(-1e3)}this._rebuildIndex(),this._persist()}}const JR="6.16.0";function ZR(i,e,t){const n=e.split("|").map(r=>r.trim());for(let r=0;r<n.length;r++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof i===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${t}`,s.value=i,s}async function Hn(i){const e=Object.keys(i);return(await Promise.all(e.map(n=>Promise.resolve(i[n])))).reduce((n,s,r)=>(n[e[r]]=s,n),{})}function Ye(i,e,t){for(let n in e){let s=e[n];const r=t?t[n]:null;r&&ZR(s,r,n),Object.defineProperty(i,n,{enumerable:!0,value:s,writable:!1})}}function Pa(i,e){if(i==null)return"null";if(e==null&&(e=new Set),typeof i=="object"){if(e.has(i))return"[Circular]";e.add(i)}if(Array.isArray(i))return"[ "+i.map(t=>Pa(t,e)).join(", ")+" ]";if(i instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let s=0;s<i.length;s++)n+=t[i[s]>>4],n+=t[i[s]&15];return n}if(typeof i=="object"&&typeof i.toJSON=="function")return Pa(i.toJSON(),e);switch(typeof i){case"boolean":case"number":case"symbol":return i.toString();case"bigint":return BigInt(i).toString();case"string":return JSON.stringify(i);case"object":{const t=Object.keys(i);return t.sort(),"{ "+t.map(n=>`${Pa(n,e)}: ${Pa(i[n],e)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Tn(i,e){return i&&i.code===e}function Rf(i){return Tn(i,"CALL_EXCEPTION")}function Qt(i,e,t){let n=i;{const r=[];if(t){if("message"in t||"code"in t||"name"in t)throw new Error(`value will overwrite populated values: ${Pa(t)}`);for(const a in t){if(a==="shortMessage")continue;const o=t[a];r.push(a+"="+Pa(o))}}r.push(`code=${e}`),r.push(`version=${JR}`),r.length&&(i+=" ("+r.join(", ")+")")}let s;switch(e){case"INVALID_ARGUMENT":s=new TypeError(i);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":s=new RangeError(i);break;default:s=new Error(i)}return Ye(s,{code:e}),t&&Object.assign(s,t),s.shortMessage==null&&Ye(s,{shortMessage:n}),s}function pe(i,e,t,n){if(!i)throw Qt(e,t,n)}function V(i,e,t,n){pe(i,e,"INVALID_ARGUMENT",{argument:t,value:n})}function sx(i,e,t){t==null&&(t=""),t&&(t=": "+t),pe(i>=e,"missing argument"+t,"MISSING_ARGUMENT",{count:i,expectedCount:e}),pe(i<=e,"too many arguments"+t,"UNEXPECTED_ARGUMENT",{count:i,expectedCount:e})}["NFD","NFC","NFKD","NFKC"].reduce((i,e)=>{try{if("test".normalize(e)!=="test")throw new Error("bad");if(e==="NFD"&&"é".normalize("NFD")!=="é")throw new Error("broken");i.push(e)}catch{}return i},[]);function ih(i,e,t){if(t==null&&(t=""),i!==e){let n=t,s="new";t&&(n+=".",s+=" "+t),pe(!1,`private constructor; use ${n}from* methods`,"UNSUPPORTED_OPERATION",{operation:s})}}function rx(i,e,t){if(i instanceof Uint8Array)return t?new Uint8Array(i):i;if(typeof i=="string"&&i.length%2===0&&i.match(/^0x[0-9a-f]*$/i)){const n=new Uint8Array((i.length-2)/2);let s=2;for(let r=0;r<n.length;r++)n[r]=parseInt(i.substring(s,s+2),16),s+=2;return n}V(!1,"invalid BytesLike value",e||"value",i)}function ut(i,e){return rx(i,e,!1)}function zn(i,e){return rx(i,e,!0)}function Pt(i,e){return!(typeof i!="string"||!i.match(/^0x[0-9A-Fa-f]*$/)||typeof e=="number"&&i.length!==2+2*e||e===!0&&i.length%2!==0)}function Ff(i){return Pt(i,!0)||i instanceof Uint8Array}const ax="0123456789abcdef";function Ce(i){const e=ut(i);let t="0x";for(let n=0;n<e.length;n++){const s=e[n];t+=ax[(s&240)>>4]+ax[s&15]}return t}function Gt(i){return"0x"+i.map(e=>Ce(e).substring(2)).join("")}function ka(i){return Pt(i,!0)?(i.length-2)/2:ut(i).length}function Kt(i,e,t){const n=ut(i);return t!=null&&t>n.length&&pe(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:n,length:n.length,offset:t}),Ce(n.slice(e??0,t??n.length))}function ox(i,e,t){const n=ut(i);pe(e>=n.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(n),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),t?s.set(n,e-n.length):s.set(n,0),Ce(s)}function us(i,e){return ox(i,e,!0)}function $R(i,e){return ox(i,e,!1)}const Jo=BigInt(0),Ti=BigInt(1),Ua=9007199254740991;function eF(i,e){const t=sh(i,"value"),n=BigInt(dt(e,"width"));if(pe(t>>n===Jo,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:i}),t>>n-Ti){const s=(Ti<<n)-Ti;return-((~t&s)+Ti)}return t}function cx(i,e){let t=Ne(i,"value");const n=BigInt(dt(e,"width")),s=Ti<<n-Ti;if(t<Jo){t=-t,pe(t<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:i});const r=(Ti<<n)-Ti;return(~t&r)+Ti}else pe(t<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:i});return t}function Zo(i,e){const t=sh(i,"value"),n=BigInt(dt(e,"bits"));return t&(Ti<<n)-Ti}function Ne(i,e){switch(typeof i){case"bigint":return i;case"number":return V(Number.isInteger(i),"underflow",e||"value",i),V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),BigInt(i);case"string":try{if(i==="")throw new Error("empty string");return i[0]==="-"&&i[1]!=="-"?-BigInt(i.substring(1)):BigInt(i)}catch(t){V(!1,`invalid BigNumberish string: ${t.message}`,e||"value",i)}}V(!1,"invalid BigNumberish value",e||"value",i)}function sh(i,e){const t=Ne(i,e);return pe(t>=Jo,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:i}),t}const lx="0123456789abcdef";function Nf(i){if(i instanceof Uint8Array){let e="0x0";for(const t of i)e+=lx[t>>4],e+=lx[t&15];return BigInt(e)}return Ne(i)}function dt(i,e){switch(typeof i){case"bigint":return V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),Number(i);case"number":return V(Number.isInteger(i),"underflow",e||"value",i),V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),i;case"string":try{if(i==="")throw new Error("empty string");return dt(BigInt(i),e)}catch(t){V(!1,`invalid numeric string: ${t.message}`,e||"value",i)}}V(!1,"invalid numeric value",e||"value",i)}function tF(i){return dt(Nf(i))}function Ks(i,e){const t=sh(i,"value");let n=t.toString(16);if(e==null)n.length%2&&(n="0"+n);else{const s=dt(e,"width");if(s===0&&t===Jo)return"0x";for(pe(s*2>=n.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:i});n.length<s*2;)n="0"+n}return"0x"+n}function rn(i,e){const t=sh(i,"value");if(t===Jo)return new Uint8Array(0);let n=t.toString(16);n.length%2&&(n="0"+n);const s=new Uint8Array(n.length/2);for(let r=0;r<s.length;r++){const a=r*2;s[r]=parseInt(n.substring(a,a+2),16)}return s}function Ri(i){let e=Ce(Ff(i)?i:rn(i)).substring(2);for(;e.startsWith("0");)e=e.substring(1);return e===""&&(e="0"),"0x"+e}const hx="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";BigInt(0);const ux=BigInt(58);function nF(i){const e=ut(i);let t=Nf(e),n="";for(;t;)n=hx[Number(t%ux)]+n,t/=ux;for(let s=0;s<e.length&&!e[s];s++)n=hx[0]+n;return n}function iF(i){i=atob(i);const e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return ut(e)}function sF(i){const e=ut(i);let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}class dx{filter;emitter;#e;constructor(e,t,n){this.#e=t,Ye(this,{emitter:e,filter:n})}async removeListener(){this.#e!=null&&await this.emitter.off(this.filter,this.#e)}}function rF(i,e,t,n,s){V(!1,`invalid codepoint at offset ${e}; ${i}`,"bytes",t)}function fx(i,e,t,n,s){if(i==="BAD_PREFIX"||i==="UNEXPECTED_CONTINUE"){let r=0;for(let a=e+1;a<t.length&&t[a]>>6===2;a++)r++;return r}return i==="OVERRUN"?t.length-e-1:0}function aF(i,e,t,n,s){return i==="OVERLONG"?(V(typeof s=="number","invalid bad code point for replacement","badCodepoint",s),n.push(s),0):(n.push(65533),fx(i,e,t))}const oF=Object.freeze({error:rF,ignore:fx,replace:aF});function cF(i,e){e==null&&(e=oF.error);const t=ut(i,"bytes"),n=[];let s=0;for(;s<t.length;){const r=t[s++];if(r>>7===0){n.push(r);continue}let a=null,o=null;if((r&224)===192)a=1,o=127;else if((r&240)===224)a=2,o=2047;else if((r&248)===240)a=3,o=65535;else{(r&192)===128?s+=e("UNEXPECTED_CONTINUE",s-1,t,n):s+=e("BAD_PREFIX",s-1,t,n);continue}if(s-1+a>=t.length){s+=e("OVERRUN",s-1,t,n);continue}let c=r&(1<<8-a-1)-1;for(let l=0;l<a;l++){let h=t[s];if((h&192)!=128){s+=e("MISSING_CONTINUE",s,t,n),c=null;break}c=c<<6|h&63,s++}if(c!==null){if(c>1114111){s+=e("OUT_OF_RANGE",s-1-a,t,n,c);continue}if(c>=55296&&c<=57343){s+=e("UTF16_SURROGATE",s-1-a,t,n,c);continue}if(c<=o){s+=e("OVERLONG",s-1-a,t,n,c);continue}n.push(c)}}return n}function ds(i,e){V(typeof i=="string","invalid string value","str",i);let t=[];for(let n=0;n<i.length;n++){const s=i.charCodeAt(n);if(s<128)t.push(s);else if(s<2048)t.push(s>>6|192),t.push(s&63|128);else if((s&64512)==55296){n++;const r=i.charCodeAt(n);V(n<i.length&&(r&64512)===56320,"invalid surrogate pair","str",i);const a=65536+((s&1023)<<10)+(r&1023);t.push(a>>18|240),t.push(a>>12&63|128),t.push(a>>6&63|128),t.push(a&63|128)}else t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128)}return new Uint8Array(t)}function lF(i){return i.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10&1023)+55296,(e&1023)+56320))).join("")}function rh(i,e){return lF(cF(i,e))}function px(i){async function e(t,n){pe(n==null||!n.cancelled,"request cancelled before sending","CANCELLED");const s=t.url.split(":")[0].toLowerCase();pe(s==="http"||s==="https",`unsupported protocol ${s}`,"UNSUPPORTED_OPERATION",{info:{protocol:s},operation:"request"}),pe(s==="https"||!t.credentials||t.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let r=null;const a=new AbortController,o=setTimeout(()=>{r=Qt("request timeout","TIMEOUT"),a.abort()},t.timeout);n&&n.addListener(()=>{r=Qt("request cancelled","CANCELLED"),a.abort()});const c=Object.assign({},i,{method:t.method,headers:new Headers(Array.from(t)),body:t.body||void 0,signal:a.signal});let l;try{l=await fetch(t.url,c)}catch(f){throw clearTimeout(o),r||f}clearTimeout(o);const h={};l.headers.forEach((f,p)=>{h[p.toLowerCase()]=f});const u=await l.arrayBuffer(),d=u==null?null:new Uint8Array(u);return{statusCode:l.status,statusMessage:l.statusText,headers:h,body:d}}return e}const hF=12,uF=250;let Ax=px();const dF=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),fF=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let Df=!1;async function gx(i,e){try{const t=i.match(dF);if(!t)throw new Error("invalid data");return new js(200,"OK",{"content-type":t[1]||"text/plain"},t[2]?iF(t[3]):AF(t[3]))}catch{return new js(599,"BAD REQUEST (invalid data: URI)",{},null,new zi(i))}}function mx(i){async function e(t,n){try{const s=t.match(fF);if(!s)throw new Error("invalid link");return new zi(`${i}${s[2]}`)}catch{return new js(599,"BAD REQUEST (invalid IPFS URI)",{},null,new zi(t))}}return e}const ah={data:gx,ipfs:mx("https://gateway.ipfs.io/ipfs/")},xx=new WeakMap;class pF{#e;#t;constructor(e){this.#e=[],this.#t=!1,xx.set(e,()=>{if(!this.#t){this.#t=!0;for(const t of this.#e)setTimeout(()=>{t()},0);this.#e=[]}})}addListener(e){pe(!this.#t,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),this.#e.push(e)}get cancelled(){return this.#t}checkSignal(){pe(!this.cancelled,"cancelled","CANCELLED",{})}}function oh(i){if(i==null)throw new Error("missing signal; should not happen");return i.checkSignal(),i}class zi{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;#c;#h;#u;get url(){return this.#a}set url(e){this.#a=String(e)}get body(){return this.#r==null?null:new Uint8Array(this.#r)}set body(e){if(e==null)this.#r=void 0,this.#o=void 0;else if(typeof e=="string")this.#r=ds(e),this.#o="text/plain";else if(e instanceof Uint8Array)this.#r=e,this.#o="application/octet-stream";else if(typeof e=="object")this.#r=ds(JSON.stringify(e)),this.#o="application/json";else throw new Error("invalid body")}hasBody(){return this.#r!=null}get method(){return this.#i?this.#i:this.hasBody()?"POST":"GET"}set method(e){e==null&&(e=""),this.#i=String(e).toUpperCase()}get headers(){const e=Object.assign({},this.#n);return this.#f&&(e.authorization=`Basic ${sF(ds(this.#f))}`),this.allowGzip&&(e["accept-encoding"]="gzip"),e["content-type"]==null&&this.#o&&(e["content-type"]=this.#o),this.body&&(e["content-length"]=String(this.body.length)),e}getHeader(e){return this.headers[e.toLowerCase()]}setHeader(e,t){this.#n[String(e).toLowerCase()]=String(t)}clearHeaders(){this.#n={}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const s=t[n++];return{value:[s,e[s]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#f||null}setCredentials(e,t){V(!e.match(/:/),"invalid basic authentication username","username","[REDACTED]"),this.#f=`${e}:${t}`}get allowGzip(){return this.#t}set allowGzip(e){this.#t=!!e}get allowInsecureAuthentication(){return!!this.#e}set allowInsecureAuthentication(e){this.#e=!!e}get timeout(){return this.#s}set timeout(e){V(e>=0,"timeout must be non-zero","timeout",e),this.#s=e}get preflightFunc(){return this.#l||null}set preflightFunc(e){this.#l=e}get processFunc(){return this.#p||null}set processFunc(e){this.#p=e}get retryFunc(){return this.#A||null}set retryFunc(e){this.#A=e}get getUrlFunc(){return this.#u||Ax}set getUrlFunc(e){this.#u=e}constructor(e){this.#a=String(e),this.#e=!1,this.#t=!0,this.#n={},this.#i="",this.#s=3e5,this.#h={slotInterval:uF,maxAttempts:hF},this.#u=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#r?Ce(this.#r):"null"}>`}setThrottleParams(e){e.slotInterval!=null&&(this.#h.slotInterval=e.slotInterval),e.maxAttempts!=null&&(this.#h.maxAttempts=e.maxAttempts)}async#d(e,t,n,s,r){if(e>=this.#h.maxAttempts)return r.makeServerError("exceeded maximum retry limit");pe(bx()<=t,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:s}),n>0&&await gF(n);let a=this.clone();const o=(a.url.split(":")[0]||"").toLowerCase();if(o in ah){const h=await ah[o](a.url,oh(s.#c));if(h instanceof js){let u=h;if(this.processFunc){oh(s.#c);try{u=await this.processFunc(a,u)}catch(d){(d.throttle==null||typeof d.stall!="number")&&u.makeServerError("error in post-processing function",d).assertOk()}}return u}a=h}this.preflightFunc&&(a=await this.preflightFunc(a));const c=await this.getUrlFunc(a,oh(s.#c));let l=new js(c.statusCode,c.statusMessage,c.headers,c.body,s);if(l.statusCode===301||l.statusCode===302){try{const h=l.headers.location||"";return a.redirect(h).#d(e+1,t,0,s,l)}catch{}return l}else if(l.statusCode===429&&(this.retryFunc==null||await this.retryFunc(a,l,e))){const h=l.headers["retry-after"];let u=this.#h.slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return typeof h=="string"&&h.match(/^[1-9][0-9]*$/)&&(u=parseInt(h)),a.clone().#d(e+1,t,u,s,l)}if(this.processFunc){oh(s.#c);try{l=await this.processFunc(a,l)}catch(h){(h.throttle==null||typeof h.stall!="number")&&l.makeServerError("error in post-processing function",h).assertOk();let u=this.#h.slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return h.stall>=0&&(u=h.stall),a.clone().#d(e+1,t,u,s,l)}}return l}send(){return pe(this.#c==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),this.#c=new pF(this),this.#d(0,bx()+this.timeout,0,this,new js(0,"",{},null,this))}cancel(){pe(this.#c!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const e=xx.get(this);if(!e)throw new Error("missing signal; should not happen");e()}redirect(e){const t=this.url.split(":")[0].toLowerCase(),n=e.split(":")[0].toLowerCase();pe(this.method==="GET"&&(t!=="https"||n!=="http")&&e.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(e)})`});const s=new zi(e);return s.method="GET",s.allowGzip=this.allowGzip,s.timeout=this.timeout,s.#n=Object.assign({},this.#n),this.#r&&(s.#r=new Uint8Array(this.#r)),s.#o=this.#o,s}clone(){const e=new zi(this.url);return e.#i=this.#i,this.#r&&(e.#r=this.#r),e.#o=this.#o,e.#n=Object.assign({},this.#n),e.#f=this.#f,this.allowGzip&&(e.allowGzip=!0),e.timeout=this.timeout,this.allowInsecureAuthentication&&(e.allowInsecureAuthentication=!0),e.#l=this.#l,e.#p=this.#p,e.#A=this.#A,e.#h=Object.assign({},this.#h),e.#u=this.#u,e}static lockConfig(){Df=!0}static getGateway(e){return ah[e.toLowerCase()]||null}static registerGateway(e,t){if(e=e.toLowerCase(),e==="http"||e==="https")throw new Error(`cannot intercept ${e}; use registerGetUrl`);if(Df)throw new Error("gateways locked");ah[e]=t}static registerGetUrl(e){if(Df)throw new Error("gateways locked");Ax=e}static createGetUrlFunc(e){return px(e)}static createDataGateway(){return gx}static createIpfsGatewayFunc(e){return mx(e)}}class js{#e;#t;#n;#i;#s;#a;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#i?Ce(this.#i):"null"}>`}get statusCode(){return this.#e}get statusMessage(){return this.#t}get headers(){return Object.assign({},this.#n)}get body(){return this.#i==null?null:new Uint8Array(this.#i)}get bodyText(){try{return this.#i==null?"":rh(this.#i)}catch{pe(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch{pe(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const s=t[n++];return{value:[s,e[s]],done:!1}}return{value:void 0,done:!0}}}}constructor(e,t,n,s,r){this.#e=e,this.#t=t,this.#n=Object.keys(n).reduce((a,o)=>(a[o.toLowerCase()]=String(n[o]),a),{}),this.#i=s==null?null:new Uint8Array(s),this.#s=r||null,this.#a={message:""}}makeServerError(e,t){let n;e?n=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${e})`:(e=`${this.statusCode} ${this.statusMessage}`,n=`CLIENT ESCALATED SERVER ERROR (${e})`);const s=new js(599,n,this.headers,this.body,this.#s||void 0);return s.#a={message:e,error:t},s}throwThrottleError(e,t){t==null?t=-1:V(Number.isInteger(t)&&t>=0,"invalid stall timeout","stall",t);const n=new Error(e||"throttling requests");throw Ye(n,{stall:t,throttle:!0}),n}getHeader(e){return this.headers[e.toLowerCase()]}hasBody(){return this.#i!=null}get request(){return this.#s}ok(){return this.#a.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:e,error:t}=this.#a;e===""&&(e=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let s=null;try{this.#i&&(s=rh(this.#i))}catch{}pe(!1,e,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:t,info:{requestUrl:n,responseBody:s,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}function bx(){return new Date().getTime()}function AF(i){return ds(i.replace(/%([0-9a-f][0-9a-f])/gi,(e,t)=>String.fromCharCode(parseInt(t,16))))}function gF(i){return new Promise(e=>setTimeout(e,i))}function mF(i){let e=i.toString(16);for(;e.length<2;)e="0"+e;return"0x"+e}function Ex(i,e,t){let n=0;for(let s=0;s<t;s++)n=n*256+i[e+s];return n}function yx(i,e,t,n){const s=[];for(;t<e+1+n;){const r=_x(i,t);s.push(r.result),t+=r.consumed,pe(t<=e+1+n,"child data too short","BUFFER_OVERRUN",{buffer:i,length:n,offset:e})}return{consumed:1+n,result:s}}function _x(i,e){pe(i.length!==0,"data too short","BUFFER_OVERRUN",{buffer:i,length:0,offset:1});const t=n=>{pe(n<=i.length,"data short segment too short","BUFFER_OVERRUN",{buffer:i,length:i.length,offset:n})};if(i[e]>=248){const n=i[e]-247;t(e+1+n);const s=Ex(i,e+1,n);return t(e+1+n+s),yx(i,e,e+1+n,n+s)}else if(i[e]>=192){const n=i[e]-192;return t(e+1+n),yx(i,e,e+1,n)}else if(i[e]>=184){const n=i[e]-183;t(e+1+n);const s=Ex(i,e+1,n);t(e+1+n+s);const r=Ce(i.slice(e+1+n,e+1+n+s));return{consumed:1+n+s,result:r}}else if(i[e]>=128){const n=i[e]-128;t(e+1+n);const s=Ce(i.slice(e+1,e+1+n));return{consumed:1+n,result:s}}return{consumed:1,result:mF(i[e])}}function $o(i){const e=ut(i,"data"),t=_x(e,0);return V(t.consumed===e.length,"unexpected junk after rlp payload","data",i),t.result}function wx(i){const e=[];for(;i;)e.unshift(i&255),i>>=8;return e}function vx(i){if(Array.isArray(i)){let n=[];if(i.forEach(function(r){n=n.concat(vx(r))}),n.length<=55)return n.unshift(192+n.length),n;const s=wx(n.length);return s.unshift(247+s.length),s.concat(n)}const e=Array.prototype.slice.call(ut(i,"object"));if(e.length===1&&e[0]<=127)return e;if(e.length<=55)return e.unshift(128+e.length),e;const t=wx(e.length);return t.unshift(183+t.length),t.concat(e)}const Cx="0123456789abcdef";function fs(i){let e="0x";for(const t of vx(i))e+=Cx[t>>4],e+=Cx[t&15];return e}const Vn=32,Lf=new Uint8Array(Vn),xF=["then"],ch={},Ix=new WeakMap;function Cr(i){return Ix.get(i)}function Sx(i,e){Ix.set(i,e)}function ec(i,e){const t=new Error(`deferred error during ABI decoding triggered accessing ${i}`);throw t.error=e,t}function Pf(i,e,t){return i.indexOf(null)>=0?e.map((n,s)=>n instanceof ps?Pf(Cr(n),n,t):n):i.reduce((n,s,r)=>{let a=e.getValue(s);return s in n||(t&&a instanceof ps&&(a=Pf(Cr(a),a,t)),n[s]=a),n},{})}class ps extends Array{#e;constructor(...e){const t=e[0];let n=e[1],s=(e[2]||[]).slice(),r=!0;t!==ch&&(n=e,s=[],r=!1),super(n.length),n.forEach((c,l)=>{this[l]=c});const a=s.reduce((c,l)=>(typeof l=="string"&&c.set(l,(c.get(l)||0)+1),c),new Map);if(Sx(this,Object.freeze(n.map((c,l)=>{const h=s[l];return h!=null&&a.get(h)===1?h:null}))),this.#e=[],this.#e==null&&this.#e,!r)return;Object.freeze(this);const o=new Proxy(this,{get:(c,l,h)=>{if(typeof l=="string"){if(l.match(/^[0-9]+$/)){const d=dt(l,"%index");if(d<0||d>=this.length)throw new RangeError("out of result range");const f=c[d];return f instanceof Error&&ec(`index ${d}`,f),f}if(xF.indexOf(l)>=0)return Reflect.get(c,l,h);const u=c[l];if(u instanceof Function)return function(...d){return u.apply(this===h?c:this,d)};if(!(l in c))return c.getValue.apply(this===h?c:this,[l])}return Reflect.get(c,l,h)}});return Sx(o,Cr(this)),o}toArray(e){const t=[];return this.forEach((n,s)=>{n instanceof Error&&ec(`index ${s}`,n),e&&n instanceof ps&&(n=n.toArray(e)),t.push(n)}),t}toObject(e){const t=Cr(this);return t.reduce((n,s,r)=>(pe(s!=null,`value at index ${r} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),Pf(t,this,e)),{})}slice(e,t){e==null&&(e=0),e<0&&(e+=this.length,e<0&&(e=0)),t==null&&(t=this.length),t<0&&(t+=this.length,t<0&&(t=0)),t>this.length&&(t=this.length);const n=Cr(this),s=[],r=[];for(let a=e;a<t;a++)s.push(this[a]),r.push(n[a]);return new ps(ch,s,r)}filter(e,t){const n=Cr(this),s=[],r=[];for(let a=0;a<this.length;a++){const o=this[a];o instanceof Error&&ec(`index ${a}`,o),e.call(t,o,a,this)&&(s.push(o),r.push(n[a]))}return new ps(ch,s,r)}map(e,t){const n=[];for(let s=0;s<this.length;s++){const r=this[s];r instanceof Error&&ec(`index ${s}`,r),n.push(e.call(t,r,s,this))}return n}getValue(e){const t=Cr(this).indexOf(e);if(t===-1)return;const n=this[t];return n instanceof Error&&ec(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(e,t){return new ps(ch,e,t)}}function Mx(i){let e=rn(i);return pe(e.length<=Vn,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:Vn,offset:e.length}),e.length!==Vn&&(e=zn(Gt([Lf.slice(e.length%Vn),e]))),e}class As{name;type;localName;dynamic;constructor(e,t,n,s){Ye(this,{name:e,type:t,localName:n,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){V(!1,e,this.localName,t)}}class kf{#e;#t;constructor(){this.#e=[],this.#t=0}get data(){return Gt(this.#e)}get length(){return this.#t}#n(e){return this.#e.push(e),this.#t+=e.length,e.length}appendWriter(e){return this.#n(zn(e.data))}writeBytes(e){let t=zn(e);const n=t.length%Vn;return n&&(t=zn(Gt([t,Lf.slice(n)]))),this.#n(t)}writeValue(e){return this.#n(Mx(e))}writeUpdatableValue(){const e=this.#e.length;return this.#e.push(Lf),this.#t+=Vn,t=>{this.#e[e]=Mx(t)}}}class Uf{allowLoose;#e;#t;#n;#i;#s;constructor(e,t,n){Ye(this,{allowLoose:!!t}),this.#e=zn(e),this.#n=0,this.#i=null,this.#s=n??1024,this.#t=0}get data(){return Ce(this.#e)}get dataLength(){return this.#e.length}get consumed(){return this.#t}get bytes(){return new Uint8Array(this.#e)}#a(e){if(this.#i)return this.#i.#a(e);this.#n+=e,pe(this.#s<1||this.#n<=this.#s*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#s} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:zn(this.#e),offset:this.#t,length:e,info:{bytesRead:this.#n,dataLength:this.dataLength}})}#r(e,t,n){let s=Math.ceil(t/Vn)*Vn;return this.#t+s>this.#e.length&&(this.allowLoose&&n&&this.#t+t<=this.#e.length?s=t:pe(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:zn(this.#e),length:this.#e.length,offset:this.#t+s})),this.#e.slice(this.#t,this.#t+s)}subReader(e){const t=new Uf(this.#e.slice(this.#t+e),this.allowLoose,this.#s);return t.#i=this,t}readBytes(e,t){let n=this.#r(0,e,!!t);return this.#a(e),this.#t+=n.length,n.slice(0,e)}readValue(){return Nf(this.readBytes(Vn))}readIndex(){return tF(this.readBytes(Vn))}}function lh(i){if(!Number.isSafeInteger(i)||i<0)throw new Error(`Wrong positive integer: ${i}`)}function Of(i,...e){if(!(i instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(i.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${i.length}`)}function bF(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");lh(i.outputLen),lh(i.blockLen)}function Oa(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Bx(i,e){Of(i);const t=e.outputLen;if(i.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const Qf=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;const Tx=i=>i instanceof Uint8Array,EF=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Gf=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Vi=(i,e)=>i<<32-e|i>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function yF(i){if(typeof i!="string")throw new Error(`utf8ToBytes expected string, got ${typeof i}`);return new Uint8Array(new TextEncoder().encode(i))}function hh(i){if(typeof i=="string"&&(i=yF(i)),!Tx(i))throw new Error(`expected Uint8Array, got ${typeof i}`);return i}function _F(...i){const e=new Uint8Array(i.reduce((n,s)=>n+s.length,0));let t=0;return i.forEach(n=>{if(!Tx(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}class Hf{clone(){return this._cloneInto()}}function zf(i){const e=n=>i().update(hh(n)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function wF(i=32){if(Qf&&typeof Qf.getRandomValues=="function")return Qf.getRandomValues(new Uint8Array(i));throw new Error("crypto.getRandomValues must be defined")}class Rx extends Hf{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,bF(e);const n=hh(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,r=new Uint8Array(s);r.set(n.length>s?e.create().update(n).digest():n);for(let a=0;a<r.length;a++)r[a]^=54;this.iHash.update(r),this.oHash=e.create();for(let a=0;a<r.length;a++)r[a]^=106;this.oHash.update(r),r.fill(0)}update(e){return Oa(this),this.iHash.update(e),this}digestInto(e){Oa(this),Of(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:s,destroyed:r,blockLen:a,outputLen:o}=this;return e=e,e.finished=s,e.destroyed=r,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Fx=(i,e,t)=>new Rx(i,e).update(t).digest();Fx.create=(i,e)=>new Rx(i,e);function vF(i,e,t,n){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,n);const s=BigInt(32),r=BigInt(4294967295),a=Number(t>>s&r),o=Number(t&r),c=n?4:0,l=n?0:4;i.setUint32(e+c,a,n),i.setUint32(e+l,o,n)}class Nx extends Hf{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Gf(this.buffer)}update(e){Oa(this);const{view:t,buffer:n,blockLen:s}=this;e=hh(e);const r=e.length;for(let a=0;a<r;){const o=Math.min(s-this.pos,r-a);if(o===s){const c=Gf(e);for(;s<=r-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Oa(this),Bx(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(n,0),a=0);for(let u=a;u<s;u++)t[u]=0;vF(n,s-8,BigInt(this.length*8),r),this.process(n,0);const o=Gf(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)o.setUint32(4*u,h[u],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:a,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=a,s%t&&e.buffer.set(n),e}}const CF=(i,e,t)=>i&e^~i&t,IF=(i,e,t)=>i&e^i&t^e&t,SF=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xs=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ys=new Uint32Array(64);class MF extends Nx{constructor(){super(64,32,8,!1),this.A=Xs[0]|0,this.B=Xs[1]|0,this.C=Xs[2]|0,this.D=Xs[3]|0,this.E=Xs[4]|0,this.F=Xs[5]|0,this.G=Xs[6]|0,this.H=Xs[7]|0}get(){const{A:e,B:t,C:n,D:s,E:r,F:a,G:o,H:c}=this;return[e,t,n,s,r,a,o,c]}set(e,t,n,s,r,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=r|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ys[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Ys[u-15],f=Ys[u-2],p=Vi(d,7)^Vi(d,18)^d>>>3,m=Vi(f,17)^Vi(f,19)^f>>>10;Ys[u]=m+Ys[u-7]+p+Ys[u-16]|0}let{A:n,B:s,C:r,D:a,E:o,F:c,G:l,H:h}=this;for(let u=0;u<64;u++){const d=Vi(o,6)^Vi(o,11)^Vi(o,25),f=h+d+CF(o,c,l)+SF[u]+Ys[u]|0,m=(Vi(n,2)^Vi(n,13)^Vi(n,22))+IF(n,s,r)|0;h=l,l=c,c=o,o=a+f|0,a=r,r=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(n,s,r,a,o,c,l,h)}roundClean(){Ys.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Dx=zf(()=>new MF),uh=BigInt(2**32-1),Vf=BigInt(32);function Lx(i,e=!1){return e?{h:Number(i&uh),l:Number(i>>Vf&uh)}:{h:Number(i>>Vf&uh)|0,l:Number(i&uh)|0}}function Px(i,e=!1){let t=new Uint32Array(i.length),n=new Uint32Array(i.length);for(let s=0;s<i.length;s++){const{h:r,l:a}=Lx(i[s],e);[t[s],n[s]]=[r,a]}return[t,n]}const BF=(i,e)=>BigInt(i>>>0)<<Vf|BigInt(e>>>0),TF=(i,e,t)=>i>>>t,RF=(i,e,t)=>i<<32-t|e>>>t,FF=(i,e,t)=>i>>>t|e<<32-t,NF=(i,e,t)=>i<<32-t|e>>>t,DF=(i,e,t)=>i<<64-t|e>>>t-32,LF=(i,e,t)=>i>>>t-32|e<<64-t,PF=(i,e)=>e,kF=(i,e)=>i,kx=(i,e,t)=>i<<t|e>>>32-t,Ux=(i,e,t)=>e<<t|i>>>32-t,Ox=(i,e,t)=>e<<t-32|i>>>64-t,Qx=(i,e,t)=>i<<t-32|e>>>64-t;function UF(i,e,t,n){const s=(e>>>0)+(n>>>0);return{h:i+t+(s/2**32|0)|0,l:s|0}}const lt={fromBig:Lx,split:Px,toBig:BF,shrSH:TF,shrSL:RF,rotrSH:FF,rotrSL:NF,rotrBH:DF,rotrBL:LF,rotr32H:PF,rotr32L:kF,rotlSH:kx,rotlSL:Ux,rotlBH:Ox,rotlBL:Qx,add:UF,add3L:(i,e,t)=>(i>>>0)+(e>>>0)+(t>>>0),add3H:(i,e,t,n)=>e+t+n+(i/2**32|0)|0,add4L:(i,e,t,n)=>(i>>>0)+(e>>>0)+(t>>>0)+(n>>>0),add4H:(i,e,t,n,s)=>e+t+n+s+(i/2**32|0)|0,add5H:(i,e,t,n,s,r)=>e+t+n+s+r+(i/2**32|0)|0,add5L:(i,e,t,n,s)=>(i>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0)},[OF,QF]=lt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(i=>BigInt(i))),Js=new Uint32Array(80),Zs=new Uint32Array(80);class GF extends Nx{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:n,Bl:s,Ch:r,Cl:a,Dh:o,Dl:c,Eh:l,El:h,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g]}set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=r|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=l|0,this.El=h|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let x=0;x<16;x++,t+=4)Js[x]=e.getUint32(t),Zs[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){const E=Js[x-15]|0,S=Zs[x-15]|0,w=lt.rotrSH(E,S,1)^lt.rotrSH(E,S,8)^lt.shrSH(E,S,7),I=lt.rotrSL(E,S,1)^lt.rotrSL(E,S,8)^lt.shrSL(E,S,7),T=Js[x-2]|0,C=Zs[x-2]|0,v=lt.rotrSH(T,C,19)^lt.rotrBH(T,C,61)^lt.shrSH(T,C,6),F=lt.rotrSL(T,C,19)^lt.rotrBL(T,C,61)^lt.shrSL(T,C,6),K=lt.add4L(I,F,Zs[x-7],Zs[x-16]),q=lt.add4H(K,w,v,Js[x-7],Js[x-16]);Js[x]=q|0,Zs[x]=K|0}let{Ah:n,Al:s,Bh:r,Bl:a,Ch:o,Cl:c,Dh:l,Dl:h,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:g,Hh:A,Hl:_}=this;for(let x=0;x<80;x++){const E=lt.rotrSH(u,d,14)^lt.rotrSH(u,d,18)^lt.rotrBH(u,d,41),S=lt.rotrSL(u,d,14)^lt.rotrSL(u,d,18)^lt.rotrBL(u,d,41),w=u&f^~u&m,I=d&p^~d&g,T=lt.add5L(_,S,I,QF[x],Zs[x]),C=lt.add5H(T,A,E,w,OF[x],Js[x]),v=T|0,F=lt.rotrSH(n,s,28)^lt.rotrBH(n,s,34)^lt.rotrBH(n,s,39),K=lt.rotrSL(n,s,28)^lt.rotrBL(n,s,34)^lt.rotrBL(n,s,39),q=n&r^n&o^r&o,$=s&a^s&c^a&c;A=m|0,_=g|0,m=f|0,g=p|0,f=u|0,p=d|0,{h:u,l:d}=lt.add(l|0,h|0,C|0,v|0),l=o|0,h=c|0,o=r|0,c=a|0,r=n|0,a=s|0;const D=lt.add3L(v,K,$);n=lt.add3H(D,C,F,q),s=D|0}({h:n,l:s}=lt.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:r,l:a}=lt.add(this.Bh|0,this.Bl|0,r|0,a|0),{h:o,l:c}=lt.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:l,l:h}=lt.add(this.Dh|0,this.Dl|0,l|0,h|0),{h:u,l:d}=lt.add(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=lt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:g}=lt.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:A,l:_}=lt.add(this.Hh|0,this.Hl|0,A|0,_|0),this.set(n,s,r,a,o,c,l,h,u,d,f,p,m,g,A,_)}roundClean(){Js.fill(0),Zs.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const HF=zf(()=>new GF);function zF(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}const Gx=zF();Gx.crypto||Gx.msCrypto;function VF(i){switch(i){case"sha256":return Dx.create();case"sha512":return HF.create()}V(!1,"invalid hashing algorithm name","algorithm",i)}const[Hx,zx,Vx]=[[],[],[]],WF=BigInt(0),tc=BigInt(1),qF=BigInt(2),KF=BigInt(7),jF=BigInt(256),XF=BigInt(113);for(let i=0,e=tc,t=1,n=0;i<24;i++){[t,n]=[n,(2*t+3*n)%5],Hx.push(2*(5*n+t)),zx.push((i+1)*(i+2)/2%64);let s=WF;for(let r=0;r<7;r++)e=(e<<tc^(e>>KF)*XF)%jF,e&qF&&(s^=tc<<(tc<<BigInt(r))-tc);Vx.push(s)}const[YF,JF]=Px(Vx,!0),Wx=(i,e,t)=>t>32?Ox(i,e,t):kx(i,e,t),qx=(i,e,t)=>t>32?Qx(i,e,t):Ux(i,e,t);function ZF(i,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)t[a]=i[a]^i[a+10]^i[a+20]^i[a+30]^i[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,l=t[c],h=t[c+1],u=Wx(l,h,1)^t[o],d=qx(l,h,1)^t[o+1];for(let f=0;f<50;f+=10)i[a+f]^=u,i[a+f+1]^=d}let s=i[2],r=i[3];for(let a=0;a<24;a++){const o=zx[a],c=Wx(s,r,o),l=qx(s,r,o),h=Hx[a];s=i[h],r=i[h+1],i[h]=c,i[h+1]=l}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=i[a+o];for(let o=0;o<10;o++)i[a+o]^=~t[(o+2)%10]&t[(o+4)%10]}i[0]^=YF[n],i[1]^=JF[n]}t.fill(0)}class Wf extends Hf{constructor(e,t,n,s=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,lh(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=EF(this.state)}keccak(){ZF(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Oa(this);const{blockLen:t,state:n}=this;e=hh(e);const s=e.length;for(let r=0;r<s;){const a=Math.min(t-this.pos,s-r);for(let o=0;o<a;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Oa(this,!1),Of(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return lh(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Bx(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:a}=this;return e||(e=new Wf(t,n,s,a,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=a,e.destroyed=this.destroyed,e}}const $F=((i,e,t)=>zf(()=>new Wf(e,i,t)))(1,136,256/8);let Kx=!1;const jx=function(i){return $F(i)};let Xx=jx;function an(i){const e=ut(i,"data");return Ce(Xx(e))}an._=jx,an.lock=function(){Kx=!0},an.register=function(i){if(Kx)throw new TypeError("keccak256 is locked");Xx=i},Object.freeze(an);const Yx=function(i){return VF("sha256").update(i).digest()};let Jx=Yx,Zx=!1;function Qa(i){const e=ut(i,"data");return Ce(Jx(e))}Qa._=Yx,Qa.lock=function(){Zx=!0},Qa.register=function(i){if(Zx)throw new Error("sha256 is locked");Jx=i},Object.freeze(Qa),Object.freeze(Qa);BigInt(0);const eN=BigInt(1),tN=BigInt(2),dh=i=>i instanceof Uint8Array,nN=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Ga(i){if(!dh(i))throw new Error("Uint8Array expected");let e="";for(let t=0;t<i.length;t++)e+=nN[i[t]];return e}function qf(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return BigInt(i===""?"0":`0x${i}`)}function nc(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let n=0;n<t.length;n++){const s=n*2,r=i.slice(s,s+2),a=Number.parseInt(r,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[n]=a}return t}function Ir(i){return qf(Ga(i))}function Kf(i){if(!dh(i))throw new Error("Uint8Array expected");return qf(Ga(Uint8Array.from(i).reverse()))}function Ha(i,e){return nc(i.toString(16).padStart(e*2,"0"))}function jf(i,e){return Ha(i,e).reverse()}function Fi(i,e,t){let n;if(typeof e=="string")try{n=nc(e)}catch(r){throw new Error(`${i} must be valid hex string, got "${e}". Cause: ${r}`)}else if(dh(e))n=Uint8Array.from(e);else throw new Error(`${i} must be hex string or Uint8Array`);const s=n.length;if(typeof t=="number"&&s!==t)throw new Error(`${i} expected ${t} bytes, got ${s}`);return n}function ic(...i){const e=new Uint8Array(i.reduce((n,s)=>n+s.length,0));let t=0;return i.forEach(n=>{if(!dh(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}const Xf=i=>(tN<<BigInt(i-1))-eN,Yf=i=>new Uint8Array(i),$x=i=>Uint8Array.from(i);function eb(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Yf(i),s=Yf(i),r=0;const a=()=>{n.fill(1),s.fill(0),r=0},o=(...u)=>t(s,n,...u),c=(u=Yf())=>{s=o($x([0]),u),n=o(),u.length!==0&&(s=o($x([1]),u),n=o())},l=()=>{if(r++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){n=o();const f=n.slice();d.push(f),u+=n.length}return ic(...d)};return(u,d)=>{a(),c(u);let f;for(;!(f=d(l()));)c();return a(),f}}const iN={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||i instanceof Uint8Array,isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function sc(i,e,t={}){const n=(s,r,a)=>{const o=iN[r];if(typeof o!="function")throw new Error(`Invalid validator "${r}", expected function`);const c=i[s];if(!(a&&c===void 0)&&!o(c,i))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${r}`)};for(const[s,r]of Object.entries(e))n(s,r,!1);for(const[s,r]of Object.entries(t))n(s,r,!0);return i}const sN=Object.freeze(Object.defineProperty({__proto__:null,bitMask:Xf,bytesToHex:Ga,bytesToNumberBE:Ir,bytesToNumberLE:Kf,concatBytes:ic,createHmacDrbg:eb,ensureBytes:Fi,hexToBytes:nc,hexToNumber:qf,numberToBytesBE:Ha,numberToBytesLE:jf,validateObject:sc},Symbol.toStringTag,{value:"Module"}));const yn=BigInt(0),en=BigInt(1),Sr=BigInt(2),rN=BigInt(3),Jf=BigInt(4),tb=BigInt(5),nb=BigInt(8);BigInt(9),BigInt(16);function Xn(i,e){const t=i%e;return t>=yn?t:e+t}function aN(i,e,t){if(t<=yn||e<yn)throw new Error("Expected power/modulo > 0");if(t===en)return yn;let n=en;for(;e>yn;)e&en&&(n=n*i%t),i=i*i%t,e>>=en;return n}function pi(i,e,t){let n=i;for(;e-- >yn;)n*=n,n%=t;return n}function Zf(i,e){if(i===yn||e<=yn)throw new Error(`invert: expected positive integers, got n=${i} mod=${e}`);let t=Xn(i,e),n=e,s=yn,r=en;for(;t!==yn;){const o=n/t,c=n%t,l=s-r*o;n=t,t=c,s=r,r=l}if(n!==en)throw new Error("invert: does not exist");return Xn(s,e)}function oN(i){const e=(i-en)/Sr;let t,n,s;for(t=i-en,n=0;t%Sr===yn;t/=Sr,n++);for(s=Sr;s<i&&aN(s,e,i)!==i-en;s++);if(n===1){const a=(i+en)/Jf;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const r=(t+en)/Sr;return function(o,c){if(o.pow(c,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let l=n,h=o.pow(o.mul(o.ONE,s),t),u=o.pow(c,r),d=o.pow(c,t);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let f=1;for(let m=o.sqr(d);f<l&&!o.eql(m,o.ONE);f++)m=o.sqr(m);const p=o.pow(h,en<<BigInt(l-f-1));h=o.sqr(p),u=o.mul(u,p),d=o.mul(d,h),l=f}return u}}function cN(i){if(i%Jf===rN){const e=(i+en)/Jf;return function(n,s){const r=n.pow(s,e);if(!n.eql(n.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%nb===tb){const e=(i-tb)/nb;return function(n,s){const r=n.mul(s,Sr),a=n.pow(r,e),o=n.mul(s,a),c=n.mul(n.mul(o,Sr),a),l=n.mul(o,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),s))throw new Error("Cannot find square root");return l}}return oN(i)}const lN=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hN(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=lN.reduce((n,s)=>(n[s]="function",n),e);return sc(i,t)}function uN(i,e,t){if(t<yn)throw new Error("Expected power > 0");if(t===yn)return i.ONE;if(t===en)return e;let n=i.ONE,s=e;for(;t>yn;)t&en&&(n=i.mul(n,s)),s=i.sqr(s),t>>=en;return n}function dN(i,e){const t=new Array(e.length),n=e.reduce((r,a,o)=>i.is0(a)?r:(t[o]=r,i.mul(r,a)),i.ONE),s=i.inv(n);return e.reduceRight((r,a,o)=>i.is0(a)?r:(t[o]=i.mul(r,t[o]),i.mul(r,a)),s),t}function ib(i,e){const t=e!==void 0?e:i.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function fN(i,e,t=!1,n={}){if(i<=yn)throw new Error(`Expected Field ORDER > 0, got ${i}`);const{nBitLength:s,nByteLength:r}=ib(i,e);if(r>2048)throw new Error("Field lengths over 2048 bytes are not supported");const a=cN(i),o=Object.freeze({ORDER:i,BITS:s,BYTES:r,MASK:Xf(s),ZERO:yn,ONE:en,create:c=>Xn(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return yn<=c&&c<i},is0:c=>c===yn,isOdd:c=>(c&en)===en,neg:c=>Xn(-c,i),eql:(c,l)=>c===l,sqr:c=>Xn(c*c,i),add:(c,l)=>Xn(c+l,i),sub:(c,l)=>Xn(c-l,i),mul:(c,l)=>Xn(c*l,i),pow:(c,l)=>uN(o,c,l),div:(c,l)=>Xn(c*Zf(l,i),i),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Zf(c,i),sqrt:n.sqrt||(c=>a(o,c)),invertBatch:c=>dN(o,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?jf(c,r):Ha(c,r),fromBytes:c=>{if(c.length!==r)throw new Error(`Fp.fromBytes: expected ${r}, got ${c.length}`);return t?Kf(c):Ir(c)}});return Object.freeze(o)}function sb(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function rb(i){const e=sb(i);return e+Math.ceil(e/2)}function pN(i,e,t=!1){const n=i.length,s=sb(e),r=rb(e);if(n<16||n<r||n>1024)throw new Error(`expected ${r}-1024 bytes of input, got ${n}`);const a=t?Ir(i):Kf(i),o=Xn(a,e-en)+en;return t?jf(o,s):Ha(o,s)}const AN=BigInt(0),$f=BigInt(1);function gN(i,e){const t=(s,r)=>{const a=r.negate();return s?a:r},n=s=>{const r=Math.ceil(e/s)+1,a=2**(s-1);return{windows:r,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,r){let a=i.ZERO,o=s;for(;r>AN;)r&$f&&(a=a.add(o)),o=o.double(),r>>=$f;return a},precomputeWindow(s,r){const{windows:a,windowSize:o}=n(r),c=[];let l=s,h=l;for(let u=0;u<a;u++){h=l,c.push(h);for(let d=1;d<o;d++)h=h.add(l),c.push(h);l=h.double()}return c},wNAF(s,r,a){const{windows:o,windowSize:c}=n(s);let l=i.ZERO,h=i.BASE;const u=BigInt(2**s-1),d=2**s,f=BigInt(s);for(let p=0;p<o;p++){const m=p*c;let g=Number(a&u);a>>=f,g>c&&(g-=d,a+=$f);const A=m,_=m+Math.abs(g)-1,x=p%2!==0,E=g<0;g===0?h=h.add(t(x,r[A])):l=l.add(t(E,r[_]))}return{p:l,f:h}},wNAFCached(s,r,a,o){const c=s._WINDOW_SIZE||1;let l=r.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&r.set(s,o(l))),this.wNAF(c,l,a)}}}function ab(i){return hN(i.Fp),sc(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ib(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}function mN(i){const e=ab(i);sc(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:xN,hexToBytes:bN}=sN,Mr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(i){const{Err:e}=Mr;if(i.length<2||i[0]!==2)throw new e("Invalid signature integer tag");const t=i[1],n=i.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:xN(n),l:i.subarray(t+2)}},toSig(i){const{Err:e}=Mr,t=typeof i=="string"?bN(i):i;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");const{d:s,l:r}=Mr._parseInt(t.subarray(2)),{d:a,l:o}=Mr._parseInt(r);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:a}},hexFromSig(i){const e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{const h=l.toString(16);return h.length&1?`0${h}`:h},n=e(t(i.s)),s=e(t(i.r)),r=n.length/2,a=s.length/2,o=t(r),c=t(a);return`30${t(a+r+4)}02${c}${s}02${o}${n}`}},gs=BigInt(0),Ai=BigInt(1);BigInt(2);const ob=BigInt(3);BigInt(4);function EN(i){const e=mN(i),{Fp:t}=e,n=e.toBytes||((p,m,g)=>{const A=m.toAffine();return ic(Uint8Array.from([4]),t.toBytes(A.x),t.toBytes(A.y))}),s=e.fromBytes||(p=>{const m=p.subarray(1),g=t.fromBytes(m.subarray(0,t.BYTES)),A=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:g,y:A}});function r(p){const{a:m,b:g}=e,A=t.sqr(p),_=t.mul(A,p);return t.add(t.add(_,t.mul(p,m)),g)}if(!t.eql(t.sqr(e.Gy),r(e.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return typeof p=="bigint"&&gs<p&&p<e.n}function o(p){if(!a(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){const{allowedPrivateKeyLengths:m,nByteLength:g,wrapPrivateKey:A,n:_}=e;if(m&&typeof p!="bigint"){if(p instanceof Uint8Array&&(p=Ga(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(g*2,"0")}let x;try{x=typeof p=="bigint"?p:Ir(Fi("private key",p,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof p}`)}return A&&(x=Xn(x,_)),o(x),x}const l=new Map;function h(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,g,A){if(this.px=m,this.py=g,this.pz=A,m==null||!t.isValid(m))throw new Error("x required");if(g==null||!t.isValid(g))throw new Error("y required");if(A==null||!t.isValid(A))throw new Error("z required")}static fromAffine(m){const{x:g,y:A}=m||{};if(!m||!t.isValid(g)||!t.isValid(A))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");const _=x=>t.eql(x,t.ZERO);return _(g)&&_(A)?u.ZERO:new u(g,A,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const g=t.invertBatch(m.map(A=>A.pz));return m.map((A,_)=>A.toAffine(g[_])).map(u.fromAffine)}static fromHex(m){const g=u.fromAffine(s(Fi("pointHex",m)));return g.assertValidity(),g}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:m,y:g}=this.toAffine();if(!t.isValid(m)||!t.isValid(g))throw new Error("bad point: x or y not FE");const A=t.sqr(g),_=r(m);if(!t.eql(A,_))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){h(m);const{px:g,py:A,pz:_}=this,{px:x,py:E,pz:S}=m,w=t.eql(t.mul(g,S),t.mul(x,_)),I=t.eql(t.mul(A,S),t.mul(E,_));return w&&I}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:g}=e,A=t.mul(g,ob),{px:_,py:x,pz:E}=this;let S=t.ZERO,w=t.ZERO,I=t.ZERO,T=t.mul(_,_),C=t.mul(x,x),v=t.mul(E,E),F=t.mul(_,x);return F=t.add(F,F),I=t.mul(_,E),I=t.add(I,I),S=t.mul(m,I),w=t.mul(A,v),w=t.add(S,w),S=t.sub(C,w),w=t.add(C,w),w=t.mul(S,w),S=t.mul(F,S),I=t.mul(A,I),v=t.mul(m,v),F=t.sub(T,v),F=t.mul(m,F),F=t.add(F,I),I=t.add(T,T),T=t.add(I,T),T=t.add(T,v),T=t.mul(T,F),w=t.add(w,T),v=t.mul(x,E),v=t.add(v,v),T=t.mul(v,F),S=t.sub(S,T),I=t.mul(v,C),I=t.add(I,I),I=t.add(I,I),new u(S,w,I)}add(m){h(m);const{px:g,py:A,pz:_}=this,{px:x,py:E,pz:S}=m;let w=t.ZERO,I=t.ZERO,T=t.ZERO;const C=e.a,v=t.mul(e.b,ob);let F=t.mul(g,x),K=t.mul(A,E),q=t.mul(_,S),$=t.add(g,A),D=t.add(x,E);$=t.mul($,D),D=t.add(F,K),$=t.sub($,D),D=t.add(g,_);let O=t.add(x,S);return D=t.mul(D,O),O=t.add(F,q),D=t.sub(D,O),O=t.add(A,_),w=t.add(E,S),O=t.mul(O,w),w=t.add(K,q),O=t.sub(O,w),T=t.mul(C,D),w=t.mul(v,q),T=t.add(w,T),w=t.sub(K,T),T=t.add(K,T),I=t.mul(w,T),K=t.add(F,F),K=t.add(K,F),q=t.mul(C,q),D=t.mul(v,D),K=t.add(K,q),q=t.sub(F,q),q=t.mul(C,q),D=t.add(D,q),F=t.mul(K,D),I=t.add(I,F),F=t.mul(O,D),w=t.mul($,w),w=t.sub(w,F),F=t.mul($,K),T=t.mul(O,T),T=t.add(T,F),new u(w,I,T)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,g=>{const A=t.invertBatch(g.map(_=>_.pz));return g.map((_,x)=>_.toAffine(A[x])).map(u.fromAffine)})}multiplyUnsafe(m){const g=u.ZERO;if(m===gs)return g;if(o(m),m===Ai)return this;const{endo:A}=e;if(!A)return f.unsafeLadder(this,m);let{k1neg:_,k1:x,k2neg:E,k2:S}=A.splitScalar(m),w=g,I=g,T=this;for(;x>gs||S>gs;)x&Ai&&(w=w.add(T)),S&Ai&&(I=I.add(T)),T=T.double(),x>>=Ai,S>>=Ai;return _&&(w=w.negate()),E&&(I=I.negate()),I=new u(t.mul(I.px,A.beta),I.py,I.pz),w.add(I)}multiply(m){o(m);let g=m,A,_;const{endo:x}=e;if(x){const{k1neg:E,k1:S,k2neg:w,k2:I}=x.splitScalar(g);let{p:T,f:C}=this.wNAF(S),{p:v,f:F}=this.wNAF(I);T=f.constTimeNegate(E,T),v=f.constTimeNegate(w,v),v=new u(t.mul(v.px,x.beta),v.py,v.pz),A=T.add(v),_=C.add(F)}else{const{p:E,f:S}=this.wNAF(g);A=E,_=S}return u.normalizeZ([A,_])[0]}multiplyAndAddUnsafe(m,g,A){const _=u.BASE,x=(S,w)=>w===gs||w===Ai||!S.equals(_)?S.multiplyUnsafe(w):S.multiply(w),E=x(this,g).add(x(m,A));return E.is0()?void 0:E}toAffine(m){const{px:g,py:A,pz:_}=this,x=this.is0();m==null&&(m=x?t.ONE:t.inv(_));const E=t.mul(g,m),S=t.mul(A,m),w=t.mul(_,m);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(w,t.ONE))throw new Error("invZ was invalid");return{x:E,y:S}}isTorsionFree(){const{h:m,isTorsionFree:g}=e;if(m===Ai)return!0;if(g)return g(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:g}=e;return m===Ai?this:g?g(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return Ga(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,f=gN(u,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:r,isWithinCurveOrder:a}}function yN(i){const e=ab(i);return sc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function _N(i){const e=yN(i),{Fp:t,n}=e,s=t.BYTES+1,r=2*t.BYTES+1;function a(D){return gs<D&&D<t.ORDER}function o(D){return Xn(D,n)}function c(D){return Zf(D,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:d}=EN({...e,toBytes(D,O,Y){const Q=O.toAffine(),J=t.toBytes(Q.x),ee=ic;return Y?ee(Uint8Array.from([O.hasEvenY()?2:3]),J):ee(Uint8Array.from([4]),J,t.toBytes(Q.y))},fromBytes(D){const O=D.length,Y=D[0],Q=D.subarray(1);if(O===s&&(Y===2||Y===3)){const J=Ir(Q);if(!a(J))throw new Error("Point is not on curve");const ee=u(J);let ae=t.sqrt(ee);const _e=(ae&Ai)===Ai;return(Y&1)===1!==_e&&(ae=t.neg(ae)),{x:J,y:ae}}else if(O===r&&Y===4){const J=t.fromBytes(Q.subarray(0,t.BYTES)),ee=t.fromBytes(Q.subarray(t.BYTES,2*t.BYTES));return{x:J,y:ee}}else throw new Error(`Point of length ${O} was invalid. Expected ${s} compressed bytes or ${r} uncompressed bytes`)}}),f=D=>Ga(Ha(D,e.nByteLength));function p(D){const O=n>>Ai;return D>O}function m(D){return p(D)?o(-D):D}const g=(D,O,Y)=>Ir(D.slice(O,Y));class A{constructor(O,Y,Q){this.r=O,this.s=Y,this.recovery=Q,this.assertValidity()}static fromCompact(O){const Y=e.nByteLength;return O=Fi("compactSignature",O,Y*2),new A(g(O,0,Y),g(O,Y,2*Y))}static fromDER(O){const{r:Y,s:Q}=Mr.toSig(Fi("DER",O));return new A(Y,Q)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(O){return new A(this.r,this.s,O)}recoverPublicKey(O){const{r:Y,s:Q,recovery:J}=this,ee=I(Fi("msgHash",O));if(J==null||![0,1,2,3].includes(J))throw new Error("recovery id invalid");const ae=J===2||J===3?Y+e.n:Y;if(ae>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const _e=(J&1)===0?"02":"03",Me=l.fromHex(_e+f(ae)),se=c(ae),me=o(-ee*se),xe=o(Q*se),be=l.BASE.multiplyAndAddUnsafe(Me,me,xe);if(!be)throw new Error("point at infinify");return be.assertValidity(),be}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return nc(this.toDERHex())}toDERHex(){return Mr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return nc(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}const _={isValidPrivateKey(D){try{return h(D),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const D=rb(e.n);return pN(e.randomBytes(D),e.n)},precompute(D=8,O=l.BASE){return O._setWindowSize(D),O.multiply(BigInt(3)),O}};function x(D,O=!0){return l.fromPrivateKey(D).toRawBytes(O)}function E(D){const O=D instanceof Uint8Array,Y=typeof D=="string",Q=(O||Y)&&D.length;return O?Q===s||Q===r:Y?Q===2*s||Q===2*r:D instanceof l}function S(D,O,Y=!0){if(E(D))throw new Error("first arg must be private key");if(!E(O))throw new Error("second arg must be public key");return l.fromHex(O).multiply(h(D)).toRawBytes(Y)}const w=e.bits2int||function(D){const O=Ir(D),Y=D.length*8-e.nBitLength;return Y>0?O>>BigInt(Y):O},I=e.bits2int_modN||function(D){return o(w(D))},T=Xf(e.nBitLength);function C(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(gs<=D&&D<T))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ha(D,e.nByteLength)}function v(D,O,Y=F){if(["recovered","canonical"].some(et=>et in Y))throw new Error("sign() legacy options not supported");const{hash:Q,randomBytes:J}=e;let{lowS:ee,prehash:ae,extraEntropy:_e}=Y;ee==null&&(ee=!0),D=Fi("msgHash",D),ae&&(D=Fi("prehashed msgHash",Q(D)));const Me=I(D),se=h(O),me=[C(se),C(Me)];if(_e!=null){const et=_e===!0?J(t.BYTES):_e;me.push(Fi("extraEntropy",et))}const xe=ic(...me),be=Me;function Ue(et){const He=w(et);if(!d(He))return;const Mt=c(He),ft=l.BASE.multiply(He).toAffine(),$e=o(ft.x);if($e===gs)return;const H=o(Mt*o(be+$e*se));if(H===gs)return;let wn=(ft.x===$e?0:2)|Number(ft.y&Ai),pt=H;return ee&&p(H)&&(pt=m(H),wn^=1),new A($e,pt,wn)}return{seed:xe,k2sig:Ue}}const F={lowS:e.lowS,prehash:!1},K={lowS:e.lowS,prehash:!1};function q(D,O,Y=F){const{seed:Q,k2sig:J}=v(D,O,Y),ee=e;return eb(ee.hash.outputLen,ee.nByteLength,ee.hmac)(Q,J)}l.BASE._setWindowSize(8);function $(D,O,Y,Q=K){const J=D;if(O=Fi("msgHash",O),Y=Fi("publicKey",Y),"strict"in Q)throw new Error("options.strict was renamed to lowS");const{lowS:ee,prehash:ae}=Q;let _e,Me;try{if(typeof J=="string"||J instanceof Uint8Array)try{_e=A.fromDER(J)}catch(ft){if(!(ft instanceof Mr.Err))throw ft;_e=A.fromCompact(J)}else if(typeof J=="object"&&typeof J.r=="bigint"&&typeof J.s=="bigint"){const{r:ft,s:$e}=J;_e=new A(ft,$e)}else throw new Error("PARSE");Me=l.fromHex(Y)}catch(ft){if(ft.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(ee&&_e.hasHighS())return!1;ae&&(O=e.hash(O));const{r:se,s:me}=_e,xe=I(O),be=c(me),Ue=o(xe*be),et=o(se*be),He=l.BASE.multiplyAndAddUnsafe(Me,Ue,et)?.toAffine();return He?o(He.x)===se:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:q,verify:$,ProjectivePoint:l,Signature:A,utils:_}}function wN(i){return{hash:i,hmac:(e,...t)=>Fx(i,e,_F(...t)),randomBytes:wF}}function vN(i,e){const t=n=>_N({...i,...wN(n)});return Object.freeze({...t(e),create:t})}const cb=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),lb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),CN=BigInt(1),ep=BigInt(2),hb=(i,e)=>(i+e/ep)/e;function IN(i){const e=cb,t=BigInt(3),n=BigInt(6),s=BigInt(11),r=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),l=i*i*i%e,h=l*l*i%e,u=pi(h,t,e)*h%e,d=pi(u,t,e)*h%e,f=pi(d,ep,e)*l%e,p=pi(f,s,e)*f%e,m=pi(p,r,e)*p%e,g=pi(m,o,e)*m%e,A=pi(g,c,e)*g%e,_=pi(A,o,e)*m%e,x=pi(_,t,e)*h%e,E=pi(x,a,e)*p%e,S=pi(E,n,e)*l%e,w=pi(S,ep,e);if(!tp.eql(tp.sqr(w),i))throw new Error("Cannot find square root");return w}const tp=fN(cb,void 0,void 0,{sqrt:IN}),$s=vN({a:BigInt(0),b:BigInt(7),Fp:tp,n:lb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:i=>{const e=lb,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-CN*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),r=t,a=BigInt("0x100000000000000000000000000000000"),o=hb(r*i,e),c=hb(-n*i,e);let l=Xn(i-o*t-c*s,e),h=Xn(-o*n-c*r,e);const u=l>a,d=h>a;if(u&&(l=e-l),d&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+i);return{k1neg:u,k1:l,k2neg:d,k2:h}}}},Dx);BigInt(0),$s.ProjectivePoint;const rc="0x0000000000000000000000000000000000000000",ub="0x0000000000000000000000000000000000000000000000000000000000000000",db=BigInt(0),fb=BigInt(1),np=BigInt(2),pb=BigInt(27),Ab=BigInt(28),fh=BigInt(35),gb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),SN=gb/np,MN=Symbol.for("nodejs.util.inspect.custom"),Br={};function ip(i){return us(rn(i),32)}class Vt{#e;#t;#n;#i;get r(){return this.#e}set r(e){V(ka(e)===32,"invalid r","value",e),this.#e=Ce(e)}get s(){return V(parseInt(this.#t.substring(0,3))<8,"non-canonical s; use ._s","s",this.#t),this.#t}set s(e){V(ka(e)===32,"invalid s","value",e),this.#t=Ce(e)}get _s(){return this.#t}isValid(){return BigInt(this.#t)<=SN}get v(){return this.#n}set v(e){const t=dt(e,"value");V(t===27||t===28,"invalid v","v",e),this.#n=t}get networkV(){return this.#i}get legacyChainId(){const e=this.networkV;return e==null?null:Vt.getChainId(e)}get yParity(){return this.v===27?0:1}get yParityAndS(){const e=ut(this.s);return this.yParity&&(e[0]|=128),Ce(e)}get compactSerialized(){return Gt([this.r,this.yParityAndS])}get serialized(){return Gt([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(e,t,n,s){ih(e,Br,"Signature"),this.#e=t,this.#t=n,this.#n=s,this.#i=null}getCanonical(){if(this.isValid())return this;const e=gb-BigInt(this._s),t=55-this.v,n=new Vt(Br,this.r,ip(e),t);return this.networkV&&(n.#i=this.networkV),n}clone(){const e=new Vt(Br,this.r,this._s,this.v);return this.networkV&&(e.#i=this.networkV),e}toJSON(){const e=this.networkV;return{_type:"signature",networkV:e!=null?e.toString():null,r:this.r,s:this._s,v:this.v}}[MN](){return this.toString()}toString(){return this.isValid()?`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }`:`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`}static getChainId(e){const t=Ne(e,"v");return t==pb||t==Ab?db:(V(t>=fh,"invalid EIP-155 v","v",e),(t-fh)/np)}static getChainIdV(e,t){return Ne(e)*np+BigInt(35+t-27)}static getNormalizedV(e){const t=Ne(e);return t===db||t===pb?27:t===fb||t===Ab?28:(V(t>=fh,"invalid v","v",e),t&fb?27:28)}static from(e){function t(l,h){V(l,h,"signature",e)}if(e==null)return new Vt(Br,ub,ub,27);if(typeof e=="string"){const l=ut(e,"signature");if(l.length===64){const h=Ce(l.slice(0,32)),u=l.slice(32,64),d=u[0]&128?28:27;return u[0]&=127,new Vt(Br,h,Ce(u),d)}if(l.length===65){const h=Ce(l.slice(0,32)),u=Ce(l.slice(32,64)),d=Vt.getNormalizedV(l[64]);return new Vt(Br,h,u,d)}t(!1,"invalid raw signature length")}if(e instanceof Vt)return e.clone();const n=e.r;t(n!=null,"missing r");const s=ip(n),r=(function(l,h){if(l!=null)return ip(l);if(h!=null){t(Pt(h,32),"invalid yParityAndS");const u=ut(h);return u[0]&=127,Ce(u)}t(!1,"missing s")})(e.s,e.yParityAndS),{networkV:a,v:o}=(function(l,h,u){if(l!=null){const d=Ne(l);return{networkV:d>=fh?d:void 0,v:Vt.getNormalizedV(d)}}if(h!=null)return t(Pt(h,32),"invalid yParityAndS"),{v:ut(h)[0]&128?28:27};if(u!=null){switch(dt(u,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}t(!1,"invalid yParity")}t(!1,"missing v")})(e.v,e.yParityAndS,e.yParity),c=new Vt(Br,s,r,o);return a&&(c.#i=a),t(e.yParity==null||dt(e.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),t(e.yParityAndS==null||e.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}}class ms{#e;constructor(e){V(ka(e)===32,"invalid private key","privateKey","[REDACTED]"),this.#e=Ce(e)}get privateKey(){return this.#e}get publicKey(){return ms.computePublicKey(this.#e)}get compressedPublicKey(){return ms.computePublicKey(this.#e,!0)}sign(e){V(ka(e)===32,"invalid digest length","digest",e);const t=$s.sign(zn(e),zn(this.#e),{lowS:!0});return Vt.from({r:Ks(t.r,32),s:Ks(t.s,32),v:t.recovery?28:27})}computeSharedSecret(e){const t=ms.computePublicKey(e);return Ce($s.getSharedSecret(zn(this.#e),ut(t),!1))}static computePublicKey(e,t){let n=ut(e,"key");if(n.length===32){const r=$s.getPublicKey(n,!!t);return Ce(r)}if(n.length===64){const r=new Uint8Array(65);r[0]=4,r.set(n,1),n=r}const s=$s.ProjectivePoint.fromHex(n);return Ce(s.toRawBytes(t))}static recoverPublicKey(e,t){V(ka(e)===32,"invalid digest length","digest",e);const n=Vt.from(t);let s=$s.Signature.fromCompact(zn(Gt([n.r,n.s])));s=s.addRecoveryBit(n.yParity);const r=s.recoverPublicKey(zn(e));return V(r!=null,"invalid signature for digest","signature",t),"0x"+r.toHex(!1)}static addPoints(e,t,n){const s=$s.ProjectivePoint.fromHex(ms.computePublicKey(e).substring(2)),r=$s.ProjectivePoint.fromHex(ms.computePublicKey(t).substring(2));return"0x"+s.add(r).toHex(!!n)}}const BN=BigInt(0),TN=BigInt(36);function mb(i){i=i.toLowerCase();const e=i.substring(2).split(""),t=new Uint8Array(40);for(let s=0;s<40;s++)t[s]=e[s].charCodeAt(0);const n=ut(an(t));for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(n[s>>1]&15)>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const sp={};for(let i=0;i<10;i++)sp[String(i)]=String(i);for(let i=0;i<26;i++)sp[String.fromCharCode(65+i)]=String(10+i);const xb=15;function RN(i){i=i.toUpperCase(),i=i.substring(4)+i.substring(0,2)+"00";let e=i.split("").map(n=>sp[n]).join("");for(;e.length>=xb;){let n=e.substring(0,xb);e=parseInt(n,10)%97+e.substring(n.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}const FN=(function(){const i={};for(let e=0;e<36;e++){const t="0123456789abcdefghijklmnopqrstuvwxyz"[e];i[t]=BigInt(e)}return i})();function NN(i){i=i.toLowerCase();let e=BN;for(let t=0;t<i.length;t++)e=e*TN+FN[i[t]];return e}function St(i){if(V(typeof i=="string","invalid address","address",i),i.match(/^(0x)?[0-9a-fA-F]{40}$/)){i.startsWith("0x")||(i="0x"+i);const e=mb(i);return V(!i.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===i,"bad address checksum","address",i),e}if(i.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){V(i.substring(2,4)===RN(i),"bad icap checksum","address",i);let e=NN(i.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return mb("0x"+e)}V(!1,"invalid address","address",i)}function DN(i){const e=St(i.from);let n=Ne(i.nonce,"tx.nonce").toString(16);return n==="0"?n="0x":n.length%2?n="0x0"+n:n="0x"+n,St(Kt(an(fs([e,n])),12))}function bb(i){return i&&typeof i.getAddress=="function"}async function rp(i,e){const t=await e;return(t==null||t==="0x0000000000000000000000000000000000000000")&&(pe(typeof i!="string","unconfigured name","UNCONFIGURED_NAME",{value:i}),V(!1,"invalid AddressLike value; did not resolve to a value address","target",i)),St(t)}function Wn(i,e){if(typeof i=="string")return i.match(/^0x[0-9a-f]{40}$/i)?St(i):(pe(e!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),rp(i,e.resolveName(i)));if(bb(i))return rp(i,i.getAddress());if(i&&typeof i.then=="function")return rp(i,i);V(!1,"unsupported addressable value","target",i)}const xs={};function Be(i,e){let t=!1;return e<0&&(t=!0,e*=-1),new jt(xs,`${t?"":"u"}int${e}`,i,{signed:t,width:e})}function wt(i,e){return new jt(xs,`bytes${e||""}`,i,{size:e})}const Eb=Symbol.for("_ethers_typed");class jt{type;value;#e;_typedSymbol;constructor(e,t,n,s){s==null&&(s=null),ih(xs,e,"Typed"),Ye(this,{_typedSymbol:Eb,type:t,value:n}),this.#e=s,this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return this.#e}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return this.#e===!0?-1:this.#e===!1?this.value.length:null}static from(e,t){return new jt(xs,e,t)}static uint8(e){return Be(e,8)}static uint16(e){return Be(e,16)}static uint24(e){return Be(e,24)}static uint32(e){return Be(e,32)}static uint40(e){return Be(e,40)}static uint48(e){return Be(e,48)}static uint56(e){return Be(e,56)}static uint64(e){return Be(e,64)}static uint72(e){return Be(e,72)}static uint80(e){return Be(e,80)}static uint88(e){return Be(e,88)}static uint96(e){return Be(e,96)}static uint104(e){return Be(e,104)}static uint112(e){return Be(e,112)}static uint120(e){return Be(e,120)}static uint128(e){return Be(e,128)}static uint136(e){return Be(e,136)}static uint144(e){return Be(e,144)}static uint152(e){return Be(e,152)}static uint160(e){return Be(e,160)}static uint168(e){return Be(e,168)}static uint176(e){return Be(e,176)}static uint184(e){return Be(e,184)}static uint192(e){return Be(e,192)}static uint200(e){return Be(e,200)}static uint208(e){return Be(e,208)}static uint216(e){return Be(e,216)}static uint224(e){return Be(e,224)}static uint232(e){return Be(e,232)}static uint240(e){return Be(e,240)}static uint248(e){return Be(e,248)}static uint256(e){return Be(e,256)}static uint(e){return Be(e,256)}static int8(e){return Be(e,-8)}static int16(e){return Be(e,-16)}static int24(e){return Be(e,-24)}static int32(e){return Be(e,-32)}static int40(e){return Be(e,-40)}static int48(e){return Be(e,-48)}static int56(e){return Be(e,-56)}static int64(e){return Be(e,-64)}static int72(e){return Be(e,-72)}static int80(e){return Be(e,-80)}static int88(e){return Be(e,-88)}static int96(e){return Be(e,-96)}static int104(e){return Be(e,-104)}static int112(e){return Be(e,-112)}static int120(e){return Be(e,-120)}static int128(e){return Be(e,-128)}static int136(e){return Be(e,-136)}static int144(e){return Be(e,-144)}static int152(e){return Be(e,-152)}static int160(e){return Be(e,-160)}static int168(e){return Be(e,-168)}static int176(e){return Be(e,-176)}static int184(e){return Be(e,-184)}static int192(e){return Be(e,-192)}static int200(e){return Be(e,-200)}static int208(e){return Be(e,-208)}static int216(e){return Be(e,-216)}static int224(e){return Be(e,-224)}static int232(e){return Be(e,-232)}static int240(e){return Be(e,-240)}static int248(e){return Be(e,-248)}static int256(e){return Be(e,-256)}static int(e){return Be(e,-256)}static bytes1(e){return wt(e,1)}static bytes2(e){return wt(e,2)}static bytes3(e){return wt(e,3)}static bytes4(e){return wt(e,4)}static bytes5(e){return wt(e,5)}static bytes6(e){return wt(e,6)}static bytes7(e){return wt(e,7)}static bytes8(e){return wt(e,8)}static bytes9(e){return wt(e,9)}static bytes10(e){return wt(e,10)}static bytes11(e){return wt(e,11)}static bytes12(e){return wt(e,12)}static bytes13(e){return wt(e,13)}static bytes14(e){return wt(e,14)}static bytes15(e){return wt(e,15)}static bytes16(e){return wt(e,16)}static bytes17(e){return wt(e,17)}static bytes18(e){return wt(e,18)}static bytes19(e){return wt(e,19)}static bytes20(e){return wt(e,20)}static bytes21(e){return wt(e,21)}static bytes22(e){return wt(e,22)}static bytes23(e){return wt(e,23)}static bytes24(e){return wt(e,24)}static bytes25(e){return wt(e,25)}static bytes26(e){return wt(e,26)}static bytes27(e){return wt(e,27)}static bytes28(e){return wt(e,28)}static bytes29(e){return wt(e,29)}static bytes30(e){return wt(e,30)}static bytes31(e){return wt(e,31)}static bytes32(e){return wt(e,32)}static address(e){return new jt(xs,"address",e)}static bool(e){return new jt(xs,"bool",!!e)}static bytes(e){return new jt(xs,"bytes",e)}static string(e){return new jt(xs,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new jt(xs,"overrides",Object.assign({},e))}static isTyped(e){return e&&typeof e=="object"&&"_typedSymbol"in e&&e._typedSymbol===Eb}static dereference(e,t){if(jt.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class LN extends As{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=jt.dereference(t,"string");try{n=St(n)}catch(s){return this._throwError(s.message,t)}return e.writeValue(n)}decode(e){return St(Ks(e.readValue(),20))}}class PN extends As{coder;constructor(e){super(e.name,e.type,"_",e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function yb(i,e,t){let n=[];if(Array.isArray(t))n=t;else if(t&&typeof t=="object"){let c={};n=e.map(l=>{const h=l.localName;return pe(h,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:t}),pe(!c[h],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:t}),c[h]=!0,t[h]})}else V(!1,"invalid tuple value","tuple",t);V(e.length===n.length,"types/value length mismatch","tuple",t);let s=new kf,r=new kf,a=[];e.forEach((c,l)=>{let h=n[l];if(c.dynamic){let u=r.length;c.encode(r,h);let d=s.writeUpdatableValue();a.push(f=>{d(f+u)})}else c.encode(s,h)}),a.forEach(c=>{c(s.length)});let o=i.appendWriter(s);return o+=i.appendWriter(r),o}function _b(i,e){let t=[],n=[],s=i.subReader(0);return e.forEach(r=>{let a=null;if(r.dynamic){let o=i.readIndex(),c=s.subReader(o);try{a=r.decode(c)}catch(l){if(Tn(l,"BUFFER_OVERRUN"))throw l;a=l,a.baseType=r.name,a.name=r.localName,a.type=r.type}}else try{a=r.decode(i)}catch(o){if(Tn(o,"BUFFER_OVERRUN"))throw o;a=o,a.baseType=r.name,a.name=r.localName,a.type=r.type}if(a==null)throw new Error("investigate");t.push(a),n.push(r.localName||null)}),ps.fromItems(t,n)}class kN extends As{coder;length;constructor(e,t,n){const s=e.type+"["+(t>=0?t:"")+"]",r=t===-1||e.dynamic;super("array",s,n,r),Ye(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=jt.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let s=this.length;s===-1&&(s=n.length,e.writeValue(n.length)),sx(n.length,s,"coder array"+(this.localName?" "+this.localName:""));let r=[];for(let a=0;a<n.length;a++)r.push(this.coder);return yb(e,r,n)}decode(e){let t=this.length;t===-1&&(t=e.readIndex(),pe(t*Vn<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*Vn,length:e.dataLength}));let n=[];for(let s=0;s<t;s++)n.push(new PN(this.coder));return _b(e,n)}}class UN extends As{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=jt.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class wb extends As{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=zn(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class ON extends wb{constructor(e){super("bytes",e)}decode(e){return Ce(super.decode(e))}}class QN extends As{size;constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),Ye(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(e,t){let n=zn(jt.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return Ce(e.readBytes(this.size))}}const GN=new Uint8Array([]);class HN extends As{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return t!=null&&this._throwError("not null",t),e.writeBytes(GN)}decode(e){return e.readBytes(0),null}}const zN=BigInt(0),VN=BigInt(1),WN=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class qN extends As{size;signed;constructor(e,t,n){const s=(t?"int":"uint")+e*8;super(s,s,n,!1),Ye(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=Ne(jt.dereference(t,this.type)),s=Zo(WN,Vn*8);if(this.signed){let r=Zo(s,this.size*8-1);(n>r||n<-(r+VN))&&this._throwError("value out-of-bounds",t),n=cx(n,8*Vn)}else(n<zN||n>Zo(s,this.size*8))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=Zo(e.readValue(),this.size*8);return this.signed&&(t=eF(t,this.size*8)),t}}class KN extends wb{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,ds(jt.dereference(t,"string")))}decode(e){return rh(super.decode(e))}}class ph extends As{coders;constructor(e,t){let n=!1;const s=[];e.forEach(a=>{a.dynamic&&(n=!0),s.push(a.type)});const r="tuple("+s.join(",")+")";super("tuple",r,t,n),Ye(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach(n=>{e.push(n.defaultValue())});const t=this.coders.reduce((n,s)=>{const r=s.localName;return r&&(n[r]||(n[r]=0),n[r]++),n},{});return this.coders.forEach((n,s)=>{let r=n.localName;!r||t[r]!==1||(r==="length"&&(r="_length"),e[r]==null&&(e[r]=e[s]))}),Object.freeze(e)}encode(e,t){const n=jt.dereference(t,"tuple");return yb(e,this.coders,n)}decode(e){return _b(e,this.coders)}}function ap(i,e){return{address:St(i),storageKeys:e.map((t,n)=>(V(Pt(t,32),"invalid slot",`storageKeys[${n}]`,t),t.toLowerCase()))}}function Tr(i){if(Array.isArray(i))return i.map((t,n)=>Array.isArray(t)?(V(t.length===2,"invalid slot set",`value[${n}]`,t),ap(t[0],t[1])):(V(t!=null&&typeof t=="object","invalid address-slot set","value",i),ap(t.address,t.storageKeys)));V(i!=null&&typeof i=="object","invalid access list","value",i);const e=Object.keys(i).map(t=>{const n=i[t].reduce((s,r)=>(s[r]=!0,s),{});return ap(t,Object.keys(n).sort())});return e.sort((t,n)=>t.address.localeCompare(n.address)),e}function vb(i){return{address:St(i.address),nonce:Ne(i.nonce!=null?i.nonce:0),chainId:Ne(i.chainId!=null?i.chainId:0),signature:Vt.from(i.signature)}}function jN(i){let e;return typeof i=="string"?e=ms.computePublicKey(i,!1):e=i.publicKey,St(an("0x"+e.substring(4)).substring(26))}function XN(i,e){return jN(ms.recoverPublicKey(i,e))}const _n=BigInt(0),YN=BigInt(2),JN=BigInt(27),ZN=BigInt(28),$N=BigInt(35),eD=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),tD=Symbol.for("nodejs.util.inspect.custom"),op=4096*32,Ah=128;function nD(i){return{blobToKzgCommitment:n=>{if("computeBlobProof"in i){if("blobToKzgCommitment"in i&&typeof i.blobToKzgCommitment=="function")return ut(i.blobToKzgCommitment(Ce(n)))}else if("blobToKzgCommitment"in i&&typeof i.blobToKzgCommitment=="function")return ut(i.blobToKzgCommitment(n));if("blobToKZGCommitment"in i&&typeof i.blobToKZGCommitment=="function")return ut(i.blobToKZGCommitment(Ce(n)));V(!1,"unsupported KZG library","kzg",i)},computeBlobKzgProof:(n,s)=>{if("computeBlobProof"in i&&typeof i.computeBlobProof=="function")return ut(i.computeBlobProof(Ce(n),Ce(s)));if("computeBlobKzgProof"in i&&typeof i.computeBlobKzgProof=="function")return i.computeBlobKzgProof(n,s);if("computeBlobKZGProof"in i&&typeof i.computeBlobKZGProof=="function")return ut(i.computeBlobKZGProof(Ce(n),Ce(s)));V(!1,"unsupported KZG library","kzg",i)}}}function Cb(i,e){let t=i.toString(16);for(;t.length<2;)t="0"+t;return t+=Qa(e).substring(4),"0x"+t}function za(i){return i==="0x"?null:St(i)}function gh(i,e){try{return Tr(i)}catch(t){V(!1,t.message,e,i)}}function iD(i,e){try{if(!Array.isArray(i))throw new Error("authorizationList: invalid array");const t=[];for(let n=0;n<i.length;n++){const s=i[n];if(!Array.isArray(s))throw new Error(`authorization[${n}]: invalid array`);if(s.length!==6)throw new Error(`authorization[${n}]: wrong length`);if(!s[1])throw new Error(`authorization[${n}]: null address`);t.push({address:za(s[1]),nonce:Nt(s[2],"nonce"),chainId:Nt(s[0],"chainId"),signature:Vt.from({yParity:Rr(s[3],"yParity"),r:us(s[4],32),s:us(s[5],32)})})}return t}catch(t){V(!1,t.message,e,i)}}function Rr(i,e){return i==="0x"?0:dt(i,e)}function Nt(i,e){if(i==="0x")return _n;const t=Ne(i,e);return V(t<=eD,"value exceeds uint size",e,t),t}function xt(i,e){const t=Ne(i,"value"),n=rn(t);return V(n.length<=32,"value too large",`tx.${e}`,t),n}function mh(i){return Tr(i).map(e=>[e.address,e.storageKeys])}function sD(i){return i.map(e=>[xt(e.chainId,"chainId"),e.address,xt(e.nonce,"nonce"),xt(e.signature.yParity,"yParity"),rn(e.signature.r),rn(e.signature._s)])}function rD(i,e){V(Array.isArray(i),`invalid ${e}`,"value",i);for(let t=0;t<i.length;t++)V(Pt(i[t],32),"invalid ${ param } hash",`value[${t}]`,i[t]);return i}function aD(i){const e=$o(i);V(Array.isArray(e)&&(e.length===9||e.length===6),"invalid field count for legacy transaction","data",i);const t={type:0,nonce:Rr(e[0],"nonce"),gasPrice:Nt(e[1],"gasPrice"),gasLimit:Nt(e[2],"gasLimit"),to:za(e[3]),value:Nt(e[4],"value"),data:Ce(e[5]),chainId:_n};if(e.length===6)return t;const n=Nt(e[6],"v"),s=Nt(e[7],"r"),r=Nt(e[8],"s");if(s===_n&&r===_n)t.chainId=n;else{let a=(n-$N)/YN;a<_n&&(a=_n),t.chainId=a,V(a!==_n||n===JN||n===ZN,"non-canonical legacy v","v",e[6]),t.signature=Vt.from({r:us(e[7],32),s:us(e[8],32),v:n})}return t}function oD(i,e){const t=[xt(i.nonce,"nonce"),xt(i.gasPrice||0,"gasPrice"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data];let n=_n;if(i.chainId!=_n)n=Ne(i.chainId,"tx.chainId"),V(!e||e.networkV==null||e.legacyChainId===n,"tx.chainId/sig.v mismatch","sig",e);else if(i.signature){const r=i.signature.legacyChainId;r!=null&&(n=r)}if(!e)return n!==_n&&(t.push(rn(n)),t.push("0x"),t.push("0x")),fs(t);let s=BigInt(27+e.yParity);return n!==_n?s=Vt.getChainIdV(n,e.v):BigInt(e.v)!==s&&V(!1,"tx.chainId/sig.v mismatch","sig",e),t.push(rn(s)),t.push(rn(e.r)),t.push(rn(e._s)),fs(t)}function xh(i,e){let t;try{if(t=Rr(e[0],"yParity"),t!==0&&t!==1)throw new Error("bad yParity")}catch{V(!1,"invalid yParity","yParity",e[0])}const n=us(e[1],32),s=us(e[2],32),r=Vt.from({r:n,s,yParity:t});i.signature=r}function cD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===9||e.length===12),"invalid field count for transaction type: 2","data",Ce(i));const t={type:2,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList")};return e.length===9||xh(t,e.slice(9)),t}function lD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[])];return e&&(t.push(xt(e.yParity,"yParity")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x02",fs(t)])}function hD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===8||e.length===11),"invalid field count for transaction type: 1","data",Ce(i));const t={type:1,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),gasPrice:Nt(e[2],"gasPrice"),gasLimit:Nt(e[3],"gasLimit"),to:za(e[4]),value:Nt(e[5],"value"),data:Ce(e[6]),accessList:gh(e[7],"accessList")};return e.length===8||xh(t,e.slice(8)),t}function uD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.gasPrice||0,"gasPrice"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[])];return e&&(t.push(xt(e.yParity,"recoveryParam")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x01",fs(t)])}function dD(i){let e=$o(ut(i).slice(1)),t="3",n=null,s=null;if(e.length===4&&Array.isArray(e[0])){t="3 (network format)";const a=e[1],o=e[2],c=e[3];V(Array.isArray(a),"invalid network format: blobs not an array","fields[1]",a),V(Array.isArray(o),"invalid network format: commitments not an array","fields[2]",o),V(Array.isArray(c),"invalid network format: proofs not an array","fields[3]",c),V(a.length===o.length,"invalid network format: blobs/commitments length mismatch","fields",e),V(a.length===c.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let l=0;l<e[1].length;l++)s.push({data:a[l],commitment:o[l],proof:c[l]});e=e[0]}else if(e.length===5&&Array.isArray(e[0])){t="3 (EIP-7594 network format)",n=dt(e[1]);const a=e[2],o=e[3],c=e[4];V(n===1,`unsupported EIP-7594 network format version: ${n}`,"fields[1]",n),V(Array.isArray(a),"invalid EIP-7594 network format: blobs not an array","fields[2]",a),V(Array.isArray(o),"invalid EIP-7594 network format: commitments not an array","fields[3]",o),V(Array.isArray(c),"invalid EIP-7594 network format: proofs not an array","fields[4]",c),V(a.length===o.length,"invalid network format: blobs/commitments length mismatch","fields",e),V(a.length*Ah===c.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let l=0;l<a.length;l++){const h=[];for(let u=0;u<Ah;u++)h.push(c[l*Ah+u]);s.push({data:a[l],commitment:o[l],proof:Gt(h)})}e=e[0]}V(Array.isArray(e)&&(e.length===11||e.length===14),`invalid field count for transaction type: ${t}`,"data",Ce(i));const r={type:3,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList"),maxFeePerBlobGas:Nt(e[9],"maxFeePerBlobGas"),blobVersionedHashes:e[10],blobWrapperVersion:n};s&&(r.blobs=s),V(r.to!=null,`invalid address for transaction type: ${t}`,"data",i),V(Array.isArray(r.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",i);for(let a=0;a<r.blobVersionedHashes.length;a++)V(Pt(r.blobVersionedHashes[a],32),`invalid blobVersionedHash at index ${a}: must be length 32`,"data",i);return e.length===11||xh(r,e.slice(11)),r}function fD(i,e,t){const n=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||rc,xt(i.value,"value"),i.data,mh(i.accessList||[]),xt(i.maxFeePerBlobGas||0,"maxFeePerBlobGas"),rD(i.blobVersionedHashes||[],"blobVersionedHashes")];if(e&&(n.push(xt(e.yParity,"yParity")),n.push(rn(e.r)),n.push(rn(e.s)),t)){if(i.blobWrapperVersion!=null){const s=rn(i.blobWrapperVersion),r=[];for(const{proof:a}of t){const o=ut(a),c=o.length/Ah;for(let l=0;l<o.length;l+=c)r.push(o.subarray(l,l+c))}return Gt(["0x03",fs([n,s,t.map(a=>a.data),t.map(a=>a.commitment),r])])}return Gt(["0x03",fs([n,t.map(s=>s.data),t.map(s=>s.commitment),t.map(s=>s.proof)])])}return Gt(["0x03",fs(n)])}function pD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===10||e.length===13),"invalid field count for transaction type: 4","data",Ce(i));const t={type:4,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList"),authorizationList:iD(e[9],"authorizationList")};return e.length===10||xh(t,e.slice(10)),t}function AD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[]),sD(i.authorizationList||[])];return e&&(t.push(xt(e.yParity,"yParity")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x04",fs(t)])}class Ni{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;#c;#h;#u;#d;#x;#g;get type(){return this.#e}set type(e){switch(e){case null:this.#e=null;break;case 0:case"legacy":this.#e=0;break;case 1:case"berlin":case"eip-2930":this.#e=1;break;case 2:case"london":case"eip-1559":this.#e=2;break;case 3:case"cancun":case"eip-4844":this.#e=3;break;case 4:case"pectra":case"eip-7702":this.#e=4;break;default:V(!1,"unsupported transaction type","type",e)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const e=this.#t;return e==null&&this.type===3?rc:e}set to(e){this.#t=e==null?null:St(e)}get nonce(){return this.#i}set nonce(e){this.#i=dt(e,"value")}get gasLimit(){return this.#s}set gasLimit(e){this.#s=Ne(e)}get gasPrice(){const e=this.#a;return e==null&&(this.type===0||this.type===1)?_n:e}set gasPrice(e){this.#a=e==null?null:Ne(e,"gasPrice")}get maxPriorityFeePerGas(){const e=this.#r;return e??(this.type===2||this.type===3?_n:null)}set maxPriorityFeePerGas(e){this.#r=e==null?null:Ne(e,"maxPriorityFeePerGas")}get maxFeePerGas(){const e=this.#o;return e??(this.type===2||this.type===3?_n:null)}set maxFeePerGas(e){this.#o=e==null?null:Ne(e,"maxFeePerGas")}get data(){return this.#n}set data(e){this.#n=Ce(e)}get value(){return this.#f}set value(e){this.#f=Ne(e,"value")}get chainId(){return this.#l}set chainId(e){this.#l=Ne(e)}get signature(){return this.#p||null}set signature(e){this.#p=e==null?null:Vt.from(e)}isValid(){const e=this.signature;if(e&&!e.isValid())return!1;const t=this.authorizationList;if(t){for(const n of t)if(!n.signature.isValid())return!1}return!0}get accessList(){const e=this.#A||null;return e??(this.type===1||this.type===2||this.type===3?[]:null)}set accessList(e){this.#A=e==null?null:Tr(e)}get authorizationList(){const e=this.#x||null;return e==null&&this.type===4?[]:e}set authorizationList(e){this.#x=e==null?null:e.map(t=>vb(t))}get maxFeePerBlobGas(){const e=this.#c;return e==null&&this.type===3?_n:e}set maxFeePerBlobGas(e){this.#c=e==null?null:Ne(e,"maxFeePerBlobGas")}get blobVersionedHashes(){let e=this.#h;return e==null&&this.type===3?[]:e}set blobVersionedHashes(e){if(e!=null){V(Array.isArray(e),"blobVersionedHashes must be an Array","value",e),e=e.slice();for(let t=0;t<e.length;t++)V(Pt(e[t],32),"invalid blobVersionedHash",`value[${t}]`,e[t])}this.#h=e}get blobs(){return this.#d==null?null:this.#d.map(e=>Object.assign({},e))}set blobs(e){if(e==null){this.#d=null;return}const t=[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(Ff(r)){pe(this.#u,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let a=ut(r);if(V(a.length<=op,"blob is too large",`blobs[${s}]`,r),a.length!==op){const l=new Uint8Array(op);l.set(a),a=l}const o=this.#u.blobToKzgCommitment(a),c=Ce(this.#u.computeBlobKzgProof(a,o));t.push({data:Ce(a),commitment:Ce(o),proof:c}),n.push(Cb(1,o))}else{const a=Ce(r.data),o=Ce(r.commitment),c=Ce(r.proof);t.push({data:a,commitment:o,proof:c}),n.push(Cb(1,o))}}this.#d=t,this.#h=n}get kzg(){return this.#u}set kzg(e){e==null?this.#u=null:this.#u=nD(e)}get blobWrapperVersion(){return this.#g}set blobWrapperVersion(e){this.#g=e}constructor(){this.#e=null,this.#t=null,this.#i=0,this.#s=_n,this.#a=null,this.#r=null,this.#o=null,this.#n="0x",this.#f=_n,this.#l=_n,this.#p=null,this.#A=null,this.#c=null,this.#h=null,this.#u=null,this.#d=null,this.#x=null,this.#g=null}get hash(){return this.signature==null?null:an(this.#m(!0,!1))}get unsignedHash(){return an(this.unsignedSerialized)}get from(){return this.signature==null?null:XN(this.unsignedHash,this.signature.getCanonical())}get fromPublicKey(){return this.signature==null?null:ms.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return this.signature!=null}#m(e,t){pe(!e||this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=e?this.signature:null;switch(this.inferType()){case 0:return oD(this,n);case 1:return uD(this,n);case 2:return lD(this,n);case 3:return fD(this,n,t?this.blobs:null);case 4:return AD(this,n)}pe(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#m(!0,!0)}get unsignedSerialized(){return this.#m(!1,!1)}inferType(){const e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){const e=this.gasPrice!=null,t=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null,n=this.accessList!=null,s=this.#c!=null||this.#h;this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null&&pe(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),pe(!t||this.type!==0&&this.type!==1,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),pe(this.type!==0||!n,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const r=[];return this.type!=null?r.push(this.type):this.authorizationList&&this.authorizationList.length?r.push(4):t?r.push(2):e?(r.push(1),n||r.push(0)):n?(r.push(1),r.push(2)):(s&&this.to||(r.push(0),r.push(1),r.push(2)),r.push(3)),r.sort(),r}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}clone(){return Ni.from(this)}toJSON(){const e=t=>t==null?null:t.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[tD](){return this.toString()}toString(){const e=[],t=s=>{let r=this[s];typeof r=="string"&&(r=JSON.stringify(r)),e.push(`${s}: ${r}`)};this.type&&t("type"),t("to"),t("data"),t("nonce"),t("gasLimit"),t("value"),this.chainId!=null&&t("chainId"),this.signature&&(t("from"),e.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const s=[];for(const r of n){const a=[];a.push(`address: ${JSON.stringify(r.address)}`),r.nonce!=null&&a.push(`nonce: ${r.nonce}`),r.chainId!=null&&a.push(`chainId: ${r.chainId}`),r.signature&&a.push(`signature: ${r.signature.toString()}`),s.push(`Authorization { ${a.join(", ")} }`)}e.push(`authorizations: [ ${s.join(", ")} ]`)}return`Transaction { ${e.join(", ")} }`}static from(e){if(e==null)return new Ni;if(typeof e=="string"){const n=ut(e);if(n[0]>=127)return Ni.from(aD(n));switch(n[0]){case 1:return Ni.from(hD(n));case 2:return Ni.from(cD(n));case 3:return Ni.from(dD(n));case 4:return Ni.from(pD(n))}pe(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const t=new Ni;return e.type!=null&&(t.type=e.type),e.to!=null&&(t.to=e.to),e.nonce!=null&&(t.nonce=e.nonce),e.gasLimit!=null&&(t.gasLimit=e.gasLimit),e.gasPrice!=null&&(t.gasPrice=e.gasPrice),e.maxPriorityFeePerGas!=null&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.maxFeePerGas!=null&&(t.maxFeePerGas=e.maxFeePerGas),e.maxFeePerBlobGas!=null&&(t.maxFeePerBlobGas=e.maxFeePerBlobGas),e.data!=null&&(t.data=e.data),e.value!=null&&(t.value=e.value),e.chainId!=null&&(t.chainId=e.chainId),e.signature!=null&&(t.signature=Vt.from(e.signature)),e.accessList!=null&&(t.accessList=e.accessList),e.authorizationList!=null&&(t.authorizationList=e.authorizationList),e.blobVersionedHashes!=null&&(t.blobVersionedHashes=e.blobVersionedHashes),e.kzg!=null&&(t.kzg=e.kzg),e.blobWrapperVersion!=null&&(t.blobWrapperVersion=e.blobWrapperVersion),e.blobs!=null&&(t.blobs=e.blobs),e.hash!=null&&(V(t.isSigned(),"unsigned transaction cannot define '.hash'","tx",e),V(t.hash===e.hash,"hash mismatch","tx",e)),e.from!=null&&(V(t.isSigned(),"unsigned transaction cannot define '.from'","tx",e),V(t.from.toLowerCase()===(e.from||"").toLowerCase(),"from mismatch","tx",e)),t}}function Fr(i){return an(ds(i))}var gD="AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZ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mnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI";const Ib=new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]),Sb=4;function mD(i){let e=0;function t(){return i[e++]<<8|i[e++]}let n=t(),s=1,r=[0,1];for(let S=1;S<n;S++)r.push(s+=t());let a=t(),o=e;e+=a;let c=0,l=0;function h(){return c==0&&(l=l<<8|i[e++],c=8),l>>--c&1}const u=31,d=2**u,f=d>>>1,p=f>>1,m=d-1;let g=0;for(let S=0;S<u;S++)g=g<<1|h();let A=[],_=0,x=d;for(;;){let S=Math.floor(((g-_+1)*s-1)/x),w=0,I=n;for(;I-w>1;){let v=w+I>>>1;S<r[v]?I=v:w=v}if(w==0)break;A.push(w);let T=_+Math.floor(x*r[w]/s),C=_+Math.floor(x*r[w+1]/s)-1;for(;((T^C)&f)==0;)g=g<<1&m|h(),T=T<<1&m,C=C<<1&m|1;for(;T&~C&p;)g=g&f|g<<1&m>>>1|h(),T=T<<1^f,C=(C^f)<<1|f|1;_=T,x=1+C-T}let E=n-4;return A.map(S=>{switch(S-E){case 3:return E+65792+(i[o++]<<16|i[o++]<<8|i[o++]);case 2:return E+256+(i[o++]<<8|i[o++]);case 1:return E+i[o++];default:return S-1}})}function xD(i){let e=0;return()=>i[e++]}function Mb(i){return xD(mD(bD(i)))}function bD(i){let e=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((s,r)=>e[s.charCodeAt(0)]=r);let t=i.length,n=new Uint8Array(6*t>>3);for(let s=0,r=0,a=0,o=0;s<t;s++)o=o<<6|e[i.charCodeAt(s)],a+=6,a>=8&&(n[r++]=o>>(a-=8));return n}function ED(i){return i&1?~i>>1:i>>1}function yD(i,e){let t=Array(i);for(let n=0,s=0;n<i;n++)t[n]=s+=ED(e());return t}function ac(i,e=0){let t=[];for(;;){let n=i(),s=i();if(!s)break;e+=n;for(let r=0;r<s;r++)t.push(e+r);e+=s+1}return t}function Bb(i){return oc(()=>{let e=ac(i);if(e.length)return e})}function Tb(i){let e=[];for(;;){let t=i();if(t==0)break;e.push(_D(t,i))}for(;;){let t=i()-1;if(t<0)break;e.push(wD(t,i))}return e.flat()}function oc(i){let e=[];for(;;){let t=i(e.length);if(!t)break;e.push(t)}return e}function Rb(i,e,t){let n=Array(i).fill().map(()=>[]);for(let s=0;s<e;s++)yD(i,t).forEach((r,a)=>n[a].push(r));return n}function _D(i,e){let t=1+e(),n=e(),s=oc(e);return Rb(s.length,1+i,e).flatMap((a,o)=>{let[c,...l]=a;return Array(s[o]).fill().map((h,u)=>{let d=u*n;return[c+u*t,l.map(f=>f+d)]})})}function wD(i,e){let t=1+e();return Rb(t,1+i,e).map(s=>[s[0],s.slice(1)])}function vD(i){let e=[],t=ac(i);return s(n([]),[]),e;function n(r){let a=i(),o=oc(()=>{let c=ac(i).map(l=>t[l]);if(c.length)return n(c)});return{S:a,B:o,Q:r}}function s({S:r,B:a},o,c){if(!(r&4&&c===o[o.length-1])){r&2&&(c=o[o.length-1]),r&1&&e.push(o);for(let l of a)for(let h of l.Q)s(l,[...o,h],c)}}}function CD(i){return i.toString(16).toUpperCase().padStart(2,"0")}function Fb(i){return`{${CD(i)}}`}function ID(i){let e=[];for(let t=0,n=i.length;t<n;){let s=i.codePointAt(t);t+=s<65536?1:2,e.push(s)}return e}function Va(i){let t=i.length;if(t<4096)return String.fromCodePoint(...i);let n=[];for(let s=0;s<t;)n.push(String.fromCodePoint(...i.slice(s,s+=4096)));return n.join("")}function SD(i,e){let t=i.length,n=t-e.length;for(let s=0;n==0&&s<t;s++)n=i[s]-e[s];return n}var MD="AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4z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efHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";const cc=44032,bh=4352,Eh=4449,yh=4519,Nb=19,Db=21,Wa=28,_h=Db*Wa,BD=Nb*_h,TD=cc+BD,RD=bh+Nb,FD=Eh+Db,ND=yh+Wa;function lc(i){return i>>24&255}function Lb(i){return i&16777215}let cp,Pb,lp,wh;function DD(){let i=Mb(MD);cp=new Map(Bb(i).flatMap((e,t)=>e.map(n=>[n,t+1<<24]))),Pb=new Set(ac(i)),lp=new Map,wh=new Map;for(let[e,t]of Tb(i)){if(!Pb.has(e)&&t.length==2){let[n,s]=t,r=wh.get(n);r||(r=new Map,wh.set(n,r)),r.set(s,e)}lp.set(e,t.reverse())}}function kb(i){return i>=cc&&i<TD}function LD(i,e){if(i>=bh&&i<RD&&e>=Eh&&e<FD)return cc+(i-bh)*_h+(e-Eh)*Wa;if(kb(i)&&e>yh&&e<ND&&(i-cc)%Wa==0)return i+(e-yh);{let t=wh.get(i);return t&&(t=t.get(e),t)?t:-1}}function Ub(i){cp||DD();let e=[],t=[],n=!1;function s(r){let a=cp.get(r);a&&(n=!0,r|=a),e.push(r)}for(let r of i)for(;;){if(r<128)e.push(r);else if(kb(r)){let a=r-cc,o=a/_h|0,c=a%_h/Wa|0,l=a%Wa;s(bh+o),s(Eh+c),l>0&&s(yh+l)}else{let a=lp.get(r);a?t.push(...a):s(r)}if(!t.length)break;r=t.pop()}if(n&&e.length>1){let r=lc(e[0]);for(let a=1;a<e.length;a++){let o=lc(e[a]);if(o==0||r<=o){r=o;continue}let c=a-1;for(;;){let l=e[c+1];if(e[c+1]=e[c],e[c]=l,!c||(r=lc(e[--c]),r<=o))break}r=lc(e[a])}}return e}function PD(i){let e=[],t=[],n=-1,s=0;for(let r of i){let a=lc(r),o=Lb(r);if(n==-1)a==0?n=o:e.push(o);else if(s>0&&s>=a)a==0?(e.push(n,...t),t.length=0,n=o):t.push(o),s=a;else{let c=LD(n,o);c>=0?n=c:s==0&&a==0?(e.push(n),n=o):(t.push(o),s=a)}}return n>=0&&e.push(n,...t),e}function Ob(i){return Ub(i).map(Lb)}function kD(i){return PD(Ub(i))}const Qb=45,Gb=".",Hb=65039,zb=1,vh=i=>Array.from(i);function hc(i,e){return i.P.has(e)||i.Q.has(e)}class UD extends Array{get is_emoji(){return!0}}let hp,Vb,Nr,up,Wb,qa,dp,Ka,Dr,qb,fp;function pp(){if(hp)return;let i=Mb(gD);const e=()=>ac(i),t=()=>new Set(e()),n=(h,u)=>u.forEach(d=>h.add(d));hp=new Map(Tb(i)),Vb=t(),Nr=e(),up=new Set(e().map(h=>Nr[h])),Nr=new Set(Nr),Wb=t(),t();let s=Bb(i),r=i();const a=()=>{let h=new Set;return e().forEach(u=>n(h,s[u])),n(h,e()),h};qa=oc(h=>{let u=oc(i).map(d=>d+96);if(u.length){let d=h>=r;u[0]-=32,u=Va(u),d&&(u=`Restricted[${u}]`);let f=a(),p=a(),m=!i();return{N:u,P:f,Q:p,M:m,R:d}}}),dp=t(),Ka=new Map;let o=e().concat(vh(dp)).sort((h,u)=>h-u);o.forEach((h,u)=>{let d=i(),f=o[u]=d?o[u-d]:{V:[],M:new Map};f.V.push(h),dp.has(h)||Ka.set(h,f)});for(let{V:h,M:u}of new Set(Ka.values())){let d=[];for(let p of h){let m=qa.filter(A=>hc(A,p)),g=d.find(({G:A})=>m.some(_=>A.has(_)));g||(g={G:new Set,V:[]},d.push(g)),g.V.push(p),n(g.G,m)}let f=d.flatMap(p=>vh(p.G));for(let{G:p,V:m}of d){let g=new Set(f.filter(A=>!p.has(A)));for(let A of m)u.set(A,g)}}Dr=new Set;let c=new Set;const l=h=>Dr.has(h)?c.add(h):Dr.add(h);for(let h of qa){for(let u of h.P)l(u);for(let u of h.Q)l(u)}for(let h of Dr)!Ka.has(h)&&!c.has(h)&&Ka.set(h,zb);n(Dr,Ob(Dr)),qb=vD(i).map(h=>UD.from(h)).sort(SD),fp=new Map;for(let h of qb){let u=[fp];for(let d of h){let f=u.map(p=>{let m=p.get(d);return m||(m=new Map,p.set(d,m)),m});d===Hb?u.push(...f):u=f}for(let d of u)d.V=h}}function Ap(i){return(Kb(i)?"":`${gp(Ch([i]))} `)+Fb(i)}function gp(i){return`"${i}"‎`}function OD(i){if(i.length>=4&&i[2]==Qb&&i[3]==Qb)throw new Error(`invalid label extension: "${Va(i.slice(0,4))}"`)}function QD(i){for(let t=i.lastIndexOf(95);t>0;)if(i[--t]!==95)throw new Error("underscore allowed only at start")}function GD(i){let e=i[0],t=Ib.get(e);if(t)throw uc(`leading ${t}`);let n=i.length,s=-1;for(let r=1;r<n;r++){e=i[r];let a=Ib.get(e);if(a){if(s==r)throw uc(`${t} + ${a}`);s=r+1,t=a}}if(s==n)throw uc(`trailing ${t}`)}function Ch(i,e=1/0,t=Fb){let n=[];HD(i[0])&&n.push("◌"),i.length>e&&(e>>=1,i=[...i.slice(0,e),8230,...i.slice(-e)]);let s=0,r=i.length;for(let a=0;a<r;a++){let o=i[a];Kb(o)&&(n.push(Va(i.slice(s,a))),n.push(t(o)),s=a+1)}return n.push(Va(i.slice(s,r))),n.join("")}function HD(i){return pp(),Nr.has(i)}function Kb(i){return pp(),Wb.has(i)}function zD(i){return KD(VD(i,kD,YD))}function VD(i,e,t){if(!i)return[];pp();let n=0;return i.split(Gb).map(s=>{let r=ID(s),a={input:r,offset:n};n+=r.length+1;try{let o=a.tokens=XD(r,e,t),c=o.length,l;if(!c)throw new Error("empty label");let h=a.output=o.flat();if(QD(h),!(a.emoji=c>1||o[0].is_emoji)&&h.every(d=>d<128))OD(h),l="ASCII";else{let d=o.flatMap(f=>f.is_emoji?[]:f);if(!d.length)l="Emoji";else{if(Nr.has(h[0]))throw uc("leading combining mark");for(let m=1;m<c;m++){let g=o[m];if(!g.is_emoji&&Nr.has(g[0]))throw uc(`emoji + combining mark: "${Va(o[m-1])} + ${Ch([g[0]])}"`)}GD(h);let f=vh(new Set(d)),[p]=qD(f);jD(p,d),WD(p,f),l=p.N}}a.type=l}catch(o){a.error=o}return a})}function WD(i,e){let t,n=[];for(let s of e){let r=Ka.get(s);if(r===zb)return;if(r){let a=r.M.get(s);if(t=t?t.filter(o=>a.has(o)):vh(a),!t.length)return}else n.push(s)}if(t){for(let s of t)if(n.every(r=>hc(s,r)))throw new Error(`whole-script confusable: ${i.N}/${s.N}`)}}function qD(i){let e=qa;for(let t of i){let n=e.filter(s=>hc(s,t));if(!n.length)throw qa.some(s=>hc(s,t))?Xb(e[0],t):jb(t);if(e=n,n.length==1)break}return e}function KD(i){return i.map(({input:e,error:t,output:n})=>{if(t){let s=t.message;throw new Error(i.length==1?s:`Invalid label ${gp(Ch(e,63))}: ${s}`)}return Va(n)}).join(Gb)}function jb(i){return new Error(`disallowed character: ${Ap(i)}`)}function Xb(i,e){let t=Ap(e),n=qa.find(s=>s.P.has(e));return n&&(t=`${n.N} ${t}`),new Error(`illegal mixture: ${i.N} + ${t}`)}function uc(i){return new Error(`illegal placement: ${i}`)}function jD(i,e){for(let t of e)if(!hc(i,t))throw Xb(i,t);if(i.M){let t=Ob(e);for(let n=1,s=t.length;n<s;n++)if(up.has(t[n])){let r=n+1;for(let a;r<s&&up.has(a=t[r]);r++)for(let o=n;o<r;o++)if(t[o]==a)throw new Error(`duplicate non-spacing marks: ${Ap(a)}`);if(r-n>Sb)throw new Error(`excessive non-spacing marks: ${gp(Ch(t.slice(n-1,r)))} (${r-n}/${Sb})`);n=r}}}function XD(i,e,t){let n=[],s=[];for(i=i.slice().reverse();i.length;){let r=JD(i);if(r)s.length&&(n.push(e(s)),s=[]),n.push(t(r));else{let a=i.pop();if(Dr.has(a))s.push(a);else{let o=hp.get(a);if(o)s.push(...o);else if(!Vb.has(a))throw jb(a)}}}return s.length&&n.push(e(s)),n}function YD(i){return i.filter(e=>e!=Hb)}function JD(i,e){let t=fp,n,s=i.length;for(;s&&(t=t.get(i[--s]),!!t);){let{V:r}=t;r&&(n=r,i.length=s)}return n}const Yb=new Uint8Array(32);Yb.fill(0);function Jb(i){return V(i.length!==0,"invalid ENS name; empty component","comp",i),i}function Zb(i){const e=ds(ZD(i)),t=[];if(i.length===0)return t;let n=0;for(let s=0;s<e.length;s++)e[s]===46&&(t.push(Jb(e.slice(n,s))),n=s+1);return V(n<e.length,"invalid ENS name; empty component","name",i),t.push(Jb(e.slice(n))),t}function ZD(i){try{if(i.length===0)throw new Error("empty label");return zD(i)}catch(e){V(!1,`invalid ENS name (${e.message})`,"name",i)}}function mp(i){V(typeof i=="string","invalid ENS name; not a string","name",i),V(i.length,"invalid ENS name (empty label)","name",i);let e=Yb;const t=Zb(i);for(;t.length;)e=an(Gt([e,an(t.pop())]));return Ce(e)}function $D(i,e){const t=e;return V(t<=255,"DNS encoded label cannot exceed 255","length",t),Ce(Gt(Zb(i).map(n=>{V(n.length<=t,`label ${JSON.stringify(i)} exceeds ${t} bytes`,"name",i);const s=new Uint8Array(n.length+1);return s.set(n,1),s[0]=s.length-1,s})))+"00"}const $b=new Uint8Array(32);$b.fill(0);const eL=BigInt(-1),eE=BigInt(0),tE=BigInt(1),tL=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function nL(i){const e=ut(i),t=e.length%32;return t?Gt([e,$b.slice(t)]):Ce(e)}const iL=Ks(tE,32),sL=Ks(eE,32),nE={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},xp=["name","version","chainId","verifyingContract","salt"];function iE(i){return function(e){return V(typeof e=="string",`invalid domain value for ${JSON.stringify(i)}`,`domain.${i}`,e),e}}const rL={name:iE("name"),version:iE("version"),chainId:function(i){const e=Ne(i,"domain.chainId");return V(e>=0,"invalid chain ID","domain.chainId",i),Number.isSafeInteger(e)?Number(e):Ri(e)},verifyingContract:function(i){try{return St(i).toLowerCase()}catch{}V(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",i)},salt:function(i){const e=ut(i,"domain.salt");return V(e.length===32,'invalid domain value "salt"',"domain.salt",i),Ce(e)}};function bp(i){{const e=i.match(/^(u?)int(\d+)$/);if(e){const t=e[1]==="",n=parseInt(e[2]);V(n%8===0&&n!==0&&n<=256&&e[2]===String(n),"invalid numeric width","type",i);const s=Zo(tL,t?n-1:n),r=t?(s+tE)*eL:eE;return function(a){const o=Ne(a,"value");return V(o>=r&&o<=s,`value out-of-bounds for ${i}`,"value",o),Ks(t?cx(o,256):o,32)}}}{const e=i.match(/^bytes(\d+)$/);if(e){const t=parseInt(e[1]);return V(t!==0&&t<=32&&e[1]===String(t),"invalid bytes width","type",i),function(n){const s=ut(n);return V(s.length===t,`invalid length for ${i}`,"value",n),nL(n)}}}switch(i){case"address":return function(e){return us(St(e),32)};case"bool":return function(e){return e?iL:sL};case"bytes":return function(e){return an(e)};case"string":return function(e){return Fr(e)}}return null}function sE(i,e){return`${i}(${e.map(({name:t,type:n})=>n+" "+t).join(",")})`}function Ih(i){const e=i.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return e?{base:e[1],index:e[2]+e[4],array:{base:e[1],prefix:e[1]+e[2],count:e[5]?parseInt(e[5]):-1}}:{base:i}}class ti{primaryType;#e;get types(){return JSON.parse(this.#e)}#t;#n;constructor(e){this.#t=new Map,this.#n=new Map;const t=new Map,n=new Map,s=new Map,r={};Object.keys(e).forEach(c=>{r[c]=e[c].map(({name:l,type:h})=>{let{base:u,index:d}=Ih(h);return u==="int"&&!e.int&&(u="int256"),u==="uint"&&!e.uint&&(u="uint256"),{name:l,type:u+(d||"")}}),t.set(c,new Set),n.set(c,[]),s.set(c,new Set)}),this.#e=JSON.stringify(r);for(const c in r){const l=new Set;for(const h of r[c]){V(!l.has(h.name),`duplicate variable name ${JSON.stringify(h.name)} in ${JSON.stringify(c)}`,"types",e),l.add(h.name);const u=Ih(h.type).base;V(u!==c,`circular type reference to ${JSON.stringify(u)}`,"types",e),!bp(u)&&(V(n.has(u),`unknown type ${JSON.stringify(u)}`,"types",e),n.get(u).push(c),t.get(c).add(u))}}const a=Array.from(n.keys()).filter(c=>n.get(c).length===0);V(a.length!==0,"missing primary type","types",e),V(a.length===1,`ambiguous primary types or unused types: ${a.map(c=>JSON.stringify(c)).join(", ")}`,"types",e),Ye(this,{primaryType:a[0]});function o(c,l){V(!l.has(c),`circular type reference to ${JSON.stringify(c)}`,"types",e),l.add(c);for(const h of t.get(c))if(n.has(h)){o(h,l);for(const u of l)s.get(u).add(h)}l.delete(c)}o(this.primaryType,new Set);for(const[c,l]of s){const h=Array.from(l);h.sort(),this.#t.set(c,sE(c,r[c])+h.map(u=>sE(u,r[u])).join(""))}}getEncoder(e){let t=this.#n.get(e);return t||(t=this.#i(e),this.#n.set(e,t)),t}#i(e){{const s=bp(e);if(s)return s}const t=Ih(e).array;if(t){const s=t.prefix,r=this.getEncoder(s);return a=>{V(t.count===-1||t.count===a.length,`array length mismatch; expected length ${t.count}`,"value",a);let o=a.map(r);return this.#t.has(s)&&(o=o.map(an)),an(Gt(o))}}const n=this.types[e];if(n){const s=Fr(this.#t.get(e));return r=>{const a=n.map(({name:o,type:c})=>{const l=this.getEncoder(c)(r[o]);return this.#t.has(c)?an(l):l});return a.unshift(s),Gt(a)}}V(!1,`unknown type: ${e}`,"type",e)}encodeType(e){const t=this.#t.get(e);return V(t,`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return an(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,n){if(bp(e))return n(e,t);const s=Ih(e).array;if(s)return V(s.count===-1||s.count===t.length,`array length mismatch; expected length ${s.count}`,"value",t),t.map(a=>this._visit(s.prefix,a,n));const r=this.types[e];if(r)return r.reduce((a,{name:o,type:c})=>(a[o]=this._visit(c,t[o],n),a),{});V(!1,`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(e){return new ti(e)}static getPrimaryType(e){return ti.from(e).primaryType}static hashStruct(e,t,n){return ti.from(t).hashStruct(e,n)}static hashDomain(e){const t=[];for(const n in e){if(e[n]==null)continue;const s=nE[n];V(s,`invalid typed-data domain key: ${JSON.stringify(n)}`,"domain",e),t.push({name:n,type:s})}return t.sort((n,s)=>xp.indexOf(n.name)-xp.indexOf(s.name)),ti.hashStruct("EIP712Domain",{EIP712Domain:t},e)}static encode(e,t,n){return Gt(["0x1901",ti.hashDomain(e),ti.from(t).hash(n)])}static hash(e,t,n){return an(ti.encode(e,t,n))}static async resolveNames(e,t,n,s){e=Object.assign({},e);for(const o in e)e[o]==null&&delete e[o];const r={};e.verifyingContract&&!Pt(e.verifyingContract,20)&&(r[e.verifyingContract]="0x");const a=ti.from(t);a.visit(n,(o,c)=>(o==="address"&&!Pt(c,20)&&(r[c]="0x"),c));for(const o in r)r[o]=await s(o);return e.verifyingContract&&r[e.verifyingContract]&&(e.verifyingContract=r[e.verifyingContract]),n=a.visit(n,(o,c)=>o==="address"&&r[c]?r[c]:c),{domain:e,value:n}}static getPayload(e,t,n){ti.hashDomain(e);const s={},r=[];xp.forEach(c=>{const l=e[c];l!=null&&(s[c]=rL[c](l),r.push({name:c,type:nE[c]}))});const a=ti.from(t);t=a.types;const o=Object.assign({},t);return V(o.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",t),o.EIP712Domain=r,a.encode(n),{types:o,domain:s,primaryType:a.primaryType,message:a.visit(n,(c,l)=>{if(c.match(/^bytes(\d*)/))return Ce(ut(l));if(c.match(/^u?int/))return Ne(l).toString();switch(c){case"address":return l.toLowerCase();case"bool":return!!l;case"string":return V(typeof l=="string","invalid string","value",l),l}V(!1,"unsupported type","type",c)})}}}function qn(i){const e=new Set;return i.forEach(t=>e.add(t)),Object.freeze(e)}const aL=qn("external public payable override".split(" ")),rE="constant external internal payable private public pure view override",oL=qn(rE.split(" ")),aE="constructor error event fallback function receive struct",oE=qn(aE.split(" ")),cE="calldata memory storage payable indexed",cL=qn(cE.split(" ")),lL=[aE,cE,"tuple returns",rE].join(" "),hL=qn(lL.split(" ")),uL={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},dL=new RegExp("^(\\s*)"),fL=new RegExp("^([0-9]+)"),pL=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),lE=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),hE=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class gi{#e;#t;get offset(){return this.#e}get length(){return this.#t.length-this.#e}constructor(e){this.#e=0,this.#t=e.slice()}clone(){return new gi(this.#t)}reset(){this.#e=0}#n(e=0,t=0){return new gi(this.#t.slice(e,t).map(n=>Object.freeze(Object.assign({},n,{match:n.match-e,linkBack:n.linkBack-e,linkNext:n.linkNext-e}))))}popKeyword(e){const t=this.peek();if(t.type!=="KEYWORD"||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=this.#n(this.#e+1,e.match+1);return this.#e=e.match+1,t}popParams(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=[];for(;this.#e<e.match-1;){const n=this.peek().linkNext;t.push(this.#n(this.#e+1,n)),this.#e=n}return this.#e=e.match+1,t}peek(){if(this.#e>=this.#t.length)throw new Error("out-of-bounds");return this.#t[this.#e]}peekKeyword(e){const t=this.peekType("KEYWORD");return t!=null&&e.has(t)?t:null}peekType(e){if(this.length===0)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return this.#e++,e}toString(){const e=[];for(let t=this.#e;t<this.#t.length;t++){const n=this.#t[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}}function er(i){const e=[],t=a=>{const o=r<i.length?JSON.stringify(i[r]):"$EOI";throw new Error(`invalid token ${o} at ${r}: ${a}`)};let n=[],s=[],r=0;for(;r<i.length;){let a=i.substring(r),o=a.match(dL);o&&(r+=o[1].length,a=i.substring(r));const c={depth:n.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:r,value:-1};e.push(c);let l=uL[a[0]]||"";if(l){if(c.type=l,c.text=a[0],r++,l==="OPEN_PAREN")n.push(e.length-1),s.push(e.length-1);else if(l=="CLOSE_PAREN")n.length===0&&t("no matching open bracket"),c.match=n.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if(l==="COMMA")c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if(l==="OPEN_BRACKET")c.type="BRACKET";else if(l==="CLOSE_BRACKET"){let h=e.pop().text;if(e.length>0&&e[e.length-1].type==="NUMBER"){const u=e.pop().text;h=u+h,e[e.length-1].value=dt(u)}if(e.length===0||e[e.length-1].type!=="BRACKET")throw new Error("missing opening bracket");e[e.length-1].text+=h}continue}if(o=a.match(pL),o){if(c.text=o[1],r+=c.text.length,hL.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(hE)){c.type="TYPE";continue}c.type="ID";continue}if(o=a.match(fL),o){c.text=o[1],c.type="NUMBER",r+=c.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(a[0])} at position ${r}`)}return new gi(e.map(a=>Object.freeze(a)))}function uE(i,e){let t=[];for(const n in e.keys())i.has(n)&&t.push(n);if(t.length>1)throw new Error(`conflicting types: ${t.join(", ")}`)}function Sh(i,e){if(e.peekKeyword(oE)){const t=e.pop().text;if(t!==i)throw new Error(`expected ${i}, got ${t}`)}return e.popType("ID")}function bs(i,e){const t=new Set;for(;;){const n=i.peekType("KEYWORD");if(n==null||e&&!e.has(n))break;if(i.pop(),t.has(n))throw new Error(`duplicate keywords: ${JSON.stringify(n)}`);t.add(n)}return Object.freeze(t)}function dE(i){let e=bs(i,oL);return uE(e,qn("constant payable nonpayable".split(" "))),uE(e,qn("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function Es(i,e){return i.popParams().map(t=>kt.from(t,e))}function fE(i){if(i.peekType("AT")){if(i.pop(),i.peekType("NUMBER"))return Ne(i.pop().text);throw new Error("invalid gas")}return null}function Lr(i){if(i.length)throw new Error(`unexpected tokens at offset ${i.offset}: ${i.toString()}`)}const AL=new RegExp(/^(.*)\[([0-9]*)\]$/);function pE(i){const e=i.match(hE);if(V(e,"invalid type","type",i),i==="uint")return"uint256";if(i==="int")return"int256";if(e[2]){const t=parseInt(e[2]);V(t!==0&&t<=32,"invalid bytes length","type",i)}else if(e[3]){const t=parseInt(e[3]);V(t!==0&&t<=256&&t%8===0,"invalid numeric width","type",i)}return i}const Wt={},Yn=Symbol.for("_ethers_internal"),AE="_ParamTypeInternal",gE="_ErrorInternal",mE="_EventInternal",xE="_ConstructorInternal",bE="_FallbackInternal",EE="_FunctionInternal",yE="_StructInternal";class kt{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,s,r,a,o,c){if(ih(e,Wt,"ParamType"),Object.defineProperty(this,Yn,{value:AE}),a&&(a=Object.freeze(a.slice())),s==="array"){if(o==null||c==null)throw new Error("")}else if(o!=null||c!=null)throw new Error("");if(s==="tuple"){if(a==null)throw new Error("")}else if(a!=null)throw new Error("");Ye(this,{name:t,type:n,baseType:s,indexed:r,components:a,arrayLength:o,arrayChildren:c})}format(e){if(e==null&&(e="sighash"),e==="json"){const n=this.name||"";if(this.isArray()){const r=JSON.parse(this.arrayChildren.format("json"));return r.name=n,r.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(r)}const s={type:this.baseType==="tuple"?"tuple":this.type,name:n};return typeof this.indexed=="boolean"&&(s.indexed=this.indexed),this.isTuple()&&(s.components=this.components.map(r=>JSON.parse(r.format(e)))),JSON.stringify(s)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map(n=>n.format(e)).join(e==="full"?", ":",")+")":t+=this.type,e!=="sighash"&&(this.indexed===!0&&(t+=" indexed"),e==="full"&&this.name&&(t+=" "+this.name)),t}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(this.arrayLength!==-1&&e.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return e.map(s=>n.arrayChildren.walk(s,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map((s,r)=>n.components[r].walk(s,t))}return t(this.type,e)}#e(e,t,n,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw new Error("array is wrong length");const a=this.arrayChildren,o=t.slice();o.forEach((c,l)=>{a.#e(e,c,n,h=>{o[l]=h})}),s(o);return}if(this.isTuple()){const a=this.components;let o;if(Array.isArray(t))o=t.slice();else{if(t==null||typeof t!="object")throw new Error("invalid tuple value");o=a.map(c=>{if(!c.name)throw new Error("cannot use object value with unnamed components");if(!(c.name in t))throw new Error(`missing value for component ${c.name}`);return t[c.name]})}if(o.length!==this.components.length)throw new Error("array is wrong length");o.forEach((c,l)=>{a[l].#e(e,c,n,h=>{o[l]=h})}),s(o);return}const r=n(this.type,t);r.then?e.push((async function(){s(await r)})()):s(r)}async walkAsync(e,t){const n=[],s=[e];return this.#e(n,e,t,r=>{s[0]=r}),n.length&&await Promise.all(n),s[0]}static from(e,t){if(kt.isParamType(e))return e;if(typeof e=="string")try{return kt.from(er(e),t)}catch{V(!1,"invalid param type","obj",e)}else if(e instanceof gi){let o="",c="",l=null;bs(e,qn(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(c="tuple",l=e.popParams().map(m=>kt.from(m)),o=`tuple(${l.map(m=>m.format()).join(",")})`):(o=pE(e.popType("TYPE")),c=o);let h=null,u=null;for(;e.length&&e.peekType("BRACKET");){const m=e.pop();h=new kt(Wt,"",o,c,null,l,u,h),u=m.value,o+=m.text,c="array",l=null}let d=null;if(bs(e,cL).has("indexed")){if(!t)throw new Error("");d=!0}const p=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new kt(Wt,p,o,c,d,l,u,h)}const n=e.name;V(!n||typeof n=="string"&&n.match(lE),"invalid name","obj.name",n);let s=e.indexed;s!=null&&(V(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let r=e.type,a=r.match(AL);if(a){const o=parseInt(a[2]||"-1"),c=kt.from({type:a[1],components:e.components});return new kt(Wt,n||"",r,"array",s,null,o,c)}if(r==="tuple"||r.startsWith("tuple(")||r.startsWith("(")){const o=e.components!=null?e.components.map(l=>kt.from(l)):null;return new kt(Wt,n||"",r,"tuple",s,o,null,null)}return r=pE(e.type),new kt(Wt,n||"",r,r,s,null,null,null)}static isParamType(e){return e&&e[Yn]===AE}}class Pr{type;inputs;constructor(e,t,n){ih(e,Wt,"Fragment"),n=Object.freeze(n.slice()),Ye(this,{type:t,inputs:n})}static from(e){if(typeof e=="string"){try{Pr.from(JSON.parse(e))}catch{}return Pr.from(er(e))}if(e instanceof gi)switch(e.peekKeyword(oE)){case"constructor":return ys.from(e);case"error":return Jn.from(e);case"event":return Wi.from(e);case"fallback":case"receive":return _s.from(e);case"function":return qi.from(e);case"struct":return kr.from(e)}else if(typeof e=="object"){switch(e.type){case"constructor":return ys.from(e);case"error":return Jn.from(e);case"event":return Wi.from(e);case"fallback":case"receive":return _s.from(e);case"function":return qi.from(e);case"struct":return kr.from(e)}pe(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}V(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return ys.isFragment(e)}static isError(e){return Jn.isFragment(e)}static isEvent(e){return Wi.isFragment(e)}static isFunction(e){return qi.isFragment(e)}static isStruct(e){return kr.isFragment(e)}}class Mh extends Pr{name;constructor(e,t,n,s){super(e,t,s),V(typeof n=="string"&&n.match(lE),"invalid identifier","name",n),s=Object.freeze(s.slice()),Ye(this,{name:n})}}function dc(i,e){return"("+e.map(t=>t.format(i)).join(i==="full"?", ":",")+")"}class Jn extends Mh{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,Yn,{value:gE})}get selector(){return Fr(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("error"),t.push(this.name+dc(e,this.inputs)),t.join(" ")}static from(e){if(Jn.isFragment(e))return e;if(typeof e=="string")return Jn.from(er(e));if(e instanceof gi){const t=Sh("error",e),n=Es(e);return Lr(e),new Jn(Wt,t,n)}return new Jn(Wt,e.name,e.inputs?e.inputs.map(kt.from):[])}static isFragment(e){return e&&e[Yn]===gE}}class Wi extends Mh{anonymous;constructor(e,t,n,s){super(e,"event",t,n),Object.defineProperty(this,Yn,{value:mE}),Ye(this,{anonymous:s})}get topicHash(){return Fr(this.format("sighash"))}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("event"),t.push(this.name+dc(e,this.inputs)),e!=="sighash"&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){return t=(t||[]).map(s=>kt.from(s)),new Wi(Wt,e,t,!1).topicHash}static from(e){if(Wi.isFragment(e))return e;if(typeof e=="string")try{return Wi.from(er(e))}catch{V(!1,"invalid event fragment","obj",e)}else if(e instanceof gi){const t=Sh("event",e),n=Es(e,!0),s=!!bs(e,qn(["anonymous"])).has("anonymous");return Lr(e),new Wi(Wt,t,n,s)}return new Wi(Wt,e.name,e.inputs?e.inputs.map(t=>kt.from(t,!0)):[],!!e.anonymous)}static isFragment(e){return e&&e[Yn]===mE}}class ys extends Pr{payable;gas;constructor(e,t,n,s,r){super(e,t,n),Object.defineProperty(this,Yn,{value:xE}),Ye(this,{payable:s,gas:r})}format(e){if(pe(e!=null&&e!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),e==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[`constructor${dc(e,this.inputs)}`];return this.payable&&t.push("payable"),this.gas!=null&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(ys.isFragment(e))return e;if(typeof e=="string")try{return ys.from(er(e))}catch{V(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof gi){bs(e,qn(["constructor"]));const t=Es(e),n=!!bs(e,aL).has("payable"),s=fE(e);return Lr(e),new ys(Wt,"constructor",t,n,s)}return new ys(Wt,"constructor",e.inputs?e.inputs.map(kt.from):[],!!e.payable,e.gas!=null?e.gas:null)}static isFragment(e){return e&&e[Yn]===xE}}class _s extends Pr{payable;constructor(e,t,n){super(e,"fallback",t),Object.defineProperty(this,Yn,{value:bE}),Ye(this,{payable:n})}format(e){const t=this.inputs.length===0?"receive":"fallback";if(e==="json"){const n=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:n})}return`${t}()${this.payable?" payable":""}`}static from(e){if(_s.isFragment(e))return e;if(typeof e=="string")try{return _s.from(er(e))}catch{V(!1,"invalid fallback fragment","obj",e)}else if(e instanceof gi){const t=e.toString(),n=e.peekKeyword(qn(["fallback","receive"]));if(V(n,"type must be fallback or receive","obj",t),e.popKeyword(qn(["fallback","receive"]))==="receive"){const o=Es(e);return V(o.length===0,"receive cannot have arguments","obj.inputs",o),bs(e,qn(["payable"])),Lr(e),new _s(Wt,[],!0)}let r=Es(e);r.length?V(r.length===1&&r[0].type==="bytes","invalid fallback inputs","obj.inputs",r.map(o=>o.format("minimal")).join(", ")):r=[kt.from("bytes")];const a=dE(e);if(V(a==="nonpayable"||a==="payable","fallback cannot be constants","obj.stateMutability",a),bs(e,qn(["returns"])).has("returns")){const o=Es(e);V(o.length===1&&o[0].type==="bytes","invalid fallback outputs","obj.outputs",o.map(c=>c.format("minimal")).join(", "))}return Lr(e),new _s(Wt,r,a==="payable")}if(e.type==="receive")return new _s(Wt,[],!0);if(e.type==="fallback"){const t=[kt.from("bytes")],n=e.stateMutability==="payable";return new _s(Wt,t,n)}V(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[Yn]===bE}}class qi extends Mh{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,s,r,a){super(e,"function",t,s),Object.defineProperty(this,Yn,{value:EE}),r=Object.freeze(r.slice()),Ye(this,{constant:n==="view"||n==="pure",gas:a,outputs:r,payable:n==="payable",stateMutability:n})}get selector(){return Fr(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(n=>JSON.parse(n.format(e))),outputs:this.outputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("function"),t.push(this.name+dc(e,this.inputs)),e!=="sighash"&&(this.stateMutability!=="nonpayable"&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(dc(e,this.outputs))),this.gas!=null&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){return t=(t||[]).map(s=>kt.from(s)),new qi(Wt,e,"view",t,[],null).selector}static from(e){if(qi.isFragment(e))return e;if(typeof e=="string")try{return qi.from(er(e))}catch{V(!1,"invalid function fragment","obj",e)}else if(e instanceof gi){const n=Sh("function",e),s=Es(e),r=dE(e);let a=[];bs(e,qn(["returns"])).has("returns")&&(a=Es(e));const o=fE(e);return Lr(e),new qi(Wt,n,r,s,a,o)}let t=e.stateMutability;return t==null&&(t="payable",typeof e.constant=="boolean"?(t="view",e.constant||(t="payable",typeof e.payable=="boolean"&&!e.payable&&(t="nonpayable"))):typeof e.payable=="boolean"&&!e.payable&&(t="nonpayable")),new qi(Wt,e.name,t,e.inputs?e.inputs.map(kt.from):[],e.outputs?e.outputs.map(kt.from):[],e.gas!=null?e.gas:null)}static isFragment(e){return e&&e[Yn]===EE}}class kr extends Mh{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,Yn,{value:yE})}format(){throw new Error("@TODO")}static from(e){if(typeof e=="string")try{return kr.from(er(e))}catch{V(!1,"invalid struct fragment","obj",e)}else if(e instanceof gi){const t=Sh("struct",e),n=Es(e);return Lr(e),new kr(Wt,t,n)}return new kr(Wt,e.name,e.inputs?e.inputs.map(kt.from):[])}static isFragment(e){return e&&e[Yn]===yE}}const Di=new Map;Di.set(0,"GENERIC_PANIC"),Di.set(1,"ASSERT_FALSE"),Di.set(17,"OVERFLOW"),Di.set(18,"DIVIDE_BY_ZERO"),Di.set(33,"ENUM_RANGE_ERROR"),Di.set(34,"BAD_STORAGE_DATA"),Di.set(49,"STACK_UNDERFLOW"),Di.set(50,"ARRAY_RANGE_ERROR"),Di.set(65,"OUT_OF_MEMORY"),Di.set(81,"UNINITIALIZED_FUNCTION_CALL");const gL=new RegExp(/^bytes([0-9]*)$/),mL=new RegExp(/^(u?int)([0-9]*)$/);let Ep=null,_E=1024;function xL(i,e,t,n){let s="missing revert data",r=null;const a=null;let o=null;if(t){s="execution reverted";const l=ut(t);if(t=Ce(t),l.length===0)s+=" (no data present; likely require(false) occurred",r="require(false)";else if(l.length%32!==4)s+=" (could not decode reason; invalid data length)";else if(Ce(l.slice(0,4))==="0x08c379a0")try{r=n.decode(["string"],l.slice(4))[0],o={signature:"Error(string)",name:"Error",args:[r]},s+=`: ${JSON.stringify(r)}`}catch{s+=" (could not decode reason; invalid string data)"}else if(Ce(l.slice(0,4))==="0x4e487b71")try{const h=Number(n.decode(["uint256"],l.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[h]},r=`Panic due to ${Di.get(h)||"UNKNOWN"}(${h})`,s+=`: ${r}`}catch{s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const c={to:e.to?St(e.to):null,data:e.data||"0x"};return e.from&&(c.from=St(e.from)),Qt(s,"CALL_EXCEPTION",{action:i,data:t,reason:r,transaction:c,invocation:a,revert:o})}class ja{#e(e){if(e.isArray())return new kN(this.#e(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new ph(e.components.map(n=>this.#e(n)),e.name);switch(e.baseType){case"address":return new LN(e.name);case"bool":return new UN(e.name);case"string":return new KN(e.name);case"bytes":return new ON(e.name);case"":return new HN(e.name)}let t=e.type.match(mL);if(t){let n=parseInt(t[2]||"256");return V(n!==0&&n<=256&&n%8===0,"invalid "+t[1]+" bit length","param",e),new qN(n/8,t[1]==="int",e.name)}if(t=e.type.match(gL),t){let n=parseInt(t[1]);return V(n!==0&&n<=32,"invalid bytes length","param",e),new QN(n,e.name)}V(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map(s=>this.#e(kt.from(s)));return new ph(t,"_").defaultValue()}encode(e,t){sx(t.length,e.length,"types/values length mismatch");const n=e.map(a=>this.#e(kt.from(a))),s=new ph(n,"_"),r=new kf;return s.encode(r,t),r.data}decode(e,t,n){const s=e.map(a=>this.#e(kt.from(a)));return new ph(s,"_").decode(new Uf(t,n,_E))}static _setDefaultMaxInflation(e){V(typeof e=="number"&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),_E=e}static defaultAbiCoder(){return Ep==null&&(Ep=new ja),Ep}static getBuiltinCallException(e,t,n){return xL(e,t,n,ja.defaultAbiCoder())}}class bL{fragment;name;signature;topic;args;constructor(e,t,n){const s=e.name,r=e.format();Ye(this,{fragment:e,name:s,signature:r,topic:t,args:n})}}class EL{fragment;name;args;signature;selector;value;constructor(e,t,n,s){const r=e.name,a=e.format();Ye(this,{fragment:e,name:r,args:n,signature:a,selector:t,value:s})}}class yL{fragment;name;args;signature;selector;constructor(e,t,n){const s=e.name,r=e.format();Ye(this,{fragment:e,name:s,args:n,signature:r,selector:t})}}class wE{hash;_isIndexed;static isIndexed(e){return!!(e&&e._isIndexed)}constructor(e){Ye(this,{hash:e,_isIndexed:!0})}}const vE={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},CE={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:i=>`reverted with reason string ${JSON.stringify(i)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:i=>{let e="unknown panic code";return i>=0&&i<=255&&vE[i.toString()]&&(e=vE[i.toString()]),`reverted with panic code 0x${i.toString(16)} (${e})`}}};class Ur{fragments;deploy;fallback;receive;#e;#t;#n;#i;constructor(e){let t=[];typeof e=="string"?t=JSON.parse(e):t=e,this.#n=new Map,this.#e=new Map,this.#t=new Map;const n=[];for(const a of t)try{n.push(Pr.from(a))}catch(o){console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`,o.message)}Ye(this,{fragments:Object.freeze(n)});let s=null,r=!1;this.#i=this.getAbiCoder(),this.fragments.forEach((a,o)=>{let c;switch(a.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}Ye(this,{deploy:a});return;case"fallback":a.inputs.length===0?r=!0:(V(!s||a.payable!==s.payable,"conflicting fallback fragments",`fragments[${o}]`,a),s=a,r=s.payable);return;case"function":c=this.#n;break;case"event":c=this.#t;break;case"error":c=this.#e;break;default:return}const l=a.format();c.has(l)||c.set(l,a)}),this.deploy||Ye(this,{deploy:ys.from("constructor()")}),Ye(this,{fallback:s,receive:r})}format(e){const t=e?"minimal":"full";return this.fragments.map(s=>s.format(t))}formatJson(){const e=this.fragments.map(t=>t.format("json"));return JSON.stringify(e.map(t=>JSON.parse(t)))}getAbiCoder(){return ja.defaultAbiCoder()}#s(e,t,n){if(Pt(e)){const r=e.toLowerCase();for(const a of this.#n.values())if(r===a.selector)return a;return null}if(e.indexOf("(")===-1){const r=[];for(const[a,o]of this.#n)a.split("(")[0]===e&&r.push(o);if(t){const a=t.length>0?t[t.length-1]:null;let o=t.length,c=!0;jt.isTyped(a)&&a.type==="overrides"&&(c=!1,o--);for(let l=r.length-1;l>=0;l--){const h=r[l].inputs.length;h!==o&&(!c||h!==o-1)&&r.splice(l,1)}for(let l=r.length-1;l>=0;l--){const h=r[l].inputs;for(let u=0;u<t.length;u++)if(jt.isTyped(t[u])){if(u>=h.length){if(t[u].type==="overrides")continue;r.splice(l,1);break}if(t[u].type!==h[u].baseType){r.splice(l,1);break}}}}if(r.length===1&&t&&t.length!==r[0].inputs.length){const a=t[t.length-1];(a==null||Array.isArray(a)||typeof a!="object")&&r.splice(0,1)}if(r.length===0)return null;if(r.length>1&&n){const a=r.map(o=>JSON.stringify(o.format())).join(", ");V(!1,`ambiguous function description (i.e. matches ${a})`,"key",e)}return r[0]}const s=this.#n.get(qi.from(e).format());return s||null}getFunctionName(e){const t=this.#s(e,null,!1);return V(t,"no matching function","key",e),t.name}hasFunction(e){return!!this.#s(e,null,!1)}getFunction(e,t){return this.#s(e,t||null,!0)}forEachFunction(e){const t=Array.from(this.#n.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#n.get(s),n)}}#a(e,t,n){if(Pt(e)){const r=e.toLowerCase();for(const a of this.#t.values())if(r===a.topicHash)return a;return null}if(e.indexOf("(")===-1){const r=[];for(const[a,o]of this.#t)a.split("(")[0]===e&&r.push(o);if(t){for(let a=r.length-1;a>=0;a--)r[a].inputs.length<t.length&&r.splice(a,1);for(let a=r.length-1;a>=0;a--){const o=r[a].inputs;for(let c=0;c<t.length;c++)if(jt.isTyped(t[c])&&t[c].type!==o[c].baseType){r.splice(a,1);break}}}if(r.length===0)return null;if(r.length>1&&n){const a=r.map(o=>JSON.stringify(o.format())).join(", ");V(!1,`ambiguous event description (i.e. matches ${a})`,"key",e)}return r[0]}const s=this.#t.get(Wi.from(e).format());return s||null}getEventName(e){const t=this.#a(e,null,!1);return V(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#a(e,null,!1)}getEvent(e,t){return this.#a(e,t||null,!0)}forEachEvent(e){const t=Array.from(this.#t.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#t.get(s),n)}}getError(e,t){if(Pt(e)){const s=e.toLowerCase();if(CE[s])return Jn.from(CE[s].signature);for(const r of this.#e.values())if(s===r.selector)return r;return null}if(e.indexOf("(")===-1){const s=[];for(const[r,a]of this.#e)r.split("(")[0]===e&&s.push(a);if(s.length===0)return e==="Error"?Jn.from("error Error(string)"):e==="Panic"?Jn.from("error Panic(uint256)"):null;if(s.length>1){const r=s.map(a=>JSON.stringify(a.format())).join(", ");V(!1,`ambiguous error description (i.e. ${r})`,"name",e)}return s[0]}if(e=Jn.from(e).format(),e==="Error(string)")return Jn.from("error Error(string)");if(e==="Panic(uint256)")return Jn.from("error Panic(uint256)");const n=this.#e.get(e);return n||null}forEachError(e){const t=Array.from(this.#e.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#e.get(s),n)}}_decodeParams(e,t){return this.#i.decode(e,t)}_encodeParams(e,t){return this.#i.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if(typeof e=="string"){const n=this.getError(e);V(n,"unknown error","fragment",e),e=n}return V(Kt(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,Kt(t,4))}encodeErrorResult(e,t){if(typeof e=="string"){const n=this.getError(e);V(n,"unknown error","fragment",e),e=n}return Gt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return V(Kt(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,Kt(t,4))}encodeFunctionData(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return Gt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if(typeof e=="string"){const r=this.getFunction(e);V(r,"unknown function","fragment",e),e=r}let n="invalid length for result data";const s=zn(t);if(s.length%32===0)try{return this.#i.decode(e.outputs,s)}catch{n="could not decode result data"}pe(!1,n,"BAD_DATA",{value:Ce(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=ut(e,"data"),s=ja.getBuiltinCallException("call",t,n);if(s.message.startsWith("execution reverted (unknown custom error)")){const o=Ce(n.slice(0,4)),c=this.getError(o);if(c)try{const l=this.#i.decode(c.inputs,n.slice(4));s.revert={name:c.name,signature:c.format(),args:l},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch{s.message="execution reverted (coult not decode custom error)"}}const a=this.parseTransaction(t);return a&&(s.invocation={method:a.name,signature:a.signature,args:a.args}),s}encodeFunctionResult(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return Ce(this.#i.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if(typeof e=="string"){const r=this.getEvent(e);V(r,"unknown event","eventFragment",e),e=r}pe(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const s=(r,a)=>r.type==="string"?Fr(a):r.type==="bytes"?an(Ce(a)):(r.type==="bool"&&typeof a=="boolean"?a=a?"0x01":"0x00":r.type.match(/^u?int/)?a=Ks(a):r.type.match(/^bytes/)?a=$R(a,32):r.type==="address"&&this.#i.encode(["address"],[a]),us(Ce(a),32));for(t.forEach((r,a)=>{const o=e.inputs[a];if(!o.indexed){V(r==null,"cannot filter non-indexed parameters; must be null","contract."+o.name,r);return}r==null?n.push(null):o.baseType==="array"||o.baseType==="tuple"?V(!1,"filtering with tuples or arrays not supported","contract."+o.name,r):Array.isArray(r)?n.push(r.map(c=>s(o,c))):n.push(s(o,r))});n.length&&n[n.length-1]===null;)n.pop();return n}encodeEventLog(e,t){if(typeof e=="string"){const a=this.getEvent(e);V(a,"unknown event","eventFragment",e),e=a}const n=[],s=[],r=[];return e.anonymous||n.push(e.topicHash),V(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((a,o)=>{const c=t[o];if(a.indexed)if(a.type==="string")n.push(Fr(c));else if(a.type==="bytes")n.push(an(c));else{if(a.baseType==="tuple"||a.baseType==="array")throw new Error("not implemented");n.push(this.#i.encode([a.type],[c]))}else s.push(a),r.push(c)}),{data:this.#i.encode(s,r),topics:n}}decodeEventLog(e,t,n){if(typeof e=="string"){const f=this.getEvent(e);V(f,"unknown event","eventFragment",e),e=f}if(n!=null&&!e.anonymous){const f=e.topicHash;V(Pt(n[0],32)&&n[0].toLowerCase()===f,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const s=[],r=[],a=[];e.inputs.forEach((f,p)=>{f.indexed?f.type==="string"||f.type==="bytes"||f.baseType==="tuple"||f.baseType==="array"?(s.push(kt.from({type:"bytes32",name:f.name})),a.push(!0)):(s.push(f),a.push(!1)):(r.push(f),a.push(!1))});const o=n!=null?this.#i.decode(s,Gt(n)):null,c=this.#i.decode(r,t,!0),l=[],h=[];let u=0,d=0;return e.inputs.forEach((f,p)=>{let m=null;if(f.indexed)if(o==null)m=new wE(null);else if(a[p])m=new wE(o[d++]);else try{m=o[d++]}catch(g){m=g}else try{m=c[u++]}catch(g){m=g}l.push(m),h.push(f.name||null)}),ps.fromItems(l,h)}parseTransaction(e){const t=ut(e.data,"tx.data"),n=Ne(e.value!=null?e.value:0,"tx.value"),s=this.getFunction(Ce(t.slice(0,4)));if(!s)return null;const r=this.#i.decode(s.inputs,t.slice(4));return new EL(s,s.selector,r,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new bL(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=Ce(e),n=this.getError(Kt(t,0,4));if(!n)return null;const s=this.#i.decode(n.inputs,Kt(t,4));return new yL(n,n.selector,s)}static from(e){return e instanceof Ur?e:typeof e=="string"?new Ur(JSON.parse(e)):typeof e.formatJson=="function"?new Ur(e.formatJson()):typeof e.format=="function"?new Ur(e.format("json")):new Ur(e)}}const IE=BigInt(0);function Xa(i){return i??null}function tn(i){return i==null?null:i.toString()}class SE{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){Ye(this,{gasPrice:Xa(e),maxFeePerGas:Xa(t),maxPriorityFeePerGas:Xa(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:tn(e),maxFeePerGas:tn(t),maxPriorityFeePerGas:tn(n)}}}function Bh(i){const e={};i.to&&(e.to=i.to),i.from&&(e.from=i.from),i.data&&(e.data=Ce(i.data));const t="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of t)!(s in i)||i[s]==null||(e[s]=Ne(i[s],`request.${s}`));const n="type,nonce".split(/,/);for(const s of n)!(s in i)||i[s]==null||(e[s]=dt(i[s],`request.${s}`));return i.accessList&&(e.accessList=Tr(i.accessList)),i.authorizationList&&(e.authorizationList=i.authorizationList.slice()),"blockTag"in i&&(e.blockTag=i.blockTag),"enableCcipRead"in i&&(e.enableCcipRead=!!i.enableCcipRead),"customData"in i&&(e.customData=i.customData),"blobVersionedHashes"in i&&i.blobVersionedHashes&&(e.blobVersionedHashes=i.blobVersionedHashes.slice()),"kzg"in i&&(e.kzg=i.kzg),"blobWrapperVersion"in i&&(e.blobWrapperVersion=i.blobWrapperVersion),"blobs"in i&&i.blobs&&(e.blobs=i.blobs.map(s=>Ff(s)?Ce(s):Object.assign({},s))),e}class _L{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#e;constructor(e,t){this.#e=e.transactions.map(n=>typeof n!="string"?new pc(n,t):n),Ye(this,{provider:t,hash:Xa(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:Xa(e.prevRandao),extraData:e.extraData,baseFeePerGas:Xa(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#e.map(e=>typeof e=="string"?e:e.hash)}get prefetchedTransactions(){const e=this.#e.slice();return e.length===0?[]:(pe(typeof e[0]=="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,extraData:n,gasLimit:s,gasUsed:r,hash:a,miner:o,prevRandao:c,nonce:l,number:h,parentHash:u,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,timestamp:m,transactions:g}=this;return{_type:"Block",baseFeePerGas:tn(e),difficulty:tn(t),extraData:n,gasLimit:tn(s),gasUsed:tn(r),blobGasUsed:tn(this.blobGasUsed),excessBlobGas:tn(this.excessBlobGas),hash:a,miner:o,prevRandao:c,nonce:l,number:h,parentHash:u,timestamp:m,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,transactions:g}}[Symbol.iterator](){let e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#e.length}get date(){return this.timestamp==null?null:new Date(this.timestamp*1e3)}async getTransaction(e){let t;if(typeof e=="number")t=this.#e[e];else{const n=e.toLowerCase();for(const s of this.#e)if(typeof s=="string"){if(s!==n)continue;t=s;break}else{if(s.hash!==n)continue;t=s;break}}if(t==null)throw new Error("no such tx");return typeof t=="string"?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if(typeof e=="number")return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;V(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return wL(this)}}class fc{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const n=Object.freeze(e.topics.slice());Ye(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:o,transactionHash:c,transactionIndex:l}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:o,transactionHash:c,transactionIndex:l}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return pe(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return pe(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return pe(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return vL(this)}}class ME{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#e;constructor(e,t){this.#e=Object.freeze(e.logs.map(s=>new fc(s,t)));let n=IE;e.effectiveGasPrice!=null?n=e.effectiveGasPrice:e.gasPrice!=null&&(n=e.gasPrice),Ye(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#e}toJSON(){const{to:e,from:t,contractAddress:n,hash:s,index:r,blockHash:a,blockNumber:o,logsBloom:c,logs:l,status:h,root:u}=this;return{_type:"TransactionReceipt",blockHash:a,blockNumber:o,contractAddress:n,cumulativeGasUsed:tn(this.cumulativeGasUsed),from:t,gasPrice:tn(this.gasPrice),blobGasUsed:tn(this.blobGasUsed),blobGasPrice:tn(this.blobGasPrice),gasUsed:tn(this.gasUsed),hash:s,index:r,logs:l,logsBloom:c,root:u,status:h,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(e==null)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(e==null)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return TE(this)}reorderedEvent(e){return pe(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),BE(this,e)}}class pc{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#e;constructor(e,t){this.provider=t,this.blockNumber=e.blockNumber!=null?e.blockNumber:null,this.blockHash=e.blockHash!=null?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=e.maxPriorityFeePerGas!=null?e.maxPriorityFeePerGas:null,this.maxFeePerGas=e.maxFeePerGas!=null?e.maxFeePerGas:null,this.maxFeePerBlobGas=e.maxFeePerBlobGas!=null?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=e.accessList!=null?e.accessList:null,this.blobVersionedHashes=e.blobVersionedHashes!=null?e.blobVersionedHashes:null,this.authorizationList=e.authorizationList!=null?e.authorizationList:null,this.#e=-1}toJSON(){const{blockNumber:e,blockHash:t,index:n,hash:s,type:r,to:a,from:o,nonce:c,data:l,signature:h,accessList:u,blobVersionedHashes:d}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:e,blockHash:t,blobVersionedHashes:d,chainId:tn(this.chainId),data:l,from:o,gasLimit:tn(this.gasLimit),gasPrice:tn(this.gasPrice),hash:s,maxFeePerGas:tn(this.maxFeePerGas),maxPriorityFeePerGas:tn(this.maxPriorityFeePerGas),maxFeePerBlobGas:tn(this.maxFeePerBlobGas),nonce:c,signature:h,to:a,index:n,type:r,value:tn(this.value)}}async getBlock(){let e=this.blockNumber;if(e==null){const n=await this.getTransaction();n&&(e=n.blockNumber)}if(e==null)return null;const t=this.provider.getBlock(e);if(t==null)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(this.blockNumber==null){const{tx:t,blockNumber:n}=await Hn({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return t==null||t.blockNumber==null?0:n-t.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=e??1,s=t??0;let r=this.#e,a=-1,o=r===-1;const c=async()=>{if(o)return null;const{blockNumber:d,nonce:f}=await Hn({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(f<this.nonce){r=d;return}if(o)return null;const p=await this.getTransaction();if(!(p&&p.blockNumber!=null))for(a===-1&&(a=r-3,a<this.#e&&(a=this.#e));a<=d;){if(o)return null;const m=await this.provider.getBlock(a,!0);if(m==null)return;for(const g of m)if(g===this.hash)return;for(let g=0;g<m.length;g++){const A=await m.getTransaction(g);if(A.from===this.from&&A.nonce===this.nonce){if(o)return null;const _=await this.provider.getTransactionReceipt(A.hash);if(_==null||d-_.blockNumber+1<n)return;let x="replaced";A.data===this.data&&A.to===this.to&&A.value===this.value?x="repriced":A.data==="0x"&&A.from===A.to&&A.value===IE&&(x="cancelled"),pe(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:x==="replaced"||x==="cancelled",reason:x,replacement:A.replaceableTransaction(r),hash:A.hash,receipt:_})}}a++}},l=d=>{if(d==null||d.status!==0)return d;pe(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:d.to,from:d.from,data:""},receipt:d})},h=await this.provider.getTransactionReceipt(this.hash);if(n===0)return l(h);if(h){if(n===1||await h.confirmations()>=n)return l(h)}else if(await c(),n===0)return null;return await new Promise((d,f)=>{const p=[],m=()=>{p.forEach(A=>A())};if(p.push(()=>{o=!0}),s>0){const A=setTimeout(()=>{m(),f(Qt("wait for transaction timeout","TIMEOUT"))},s);p.push(()=>{clearTimeout(A)})}const g=async A=>{if(await A.confirmations()>=n){m();try{d(l(A))}catch(_){f(_)}}};if(p.push(()=>{this.provider.off(this.hash,g)}),this.provider.on(this.hash,g),r>=0){const A=async()=>{try{await c()}catch(_){if(Tn(_,"TRANSACTION_REPLACED")){m(),f(_);return}}o||this.provider.once("block",A)};p.push(()=>{this.provider.off("block",A)}),this.provider.once("block",A)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}removedEvent(){return pe(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),TE(this)}reorderedEvent(e){return pe(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),pe(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),BE(this,e)}replaceableTransaction(e){V(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new pc(this,this.provider);return t.#e=e,t}}function wL(i){return{orphan:"drop-block",hash:i.hash,number:i.number}}function BE(i,e){return{orphan:"reorder-transaction",tx:i,other:e}}function TE(i){return{orphan:"drop-transaction",tx:i}}function vL(i){return{orphan:"drop-log",log:{transactionHash:i.transactionHash,blockHash:i.blockHash,blockNumber:i.blockNumber,address:i.address,data:i.data,topics:Object.freeze(i.topics.slice()),index:i.index}}}class yp extends fc{interface;fragment;args;constructor(e,t,n){super(e,e.provider);const s=t.decodeEventLog(n,e.data,e.topics);Ye(this,{args:s,fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class RE extends fc{error;constructor(e,t){super(e,e.provider),Ye(this,{error:t})}}class CL extends ME{#e;constructor(e,t,n){super(n,t),this.#e=e}get logs(){return super.logs.map(e=>{const t=e.topics.length?this.#e.getEvent(e.topics[0]):null;if(t)try{return new yp(e,this.#e,t)}catch(n){return new RE(e,n)}return e})}}class _p extends pc{#e;constructor(e,t,n){super(n,t),this.#e=e}async wait(e,t){const n=await super.wait(e,t);return n==null?null:new CL(this.#e,this.provider,n)}}class FE extends dx{log;constructor(e,t,n,s){super(e,t,n),Ye(this,{log:s})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class IL extends FE{constructor(e,t,n,s,r){super(e,t,n,new yp(r,e.interface,s));const a=e.interface.decodeEventLog(s,this.log.data,this.log.topics);Ye(this,{args:a,fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const NE=BigInt(0);function DE(i){return i&&typeof i.call=="function"}function LE(i){return i&&typeof i.estimateGas=="function"}function Th(i){return i&&typeof i.resolveName=="function"}function PE(i){return i&&typeof i.sendTransaction=="function"}function kE(i){if(i!=null){if(Th(i))return i;if(i.provider)return i.provider}}class SL{#e;fragment;constructor(e,t,n){if(Ye(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const s=Or(e.runner,"resolveName"),r=Th(s)?s:null;this.#e=(async function(){const a=await Promise.all(t.inputs.map((o,c)=>n[c]==null?null:o.walkAsync(n[c],(h,u)=>h==="address"?Array.isArray(u)?Promise.all(u.map(d=>Wn(d,r))):Wn(u,r):u)));return e.interface.encodeFilterTopics(t,a)})()}getTopicFilter(){return this.#e}}function Or(i,e){return i==null?null:typeof i[e]=="function"?i:i.provider&&typeof i.provider[e]=="function"?i.provider:null}function Qr(i){return i==null?null:i.provider||null}async function UE(i,e){const t=jt.dereference(i,"overrides");V(typeof t=="object","invalid overrides parameter","overrides",i);const n=Bh(t);return V(n.to==null||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",n.to),V(n.data==null||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",n.data),n.from&&(n.from=n.from),n}async function ML(i,e,t){const n=Or(i,"resolveName"),s=Th(n)?n:null;return await Promise.all(e.map((r,a)=>r.walkAsync(t[a],(o,c)=>(c=jt.dereference(c,o),o==="address"?Wn(c,s):c))))}function BL(i){const e=async function(a){const o=await UE(a,["data"]);o.to=await i.getAddress(),o.from&&(o.from=await Wn(o.from,kE(i.runner)));const c=i.interface,l=Ne(o.value||NE,"overrides.value")===NE,h=(o.data||"0x")==="0x";c.fallback&&!c.fallback.payable&&c.receive&&!h&&!l&&V(!1,"cannot send data to receive or send value to non-payable fallback","overrides",a),V(c.fallback||h,"cannot send data to receive-only contract","overrides.data",o.data);const u=c.receive||c.fallback&&c.fallback.payable;return V(u||l,"cannot send value to non-payable fallback","overrides.value",o.value),V(c.fallback||h,"cannot send data to receive-only contract","overrides.data",o.data),o},t=async function(a){const o=Or(i.runner,"call");pe(DE(o),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const c=await e(a);try{return await o.call(c)}catch(l){throw Rf(l)&&l.data?i.interface.makeError(l.data,c):l}},n=async function(a){const o=i.runner;pe(PE(o),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const c=await o.sendTransaction(await e(a)),l=Qr(i.runner);return new _p(i.interface,l,c)},s=async function(a){const o=Or(i.runner,"estimateGas");return pe(LE(o),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await o.estimateGas(await e(a))},r=async a=>await n(a);return Ye(r,{_contract:i,estimateGas:s,populateTransaction:e,send:n,staticCall:t}),r}function TL(i,e){const t=function(...l){const h=i.interface.getFunction(e,l);return pe(h,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:l}}),h},n=async function(...l){const h=t(...l);let u={};if(h.inputs.length+1===l.length&&(u=await UE(l.pop()),u.from&&(u.from=await Wn(u.from,kE(i.runner)))),h.inputs.length!==l.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const d=await ML(i.runner,h.inputs,l);return Object.assign({},u,await Hn({to:i.getAddress(),data:i.interface.encodeFunctionData(h,d)}))},s=async function(...l){const h=await o(...l);return h.length===1?h[0]:h},r=async function(...l){const h=i.runner;pe(PE(h),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const u=await h.sendTransaction(await n(...l)),d=Qr(i.runner);return new _p(i.interface,d,u)},a=async function(...l){const h=Or(i.runner,"estimateGas");return pe(LE(h),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await h.estimateGas(await n(...l))},o=async function(...l){const h=Or(i.runner,"call");pe(DE(h),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const u=await n(...l);let d="0x";try{d=await h.call(u)}catch(p){throw Rf(p)&&p.data?i.interface.makeError(p.data,u):p}const f=t(...l);return i.interface.decodeFunctionResult(f,d)},c=async(...l)=>t(...l).constant?await s(...l):await r(...l);return Ye(c,{name:i.interface.getFunctionName(e),_contract:i,_key:e,getFragment:t,estimateGas:a,populateTransaction:n,send:r,staticCall:s,staticCallResult:o}),Object.defineProperty(c,"fragment",{configurable:!1,enumerable:!0,get:()=>{const l=i.interface.getFunction(e);return pe(l,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),l}}),c}function RL(i,e){const t=function(...s){const r=i.interface.getEvent(e,s);return pe(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:s}}),r},n=function(...s){return new SL(i,t(...s),s)};return Ye(n,{name:i.interface.getEventName(e),_contract:i,_key:e,getFragment:t}),Object.defineProperty(n,"fragment",{configurable:!1,enumerable:!0,get:()=>{const s=i.interface.getEvent(e);return pe(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),s}}),n}const Rh=Symbol.for("_ethersInternal_contract"),OE=new WeakMap;function FL(i,e){OE.set(i[Rh],e)}function ni(i){return OE.get(i[Rh])}function NL(i){return i&&typeof i=="object"&&"getTopicFilter"in i&&typeof i.getTopicFilter=="function"&&i.fragment}async function wp(i,e){let t,n=null;if(Array.isArray(e)){const r=function(a){if(Pt(a,32))return a;const o=i.interface.getEvent(a);return V(o,"unknown fragment","name",a),o.topicHash};t=e.map(a=>a==null?null:Array.isArray(a)?a.map(r):r(a))}else e==="*"?t=[null]:typeof e=="string"?Pt(e,32)?t=[e]:(n=i.interface.getEvent(e),V(n,"unknown fragment","event",e),t=[n.topicHash]):NL(e)?t=await e.getTopicFilter():"fragment"in e?(n=e.fragment,t=[n.topicHash]):V(!1,"unknown event name","event",e);t=t.map(r=>{if(r==null)return null;if(Array.isArray(r)){const a=Array.from(new Set(r.map(o=>o.toLowerCase())).values());return a.length===1?a[0]:(a.sort(),a)}return r.toLowerCase()});const s=t.map(r=>r==null?"null":Array.isArray(r)?r.join("|"):r).join("&");return{fragment:n,tag:s,topics:t}}async function Ac(i,e){const{subs:t}=ni(i);return t.get((await wp(i,e)).tag)||null}async function QE(i,e,t){const n=Qr(i.runner);pe(n,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:r,topics:a}=await wp(i,t),{addr:o,subs:c}=ni(i);let l=c.get(r);if(!l){const u={address:o||i,topics:a},d=g=>{let A=s;if(A==null)try{A=i.interface.getEvent(g.topics[0])}catch{}if(A){const _=A,x=s?i.interface.decodeEventLog(s,g.data,g.topics):[];Cp(i,t,x,E=>new IL(i,E,t,_,g))}else Cp(i,t,[],_=>new FE(i,_,t,g))};let f=[];l={tag:r,listeners:[],start:()=>{f.length||f.push(n.on(u,d))},stop:async()=>{if(f.length==0)return;let g=f;f=[],await Promise.all(g),n.off(u,d)}},c.set(r,l)}return l}let vp=Promise.resolve();async function DL(i,e,t,n){await vp;const s=await Ac(i,e);if(!s)return!1;const r=s.listeners.length;return s.listeners=s.listeners.filter(({listener:a,once:o})=>{const c=Array.from(t);n&&c.push(n(o?null:a));try{a.call(i,...c)}catch{}return!o}),s.listeners.length===0&&(s.stop(),ni(i).subs.delete(s.tag)),r>0}async function Cp(i,e,t,n){try{await vp}catch{}const s=DL(i,e,t,n);return vp=s,await s}const Fh=["then"];class gc{target;interface;runner;filters;[Rh];fallback;constructor(e,t,n,s){V(typeof e=="string"||bb(e),"invalid value for Contract target","target",e),n==null&&(n=null);const r=Ur.from(t);Ye(this,{target:e,runner:n,interface:r}),Object.defineProperty(this,Rh,{value:{}});let a,o=null,c=null;if(s){const u=Qr(n);c=new _p(this.interface,u,s)}let l=new Map;if(typeof e=="string")if(Pt(e))o=e,a=Promise.resolve(e);else{const u=Or(n,"resolveName");if(!Th(u))throw Qt("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});a=u.resolveName(e).then(d=>{if(d==null)throw Qt("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return ni(this).addr=d,d})}else a=e.getAddress().then(u=>{if(u==null)throw new Error("TODO");return ni(this).addr=u,u});FL(this,{addrPromise:a,addr:o,deployTx:c,subs:l});const h=new Proxy({},{get:(u,d,f)=>{if(typeof d=="symbol"||Fh.indexOf(d)>=0)return Reflect.get(u,d,f);try{return this.getEvent(d)}catch(p){if(!Tn(p,"INVALID_ARGUMENT")||p.argument!=="key")throw p}},has:(u,d)=>Fh.indexOf(d)>=0?Reflect.has(u,d):Reflect.has(u,d)||this.interface.hasEvent(String(d))});return Ye(this,{filters:h}),Ye(this,{fallback:r.receive||r.fallback?BL(this):null}),new Proxy(this,{get:(u,d,f)=>{if(typeof d=="symbol"||d in u||Fh.indexOf(d)>=0)return Reflect.get(u,d,f);try{return u.getFunction(d)}catch(p){if(!Tn(p,"INVALID_ARGUMENT")||p.argument!=="key")throw p}},has:(u,d)=>typeof d=="symbol"||d in u||Fh.indexOf(d)>=0?Reflect.has(u,d):u.interface.hasFunction(d)})}connect(e){return new gc(this.target,this.interface,e)}attach(e){return new gc(e,this.interface,this.runner)}async getAddress(){return await ni(this).addrPromise}async getDeployedCode(){const e=Qr(this.runner);pe(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return t==="0x"?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(await this.getDeployedCode()!=null)return this;const n=Qr(this.runner);return pe(n!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((s,r)=>{const a=async()=>{try{if(await this.getDeployedCode()!=null)return s(this);n.once("block",a)}catch(o){r(o)}};a()})}deploymentTransaction(){return ni(this).deployTx}getFunction(e){return typeof e!="string"&&(e=e.format()),TL(this,e)}getEvent(e){return typeof e!="string"&&(e=e.format()),RL(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){t==null&&(t=0),n==null&&(n="latest");const{addr:s,addrPromise:r}=ni(this),a=s||await r,{fragment:o,topics:c}=await wp(this,e),l={address:a,topics:c,fromBlock:t,toBlock:n},h=Qr(this.runner);return pe(h,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await h.getLogs(l)).map(u=>{let d=o;if(d==null)try{d=this.interface.getEvent(u.topics[0])}catch{}if(d)try{return new yp(u,this.interface,d)}catch(f){return new RE(u,f)}return new fc(u,h)})}async on(e,t){const n=await QE(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await QE(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await Cp(this,e,t,null)}async listenerCount(e){if(e){const s=await Ac(this,e);return s?s.listeners.length:0}const{subs:t}=ni(this);let n=0;for(const{listeners:s}of t.values())n+=s.length;return n}async listeners(e){if(e){const s=await Ac(this,e);return s?s.listeners.map(({listener:r})=>r):[]}const{subs:t}=ni(this);let n=[];for(const{listeners:s}of t.values())n=n.concat(s.map(({listener:r})=>r));return n}async off(e,t){const n=await Ac(this,e);if(!n)return this;if(t){const s=n.listeners.map(({listener:r})=>r).indexOf(t);s>=0&&n.listeners.splice(s,1)}return(t==null||n.listeners.length===0)&&(n.stop(),ni(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await Ac(this,e);if(!t)return this;t.stop(),ni(this).subs.delete(t.tag)}else{const{subs:t}=ni(this);for(const{tag:n,stop:s}of t.values())s(),t.delete(n)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){class t extends gc{constructor(s,r=null){super(s,e,r)}}return t}static from(e,t,n){return n==null&&(n=null),new this(e,t,n)}}function LL(){return gc}class Gr extends LL(){}function Ip(i){return i.match(/^ipfs:\/\/ipfs\//i)?i=i.substring(12):i.match(/^ipfs:\/\//i)?i=i.substring(7):V(!1,"unsupported IPFS format","link",i),`https://gateway.ipfs.io/ipfs/${i}`}class PL{name;constructor(e){Ye(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw new Error("unsupported coin")}async decodeAddress(e,t){throw new Error("unsupported coin")}}const GE=new RegExp("^(ipfs)://(.*)$","i"),HE=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),GE,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class Ya{provider;address;name;#e;#t;constructor(e,t,n){Ye(this,{provider:e,address:t,name:n}),this.#e=null,this.#t=new Gr(t,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],e)}async supportsWildcard(){return this.#e==null&&(this.#e=(async()=>{try{return await this.#t.supportsInterface("0x9061b923")}catch(e){if(Tn(e,"CALL_EXCEPTION"))return!1;throw this.#e=null,e}})()),await this.#e}async#n(e,t){t=(t||[]).slice();const n=this.#t.interface;t.unshift(mp(this.name));let s=null;await this.supportsWildcard()&&(s=n.getFunction(e),pe(s,"missing fragment","UNKNOWN_ERROR",{info:{funcName:e}}),t=[$D(this.name,255),n.encodeFunctionData(s,t)],e="resolve(bytes,bytes)"),t.push({enableCcipRead:!0});try{const r=await this.#t[e](...t);return s?n.decodeFunctionResult(s,r)[0]:r}catch(r){if(!Tn(r,"CALL_EXCEPTION"))throw r}return null}async getAddress(e){if(e==null&&(e=60),e===60)try{const r=await this.#n("addr(bytes32)");return r==null||r===rc?null:r}catch(r){if(Tn(r,"CALL_EXCEPTION"))return null;throw r}if(e>=0&&e<2147483648){let r=e+2147483648;const a=await this.#n("addr(bytes32,uint)",[r]);if(Pt(a,20))return St(a)}let t=null;for(const r of this.provider.plugins)if(r instanceof PL&&r.supportsCoinType(e)){t=r;break}if(t==null)return null;const n=await this.#n("addr(bytes32,uint)",[e]);if(n==null||n==="0x")return null;const s=await t.decodeAddress(e,n);if(s!=null)return s;pe(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${e})`,info:{coinType:e,data:n}})}async getText(e){const t=await this.#n("text(bytes32,string)",[e]);return t==null||t==="0x"?null:t}async getContentHash(){const e=await this.#n("contenthash(bytes32)");if(e==null||e==="0x")return null;const t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const s=t[1]==="e3010170"?"ipfs":"ipns",r=parseInt(t[4],16);if(t[5].length===r*2)return`${s}://${nF("0x"+t[2])}`}const n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&n[1].length===64)return`bzz://${n[1]}`;pe(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:e}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const e=[{type:"name",value:this.name}];try{const t=await this.getText("avatar");if(t==null)return e.push({type:"!avatar",value:""}),{url:null,linkage:e};e.push({type:"avatar",value:t});for(let n=0;n<HE.length;n++){const s=t.match(HE[n]);if(s==null)continue;const r=s[1].toLowerCase();switch(r){case"https":case"data":return e.push({type:"url",value:t}),{linkage:e,url:t};case"ipfs":{const a=Ip(t);return e.push({type:"ipfs",value:t}),e.push({type:"url",value:a}),{linkage:e,url:a}}case"erc721":case"erc1155":{const a=r==="erc721"?"tokenURI(uint256)":"uri(uint256)";e.push({type:r,value:t});const o=await this.getAddress();if(o==null)return e.push({type:"!owner",value:""}),{url:null,linkage:e};const c=(s[2]||"").split("/");if(c.length!==2)return e.push({type:`!${r}caip`,value:s[2]||""}),{url:null,linkage:e};const l=c[1],h=new Gr(c[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if(r==="erc721"){const m=await h.ownerOf(l);if(o!==m)return e.push({type:"!owner",value:m}),{url:null,linkage:e};e.push({type:"owner",value:m})}else if(r==="erc1155"){const m=await h.balanceOf(o,l);if(!m)return e.push({type:"!balance",value:"0"}),{url:null,linkage:e};e.push({type:"balance",value:m.toString()})}let u=await h[a](l);if(u==null||u==="0x")return e.push({type:"!metadata-url",value:""}),{url:null,linkage:e};e.push({type:"metadata-url-base",value:u}),r==="erc1155"&&(u=u.replace("{id}",Ks(l,32).substring(2)),e.push({type:"metadata-url-expanded",value:u})),u.match(/^ipfs:/i)&&(u=Ip(u)),e.push({type:"metadata-url",value:u});let d={};const f=await new zi(u).send();f.assertOk();try{d=f.bodyJson}catch{try{e.push({type:"!metadata",value:f.bodyText})}catch{const A=f.body;return A&&e.push({type:"!metadata",value:Ce(A)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!d)return e.push({type:"!metadata",value:""}),{url:null,linkage:e};e.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if(typeof p!="string")return e.push({type:"!imageUrl",value:""}),{url:null,linkage:e};if(!p.match(/^(https:\/\/|data:)/i)){if(p.match(GE)==null)return e.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:e};e.push({type:"imageUrl-ipfs",value:p}),p=Ip(p)}return e.push({type:"url",value:p}),{linkage:e,url:p}}}}}catch{}return{linkage:e,url:null}}static async getEnsAddress(e){const t=await e.getNetwork(),n=t.getPlugin("org.ethers.plugins.network.Ens");return pe(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:t}}),n.address}static async#i(e,t){const n=await Ya.getEnsAddress(e);try{const r=await new Gr(n,["function resolver(bytes32) view returns (address)"],e).resolver(mp(t),{enableCcipRead:!0});return r===rc?null:r}catch(s){throw s}return null}static async fromName(e,t){let n=t;for(;;){if(n===""||n==="."||t!=="eth"&&n==="eth")return null;const s=await Ya.#i(e,n);if(s!=null){const r=new Ya(e,s,t);return n!==t&&!await r.supportsWildcard()?null:r}n=n.split(".").slice(1).join(".")}}}const zE=BigInt(0);function bt(i,e){return(function(t){return t==null?e:i(t)})}function mc(i,e){return(t=>{if(e&&t==null)return null;if(!Array.isArray(t))throw new Error("not an array");return t.map(n=>i(n))})}function xc(i,e){return(t=>{const n={};for(const s in i){let r=s;if(e&&s in e&&!(r in t)){for(const a of e[s])if(a in t){r=a;break}}try{const a=i[s](t[r]);a!==void 0&&(n[s]=a)}catch(a){const o=a instanceof Error?a.message:"not-an-error";pe(!1,`invalid value for value.${s} (${o})`,"BAD_DATA",{value:t})}}return n})}function kL(i){switch(i){case!0:case"true":return!0;case!1:case"false":return!1}V(!1,`invalid boolean; ${JSON.stringify(i)}`,"value",i)}function Ja(i){return V(Pt(i,!0),"invalid data","value",i),i}function Rn(i){return V(Pt(i,32),"invalid hash","value",i),i}const UL=xc({address:St,blockHash:Rn,blockNumber:dt,data:Ja,index:dt,removed:bt(kL,!1),topics:mc(Rn),transactionHash:Rn,transactionIndex:dt},{index:["logIndex"]});function OL(i){return UL(i)}const QL=xc({hash:bt(Rn),parentHash:Rn,parentBeaconBlockRoot:bt(Rn,null),number:dt,timestamp:dt,nonce:bt(Ja),difficulty:Ne,gasLimit:Ne,gasUsed:Ne,stateRoot:bt(Rn,null),receiptsRoot:bt(Rn,null),blobGasUsed:bt(Ne,null),excessBlobGas:bt(Ne,null),miner:bt(St),prevRandao:bt(Rn,null),extraData:Ja,baseFeePerGas:bt(Ne)},{prevRandao:["mixHash"]});function GL(i){const e=QL(i);return e.transactions=i.transactions.map(t=>typeof t=="string"?t:VE(t)),e}const HL=xc({transactionIndex:dt,blockNumber:dt,transactionHash:Rn,address:St,topics:mc(Rn),data:Ja,index:dt,blockHash:Rn},{index:["logIndex"]});function zL(i){return HL(i)}const VL=xc({to:bt(St,null),from:bt(St,null),contractAddress:bt(St,null),index:dt,root:bt(Ce),gasUsed:Ne,blobGasUsed:bt(Ne,null),logsBloom:bt(Ja),blockHash:Rn,hash:Rn,logs:mc(zL),blockNumber:dt,cumulativeGasUsed:Ne,effectiveGasPrice:bt(Ne),blobGasPrice:bt(Ne,null),status:bt(dt),type:bt(dt,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function WL(i){return VL(i)}function VE(i){i.to&&Ne(i.to)===zE&&(i.to="0x0000000000000000000000000000000000000000");const e=xc({hash:Rn,index:bt(dt,void 0),type:t=>t==="0x"||t==null?0:dt(t),accessList:bt(Tr,null),blobVersionedHashes:bt(mc(Rn,!0),null),authorizationList:bt(mc(t=>{let n;if(t.signature)n=t.signature;else{let s=t.yParity;s==="0x1b"?s=0:s==="0x1c"&&(s=1),n=Object.assign({},t,{yParity:s})}return{address:St(t.address),chainId:Ne(t.chainId),nonce:Ne(t.nonce),signature:Vt.from(n)}},!1),null),blockHash:bt(Rn,null),blockNumber:bt(dt,null),transactionIndex:bt(dt,null),from:St,gasPrice:bt(Ne),maxPriorityFeePerGas:bt(Ne),maxFeePerGas:bt(Ne),maxFeePerBlobGas:bt(Ne,null),gasLimit:Ne,to:bt(St,null),value:Ne,nonce:dt,data:Ja,creates:bt(St,null),chainId:bt(Ne,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(i);if(e.to==null&&e.creates==null&&(e.creates=DN(e)),(i.type===1||i.type===2)&&i.accessList==null&&(e.accessList=[]),i.signature?e.signature=Vt.from(i.signature):e.signature=Vt.from(i),e.chainId==null){const t=e.signature.legacyChainId;t!=null&&(e.chainId=t)}return e.blockHash&&Ne(e.blockHash)===zE&&(e.blockHash=null),e}const qL="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class bc{name;constructor(e){Ye(this,{name:e})}clone(){return new bc(this.name)}}class Nh extends bc{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(e,t){e==null&&(e=0),super(`org.ethers.network.plugins.GasCost#${e||0}`);const n={effectiveBlock:e};function s(r,a){let o=(t||{})[r];o==null&&(o=a),V(typeof o=="number",`invalud value for ${r}`,"costs",t),n[r]=o}s("txBase",21e3),s("txCreate",32e3),s("txDataZero",4),s("txDataNonzero",16),s("txAccessListStorageKey",1900),s("txAccessListAddress",2400),Ye(this,n)}clone(){return new Nh(this.effectiveBlock,this)}}class Dh extends bc{address;targetNetwork;constructor(e,t){super("org.ethers.plugins.network.Ens"),Ye(this,{address:e||qL,targetNetwork:t??1})}clone(){return new Dh(this.address,this.targetNetwork)}}class KL extends bc{#e;#t;get url(){return this.#e}get processFunc(){return this.#t}constructor(e,t){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#e=e,this.#t=t}clone(){return this}}const Sp=new Map;class ii{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=Ne(t),this.#n=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#e}set name(e){this.#e=e}get chainId(){return this.#t}set chainId(e){this.#t=Ne(e,"chainId")}matches(e){if(e==null)return!1;if(typeof e=="string"){try{return this.chainId===Ne(e)}catch{}return this.name===e}if(typeof e=="number"||typeof e=="bigint"){try{return this.chainId===Ne(e)}catch{}return!1}if(typeof e=="object"){if(e.chainId!=null){try{return this.chainId===Ne(e.chainId)}catch{}return!1}return e.name!=null?this.name===e.name:!1}return!1}get plugins(){return Array.from(this.#n.values())}attachPlugin(e){if(this.#n.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#n.set(e.name,e.clone()),this}getPlugin(e){return this.#n.get(e)||null}getPlugins(e){return this.plugins.filter(t=>t.name.split("#")[0]===e)}clone(){const e=new ii(this.name,this.chainId);return this.plugins.forEach(t=>{e.attachPlugin(t.clone())}),e}computeIntrinsicGas(e){const t=this.getPlugin("org.ethers.plugins.network.GasCost")||new Nh;let n=t.txBase;if(e.to==null&&(n+=t.txCreate),e.data)for(let s=2;s<e.data.length;s+=2)e.data.substring(s,s+2)==="00"?n+=t.txDataZero:n+=t.txDataNonzero;if(e.accessList){const s=Tr(e.accessList);for(const r in s)n+=t.txAccessListAddress+t.txAccessListStorageKey*s[r].storageKeys.length}return n}static from(e){if(jL(),e==null)return ii.from("mainnet");if(typeof e=="number"&&(e=BigInt(e)),typeof e=="string"||typeof e=="bigint"){const t=Sp.get(e);if(t)return t();if(typeof e=="bigint")return new ii("unknown",e);V(!1,"unknown network","network",e)}if(typeof e.clone=="function")return e.clone();if(typeof e=="object"){V(typeof e.name=="string"&&typeof e.chainId=="number","invalid network object name or chainId","network",e);const t=new ii(e.name,e.chainId);return(e.ensAddress||e.ensNetwork!=null)&&t.attachPlugin(new Dh(e.ensAddress,e.ensNetwork)),t}V(!1,"invalid network","network",e)}static register(e,t){typeof e=="number"&&(e=BigInt(e));const n=Sp.get(e);n&&V(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",e),Sp.set(e,t)}}function WE(i,e){const t=String(i);if(!t.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${i}`);const n=t.split(".");if(n.length===1&&n.push(""),n.length!==2)throw new Error(`invalid gwei value: ${i}`);for(;n[1].length<e;)n[1]+="0";if(n[1].length>9){let s=BigInt(n[1].substring(0,9));n[1].substring(9).match(/^0+$/)||s++,n[1]=s.toString()}return BigInt(n[0]+n[1])}function qE(i){return new KL(i,async(e,t,n)=>{n.setHeader("User-Agent","ethers");let s;try{const[r,a]=await Promise.all([n.send(),e()]);s=r;const o=s.bodyJson.standard;return{gasPrice:a.gasPrice,maxFeePerGas:WE(o.maxFee,9),maxPriorityFeePerGas:WE(o.maxPriorityFee,9)}}catch(r){pe(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:s,error:r})}})}let KE=!1;function jL(){if(KE)return;KE=!0;function i(e,t,n){const s=function(){const r=new ii(e,t);return n.ensNetwork!=null&&r.attachPlugin(new Dh(null,n.ensNetwork)),r.attachPlugin(new Nh),(n.plugins||[]).forEach(a=>{r.attachPlugin(a)}),r};ii.register(e,s),ii.register(t,s),n.altNames&&n.altNames.forEach(r=>{ii.register(r,s)})}i("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),i("ropsten",3,{ensNetwork:3}),i("rinkeby",4,{ensNetwork:4}),i("goerli",5,{ensNetwork:5}),i("kovan",42,{ensNetwork:42}),i("sepolia",11155111,{ensNetwork:11155111}),i("holesky",17e3,{ensNetwork:17e3}),i("classic",61,{}),i("classicKotti",6,{}),i("arbitrum",42161,{ensNetwork:1}),i("arbitrum-goerli",421613,{}),i("arbitrum-sepolia",421614,{}),i("base",8453,{ensNetwork:1}),i("base-goerli",84531,{}),i("base-sepolia",84532,{}),i("bnb",56,{ensNetwork:1}),i("bnbt",97,{}),i("filecoin",314,{}),i("filecoin-calibration",314159,{}),i("linea",59144,{ensNetwork:1}),i("linea-goerli",59140,{}),i("linea-sepolia",59141,{}),i("matic",137,{ensNetwork:1,plugins:[qE("https://gasstation.polygon.technology/v2")]}),i("matic-amoy",80002,{}),i("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[qE("https://gasstation-testnet.polygon.technology/v2")]}),i("optimism",10,{ensNetwork:1,plugins:[]}),i("optimism-goerli",420,{}),i("optimism-sepolia",11155420,{}),i("xdai",100,{ensNetwork:1})}function Mp(i){return JSON.parse(JSON.stringify(i))}class XL{#e;#t;#n;#i;constructor(e){this.#e=e,this.#t=null,this.#n=4e3,this.#i=-2}get pollingInterval(){return this.#n}set pollingInterval(e){this.#n=e}async#s(){try{const e=await this.#e.getBlockNumber();if(this.#i===-2){this.#i=e;return}if(e!==this.#i){for(let t=this.#i+1;t<=e;t++){if(this.#t==null)return;await this.#e.emit("block",t)}this.#i=e}}catch{}this.#t!=null&&(this.#t=this.#e._setTimeout(this.#s.bind(this),this.#n))}start(){this.#t||(this.#t=this.#e._setTimeout(this.#s.bind(this),this.#n),this.#s())}stop(){this.#t&&(this.#e._clearTimeout(this.#t),this.#t=null)}pause(e){this.stop(),e&&(this.#i=-2)}resume(){this.start()}}class Bp{#e;#t;#n;constructor(e){this.#e=e,this.#n=!1,this.#t=t=>{this._poll(t,this.#e)}}async _poll(e,t){throw new Error("sub-classes must override this")}start(){this.#n||(this.#n=!0,this.#t(-2),this.#e.on("block",this.#t))}stop(){this.#n&&(this.#n=!1,this.#e.off("block",this.#t))}pause(e){this.stop()}resume(){this.start()}}class YL extends Bp{#e;#t;constructor(e,t){super(e),this.#e=t,this.#t=-2}pause(e){e&&(this.#t=-2),super.pause(e)}async _poll(e,t){const n=await t.getBlock(this.#e);n!=null&&(this.#t===-2?this.#t=n.number:n.number>this.#t&&(t.emit(this.#e,n.number),this.#t=n.number))}}class JL extends Bp{#e;constructor(e,t){super(e),this.#e=Mp(t)}async _poll(e,t){throw new Error("@TODO")}}class ZL extends Bp{#e;constructor(e,t){super(e),this.#e=t}async _poll(e,t){const n=await t.getTransactionReceipt(this.#e);n&&t.emit(this.#e,n)}}class Tp{#e;#t;#n;#i;#s;constructor(e,t){this.#e=e,this.#t=Mp(t),this.#n=this.#a.bind(this),this.#i=!1,this.#s=-2}async#a(e){if(this.#s===-2)return;const t=Mp(this.#t);t.fromBlock=this.#s+1,t.toBlock=e;const n=await this.#e.getLogs(t);if(n.length===0){this.#s<e-60&&(this.#s=e-60);return}for(const s of n)this.#e.emit(this.#t,s),this.#s=s.blockNumber}start(){this.#i||(this.#i=!0,this.#s===-2&&this.#e.getBlockNumber().then(e=>{this.#s=e}),this.#e.on("block",this.#n))}stop(){this.#i&&(this.#i=!1,this.#e.off("block",this.#n))}pause(e){this.stop(),e&&(this.#s=-2)}resume(){this.start()}}const $L=BigInt(2),e2=10;function Lh(i){return i&&typeof i.then=="function"}function Ph(i,e){return i+":"+JSON.stringify(e,(t,n)=>{if(n==null)return"null";if(typeof n=="bigint")return`bigint:${n.toString()}`;if(typeof n=="string")return n.toLowerCase();if(typeof n=="object"&&!Array.isArray(n)){const s=Object.keys(n);return s.sort(),s.reduce((r,a)=>(r[a]=n[a],r),{})}return n})}class jE{name;constructor(e){Ye(this,{name:e})}start(){}stop(){}pause(e){}resume(){}}function t2(i){return JSON.parse(JSON.stringify(i))}function Rp(i){return i=Array.from(new Set(i).values()),i.sort(),i}async function Fp(i,e){if(i==null)throw new Error("invalid event");if(Array.isArray(i)&&(i={topics:i}),typeof i=="string")switch(i){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:i,tag:i}}if(Pt(i,32)){const t=i.toLowerCase();return{type:"transaction",tag:Ph("tx",{hash:t}),hash:t}}if(i.orphan){const t=i;return{type:"orphan",tag:Ph("orphan",t),filter:t2(t)}}if(i.address||i.topics){const t=i,n={topics:(t.topics||[]).map(s=>s==null?null:Array.isArray(s)?Rp(s.map(r=>r.toLowerCase())):s.toLowerCase())};if(t.address){const s=[],r=[],a=o=>{Pt(o)?s.push(o):r.push((async()=>{s.push(await Wn(o,e))})())};Array.isArray(t.address)?t.address.forEach(a):a(t.address),r.length&&await Promise.all(r),n.address=Rp(s.map(o=>o.toLowerCase()))}return{filter:n,tag:Ph("event",n),type:"event"}}V(!1,"unknown ProviderEvent","event",i)}function Np(){return new Date().getTime()}const n2={cacheTimeout:250,pollingInterval:4e3};class i2{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;constructor(e,t){if(this.#A=Object.assign({},n2,t||{}),e==="any")this.#a=!0,this.#s=null;else if(e){const n=ii.from(e);this.#a=!1,this.#s=Promise.resolve(n),setTimeout(()=>{this.emit("network",n,null)},0)}else this.#a=!1,this.#s=null;this.#o=-1,this.#r=new Map,this.#e=new Map,this.#t=new Map,this.#n=null,this.#i=!1,this.#f=1,this.#l=new Map,this.#p=!1}get pollingInterval(){return this.#A.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#t.values())}attachPlugin(e){if(this.#t.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#t.set(e.name,e.connect(this)),this}getPlugin(e){return this.#t.get(e)||null}get disableCcipRead(){return this.#p}set disableCcipRead(e){this.#p=!!e}async#c(e){const t=this.#A.cacheTimeout;if(t<0)return await this._perform(e);const n=Ph(e.method,e);let s=this.#r.get(n);return s||(s=this._perform(e),this.#r.set(n,s),setTimeout(()=>{this.#r.get(n)===s&&this.#r.delete(n)},t)),await s}async ccipReadFetch(e,t,n){if(this.disableCcipRead||n.length===0||e.to==null)return null;const s=e.to.toLowerCase(),r=t.toLowerCase(),a=[];for(let o=0;o<n.length;o++){const c=n[o],l=c.replace("{sender}",s).replace("{data}",r),h=new zi(l);c.indexOf("{data}")===-1&&(h.body={data:r,sender:s}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:h,index:o,urls:n});let u="unknown error",d;try{d=await h.send()}catch(f){a.push(f.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:h,result:{error:f}});continue}try{const f=d.bodyJson;if(f.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:h,result:f}),f.data;f.message&&(u=f.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:h,result:f})}catch{}pe(d.statusCode<400||d.statusCode>=500,`response not found during CCIP fetch: ${u}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:e,info:{url:c,errorMessage:u}}),a.push(u)}pe(!1,`error encountered during CCIP fetch: ${a.map(o=>JSON.stringify(o)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:e,info:{urls:n,errorMessages:a}})}_wrapBlock(e,t){return new _L(GL(e),this)}_wrapLog(e,t){return new fc(OL(e),this)}_wrapTransactionReceipt(e,t){return new ME(WL(e),this)}_wrapTransactionResponse(e,t){return new pc(VE(e),this)}_detectNetwork(){pe(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(e){pe(!1,`unsupported method: ${e.method}`,"UNSUPPORTED_OPERATION",{operation:e.method,info:e})}async getBlockNumber(){const e=dt(await this.#c({method:"getBlockNumber"}),"%response");return this.#o>=0&&(this.#o=e),e}_getAddress(e){return Wn(e,this)}_getBlockTag(e){if(e==null)return"latest";switch(e){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return e}if(Pt(e))return Pt(e,32)?e:Ri(e);if(typeof e=="bigint"&&(e=dt(e,"blockTag")),typeof e=="number")return e>=0?Ri(e):this.#o>=0?Ri(this.#o+e):this.getBlockNumber().then(t=>Ri(t+e));V(!1,"invalid blockTag","blockTag",e)}_getFilter(e){const t=(e.topics||[]).map(c=>c==null?null:Array.isArray(c)?Rp(c.map(l=>l.toLowerCase())):c.toLowerCase()),n="blockHash"in e?e.blockHash:void 0,s=(c,l,h)=>{let u;switch(c.length){case 0:break;case 1:u=c[0];break;default:c.sort(),u=c}if(n&&(l!=null||h!=null))throw new Error("invalid filter");const d={};return u&&(d.address=u),t.length&&(d.topics=t),l&&(d.fromBlock=l),h&&(d.toBlock=h),n&&(d.blockHash=n),d};let r=[];if(e.address)if(Array.isArray(e.address))for(const c of e.address)r.push(this._getAddress(c));else r.push(this._getAddress(e.address));let a;"fromBlock"in e&&(a=this._getBlockTag(e.fromBlock));let o;return"toBlock"in e&&(o=this._getBlockTag(e.toBlock)),r.filter(c=>typeof c!="string").length||a!=null&&typeof a!="string"||o!=null&&typeof o!="string"?Promise.all([Promise.all(r),a,o]).then(c=>s(c[0],c[1],c[2])):s(r,a,o)}_getTransactionRequest(e){const t=Bh(e),n=[];if(["to","from"].forEach(s=>{if(t[s]==null)return;const r=Wn(t[s],this);Lh(r)?n.push((async function(){t[s]=await r})()):t[s]=r}),t.blockTag!=null){const s=this._getBlockTag(t.blockTag);Lh(s)?n.push((async function(){t.blockTag=await s})()):t.blockTag=s}return n.length?(async function(){return await Promise.all(n),t})():t}async getNetwork(){if(this.#s==null){const s=(async()=>{try{const r=await this._detectNetwork();return this.emit("network",r,null),r}catch(r){throw this.#s===s&&(this.#s=null),r}})();return this.#s=s,(await s).clone()}const e=this.#s,[t,n]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==n.chainId&&(this.#a?(this.emit("network",n,t),this.#s===e&&(this.#s=Promise.resolve(n))):pe(!1,`network changed: ${t.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),t.clone()}async getFeeData(){const e=await this.getNetwork(),t=async()=>{const{_block:s,gasPrice:r,priorityFee:a}=await Hn({_block:this.#x("latest",!1),gasPrice:(async()=>{try{const h=await this.#c({method:"getGasPrice"});return Ne(h,"%response")}catch{}return null})(),priorityFee:(async()=>{try{const h=await this.#c({method:"getPriorityFee"});return Ne(h,"%response")}catch{}return null})()});let o=null,c=null;const l=this._wrapBlock(s,e);return l&&l.baseFeePerGas&&(c=a??BigInt("1000000000"),o=l.baseFeePerGas*$L+c),new SE(r,o,c)},n=e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const s=new zi(n.url),r=await n.processFunc(t,this,s);return new SE(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return Lh(t)&&(t=await t),Ne(await this.#c({method:"estimateGas",transaction:t}),"%response")}async#h(e,t,n){pe(n<e2,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});const s=Bh(e);try{return Ce(await this._perform({method:"call",transaction:s,blockTag:t}))}catch(r){if(!this.disableCcipRead&&Rf(r)&&r.data&&n>=0&&t==="latest"&&s.to!=null&&Kt(r.data,0,4)==="0x556f1830"){const a=r.data,o=await Wn(s.to,this);let c;try{c=c2(Kt(r.data,4))}catch(u){pe(!1,u.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:s,info:{data:a}})}pe(c.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:a,reason:"OffchainLookup",transaction:s,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:c.errorArgs}});const l=await this.ccipReadFetch(s,c.calldata,c.urls);pe(l!=null,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:s,info:{data:r.data,errorArgs:c.errorArgs}});const h={to:o,data:Gt([c.selector,o2([l,c.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:h});try{const u=await this.#h(h,t,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},h),result:u}),u}catch(u){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},h),error:u}),u}}throw r}}async#u(e){const{value:t}=await Hn({network:this.getNetwork(),value:e});return t}async call(e){const{tx:t,blockTag:n}=await Hn({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await this.#u(this.#h(t,n,e.enableCcipRead?0:-1))}async#d(e,t,n){let s=this._getAddress(t),r=this._getBlockTag(n);return(typeof s!="string"||typeof r!="string")&&([s,r]=await Promise.all([s,r])),await this.#u(this.#c(Object.assign(e,{address:s,blockTag:r})))}async getBalance(e,t){return Ne(await this.#d({method:"getBalance"},e,t),"%response")}async getTransactionCount(e,t){return dt(await this.#d({method:"getTransactionCount"},e,t),"%response")}async getCode(e,t){return Ce(await this.#d({method:"getCode"},e,t))}async getStorage(e,t,n){const s=Ne(t,"position");return Ce(await this.#d({method:"getStorage",position:s},e,n))}async broadcastTransaction(e){const{blockNumber:t,hash:n,network:s}=await Hn({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:e}),network:this.getNetwork()}),r=Ni.from(e);if(r.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(r,s).replaceableTransaction(t)}async#x(e,t){if(Pt(e,32))return await this.#c({method:"getBlock",blockHash:e,includeTransactions:t});let n=this._getBlockTag(e);return typeof n!="string"&&(n=await n),await this.#c({method:"getBlock",blockTag:n,includeTransactions:t})}async getBlock(e,t){const{network:n,params:s}=await Hn({network:this.getNetwork(),params:this.#x(e,!!t)});return s==null?null:this._wrapBlock(s,n)}async getTransaction(e){const{network:t,params:n}=await Hn({network:this.getNetwork(),params:this.#c({method:"getTransaction",hash:e})});return n==null?null:this._wrapTransactionResponse(n,t)}async getTransactionReceipt(e){const{network:t,params:n}=await Hn({network:this.getNetwork(),params:this.#c({method:"getTransactionReceipt",hash:e})});if(n==null)return null;if(n.gasPrice==null&&n.effectiveGasPrice==null){const s=await this.#c({method:"getTransaction",hash:e});if(s==null)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=s.gasPrice}return this._wrapTransactionReceipt(n,t)}async getTransactionResult(e){const{result:t}=await Hn({network:this.getNetwork(),result:this.#c({method:"getTransactionResult",hash:e})});return t==null?null:Ce(t)}async getLogs(e){let t=this._getFilter(e);Lh(t)&&(t=await t);const{network:n,params:s}=await Hn({network:this.getNetwork(),params:this.#c({method:"getLogs",filter:t})});return s.map(r=>this._wrapLog(r,n))}_getProvider(e){pe(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(e){return await Ya.fromName(this,e)}async getAvatar(e){const t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e){const t=await this.getResolver(e);return t?await t.getAddress():null}async lookupAddress(e){e=St(e);const t=mp(e.substring(2).toLowerCase()+".addr.reverse");try{const n=await Ya.getEnsAddress(this),r=await new Gr(n,["function resolver(bytes32) view returns (address)"],this).resolver(t);if(r==null||r===rc)return null;const o=await new Gr(r,["function name(bytes32) view returns (string)"],this).name(t);return await this.resolveName(o)!==e?null:o}catch(n){if(Tn(n,"BAD_DATA")&&n.value==="0x"||Tn(n,"CALL_EXCEPTION"))return null;throw n}return null}async waitForTransaction(e,t,n){const s=t??1;return s===0?this.getTransactionReceipt(e):new Promise(async(r,a)=>{let o=null;const c=(async l=>{try{const h=await this.getTransactionReceipt(e);if(h!=null&&l-h.blockNumber+1>=s){r(h),o&&(clearTimeout(o),o=null);return}}catch(h){console.log("EEE",h)}this.once("block",c)});n!=null&&(o=setTimeout(()=>{o!=null&&(o=null,this.off("block",c),a(Qt("timeout","TIMEOUT",{reason:"timeout"})))},n)),c(await this.getBlockNumber())})}async waitForBlock(e){pe(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(e){const t=this.#l.get(e);t&&(t.timer&&clearTimeout(t.timer),this.#l.delete(e))}_setTimeout(e,t){t==null&&(t=0);const n=this.#f++,s=()=>{this.#l.delete(n),e()};if(this.paused)this.#l.set(n,{timer:null,func:s,time:t});else{const r=setTimeout(s,t);this.#l.set(n,{timer:r,func:s,time:Np()})}return n}_forEachSubscriber(e){for(const t of this.#e.values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case"debug":case"error":case"network":return new jE(e.type);case"block":{const t=new XL(this);return t.pollingInterval=this.pollingInterval,t}case"safe":case"finalized":return new YL(this,e.type);case"event":return new Tp(this,e.filter);case"transaction":return new ZL(this,e.hash);case"orphan":return new JL(this,e.filter)}throw new Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(const n of this.#e.values())if(n.subscriber===e){n.started&&n.subscriber.stop(),n.subscriber=t,n.started&&t.start(),this.#n!=null&&t.pause(this.#n);break}}async#g(e,t){let n=await Fp(e,this);return n.type==="event"&&t&&t.length>0&&t[0].removed===!0&&(n=await Fp({orphan:"drop-log",log:t[0]},this)),this.#e.get(n.tag)||null}async#m(e){const t=await Fp(e,this),n=t.tag;let s=this.#e.get(n);return s||(s={subscriber:this._getSubscriber(t),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#e.set(n,s)),s}async on(e,t){const n=await this.#m(e);return n.listeners.push({listener:t,once:!1}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async once(e,t){const n=await this.#m(e);return n.listeners.push({listener:t,once:!0}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async emit(e,...t){const n=await this.#g(e,t);if(!n||n.listeners.length===0)return!1;const s=n.listeners.length;return n.listeners=n.listeners.filter(({listener:r,once:a})=>{const o=new dx(this,a?null:r,e);try{r.call(this,...t,o)}catch{}return!a}),n.listeners.length===0&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),s>0}async listenerCount(e){if(e){const n=await this.#g(e);return n?n.listeners.length:0}let t=0;for(const{listeners:n}of this.#e.values())t+=n.length;return t}async listeners(e){if(e){const n=await this.#g(e);return n?n.listeners.map(({listener:s})=>s):[]}let t=[];for(const{listeners:n}of this.#e.values())t=t.concat(n.map(({listener:s})=>s));return t}async off(e,t){const n=await this.#g(e);if(!n)return this;if(t){const s=n.listeners.map(({listener:r})=>r).indexOf(t);s>=0&&n.listeners.splice(s,1)}return(!t||n.listeners.length===0)&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),this}async removeAllListeners(e){if(e){const{tag:t,started:n,subscriber:s}=await this.#m(e);n&&s.stop(),this.#e.delete(t)}else for(const[t,{started:n,subscriber:s}]of this.#e)n&&s.stop(),this.#e.delete(t);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return this.#i}destroy(){this.removeAllListeners();for(const e of this.#l.keys())this._clearTimeout(e);this.#i=!0}get paused(){return this.#n!=null}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(this.#o=-1,this.#n!=null){if(this.#n==!!e)return;pe(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(t=>t.pause(e)),this.#n=!!e;for(const t of this.#l.values())t.timer&&clearTimeout(t.timer),t.time=Np()-t.time}resume(){if(this.#n!=null){this._forEachSubscriber(e=>e.resume()),this.#n=null;for(const e of this.#l.values()){let t=e.time;t<0&&(t=0),e.time=Np(),setTimeout(e.func,t)}}}}function s2(i,e){try{const t=Dp(i,e);if(t)return rh(t)}catch{}return null}function Dp(i,e){if(i==="0x")return null;try{const t=dt(Kt(i,e,e+32)),n=dt(Kt(i,t,t+32));return Kt(i,t+32,t+32+n)}catch{}return null}function XE(i){const e=rn(i);if(e.length>32)throw new Error("internal; should not happen");const t=new Uint8Array(32);return t.set(e,32-e.length),t}function r2(i){if(i.length%32===0)return i;const e=new Uint8Array(Math.ceil(i.length/32)*32);return e.set(i),e}const a2=new Uint8Array([]);function o2(i){const e=[];let t=0;for(let n=0;n<i.length;n++)e.push(a2),t+=32;for(let n=0;n<i.length;n++){const s=ut(i[n]);e[n]=XE(t),e.push(XE(s.length)),e.push(r2(s)),t+=32+Math.ceil(s.length/32)*32}return Gt(e)}const YE="0x0000000000000000000000000000000000000000000000000000000000000000";function c2(i){const e={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};pe(ka(i)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const t=Kt(i,0,32);pe(Kt(t,0,12)===Kt(YE,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),e.sender=Kt(t,12);try{const n=[],s=dt(Kt(i,32,64)),r=dt(Kt(i,s,s+32)),a=Kt(i,s+32);for(let o=0;o<r;o++){const c=s2(a,o*32);if(c==null)throw new Error("abort");n.push(c)}e.urls=n}catch{pe(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=Dp(i,64);if(n==null)throw new Error("abort");e.calldata=n}catch{pe(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}pe(Kt(i,100,128)===Kt(YE,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),e.selector=Kt(i,96,100);try{const n=Dp(i,128);if(n==null)throw new Error("abort");e.extraData=n}catch{pe(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return e.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map(n=>e[n]),e}function Hr(i,e){if(i.provider)return i.provider;pe(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:e})}async function JE(i,e){let t=Bh(e);if(t.to!=null&&(t.to=Wn(t.to,i)),t.from!=null){const n=t.from;t.from=Promise.all([i.getAddress(),Wn(n,i)]).then(([s,r])=>(V(s.toLowerCase()===r.toLowerCase(),"transaction from mismatch","tx.from",r),s))}else t.from=i.getAddress();return await Hn(t)}class l2{provider;constructor(e){Ye(this,{provider:e||null})}async getNonce(e){return Hr(this,"getTransactionCount").getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await JE(this,e)}async populateTransaction(e){const t=Hr(this,"populateTransaction"),n=await JE(this,e);n.nonce==null&&(n.nonce=await this.getNonce("pending")),n.gasLimit==null&&(n.gasLimit=await this.estimateGas(n));const s=await this.provider.getNetwork();if(n.chainId!=null){const a=Ne(n.chainId);V(a===s.chainId,"transaction chainId mismatch","tx.chainId",e.chainId)}else n.chainId=s.chainId;const r=n.maxFeePerGas!=null||n.maxPriorityFeePerGas!=null;if(n.gasPrice!=null&&(n.type===2||r)?V(!1,"eip-1559 transaction do not support gasPrice","tx",e):(n.type===0||n.type===1)&&r&&V(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",e),(n.type===2||n.type==null)&&n.maxFeePerGas!=null&&n.maxPriorityFeePerGas!=null)n.type=2;else if(n.type===0||n.type===1){const a=await t.getFeeData();pe(a.gasPrice!=null,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),n.gasPrice==null&&(n.gasPrice=a.gasPrice)}else{const a=await t.getFeeData();if(n.type==null)if(a.maxFeePerGas!=null&&a.maxPriorityFeePerGas!=null)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,n.gasPrice!=null){const o=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=o,n.maxPriorityFeePerGas=o}else n.maxFeePerGas==null&&(n.maxFeePerGas=a.maxFeePerGas),n.maxPriorityFeePerGas==null&&(n.maxPriorityFeePerGas=a.maxPriorityFeePerGas);else a.gasPrice!=null?(pe(!r,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),n.gasPrice==null&&(n.gasPrice=a.gasPrice),n.type=0):pe(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else(n.type===2||n.type===3||n.type===4)&&(n.maxFeePerGas==null&&(n.maxFeePerGas=a.maxFeePerGas),n.maxPriorityFeePerGas==null&&(n.maxPriorityFeePerGas=a.maxPriorityFeePerGas))}return await Hn(n)}async populateAuthorization(e){const t=Object.assign({},e);return t.chainId==null&&(t.chainId=(await Hr(this,"getNetwork").getNetwork()).chainId),t.nonce==null&&(t.nonce=await this.getNonce()),t}async estimateGas(e){return Hr(this,"estimateGas").estimateGas(await this.populateCall(e))}async call(e){return Hr(this,"call").call(await this.populateCall(e))}async resolveName(e){return await Hr(this,"resolveName").resolveName(e)}async sendTransaction(e){const t=Hr(this,"sendTransaction"),n=await this.populateTransaction(e);delete n.from;const s=Ni.from(n);return await t.broadcastTransaction(await this.signTransaction(s))}authorize(e){pe(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}function h2(i){return JSON.parse(JSON.stringify(i))}class ZE{#e;#t;#n;#i;#s;#a;constructor(e){this.#e=e,this.#t=null,this.#n=this.#r.bind(this),this.#i=!1,this.#s=null,this.#a=!1}_subscribe(e){throw new Error("subclasses must override this")}_emitResults(e,t){throw new Error("subclasses must override this")}_recover(e){throw new Error("subclasses must override this")}async#r(e){try{this.#t==null&&(this.#t=this._subscribe(this.#e));let t=null;try{t=await this.#t}catch(r){if(!Tn(r,"UNSUPPORTED_OPERATION")||r.operation!=="eth_newFilter")throw r}if(t==null){this.#t=null,this.#e._recoverSubscriber(this,this._recover(this.#e));return}const n=await this.#e.getNetwork();if(this.#s||(this.#s=n),this.#s.chainId!==n.chainId)throw new Error("chaid changed");if(this.#a)return;const s=await this.#e.send("eth_getFilterChanges",[t]);await this._emitResults(this.#e,s)}catch(t){console.log("@TODO",t)}this.#e.once("block",this.#n)}#o(){const e=this.#t;e&&(this.#t=null,e.then(t=>{this.#e.destroyed||this.#e.send("eth_uninstallFilter",[t])}))}start(){this.#i||(this.#i=!0,this.#r(-2))}stop(){this.#i&&(this.#i=!1,this.#a=!0,this.#o(),this.#e.off("block",this.#n))}pause(e){e&&this.#o(),this.#e.off("block",this.#n)}resume(){this.start()}}class u2 extends ZE{#e;constructor(e,t){super(e),this.#e=h2(t)}_recover(e){return new Tp(e,this.#e)}async _subscribe(e){return await e.send("eth_newFilter",[this.#e])}async _emitResults(e,t){for(const n of t)e.emit(this.#e,e._wrapLog(n,e._network))}}class d2 extends ZE{async _subscribe(e){return await e.send("eth_newPendingTransactionFilter",[])}async _emitResults(e,t){for(const n of t)e.emit("pending",n)}}const f2="bigint,boolean,function,number,string,symbol".split(/,/g);function kh(i){if(i==null||f2.indexOf(typeof i)>=0||typeof i.getAddress=="function")return i;if(Array.isArray(i))return i.map(kh);if(typeof i=="object")return Object.keys(i).reduce((e,t)=>(e[t]=i[t],e),{});throw new Error(`should not happen: ${i} (${typeof i})`)}function p2(i){return new Promise(e=>{setTimeout(e,i)})}function Za(i){return i&&i.toLowerCase()}function $E(i){return i&&typeof i.pollingInterval=="number"}const ey={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class Lp extends l2{address;constructor(e,t){super(e),t=St(t),Ye(this,{address:t})}connect(e){pe(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){const t=kh(e),n=[];if(t.from){const r=t.from;n.push((async()=>{const a=await Wn(r,this.provider);V(a!=null&&a.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=a})())}else t.from=this.address;if(t.gasLimit==null&&n.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),t.to!=null){const r=t.to;n.push((async()=>{t.to=await Wn(r,this.provider)})())}n.length&&await Promise.all(n);const s=this.provider.getRpcTransaction(t);return this.provider.send("eth_sendTransaction",[s])}async sendTransaction(e){const t=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(e);return await new Promise((s,r)=>{const a=[1e3,100];let o=0;const c=async()=>{try{const l=await this.provider.getTransaction(n);if(l!=null){s(l.replaceableTransaction(t));return}}catch(l){if(Tn(l,"CANCELLED")||Tn(l,"BAD_DATA")||Tn(l,"NETWORK_ERROR")||Tn(l,"UNSUPPORTED_OPERATION")){l.info==null&&(l.info={}),l.info.sendTransactionHash=n,r(l);return}if(Tn(l,"INVALID_ARGUMENT")&&(o++,l.info==null&&(l.info={}),l.info.sendTransactionHash=n,o>10)){r(l);return}this.provider.emit("error",Qt("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:l}))}this.provider._setTimeout(()=>{c()},a.pop()||4e3)};c()})}async signTransaction(e){const t=kh(e);if(t.from){const s=await Wn(t.from,this.provider);V(s!=null&&s.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=s}else t.from=this.address;const n=this.provider.getRpcTransaction(t);return await this.provider.send("eth_signTransaction",[n])}async signMessage(e){const t=typeof e=="string"?ds(e):e;return await this.provider.send("personal_sign",[Ce(t),this.address.toLowerCase()])}async signTypedData(e,t,n){const s=kh(n),r=await ti.resolveNames(e,t,s,async a=>{const o=await Wn(a);return V(o!=null,"TypedData does not support null address","value",a),o});return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(ti.getPayload(r.domain,t,r.value))])}async unlock(e){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){const t=typeof e=="string"?ds(e):e;return await this.provider.send("eth_sign",[this.address.toLowerCase(),Ce(t)])}}class A2 extends i2{#e;#t;#n;#i;#s;#a;#r;#o(){if(this.#i)return;const e=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#i=setTimeout(()=>{this.#i=null;const t=this.#n;for(this.#n=[];t.length;){const n=[t.shift()];for(;t.length&&n.length!==this.#e.batchMaxCount;)if(n.push(t.shift()),JSON.stringify(n.map(r=>r.payload)).length>this.#e.batchMaxSize){t.unshift(n.pop());break}(async()=>{const s=n.length===1?n[0].payload:n.map(r=>r.payload);this.emit("debug",{action:"sendRpcPayload",payload:s});try{const r=await this._send(s);this.emit("debug",{action:"receiveRpcResult",result:r});for(const{resolve:a,reject:o,payload:c}of n){if(this.destroyed){o(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:c.method}));continue}const l=r.filter(h=>h.id===c.id)[0];if(l==null){const h=Qt("missing response for request","BAD_DATA",{value:r,info:{payload:c}});this.emit("error",h),o(h);continue}if("error"in l){o(this.getRpcError(c,l));continue}a(l.result)}}catch(r){this.emit("debug",{action:"receiveRpcError",error:r});for(const{reject:a}of n)a(r)}})()}},e)}constructor(e,t){super(e,t),this.#t=1,this.#e=Object.assign({},ey,t||{}),this.#n=[],this.#i=null,this.#a=null,this.#r=null;{let s=null;const r=new Promise(a=>{s=a});this.#s={promise:r,resolve:s}}const n=this._getOption("staticNetwork");typeof n=="boolean"?(V(!n||e!=="any","staticNetwork cannot be used on special network 'any'","options",t),n&&e!=null&&(this.#a=ii.from(e))):n&&(V(e==null||n.matches(e),"staticNetwork MUST match network object","options",t),this.#a=n)}_getOption(e){return this.#e[e]}get _network(){return pe(this.#a,"network is not available yet","NETWORK_ERROR"),this.#a}async _perform(e){if(e.method==="call"||e.method==="estimateGas"){let n=e.transaction;if(n&&n.type!=null&&Ne(n.type)&&n.maxFeePerGas==null&&n.maxPriorityFeePerGas==null){const s=await this.getFeeData();s.maxFeePerGas==null&&s.maxPriorityFeePerGas==null&&(e=Object.assign({},e,{transaction:Object.assign({},n,{type:void 0})}))}}const t=this.getRpcRequest(e);return t!=null?await this.send(t.method,t.args):super._perform(e)}async _detectNetwork(){const e=this._getOption("staticNetwork");if(e)if(e===!0){if(this.#a)return this.#a}else return e;return this.#r?await this.#r:this.ready?(this.#r=(async()=>{try{const t=ii.from(Ne(await this.send("eth_chainId",[])));return this.#r=null,t}catch(t){throw this.#r=null,t}})(),await this.#r):(this.#r=(async()=>{const t={id:this.#t++,method:"eth_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",{action:"sendRpcPayload",payload:t});let n;try{n=(await this._send(t))[0],this.#r=null}catch(s){throw this.#r=null,this.emit("debug",{action:"receiveRpcError",error:s}),s}if(this.emit("debug",{action:"receiveRpcResult",result:n}),"result"in n)return ii.from(Ne(n.result));throw this.getRpcError(t,n)})(),await this.#r)}_start(){this.#s==null||this.#s.resolve==null||(this.#s.resolve(),this.#s=null,(async()=>{for(;this.#a==null&&!this.destroyed;)try{this.#a=await this._detectNetwork()}catch(e){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",Qt("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:e}})),await p2(1e3)}this.#o()})())}async _waitUntilReady(){if(this.#s!=null)return await this.#s.promise}_getSubscriber(e){return e.type==="pending"?new d2(this):e.type==="event"?this._getOption("polling")?new Tp(this,e.filter):new u2(this,e.filter):e.type==="orphan"&&e.filter.orphan==="drop-log"?new jE("orphan"):super._getSubscriber(e)}get ready(){return this.#s==null}getRpcTransaction(e){const t={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(n=>{if(e[n]==null)return;let s=n;n==="gasLimit"&&(s="gas"),t[s]=Ri(Ne(e[n],`tx.${n}`))}),["from","to","data"].forEach(n=>{e[n]!=null&&(t[n]=Ce(e[n]))}),e.accessList&&(t.accessList=Tr(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map(n=>n.toLowerCase())),e.authorizationList&&(t.authorizationList=e.authorizationList.map(n=>{const s=vb(n);return{address:s.address,nonce:Ri(s.nonce),chainId:Ri(s.chainId),yParity:Ri(s.signature.yParity),r:Ri(s.signature.r),s:Ri(s.signature.s)}})),t}getRpcRequest(e){switch(e.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[Za(e.address),e.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[Za(e.address),e.blockTag]};case"getCode":return{method:"eth_getCode",args:[Za(e.address),e.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[Za(e.address),"0x"+e.position.toString(16),e.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[e.signedTransaction]};case"getBlock":if("blockTag"in e)return{method:"eth_getBlockByNumber",args:[e.blockTag,!!e.includeTransactions]};if("blockHash"in e)return{method:"eth_getBlockByHash",args:[e.blockHash,!!e.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[e.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[e.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(e.transaction),e.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(e.transaction)]};case"getLogs":return e.filter&&e.filter.address!=null&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(Za):e.filter.address=Za(e.filter.address)),{method:"eth_getLogs",args:[e.filter]}}return null}getRpcError(e,t){const{method:n}=e,{error:s}=t;if(n==="eth_estimateGas"&&s.message){const o=s.message;if(!o.match(/revert/i)&&o.match(/insufficient funds/i))return Qt("insufficient funds","INSUFFICIENT_FUNDS",{transaction:e.params[0],info:{payload:e,error:s}});if(o.match(/nonce/i)&&o.match(/too low/i))return Qt("nonce has already been used","NONCE_EXPIRED",{transaction:e.params[0],info:{payload:e,error:s}})}if(n==="eth_call"||n==="eth_estimateGas"){const o=Pp(s),c=ja.getBuiltinCallException(n==="eth_call"?"call":"estimateGas",e.params[0],o?o.data:null);return c.info={error:s,payload:e},c}const r=JSON.stringify(g2(s));if(typeof s.message=="string"&&s.message.match(/user denied|ethers-user-denied/i))return Qt("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[n]||"unknown",reason:"rejected",info:{payload:e,error:s}});if(n==="eth_sendRawTransaction"||n==="eth_sendTransaction"){const o=e.params[0];if(r.match(/insufficient funds|base fee exceeds gas limit/i))return Qt("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:o,info:{error:s}});if(r.match(/nonce/i)&&r.match(/too low/i))return Qt("nonce has already been used","NONCE_EXPIRED",{transaction:o,info:{error:s}});if(r.match(/replacement transaction/i)&&r.match(/underpriced/i))return Qt("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:o,info:{error:s}});if(r.match(/only replay-protected/i))return Qt("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:o,info:{error:s}}})}let a=!!r.match(/the method .* does not exist/i);return a||s&&s.details&&s.details.startsWith("Unauthorized method:")&&(a=!0),a?Qt("unsupported operation","UNSUPPORTED_OPERATION",{operation:e.method,info:{error:s,payload:e}}):Qt("could not coalesce error","UNKNOWN_ERROR",{error:s,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e}));const n=this.#t++,s=new Promise((r,a)=>{this.#n.push({resolve:r,reject:a,payload:{method:e,params:t,id:n,jsonrpc:"2.0"}})});return this.#o(),s}async getSigner(e){e==null&&(e=0);const t=this.send("eth_accounts",[]);if(typeof e=="number"){const s=await t;if(e>=s.length)throw new Error("no such account");return new Lp(this,s[e])}const{accounts:n}=await Hn({network:this.getNetwork(),accounts:t});e=St(e);for(const s of n)if(St(s)===e)return new Lp(this,e);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map(t=>new Lp(this,t))}destroy(){this.#i&&(clearTimeout(this.#i),this.#i=null);for(const{payload:e,reject:t}of this.#n)t(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e.method}));this.#n=[],super.destroy()}}class ty extends A2{#e;constructor(e,t){super(e,t);let n=this._getOption("pollingInterval");n==null&&(n=ey.pollingInterval),this.#e=n}_getSubscriber(e){const t=super._getSubscriber(e);return $E(t)&&(t.pollingInterval=this.#e),t}get pollingInterval(){return this.#e}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw new Error("invalid interval");this.#e=e,this._forEachSubscriber(t=>{$E(t)&&(t.pollingInterval=this.#e)})}}class ny extends ty{#e;constructor(e,t,n){e==null&&(e="http://localhost:8545"),super(t,n),typeof e=="string"?this.#e=new zi(e):this.#e=e.clone()}_getConnection(){return this.#e.clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){const t=this._getConnection();t.body=JSON.stringify(e),t.setHeader("content-type","application/json");const n=await t.send();n.assertOk();let s=n.bodyJson;return Array.isArray(s)||(s=[s]),s}}function Pp(i){if(i==null)return null;if(typeof i.message=="string"&&i.message.match(/revert/i)&&Pt(i.data))return{message:i.message,data:i.data};if(typeof i=="object"){for(const e in i){const t=Pp(i[e]);if(t)return t}return null}if(typeof i=="string")try{return Pp(JSON.parse(i))}catch{}return null}function kp(i,e){if(i!=null){if(typeof i.message=="string"&&e.push(i.message),typeof i=="object")for(const t in i)kp(i[t],e);if(typeof i=="string")try{return kp(JSON.parse(i),e)}catch{}}}function g2(i){const e=[];return kp(i,e),e}class zr extends ty{#e;#t;constructor(e,t,n){const s=Object.assign({},n??{},{batchMaxCount:1});V(e&&e.request,"invalid EIP-1193 provider","ethereum",e),super(t,s),this.#t=null,n&&n.providerInfo&&(this.#t=n.providerInfo),this.#e=async(r,a)=>{const o={method:r,params:a};this.emit("debug",{action:"sendEip1193Request",payload:o});try{const c=await e.request(o);return this.emit("debug",{action:"receiveEip1193Result",result:c}),c}catch(c){const l=new Error(c.message);throw l.code=c.code,l.data=c.data,l.payload=o,this.emit("debug",{action:"receiveEip1193Error",error:l}),l}}}get providerInfo(){return this.#t}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){V(!Array.isArray(e),"EIP-1193 does not support batch request","payload",e);try{const t=await this.#e(e.method,e.params||[]);return[{id:e.id,result:t}]}catch(t){return[{id:e.id,error:{code:t.code,data:t.data,message:t.message}}]}}getRpcError(e,t){switch(t=JSON.parse(JSON.stringify(t)),t.error.code||-1){case 4001:t.error.message=`ethers-user-denied: ${t.error.message}`;break;case 4200:t.error.message=`ethers-unsupported: ${t.error.message}`;break}return super.getRpcError(e,t)}async hasSigner(e){e==null&&(e=0);const t=await this.send("eth_accounts",[]);return typeof e=="number"?t.length>e:(e=e.toLowerCase(),t.filter(n=>n.toLowerCase()===e).length!==0)}async getSigner(e){if(e==null&&(e=0),!await this.hasSigner(e))try{await this.#e("eth_requestAccounts",[])}catch(t){const n=t.payload;throw this.getRpcError(n,{id:n.id,error:t})}return await super.getSigner(e)}static async discover(e){if(e==null&&(e={}),e.provider)return new zr(e.provider);const t=e.window?e.window:typeof window<"u"?window:null;if(t==null)return null;const n=e.anyProvider;if(n&&t.ethereum)return new zr(t.ethereum);if(!("addEventListener"in t&&"dispatchEvent"in t&&"removeEventListener"in t))return null;const s=e.timeout?e.timeout:300;return s===0?null:await new Promise((r,a)=>{let o=[];const c=u=>{o.push(u.detail),n&&l()},l=()=>{if(clearTimeout(h),o.length)if(e&&e.filter){const u=e.filter(o.map(d=>Object.assign({},d.info)));if(u==null)r(null);else if(u instanceof zr)r(u);else{let d=null;if(u.uuid&&(d=o.filter(p=>u.uuid===p.info.uuid)[0]),d){const{provider:f,info:p}=d;r(new zr(f,void 0,{providerInfo:p}))}else a(Qt("filter returned unknown info","UNSUPPORTED_OPERATION",{value:u}))}}else{const{provider:u,info:d}=o[0];r(new zr(u,void 0,{providerInfo:d}))}else r(null);t.removeEventListener("eip6963:announceProvider",c)},h=setTimeout(()=>{l()},s);t.addEventListener("eip6963:announceProvider",c),t.dispatchEvent(new Event("eip6963:requestProvider"))})}}const iy=["function register() external returns (uint256 agentId)","function register(string agentURI) external returns (uint256 agentId)","function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)","function setAgentURI(uint256 agentId, string newURI) external","function tokenURI(uint256 tokenId) external view returns (string)","function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external","function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)","function getAgentWallet(uint256 agentId) external view returns (address)","function ownerOf(uint256 tokenId) external view returns (address)","function balanceOf(address owner) external view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)","function totalSupply() external view returns (uint256)","function name() external view returns (string)","function symbol() external view returns (string)","function getVersion() external pure returns (string)","function transferFrom(address from, address to, uint256 tokenId) external","function safeTransferFrom(address from, address to, uint256 tokenId) external","function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) external","function approve(address to, uint256 tokenId) external","function setApprovalForAll(address operator, bool approved) external","event Registered(uint256 indexed agentId, string agentURI, address indexed owner)","event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"],Vr={identityRegistry:"0x8004A818BFB912233c491871b3d84c89A494BD9e",reputationRegistry:"0x8004B663056A597Dffe9eCcC1965A193B7388713",validationRegistry:"0x8004Cb1BF31DAf7788923b405b754f57acEB4272"},Kn={identityRegistry:"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",reputationRegistry:"0x8004BAa17C55a88189AE136b182e5fdA19dE9b63",validationRegistry:""},Uh={1:Kn,10:Kn,56:Kn,100:Kn,137:Kn,250:Kn,324:Kn,1284:Kn,5e3:Kn,8453:Kn,42161:Kn,42220:Kn,43114:Kn,59144:Kn,534352:Kn,97:Vr,11155111:Vr,84532:Vr,421614:Vr,11155420:Vr,80002:Vr,43113:Vr};function m2(i,e){return`eip155:${i}:${e}`}const sy={1:{name:"Ethereum",shortName:"ETH",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://ethereum-rpc.publicnode.com",explorer:"https://etherscan.io",testnet:!1},10:{name:"Optimism",shortName:"OP",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.optimism.io",explorer:"https://optimistic.etherscan.io",testnet:!1},56:{name:"BNB Chain",shortName:"BSC",currency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrl:"https://bsc-dataseed.bnbchain.org",explorer:"https://bscscan.com",testnet:!1},100:{name:"Gnosis",shortName:"GNO",currency:{name:"xDAI",symbol:"xDAI",decimals:18},rpcUrl:"https://rpc.gnosischain.com",explorer:"https://gnosisscan.io",testnet:!1},137:{name:"Polygon",shortName:"POL",currency:{name:"POL",symbol:"POL",decimals:18},rpcUrl:"https://polygon-rpc.com",explorer:"https://polygonscan.com",testnet:!1},250:{name:"Fantom",shortName:"FTM",currency:{name:"Fantom",symbol:"FTM",decimals:18},rpcUrl:"https://rpc.ftm.tools",explorer:"https://ftmscan.com",testnet:!1},324:{name:"zkSync Era",shortName:"zkSync",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.era.zksync.io",explorer:"https://explorer.zksync.io",testnet:!1},1284:{name:"Moonbeam",shortName:"GLMR",currency:{name:"Glimmer",symbol:"GLMR",decimals:18},rpcUrl:"https://rpc.api.moonbeam.network",explorer:"https://moonbeam.moonscan.io",testnet:!1},5e3:{name:"Mantle",shortName:"MNT",currency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrl:"https://rpc.mantle.xyz",explorer:"https://explorer.mantle.xyz",testnet:!1},8453:{name:"Base",shortName:"Base",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.base.org",explorer:"https://basescan.org",testnet:!1},42161:{name:"Arbitrum One",shortName:"ARB",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://arb1.arbitrum.io/rpc",explorer:"https://arbiscan.io",testnet:!1},42220:{name:"Celo",shortName:"CELO",currency:{name:"Celo",symbol:"CELO",decimals:18},rpcUrl:"https://forno.celo.org",explorer:"https://celoscan.io",testnet:!1},43114:{name:"Avalanche",shortName:"AVAX",currency:{name:"Avax",symbol:"AVAX",decimals:18},rpcUrl:"https://api.avax.network/ext/bc/C/rpc",explorer:"https://snowtrace.io",testnet:!1},59144:{name:"Linea",shortName:"Linea",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://rpc.linea.build",explorer:"https://lineascan.build",testnet:!1},534352:{name:"Scroll",shortName:"Scroll",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://rpc.scroll.io",explorer:"https://scrollscan.com",testnet:!1},97:{name:"BSC Testnet",shortName:"BSCt",currency:{name:"tBNB",symbol:"tBNB",decimals:18},rpcUrl:"https://bsc-testnet-rpc.publicnode.com",explorer:"https://testnet.bscscan.com",testnet:!0},11155111:{name:"Ethereum Sepolia",shortName:"Sep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://ethereum-sepolia-rpc.publicnode.com",explorer:"https://sepolia.etherscan.io",testnet:!0},84532:{name:"Base Sepolia",shortName:"BaseSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia.base.org",explorer:"https://sepolia.basescan.org",testnet:!0},421614:{name:"Arbitrum Sepolia",shortName:"ArbSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia-rollup.arbitrum.io/rpc",explorer:"https://sepolia.arbiscan.io",testnet:!0},11155420:{name:"Optimism Sepolia",shortName:"OpSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia.optimism.io",explorer:"https://sepolia-optimism.etherscan.io",testnet:!0},80002:{name:"Polygon Amoy",shortName:"Amoy",currency:{name:"POL",symbol:"POL",decimals:18},rpcUrl:"https://rpc-amoy.polygon.technology",explorer:"https://amoy.polygonscan.com",testnet:!0},43113:{name:"Avalanche Fuji",shortName:"Fuji",currency:{name:"Avax",symbol:"AVAX",decimals:18},rpcUrl:"https://api.avax-test.network/ext/bc/C/rpc",explorer:"https://testnet.snowtrace.io",testnet:!0}};function x2(i,e){if(e)return new zr(e);const t=sy[i];if(!t)throw new Error(`No RPC configured for chainId ${i}`);return new ny(t.rpcUrl,i)}function b2(i,e){const t=Uh[i];if(!t||!t.identityRegistry)throw new Error(`No Identity Registry for chainId ${i}`);const n=x2(i,e);return new Gr(t.identityRegistry,iy,n)}async function E2({chainId:i,agentId:e,ethProvider:t}){const n=b2(i,t),[s,r]=await Promise.all([n.ownerOf(e).catch(()=>null),n.tokenURI(e).catch(()=>null)]);return{agentId:BigInt(e),owner:s,uri:r}}function ry(i){if(!i||typeof i!="object")return null;const e=Array.isArray(i.services)?i.services:[];for(const n of e){if(!n||typeof n!="object")continue;const s=String(n.endpoint||"").trim();if(!s)continue;const r=String(n.name||"").toLowerCase(),a=String(n.version||"").toLowerCase();if(r==="avatar"||r==="avatar-3d"||a.startsWith("gltf")||/\.(glb|gltf)(\?|#|$)/i.test(s))return s}const t=String(i.image||"").trim();return/\.(glb|gltf)(\?|#|$)/i.test(t)?t:null}async function y2(i){if(!i)return{ok:!1,error:"empty uri"};if(i.startsWith("data:"))try{const t=i.match(/^data:application\/json(?:;base64)?,(.*)$/);if(!t)return{ok:!1,error:"unsupported data URI"};const n=/;base64,/.test(i)?atob(t[1]):decodeURIComponent(t[1]);return{ok:!0,data:JSON.parse(n),resolvedUrl:i}}catch(t){return{ok:!1,error:"data URI parse failed: "+t.message}}let e=i;i.startsWith("ipfs://")?e="https://ipfs.io/ipfs/"+i.slice(7):i.startsWith("ar://")&&(e="https://arweave.net/"+i.slice(5));try{const t=await fetch(e);return t.ok?{ok:!0,data:await t.json(),resolvedUrl:e}:{ok:!1,error:`HTTP ${t.status}`,resolvedUrl:e}}catch(t){return{ok:!1,error:t.message,resolvedUrl:e}}}const _2={base:8453,"base-mainnet":8453,"base-sepolia":84532,ethereum:1,mainnet:1},w2={8453:"https://mainnet.base.org",84532:"https://sepolia.base.org",1:"https://eth.llamarpc.com"};async function Ec(i,{rpcURL:e,registry:t}={}){if(!i)throw new Error("loadManifest: source required");if(i.startsWith("agent://"))return v2(i,{rpcURL:e,registryOverride:t});if(i.startsWith("ipfs://")||i.startsWith("ar://")){const n=hs(i),s=await Up(n);return Oh(s,{baseURI:Op(n)})}if(i.startsWith("http")){const n=await Up(i);return Oh(n,{baseURI:Op(i)})}throw new Error(`Unsupported manifest source: ${i}`)}async function v2(i,{rpcURL:e,registryOverride:t}){const n=i.match(/^agent:\/\/([^/]+)\/(\d+)$/);if(!n)throw new Error(`Malformed agent URI: ${i}`);const[,s,r]=n,a=_2[s.toLowerCase()]||Number(s);if(!a)throw new Error(`Unknown chain: ${s}`);const o=Uh[a],c=t||o?.identityRegistry;if(!c)throw new Error(`No registry deployed on chain ${a}. Pass registry= override.`);const l=new ny(e||w2[a]),h=new Gr(c,iy,l),u=BigInt(r),d=await h.tokenURI(u);if(!d)throw new Error(`Agent ${r} on chain ${a} has no URI`);const f=hs(d),p=await Up(f),m=Oh(p,{baseURI:Op(f)});return m.id={...m.id,chain:s,chainId:a,registry:c,agentId:r},m}async function Up(i){let e;try{e=await fetch(i)}catch{e=await J0(i)}if(!e.ok)throw new Error(`Manifest fetch failed: ${i} (${e.status})`);return e.json()}function Oh(i,{baseURI:e=""}={}){if(i.spec&&i.spec.startsWith("agent-manifest/")){const t={...i,_baseURI:e};return t.body=t.body||{},!t.body.uri&&t.image&&(t.body.uri=t.image),t}if(i.type&&i.type.includes("eip-8004")){const t=i.registrations?.[0]||{},n=ry(i);return{spec:"agent-manifest/0.1",_baseURI:e,_source:"erc8004-registration",id:{agentId:t.agentId?.toString()},name:i.name,description:i.description,image:i.image,body:{uri:hs(n||i.image||""),format:"gltf-binary"},brain:{provider:"none"},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:[],memory:{mode:"local"},tools:["wave","lookAt","play_clip","setExpression"],version:"0.1.0",services:Array.isArray(i.services)?i.services:[],x402Support:!!i.x402Support,embedPolicy:i.embedPolicy||null}}return{spec:"agent-manifest/0.1",_baseURI:e,name:i.name||"Unnamed agent",description:i.description||"",body:{uri:i.body?.uri||i.image||i.model||"",format:i.body?.format||"gltf-binary"},brain:i.brain||{provider:"none"},voice:i.voice||{tts:{provider:"browser"},stt:{provider:"browser"}},skills:i.skills||[],memory:i.memory||{mode:"local"},tools:i.tools||["wave","lookAt","play_clip","setExpression"],version:i.version||"0.1.0"}}function Op(i){const e=i.lastIndexOf("/");return e>=0?i.slice(0,e+1):i}async function ay(i,e){if(!i._baseURI)return null;try{const t=new URL(e,i._baseURI).href,n=await fetch(t);return n.ok?n.text():null}catch{return null}}class Dn extends Error{constructor(e,t,{status:n}={}){super(t),this.name="AgentResolveError",this.code=e,n!==void 0&&(this.status=n)}}async function oy(i,{fetchFn:e}){let t;try{t=await e(i,{credentials:"include"})}catch(n){throw new Dn("network",`network error fetching ${i}: ${n.message||n}`)}if(t.status===401||t.status===403)throw new Dn("unauthorized",`unauthorized fetching ${i} (${t.status})`,{status:t.status});if(t.status===404)throw new Dn("not_found",`resource not found: ${i}`,{status:404});if(!t.ok)throw new Dn("network",`request failed: ${i} (${t.status})`,{status:t.status});try{return await t.json()}catch(n){throw new Dn("network",`invalid JSON from ${i}: ${n.message||n}`)}}const $a=new Map,C2=100;async function I2(i,e){if(!i)throw new Dn("not-found","agentId required");if($a.has(i))return $a.get(i);const t=typeof location<"u"?location.origin:"",n=`${t}/api/agents/${encodeURIComponent(i)}`;let s;try{s=await fetch(n,{credentials:"include",signal:e})}catch(c){throw c?.name==="AbortError"?c:new Dn("network",`network error fetching ${n}: ${c.message||c}`)}if(s.status===404)throw new Dn("not-found",`agent ${i} not found`,{status:404});if(s.status===401||s.status===403)throw new Dn("unauthorized",`unauthorized (${s.status})`,{status:s.status});if(!s.ok)throw new Dn("network",`request failed (${s.status})`,{status:s.status});let r;try{r=await s.json()}catch{throw new Dn("network",`invalid JSON from ${n}`)}const a=r?.agent?.manifestUrl??null;let o=null;if(a)try{o=new URL(a,t).href}catch{o=a}return $a.size>=C2&&$a.delete($a.keys().next().value),$a.set(i,o),o}async function S2(i,{origin:e=typeof location<"u"?location.origin:"",fetchFn:t=fetch}={}){if(!i)throw new Dn("not_found","agentId required");const n=t.bind(typeof globalThis<"u"?globalThis:void 0),r=(await oy(`${e}/api/agents/${encodeURIComponent(i)}`,{fetchFn:n}))?.agent;if(!r)throw new Dn("not_found",`agent ${i} not found`);if(!r.avatar_id)throw new Dn("no_avatar",`agent ${i} has no avatar bound`);const o=(await oy(`${e}/api/avatars/${encodeURIComponent(r.avatar_id)}`,{fetchFn:n}))?.avatar;if(!o||!o.url)throw new Dn("no_avatar",`avatar ${r.avatar_id} has no url`);const c=Array.isArray(r.skills)?r.skills.map(l=>typeof l=="string"?{name:l}:l).filter(Boolean):[];return{spec:"agent-manifest/0.1",name:r.name||"Agent",description:r.description||"",id:{agentId:r.id,owner:r.wallet_address,chainId:r.chain_id,walletAddress:r.wallet_address},body:{uri:o.url,format:"gltf-binary"},brain:{},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:c,memory:{mode:"remote",namespace:r.id},tools:["wave","lookAt","play_clip","setExpression","speak","remember"],version:"0.1.0",_baseURI:`${e}/agent/${r.id}/`,_source:"agent-id"}}function cy(i){if(!i)return null;if(typeof i=="object")return i.chainId&&i.agentId!==void 0?{chainId:Number(i.chainId),agentId:String(i.agentId),registry:i.registry||void 0}:null;const e=String(i).trim();if(!e)return null;let t=e.match(/^eip155:(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/);return t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:(t=e.match(/^eip155:(\d+)\/erc721:(0x[0-9a-fA-F]{40})\/(\d+)$/),t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:(t=e.match(/^onchain:(\d+):(\d+)$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^agent:\/\/(\d+)\/(\d+)$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^\/?a\/(\d+)\/(\d+)(?:\/(embed))?\/?$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^\/?a\/(\d+)\/(0x[0-9a-fA-F]{40})\/(\d+)\/?$/),t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:null)))))}function M2(i){const e=i.registry||Uh[i.chainId]?.identityRegistry;return e?`eip155:${i.chainId}:${e}:${i.agentId}`:`onchain:${i.chainId}:${i.agentId}`}function B2(i,{embed:e=!1,origin:t}={}){return`${t||(typeof location<"u"?location.origin:"")}/a/${i.chainId}/${i.agentId}${e?"/embed":""}`}const T2=["https://ipfs.io/ipfs/","https://dweb.link/ipfs/","https://cloudflare-ipfs.com/ipfs/","https://gateway.pinata.cloud/ipfs/"],R2="https://arweave.net/";function ly(i){return i?i.startsWith("ipfs://")?T2[0]+i.slice(7):i.startsWith("ar://")?R2+i.slice(5):i:""}const yc=new Map;function F2(i){return`${i.chainId}:${i.agentId}`}async function N2(i,{ethProvider:e,fresh:t=!1}={}){const n=cy(i);if(!n)throw new Error(`Unrecognised agent reference: ${i}`);const s={chainId:n.chainId,agentId:String(n.agentId),registry:n.registry||Uh[n.chainId]?.identityRegistry||null};if(!s.registry)throw new Error(`No registry deployed on chain ${s.chainId}`);const r=F2(s);if(!t&&yc.has(r))return yc.get(r);const a=sy[s.chainId]||null,o={ref:s,caip:M2(s),publicUrl:typeof location<"u"?B2(s):`/a/${s.chainId}/${s.agentId}`,chain:a?{name:a.name,testnet:!!a.testnet,explorer:a.explorer}:null,onchain:{owner:null,uri:null},metadata:null,metadataUrl:null,image:null,glbUrl:null,name:`Agent #${s.agentId}`,description:"",services:[]};try{const{owner:c,uri:l}=await E2({chainId:s.chainId,agentId:s.agentId,ethProvider:e});if(o.onchain={owner:c,uri:l},!l)return o.error="agentURI not set",yc.set(r,o),o;const h=await y2(l);if(!h.ok)return o.error=h.error,o.metadataUrl=h.resolvedUrl||null,yc.set(r,o),o;const u=h.data;o.metadata=u,o.metadataUrl=h.resolvedUrl||null,o.name=u?.name&&String(u.name)||o.name,o.description=u?.description&&String(u.description)||"",o.image=u?.image?String(u.image):null,o.services=Array.isArray(u?.services)?u.services:[],o.glbUrl=ry(u)}catch(c){o.error=c.message||String(c)}return yc.set(r,o),o}function D2(i){const e=Array.isArray(i.services)?i.services:[],t=e.find(a=>/brain|llm|chat/i.test(a?.name||a?.type||"")),n=e.filter(a=>/skill/i.test(a?.name||a?.type||"")),s=i.glbUrl?ly(i.glbUrl):"",r=i.image?ly(i.image):"";return{spec:"agent-manifest/0.1",_baseURI:i.metadataUrl?L2(i.metadataUrl):"",_source:"erc8004-resolver",id:{agentId:i.ref.agentId,chainId:i.ref.chainId,registry:i.ref.registry,owner:i.onchain.owner||void 0,walletAddress:i.onchain.owner||void 0,caip:i.caip,agentRegistry:m2(i.ref.chainId,i.ref.registry)},name:i.name,description:i.description,image:r,body:{uri:s||r,format:"gltf-binary"},brain:t?{provider:"remote",endpoint:t.endpoint}:{provider:"none"},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:n.map(a=>({name:a.name,uri:a.endpoint})),memory:{mode:"local",namespace:i.caip},tools:["wave","lookAt","play_clip","setExpression"],version:"0.1.0",services:e,x402Support:!!(i.metadata?.x402Support||i.metadata?.x402),embedPolicy:i.metadata?.embedPolicy||null}}function L2(i){const e=i.lastIndexOf("/");return e>=0?i.slice(0,e+1):i}const hy=1,P2=256;function Qh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}const Qp={speak:"speak",gesture:"gesture",emote:"emote",look:"look-at"};class k2{constructor({protocol:e,avatar:t=null,manifest:n,window:s}){this._protocol=e,this._avatar=t,this._manifest=n,this._win=s,this._subscribed=!1,this._evtQueue=[],this._running=!1,this._onMessage=this._handleMessage.bind(this),this._onAction=this._handleAction.bind(this)}start(){if(this._running)return;this._running=!0,this._win.addEventListener("message",this._onMessage),this._protocol.on("*",this._onAction);const e=this._manifest?.id?.agentId||this._manifest?.agentId||"",t=[...Object.keys(Qp),"setAgent","ping","subscribe"];this._toParent({kind:"event",op:"ready",payload:{agentId:e,capabilities:t}})}stop(){this._running&&(this._running=!1,this._win.removeEventListener("message",this._onMessage),this._protocol.off("*",this._onAction),this._evtQueue=[])}_allowedOrigins(){const e=this._manifest?.policy;if(!e)return[];const t=e.origins||e.allowlist||[];return Array.isArray(t)?t:[t]}_originAllowed(e){const t=this._allowedOrigins();return t.length===0?!0:t.some(n=>{if(n==="*")return!0;try{return new URL(n).origin===e}catch{return n===e}})}_toParent(e){this._win.parent.postMessage({...e,v:hy,source:"agent-3d",id:e.id||Qh()},"*")}_reply(e,t){this._toParent({id:Qh(),inReplyTo:e.id,kind:"response",op:e.op==="ping"?"pong":e.op,payload:t})}_replyError(e,t,n){this._toParent({id:Qh(),inReplyTo:e.id,kind:"response",op:e.op,payload:{error:`${t}: ${n}`}})}_handleMessage(e){if(e.source!==this._win.parent||!this._originAllowed(e.origin))return;const t=e.data;if(!t||t.v!==hy||t.source!=="agent-host"||t.kind!=="request")return;const{op:n,payload:s={}}=t;if(n==="ping"){this._reply(t,{capabilities:[...Object.keys(Qp),"subscribe"]});return}if(n==="subscribe"){this._subscribed=!0,this._reply(t,{ok:!0});for(const a of this._evtQueue)this._toParent(a);this._evtQueue=[];return}if(n==="setAgent"){this._replyError(t,"not_supported","setAgent requires host to update the iframe src");return}const r=Qp[n];if(!r){this._replyError(t,"unknown_op",`Unknown op "${n}"`);return}try{this._protocol.emit({type:r,payload:s}),this._reply(t,{ok:!0})}catch(a){this._replyError(t,"emit_failed",a?.message||String(a))}}_handleAction(e){if(!this._running)return;const t={id:Qh(),kind:"event",op:"action",payload:{type:e.type,payload:e.payload,agentId:e.agentId}};if(!this._subscribed){this._evtQueue.length>=P2&&this._evtQueue.shift(),this._evtQueue.push(t);return}this._toParent(t)}}const U2={SPEAK:"speak"};class O2 extends EventTarget{constructor(){super(),this._history=[],this._maxHistory=200}emit(e){const t={type:e.type,payload:e.payload||{},timestamp:Date.now(),agentId:e.agentId||"default",sourceSkill:e.sourceSkill||null};this._history.push(t),this._history.length>this._maxHistory&&this._history.shift(),this.dispatchEvent(new CustomEvent(t.type,{detail:t})),this.dispatchEvent(new CustomEvent("*",{detail:t}))}on(e,t){this._wrap(e,t,!1)}once(e,t){this._wrap(e,t,!0)}off(e,t){t.__protocolWrapped?this.removeEventListener(e,t.__protocolWrapped):this.removeEventListener(e,t)}get history(){return this._history.slice()}recent(e,t=10){return this._history.filter(n=>n.type===e).slice(-t)}_wrap(e,t,n){const s=r=>t(r.detail);t.__protocolWrapped=s,n?this.addEventListener(e,s,{once:!0}):this.addEventListener(e,s)}}const uy=new O2,Q2=["inline","floating","section","fullscreen"],dy=(()=>{try{return new URL(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:nr&&nr.tagName.toUpperCase()==="SCRIPT"&&nr.src||new URL("agent-3d.umd.cjs",document.baseURI).href).origin}catch{return""}})();function G2(i,e,t=[]){if(!i)return!1;let n;try{n=new URL(i).hostname.toLowerCase()}catch{return!1}if(t.some(o=>n===o||n.endsWith("."+o)))return!0;const s=e?.origins?.hosts??[],r=e?.origins?.mode??"allowlist",a=s.some(o=>{const c=o.toLowerCase();return c.startsWith("*.")?n.endsWith(c.slice(1))&&n!==c.slice(2):n===c});return r==="allowlist"?a:!a}const H2=`
+`)}async export(){return{version:"memory/0.1",index:this.indexText,files:Object.fromEntries(this.files),timeline:this.timeline}}async import(e,{strategy:t="merge"}={}){if(t==="replace")this.files=new Map(Object.entries(e.files||{})),this.timeline=e.timeline||[];else{for(const[n,s]of Object.entries(e.files||{}))this.files.has(n)||this.files.set(n,s);this.timeline=[...this.timeline,...e.timeline||[]].slice(-1e3)}this._rebuildIndex(),this._persist()}}const YR="6.16.0";function JR(i,e,t){const n=e.split("|").map(r=>r.trim());for(let r=0;r<n.length;r++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof i===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${t}`,s.value=i,s}async function Hn(i){const e=Object.keys(i);return(await Promise.all(e.map(n=>Promise.resolve(i[n])))).reduce((n,s,r)=>(n[e[r]]=s,n),{})}function Ye(i,e,t){for(let n in e){let s=e[n];const r=t?t[n]:null;r&&JR(s,r,n),Object.defineProperty(i,n,{enumerable:!0,value:s,writable:!1})}}function Pa(i,e){if(i==null)return"null";if(e==null&&(e=new Set),typeof i=="object"){if(e.has(i))return"[Circular]";e.add(i)}if(Array.isArray(i))return"[ "+i.map(t=>Pa(t,e)).join(", ")+" ]";if(i instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let s=0;s<i.length;s++)n+=t[i[s]>>4],n+=t[i[s]&15];return n}if(typeof i=="object"&&typeof i.toJSON=="function")return Pa(i.toJSON(),e);switch(typeof i){case"boolean":case"number":case"symbol":return i.toString();case"bigint":return BigInt(i).toString();case"string":return JSON.stringify(i);case"object":{const t=Object.keys(i);return t.sort(),"{ "+t.map(n=>`${Pa(n,e)}: ${Pa(i[n],e)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Tn(i,e){return i&&i.code===e}function Rf(i){return Tn(i,"CALL_EXCEPTION")}function Qt(i,e,t){let n=i;{const r=[];if(t){if("message"in t||"code"in t||"name"in t)throw new Error(`value will overwrite populated values: ${Pa(t)}`);for(const a in t){if(a==="shortMessage")continue;const o=t[a];r.push(a+"="+Pa(o))}}r.push(`code=${e}`),r.push(`version=${YR}`),r.length&&(i+=" ("+r.join(", ")+")")}let s;switch(e){case"INVALID_ARGUMENT":s=new TypeError(i);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":s=new RangeError(i);break;default:s=new Error(i)}return Ye(s,{code:e}),t&&Object.assign(s,t),s.shortMessage==null&&Ye(s,{shortMessage:n}),s}function pe(i,e,t,n){if(!i)throw Qt(e,t,n)}function V(i,e,t,n){pe(i,e,"INVALID_ARGUMENT",{argument:t,value:n})}function sx(i,e,t){t==null&&(t=""),t&&(t=": "+t),pe(i>=e,"missing argument"+t,"MISSING_ARGUMENT",{count:i,expectedCount:e}),pe(i<=e,"too many arguments"+t,"UNEXPECTED_ARGUMENT",{count:i,expectedCount:e})}["NFD","NFC","NFKD","NFKC"].reduce((i,e)=>{try{if("test".normalize(e)!=="test")throw new Error("bad");if(e==="NFD"&&"é".normalize("NFD")!=="é")throw new Error("broken");i.push(e)}catch{}return i},[]);function ih(i,e,t){if(t==null&&(t=""),i!==e){let n=t,s="new";t&&(n+=".",s+=" "+t),pe(!1,`private constructor; use ${n}from* methods`,"UNSUPPORTED_OPERATION",{operation:s})}}function rx(i,e,t){if(i instanceof Uint8Array)return t?new Uint8Array(i):i;if(typeof i=="string"&&i.length%2===0&&i.match(/^0x[0-9a-f]*$/i)){const n=new Uint8Array((i.length-2)/2);let s=2;for(let r=0;r<n.length;r++)n[r]=parseInt(i.substring(s,s+2),16),s+=2;return n}V(!1,"invalid BytesLike value",e||"value",i)}function ut(i,e){return rx(i,e,!1)}function zn(i,e){return rx(i,e,!0)}function Pt(i,e){return!(typeof i!="string"||!i.match(/^0x[0-9A-Fa-f]*$/)||typeof e=="number"&&i.length!==2+2*e||e===!0&&i.length%2!==0)}function Ff(i){return Pt(i,!0)||i instanceof Uint8Array}const ax="0123456789abcdef";function Ce(i){const e=ut(i);let t="0x";for(let n=0;n<e.length;n++){const s=e[n];t+=ax[(s&240)>>4]+ax[s&15]}return t}function Gt(i){return"0x"+i.map(e=>Ce(e).substring(2)).join("")}function ka(i){return Pt(i,!0)?(i.length-2)/2:ut(i).length}function Kt(i,e,t){const n=ut(i);return t!=null&&t>n.length&&pe(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:n,length:n.length,offset:t}),Ce(n.slice(e??0,t??n.length))}function ox(i,e,t){const n=ut(i);pe(e>=n.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(n),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),t?s.set(n,e-n.length):s.set(n,0),Ce(s)}function us(i,e){return ox(i,e,!0)}function ZR(i,e){return ox(i,e,!1)}const Jo=BigInt(0),Ti=BigInt(1),Ua=9007199254740991;function $R(i,e){const t=sh(i,"value"),n=BigInt(dt(e,"width"));if(pe(t>>n===Jo,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:i}),t>>n-Ti){const s=(Ti<<n)-Ti;return-((~t&s)+Ti)}return t}function cx(i,e){let t=Ne(i,"value");const n=BigInt(dt(e,"width")),s=Ti<<n-Ti;if(t<Jo){t=-t,pe(t<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:i});const r=(Ti<<n)-Ti;return(~t&r)+Ti}else pe(t<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:i});return t}function Zo(i,e){const t=sh(i,"value"),n=BigInt(dt(e,"bits"));return t&(Ti<<n)-Ti}function Ne(i,e){switch(typeof i){case"bigint":return i;case"number":return V(Number.isInteger(i),"underflow",e||"value",i),V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),BigInt(i);case"string":try{if(i==="")throw new Error("empty string");return i[0]==="-"&&i[1]!=="-"?-BigInt(i.substring(1)):BigInt(i)}catch(t){V(!1,`invalid BigNumberish string: ${t.message}`,e||"value",i)}}V(!1,"invalid BigNumberish value",e||"value",i)}function sh(i,e){const t=Ne(i,e);return pe(t>=Jo,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:i}),t}const lx="0123456789abcdef";function Nf(i){if(i instanceof Uint8Array){let e="0x0";for(const t of i)e+=lx[t>>4],e+=lx[t&15];return BigInt(e)}return Ne(i)}function dt(i,e){switch(typeof i){case"bigint":return V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),Number(i);case"number":return V(Number.isInteger(i),"underflow",e||"value",i),V(i>=-Ua&&i<=Ua,"overflow",e||"value",i),i;case"string":try{if(i==="")throw new Error("empty string");return dt(BigInt(i),e)}catch(t){V(!1,`invalid numeric string: ${t.message}`,e||"value",i)}}V(!1,"invalid numeric value",e||"value",i)}function eF(i){return dt(Nf(i))}function Ks(i,e){const t=sh(i,"value");let n=t.toString(16);if(e==null)n.length%2&&(n="0"+n);else{const s=dt(e,"width");if(s===0&&t===Jo)return"0x";for(pe(s*2>=n.length,`value exceeds width (${s} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:i});n.length<s*2;)n="0"+n}return"0x"+n}function rn(i,e){const t=sh(i,"value");if(t===Jo)return new Uint8Array(0);let n=t.toString(16);n.length%2&&(n="0"+n);const s=new Uint8Array(n.length/2);for(let r=0;r<s.length;r++){const a=r*2;s[r]=parseInt(n.substring(a,a+2),16)}return s}function Ri(i){let e=Ce(Ff(i)?i:rn(i)).substring(2);for(;e.startsWith("0");)e=e.substring(1);return e===""&&(e="0"),"0x"+e}const hx="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";BigInt(0);const ux=BigInt(58);function tF(i){const e=ut(i);let t=Nf(e),n="";for(;t;)n=hx[Number(t%ux)]+n,t/=ux;for(let s=0;s<e.length&&!e[s];s++)n=hx[0]+n;return n}function nF(i){i=atob(i);const e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return ut(e)}function iF(i){const e=ut(i);let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}class dx{filter;emitter;#e;constructor(e,t,n){this.#e=t,Ye(this,{emitter:e,filter:n})}async removeListener(){this.#e!=null&&await this.emitter.off(this.filter,this.#e)}}function sF(i,e,t,n,s){V(!1,`invalid codepoint at offset ${e}; ${i}`,"bytes",t)}function fx(i,e,t,n,s){if(i==="BAD_PREFIX"||i==="UNEXPECTED_CONTINUE"){let r=0;for(let a=e+1;a<t.length&&t[a]>>6===2;a++)r++;return r}return i==="OVERRUN"?t.length-e-1:0}function rF(i,e,t,n,s){return i==="OVERLONG"?(V(typeof s=="number","invalid bad code point for replacement","badCodepoint",s),n.push(s),0):(n.push(65533),fx(i,e,t))}const aF=Object.freeze({error:sF,ignore:fx,replace:rF});function oF(i,e){e==null&&(e=aF.error);const t=ut(i,"bytes"),n=[];let s=0;for(;s<t.length;){const r=t[s++];if(r>>7===0){n.push(r);continue}let a=null,o=null;if((r&224)===192)a=1,o=127;else if((r&240)===224)a=2,o=2047;else if((r&248)===240)a=3,o=65535;else{(r&192)===128?s+=e("UNEXPECTED_CONTINUE",s-1,t,n):s+=e("BAD_PREFIX",s-1,t,n);continue}if(s-1+a>=t.length){s+=e("OVERRUN",s-1,t,n);continue}let c=r&(1<<8-a-1)-1;for(let l=0;l<a;l++){let h=t[s];if((h&192)!=128){s+=e("MISSING_CONTINUE",s,t,n),c=null;break}c=c<<6|h&63,s++}if(c!==null){if(c>1114111){s+=e("OUT_OF_RANGE",s-1-a,t,n,c);continue}if(c>=55296&&c<=57343){s+=e("UTF16_SURROGATE",s-1-a,t,n,c);continue}if(c<=o){s+=e("OVERLONG",s-1-a,t,n,c);continue}n.push(c)}}return n}function ds(i,e){V(typeof i=="string","invalid string value","str",i);let t=[];for(let n=0;n<i.length;n++){const s=i.charCodeAt(n);if(s<128)t.push(s);else if(s<2048)t.push(s>>6|192),t.push(s&63|128);else if((s&64512)==55296){n++;const r=i.charCodeAt(n);V(n<i.length&&(r&64512)===56320,"invalid surrogate pair","str",i);const a=65536+((s&1023)<<10)+(r&1023);t.push(a>>18|240),t.push(a>>12&63|128),t.push(a>>6&63|128),t.push(a&63|128)}else t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128)}return new Uint8Array(t)}function cF(i){return i.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10&1023)+55296,(e&1023)+56320))).join("")}function rh(i,e){return cF(oF(i,e))}function px(i){async function e(t,n){pe(n==null||!n.cancelled,"request cancelled before sending","CANCELLED");const s=t.url.split(":")[0].toLowerCase();pe(s==="http"||s==="https",`unsupported protocol ${s}`,"UNSUPPORTED_OPERATION",{info:{protocol:s},operation:"request"}),pe(s==="https"||!t.credentials||t.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let r=null;const a=new AbortController,o=setTimeout(()=>{r=Qt("request timeout","TIMEOUT"),a.abort()},t.timeout);n&&n.addListener(()=>{r=Qt("request cancelled","CANCELLED"),a.abort()});const c=Object.assign({},i,{method:t.method,headers:new Headers(Array.from(t)),body:t.body||void 0,signal:a.signal});let l;try{l=await fetch(t.url,c)}catch(f){throw clearTimeout(o),r||f}clearTimeout(o);const h={};l.headers.forEach((f,p)=>{h[p.toLowerCase()]=f});const u=await l.arrayBuffer(),d=u==null?null:new Uint8Array(u);return{statusCode:l.status,statusMessage:l.statusText,headers:h,body:d}}return e}const lF=12,hF=250;let Ax=px();const uF=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),dF=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let Df=!1;async function gx(i,e){try{const t=i.match(uF);if(!t)throw new Error("invalid data");return new js(200,"OK",{"content-type":t[1]||"text/plain"},t[2]?nF(t[3]):pF(t[3]))}catch{return new js(599,"BAD REQUEST (invalid data: URI)",{},null,new zi(i))}}function mx(i){async function e(t,n){try{const s=t.match(dF);if(!s)throw new Error("invalid link");return new zi(`${i}${s[2]}`)}catch{return new js(599,"BAD REQUEST (invalid IPFS URI)",{},null,new zi(t))}}return e}const ah={data:gx,ipfs:mx("https://gateway.ipfs.io/ipfs/")},xx=new WeakMap;class fF{#e;#t;constructor(e){this.#e=[],this.#t=!1,xx.set(e,()=>{if(!this.#t){this.#t=!0;for(const t of this.#e)setTimeout(()=>{t()},0);this.#e=[]}})}addListener(e){pe(!this.#t,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"}),this.#e.push(e)}get cancelled(){return this.#t}checkSignal(){pe(!this.cancelled,"cancelled","CANCELLED",{})}}function oh(i){if(i==null)throw new Error("missing signal; should not happen");return i.checkSignal(),i}class zi{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;#c;#h;#u;get url(){return this.#a}set url(e){this.#a=String(e)}get body(){return this.#r==null?null:new Uint8Array(this.#r)}set body(e){if(e==null)this.#r=void 0,this.#o=void 0;else if(typeof e=="string")this.#r=ds(e),this.#o="text/plain";else if(e instanceof Uint8Array)this.#r=e,this.#o="application/octet-stream";else if(typeof e=="object")this.#r=ds(JSON.stringify(e)),this.#o="application/json";else throw new Error("invalid body")}hasBody(){return this.#r!=null}get method(){return this.#i?this.#i:this.hasBody()?"POST":"GET"}set method(e){e==null&&(e=""),this.#i=String(e).toUpperCase()}get headers(){const e=Object.assign({},this.#n);return this.#f&&(e.authorization=`Basic ${iF(ds(this.#f))}`),this.allowGzip&&(e["accept-encoding"]="gzip"),e["content-type"]==null&&this.#o&&(e["content-type"]=this.#o),this.body&&(e["content-length"]=String(this.body.length)),e}getHeader(e){return this.headers[e.toLowerCase()]}setHeader(e,t){this.#n[String(e).toLowerCase()]=String(t)}clearHeaders(){this.#n={}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const s=t[n++];return{value:[s,e[s]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#f||null}setCredentials(e,t){V(!e.match(/:/),"invalid basic authentication username","username","[REDACTED]"),this.#f=`${e}:${t}`}get allowGzip(){return this.#t}set allowGzip(e){this.#t=!!e}get allowInsecureAuthentication(){return!!this.#e}set allowInsecureAuthentication(e){this.#e=!!e}get timeout(){return this.#s}set timeout(e){V(e>=0,"timeout must be non-zero","timeout",e),this.#s=e}get preflightFunc(){return this.#l||null}set preflightFunc(e){this.#l=e}get processFunc(){return this.#p||null}set processFunc(e){this.#p=e}get retryFunc(){return this.#A||null}set retryFunc(e){this.#A=e}get getUrlFunc(){return this.#u||Ax}set getUrlFunc(e){this.#u=e}constructor(e){this.#a=String(e),this.#e=!1,this.#t=!0,this.#n={},this.#i="",this.#s=3e5,this.#h={slotInterval:hF,maxAttempts:lF},this.#u=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#r?Ce(this.#r):"null"}>`}setThrottleParams(e){e.slotInterval!=null&&(this.#h.slotInterval=e.slotInterval),e.maxAttempts!=null&&(this.#h.maxAttempts=e.maxAttempts)}async#d(e,t,n,s,r){if(e>=this.#h.maxAttempts)return r.makeServerError("exceeded maximum retry limit");pe(bx()<=t,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:s}),n>0&&await AF(n);let a=this.clone();const o=(a.url.split(":")[0]||"").toLowerCase();if(o in ah){const h=await ah[o](a.url,oh(s.#c));if(h instanceof js){let u=h;if(this.processFunc){oh(s.#c);try{u=await this.processFunc(a,u)}catch(d){(d.throttle==null||typeof d.stall!="number")&&u.makeServerError("error in post-processing function",d).assertOk()}}return u}a=h}this.preflightFunc&&(a=await this.preflightFunc(a));const c=await this.getUrlFunc(a,oh(s.#c));let l=new js(c.statusCode,c.statusMessage,c.headers,c.body,s);if(l.statusCode===301||l.statusCode===302){try{const h=l.headers.location||"";return a.redirect(h).#d(e+1,t,0,s,l)}catch{}return l}else if(l.statusCode===429&&(this.retryFunc==null||await this.retryFunc(a,l,e))){const h=l.headers["retry-after"];let u=this.#h.slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return typeof h=="string"&&h.match(/^[1-9][0-9]*$/)&&(u=parseInt(h)),a.clone().#d(e+1,t,u,s,l)}if(this.processFunc){oh(s.#c);try{l=await this.processFunc(a,l)}catch(h){(h.throttle==null||typeof h.stall!="number")&&l.makeServerError("error in post-processing function",h).assertOk();let u=this.#h.slotInterval*Math.trunc(Math.random()*Math.pow(2,e));return h.stall>=0&&(u=h.stall),a.clone().#d(e+1,t,u,s,l)}}return l}send(){return pe(this.#c==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"}),this.#c=new fF(this),this.#d(0,bx()+this.timeout,0,this,new js(0,"",{},null,this))}cancel(){pe(this.#c!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const e=xx.get(this);if(!e)throw new Error("missing signal; should not happen");e()}redirect(e){const t=this.url.split(":")[0].toLowerCase(),n=e.split(":")[0].toLowerCase();pe(this.method==="GET"&&(t!=="https"||n!=="http")&&e.match(/^https?:/),"unsupported redirect","UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(e)})`});const s=new zi(e);return s.method="GET",s.allowGzip=this.allowGzip,s.timeout=this.timeout,s.#n=Object.assign({},this.#n),this.#r&&(s.#r=new Uint8Array(this.#r)),s.#o=this.#o,s}clone(){const e=new zi(this.url);return e.#i=this.#i,this.#r&&(e.#r=this.#r),e.#o=this.#o,e.#n=Object.assign({},this.#n),e.#f=this.#f,this.allowGzip&&(e.allowGzip=!0),e.timeout=this.timeout,this.allowInsecureAuthentication&&(e.allowInsecureAuthentication=!0),e.#l=this.#l,e.#p=this.#p,e.#A=this.#A,e.#h=Object.assign({},this.#h),e.#u=this.#u,e}static lockConfig(){Df=!0}static getGateway(e){return ah[e.toLowerCase()]||null}static registerGateway(e,t){if(e=e.toLowerCase(),e==="http"||e==="https")throw new Error(`cannot intercept ${e}; use registerGetUrl`);if(Df)throw new Error("gateways locked");ah[e]=t}static registerGetUrl(e){if(Df)throw new Error("gateways locked");Ax=e}static createGetUrlFunc(e){return px(e)}static createDataGateway(){return gx}static createIpfsGatewayFunc(e){return mx(e)}}class js{#e;#t;#n;#i;#s;#a;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#i?Ce(this.#i):"null"}>`}get statusCode(){return this.#e}get statusMessage(){return this.#t}get headers(){return Object.assign({},this.#n)}get body(){return this.#i==null?null:new Uint8Array(this.#i)}get bodyText(){try{return this.#i==null?"":rh(this.#i)}catch{pe(!1,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch{pe(!1,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const e=this.headers,t=Object.keys(e);let n=0;return{next:()=>{if(n<t.length){const s=t[n++];return{value:[s,e[s]],done:!1}}return{value:void 0,done:!0}}}}constructor(e,t,n,s,r){this.#e=e,this.#t=t,this.#n=Object.keys(n).reduce((a,o)=>(a[o.toLowerCase()]=String(n[o]),a),{}),this.#i=s==null?null:new Uint8Array(s),this.#s=r||null,this.#a={message:""}}makeServerError(e,t){let n;e?n=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${e})`:(e=`${this.statusCode} ${this.statusMessage}`,n=`CLIENT ESCALATED SERVER ERROR (${e})`);const s=new js(599,n,this.headers,this.body,this.#s||void 0);return s.#a={message:e,error:t},s}throwThrottleError(e,t){t==null?t=-1:V(Number.isInteger(t)&&t>=0,"invalid stall timeout","stall",t);const n=new Error(e||"throttling requests");throw Ye(n,{stall:t,throttle:!0}),n}getHeader(e){return this.headers[e.toLowerCase()]}hasBody(){return this.#i!=null}get request(){return this.#s}ok(){return this.#a.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:e,error:t}=this.#a;e===""&&(e=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let s=null;try{this.#i&&(s=rh(this.#i))}catch{}pe(!1,e,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:t,info:{requestUrl:n,responseBody:s,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}}function bx(){return new Date().getTime()}function pF(i){return ds(i.replace(/%([0-9a-f][0-9a-f])/gi,(e,t)=>String.fromCharCode(parseInt(t,16))))}function AF(i){return new Promise(e=>setTimeout(e,i))}function gF(i){let e=i.toString(16);for(;e.length<2;)e="0"+e;return"0x"+e}function Ex(i,e,t){let n=0;for(let s=0;s<t;s++)n=n*256+i[e+s];return n}function yx(i,e,t,n){const s=[];for(;t<e+1+n;){const r=_x(i,t);s.push(r.result),t+=r.consumed,pe(t<=e+1+n,"child data too short","BUFFER_OVERRUN",{buffer:i,length:n,offset:e})}return{consumed:1+n,result:s}}function _x(i,e){pe(i.length!==0,"data too short","BUFFER_OVERRUN",{buffer:i,length:0,offset:1});const t=n=>{pe(n<=i.length,"data short segment too short","BUFFER_OVERRUN",{buffer:i,length:i.length,offset:n})};if(i[e]>=248){const n=i[e]-247;t(e+1+n);const s=Ex(i,e+1,n);return t(e+1+n+s),yx(i,e,e+1+n,n+s)}else if(i[e]>=192){const n=i[e]-192;return t(e+1+n),yx(i,e,e+1,n)}else if(i[e]>=184){const n=i[e]-183;t(e+1+n);const s=Ex(i,e+1,n);t(e+1+n+s);const r=Ce(i.slice(e+1+n,e+1+n+s));return{consumed:1+n+s,result:r}}else if(i[e]>=128){const n=i[e]-128;t(e+1+n);const s=Ce(i.slice(e+1,e+1+n));return{consumed:1+n,result:s}}return{consumed:1,result:gF(i[e])}}function $o(i){const e=ut(i,"data"),t=_x(e,0);return V(t.consumed===e.length,"unexpected junk after rlp payload","data",i),t.result}function wx(i){const e=[];for(;i;)e.unshift(i&255),i>>=8;return e}function vx(i){if(Array.isArray(i)){let n=[];if(i.forEach(function(r){n=n.concat(vx(r))}),n.length<=55)return n.unshift(192+n.length),n;const s=wx(n.length);return s.unshift(247+s.length),s.concat(n)}const e=Array.prototype.slice.call(ut(i,"object"));if(e.length===1&&e[0]<=127)return e;if(e.length<=55)return e.unshift(128+e.length),e;const t=wx(e.length);return t.unshift(183+t.length),t.concat(e)}const Cx="0123456789abcdef";function fs(i){let e="0x";for(const t of vx(i))e+=Cx[t>>4],e+=Cx[t&15];return e}const Vn=32,Lf=new Uint8Array(Vn),mF=["then"],ch={},Ix=new WeakMap;function Cr(i){return Ix.get(i)}function Sx(i,e){Ix.set(i,e)}function ec(i,e){const t=new Error(`deferred error during ABI decoding triggered accessing ${i}`);throw t.error=e,t}function Pf(i,e,t){return i.indexOf(null)>=0?e.map((n,s)=>n instanceof ps?Pf(Cr(n),n,t):n):i.reduce((n,s,r)=>{let a=e.getValue(s);return s in n||(t&&a instanceof ps&&(a=Pf(Cr(a),a,t)),n[s]=a),n},{})}class ps extends Array{#e;constructor(...e){const t=e[0];let n=e[1],s=(e[2]||[]).slice(),r=!0;t!==ch&&(n=e,s=[],r=!1),super(n.length),n.forEach((c,l)=>{this[l]=c});const a=s.reduce((c,l)=>(typeof l=="string"&&c.set(l,(c.get(l)||0)+1),c),new Map);if(Sx(this,Object.freeze(n.map((c,l)=>{const h=s[l];return h!=null&&a.get(h)===1?h:null}))),this.#e=[],this.#e==null&&this.#e,!r)return;Object.freeze(this);const o=new Proxy(this,{get:(c,l,h)=>{if(typeof l=="string"){if(l.match(/^[0-9]+$/)){const d=dt(l,"%index");if(d<0||d>=this.length)throw new RangeError("out of result range");const f=c[d];return f instanceof Error&&ec(`index ${d}`,f),f}if(mF.indexOf(l)>=0)return Reflect.get(c,l,h);const u=c[l];if(u instanceof Function)return function(...d){return u.apply(this===h?c:this,d)};if(!(l in c))return c.getValue.apply(this===h?c:this,[l])}return Reflect.get(c,l,h)}});return Sx(o,Cr(this)),o}toArray(e){const t=[];return this.forEach((n,s)=>{n instanceof Error&&ec(`index ${s}`,n),e&&n instanceof ps&&(n=n.toArray(e)),t.push(n)}),t}toObject(e){const t=Cr(this);return t.reduce((n,s,r)=>(pe(s!=null,`value at index ${r} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),Pf(t,this,e)),{})}slice(e,t){e==null&&(e=0),e<0&&(e+=this.length,e<0&&(e=0)),t==null&&(t=this.length),t<0&&(t+=this.length,t<0&&(t=0)),t>this.length&&(t=this.length);const n=Cr(this),s=[],r=[];for(let a=e;a<t;a++)s.push(this[a]),r.push(n[a]);return new ps(ch,s,r)}filter(e,t){const n=Cr(this),s=[],r=[];for(let a=0;a<this.length;a++){const o=this[a];o instanceof Error&&ec(`index ${a}`,o),e.call(t,o,a,this)&&(s.push(o),r.push(n[a]))}return new ps(ch,s,r)}map(e,t){const n=[];for(let s=0;s<this.length;s++){const r=this[s];r instanceof Error&&ec(`index ${s}`,r),n.push(e.call(t,r,s,this))}return n}getValue(e){const t=Cr(this).indexOf(e);if(t===-1)return;const n=this[t];return n instanceof Error&&ec(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(e,t){return new ps(ch,e,t)}}function Mx(i){let e=rn(i);return pe(e.length<=Vn,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:Vn,offset:e.length}),e.length!==Vn&&(e=zn(Gt([Lf.slice(e.length%Vn),e]))),e}class As{name;type;localName;dynamic;constructor(e,t,n,s){Ye(this,{name:e,type:t,localName:n,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){V(!1,e,this.localName,t)}}class kf{#e;#t;constructor(){this.#e=[],this.#t=0}get data(){return Gt(this.#e)}get length(){return this.#t}#n(e){return this.#e.push(e),this.#t+=e.length,e.length}appendWriter(e){return this.#n(zn(e.data))}writeBytes(e){let t=zn(e);const n=t.length%Vn;return n&&(t=zn(Gt([t,Lf.slice(n)]))),this.#n(t)}writeValue(e){return this.#n(Mx(e))}writeUpdatableValue(){const e=this.#e.length;return this.#e.push(Lf),this.#t+=Vn,t=>{this.#e[e]=Mx(t)}}}class Uf{allowLoose;#e;#t;#n;#i;#s;constructor(e,t,n){Ye(this,{allowLoose:!!t}),this.#e=zn(e),this.#n=0,this.#i=null,this.#s=n??1024,this.#t=0}get data(){return Ce(this.#e)}get dataLength(){return this.#e.length}get consumed(){return this.#t}get bytes(){return new Uint8Array(this.#e)}#a(e){if(this.#i)return this.#i.#a(e);this.#n+=e,pe(this.#s<1||this.#n<=this.#s*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#s} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:zn(this.#e),offset:this.#t,length:e,info:{bytesRead:this.#n,dataLength:this.dataLength}})}#r(e,t,n){let s=Math.ceil(t/Vn)*Vn;return this.#t+s>this.#e.length&&(this.allowLoose&&n&&this.#t+t<=this.#e.length?s=t:pe(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:zn(this.#e),length:this.#e.length,offset:this.#t+s})),this.#e.slice(this.#t,this.#t+s)}subReader(e){const t=new Uf(this.#e.slice(this.#t+e),this.allowLoose,this.#s);return t.#i=this,t}readBytes(e,t){let n=this.#r(0,e,!!t);return this.#a(e),this.#t+=n.length,n.slice(0,e)}readValue(){return Nf(this.readBytes(Vn))}readIndex(){return eF(this.readBytes(Vn))}}function lh(i){if(!Number.isSafeInteger(i)||i<0)throw new Error(`Wrong positive integer: ${i}`)}function Of(i,...e){if(!(i instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(i.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${i.length}`)}function xF(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");lh(i.outputLen),lh(i.blockLen)}function Oa(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Bx(i,e){Of(i);const t=e.outputLen;if(i.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const Qf=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;const Tx=i=>i instanceof Uint8Array,bF=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Gf=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Vi=(i,e)=>i<<32-e|i>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function EF(i){if(typeof i!="string")throw new Error(`utf8ToBytes expected string, got ${typeof i}`);return new Uint8Array(new TextEncoder().encode(i))}function hh(i){if(typeof i=="string"&&(i=EF(i)),!Tx(i))throw new Error(`expected Uint8Array, got ${typeof i}`);return i}function yF(...i){const e=new Uint8Array(i.reduce((n,s)=>n+s.length,0));let t=0;return i.forEach(n=>{if(!Tx(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}class Hf{clone(){return this._cloneInto()}}function zf(i){const e=n=>i().update(hh(n)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function _F(i=32){if(Qf&&typeof Qf.getRandomValues=="function")return Qf.getRandomValues(new Uint8Array(i));throw new Error("crypto.getRandomValues must be defined")}class Rx extends Hf{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,xF(e);const n=hh(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,r=new Uint8Array(s);r.set(n.length>s?e.create().update(n).digest():n);for(let a=0;a<r.length;a++)r[a]^=54;this.iHash.update(r),this.oHash=e.create();for(let a=0;a<r.length;a++)r[a]^=106;this.oHash.update(r),r.fill(0)}update(e){return Oa(this),this.iHash.update(e),this}digestInto(e){Oa(this),Of(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:s,destroyed:r,blockLen:a,outputLen:o}=this;return e=e,e.finished=s,e.destroyed=r,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Fx=(i,e,t)=>new Rx(i,e).update(t).digest();Fx.create=(i,e)=>new Rx(i,e);function wF(i,e,t,n){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,n);const s=BigInt(32),r=BigInt(4294967295),a=Number(t>>s&r),o=Number(t&r),c=n?4:0,l=n?0:4;i.setUint32(e+c,a,n),i.setUint32(e+l,o,n)}class Nx extends Hf{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Gf(this.buffer)}update(e){Oa(this);const{view:t,buffer:n,blockLen:s}=this;e=hh(e);const r=e.length;for(let a=0;a<r;){const o=Math.min(s-this.pos,r-a);if(o===s){const c=Gf(e);for(;s<=r-a;a+=s)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Oa(this),Bx(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(n,0),a=0);for(let u=a;u<s;u++)t[u]=0;wF(n,s-8,BigInt(this.length*8),r),this.process(n,0);const o=Gf(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)o.setUint32(4*u,h[u],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:a,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=a,s%t&&e.buffer.set(n),e}}const vF=(i,e,t)=>i&e^~i&t,CF=(i,e,t)=>i&e^i&t^e&t,IF=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xs=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ys=new Uint32Array(64);class SF extends Nx{constructor(){super(64,32,8,!1),this.A=Xs[0]|0,this.B=Xs[1]|0,this.C=Xs[2]|0,this.D=Xs[3]|0,this.E=Xs[4]|0,this.F=Xs[5]|0,this.G=Xs[6]|0,this.H=Xs[7]|0}get(){const{A:e,B:t,C:n,D:s,E:r,F:a,G:o,H:c}=this;return[e,t,n,s,r,a,o,c]}set(e,t,n,s,r,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=r|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ys[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const d=Ys[u-15],f=Ys[u-2],p=Vi(d,7)^Vi(d,18)^d>>>3,m=Vi(f,17)^Vi(f,19)^f>>>10;Ys[u]=m+Ys[u-7]+p+Ys[u-16]|0}let{A:n,B:s,C:r,D:a,E:o,F:c,G:l,H:h}=this;for(let u=0;u<64;u++){const d=Vi(o,6)^Vi(o,11)^Vi(o,25),f=h+d+vF(o,c,l)+IF[u]+Ys[u]|0,m=(Vi(n,2)^Vi(n,13)^Vi(n,22))+CF(n,s,r)|0;h=l,l=c,c=o,o=a+f|0,a=r,r=s,s=n,n=f+m|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(n,s,r,a,o,c,l,h)}roundClean(){Ys.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Dx=zf(()=>new SF),uh=BigInt(2**32-1),Vf=BigInt(32);function Lx(i,e=!1){return e?{h:Number(i&uh),l:Number(i>>Vf&uh)}:{h:Number(i>>Vf&uh)|0,l:Number(i&uh)|0}}function Px(i,e=!1){let t=new Uint32Array(i.length),n=new Uint32Array(i.length);for(let s=0;s<i.length;s++){const{h:r,l:a}=Lx(i[s],e);[t[s],n[s]]=[r,a]}return[t,n]}const MF=(i,e)=>BigInt(i>>>0)<<Vf|BigInt(e>>>0),BF=(i,e,t)=>i>>>t,TF=(i,e,t)=>i<<32-t|e>>>t,RF=(i,e,t)=>i>>>t|e<<32-t,FF=(i,e,t)=>i<<32-t|e>>>t,NF=(i,e,t)=>i<<64-t|e>>>t-32,DF=(i,e,t)=>i>>>t-32|e<<64-t,LF=(i,e)=>e,PF=(i,e)=>i,kx=(i,e,t)=>i<<t|e>>>32-t,Ux=(i,e,t)=>e<<t|i>>>32-t,Ox=(i,e,t)=>e<<t-32|i>>>64-t,Qx=(i,e,t)=>i<<t-32|e>>>64-t;function kF(i,e,t,n){const s=(e>>>0)+(n>>>0);return{h:i+t+(s/2**32|0)|0,l:s|0}}const lt={fromBig:Lx,split:Px,toBig:MF,shrSH:BF,shrSL:TF,rotrSH:RF,rotrSL:FF,rotrBH:NF,rotrBL:DF,rotr32H:LF,rotr32L:PF,rotlSH:kx,rotlSL:Ux,rotlBH:Ox,rotlBL:Qx,add:kF,add3L:(i,e,t)=>(i>>>0)+(e>>>0)+(t>>>0),add3H:(i,e,t,n)=>e+t+n+(i/2**32|0)|0,add4L:(i,e,t,n)=>(i>>>0)+(e>>>0)+(t>>>0)+(n>>>0),add4H:(i,e,t,n,s)=>e+t+n+s+(i/2**32|0)|0,add5H:(i,e,t,n,s,r)=>e+t+n+s+r+(i/2**32|0)|0,add5L:(i,e,t,n,s)=>(i>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0)},[UF,OF]=lt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(i=>BigInt(i))),Js=new Uint32Array(80),Zs=new Uint32Array(80);class QF extends Nx{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:n,Bl:s,Ch:r,Cl:a,Dh:o,Dl:c,Eh:l,El:h,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:g}=this;return[e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g]}set(e,t,n,s,r,a,o,c,l,h,u,d,f,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=r|0,this.Cl=a|0,this.Dh=o|0,this.Dl=c|0,this.Eh=l|0,this.El=h|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let x=0;x<16;x++,t+=4)Js[x]=e.getUint32(t),Zs[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){const E=Js[x-15]|0,S=Zs[x-15]|0,w=lt.rotrSH(E,S,1)^lt.rotrSH(E,S,8)^lt.shrSH(E,S,7),I=lt.rotrSL(E,S,1)^lt.rotrSL(E,S,8)^lt.shrSL(E,S,7),T=Js[x-2]|0,C=Zs[x-2]|0,v=lt.rotrSH(T,C,19)^lt.rotrBH(T,C,61)^lt.shrSH(T,C,6),F=lt.rotrSL(T,C,19)^lt.rotrBL(T,C,61)^lt.shrSL(T,C,6),K=lt.add4L(I,F,Zs[x-7],Zs[x-16]),q=lt.add4H(K,w,v,Js[x-7],Js[x-16]);Js[x]=q|0,Zs[x]=K|0}let{Ah:n,Al:s,Bh:r,Bl:a,Ch:o,Cl:c,Dh:l,Dl:h,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:g,Hh:A,Hl:_}=this;for(let x=0;x<80;x++){const E=lt.rotrSH(u,d,14)^lt.rotrSH(u,d,18)^lt.rotrBH(u,d,41),S=lt.rotrSL(u,d,14)^lt.rotrSL(u,d,18)^lt.rotrBL(u,d,41),w=u&f^~u&m,I=d&p^~d&g,T=lt.add5L(_,S,I,OF[x],Zs[x]),C=lt.add5H(T,A,E,w,UF[x],Js[x]),v=T|0,F=lt.rotrSH(n,s,28)^lt.rotrBH(n,s,34)^lt.rotrBH(n,s,39),K=lt.rotrSL(n,s,28)^lt.rotrBL(n,s,34)^lt.rotrBL(n,s,39),q=n&r^n&o^r&o,$=s&a^s&c^a&c;A=m|0,_=g|0,m=f|0,g=p|0,f=u|0,p=d|0,{h:u,l:d}=lt.add(l|0,h|0,C|0,v|0),l=o|0,h=c|0,o=r|0,c=a|0,r=n|0,a=s|0;const D=lt.add3L(v,K,$);n=lt.add3H(D,C,F,q),s=D|0}({h:n,l:s}=lt.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:r,l:a}=lt.add(this.Bh|0,this.Bl|0,r|0,a|0),{h:o,l:c}=lt.add(this.Ch|0,this.Cl|0,o|0,c|0),{h:l,l:h}=lt.add(this.Dh|0,this.Dl|0,l|0,h|0),{h:u,l:d}=lt.add(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=lt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:g}=lt.add(this.Gh|0,this.Gl|0,m|0,g|0),{h:A,l:_}=lt.add(this.Hh|0,this.Hl|0,A|0,_|0),this.set(n,s,r,a,o,c,l,h,u,d,f,p,m,g,A,_)}roundClean(){Js.fill(0),Zs.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const GF=zf(()=>new QF);function HF(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")}const Gx=HF();Gx.crypto||Gx.msCrypto;function zF(i){switch(i){case"sha256":return Dx.create();case"sha512":return GF.create()}V(!1,"invalid hashing algorithm name","algorithm",i)}const[Hx,zx,Vx]=[[],[],[]],VF=BigInt(0),tc=BigInt(1),WF=BigInt(2),qF=BigInt(7),KF=BigInt(256),jF=BigInt(113);for(let i=0,e=tc,t=1,n=0;i<24;i++){[t,n]=[n,(2*t+3*n)%5],Hx.push(2*(5*n+t)),zx.push((i+1)*(i+2)/2%64);let s=VF;for(let r=0;r<7;r++)e=(e<<tc^(e>>qF)*jF)%KF,e&WF&&(s^=tc<<(tc<<BigInt(r))-tc);Vx.push(s)}const[XF,YF]=Px(Vx,!0),Wx=(i,e,t)=>t>32?Ox(i,e,t):kx(i,e,t),qx=(i,e,t)=>t>32?Qx(i,e,t):Ux(i,e,t);function JF(i,e=24){const t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let a=0;a<10;a++)t[a]=i[a]^i[a+10]^i[a+20]^i[a+30]^i[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,l=t[c],h=t[c+1],u=Wx(l,h,1)^t[o],d=qx(l,h,1)^t[o+1];for(let f=0;f<50;f+=10)i[a+f]^=u,i[a+f+1]^=d}let s=i[2],r=i[3];for(let a=0;a<24;a++){const o=zx[a],c=Wx(s,r,o),l=qx(s,r,o),h=Hx[a];s=i[h],r=i[h+1],i[h]=c,i[h+1]=l}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=i[a+o];for(let o=0;o<10;o++)i[a+o]^=~t[(o+2)%10]&t[(o+4)%10]}i[0]^=XF[n],i[1]^=YF[n]}t.fill(0)}class Wf extends Hf{constructor(e,t,n,s=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,lh(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=bF(this.state)}keccak(){JF(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Oa(this);const{blockLen:t,state:n}=this;e=hh(e);const s=e.length;for(let r=0;r<s;){const a=Math.min(t-this.pos,s-r);for(let o=0;o<a;o++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Oa(this,!1),Of(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const a=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return lh(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Bx(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:a}=this;return e||(e=new Wf(t,n,s,a,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=a,e.destroyed=this.destroyed,e}}const ZF=((i,e,t)=>zf(()=>new Wf(e,i,t)))(1,136,256/8);let Kx=!1;const jx=function(i){return ZF(i)};let Xx=jx;function an(i){const e=ut(i,"data");return Ce(Xx(e))}an._=jx,an.lock=function(){Kx=!0},an.register=function(i){if(Kx)throw new TypeError("keccak256 is locked");Xx=i},Object.freeze(an);const Yx=function(i){return zF("sha256").update(i).digest()};let Jx=Yx,Zx=!1;function Qa(i){const e=ut(i,"data");return Ce(Jx(e))}Qa._=Yx,Qa.lock=function(){Zx=!0},Qa.register=function(i){if(Zx)throw new Error("sha256 is locked");Jx=i},Object.freeze(Qa),Object.freeze(Qa);BigInt(0);const $F=BigInt(1),eN=BigInt(2),dh=i=>i instanceof Uint8Array,tN=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Ga(i){if(!dh(i))throw new Error("Uint8Array expected");let e="";for(let t=0;t<i.length;t++)e+=tN[i[t]];return e}function qf(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return BigInt(i===""?"0":`0x${i}`)}function nc(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let n=0;n<t.length;n++){const s=n*2,r=i.slice(s,s+2),a=Number.parseInt(r,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[n]=a}return t}function Ir(i){return qf(Ga(i))}function Kf(i){if(!dh(i))throw new Error("Uint8Array expected");return qf(Ga(Uint8Array.from(i).reverse()))}function Ha(i,e){return nc(i.toString(16).padStart(e*2,"0"))}function jf(i,e){return Ha(i,e).reverse()}function Fi(i,e,t){let n;if(typeof e=="string")try{n=nc(e)}catch(r){throw new Error(`${i} must be valid hex string, got "${e}". Cause: ${r}`)}else if(dh(e))n=Uint8Array.from(e);else throw new Error(`${i} must be hex string or Uint8Array`);const s=n.length;if(typeof t=="number"&&s!==t)throw new Error(`${i} expected ${t} bytes, got ${s}`);return n}function ic(...i){const e=new Uint8Array(i.reduce((n,s)=>n+s.length,0));let t=0;return i.forEach(n=>{if(!dh(n))throw new Error("Uint8Array expected");e.set(n,t),t+=n.length}),e}const Xf=i=>(eN<<BigInt(i-1))-$F,Yf=i=>new Uint8Array(i),$x=i=>Uint8Array.from(i);function eb(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Yf(i),s=Yf(i),r=0;const a=()=>{n.fill(1),s.fill(0),r=0},o=(...u)=>t(s,n,...u),c=(u=Yf())=>{s=o($x([0]),u),n=o(),u.length!==0&&(s=o($x([1]),u),n=o())},l=()=>{if(r++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){n=o();const f=n.slice();d.push(f),u+=n.length}return ic(...d)};return(u,d)=>{a(),c(u);let f;for(;!(f=d(l()));)c();return a(),f}}const nN={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||i instanceof Uint8Array,isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function sc(i,e,t={}){const n=(s,r,a)=>{const o=nN[r];if(typeof o!="function")throw new Error(`Invalid validator "${r}", expected function`);const c=i[s];if(!(a&&c===void 0)&&!o(c,i))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${r}`)};for(const[s,r]of Object.entries(e))n(s,r,!1);for(const[s,r]of Object.entries(t))n(s,r,!0);return i}const iN=Object.freeze(Object.defineProperty({__proto__:null,bitMask:Xf,bytesToHex:Ga,bytesToNumberBE:Ir,bytesToNumberLE:Kf,concatBytes:ic,createHmacDrbg:eb,ensureBytes:Fi,hexToBytes:nc,hexToNumber:qf,numberToBytesBE:Ha,numberToBytesLE:jf,validateObject:sc},Symbol.toStringTag,{value:"Module"}));const yn=BigInt(0),en=BigInt(1),Sr=BigInt(2),sN=BigInt(3),Jf=BigInt(4),tb=BigInt(5),nb=BigInt(8);BigInt(9),BigInt(16);function Xn(i,e){const t=i%e;return t>=yn?t:e+t}function rN(i,e,t){if(t<=yn||e<yn)throw new Error("Expected power/modulo > 0");if(t===en)return yn;let n=en;for(;e>yn;)e&en&&(n=n*i%t),i=i*i%t,e>>=en;return n}function pi(i,e,t){let n=i;for(;e-- >yn;)n*=n,n%=t;return n}function Zf(i,e){if(i===yn||e<=yn)throw new Error(`invert: expected positive integers, got n=${i} mod=${e}`);let t=Xn(i,e),n=e,s=yn,r=en;for(;t!==yn;){const o=n/t,c=n%t,l=s-r*o;n=t,t=c,s=r,r=l}if(n!==en)throw new Error("invert: does not exist");return Xn(s,e)}function aN(i){const e=(i-en)/Sr;let t,n,s;for(t=i-en,n=0;t%Sr===yn;t/=Sr,n++);for(s=Sr;s<i&&rN(s,e,i)!==i-en;s++);if(n===1){const a=(i+en)/Jf;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const r=(t+en)/Sr;return function(o,c){if(o.pow(c,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let l=n,h=o.pow(o.mul(o.ONE,s),t),u=o.pow(c,r),d=o.pow(c,t);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let f=1;for(let m=o.sqr(d);f<l&&!o.eql(m,o.ONE);f++)m=o.sqr(m);const p=o.pow(h,en<<BigInt(l-f-1));h=o.sqr(p),u=o.mul(u,p),d=o.mul(d,h),l=f}return u}}function oN(i){if(i%Jf===sN){const e=(i+en)/Jf;return function(n,s){const r=n.pow(s,e);if(!n.eql(n.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%nb===tb){const e=(i-tb)/nb;return function(n,s){const r=n.mul(s,Sr),a=n.pow(r,e),o=n.mul(s,a),c=n.mul(n.mul(o,Sr),a),l=n.mul(o,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),s))throw new Error("Cannot find square root");return l}}return aN(i)}const cN=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lN(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=cN.reduce((n,s)=>(n[s]="function",n),e);return sc(i,t)}function hN(i,e,t){if(t<yn)throw new Error("Expected power > 0");if(t===yn)return i.ONE;if(t===en)return e;let n=i.ONE,s=e;for(;t>yn;)t&en&&(n=i.mul(n,s)),s=i.sqr(s),t>>=en;return n}function uN(i,e){const t=new Array(e.length),n=e.reduce((r,a,o)=>i.is0(a)?r:(t[o]=r,i.mul(r,a)),i.ONE),s=i.inv(n);return e.reduceRight((r,a,o)=>i.is0(a)?r:(t[o]=i.mul(r,t[o]),i.mul(r,a)),s),t}function ib(i,e){const t=e!==void 0?e:i.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function dN(i,e,t=!1,n={}){if(i<=yn)throw new Error(`Expected Field ORDER > 0, got ${i}`);const{nBitLength:s,nByteLength:r}=ib(i,e);if(r>2048)throw new Error("Field lengths over 2048 bytes are not supported");const a=oN(i),o=Object.freeze({ORDER:i,BITS:s,BYTES:r,MASK:Xf(s),ZERO:yn,ONE:en,create:c=>Xn(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return yn<=c&&c<i},is0:c=>c===yn,isOdd:c=>(c&en)===en,neg:c=>Xn(-c,i),eql:(c,l)=>c===l,sqr:c=>Xn(c*c,i),add:(c,l)=>Xn(c+l,i),sub:(c,l)=>Xn(c-l,i),mul:(c,l)=>Xn(c*l,i),pow:(c,l)=>hN(o,c,l),div:(c,l)=>Xn(c*Zf(l,i),i),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Zf(c,i),sqrt:n.sqrt||(c=>a(o,c)),invertBatch:c=>uN(o,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?jf(c,r):Ha(c,r),fromBytes:c=>{if(c.length!==r)throw new Error(`Fp.fromBytes: expected ${r}, got ${c.length}`);return t?Kf(c):Ir(c)}});return Object.freeze(o)}function sb(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function rb(i){const e=sb(i);return e+Math.ceil(e/2)}function fN(i,e,t=!1){const n=i.length,s=sb(e),r=rb(e);if(n<16||n<r||n>1024)throw new Error(`expected ${r}-1024 bytes of input, got ${n}`);const a=t?Ir(i):Kf(i),o=Xn(a,e-en)+en;return t?jf(o,s):Ha(o,s)}const pN=BigInt(0),$f=BigInt(1);function AN(i,e){const t=(s,r)=>{const a=r.negate();return s?a:r},n=s=>{const r=Math.ceil(e/s)+1,a=2**(s-1);return{windows:r,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,r){let a=i.ZERO,o=s;for(;r>pN;)r&$f&&(a=a.add(o)),o=o.double(),r>>=$f;return a},precomputeWindow(s,r){const{windows:a,windowSize:o}=n(r),c=[];let l=s,h=l;for(let u=0;u<a;u++){h=l,c.push(h);for(let d=1;d<o;d++)h=h.add(l),c.push(h);l=h.double()}return c},wNAF(s,r,a){const{windows:o,windowSize:c}=n(s);let l=i.ZERO,h=i.BASE;const u=BigInt(2**s-1),d=2**s,f=BigInt(s);for(let p=0;p<o;p++){const m=p*c;let g=Number(a&u);a>>=f,g>c&&(g-=d,a+=$f);const A=m,_=m+Math.abs(g)-1,x=p%2!==0,E=g<0;g===0?h=h.add(t(x,r[A])):l=l.add(t(E,r[_]))}return{p:l,f:h}},wNAFCached(s,r,a,o){const c=s._WINDOW_SIZE||1;let l=r.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&r.set(s,o(l))),this.wNAF(c,l,a)}}}function ab(i){return lN(i.Fp),sc(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ib(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}function gN(i){const e=ab(i);sc(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:mN,hexToBytes:xN}=iN,Mr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(i){const{Err:e}=Mr;if(i.length<2||i[0]!==2)throw new e("Invalid signature integer tag");const t=i[1],n=i.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:mN(n),l:i.subarray(t+2)}},toSig(i){const{Err:e}=Mr,t=typeof i=="string"?xN(i):i;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");const{d:s,l:r}=Mr._parseInt(t.subarray(2)),{d:a,l:o}=Mr._parseInt(r);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:a}},hexFromSig(i){const e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{const h=l.toString(16);return h.length&1?`0${h}`:h},n=e(t(i.s)),s=e(t(i.r)),r=n.length/2,a=s.length/2,o=t(r),c=t(a);return`30${t(a+r+4)}02${c}${s}02${o}${n}`}},gs=BigInt(0),Ai=BigInt(1);BigInt(2);const ob=BigInt(3);BigInt(4);function bN(i){const e=gN(i),{Fp:t}=e,n=e.toBytes||((p,m,g)=>{const A=m.toAffine();return ic(Uint8Array.from([4]),t.toBytes(A.x),t.toBytes(A.y))}),s=e.fromBytes||(p=>{const m=p.subarray(1),g=t.fromBytes(m.subarray(0,t.BYTES)),A=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:g,y:A}});function r(p){const{a:m,b:g}=e,A=t.sqr(p),_=t.mul(A,p);return t.add(t.add(_,t.mul(p,m)),g)}if(!t.eql(t.sqr(e.Gy),r(e.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return typeof p=="bigint"&&gs<p&&p<e.n}function o(p){if(!a(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){const{allowedPrivateKeyLengths:m,nByteLength:g,wrapPrivateKey:A,n:_}=e;if(m&&typeof p!="bigint"){if(p instanceof Uint8Array&&(p=Ga(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(g*2,"0")}let x;try{x=typeof p=="bigint"?p:Ir(Fi("private key",p,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof p}`)}return A&&(x=Xn(x,_)),o(x),x}const l=new Map;function h(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,g,A){if(this.px=m,this.py=g,this.pz=A,m==null||!t.isValid(m))throw new Error("x required");if(g==null||!t.isValid(g))throw new Error("y required");if(A==null||!t.isValid(A))throw new Error("z required")}static fromAffine(m){const{x:g,y:A}=m||{};if(!m||!t.isValid(g)||!t.isValid(A))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");const _=x=>t.eql(x,t.ZERO);return _(g)&&_(A)?u.ZERO:new u(g,A,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const g=t.invertBatch(m.map(A=>A.pz));return m.map((A,_)=>A.toAffine(g[_])).map(u.fromAffine)}static fromHex(m){const g=u.fromAffine(s(Fi("pointHex",m)));return g.assertValidity(),g}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:m,y:g}=this.toAffine();if(!t.isValid(m)||!t.isValid(g))throw new Error("bad point: x or y not FE");const A=t.sqr(g),_=r(m);if(!t.eql(A,_))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){h(m);const{px:g,py:A,pz:_}=this,{px:x,py:E,pz:S}=m,w=t.eql(t.mul(g,S),t.mul(x,_)),I=t.eql(t.mul(A,S),t.mul(E,_));return w&&I}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:g}=e,A=t.mul(g,ob),{px:_,py:x,pz:E}=this;let S=t.ZERO,w=t.ZERO,I=t.ZERO,T=t.mul(_,_),C=t.mul(x,x),v=t.mul(E,E),F=t.mul(_,x);return F=t.add(F,F),I=t.mul(_,E),I=t.add(I,I),S=t.mul(m,I),w=t.mul(A,v),w=t.add(S,w),S=t.sub(C,w),w=t.add(C,w),w=t.mul(S,w),S=t.mul(F,S),I=t.mul(A,I),v=t.mul(m,v),F=t.sub(T,v),F=t.mul(m,F),F=t.add(F,I),I=t.add(T,T),T=t.add(I,T),T=t.add(T,v),T=t.mul(T,F),w=t.add(w,T),v=t.mul(x,E),v=t.add(v,v),T=t.mul(v,F),S=t.sub(S,T),I=t.mul(v,C),I=t.add(I,I),I=t.add(I,I),new u(S,w,I)}add(m){h(m);const{px:g,py:A,pz:_}=this,{px:x,py:E,pz:S}=m;let w=t.ZERO,I=t.ZERO,T=t.ZERO;const C=e.a,v=t.mul(e.b,ob);let F=t.mul(g,x),K=t.mul(A,E),q=t.mul(_,S),$=t.add(g,A),D=t.add(x,E);$=t.mul($,D),D=t.add(F,K),$=t.sub($,D),D=t.add(g,_);let O=t.add(x,S);return D=t.mul(D,O),O=t.add(F,q),D=t.sub(D,O),O=t.add(A,_),w=t.add(E,S),O=t.mul(O,w),w=t.add(K,q),O=t.sub(O,w),T=t.mul(C,D),w=t.mul(v,q),T=t.add(w,T),w=t.sub(K,T),T=t.add(K,T),I=t.mul(w,T),K=t.add(F,F),K=t.add(K,F),q=t.mul(C,q),D=t.mul(v,D),K=t.add(K,q),q=t.sub(F,q),q=t.mul(C,q),D=t.add(D,q),F=t.mul(K,D),I=t.add(I,F),F=t.mul(O,D),w=t.mul($,w),w=t.sub(w,F),F=t.mul($,K),T=t.mul(O,T),T=t.add(T,F),new u(w,I,T)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,g=>{const A=t.invertBatch(g.map(_=>_.pz));return g.map((_,x)=>_.toAffine(A[x])).map(u.fromAffine)})}multiplyUnsafe(m){const g=u.ZERO;if(m===gs)return g;if(o(m),m===Ai)return this;const{endo:A}=e;if(!A)return f.unsafeLadder(this,m);let{k1neg:_,k1:x,k2neg:E,k2:S}=A.splitScalar(m),w=g,I=g,T=this;for(;x>gs||S>gs;)x&Ai&&(w=w.add(T)),S&Ai&&(I=I.add(T)),T=T.double(),x>>=Ai,S>>=Ai;return _&&(w=w.negate()),E&&(I=I.negate()),I=new u(t.mul(I.px,A.beta),I.py,I.pz),w.add(I)}multiply(m){o(m);let g=m,A,_;const{endo:x}=e;if(x){const{k1neg:E,k1:S,k2neg:w,k2:I}=x.splitScalar(g);let{p:T,f:C}=this.wNAF(S),{p:v,f:F}=this.wNAF(I);T=f.constTimeNegate(E,T),v=f.constTimeNegate(w,v),v=new u(t.mul(v.px,x.beta),v.py,v.pz),A=T.add(v),_=C.add(F)}else{const{p:E,f:S}=this.wNAF(g);A=E,_=S}return u.normalizeZ([A,_])[0]}multiplyAndAddUnsafe(m,g,A){const _=u.BASE,x=(S,w)=>w===gs||w===Ai||!S.equals(_)?S.multiplyUnsafe(w):S.multiply(w),E=x(this,g).add(x(m,A));return E.is0()?void 0:E}toAffine(m){const{px:g,py:A,pz:_}=this,x=this.is0();m==null&&(m=x?t.ONE:t.inv(_));const E=t.mul(g,m),S=t.mul(A,m),w=t.mul(_,m);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(w,t.ONE))throw new Error("invZ was invalid");return{x:E,y:S}}isTorsionFree(){const{h:m,isTorsionFree:g}=e;if(m===Ai)return!0;if(g)return g(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:g}=e;return m===Ai?this:g?g(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return Ga(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,f=AN(u,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:r,isWithinCurveOrder:a}}function EN(i){const e=ab(i);return sc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function yN(i){const e=EN(i),{Fp:t,n}=e,s=t.BYTES+1,r=2*t.BYTES+1;function a(D){return gs<D&&D<t.ORDER}function o(D){return Xn(D,n)}function c(D){return Zf(D,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:d}=bN({...e,toBytes(D,O,Y){const Q=O.toAffine(),J=t.toBytes(Q.x),ee=ic;return Y?ee(Uint8Array.from([O.hasEvenY()?2:3]),J):ee(Uint8Array.from([4]),J,t.toBytes(Q.y))},fromBytes(D){const O=D.length,Y=D[0],Q=D.subarray(1);if(O===s&&(Y===2||Y===3)){const J=Ir(Q);if(!a(J))throw new Error("Point is not on curve");const ee=u(J);let ae=t.sqrt(ee);const _e=(ae&Ai)===Ai;return(Y&1)===1!==_e&&(ae=t.neg(ae)),{x:J,y:ae}}else if(O===r&&Y===4){const J=t.fromBytes(Q.subarray(0,t.BYTES)),ee=t.fromBytes(Q.subarray(t.BYTES,2*t.BYTES));return{x:J,y:ee}}else throw new Error(`Point of length ${O} was invalid. Expected ${s} compressed bytes or ${r} uncompressed bytes`)}}),f=D=>Ga(Ha(D,e.nByteLength));function p(D){const O=n>>Ai;return D>O}function m(D){return p(D)?o(-D):D}const g=(D,O,Y)=>Ir(D.slice(O,Y));class A{constructor(O,Y,Q){this.r=O,this.s=Y,this.recovery=Q,this.assertValidity()}static fromCompact(O){const Y=e.nByteLength;return O=Fi("compactSignature",O,Y*2),new A(g(O,0,Y),g(O,Y,2*Y))}static fromDER(O){const{r:Y,s:Q}=Mr.toSig(Fi("DER",O));return new A(Y,Q)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(O){return new A(this.r,this.s,O)}recoverPublicKey(O){const{r:Y,s:Q,recovery:J}=this,ee=I(Fi("msgHash",O));if(J==null||![0,1,2,3].includes(J))throw new Error("recovery id invalid");const ae=J===2||J===3?Y+e.n:Y;if(ae>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const _e=(J&1)===0?"02":"03",Me=l.fromHex(_e+f(ae)),se=c(ae),me=o(-ee*se),xe=o(Q*se),be=l.BASE.multiplyAndAddUnsafe(Me,me,xe);if(!be)throw new Error("point at infinify");return be.assertValidity(),be}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new A(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return nc(this.toDERHex())}toDERHex(){return Mr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return nc(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}const _={isValidPrivateKey(D){try{return h(D),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const D=rb(e.n);return fN(e.randomBytes(D),e.n)},precompute(D=8,O=l.BASE){return O._setWindowSize(D),O.multiply(BigInt(3)),O}};function x(D,O=!0){return l.fromPrivateKey(D).toRawBytes(O)}function E(D){const O=D instanceof Uint8Array,Y=typeof D=="string",Q=(O||Y)&&D.length;return O?Q===s||Q===r:Y?Q===2*s||Q===2*r:D instanceof l}function S(D,O,Y=!0){if(E(D))throw new Error("first arg must be private key");if(!E(O))throw new Error("second arg must be public key");return l.fromHex(O).multiply(h(D)).toRawBytes(Y)}const w=e.bits2int||function(D){const O=Ir(D),Y=D.length*8-e.nBitLength;return Y>0?O>>BigInt(Y):O},I=e.bits2int_modN||function(D){return o(w(D))},T=Xf(e.nBitLength);function C(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(gs<=D&&D<T))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ha(D,e.nByteLength)}function v(D,O,Y=F){if(["recovered","canonical"].some(et=>et in Y))throw new Error("sign() legacy options not supported");const{hash:Q,randomBytes:J}=e;let{lowS:ee,prehash:ae,extraEntropy:_e}=Y;ee==null&&(ee=!0),D=Fi("msgHash",D),ae&&(D=Fi("prehashed msgHash",Q(D)));const Me=I(D),se=h(O),me=[C(se),C(Me)];if(_e!=null){const et=_e===!0?J(t.BYTES):_e;me.push(Fi("extraEntropy",et))}const xe=ic(...me),be=Me;function Ue(et){const He=w(et);if(!d(He))return;const Mt=c(He),ft=l.BASE.multiply(He).toAffine(),$e=o(ft.x);if($e===gs)return;const H=o(Mt*o(be+$e*se));if(H===gs)return;let wn=(ft.x===$e?0:2)|Number(ft.y&Ai),pt=H;return ee&&p(H)&&(pt=m(H),wn^=1),new A($e,pt,wn)}return{seed:xe,k2sig:Ue}}const F={lowS:e.lowS,prehash:!1},K={lowS:e.lowS,prehash:!1};function q(D,O,Y=F){const{seed:Q,k2sig:J}=v(D,O,Y),ee=e;return eb(ee.hash.outputLen,ee.nByteLength,ee.hmac)(Q,J)}l.BASE._setWindowSize(8);function $(D,O,Y,Q=K){const J=D;if(O=Fi("msgHash",O),Y=Fi("publicKey",Y),"strict"in Q)throw new Error("options.strict was renamed to lowS");const{lowS:ee,prehash:ae}=Q;let _e,Me;try{if(typeof J=="string"||J instanceof Uint8Array)try{_e=A.fromDER(J)}catch(ft){if(!(ft instanceof Mr.Err))throw ft;_e=A.fromCompact(J)}else if(typeof J=="object"&&typeof J.r=="bigint"&&typeof J.s=="bigint"){const{r:ft,s:$e}=J;_e=new A(ft,$e)}else throw new Error("PARSE");Me=l.fromHex(Y)}catch(ft){if(ft.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(ee&&_e.hasHighS())return!1;ae&&(O=e.hash(O));const{r:se,s:me}=_e,xe=I(O),be=c(me),Ue=o(xe*be),et=o(se*be),He=l.BASE.multiplyAndAddUnsafe(Me,Ue,et)?.toAffine();return He?o(He.x)===se:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:q,verify:$,ProjectivePoint:l,Signature:A,utils:_}}function _N(i){return{hash:i,hmac:(e,...t)=>Fx(i,e,yF(...t)),randomBytes:_F}}function wN(i,e){const t=n=>yN({...i,..._N(n)});return Object.freeze({...t(e),create:t})}const cb=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),lb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),vN=BigInt(1),ep=BigInt(2),hb=(i,e)=>(i+e/ep)/e;function CN(i){const e=cb,t=BigInt(3),n=BigInt(6),s=BigInt(11),r=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),l=i*i*i%e,h=l*l*i%e,u=pi(h,t,e)*h%e,d=pi(u,t,e)*h%e,f=pi(d,ep,e)*l%e,p=pi(f,s,e)*f%e,m=pi(p,r,e)*p%e,g=pi(m,o,e)*m%e,A=pi(g,c,e)*g%e,_=pi(A,o,e)*m%e,x=pi(_,t,e)*h%e,E=pi(x,a,e)*p%e,S=pi(E,n,e)*l%e,w=pi(S,ep,e);if(!tp.eql(tp.sqr(w),i))throw new Error("Cannot find square root");return w}const tp=dN(cb,void 0,void 0,{sqrt:CN}),$s=wN({a:BigInt(0),b:BigInt(7),Fp:tp,n:lb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:i=>{const e=lb,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-vN*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),r=t,a=BigInt("0x100000000000000000000000000000000"),o=hb(r*i,e),c=hb(-n*i,e);let l=Xn(i-o*t-c*s,e),h=Xn(-o*n-c*r,e);const u=l>a,d=h>a;if(u&&(l=e-l),d&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+i);return{k1neg:u,k1:l,k2neg:d,k2:h}}}},Dx);BigInt(0),$s.ProjectivePoint;const rc="0x0000000000000000000000000000000000000000",ub="0x0000000000000000000000000000000000000000000000000000000000000000",db=BigInt(0),fb=BigInt(1),np=BigInt(2),pb=BigInt(27),Ab=BigInt(28),fh=BigInt(35),gb=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),IN=gb/np,SN=Symbol.for("nodejs.util.inspect.custom"),Br={};function ip(i){return us(rn(i),32)}class Vt{#e;#t;#n;#i;get r(){return this.#e}set r(e){V(ka(e)===32,"invalid r","value",e),this.#e=Ce(e)}get s(){return V(parseInt(this.#t.substring(0,3))<8,"non-canonical s; use ._s","s",this.#t),this.#t}set s(e){V(ka(e)===32,"invalid s","value",e),this.#t=Ce(e)}get _s(){return this.#t}isValid(){return BigInt(this.#t)<=IN}get v(){return this.#n}set v(e){const t=dt(e,"value");V(t===27||t===28,"invalid v","v",e),this.#n=t}get networkV(){return this.#i}get legacyChainId(){const e=this.networkV;return e==null?null:Vt.getChainId(e)}get yParity(){return this.v===27?0:1}get yParityAndS(){const e=ut(this.s);return this.yParity&&(e[0]|=128),Ce(e)}get compactSerialized(){return Gt([this.r,this.yParityAndS])}get serialized(){return Gt([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(e,t,n,s){ih(e,Br,"Signature"),this.#e=t,this.#t=n,this.#n=s,this.#i=null}getCanonical(){if(this.isValid())return this;const e=gb-BigInt(this._s),t=55-this.v,n=new Vt(Br,this.r,ip(e),t);return this.networkV&&(n.#i=this.networkV),n}clone(){const e=new Vt(Br,this.r,this._s,this.v);return this.networkV&&(e.#i=this.networkV),e}toJSON(){const e=this.networkV;return{_type:"signature",networkV:e!=null?e.toString():null,r:this.r,s:this._s,v:this.v}}[SN](){return this.toString()}toString(){return this.isValid()?`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }`:`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`}static getChainId(e){const t=Ne(e,"v");return t==pb||t==Ab?db:(V(t>=fh,"invalid EIP-155 v","v",e),(t-fh)/np)}static getChainIdV(e,t){return Ne(e)*np+BigInt(35+t-27)}static getNormalizedV(e){const t=Ne(e);return t===db||t===pb?27:t===fb||t===Ab?28:(V(t>=fh,"invalid v","v",e),t&fb?27:28)}static from(e){function t(l,h){V(l,h,"signature",e)}if(e==null)return new Vt(Br,ub,ub,27);if(typeof e=="string"){const l=ut(e,"signature");if(l.length===64){const h=Ce(l.slice(0,32)),u=l.slice(32,64),d=u[0]&128?28:27;return u[0]&=127,new Vt(Br,h,Ce(u),d)}if(l.length===65){const h=Ce(l.slice(0,32)),u=Ce(l.slice(32,64)),d=Vt.getNormalizedV(l[64]);return new Vt(Br,h,u,d)}t(!1,"invalid raw signature length")}if(e instanceof Vt)return e.clone();const n=e.r;t(n!=null,"missing r");const s=ip(n),r=(function(l,h){if(l!=null)return ip(l);if(h!=null){t(Pt(h,32),"invalid yParityAndS");const u=ut(h);return u[0]&=127,Ce(u)}t(!1,"missing s")})(e.s,e.yParityAndS),{networkV:a,v:o}=(function(l,h,u){if(l!=null){const d=Ne(l);return{networkV:d>=fh?d:void 0,v:Vt.getNormalizedV(d)}}if(h!=null)return t(Pt(h,32),"invalid yParityAndS"),{v:ut(h)[0]&128?28:27};if(u!=null){switch(dt(u,"sig.yParity")){case 0:return{v:27};case 1:return{v:28}}t(!1,"invalid yParity")}t(!1,"missing v")})(e.v,e.yParityAndS,e.yParity),c=new Vt(Br,s,r,o);return a&&(c.#i=a),t(e.yParity==null||dt(e.yParity,"sig.yParity")===c.yParity,"yParity mismatch"),t(e.yParityAndS==null||e.yParityAndS===c.yParityAndS,"yParityAndS mismatch"),c}}class ms{#e;constructor(e){V(ka(e)===32,"invalid private key","privateKey","[REDACTED]"),this.#e=Ce(e)}get privateKey(){return this.#e}get publicKey(){return ms.computePublicKey(this.#e)}get compressedPublicKey(){return ms.computePublicKey(this.#e,!0)}sign(e){V(ka(e)===32,"invalid digest length","digest",e);const t=$s.sign(zn(e),zn(this.#e),{lowS:!0});return Vt.from({r:Ks(t.r,32),s:Ks(t.s,32),v:t.recovery?28:27})}computeSharedSecret(e){const t=ms.computePublicKey(e);return Ce($s.getSharedSecret(zn(this.#e),ut(t),!1))}static computePublicKey(e,t){let n=ut(e,"key");if(n.length===32){const r=$s.getPublicKey(n,!!t);return Ce(r)}if(n.length===64){const r=new Uint8Array(65);r[0]=4,r.set(n,1),n=r}const s=$s.ProjectivePoint.fromHex(n);return Ce(s.toRawBytes(t))}static recoverPublicKey(e,t){V(ka(e)===32,"invalid digest length","digest",e);const n=Vt.from(t);let s=$s.Signature.fromCompact(zn(Gt([n.r,n.s])));s=s.addRecoveryBit(n.yParity);const r=s.recoverPublicKey(zn(e));return V(r!=null,"invalid signature for digest","signature",t),"0x"+r.toHex(!1)}static addPoints(e,t,n){const s=$s.ProjectivePoint.fromHex(ms.computePublicKey(e).substring(2)),r=$s.ProjectivePoint.fromHex(ms.computePublicKey(t).substring(2));return"0x"+s.add(r).toHex(!!n)}}const MN=BigInt(0),BN=BigInt(36);function mb(i){i=i.toLowerCase();const e=i.substring(2).split(""),t=new Uint8Array(40);for(let s=0;s<40;s++)t[s]=e[s].charCodeAt(0);const n=ut(an(t));for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(n[s>>1]&15)>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const sp={};for(let i=0;i<10;i++)sp[String(i)]=String(i);for(let i=0;i<26;i++)sp[String.fromCharCode(65+i)]=String(10+i);const xb=15;function TN(i){i=i.toUpperCase(),i=i.substring(4)+i.substring(0,2)+"00";let e=i.split("").map(n=>sp[n]).join("");for(;e.length>=xb;){let n=e.substring(0,xb);e=parseInt(n,10)%97+e.substring(n.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}const RN=(function(){const i={};for(let e=0;e<36;e++){const t="0123456789abcdefghijklmnopqrstuvwxyz"[e];i[t]=BigInt(e)}return i})();function FN(i){i=i.toLowerCase();let e=MN;for(let t=0;t<i.length;t++)e=e*BN+RN[i[t]];return e}function St(i){if(V(typeof i=="string","invalid address","address",i),i.match(/^(0x)?[0-9a-fA-F]{40}$/)){i.startsWith("0x")||(i="0x"+i);const e=mb(i);return V(!i.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===i,"bad address checksum","address",i),e}if(i.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){V(i.substring(2,4)===TN(i),"bad icap checksum","address",i);let e=FN(i.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return mb("0x"+e)}V(!1,"invalid address","address",i)}function NN(i){const e=St(i.from);let n=Ne(i.nonce,"tx.nonce").toString(16);return n==="0"?n="0x":n.length%2?n="0x0"+n:n="0x"+n,St(Kt(an(fs([e,n])),12))}function bb(i){return i&&typeof i.getAddress=="function"}async function rp(i,e){const t=await e;return(t==null||t==="0x0000000000000000000000000000000000000000")&&(pe(typeof i!="string","unconfigured name","UNCONFIGURED_NAME",{value:i}),V(!1,"invalid AddressLike value; did not resolve to a value address","target",i)),St(t)}function Wn(i,e){if(typeof i=="string")return i.match(/^0x[0-9a-f]{40}$/i)?St(i):(pe(e!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),rp(i,e.resolveName(i)));if(bb(i))return rp(i,i.getAddress());if(i&&typeof i.then=="function")return rp(i,i);V(!1,"unsupported addressable value","target",i)}const xs={};function Be(i,e){let t=!1;return e<0&&(t=!0,e*=-1),new jt(xs,`${t?"":"u"}int${e}`,i,{signed:t,width:e})}function wt(i,e){return new jt(xs,`bytes${e||""}`,i,{size:e})}const Eb=Symbol.for("_ethers_typed");class jt{type;value;#e;_typedSymbol;constructor(e,t,n,s){s==null&&(s=null),ih(xs,e,"Typed"),Ye(this,{_typedSymbol:Eb,type:t,value:n}),this.#e=s,this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return this.#e}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return this.#e===!0?-1:this.#e===!1?this.value.length:null}static from(e,t){return new jt(xs,e,t)}static uint8(e){return Be(e,8)}static uint16(e){return Be(e,16)}static uint24(e){return Be(e,24)}static uint32(e){return Be(e,32)}static uint40(e){return Be(e,40)}static uint48(e){return Be(e,48)}static uint56(e){return Be(e,56)}static uint64(e){return Be(e,64)}static uint72(e){return Be(e,72)}static uint80(e){return Be(e,80)}static uint88(e){return Be(e,88)}static uint96(e){return Be(e,96)}static uint104(e){return Be(e,104)}static uint112(e){return Be(e,112)}static uint120(e){return Be(e,120)}static uint128(e){return Be(e,128)}static uint136(e){return Be(e,136)}static uint144(e){return Be(e,144)}static uint152(e){return Be(e,152)}static uint160(e){return Be(e,160)}static uint168(e){return Be(e,168)}static uint176(e){return Be(e,176)}static uint184(e){return Be(e,184)}static uint192(e){return Be(e,192)}static uint200(e){return Be(e,200)}static uint208(e){return Be(e,208)}static uint216(e){return Be(e,216)}static uint224(e){return Be(e,224)}static uint232(e){return Be(e,232)}static uint240(e){return Be(e,240)}static uint248(e){return Be(e,248)}static uint256(e){return Be(e,256)}static uint(e){return Be(e,256)}static int8(e){return Be(e,-8)}static int16(e){return Be(e,-16)}static int24(e){return Be(e,-24)}static int32(e){return Be(e,-32)}static int40(e){return Be(e,-40)}static int48(e){return Be(e,-48)}static int56(e){return Be(e,-56)}static int64(e){return Be(e,-64)}static int72(e){return Be(e,-72)}static int80(e){return Be(e,-80)}static int88(e){return Be(e,-88)}static int96(e){return Be(e,-96)}static int104(e){return Be(e,-104)}static int112(e){return Be(e,-112)}static int120(e){return Be(e,-120)}static int128(e){return Be(e,-128)}static int136(e){return Be(e,-136)}static int144(e){return Be(e,-144)}static int152(e){return Be(e,-152)}static int160(e){return Be(e,-160)}static int168(e){return Be(e,-168)}static int176(e){return Be(e,-176)}static int184(e){return Be(e,-184)}static int192(e){return Be(e,-192)}static int200(e){return Be(e,-200)}static int208(e){return Be(e,-208)}static int216(e){return Be(e,-216)}static int224(e){return Be(e,-224)}static int232(e){return Be(e,-232)}static int240(e){return Be(e,-240)}static int248(e){return Be(e,-248)}static int256(e){return Be(e,-256)}static int(e){return Be(e,-256)}static bytes1(e){return wt(e,1)}static bytes2(e){return wt(e,2)}static bytes3(e){return wt(e,3)}static bytes4(e){return wt(e,4)}static bytes5(e){return wt(e,5)}static bytes6(e){return wt(e,6)}static bytes7(e){return wt(e,7)}static bytes8(e){return wt(e,8)}static bytes9(e){return wt(e,9)}static bytes10(e){return wt(e,10)}static bytes11(e){return wt(e,11)}static bytes12(e){return wt(e,12)}static bytes13(e){return wt(e,13)}static bytes14(e){return wt(e,14)}static bytes15(e){return wt(e,15)}static bytes16(e){return wt(e,16)}static bytes17(e){return wt(e,17)}static bytes18(e){return wt(e,18)}static bytes19(e){return wt(e,19)}static bytes20(e){return wt(e,20)}static bytes21(e){return wt(e,21)}static bytes22(e){return wt(e,22)}static bytes23(e){return wt(e,23)}static bytes24(e){return wt(e,24)}static bytes25(e){return wt(e,25)}static bytes26(e){return wt(e,26)}static bytes27(e){return wt(e,27)}static bytes28(e){return wt(e,28)}static bytes29(e){return wt(e,29)}static bytes30(e){return wt(e,30)}static bytes31(e){return wt(e,31)}static bytes32(e){return wt(e,32)}static address(e){return new jt(xs,"address",e)}static bool(e){return new jt(xs,"bool",!!e)}static bytes(e){return new jt(xs,"bytes",e)}static string(e){return new jt(xs,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new jt(xs,"overrides",Object.assign({},e))}static isTyped(e){return e&&typeof e=="object"&&"_typedSymbol"in e&&e._typedSymbol===Eb}static dereference(e,t){if(jt.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class DN extends As{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=jt.dereference(t,"string");try{n=St(n)}catch(s){return this._throwError(s.message,t)}return e.writeValue(n)}decode(e){return St(Ks(e.readValue(),20))}}class LN extends As{coder;constructor(e){super(e.name,e.type,"_",e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function yb(i,e,t){let n=[];if(Array.isArray(t))n=t;else if(t&&typeof t=="object"){let c={};n=e.map(l=>{const h=l.localName;return pe(h,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:t}),pe(!c[h],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:l},value:t}),c[h]=!0,t[h]})}else V(!1,"invalid tuple value","tuple",t);V(e.length===n.length,"types/value length mismatch","tuple",t);let s=new kf,r=new kf,a=[];e.forEach((c,l)=>{let h=n[l];if(c.dynamic){let u=r.length;c.encode(r,h);let d=s.writeUpdatableValue();a.push(f=>{d(f+u)})}else c.encode(s,h)}),a.forEach(c=>{c(s.length)});let o=i.appendWriter(s);return o+=i.appendWriter(r),o}function _b(i,e){let t=[],n=[],s=i.subReader(0);return e.forEach(r=>{let a=null;if(r.dynamic){let o=i.readIndex(),c=s.subReader(o);try{a=r.decode(c)}catch(l){if(Tn(l,"BUFFER_OVERRUN"))throw l;a=l,a.baseType=r.name,a.name=r.localName,a.type=r.type}}else try{a=r.decode(i)}catch(o){if(Tn(o,"BUFFER_OVERRUN"))throw o;a=o,a.baseType=r.name,a.name=r.localName,a.type=r.type}if(a==null)throw new Error("investigate");t.push(a),n.push(r.localName||null)}),ps.fromItems(t,n)}class PN extends As{coder;length;constructor(e,t,n){const s=e.type+"["+(t>=0?t:"")+"]",r=t===-1||e.dynamic;super("array",s,n,r),Ye(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=jt.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let s=this.length;s===-1&&(s=n.length,e.writeValue(n.length)),sx(n.length,s,"coder array"+(this.localName?" "+this.localName:""));let r=[];for(let a=0;a<n.length;a++)r.push(this.coder);return yb(e,r,n)}decode(e){let t=this.length;t===-1&&(t=e.readIndex(),pe(t*Vn<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*Vn,length:e.dataLength}));let n=[];for(let s=0;s<t;s++)n.push(new LN(this.coder));return _b(e,n)}}class kN extends As{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=jt.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class wb extends As{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=zn(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class UN extends wb{constructor(e){super("bytes",e)}decode(e){return Ce(super.decode(e))}}class ON extends As{size;constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),Ye(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(e,t){let n=zn(jt.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return Ce(e.readBytes(this.size))}}const QN=new Uint8Array([]);class GN extends As{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return t!=null&&this._throwError("not null",t),e.writeBytes(QN)}decode(e){return e.readBytes(0),null}}const HN=BigInt(0),zN=BigInt(1),VN=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class WN extends As{size;signed;constructor(e,t,n){const s=(t?"int":"uint")+e*8;super(s,s,n,!1),Ye(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=Ne(jt.dereference(t,this.type)),s=Zo(VN,Vn*8);if(this.signed){let r=Zo(s,this.size*8-1);(n>r||n<-(r+zN))&&this._throwError("value out-of-bounds",t),n=cx(n,8*Vn)}else(n<HN||n>Zo(s,this.size*8))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=Zo(e.readValue(),this.size*8);return this.signed&&(t=$R(t,this.size*8)),t}}class qN extends wb{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,ds(jt.dereference(t,"string")))}decode(e){return rh(super.decode(e))}}class ph extends As{coders;constructor(e,t){let n=!1;const s=[];e.forEach(a=>{a.dynamic&&(n=!0),s.push(a.type)});const r="tuple("+s.join(",")+")";super("tuple",r,t,n),Ye(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach(n=>{e.push(n.defaultValue())});const t=this.coders.reduce((n,s)=>{const r=s.localName;return r&&(n[r]||(n[r]=0),n[r]++),n},{});return this.coders.forEach((n,s)=>{let r=n.localName;!r||t[r]!==1||(r==="length"&&(r="_length"),e[r]==null&&(e[r]=e[s]))}),Object.freeze(e)}encode(e,t){const n=jt.dereference(t,"tuple");return yb(e,this.coders,n)}decode(e){return _b(e,this.coders)}}function ap(i,e){return{address:St(i),storageKeys:e.map((t,n)=>(V(Pt(t,32),"invalid slot",`storageKeys[${n}]`,t),t.toLowerCase()))}}function Tr(i){if(Array.isArray(i))return i.map((t,n)=>Array.isArray(t)?(V(t.length===2,"invalid slot set",`value[${n}]`,t),ap(t[0],t[1])):(V(t!=null&&typeof t=="object","invalid address-slot set","value",i),ap(t.address,t.storageKeys)));V(i!=null&&typeof i=="object","invalid access list","value",i);const e=Object.keys(i).map(t=>{const n=i[t].reduce((s,r)=>(s[r]=!0,s),{});return ap(t,Object.keys(n).sort())});return e.sort((t,n)=>t.address.localeCompare(n.address)),e}function vb(i){return{address:St(i.address),nonce:Ne(i.nonce!=null?i.nonce:0),chainId:Ne(i.chainId!=null?i.chainId:0),signature:Vt.from(i.signature)}}function KN(i){let e;return typeof i=="string"?e=ms.computePublicKey(i,!1):e=i.publicKey,St(an("0x"+e.substring(4)).substring(26))}function jN(i,e){return KN(ms.recoverPublicKey(i,e))}const _n=BigInt(0),XN=BigInt(2),YN=BigInt(27),JN=BigInt(28),ZN=BigInt(35),$N=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),eD=Symbol.for("nodejs.util.inspect.custom"),op=4096*32,Ah=128;function tD(i){return{blobToKzgCommitment:n=>{if("computeBlobProof"in i){if("blobToKzgCommitment"in i&&typeof i.blobToKzgCommitment=="function")return ut(i.blobToKzgCommitment(Ce(n)))}else if("blobToKzgCommitment"in i&&typeof i.blobToKzgCommitment=="function")return ut(i.blobToKzgCommitment(n));if("blobToKZGCommitment"in i&&typeof i.blobToKZGCommitment=="function")return ut(i.blobToKZGCommitment(Ce(n)));V(!1,"unsupported KZG library","kzg",i)},computeBlobKzgProof:(n,s)=>{if("computeBlobProof"in i&&typeof i.computeBlobProof=="function")return ut(i.computeBlobProof(Ce(n),Ce(s)));if("computeBlobKzgProof"in i&&typeof i.computeBlobKzgProof=="function")return i.computeBlobKzgProof(n,s);if("computeBlobKZGProof"in i&&typeof i.computeBlobKZGProof=="function")return ut(i.computeBlobKZGProof(Ce(n),Ce(s)));V(!1,"unsupported KZG library","kzg",i)}}}function Cb(i,e){let t=i.toString(16);for(;t.length<2;)t="0"+t;return t+=Qa(e).substring(4),"0x"+t}function za(i){return i==="0x"?null:St(i)}function gh(i,e){try{return Tr(i)}catch(t){V(!1,t.message,e,i)}}function nD(i,e){try{if(!Array.isArray(i))throw new Error("authorizationList: invalid array");const t=[];for(let n=0;n<i.length;n++){const s=i[n];if(!Array.isArray(s))throw new Error(`authorization[${n}]: invalid array`);if(s.length!==6)throw new Error(`authorization[${n}]: wrong length`);if(!s[1])throw new Error(`authorization[${n}]: null address`);t.push({address:za(s[1]),nonce:Nt(s[2],"nonce"),chainId:Nt(s[0],"chainId"),signature:Vt.from({yParity:Rr(s[3],"yParity"),r:us(s[4],32),s:us(s[5],32)})})}return t}catch(t){V(!1,t.message,e,i)}}function Rr(i,e){return i==="0x"?0:dt(i,e)}function Nt(i,e){if(i==="0x")return _n;const t=Ne(i,e);return V(t<=$N,"value exceeds uint size",e,t),t}function xt(i,e){const t=Ne(i,"value"),n=rn(t);return V(n.length<=32,"value too large",`tx.${e}`,t),n}function mh(i){return Tr(i).map(e=>[e.address,e.storageKeys])}function iD(i){return i.map(e=>[xt(e.chainId,"chainId"),e.address,xt(e.nonce,"nonce"),xt(e.signature.yParity,"yParity"),rn(e.signature.r),rn(e.signature._s)])}function sD(i,e){V(Array.isArray(i),`invalid ${e}`,"value",i);for(let t=0;t<i.length;t++)V(Pt(i[t],32),"invalid ${ param } hash",`value[${t}]`,i[t]);return i}function rD(i){const e=$o(i);V(Array.isArray(e)&&(e.length===9||e.length===6),"invalid field count for legacy transaction","data",i);const t={type:0,nonce:Rr(e[0],"nonce"),gasPrice:Nt(e[1],"gasPrice"),gasLimit:Nt(e[2],"gasLimit"),to:za(e[3]),value:Nt(e[4],"value"),data:Ce(e[5]),chainId:_n};if(e.length===6)return t;const n=Nt(e[6],"v"),s=Nt(e[7],"r"),r=Nt(e[8],"s");if(s===_n&&r===_n)t.chainId=n;else{let a=(n-ZN)/XN;a<_n&&(a=_n),t.chainId=a,V(a!==_n||n===YN||n===JN,"non-canonical legacy v","v",e[6]),t.signature=Vt.from({r:us(e[7],32),s:us(e[8],32),v:n})}return t}function aD(i,e){const t=[xt(i.nonce,"nonce"),xt(i.gasPrice||0,"gasPrice"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data];let n=_n;if(i.chainId!=_n)n=Ne(i.chainId,"tx.chainId"),V(!e||e.networkV==null||e.legacyChainId===n,"tx.chainId/sig.v mismatch","sig",e);else if(i.signature){const r=i.signature.legacyChainId;r!=null&&(n=r)}if(!e)return n!==_n&&(t.push(rn(n)),t.push("0x"),t.push("0x")),fs(t);let s=BigInt(27+e.yParity);return n!==_n?s=Vt.getChainIdV(n,e.v):BigInt(e.v)!==s&&V(!1,"tx.chainId/sig.v mismatch","sig",e),t.push(rn(s)),t.push(rn(e.r)),t.push(rn(e._s)),fs(t)}function xh(i,e){let t;try{if(t=Rr(e[0],"yParity"),t!==0&&t!==1)throw new Error("bad yParity")}catch{V(!1,"invalid yParity","yParity",e[0])}const n=us(e[1],32),s=us(e[2],32),r=Vt.from({r:n,s,yParity:t});i.signature=r}function oD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===9||e.length===12),"invalid field count for transaction type: 2","data",Ce(i));const t={type:2,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList")};return e.length===9||xh(t,e.slice(9)),t}function cD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[])];return e&&(t.push(xt(e.yParity,"yParity")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x02",fs(t)])}function lD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===8||e.length===11),"invalid field count for transaction type: 1","data",Ce(i));const t={type:1,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),gasPrice:Nt(e[2],"gasPrice"),gasLimit:Nt(e[3],"gasLimit"),to:za(e[4]),value:Nt(e[5],"value"),data:Ce(e[6]),accessList:gh(e[7],"accessList")};return e.length===8||xh(t,e.slice(8)),t}function hD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.gasPrice||0,"gasPrice"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[])];return e&&(t.push(xt(e.yParity,"recoveryParam")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x01",fs(t)])}function uD(i){let e=$o(ut(i).slice(1)),t="3",n=null,s=null;if(e.length===4&&Array.isArray(e[0])){t="3 (network format)";const a=e[1],o=e[2],c=e[3];V(Array.isArray(a),"invalid network format: blobs not an array","fields[1]",a),V(Array.isArray(o),"invalid network format: commitments not an array","fields[2]",o),V(Array.isArray(c),"invalid network format: proofs not an array","fields[3]",c),V(a.length===o.length,"invalid network format: blobs/commitments length mismatch","fields",e),V(a.length===c.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let l=0;l<e[1].length;l++)s.push({data:a[l],commitment:o[l],proof:c[l]});e=e[0]}else if(e.length===5&&Array.isArray(e[0])){t="3 (EIP-7594 network format)",n=dt(e[1]);const a=e[2],o=e[3],c=e[4];V(n===1,`unsupported EIP-7594 network format version: ${n}`,"fields[1]",n),V(Array.isArray(a),"invalid EIP-7594 network format: blobs not an array","fields[2]",a),V(Array.isArray(o),"invalid EIP-7594 network format: commitments not an array","fields[3]",o),V(Array.isArray(c),"invalid EIP-7594 network format: proofs not an array","fields[4]",c),V(a.length===o.length,"invalid network format: blobs/commitments length mismatch","fields",e),V(a.length*Ah===c.length,"invalid network format: blobs/proofs length mismatch","fields",e),s=[];for(let l=0;l<a.length;l++){const h=[];for(let u=0;u<Ah;u++)h.push(c[l*Ah+u]);s.push({data:a[l],commitment:o[l],proof:Gt(h)})}e=e[0]}V(Array.isArray(e)&&(e.length===11||e.length===14),`invalid field count for transaction type: ${t}`,"data",Ce(i));const r={type:3,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList"),maxFeePerBlobGas:Nt(e[9],"maxFeePerBlobGas"),blobVersionedHashes:e[10],blobWrapperVersion:n};s&&(r.blobs=s),V(r.to!=null,`invalid address for transaction type: ${t}`,"data",i),V(Array.isArray(r.blobVersionedHashes),"invalid blobVersionedHashes: must be an array","data",i);for(let a=0;a<r.blobVersionedHashes.length;a++)V(Pt(r.blobVersionedHashes[a],32),`invalid blobVersionedHash at index ${a}: must be length 32`,"data",i);return e.length===11||xh(r,e.slice(11)),r}function dD(i,e,t){const n=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||rc,xt(i.value,"value"),i.data,mh(i.accessList||[]),xt(i.maxFeePerBlobGas||0,"maxFeePerBlobGas"),sD(i.blobVersionedHashes||[],"blobVersionedHashes")];if(e&&(n.push(xt(e.yParity,"yParity")),n.push(rn(e.r)),n.push(rn(e.s)),t)){if(i.blobWrapperVersion!=null){const s=rn(i.blobWrapperVersion),r=[];for(const{proof:a}of t){const o=ut(a),c=o.length/Ah;for(let l=0;l<o.length;l+=c)r.push(o.subarray(l,l+c))}return Gt(["0x03",fs([n,s,t.map(a=>a.data),t.map(a=>a.commitment),r])])}return Gt(["0x03",fs([n,t.map(s=>s.data),t.map(s=>s.commitment),t.map(s=>s.proof)])])}return Gt(["0x03",fs(n)])}function fD(i){const e=$o(ut(i).slice(1));V(Array.isArray(e)&&(e.length===10||e.length===13),"invalid field count for transaction type: 4","data",Ce(i));const t={type:4,chainId:Nt(e[0],"chainId"),nonce:Rr(e[1],"nonce"),maxPriorityFeePerGas:Nt(e[2],"maxPriorityFeePerGas"),maxFeePerGas:Nt(e[3],"maxFeePerGas"),gasPrice:null,gasLimit:Nt(e[4],"gasLimit"),to:za(e[5]),value:Nt(e[6],"value"),data:Ce(e[7]),accessList:gh(e[8],"accessList"),authorizationList:nD(e[9],"authorizationList")};return e.length===10||xh(t,e.slice(10)),t}function pD(i,e){const t=[xt(i.chainId,"chainId"),xt(i.nonce,"nonce"),xt(i.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),xt(i.maxFeePerGas||0,"maxFeePerGas"),xt(i.gasLimit,"gasLimit"),i.to||"0x",xt(i.value,"value"),i.data,mh(i.accessList||[]),iD(i.authorizationList||[])];return e&&(t.push(xt(e.yParity,"yParity")),t.push(rn(e.r)),t.push(rn(e.s))),Gt(["0x04",fs(t)])}class Ni{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;#c;#h;#u;#d;#x;#g;get type(){return this.#e}set type(e){switch(e){case null:this.#e=null;break;case 0:case"legacy":this.#e=0;break;case 1:case"berlin":case"eip-2930":this.#e=1;break;case 2:case"london":case"eip-1559":this.#e=2;break;case 3:case"cancun":case"eip-4844":this.#e=3;break;case 4:case"pectra":case"eip-7702":this.#e=4;break;default:V(!1,"unsupported transaction type","type",e)}}get typeName(){switch(this.type){case 0:return"legacy";case 1:return"eip-2930";case 2:return"eip-1559";case 3:return"eip-4844";case 4:return"eip-7702"}return null}get to(){const e=this.#t;return e==null&&this.type===3?rc:e}set to(e){this.#t=e==null?null:St(e)}get nonce(){return this.#i}set nonce(e){this.#i=dt(e,"value")}get gasLimit(){return this.#s}set gasLimit(e){this.#s=Ne(e)}get gasPrice(){const e=this.#a;return e==null&&(this.type===0||this.type===1)?_n:e}set gasPrice(e){this.#a=e==null?null:Ne(e,"gasPrice")}get maxPriorityFeePerGas(){const e=this.#r;return e??(this.type===2||this.type===3?_n:null)}set maxPriorityFeePerGas(e){this.#r=e==null?null:Ne(e,"maxPriorityFeePerGas")}get maxFeePerGas(){const e=this.#o;return e??(this.type===2||this.type===3?_n:null)}set maxFeePerGas(e){this.#o=e==null?null:Ne(e,"maxFeePerGas")}get data(){return this.#n}set data(e){this.#n=Ce(e)}get value(){return this.#f}set value(e){this.#f=Ne(e,"value")}get chainId(){return this.#l}set chainId(e){this.#l=Ne(e)}get signature(){return this.#p||null}set signature(e){this.#p=e==null?null:Vt.from(e)}isValid(){const e=this.signature;if(e&&!e.isValid())return!1;const t=this.authorizationList;if(t){for(const n of t)if(!n.signature.isValid())return!1}return!0}get accessList(){const e=this.#A||null;return e??(this.type===1||this.type===2||this.type===3?[]:null)}set accessList(e){this.#A=e==null?null:Tr(e)}get authorizationList(){const e=this.#x||null;return e==null&&this.type===4?[]:e}set authorizationList(e){this.#x=e==null?null:e.map(t=>vb(t))}get maxFeePerBlobGas(){const e=this.#c;return e==null&&this.type===3?_n:e}set maxFeePerBlobGas(e){this.#c=e==null?null:Ne(e,"maxFeePerBlobGas")}get blobVersionedHashes(){let e=this.#h;return e==null&&this.type===3?[]:e}set blobVersionedHashes(e){if(e!=null){V(Array.isArray(e),"blobVersionedHashes must be an Array","value",e),e=e.slice();for(let t=0;t<e.length;t++)V(Pt(e[t],32),"invalid blobVersionedHash",`value[${t}]`,e[t])}this.#h=e}get blobs(){return this.#d==null?null:this.#d.map(e=>Object.assign({},e))}set blobs(e){if(e==null){this.#d=null;return}const t=[],n=[];for(let s=0;s<e.length;s++){const r=e[s];if(Ff(r)){pe(this.#u,"adding a raw blob requires a KZG library","UNSUPPORTED_OPERATION",{operation:"set blobs()"});let a=ut(r);if(V(a.length<=op,"blob is too large",`blobs[${s}]`,r),a.length!==op){const l=new Uint8Array(op);l.set(a),a=l}const o=this.#u.blobToKzgCommitment(a),c=Ce(this.#u.computeBlobKzgProof(a,o));t.push({data:Ce(a),commitment:Ce(o),proof:c}),n.push(Cb(1,o))}else{const a=Ce(r.data),o=Ce(r.commitment),c=Ce(r.proof);t.push({data:a,commitment:o,proof:c}),n.push(Cb(1,o))}}this.#d=t,this.#h=n}get kzg(){return this.#u}set kzg(e){e==null?this.#u=null:this.#u=tD(e)}get blobWrapperVersion(){return this.#g}set blobWrapperVersion(e){this.#g=e}constructor(){this.#e=null,this.#t=null,this.#i=0,this.#s=_n,this.#a=null,this.#r=null,this.#o=null,this.#n="0x",this.#f=_n,this.#l=_n,this.#p=null,this.#A=null,this.#c=null,this.#h=null,this.#u=null,this.#d=null,this.#x=null,this.#g=null}get hash(){return this.signature==null?null:an(this.#m(!0,!1))}get unsignedHash(){return an(this.unsignedSerialized)}get from(){return this.signature==null?null:jN(this.unsignedHash,this.signature.getCanonical())}get fromPublicKey(){return this.signature==null?null:ms.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return this.signature!=null}#m(e,t){pe(!e||this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});const n=e?this.signature:null;switch(this.inferType()){case 0:return aD(this,n);case 1:return hD(this,n);case 2:return cD(this,n);case 3:return dD(this,n,t?this.blobs:null);case 4:return pD(this,n)}pe(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:".serialized"})}get serialized(){return this.#m(!0,!0)}get unsignedSerialized(){return this.#m(!1,!1)}inferType(){const e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){const e=this.gasPrice!=null,t=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null,n=this.accessList!=null,s=this.#c!=null||this.#h;this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null&&pe(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this}),pe(!t||this.type!==0&&this.type!==1,"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas","BAD_DATA",{value:this}),pe(this.type!==0||!n,"legacy transaction cannot have accessList","BAD_DATA",{value:this});const r=[];return this.type!=null?r.push(this.type):this.authorizationList&&this.authorizationList.length?r.push(4):t?r.push(2):e?(r.push(1),n||r.push(0)):n?(r.push(1),r.push(2)):(s&&this.to||(r.push(0),r.push(1),r.push(2)),r.push(3)),r.sort(),r}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}clone(){return Ni.from(this)}toJSON(){const e=t=>t==null?null:t.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[eD](){return this.toString()}toString(){const e=[],t=s=>{let r=this[s];typeof r=="string"&&(r=JSON.stringify(r)),e.push(`${s}: ${r}`)};this.type&&t("type"),t("to"),t("data"),t("nonce"),t("gasLimit"),t("value"),this.chainId!=null&&t("chainId"),this.signature&&(t("from"),e.push(`signature: ${this.signature.toString()}`));const n=this.authorizationList;if(n){const s=[];for(const r of n){const a=[];a.push(`address: ${JSON.stringify(r.address)}`),r.nonce!=null&&a.push(`nonce: ${r.nonce}`),r.chainId!=null&&a.push(`chainId: ${r.chainId}`),r.signature&&a.push(`signature: ${r.signature.toString()}`),s.push(`Authorization { ${a.join(", ")} }`)}e.push(`authorizations: [ ${s.join(", ")} ]`)}return`Transaction { ${e.join(", ")} }`}static from(e){if(e==null)return new Ni;if(typeof e=="string"){const n=ut(e);if(n[0]>=127)return Ni.from(rD(n));switch(n[0]){case 1:return Ni.from(lD(n));case 2:return Ni.from(oD(n));case 3:return Ni.from(uD(n));case 4:return Ni.from(fD(n))}pe(!1,"unsupported transaction type","UNSUPPORTED_OPERATION",{operation:"from"})}const t=new Ni;return e.type!=null&&(t.type=e.type),e.to!=null&&(t.to=e.to),e.nonce!=null&&(t.nonce=e.nonce),e.gasLimit!=null&&(t.gasLimit=e.gasLimit),e.gasPrice!=null&&(t.gasPrice=e.gasPrice),e.maxPriorityFeePerGas!=null&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.maxFeePerGas!=null&&(t.maxFeePerGas=e.maxFeePerGas),e.maxFeePerBlobGas!=null&&(t.maxFeePerBlobGas=e.maxFeePerBlobGas),e.data!=null&&(t.data=e.data),e.value!=null&&(t.value=e.value),e.chainId!=null&&(t.chainId=e.chainId),e.signature!=null&&(t.signature=Vt.from(e.signature)),e.accessList!=null&&(t.accessList=e.accessList),e.authorizationList!=null&&(t.authorizationList=e.authorizationList),e.blobVersionedHashes!=null&&(t.blobVersionedHashes=e.blobVersionedHashes),e.kzg!=null&&(t.kzg=e.kzg),e.blobWrapperVersion!=null&&(t.blobWrapperVersion=e.blobWrapperVersion),e.blobs!=null&&(t.blobs=e.blobs),e.hash!=null&&(V(t.isSigned(),"unsigned transaction cannot define '.hash'","tx",e),V(t.hash===e.hash,"hash mismatch","tx",e)),e.from!=null&&(V(t.isSigned(),"unsigned transaction cannot define '.from'","tx",e),V(t.from.toLowerCase()===(e.from||"").toLowerCase(),"from mismatch","tx",e)),t}}function Fr(i){return an(ds(i))}var AD="AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeX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le dot"]]),Sb=4;function gD(i){let e=0;function t(){return i[e++]<<8|i[e++]}let n=t(),s=1,r=[0,1];for(let S=1;S<n;S++)r.push(s+=t());let a=t(),o=e;e+=a;let c=0,l=0;function h(){return c==0&&(l=l<<8|i[e++],c=8),l>>--c&1}const u=31,d=2**u,f=d>>>1,p=f>>1,m=d-1;let g=0;for(let S=0;S<u;S++)g=g<<1|h();let A=[],_=0,x=d;for(;;){let S=Math.floor(((g-_+1)*s-1)/x),w=0,I=n;for(;I-w>1;){let v=w+I>>>1;S<r[v]?I=v:w=v}if(w==0)break;A.push(w);let T=_+Math.floor(x*r[w]/s),C=_+Math.floor(x*r[w+1]/s)-1;for(;((T^C)&f)==0;)g=g<<1&m|h(),T=T<<1&m,C=C<<1&m|1;for(;T&~C&p;)g=g&f|g<<1&m>>>1|h(),T=T<<1^f,C=(C^f)<<1|f|1;_=T,x=1+C-T}let E=n-4;return A.map(S=>{switch(S-E){case 3:return E+65792+(i[o++]<<16|i[o++]<<8|i[o++]);case 2:return E+256+(i[o++]<<8|i[o++]);case 1:return E+i[o++];default:return S-1}})}function mD(i){let e=0;return()=>i[e++]}function Mb(i){return mD(gD(xD(i)))}function xD(i){let e=[];[..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((s,r)=>e[s.charCodeAt(0)]=r);let t=i.length,n=new Uint8Array(6*t>>3);for(let s=0,r=0,a=0,o=0;s<t;s++)o=o<<6|e[i.charCodeAt(s)],a+=6,a>=8&&(n[r++]=o>>(a-=8));return n}function bD(i){return i&1?~i>>1:i>>1}function ED(i,e){let t=Array(i);for(let n=0,s=0;n<i;n++)t[n]=s+=bD(e());return t}function ac(i,e=0){let t=[];for(;;){let n=i(),s=i();if(!s)break;e+=n;for(let r=0;r<s;r++)t.push(e+r);e+=s+1}return t}function Bb(i){return oc(()=>{let e=ac(i);if(e.length)return e})}function Tb(i){let e=[];for(;;){let t=i();if(t==0)break;e.push(yD(t,i))}for(;;){let t=i()-1;if(t<0)break;e.push(_D(t,i))}return e.flat()}function oc(i){let e=[];for(;;){let t=i(e.length);if(!t)break;e.push(t)}return e}function Rb(i,e,t){let n=Array(i).fill().map(()=>[]);for(let s=0;s<e;s++)ED(i,t).forEach((r,a)=>n[a].push(r));return n}function yD(i,e){let t=1+e(),n=e(),s=oc(e);return Rb(s.length,1+i,e).flatMap((a,o)=>{let[c,...l]=a;return Array(s[o]).fill().map((h,u)=>{let d=u*n;return[c+u*t,l.map(f=>f+d)]})})}function _D(i,e){let t=1+e();return Rb(t,1+i,e).map(s=>[s[0],s.slice(1)])}function wD(i){let e=[],t=ac(i);return s(n([]),[]),e;function n(r){let a=i(),o=oc(()=>{let c=ac(i).map(l=>t[l]);if(c.length)return n(c)});return{S:a,B:o,Q:r}}function s({S:r,B:a},o,c){if(!(r&4&&c===o[o.length-1])){r&2&&(c=o[o.length-1]),r&1&&e.push(o);for(let l of a)for(let h of l.Q)s(l,[...o,h],c)}}}function vD(i){return i.toString(16).toUpperCase().padStart(2,"0")}function Fb(i){return`{${vD(i)}}`}function CD(i){let e=[];for(let t=0,n=i.length;t<n;){let s=i.codePointAt(t);t+=s<65536?1:2,e.push(s)}return e}function Va(i){let t=i.length;if(t<4096)return String.fromCodePoint(...i);let n=[];for(let s=0;s<t;)n.push(String.fromCodePoint(...i.slice(s,s+=4096)));return n.join("")}function ID(i,e){let t=i.length,n=t-e.length;for(let s=0;n==0&&s<t;s++)n=i[s]-e[s];return n}var SD="AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSM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k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g";const cc=44032,bh=4352,Eh=4449,yh=4519,Nb=19,Db=21,Wa=28,_h=Db*Wa,MD=Nb*_h,BD=cc+MD,TD=bh+Nb,RD=Eh+Db,FD=yh+Wa;function lc(i){return i>>24&255}function Lb(i){return i&16777215}let cp,Pb,lp,wh;function ND(){let i=Mb(SD);cp=new Map(Bb(i).flatMap((e,t)=>e.map(n=>[n,t+1<<24]))),Pb=new Set(ac(i)),lp=new Map,wh=new Map;for(let[e,t]of Tb(i)){if(!Pb.has(e)&&t.length==2){let[n,s]=t,r=wh.get(n);r||(r=new Map,wh.set(n,r)),r.set(s,e)}lp.set(e,t.reverse())}}function kb(i){return i>=cc&&i<BD}function DD(i,e){if(i>=bh&&i<TD&&e>=Eh&&e<RD)return cc+(i-bh)*_h+(e-Eh)*Wa;if(kb(i)&&e>yh&&e<FD&&(i-cc)%Wa==0)return i+(e-yh);{let t=wh.get(i);return t&&(t=t.get(e),t)?t:-1}}function Ub(i){cp||ND();let e=[],t=[],n=!1;function s(r){let a=cp.get(r);a&&(n=!0,r|=a),e.push(r)}for(let r of i)for(;;){if(r<128)e.push(r);else if(kb(r)){let a=r-cc,o=a/_h|0,c=a%_h/Wa|0,l=a%Wa;s(bh+o),s(Eh+c),l>0&&s(yh+l)}else{let a=lp.get(r);a?t.push(...a):s(r)}if(!t.length)break;r=t.pop()}if(n&&e.length>1){let r=lc(e[0]);for(let a=1;a<e.length;a++){let o=lc(e[a]);if(o==0||r<=o){r=o;continue}let c=a-1;for(;;){let l=e[c+1];if(e[c+1]=e[c],e[c]=l,!c||(r=lc(e[--c]),r<=o))break}r=lc(e[a])}}return e}function LD(i){let e=[],t=[],n=-1,s=0;for(let r of i){let a=lc(r),o=Lb(r);if(n==-1)a==0?n=o:e.push(o);else if(s>0&&s>=a)a==0?(e.push(n,...t),t.length=0,n=o):t.push(o),s=a;else{let c=DD(n,o);c>=0?n=c:s==0&&a==0?(e.push(n),n=o):(t.push(o),s=a)}}return n>=0&&e.push(n,...t),e}function Ob(i){return Ub(i).map(Lb)}function PD(i){return LD(Ub(i))}const Qb=45,Gb=".",Hb=65039,zb=1,vh=i=>Array.from(i);function hc(i,e){return i.P.has(e)||i.Q.has(e)}class kD extends Array{get is_emoji(){return!0}}let hp,Vb,Nr,up,Wb,qa,dp,Ka,Dr,qb,fp;function pp(){if(hp)return;let i=Mb(AD);const e=()=>ac(i),t=()=>new Set(e()),n=(h,u)=>u.forEach(d=>h.add(d));hp=new Map(Tb(i)),Vb=t(),Nr=e(),up=new Set(e().map(h=>Nr[h])),Nr=new Set(Nr),Wb=t(),t();let s=Bb(i),r=i();const a=()=>{let h=new Set;return e().forEach(u=>n(h,s[u])),n(h,e()),h};qa=oc(h=>{let u=oc(i).map(d=>d+96);if(u.length){let d=h>=r;u[0]-=32,u=Va(u),d&&(u=`Restricted[${u}]`);let f=a(),p=a(),m=!i();return{N:u,P:f,Q:p,M:m,R:d}}}),dp=t(),Ka=new Map;let o=e().concat(vh(dp)).sort((h,u)=>h-u);o.forEach((h,u)=>{let d=i(),f=o[u]=d?o[u-d]:{V:[],M:new Map};f.V.push(h),dp.has(h)||Ka.set(h,f)});for(let{V:h,M:u}of new Set(Ka.values())){let d=[];for(let p of h){let m=qa.filter(A=>hc(A,p)),g=d.find(({G:A})=>m.some(_=>A.has(_)));g||(g={G:new Set,V:[]},d.push(g)),g.V.push(p),n(g.G,m)}let f=d.flatMap(p=>vh(p.G));for(let{G:p,V:m}of d){let g=new Set(f.filter(A=>!p.has(A)));for(let A of m)u.set(A,g)}}Dr=new Set;let c=new Set;const l=h=>Dr.has(h)?c.add(h):Dr.add(h);for(let h of qa){for(let u of h.P)l(u);for(let u of h.Q)l(u)}for(let h of Dr)!Ka.has(h)&&!c.has(h)&&Ka.set(h,zb);n(Dr,Ob(Dr)),qb=wD(i).map(h=>kD.from(h)).sort(ID),fp=new Map;for(let h of qb){let u=[fp];for(let d of h){let f=u.map(p=>{let m=p.get(d);return m||(m=new Map,p.set(d,m)),m});d===Hb?u.push(...f):u=f}for(let d of u)d.V=h}}function Ap(i){return(Kb(i)?"":`${gp(Ch([i]))} `)+Fb(i)}function gp(i){return`"${i}"‎`}function UD(i){if(i.length>=4&&i[2]==Qb&&i[3]==Qb)throw new Error(`invalid label extension: "${Va(i.slice(0,4))}"`)}function OD(i){for(let t=i.lastIndexOf(95);t>0;)if(i[--t]!==95)throw new Error("underscore allowed only at start")}function QD(i){let e=i[0],t=Ib.get(e);if(t)throw uc(`leading ${t}`);let n=i.length,s=-1;for(let r=1;r<n;r++){e=i[r];let a=Ib.get(e);if(a){if(s==r)throw uc(`${t} + ${a}`);s=r+1,t=a}}if(s==n)throw uc(`trailing ${t}`)}function Ch(i,e=1/0,t=Fb){let n=[];GD(i[0])&&n.push("◌"),i.length>e&&(e>>=1,i=[...i.slice(0,e),8230,...i.slice(-e)]);let s=0,r=i.length;for(let a=0;a<r;a++){let o=i[a];Kb(o)&&(n.push(Va(i.slice(s,a))),n.push(t(o)),s=a+1)}return n.push(Va(i.slice(s,r))),n.join("")}function GD(i){return pp(),Nr.has(i)}function Kb(i){return pp(),Wb.has(i)}function HD(i){return qD(zD(i,PD,XD))}function zD(i,e,t){if(!i)return[];pp();let n=0;return i.split(Gb).map(s=>{let r=CD(s),a={input:r,offset:n};n+=r.length+1;try{let o=a.tokens=jD(r,e,t),c=o.length,l;if(!c)throw new Error("empty label");let h=a.output=o.flat();if(OD(h),!(a.emoji=c>1||o[0].is_emoji)&&h.every(d=>d<128))UD(h),l="ASCII";else{let d=o.flatMap(f=>f.is_emoji?[]:f);if(!d.length)l="Emoji";else{if(Nr.has(h[0]))throw uc("leading combining mark");for(let m=1;m<c;m++){let g=o[m];if(!g.is_emoji&&Nr.has(g[0]))throw uc(`emoji + combining mark: "${Va(o[m-1])} + ${Ch([g[0]])}"`)}QD(h);let f=vh(new Set(d)),[p]=WD(f);KD(p,d),VD(p,f),l=p.N}}a.type=l}catch(o){a.error=o}return a})}function VD(i,e){let t,n=[];for(let s of e){let r=Ka.get(s);if(r===zb)return;if(r){let a=r.M.get(s);if(t=t?t.filter(o=>a.has(o)):vh(a),!t.length)return}else n.push(s)}if(t){for(let s of t)if(n.every(r=>hc(s,r)))throw new Error(`whole-script confusable: ${i.N}/${s.N}`)}}function WD(i){let e=qa;for(let t of i){let n=e.filter(s=>hc(s,t));if(!n.length)throw qa.some(s=>hc(s,t))?Xb(e[0],t):jb(t);if(e=n,n.length==1)break}return e}function qD(i){return i.map(({input:e,error:t,output:n})=>{if(t){let s=t.message;throw new Error(i.length==1?s:`Invalid label ${gp(Ch(e,63))}: ${s}`)}return Va(n)}).join(Gb)}function jb(i){return new Error(`disallowed character: ${Ap(i)}`)}function Xb(i,e){let t=Ap(e),n=qa.find(s=>s.P.has(e));return n&&(t=`${n.N} ${t}`),new Error(`illegal mixture: ${i.N} + ${t}`)}function uc(i){return new Error(`illegal placement: ${i}`)}function KD(i,e){for(let t of e)if(!hc(i,t))throw Xb(i,t);if(i.M){let t=Ob(e);for(let n=1,s=t.length;n<s;n++)if(up.has(t[n])){let r=n+1;for(let a;r<s&&up.has(a=t[r]);r++)for(let o=n;o<r;o++)if(t[o]==a)throw new Error(`duplicate non-spacing marks: ${Ap(a)}`);if(r-n>Sb)throw new Error(`excessive non-spacing marks: ${gp(Ch(t.slice(n-1,r)))} (${r-n}/${Sb})`);n=r}}}function jD(i,e,t){let n=[],s=[];for(i=i.slice().reverse();i.length;){let r=YD(i);if(r)s.length&&(n.push(e(s)),s=[]),n.push(t(r));else{let a=i.pop();if(Dr.has(a))s.push(a);else{let o=hp.get(a);if(o)s.push(...o);else if(!Vb.has(a))throw jb(a)}}}return s.length&&n.push(e(s)),n}function XD(i){return i.filter(e=>e!=Hb)}function YD(i,e){let t=fp,n,s=i.length;for(;s&&(t=t.get(i[--s]),!!t);){let{V:r}=t;r&&(n=r,i.length=s)}return n}const Yb=new Uint8Array(32);Yb.fill(0);function Jb(i){return V(i.length!==0,"invalid ENS name; empty component","comp",i),i}function Zb(i){const e=ds(JD(i)),t=[];if(i.length===0)return t;let n=0;for(let s=0;s<e.length;s++)e[s]===46&&(t.push(Jb(e.slice(n,s))),n=s+1);return V(n<e.length,"invalid ENS name; empty component","name",i),t.push(Jb(e.slice(n))),t}function JD(i){try{if(i.length===0)throw new Error("empty label");return HD(i)}catch(e){V(!1,`invalid ENS name (${e.message})`,"name",i)}}function mp(i){V(typeof i=="string","invalid ENS name; not a string","name",i),V(i.length,"invalid ENS name (empty label)","name",i);let e=Yb;const t=Zb(i);for(;t.length;)e=an(Gt([e,an(t.pop())]));return Ce(e)}function ZD(i,e){const t=e;return V(t<=255,"DNS encoded label cannot exceed 255","length",t),Ce(Gt(Zb(i).map(n=>{V(n.length<=t,`label ${JSON.stringify(i)} exceeds ${t} bytes`,"name",i);const s=new Uint8Array(n.length+1);return s.set(n,1),s[0]=s.length-1,s})))+"00"}const $b=new Uint8Array(32);$b.fill(0);const $D=BigInt(-1),eE=BigInt(0),tE=BigInt(1),eL=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function tL(i){const e=ut(i),t=e.length%32;return t?Gt([e,$b.slice(t)]):Ce(e)}const nL=Ks(tE,32),iL=Ks(eE,32),nE={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},xp=["name","version","chainId","verifyingContract","salt"];function iE(i){return function(e){return V(typeof e=="string",`invalid domain value for ${JSON.stringify(i)}`,`domain.${i}`,e),e}}const sL={name:iE("name"),version:iE("version"),chainId:function(i){const e=Ne(i,"domain.chainId");return V(e>=0,"invalid chain ID","domain.chainId",i),Number.isSafeInteger(e)?Number(e):Ri(e)},verifyingContract:function(i){try{return St(i).toLowerCase()}catch{}V(!1,'invalid domain value "verifyingContract"',"domain.verifyingContract",i)},salt:function(i){const e=ut(i,"domain.salt");return V(e.length===32,'invalid domain value "salt"',"domain.salt",i),Ce(e)}};function bp(i){{const e=i.match(/^(u?)int(\d+)$/);if(e){const t=e[1]==="",n=parseInt(e[2]);V(n%8===0&&n!==0&&n<=256&&e[2]===String(n),"invalid numeric width","type",i);const s=Zo(eL,t?n-1:n),r=t?(s+tE)*$D:eE;return function(a){const o=Ne(a,"value");return V(o>=r&&o<=s,`value out-of-bounds for ${i}`,"value",o),Ks(t?cx(o,256):o,32)}}}{const e=i.match(/^bytes(\d+)$/);if(e){const t=parseInt(e[1]);return V(t!==0&&t<=32&&e[1]===String(t),"invalid bytes width","type",i),function(n){const s=ut(n);return V(s.length===t,`invalid length for ${i}`,"value",n),tL(n)}}}switch(i){case"address":return function(e){return us(St(e),32)};case"bool":return function(e){return e?nL:iL};case"bytes":return function(e){return an(e)};case"string":return function(e){return Fr(e)}}return null}function sE(i,e){return`${i}(${e.map(({name:t,type:n})=>n+" "+t).join(",")})`}function Ih(i){const e=i.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return e?{base:e[1],index:e[2]+e[4],array:{base:e[1],prefix:e[1]+e[2],count:e[5]?parseInt(e[5]):-1}}:{base:i}}class ti{primaryType;#e;get types(){return JSON.parse(this.#e)}#t;#n;constructor(e){this.#t=new Map,this.#n=new Map;const t=new Map,n=new Map,s=new Map,r={};Object.keys(e).forEach(c=>{r[c]=e[c].map(({name:l,type:h})=>{let{base:u,index:d}=Ih(h);return u==="int"&&!e.int&&(u="int256"),u==="uint"&&!e.uint&&(u="uint256"),{name:l,type:u+(d||"")}}),t.set(c,new Set),n.set(c,[]),s.set(c,new Set)}),this.#e=JSON.stringify(r);for(const c in r){const l=new Set;for(const h of r[c]){V(!l.has(h.name),`duplicate variable name ${JSON.stringify(h.name)} in ${JSON.stringify(c)}`,"types",e),l.add(h.name);const u=Ih(h.type).base;V(u!==c,`circular type reference to ${JSON.stringify(u)}`,"types",e),!bp(u)&&(V(n.has(u),`unknown type ${JSON.stringify(u)}`,"types",e),n.get(u).push(c),t.get(c).add(u))}}const a=Array.from(n.keys()).filter(c=>n.get(c).length===0);V(a.length!==0,"missing primary type","types",e),V(a.length===1,`ambiguous primary types or unused types: ${a.map(c=>JSON.stringify(c)).join(", ")}`,"types",e),Ye(this,{primaryType:a[0]});function o(c,l){V(!l.has(c),`circular type reference to ${JSON.stringify(c)}`,"types",e),l.add(c);for(const h of t.get(c))if(n.has(h)){o(h,l);for(const u of l)s.get(u).add(h)}l.delete(c)}o(this.primaryType,new Set);for(const[c,l]of s){const h=Array.from(l);h.sort(),this.#t.set(c,sE(c,r[c])+h.map(u=>sE(u,r[u])).join(""))}}getEncoder(e){let t=this.#n.get(e);return t||(t=this.#i(e),this.#n.set(e,t)),t}#i(e){{const s=bp(e);if(s)return s}const t=Ih(e).array;if(t){const s=t.prefix,r=this.getEncoder(s);return a=>{V(t.count===-1||t.count===a.length,`array length mismatch; expected length ${t.count}`,"value",a);let o=a.map(r);return this.#t.has(s)&&(o=o.map(an)),an(Gt(o))}}const n=this.types[e];if(n){const s=Fr(this.#t.get(e));return r=>{const a=n.map(({name:o,type:c})=>{const l=this.getEncoder(c)(r[o]);return this.#t.has(c)?an(l):l});return a.unshift(s),Gt(a)}}V(!1,`unknown type: ${e}`,"type",e)}encodeType(e){const t=this.#t.get(e);return V(t,`unknown type: ${JSON.stringify(e)}`,"name",e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return an(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,n){if(bp(e))return n(e,t);const s=Ih(e).array;if(s)return V(s.count===-1||s.count===t.length,`array length mismatch; expected length ${s.count}`,"value",t),t.map(a=>this._visit(s.prefix,a,n));const r=this.types[e];if(r)return r.reduce((a,{name:o,type:c})=>(a[o]=this._visit(c,t[o],n),a),{});V(!1,`unknown type: ${e}`,"type",e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(e){return new ti(e)}static getPrimaryType(e){return ti.from(e).primaryType}static hashStruct(e,t,n){return ti.from(t).hashStruct(e,n)}static hashDomain(e){const t=[];for(const n in e){if(e[n]==null)continue;const s=nE[n];V(s,`invalid typed-data domain key: ${JSON.stringify(n)}`,"domain",e),t.push({name:n,type:s})}return t.sort((n,s)=>xp.indexOf(n.name)-xp.indexOf(s.name)),ti.hashStruct("EIP712Domain",{EIP712Domain:t},e)}static encode(e,t,n){return Gt(["0x1901",ti.hashDomain(e),ti.from(t).hash(n)])}static hash(e,t,n){return an(ti.encode(e,t,n))}static async resolveNames(e,t,n,s){e=Object.assign({},e);for(const o in e)e[o]==null&&delete e[o];const r={};e.verifyingContract&&!Pt(e.verifyingContract,20)&&(r[e.verifyingContract]="0x");const a=ti.from(t);a.visit(n,(o,c)=>(o==="address"&&!Pt(c,20)&&(r[c]="0x"),c));for(const o in r)r[o]=await s(o);return e.verifyingContract&&r[e.verifyingContract]&&(e.verifyingContract=r[e.verifyingContract]),n=a.visit(n,(o,c)=>o==="address"&&r[c]?r[c]:c),{domain:e,value:n}}static getPayload(e,t,n){ti.hashDomain(e);const s={},r=[];xp.forEach(c=>{const l=e[c];l!=null&&(s[c]=sL[c](l),r.push({name:c,type:nE[c]}))});const a=ti.from(t);t=a.types;const o=Object.assign({},t);return V(o.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",t),o.EIP712Domain=r,a.encode(n),{types:o,domain:s,primaryType:a.primaryType,message:a.visit(n,(c,l)=>{if(c.match(/^bytes(\d*)/))return Ce(ut(l));if(c.match(/^u?int/))return Ne(l).toString();switch(c){case"address":return l.toLowerCase();case"bool":return!!l;case"string":return V(typeof l=="string","invalid string","value",l),l}V(!1,"unsupported type","type",c)})}}}function qn(i){const e=new Set;return i.forEach(t=>e.add(t)),Object.freeze(e)}const rL=qn("external public payable override".split(" ")),rE="constant external internal payable private public pure view override",aL=qn(rE.split(" ")),aE="constructor error event fallback function receive struct",oE=qn(aE.split(" ")),cE="calldata memory storage payable indexed",oL=qn(cE.split(" ")),cL=[aE,cE,"tuple returns",rE].join(" "),lL=qn(cL.split(" ")),hL={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},uL=new RegExp("^(\\s*)"),dL=new RegExp("^([0-9]+)"),fL=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),lE=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),hE=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class gi{#e;#t;get offset(){return this.#e}get length(){return this.#t.length-this.#e}constructor(e){this.#e=0,this.#t=e.slice()}clone(){return new gi(this.#t)}reset(){this.#e=0}#n(e=0,t=0){return new gi(this.#t.slice(e,t).map(n=>Object.freeze(Object.assign({},n,{match:n.match-e,linkBack:n.linkBack-e,linkNext:n.linkNext-e}))))}popKeyword(e){const t=this.peek();if(t.type!=="KEYWORD"||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=this.#n(this.#e+1,e.match+1);return this.#e=e.match+1,t}popParams(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=[];for(;this.#e<e.match-1;){const n=this.peek().linkNext;t.push(this.#n(this.#e+1,n)),this.#e=n}return this.#e=e.match+1,t}peek(){if(this.#e>=this.#t.length)throw new Error("out-of-bounds");return this.#t[this.#e]}peekKeyword(e){const t=this.peekType("KEYWORD");return t!=null&&e.has(t)?t:null}peekType(e){if(this.length===0)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return this.#e++,e}toString(){const e=[];for(let t=this.#e;t<this.#t.length;t++){const n=this.#t[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}}function er(i){const e=[],t=a=>{const o=r<i.length?JSON.stringify(i[r]):"$EOI";throw new Error(`invalid token ${o} at ${r}: ${a}`)};let n=[],s=[],r=0;for(;r<i.length;){let a=i.substring(r),o=a.match(uL);o&&(r+=o[1].length,a=i.substring(r));const c={depth:n.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:r,value:-1};e.push(c);let l=hL[a[0]]||"";if(l){if(c.type=l,c.text=a[0],r++,l==="OPEN_PAREN")n.push(e.length-1),s.push(e.length-1);else if(l=="CLOSE_PAREN")n.length===0&&t("no matching open bracket"),c.match=n.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if(l==="COMMA")c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if(l==="OPEN_BRACKET")c.type="BRACKET";else if(l==="CLOSE_BRACKET"){let h=e.pop().text;if(e.length>0&&e[e.length-1].type==="NUMBER"){const u=e.pop().text;h=u+h,e[e.length-1].value=dt(u)}if(e.length===0||e[e.length-1].type!=="BRACKET")throw new Error("missing opening bracket");e[e.length-1].text+=h}continue}if(o=a.match(fL),o){if(c.text=o[1],r+=c.text.length,lL.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(hE)){c.type="TYPE";continue}c.type="ID";continue}if(o=a.match(dL),o){c.text=o[1],c.type="NUMBER",r+=c.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(a[0])} at position ${r}`)}return new gi(e.map(a=>Object.freeze(a)))}function uE(i,e){let t=[];for(const n in e.keys())i.has(n)&&t.push(n);if(t.length>1)throw new Error(`conflicting types: ${t.join(", ")}`)}function Sh(i,e){if(e.peekKeyword(oE)){const t=e.pop().text;if(t!==i)throw new Error(`expected ${i}, got ${t}`)}return e.popType("ID")}function bs(i,e){const t=new Set;for(;;){const n=i.peekType("KEYWORD");if(n==null||e&&!e.has(n))break;if(i.pop(),t.has(n))throw new Error(`duplicate keywords: ${JSON.stringify(n)}`);t.add(n)}return Object.freeze(t)}function dE(i){let e=bs(i,aL);return uE(e,qn("constant payable nonpayable".split(" "))),uE(e,qn("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function Es(i,e){return i.popParams().map(t=>kt.from(t,e))}function fE(i){if(i.peekType("AT")){if(i.pop(),i.peekType("NUMBER"))return Ne(i.pop().text);throw new Error("invalid gas")}return null}function Lr(i){if(i.length)throw new Error(`unexpected tokens at offset ${i.offset}: ${i.toString()}`)}const pL=new RegExp(/^(.*)\[([0-9]*)\]$/);function pE(i){const e=i.match(hE);if(V(e,"invalid type","type",i),i==="uint")return"uint256";if(i==="int")return"int256";if(e[2]){const t=parseInt(e[2]);V(t!==0&&t<=32,"invalid bytes length","type",i)}else if(e[3]){const t=parseInt(e[3]);V(t!==0&&t<=256&&t%8===0,"invalid numeric width","type",i)}return i}const Wt={},Yn=Symbol.for("_ethers_internal"),AE="_ParamTypeInternal",gE="_ErrorInternal",mE="_EventInternal",xE="_ConstructorInternal",bE="_FallbackInternal",EE="_FunctionInternal",yE="_StructInternal";class kt{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,s,r,a,o,c){if(ih(e,Wt,"ParamType"),Object.defineProperty(this,Yn,{value:AE}),a&&(a=Object.freeze(a.slice())),s==="array"){if(o==null||c==null)throw new Error("")}else if(o!=null||c!=null)throw new Error("");if(s==="tuple"){if(a==null)throw new Error("")}else if(a!=null)throw new Error("");Ye(this,{name:t,type:n,baseType:s,indexed:r,components:a,arrayLength:o,arrayChildren:c})}format(e){if(e==null&&(e="sighash"),e==="json"){const n=this.name||"";if(this.isArray()){const r=JSON.parse(this.arrayChildren.format("json"));return r.name=n,r.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(r)}const s={type:this.baseType==="tuple"?"tuple":this.type,name:n};return typeof this.indexed=="boolean"&&(s.indexed=this.indexed),this.isTuple()&&(s.components=this.components.map(r=>JSON.parse(r.format(e)))),JSON.stringify(s)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map(n=>n.format(e)).join(e==="full"?", ":",")+")":t+=this.type,e!=="sighash"&&(this.indexed===!0&&(t+=" indexed"),e==="full"&&this.name&&(t+=" "+this.name)),t}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(this.arrayLength!==-1&&e.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return e.map(s=>n.arrayChildren.walk(s,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map((s,r)=>n.components[r].walk(s,t))}return t(this.type,e)}#e(e,t,n,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw new Error("array is wrong length");const a=this.arrayChildren,o=t.slice();o.forEach((c,l)=>{a.#e(e,c,n,h=>{o[l]=h})}),s(o);return}if(this.isTuple()){const a=this.components;let o;if(Array.isArray(t))o=t.slice();else{if(t==null||typeof t!="object")throw new Error("invalid tuple value");o=a.map(c=>{if(!c.name)throw new Error("cannot use object value with unnamed components");if(!(c.name in t))throw new Error(`missing value for component ${c.name}`);return t[c.name]})}if(o.length!==this.components.length)throw new Error("array is wrong length");o.forEach((c,l)=>{a[l].#e(e,c,n,h=>{o[l]=h})}),s(o);return}const r=n(this.type,t);r.then?e.push((async function(){s(await r)})()):s(r)}async walkAsync(e,t){const n=[],s=[e];return this.#e(n,e,t,r=>{s[0]=r}),n.length&&await Promise.all(n),s[0]}static from(e,t){if(kt.isParamType(e))return e;if(typeof e=="string")try{return kt.from(er(e),t)}catch{V(!1,"invalid param type","obj",e)}else if(e instanceof gi){let o="",c="",l=null;bs(e,qn(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(c="tuple",l=e.popParams().map(m=>kt.from(m)),o=`tuple(${l.map(m=>m.format()).join(",")})`):(o=pE(e.popType("TYPE")),c=o);let h=null,u=null;for(;e.length&&e.peekType("BRACKET");){const m=e.pop();h=new kt(Wt,"",o,c,null,l,u,h),u=m.value,o+=m.text,c="array",l=null}let d=null;if(bs(e,oL).has("indexed")){if(!t)throw new Error("");d=!0}const p=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new kt(Wt,p,o,c,d,l,u,h)}const n=e.name;V(!n||typeof n=="string"&&n.match(lE),"invalid name","obj.name",n);let s=e.indexed;s!=null&&(V(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let r=e.type,a=r.match(pL);if(a){const o=parseInt(a[2]||"-1"),c=kt.from({type:a[1],components:e.components});return new kt(Wt,n||"",r,"array",s,null,o,c)}if(r==="tuple"||r.startsWith("tuple(")||r.startsWith("(")){const o=e.components!=null?e.components.map(l=>kt.from(l)):null;return new kt(Wt,n||"",r,"tuple",s,o,null,null)}return r=pE(e.type),new kt(Wt,n||"",r,r,s,null,null,null)}static isParamType(e){return e&&e[Yn]===AE}}class Pr{type;inputs;constructor(e,t,n){ih(e,Wt,"Fragment"),n=Object.freeze(n.slice()),Ye(this,{type:t,inputs:n})}static from(e){if(typeof e=="string"){try{Pr.from(JSON.parse(e))}catch{}return Pr.from(er(e))}if(e instanceof gi)switch(e.peekKeyword(oE)){case"constructor":return ys.from(e);case"error":return Jn.from(e);case"event":return Wi.from(e);case"fallback":case"receive":return _s.from(e);case"function":return qi.from(e);case"struct":return kr.from(e)}else if(typeof e=="object"){switch(e.type){case"constructor":return ys.from(e);case"error":return Jn.from(e);case"event":return Wi.from(e);case"fallback":case"receive":return _s.from(e);case"function":return qi.from(e);case"struct":return kr.from(e)}pe(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}V(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return ys.isFragment(e)}static isError(e){return Jn.isFragment(e)}static isEvent(e){return Wi.isFragment(e)}static isFunction(e){return qi.isFragment(e)}static isStruct(e){return kr.isFragment(e)}}class Mh extends Pr{name;constructor(e,t,n,s){super(e,t,s),V(typeof n=="string"&&n.match(lE),"invalid identifier","name",n),s=Object.freeze(s.slice()),Ye(this,{name:n})}}function dc(i,e){return"("+e.map(t=>t.format(i)).join(i==="full"?", ":",")+")"}class Jn extends Mh{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,Yn,{value:gE})}get selector(){return Fr(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("error"),t.push(this.name+dc(e,this.inputs)),t.join(" ")}static from(e){if(Jn.isFragment(e))return e;if(typeof e=="string")return Jn.from(er(e));if(e instanceof gi){const t=Sh("error",e),n=Es(e);return Lr(e),new Jn(Wt,t,n)}return new Jn(Wt,e.name,e.inputs?e.inputs.map(kt.from):[])}static isFragment(e){return e&&e[Yn]===gE}}class Wi extends Mh{anonymous;constructor(e,t,n,s){super(e,"event",t,n),Object.defineProperty(this,Yn,{value:mE}),Ye(this,{anonymous:s})}get topicHash(){return Fr(this.format("sighash"))}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("event"),t.push(this.name+dc(e,this.inputs)),e!=="sighash"&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){return t=(t||[]).map(s=>kt.from(s)),new Wi(Wt,e,t,!1).topicHash}static from(e){if(Wi.isFragment(e))return e;if(typeof e=="string")try{return Wi.from(er(e))}catch{V(!1,"invalid event fragment","obj",e)}else if(e instanceof gi){const t=Sh("event",e),n=Es(e,!0),s=!!bs(e,qn(["anonymous"])).has("anonymous");return Lr(e),new Wi(Wt,t,n,s)}return new Wi(Wt,e.name,e.inputs?e.inputs.map(t=>kt.from(t,!0)):[],!!e.anonymous)}static isFragment(e){return e&&e[Yn]===mE}}class ys extends Pr{payable;gas;constructor(e,t,n,s,r){super(e,t,n),Object.defineProperty(this,Yn,{value:xE}),Ye(this,{payable:s,gas:r})}format(e){if(pe(e!=null&&e!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),e==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(n=>JSON.parse(n.format(e)))});const t=[`constructor${dc(e,this.inputs)}`];return this.payable&&t.push("payable"),this.gas!=null&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(ys.isFragment(e))return e;if(typeof e=="string")try{return ys.from(er(e))}catch{V(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof gi){bs(e,qn(["constructor"]));const t=Es(e),n=!!bs(e,rL).has("payable"),s=fE(e);return Lr(e),new ys(Wt,"constructor",t,n,s)}return new ys(Wt,"constructor",e.inputs?e.inputs.map(kt.from):[],!!e.payable,e.gas!=null?e.gas:null)}static isFragment(e){return e&&e[Yn]===xE}}class _s extends Pr{payable;constructor(e,t,n){super(e,"fallback",t),Object.defineProperty(this,Yn,{value:bE}),Ye(this,{payable:n})}format(e){const t=this.inputs.length===0?"receive":"fallback";if(e==="json"){const n=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:n})}return`${t}()${this.payable?" payable":""}`}static from(e){if(_s.isFragment(e))return e;if(typeof e=="string")try{return _s.from(er(e))}catch{V(!1,"invalid fallback fragment","obj",e)}else if(e instanceof gi){const t=e.toString(),n=e.peekKeyword(qn(["fallback","receive"]));if(V(n,"type must be fallback or receive","obj",t),e.popKeyword(qn(["fallback","receive"]))==="receive"){const o=Es(e);return V(o.length===0,"receive cannot have arguments","obj.inputs",o),bs(e,qn(["payable"])),Lr(e),new _s(Wt,[],!0)}let r=Es(e);r.length?V(r.length===1&&r[0].type==="bytes","invalid fallback inputs","obj.inputs",r.map(o=>o.format("minimal")).join(", ")):r=[kt.from("bytes")];const a=dE(e);if(V(a==="nonpayable"||a==="payable","fallback cannot be constants","obj.stateMutability",a),bs(e,qn(["returns"])).has("returns")){const o=Es(e);V(o.length===1&&o[0].type==="bytes","invalid fallback outputs","obj.outputs",o.map(c=>c.format("minimal")).join(", "))}return Lr(e),new _s(Wt,r,a==="payable")}if(e.type==="receive")return new _s(Wt,[],!0);if(e.type==="fallback"){const t=[kt.from("bytes")],n=e.stateMutability==="payable";return new _s(Wt,t,n)}V(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[Yn]===bE}}class qi extends Mh{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,s,r,a){super(e,"function",t,s),Object.defineProperty(this,Yn,{value:EE}),r=Object.freeze(r.slice()),Ye(this,{constant:n==="view"||n==="pure",gas:a,outputs:r,payable:n==="payable",stateMutability:n})}get selector(){return Fr(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(n=>JSON.parse(n.format(e))),outputs:this.outputs.map(n=>JSON.parse(n.format(e)))});const t=[];return e!=="sighash"&&t.push("function"),t.push(this.name+dc(e,this.inputs)),e!=="sighash"&&(this.stateMutability!=="nonpayable"&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(dc(e,this.outputs))),this.gas!=null&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){return t=(t||[]).map(s=>kt.from(s)),new qi(Wt,e,"view",t,[],null).selector}static from(e){if(qi.isFragment(e))return e;if(typeof e=="string")try{return qi.from(er(e))}catch{V(!1,"invalid function fragment","obj",e)}else if(e instanceof gi){const n=Sh("function",e),s=Es(e),r=dE(e);let a=[];bs(e,qn(["returns"])).has("returns")&&(a=Es(e));const o=fE(e);return Lr(e),new qi(Wt,n,r,s,a,o)}let t=e.stateMutability;return t==null&&(t="payable",typeof e.constant=="boolean"?(t="view",e.constant||(t="payable",typeof e.payable=="boolean"&&!e.payable&&(t="nonpayable"))):typeof e.payable=="boolean"&&!e.payable&&(t="nonpayable")),new qi(Wt,e.name,t,e.inputs?e.inputs.map(kt.from):[],e.outputs?e.outputs.map(kt.from):[],e.gas!=null?e.gas:null)}static isFragment(e){return e&&e[Yn]===EE}}class kr extends Mh{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,Yn,{value:yE})}format(){throw new Error("@TODO")}static from(e){if(typeof e=="string")try{return kr.from(er(e))}catch{V(!1,"invalid struct fragment","obj",e)}else if(e instanceof gi){const t=Sh("struct",e),n=Es(e);return Lr(e),new kr(Wt,t,n)}return new kr(Wt,e.name,e.inputs?e.inputs.map(kt.from):[])}static isFragment(e){return e&&e[Yn]===yE}}const Di=new Map;Di.set(0,"GENERIC_PANIC"),Di.set(1,"ASSERT_FALSE"),Di.set(17,"OVERFLOW"),Di.set(18,"DIVIDE_BY_ZERO"),Di.set(33,"ENUM_RANGE_ERROR"),Di.set(34,"BAD_STORAGE_DATA"),Di.set(49,"STACK_UNDERFLOW"),Di.set(50,"ARRAY_RANGE_ERROR"),Di.set(65,"OUT_OF_MEMORY"),Di.set(81,"UNINITIALIZED_FUNCTION_CALL");const AL=new RegExp(/^bytes([0-9]*)$/),gL=new RegExp(/^(u?int)([0-9]*)$/);let Ep=null,_E=1024;function mL(i,e,t,n){let s="missing revert data",r=null;const a=null;let o=null;if(t){s="execution reverted";const l=ut(t);if(t=Ce(t),l.length===0)s+=" (no data present; likely require(false) occurred",r="require(false)";else if(l.length%32!==4)s+=" (could not decode reason; invalid data length)";else if(Ce(l.slice(0,4))==="0x08c379a0")try{r=n.decode(["string"],l.slice(4))[0],o={signature:"Error(string)",name:"Error",args:[r]},s+=`: ${JSON.stringify(r)}`}catch{s+=" (could not decode reason; invalid string data)"}else if(Ce(l.slice(0,4))==="0x4e487b71")try{const h=Number(n.decode(["uint256"],l.slice(4))[0]);o={signature:"Panic(uint256)",name:"Panic",args:[h]},r=`Panic due to ${Di.get(h)||"UNKNOWN"}(${h})`,s+=`: ${r}`}catch{s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const c={to:e.to?St(e.to):null,data:e.data||"0x"};return e.from&&(c.from=St(e.from)),Qt(s,"CALL_EXCEPTION",{action:i,data:t,reason:r,transaction:c,invocation:a,revert:o})}class ja{#e(e){if(e.isArray())return new PN(this.#e(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new ph(e.components.map(n=>this.#e(n)),e.name);switch(e.baseType){case"address":return new DN(e.name);case"bool":return new kN(e.name);case"string":return new qN(e.name);case"bytes":return new UN(e.name);case"":return new GN(e.name)}let t=e.type.match(gL);if(t){let n=parseInt(t[2]||"256");return V(n!==0&&n<=256&&n%8===0,"invalid "+t[1]+" bit length","param",e),new WN(n/8,t[1]==="int",e.name)}if(t=e.type.match(AL),t){let n=parseInt(t[1]);return V(n!==0&&n<=32,"invalid bytes length","param",e),new ON(n,e.name)}V(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map(s=>this.#e(kt.from(s)));return new ph(t,"_").defaultValue()}encode(e,t){sx(t.length,e.length,"types/values length mismatch");const n=e.map(a=>this.#e(kt.from(a))),s=new ph(n,"_"),r=new kf;return s.encode(r,t),r.data}decode(e,t,n){const s=e.map(a=>this.#e(kt.from(a)));return new ph(s,"_").decode(new Uf(t,n,_E))}static _setDefaultMaxInflation(e){V(typeof e=="number"&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),_E=e}static defaultAbiCoder(){return Ep==null&&(Ep=new ja),Ep}static getBuiltinCallException(e,t,n){return mL(e,t,n,ja.defaultAbiCoder())}}class xL{fragment;name;signature;topic;args;constructor(e,t,n){const s=e.name,r=e.format();Ye(this,{fragment:e,name:s,signature:r,topic:t,args:n})}}class bL{fragment;name;args;signature;selector;value;constructor(e,t,n,s){const r=e.name,a=e.format();Ye(this,{fragment:e,name:r,args:n,signature:a,selector:t,value:s})}}class EL{fragment;name;args;signature;selector;constructor(e,t,n){const s=e.name,r=e.format();Ye(this,{fragment:e,name:s,args:n,signature:r,selector:t})}}class wE{hash;_isIndexed;static isIndexed(e){return!!(e&&e._isIndexed)}constructor(e){Ye(this,{hash:e,_isIndexed:!0})}}const vE={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},CE={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:i=>`reverted with reason string ${JSON.stringify(i)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:i=>{let e="unknown panic code";return i>=0&&i<=255&&vE[i.toString()]&&(e=vE[i.toString()]),`reverted with panic code 0x${i.toString(16)} (${e})`}}};class Ur{fragments;deploy;fallback;receive;#e;#t;#n;#i;constructor(e){let t=[];typeof e=="string"?t=JSON.parse(e):t=e,this.#n=new Map,this.#e=new Map,this.#t=new Map;const n=[];for(const a of t)try{n.push(Pr.from(a))}catch(o){console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`,o.message)}Ye(this,{fragments:Object.freeze(n)});let s=null,r=!1;this.#i=this.getAbiCoder(),this.fragments.forEach((a,o)=>{let c;switch(a.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}Ye(this,{deploy:a});return;case"fallback":a.inputs.length===0?r=!0:(V(!s||a.payable!==s.payable,"conflicting fallback fragments",`fragments[${o}]`,a),s=a,r=s.payable);return;case"function":c=this.#n;break;case"event":c=this.#t;break;case"error":c=this.#e;break;default:return}const l=a.format();c.has(l)||c.set(l,a)}),this.deploy||Ye(this,{deploy:ys.from("constructor()")}),Ye(this,{fallback:s,receive:r})}format(e){const t=e?"minimal":"full";return this.fragments.map(s=>s.format(t))}formatJson(){const e=this.fragments.map(t=>t.format("json"));return JSON.stringify(e.map(t=>JSON.parse(t)))}getAbiCoder(){return ja.defaultAbiCoder()}#s(e,t,n){if(Pt(e)){const r=e.toLowerCase();for(const a of this.#n.values())if(r===a.selector)return a;return null}if(e.indexOf("(")===-1){const r=[];for(const[a,o]of this.#n)a.split("(")[0]===e&&r.push(o);if(t){const a=t.length>0?t[t.length-1]:null;let o=t.length,c=!0;jt.isTyped(a)&&a.type==="overrides"&&(c=!1,o--);for(let l=r.length-1;l>=0;l--){const h=r[l].inputs.length;h!==o&&(!c||h!==o-1)&&r.splice(l,1)}for(let l=r.length-1;l>=0;l--){const h=r[l].inputs;for(let u=0;u<t.length;u++)if(jt.isTyped(t[u])){if(u>=h.length){if(t[u].type==="overrides")continue;r.splice(l,1);break}if(t[u].type!==h[u].baseType){r.splice(l,1);break}}}}if(r.length===1&&t&&t.length!==r[0].inputs.length){const a=t[t.length-1];(a==null||Array.isArray(a)||typeof a!="object")&&r.splice(0,1)}if(r.length===0)return null;if(r.length>1&&n){const a=r.map(o=>JSON.stringify(o.format())).join(", ");V(!1,`ambiguous function description (i.e. matches ${a})`,"key",e)}return r[0]}const s=this.#n.get(qi.from(e).format());return s||null}getFunctionName(e){const t=this.#s(e,null,!1);return V(t,"no matching function","key",e),t.name}hasFunction(e){return!!this.#s(e,null,!1)}getFunction(e,t){return this.#s(e,t||null,!0)}forEachFunction(e){const t=Array.from(this.#n.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#n.get(s),n)}}#a(e,t,n){if(Pt(e)){const r=e.toLowerCase();for(const a of this.#t.values())if(r===a.topicHash)return a;return null}if(e.indexOf("(")===-1){const r=[];for(const[a,o]of this.#t)a.split("(")[0]===e&&r.push(o);if(t){for(let a=r.length-1;a>=0;a--)r[a].inputs.length<t.length&&r.splice(a,1);for(let a=r.length-1;a>=0;a--){const o=r[a].inputs;for(let c=0;c<t.length;c++)if(jt.isTyped(t[c])&&t[c].type!==o[c].baseType){r.splice(a,1);break}}}if(r.length===0)return null;if(r.length>1&&n){const a=r.map(o=>JSON.stringify(o.format())).join(", ");V(!1,`ambiguous event description (i.e. matches ${a})`,"key",e)}return r[0]}const s=this.#t.get(Wi.from(e).format());return s||null}getEventName(e){const t=this.#a(e,null,!1);return V(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#a(e,null,!1)}getEvent(e,t){return this.#a(e,t||null,!0)}forEachEvent(e){const t=Array.from(this.#t.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#t.get(s),n)}}getError(e,t){if(Pt(e)){const s=e.toLowerCase();if(CE[s])return Jn.from(CE[s].signature);for(const r of this.#e.values())if(s===r.selector)return r;return null}if(e.indexOf("(")===-1){const s=[];for(const[r,a]of this.#e)r.split("(")[0]===e&&s.push(a);if(s.length===0)return e==="Error"?Jn.from("error Error(string)"):e==="Panic"?Jn.from("error Panic(uint256)"):null;if(s.length>1){const r=s.map(a=>JSON.stringify(a.format())).join(", ");V(!1,`ambiguous error description (i.e. ${r})`,"name",e)}return s[0]}if(e=Jn.from(e).format(),e==="Error(string)")return Jn.from("error Error(string)");if(e==="Panic(uint256)")return Jn.from("error Panic(uint256)");const n=this.#e.get(e);return n||null}forEachError(e){const t=Array.from(this.#e.keys());t.sort((n,s)=>n.localeCompare(s));for(let n=0;n<t.length;n++){const s=t[n];e(this.#e.get(s),n)}}_decodeParams(e,t){return this.#i.decode(e,t)}_encodeParams(e,t){return this.#i.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if(typeof e=="string"){const n=this.getError(e);V(n,"unknown error","fragment",e),e=n}return V(Kt(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,Kt(t,4))}encodeErrorResult(e,t){if(typeof e=="string"){const n=this.getError(e);V(n,"unknown error","fragment",e),e=n}return Gt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return V(Kt(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,Kt(t,4))}encodeFunctionData(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return Gt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if(typeof e=="string"){const r=this.getFunction(e);V(r,"unknown function","fragment",e),e=r}let n="invalid length for result data";const s=zn(t);if(s.length%32===0)try{return this.#i.decode(e.outputs,s)}catch{n="could not decode result data"}pe(!1,n,"BAD_DATA",{value:Ce(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=ut(e,"data"),s=ja.getBuiltinCallException("call",t,n);if(s.message.startsWith("execution reverted (unknown custom error)")){const o=Ce(n.slice(0,4)),c=this.getError(o);if(c)try{const l=this.#i.decode(c.inputs,n.slice(4));s.revert={name:c.name,signature:c.format(),args:l},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch{s.message="execution reverted (coult not decode custom error)"}}const a=this.parseTransaction(t);return a&&(s.invocation={method:a.name,signature:a.signature,args:a.args}),s}encodeFunctionResult(e,t){if(typeof e=="string"){const n=this.getFunction(e);V(n,"unknown function","fragment",e),e=n}return Ce(this.#i.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if(typeof e=="string"){const r=this.getEvent(e);V(r,"unknown event","eventFragment",e),e=r}pe(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const s=(r,a)=>r.type==="string"?Fr(a):r.type==="bytes"?an(Ce(a)):(r.type==="bool"&&typeof a=="boolean"?a=a?"0x01":"0x00":r.type.match(/^u?int/)?a=Ks(a):r.type.match(/^bytes/)?a=ZR(a,32):r.type==="address"&&this.#i.encode(["address"],[a]),us(Ce(a),32));for(t.forEach((r,a)=>{const o=e.inputs[a];if(!o.indexed){V(r==null,"cannot filter non-indexed parameters; must be null","contract."+o.name,r);return}r==null?n.push(null):o.baseType==="array"||o.baseType==="tuple"?V(!1,"filtering with tuples or arrays not supported","contract."+o.name,r):Array.isArray(r)?n.push(r.map(c=>s(o,c))):n.push(s(o,r))});n.length&&n[n.length-1]===null;)n.pop();return n}encodeEventLog(e,t){if(typeof e=="string"){const a=this.getEvent(e);V(a,"unknown event","eventFragment",e),e=a}const n=[],s=[],r=[];return e.anonymous||n.push(e.topicHash),V(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((a,o)=>{const c=t[o];if(a.indexed)if(a.type==="string")n.push(Fr(c));else if(a.type==="bytes")n.push(an(c));else{if(a.baseType==="tuple"||a.baseType==="array")throw new Error("not implemented");n.push(this.#i.encode([a.type],[c]))}else s.push(a),r.push(c)}),{data:this.#i.encode(s,r),topics:n}}decodeEventLog(e,t,n){if(typeof e=="string"){const f=this.getEvent(e);V(f,"unknown event","eventFragment",e),e=f}if(n!=null&&!e.anonymous){const f=e.topicHash;V(Pt(n[0],32)&&n[0].toLowerCase()===f,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const s=[],r=[],a=[];e.inputs.forEach((f,p)=>{f.indexed?f.type==="string"||f.type==="bytes"||f.baseType==="tuple"||f.baseType==="array"?(s.push(kt.from({type:"bytes32",name:f.name})),a.push(!0)):(s.push(f),a.push(!1)):(r.push(f),a.push(!1))});const o=n!=null?this.#i.decode(s,Gt(n)):null,c=this.#i.decode(r,t,!0),l=[],h=[];let u=0,d=0;return e.inputs.forEach((f,p)=>{let m=null;if(f.indexed)if(o==null)m=new wE(null);else if(a[p])m=new wE(o[d++]);else try{m=o[d++]}catch(g){m=g}else try{m=c[u++]}catch(g){m=g}l.push(m),h.push(f.name||null)}),ps.fromItems(l,h)}parseTransaction(e){const t=ut(e.data,"tx.data"),n=Ne(e.value!=null?e.value:0,"tx.value"),s=this.getFunction(Ce(t.slice(0,4)));if(!s)return null;const r=this.#i.decode(s.inputs,t.slice(4));return new bL(s,s.selector,r,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new xL(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=Ce(e),n=this.getError(Kt(t,0,4));if(!n)return null;const s=this.#i.decode(n.inputs,Kt(t,4));return new EL(n,n.selector,s)}static from(e){return e instanceof Ur?e:typeof e=="string"?new Ur(JSON.parse(e)):typeof e.formatJson=="function"?new Ur(e.formatJson()):typeof e.format=="function"?new Ur(e.format("json")):new Ur(e)}}const IE=BigInt(0);function Xa(i){return i??null}function tn(i){return i==null?null:i.toString()}class SE{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){Ye(this,{gasPrice:Xa(e),maxFeePerGas:Xa(t),maxPriorityFeePerGas:Xa(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:tn(e),maxFeePerGas:tn(t),maxPriorityFeePerGas:tn(n)}}}function Bh(i){const e={};i.to&&(e.to=i.to),i.from&&(e.from=i.from),i.data&&(e.data=Ce(i.data));const t="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of t)!(s in i)||i[s]==null||(e[s]=Ne(i[s],`request.${s}`));const n="type,nonce".split(/,/);for(const s of n)!(s in i)||i[s]==null||(e[s]=dt(i[s],`request.${s}`));return i.accessList&&(e.accessList=Tr(i.accessList)),i.authorizationList&&(e.authorizationList=i.authorizationList.slice()),"blockTag"in i&&(e.blockTag=i.blockTag),"enableCcipRead"in i&&(e.enableCcipRead=!!i.enableCcipRead),"customData"in i&&(e.customData=i.customData),"blobVersionedHashes"in i&&i.blobVersionedHashes&&(e.blobVersionedHashes=i.blobVersionedHashes.slice()),"kzg"in i&&(e.kzg=i.kzg),"blobWrapperVersion"in i&&(e.blobWrapperVersion=i.blobWrapperVersion),"blobs"in i&&i.blobs&&(e.blobs=i.blobs.map(s=>Ff(s)?Ce(s):Object.assign({},s))),e}class yL{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#e;constructor(e,t){this.#e=e.transactions.map(n=>typeof n!="string"?new pc(n,t):n),Ye(this,{provider:t,hash:Xa(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:Xa(e.prevRandao),extraData:e.extraData,baseFeePerGas:Xa(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#e.map(e=>typeof e=="string"?e:e.hash)}get prefetchedTransactions(){const e=this.#e.slice();return e.length===0?[]:(pe(typeof e[0]=="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,extraData:n,gasLimit:s,gasUsed:r,hash:a,miner:o,prevRandao:c,nonce:l,number:h,parentHash:u,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,timestamp:m,transactions:g}=this;return{_type:"Block",baseFeePerGas:tn(e),difficulty:tn(t),extraData:n,gasLimit:tn(s),gasUsed:tn(r),blobGasUsed:tn(this.blobGasUsed),excessBlobGas:tn(this.excessBlobGas),hash:a,miner:o,prevRandao:c,nonce:l,number:h,parentHash:u,timestamp:m,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,transactions:g}}[Symbol.iterator](){let e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#e.length}get date(){return this.timestamp==null?null:new Date(this.timestamp*1e3)}async getTransaction(e){let t;if(typeof e=="number")t=this.#e[e];else{const n=e.toLowerCase();for(const s of this.#e)if(typeof s=="string"){if(s!==n)continue;t=s;break}else{if(s.hash!==n)continue;t=s;break}}if(t==null)throw new Error("no such tx");return typeof t=="string"?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if(typeof e=="number")return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;V(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return _L(this)}}class fc{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const n=Object.freeze(e.topics.slice());Ye(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:o,transactionHash:c,transactionIndex:l}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:a,topics:o,transactionHash:c,transactionIndex:l}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return pe(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return pe(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return pe(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return wL(this)}}class ME{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#e;constructor(e,t){this.#e=Object.freeze(e.logs.map(s=>new fc(s,t)));let n=IE;e.effectiveGasPrice!=null?n=e.effectiveGasPrice:e.gasPrice!=null&&(n=e.gasPrice),Ye(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#e}toJSON(){const{to:e,from:t,contractAddress:n,hash:s,index:r,blockHash:a,blockNumber:o,logsBloom:c,logs:l,status:h,root:u}=this;return{_type:"TransactionReceipt",blockHash:a,blockNumber:o,contractAddress:n,cumulativeGasUsed:tn(this.cumulativeGasUsed),from:t,gasPrice:tn(this.gasPrice),blobGasUsed:tn(this.blobGasUsed),blobGasPrice:tn(this.blobGasPrice),gasUsed:tn(this.gasUsed),hash:s,index:r,logs:l,logsBloom:c,root:u,status:h,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(e==null)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(e==null)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return TE(this)}reorderedEvent(e){return pe(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),BE(this,e)}}class pc{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#e;constructor(e,t){this.provider=t,this.blockNumber=e.blockNumber!=null?e.blockNumber:null,this.blockHash=e.blockHash!=null?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=e.maxPriorityFeePerGas!=null?e.maxPriorityFeePerGas:null,this.maxFeePerGas=e.maxFeePerGas!=null?e.maxFeePerGas:null,this.maxFeePerBlobGas=e.maxFeePerBlobGas!=null?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=e.accessList!=null?e.accessList:null,this.blobVersionedHashes=e.blobVersionedHashes!=null?e.blobVersionedHashes:null,this.authorizationList=e.authorizationList!=null?e.authorizationList:null,this.#e=-1}toJSON(){const{blockNumber:e,blockHash:t,index:n,hash:s,type:r,to:a,from:o,nonce:c,data:l,signature:h,accessList:u,blobVersionedHashes:d}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:e,blockHash:t,blobVersionedHashes:d,chainId:tn(this.chainId),data:l,from:o,gasLimit:tn(this.gasLimit),gasPrice:tn(this.gasPrice),hash:s,maxFeePerGas:tn(this.maxFeePerGas),maxPriorityFeePerGas:tn(this.maxPriorityFeePerGas),maxFeePerBlobGas:tn(this.maxFeePerBlobGas),nonce:c,signature:h,to:a,index:n,type:r,value:tn(this.value)}}async getBlock(){let e=this.blockNumber;if(e==null){const n=await this.getTransaction();n&&(e=n.blockNumber)}if(e==null)return null;const t=this.provider.getBlock(e);if(t==null)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(this.blockNumber==null){const{tx:t,blockNumber:n}=await Hn({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return t==null||t.blockNumber==null?0:n-t.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=e??1,s=t??0;let r=this.#e,a=-1,o=r===-1;const c=async()=>{if(o)return null;const{blockNumber:d,nonce:f}=await Hn({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(f<this.nonce){r=d;return}if(o)return null;const p=await this.getTransaction();if(!(p&&p.blockNumber!=null))for(a===-1&&(a=r-3,a<this.#e&&(a=this.#e));a<=d;){if(o)return null;const m=await this.provider.getBlock(a,!0);if(m==null)return;for(const g of m)if(g===this.hash)return;for(let g=0;g<m.length;g++){const A=await m.getTransaction(g);if(A.from===this.from&&A.nonce===this.nonce){if(o)return null;const _=await this.provider.getTransactionReceipt(A.hash);if(_==null||d-_.blockNumber+1<n)return;let x="replaced";A.data===this.data&&A.to===this.to&&A.value===this.value?x="repriced":A.data==="0x"&&A.from===A.to&&A.value===IE&&(x="cancelled"),pe(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:x==="replaced"||x==="cancelled",reason:x,replacement:A.replaceableTransaction(r),hash:A.hash,receipt:_})}}a++}},l=d=>{if(d==null||d.status!==0)return d;pe(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:d.to,from:d.from,data:""},receipt:d})},h=await this.provider.getTransactionReceipt(this.hash);if(n===0)return l(h);if(h){if(n===1||await h.confirmations()>=n)return l(h)}else if(await c(),n===0)return null;return await new Promise((d,f)=>{const p=[],m=()=>{p.forEach(A=>A())};if(p.push(()=>{o=!0}),s>0){const A=setTimeout(()=>{m(),f(Qt("wait for transaction timeout","TIMEOUT"))},s);p.push(()=>{clearTimeout(A)})}const g=async A=>{if(await A.confirmations()>=n){m();try{d(l(A))}catch(_){f(_)}}};if(p.push(()=>{this.provider.off(this.hash,g)}),this.provider.on(this.hash,g),r>=0){const A=async()=>{try{await c()}catch(_){if(Tn(_,"TRANSACTION_REPLACED")){m(),f(_);return}}o||this.provider.once("block",A)};p.push(()=>{this.provider.off("block",A)}),this.provider.once("block",A)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}removedEvent(){return pe(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),TE(this)}reorderedEvent(e){return pe(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),pe(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),BE(this,e)}replaceableTransaction(e){V(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new pc(this,this.provider);return t.#e=e,t}}function _L(i){return{orphan:"drop-block",hash:i.hash,number:i.number}}function BE(i,e){return{orphan:"reorder-transaction",tx:i,other:e}}function TE(i){return{orphan:"drop-transaction",tx:i}}function wL(i){return{orphan:"drop-log",log:{transactionHash:i.transactionHash,blockHash:i.blockHash,blockNumber:i.blockNumber,address:i.address,data:i.data,topics:Object.freeze(i.topics.slice()),index:i.index}}}class yp extends fc{interface;fragment;args;constructor(e,t,n){super(e,e.provider);const s=t.decodeEventLog(n,e.data,e.topics);Ye(this,{args:s,fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class RE extends fc{error;constructor(e,t){super(e,e.provider),Ye(this,{error:t})}}class vL extends ME{#e;constructor(e,t,n){super(n,t),this.#e=e}get logs(){return super.logs.map(e=>{const t=e.topics.length?this.#e.getEvent(e.topics[0]):null;if(t)try{return new yp(e,this.#e,t)}catch(n){return new RE(e,n)}return e})}}class _p extends pc{#e;constructor(e,t,n){super(n,t),this.#e=e}async wait(e,t){const n=await super.wait(e,t);return n==null?null:new vL(this.#e,this.provider,n)}}class FE extends dx{log;constructor(e,t,n,s){super(e,t,n),Ye(this,{log:s})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class CL extends FE{constructor(e,t,n,s,r){super(e,t,n,new yp(r,e.interface,s));const a=e.interface.decodeEventLog(s,this.log.data,this.log.topics);Ye(this,{args:a,fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const NE=BigInt(0);function DE(i){return i&&typeof i.call=="function"}function LE(i){return i&&typeof i.estimateGas=="function"}function Th(i){return i&&typeof i.resolveName=="function"}function PE(i){return i&&typeof i.sendTransaction=="function"}function kE(i){if(i!=null){if(Th(i))return i;if(i.provider)return i.provider}}class IL{#e;fragment;constructor(e,t,n){if(Ye(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const s=Or(e.runner,"resolveName"),r=Th(s)?s:null;this.#e=(async function(){const a=await Promise.all(t.inputs.map((o,c)=>n[c]==null?null:o.walkAsync(n[c],(h,u)=>h==="address"?Array.isArray(u)?Promise.all(u.map(d=>Wn(d,r))):Wn(u,r):u)));return e.interface.encodeFilterTopics(t,a)})()}getTopicFilter(){return this.#e}}function Or(i,e){return i==null?null:typeof i[e]=="function"?i:i.provider&&typeof i.provider[e]=="function"?i.provider:null}function Qr(i){return i==null?null:i.provider||null}async function UE(i,e){const t=jt.dereference(i,"overrides");V(typeof t=="object","invalid overrides parameter","overrides",i);const n=Bh(t);return V(n.to==null||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",n.to),V(n.data==null||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",n.data),n.from&&(n.from=n.from),n}async function SL(i,e,t){const n=Or(i,"resolveName"),s=Th(n)?n:null;return await Promise.all(e.map((r,a)=>r.walkAsync(t[a],(o,c)=>(c=jt.dereference(c,o),o==="address"?Wn(c,s):c))))}function ML(i){const e=async function(a){const o=await UE(a,["data"]);o.to=await i.getAddress(),o.from&&(o.from=await Wn(o.from,kE(i.runner)));const c=i.interface,l=Ne(o.value||NE,"overrides.value")===NE,h=(o.data||"0x")==="0x";c.fallback&&!c.fallback.payable&&c.receive&&!h&&!l&&V(!1,"cannot send data to receive or send value to non-payable fallback","overrides",a),V(c.fallback||h,"cannot send data to receive-only contract","overrides.data",o.data);const u=c.receive||c.fallback&&c.fallback.payable;return V(u||l,"cannot send value to non-payable fallback","overrides.value",o.value),V(c.fallback||h,"cannot send data to receive-only contract","overrides.data",o.data),o},t=async function(a){const o=Or(i.runner,"call");pe(DE(o),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const c=await e(a);try{return await o.call(c)}catch(l){throw Rf(l)&&l.data?i.interface.makeError(l.data,c):l}},n=async function(a){const o=i.runner;pe(PE(o),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const c=await o.sendTransaction(await e(a)),l=Qr(i.runner);return new _p(i.interface,l,c)},s=async function(a){const o=Or(i.runner,"estimateGas");return pe(LE(o),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await o.estimateGas(await e(a))},r=async a=>await n(a);return Ye(r,{_contract:i,estimateGas:s,populateTransaction:e,send:n,staticCall:t}),r}function BL(i,e){const t=function(...l){const h=i.interface.getFunction(e,l);return pe(h,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:l}}),h},n=async function(...l){const h=t(...l);let u={};if(h.inputs.length+1===l.length&&(u=await UE(l.pop()),u.from&&(u.from=await Wn(u.from,kE(i.runner)))),h.inputs.length!==l.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const d=await SL(i.runner,h.inputs,l);return Object.assign({},u,await Hn({to:i.getAddress(),data:i.interface.encodeFunctionData(h,d)}))},s=async function(...l){const h=await o(...l);return h.length===1?h[0]:h},r=async function(...l){const h=i.runner;pe(PE(h),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const u=await h.sendTransaction(await n(...l)),d=Qr(i.runner);return new _p(i.interface,d,u)},a=async function(...l){const h=Or(i.runner,"estimateGas");return pe(LE(h),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await h.estimateGas(await n(...l))},o=async function(...l){const h=Or(i.runner,"call");pe(DE(h),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const u=await n(...l);let d="0x";try{d=await h.call(u)}catch(p){throw Rf(p)&&p.data?i.interface.makeError(p.data,u):p}const f=t(...l);return i.interface.decodeFunctionResult(f,d)},c=async(...l)=>t(...l).constant?await s(...l):await r(...l);return Ye(c,{name:i.interface.getFunctionName(e),_contract:i,_key:e,getFragment:t,estimateGas:a,populateTransaction:n,send:r,staticCall:s,staticCallResult:o}),Object.defineProperty(c,"fragment",{configurable:!1,enumerable:!0,get:()=>{const l=i.interface.getFunction(e);return pe(l,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),l}}),c}function TL(i,e){const t=function(...s){const r=i.interface.getEvent(e,s);return pe(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e,args:s}}),r},n=function(...s){return new IL(i,t(...s),s)};return Ye(n,{name:i.interface.getEventName(e),_contract:i,_key:e,getFragment:t}),Object.defineProperty(n,"fragment",{configurable:!1,enumerable:!0,get:()=>{const s=i.interface.getEvent(e);return pe(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:e}}),s}}),n}const Rh=Symbol.for("_ethersInternal_contract"),OE=new WeakMap;function RL(i,e){OE.set(i[Rh],e)}function ni(i){return OE.get(i[Rh])}function FL(i){return i&&typeof i=="object"&&"getTopicFilter"in i&&typeof i.getTopicFilter=="function"&&i.fragment}async function wp(i,e){let t,n=null;if(Array.isArray(e)){const r=function(a){if(Pt(a,32))return a;const o=i.interface.getEvent(a);return V(o,"unknown fragment","name",a),o.topicHash};t=e.map(a=>a==null?null:Array.isArray(a)?a.map(r):r(a))}else e==="*"?t=[null]:typeof e=="string"?Pt(e,32)?t=[e]:(n=i.interface.getEvent(e),V(n,"unknown fragment","event",e),t=[n.topicHash]):FL(e)?t=await e.getTopicFilter():"fragment"in e?(n=e.fragment,t=[n.topicHash]):V(!1,"unknown event name","event",e);t=t.map(r=>{if(r==null)return null;if(Array.isArray(r)){const a=Array.from(new Set(r.map(o=>o.toLowerCase())).values());return a.length===1?a[0]:(a.sort(),a)}return r.toLowerCase()});const s=t.map(r=>r==null?"null":Array.isArray(r)?r.join("|"):r).join("&");return{fragment:n,tag:s,topics:t}}async function Ac(i,e){const{subs:t}=ni(i);return t.get((await wp(i,e)).tag)||null}async function QE(i,e,t){const n=Qr(i.runner);pe(n,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:r,topics:a}=await wp(i,t),{addr:o,subs:c}=ni(i);let l=c.get(r);if(!l){const u={address:o||i,topics:a},d=g=>{let A=s;if(A==null)try{A=i.interface.getEvent(g.topics[0])}catch{}if(A){const _=A,x=s?i.interface.decodeEventLog(s,g.data,g.topics):[];Cp(i,t,x,E=>new CL(i,E,t,_,g))}else Cp(i,t,[],_=>new FE(i,_,t,g))};let f=[];l={tag:r,listeners:[],start:()=>{f.length||f.push(n.on(u,d))},stop:async()=>{if(f.length==0)return;let g=f;f=[],await Promise.all(g),n.off(u,d)}},c.set(r,l)}return l}let vp=Promise.resolve();async function NL(i,e,t,n){await vp;const s=await Ac(i,e);if(!s)return!1;const r=s.listeners.length;return s.listeners=s.listeners.filter(({listener:a,once:o})=>{const c=Array.from(t);n&&c.push(n(o?null:a));try{a.call(i,...c)}catch{}return!o}),s.listeners.length===0&&(s.stop(),ni(i).subs.delete(s.tag)),r>0}async function Cp(i,e,t,n){try{await vp}catch{}const s=NL(i,e,t,n);return vp=s,await s}const Fh=["then"];class gc{target;interface;runner;filters;[Rh];fallback;constructor(e,t,n,s){V(typeof e=="string"||bb(e),"invalid value for Contract target","target",e),n==null&&(n=null);const r=Ur.from(t);Ye(this,{target:e,runner:n,interface:r}),Object.defineProperty(this,Rh,{value:{}});let a,o=null,c=null;if(s){const u=Qr(n);c=new _p(this.interface,u,s)}let l=new Map;if(typeof e=="string")if(Pt(e))o=e,a=Promise.resolve(e);else{const u=Or(n,"resolveName");if(!Th(u))throw Qt("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});a=u.resolveName(e).then(d=>{if(d==null)throw Qt("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return ni(this).addr=d,d})}else a=e.getAddress().then(u=>{if(u==null)throw new Error("TODO");return ni(this).addr=u,u});RL(this,{addrPromise:a,addr:o,deployTx:c,subs:l});const h=new Proxy({},{get:(u,d,f)=>{if(typeof d=="symbol"||Fh.indexOf(d)>=0)return Reflect.get(u,d,f);try{return this.getEvent(d)}catch(p){if(!Tn(p,"INVALID_ARGUMENT")||p.argument!=="key")throw p}},has:(u,d)=>Fh.indexOf(d)>=0?Reflect.has(u,d):Reflect.has(u,d)||this.interface.hasEvent(String(d))});return Ye(this,{filters:h}),Ye(this,{fallback:r.receive||r.fallback?ML(this):null}),new Proxy(this,{get:(u,d,f)=>{if(typeof d=="symbol"||d in u||Fh.indexOf(d)>=0)return Reflect.get(u,d,f);try{return u.getFunction(d)}catch(p){if(!Tn(p,"INVALID_ARGUMENT")||p.argument!=="key")throw p}},has:(u,d)=>typeof d=="symbol"||d in u||Fh.indexOf(d)>=0?Reflect.has(u,d):u.interface.hasFunction(d)})}connect(e){return new gc(this.target,this.interface,e)}attach(e){return new gc(e,this.interface,this.runner)}async getAddress(){return await ni(this).addrPromise}async getDeployedCode(){const e=Qr(this.runner);pe(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return t==="0x"?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(await this.getDeployedCode()!=null)return this;const n=Qr(this.runner);return pe(n!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((s,r)=>{const a=async()=>{try{if(await this.getDeployedCode()!=null)return s(this);n.once("block",a)}catch(o){r(o)}};a()})}deploymentTransaction(){return ni(this).deployTx}getFunction(e){return typeof e!="string"&&(e=e.format()),BL(this,e)}getEvent(e){return typeof e!="string"&&(e=e.format()),TL(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){t==null&&(t=0),n==null&&(n="latest");const{addr:s,addrPromise:r}=ni(this),a=s||await r,{fragment:o,topics:c}=await wp(this,e),l={address:a,topics:c,fromBlock:t,toBlock:n},h=Qr(this.runner);return pe(h,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await h.getLogs(l)).map(u=>{let d=o;if(d==null)try{d=this.interface.getEvent(u.topics[0])}catch{}if(d)try{return new yp(u,this.interface,d)}catch(f){return new RE(u,f)}return new fc(u,h)})}async on(e,t){const n=await QE(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await QE(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await Cp(this,e,t,null)}async listenerCount(e){if(e){const s=await Ac(this,e);return s?s.listeners.length:0}const{subs:t}=ni(this);let n=0;for(const{listeners:s}of t.values())n+=s.length;return n}async listeners(e){if(e){const s=await Ac(this,e);return s?s.listeners.map(({listener:r})=>r):[]}const{subs:t}=ni(this);let n=[];for(const{listeners:s}of t.values())n=n.concat(s.map(({listener:r})=>r));return n}async off(e,t){const n=await Ac(this,e);if(!n)return this;if(t){const s=n.listeners.map(({listener:r})=>r).indexOf(t);s>=0&&n.listeners.splice(s,1)}return(t==null||n.listeners.length===0)&&(n.stop(),ni(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await Ac(this,e);if(!t)return this;t.stop(),ni(this).subs.delete(t.tag)}else{const{subs:t}=ni(this);for(const{tag:n,stop:s}of t.values())s(),t.delete(n)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){class t extends gc{constructor(s,r=null){super(s,e,r)}}return t}static from(e,t,n){return n==null&&(n=null),new this(e,t,n)}}function DL(){return gc}class Gr extends DL(){}function Ip(i){return i.match(/^ipfs:\/\/ipfs\//i)?i=i.substring(12):i.match(/^ipfs:\/\//i)?i=i.substring(7):V(!1,"unsupported IPFS format","link",i),`https://gateway.ipfs.io/ipfs/${i}`}class LL{name;constructor(e){Ye(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw new Error("unsupported coin")}async decodeAddress(e,t){throw new Error("unsupported coin")}}const GE=new RegExp("^(ipfs)://(.*)$","i"),HE=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),GE,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];class Ya{provider;address;name;#e;#t;constructor(e,t,n){Ye(this,{provider:e,address:t,name:n}),this.#e=null,this.#t=new Gr(t,["function supportsInterface(bytes4) view returns (bool)","function resolve(bytes, bytes) view returns (bytes)","function addr(bytes32) view returns (address)","function addr(bytes32, uint) view returns (bytes)","function text(bytes32, string) view returns (string)","function contenthash(bytes32) view returns (bytes)"],e)}async supportsWildcard(){return this.#e==null&&(this.#e=(async()=>{try{return await this.#t.supportsInterface("0x9061b923")}catch(e){if(Tn(e,"CALL_EXCEPTION"))return!1;throw this.#e=null,e}})()),await this.#e}async#n(e,t){t=(t||[]).slice();const n=this.#t.interface;t.unshift(mp(this.name));let s=null;await this.supportsWildcard()&&(s=n.getFunction(e),pe(s,"missing fragment","UNKNOWN_ERROR",{info:{funcName:e}}),t=[ZD(this.name,255),n.encodeFunctionData(s,t)],e="resolve(bytes,bytes)"),t.push({enableCcipRead:!0});try{const r=await this.#t[e](...t);return s?n.decodeFunctionResult(s,r)[0]:r}catch(r){if(!Tn(r,"CALL_EXCEPTION"))throw r}return null}async getAddress(e){if(e==null&&(e=60),e===60)try{const r=await this.#n("addr(bytes32)");return r==null||r===rc?null:r}catch(r){if(Tn(r,"CALL_EXCEPTION"))return null;throw r}if(e>=0&&e<2147483648){let r=e+2147483648;const a=await this.#n("addr(bytes32,uint)",[r]);if(Pt(a,20))return St(a)}let t=null;for(const r of this.provider.plugins)if(r instanceof LL&&r.supportsCoinType(e)){t=r;break}if(t==null)return null;const n=await this.#n("addr(bytes32,uint)",[e]);if(n==null||n==="0x")return null;const s=await t.decodeAddress(e,n);if(s!=null)return s;pe(!1,"invalid coin data","UNSUPPORTED_OPERATION",{operation:`getAddress(${e})`,info:{coinType:e,data:n}})}async getText(e){const t=await this.#n("text(bytes32,string)",[e]);return t==null||t==="0x"?null:t}async getContentHash(){const e=await this.#n("contenthash(bytes32)");if(e==null||e==="0x")return null;const t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){const s=t[1]==="e3010170"?"ipfs":"ipns",r=parseInt(t[4],16);if(t[5].length===r*2)return`${s}://${tF("0x"+t[2])}`}const n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&n[1].length===64)return`bzz://${n[1]}`;pe(!1,"invalid or unsupported content hash data","UNSUPPORTED_OPERATION",{operation:"getContentHash()",info:{data:e}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){const e=[{type:"name",value:this.name}];try{const t=await this.getText("avatar");if(t==null)return e.push({type:"!avatar",value:""}),{url:null,linkage:e};e.push({type:"avatar",value:t});for(let n=0;n<HE.length;n++){const s=t.match(HE[n]);if(s==null)continue;const r=s[1].toLowerCase();switch(r){case"https":case"data":return e.push({type:"url",value:t}),{linkage:e,url:t};case"ipfs":{const a=Ip(t);return e.push({type:"ipfs",value:t}),e.push({type:"url",value:a}),{linkage:e,url:a}}case"erc721":case"erc1155":{const a=r==="erc721"?"tokenURI(uint256)":"uri(uint256)";e.push({type:r,value:t});const o=await this.getAddress();if(o==null)return e.push({type:"!owner",value:""}),{url:null,linkage:e};const c=(s[2]||"").split("/");if(c.length!==2)return e.push({type:`!${r}caip`,value:s[2]||""}),{url:null,linkage:e};const l=c[1],h=new Gr(c[0],["function tokenURI(uint) view returns (string)","function ownerOf(uint) view returns (address)","function uri(uint) view returns (string)","function balanceOf(address, uint256) view returns (uint)"],this.provider);if(r==="erc721"){const m=await h.ownerOf(l);if(o!==m)return e.push({type:"!owner",value:m}),{url:null,linkage:e};e.push({type:"owner",value:m})}else if(r==="erc1155"){const m=await h.balanceOf(o,l);if(!m)return e.push({type:"!balance",value:"0"}),{url:null,linkage:e};e.push({type:"balance",value:m.toString()})}let u=await h[a](l);if(u==null||u==="0x")return e.push({type:"!metadata-url",value:""}),{url:null,linkage:e};e.push({type:"metadata-url-base",value:u}),r==="erc1155"&&(u=u.replace("{id}",Ks(l,32).substring(2)),e.push({type:"metadata-url-expanded",value:u})),u.match(/^ipfs:/i)&&(u=Ip(u)),e.push({type:"metadata-url",value:u});let d={};const f=await new zi(u).send();f.assertOk();try{d=f.bodyJson}catch{try{e.push({type:"!metadata",value:f.bodyText})}catch{const A=f.body;return A&&e.push({type:"!metadata",value:Ce(A)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!d)return e.push({type:"!metadata",value:""}),{url:null,linkage:e};e.push({type:"metadata",value:JSON.stringify(d)});let p=d.image;if(typeof p!="string")return e.push({type:"!imageUrl",value:""}),{url:null,linkage:e};if(!p.match(/^(https:\/\/|data:)/i)){if(p.match(GE)==null)return e.push({type:"!imageUrl-ipfs",value:p}),{url:null,linkage:e};e.push({type:"imageUrl-ipfs",value:p}),p=Ip(p)}return e.push({type:"url",value:p}),{linkage:e,url:p}}}}}catch{}return{linkage:e,url:null}}static async getEnsAddress(e){const t=await e.getNetwork(),n=t.getPlugin("org.ethers.plugins.network.Ens");return pe(n,"network does not support ENS","UNSUPPORTED_OPERATION",{operation:"getEnsAddress",info:{network:t}}),n.address}static async#i(e,t){const n=await Ya.getEnsAddress(e);try{const r=await new Gr(n,["function resolver(bytes32) view returns (address)"],e).resolver(mp(t),{enableCcipRead:!0});return r===rc?null:r}catch(s){throw s}return null}static async fromName(e,t){let n=t;for(;;){if(n===""||n==="."||t!=="eth"&&n==="eth")return null;const s=await Ya.#i(e,n);if(s!=null){const r=new Ya(e,s,t);return n!==t&&!await r.supportsWildcard()?null:r}n=n.split(".").slice(1).join(".")}}}const zE=BigInt(0);function bt(i,e){return(function(t){return t==null?e:i(t)})}function mc(i,e){return(t=>{if(e&&t==null)return null;if(!Array.isArray(t))throw new Error("not an array");return t.map(n=>i(n))})}function xc(i,e){return(t=>{const n={};for(const s in i){let r=s;if(e&&s in e&&!(r in t)){for(const a of e[s])if(a in t){r=a;break}}try{const a=i[s](t[r]);a!==void 0&&(n[s]=a)}catch(a){const o=a instanceof Error?a.message:"not-an-error";pe(!1,`invalid value for value.${s} (${o})`,"BAD_DATA",{value:t})}}return n})}function PL(i){switch(i){case!0:case"true":return!0;case!1:case"false":return!1}V(!1,`invalid boolean; ${JSON.stringify(i)}`,"value",i)}function Ja(i){return V(Pt(i,!0),"invalid data","value",i),i}function Rn(i){return V(Pt(i,32),"invalid hash","value",i),i}const kL=xc({address:St,blockHash:Rn,blockNumber:dt,data:Ja,index:dt,removed:bt(PL,!1),topics:mc(Rn),transactionHash:Rn,transactionIndex:dt},{index:["logIndex"]});function UL(i){return kL(i)}const OL=xc({hash:bt(Rn),parentHash:Rn,parentBeaconBlockRoot:bt(Rn,null),number:dt,timestamp:dt,nonce:bt(Ja),difficulty:Ne,gasLimit:Ne,gasUsed:Ne,stateRoot:bt(Rn,null),receiptsRoot:bt(Rn,null),blobGasUsed:bt(Ne,null),excessBlobGas:bt(Ne,null),miner:bt(St),prevRandao:bt(Rn,null),extraData:Ja,baseFeePerGas:bt(Ne)},{prevRandao:["mixHash"]});function QL(i){const e=OL(i);return e.transactions=i.transactions.map(t=>typeof t=="string"?t:VE(t)),e}const GL=xc({transactionIndex:dt,blockNumber:dt,transactionHash:Rn,address:St,topics:mc(Rn),data:Ja,index:dt,blockHash:Rn},{index:["logIndex"]});function HL(i){return GL(i)}const zL=xc({to:bt(St,null),from:bt(St,null),contractAddress:bt(St,null),index:dt,root:bt(Ce),gasUsed:Ne,blobGasUsed:bt(Ne,null),logsBloom:bt(Ja),blockHash:Rn,hash:Rn,logs:mc(HL),blockNumber:dt,cumulativeGasUsed:Ne,effectiveGasPrice:bt(Ne),blobGasPrice:bt(Ne,null),status:bt(dt),type:bt(dt,0)},{effectiveGasPrice:["gasPrice"],hash:["transactionHash"],index:["transactionIndex"]});function VL(i){return zL(i)}function VE(i){i.to&&Ne(i.to)===zE&&(i.to="0x0000000000000000000000000000000000000000");const e=xc({hash:Rn,index:bt(dt,void 0),type:t=>t==="0x"||t==null?0:dt(t),accessList:bt(Tr,null),blobVersionedHashes:bt(mc(Rn,!0),null),authorizationList:bt(mc(t=>{let n;if(t.signature)n=t.signature;else{let s=t.yParity;s==="0x1b"?s=0:s==="0x1c"&&(s=1),n=Object.assign({},t,{yParity:s})}return{address:St(t.address),chainId:Ne(t.chainId),nonce:Ne(t.nonce),signature:Vt.from(n)}},!1),null),blockHash:bt(Rn,null),blockNumber:bt(dt,null),transactionIndex:bt(dt,null),from:St,gasPrice:bt(Ne),maxPriorityFeePerGas:bt(Ne),maxFeePerGas:bt(Ne),maxFeePerBlobGas:bt(Ne,null),gasLimit:Ne,to:bt(St,null),value:Ne,nonce:dt,data:Ja,creates:bt(St,null),chainId:bt(Ne,null)},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(i);if(e.to==null&&e.creates==null&&(e.creates=NN(e)),(i.type===1||i.type===2)&&i.accessList==null&&(e.accessList=[]),i.signature?e.signature=Vt.from(i.signature):e.signature=Vt.from(i),e.chainId==null){const t=e.signature.legacyChainId;t!=null&&(e.chainId=t)}return e.blockHash&&Ne(e.blockHash)===zE&&(e.blockHash=null),e}const WL="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";class bc{name;constructor(e){Ye(this,{name:e})}clone(){return new bc(this.name)}}class Nh extends bc{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(e,t){e==null&&(e=0),super(`org.ethers.network.plugins.GasCost#${e||0}`);const n={effectiveBlock:e};function s(r,a){let o=(t||{})[r];o==null&&(o=a),V(typeof o=="number",`invalud value for ${r}`,"costs",t),n[r]=o}s("txBase",21e3),s("txCreate",32e3),s("txDataZero",4),s("txDataNonzero",16),s("txAccessListStorageKey",1900),s("txAccessListAddress",2400),Ye(this,n)}clone(){return new Nh(this.effectiveBlock,this)}}class Dh extends bc{address;targetNetwork;constructor(e,t){super("org.ethers.plugins.network.Ens"),Ye(this,{address:e||WL,targetNetwork:t??1})}clone(){return new Dh(this.address,this.targetNetwork)}}class qL extends bc{#e;#t;get url(){return this.#e}get processFunc(){return this.#t}constructor(e,t){super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"),this.#e=e,this.#t=t}clone(){return this}}const Sp=new Map;class ii{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=Ne(t),this.#n=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#e}set name(e){this.#e=e}get chainId(){return this.#t}set chainId(e){this.#t=Ne(e,"chainId")}matches(e){if(e==null)return!1;if(typeof e=="string"){try{return this.chainId===Ne(e)}catch{}return this.name===e}if(typeof e=="number"||typeof e=="bigint"){try{return this.chainId===Ne(e)}catch{}return!1}if(typeof e=="object"){if(e.chainId!=null){try{return this.chainId===Ne(e.chainId)}catch{}return!1}return e.name!=null?this.name===e.name:!1}return!1}get plugins(){return Array.from(this.#n.values())}attachPlugin(e){if(this.#n.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#n.set(e.name,e.clone()),this}getPlugin(e){return this.#n.get(e)||null}getPlugins(e){return this.plugins.filter(t=>t.name.split("#")[0]===e)}clone(){const e=new ii(this.name,this.chainId);return this.plugins.forEach(t=>{e.attachPlugin(t.clone())}),e}computeIntrinsicGas(e){const t=this.getPlugin("org.ethers.plugins.network.GasCost")||new Nh;let n=t.txBase;if(e.to==null&&(n+=t.txCreate),e.data)for(let s=2;s<e.data.length;s+=2)e.data.substring(s,s+2)==="00"?n+=t.txDataZero:n+=t.txDataNonzero;if(e.accessList){const s=Tr(e.accessList);for(const r in s)n+=t.txAccessListAddress+t.txAccessListStorageKey*s[r].storageKeys.length}return n}static from(e){if(KL(),e==null)return ii.from("mainnet");if(typeof e=="number"&&(e=BigInt(e)),typeof e=="string"||typeof e=="bigint"){const t=Sp.get(e);if(t)return t();if(typeof e=="bigint")return new ii("unknown",e);V(!1,"unknown network","network",e)}if(typeof e.clone=="function")return e.clone();if(typeof e=="object"){V(typeof e.name=="string"&&typeof e.chainId=="number","invalid network object name or chainId","network",e);const t=new ii(e.name,e.chainId);return(e.ensAddress||e.ensNetwork!=null)&&t.attachPlugin(new Dh(e.ensAddress,e.ensNetwork)),t}V(!1,"invalid network","network",e)}static register(e,t){typeof e=="number"&&(e=BigInt(e));const n=Sp.get(e);n&&V(!1,`conflicting network for ${JSON.stringify(n.name)}`,"nameOrChainId",e),Sp.set(e,t)}}function WE(i,e){const t=String(i);if(!t.match(/^[0-9.]+$/))throw new Error(`invalid gwei value: ${i}`);const n=t.split(".");if(n.length===1&&n.push(""),n.length!==2)throw new Error(`invalid gwei value: ${i}`);for(;n[1].length<e;)n[1]+="0";if(n[1].length>9){let s=BigInt(n[1].substring(0,9));n[1].substring(9).match(/^0+$/)||s++,n[1]=s.toString()}return BigInt(n[0]+n[1])}function qE(i){return new qL(i,async(e,t,n)=>{n.setHeader("User-Agent","ethers");let s;try{const[r,a]=await Promise.all([n.send(),e()]);s=r;const o=s.bodyJson.standard;return{gasPrice:a.gasPrice,maxFeePerGas:WE(o.maxFee,9),maxPriorityFeePerGas:WE(o.maxPriorityFee,9)}}catch(r){pe(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,"SERVER_ERROR",{request:n,response:s,error:r})}})}let KE=!1;function KL(){if(KE)return;KE=!0;function i(e,t,n){const s=function(){const r=new ii(e,t);return n.ensNetwork!=null&&r.attachPlugin(new Dh(null,n.ensNetwork)),r.attachPlugin(new Nh),(n.plugins||[]).forEach(a=>{r.attachPlugin(a)}),r};ii.register(e,s),ii.register(t,s),n.altNames&&n.altNames.forEach(r=>{ii.register(r,s)})}i("mainnet",1,{ensNetwork:1,altNames:["homestead"]}),i("ropsten",3,{ensNetwork:3}),i("rinkeby",4,{ensNetwork:4}),i("goerli",5,{ensNetwork:5}),i("kovan",42,{ensNetwork:42}),i("sepolia",11155111,{ensNetwork:11155111}),i("holesky",17e3,{ensNetwork:17e3}),i("classic",61,{}),i("classicKotti",6,{}),i("arbitrum",42161,{ensNetwork:1}),i("arbitrum-goerli",421613,{}),i("arbitrum-sepolia",421614,{}),i("base",8453,{ensNetwork:1}),i("base-goerli",84531,{}),i("base-sepolia",84532,{}),i("bnb",56,{ensNetwork:1}),i("bnbt",97,{}),i("filecoin",314,{}),i("filecoin-calibration",314159,{}),i("linea",59144,{ensNetwork:1}),i("linea-goerli",59140,{}),i("linea-sepolia",59141,{}),i("matic",137,{ensNetwork:1,plugins:[qE("https://gasstation.polygon.technology/v2")]}),i("matic-amoy",80002,{}),i("matic-mumbai",80001,{altNames:["maticMumbai","maticmum"],plugins:[qE("https://gasstation-testnet.polygon.technology/v2")]}),i("optimism",10,{ensNetwork:1,plugins:[]}),i("optimism-goerli",420,{}),i("optimism-sepolia",11155420,{}),i("xdai",100,{ensNetwork:1})}function Mp(i){return JSON.parse(JSON.stringify(i))}class jL{#e;#t;#n;#i;constructor(e){this.#e=e,this.#t=null,this.#n=4e3,this.#i=-2}get pollingInterval(){return this.#n}set pollingInterval(e){this.#n=e}async#s(){try{const e=await this.#e.getBlockNumber();if(this.#i===-2){this.#i=e;return}if(e!==this.#i){for(let t=this.#i+1;t<=e;t++){if(this.#t==null)return;await this.#e.emit("block",t)}this.#i=e}}catch{}this.#t!=null&&(this.#t=this.#e._setTimeout(this.#s.bind(this),this.#n))}start(){this.#t||(this.#t=this.#e._setTimeout(this.#s.bind(this),this.#n),this.#s())}stop(){this.#t&&(this.#e._clearTimeout(this.#t),this.#t=null)}pause(e){this.stop(),e&&(this.#i=-2)}resume(){this.start()}}class Bp{#e;#t;#n;constructor(e){this.#e=e,this.#n=!1,this.#t=t=>{this._poll(t,this.#e)}}async _poll(e,t){throw new Error("sub-classes must override this")}start(){this.#n||(this.#n=!0,this.#t(-2),this.#e.on("block",this.#t))}stop(){this.#n&&(this.#n=!1,this.#e.off("block",this.#t))}pause(e){this.stop()}resume(){this.start()}}class XL extends Bp{#e;#t;constructor(e,t){super(e),this.#e=t,this.#t=-2}pause(e){e&&(this.#t=-2),super.pause(e)}async _poll(e,t){const n=await t.getBlock(this.#e);n!=null&&(this.#t===-2?this.#t=n.number:n.number>this.#t&&(t.emit(this.#e,n.number),this.#t=n.number))}}class YL extends Bp{#e;constructor(e,t){super(e),this.#e=Mp(t)}async _poll(e,t){throw new Error("@TODO")}}class JL extends Bp{#e;constructor(e,t){super(e),this.#e=t}async _poll(e,t){const n=await t.getTransactionReceipt(this.#e);n&&t.emit(this.#e,n)}}class Tp{#e;#t;#n;#i;#s;constructor(e,t){this.#e=e,this.#t=Mp(t),this.#n=this.#a.bind(this),this.#i=!1,this.#s=-2}async#a(e){if(this.#s===-2)return;const t=Mp(this.#t);t.fromBlock=this.#s+1,t.toBlock=e;const n=await this.#e.getLogs(t);if(n.length===0){this.#s<e-60&&(this.#s=e-60);return}for(const s of n)this.#e.emit(this.#t,s),this.#s=s.blockNumber}start(){this.#i||(this.#i=!0,this.#s===-2&&this.#e.getBlockNumber().then(e=>{this.#s=e}),this.#e.on("block",this.#n))}stop(){this.#i&&(this.#i=!1,this.#e.off("block",this.#n))}pause(e){this.stop(),e&&(this.#s=-2)}resume(){this.start()}}const ZL=BigInt(2),$L=10;function Lh(i){return i&&typeof i.then=="function"}function Ph(i,e){return i+":"+JSON.stringify(e,(t,n)=>{if(n==null)return"null";if(typeof n=="bigint")return`bigint:${n.toString()}`;if(typeof n=="string")return n.toLowerCase();if(typeof n=="object"&&!Array.isArray(n)){const s=Object.keys(n);return s.sort(),s.reduce((r,a)=>(r[a]=n[a],r),{})}return n})}class jE{name;constructor(e){Ye(this,{name:e})}start(){}stop(){}pause(e){}resume(){}}function e2(i){return JSON.parse(JSON.stringify(i))}function Rp(i){return i=Array.from(new Set(i).values()),i.sort(),i}async function Fp(i,e){if(i==null)throw new Error("invalid event");if(Array.isArray(i)&&(i={topics:i}),typeof i=="string")switch(i){case"block":case"debug":case"error":case"finalized":case"network":case"pending":case"safe":return{type:i,tag:i}}if(Pt(i,32)){const t=i.toLowerCase();return{type:"transaction",tag:Ph("tx",{hash:t}),hash:t}}if(i.orphan){const t=i;return{type:"orphan",tag:Ph("orphan",t),filter:e2(t)}}if(i.address||i.topics){const t=i,n={topics:(t.topics||[]).map(s=>s==null?null:Array.isArray(s)?Rp(s.map(r=>r.toLowerCase())):s.toLowerCase())};if(t.address){const s=[],r=[],a=o=>{Pt(o)?s.push(o):r.push((async()=>{s.push(await Wn(o,e))})())};Array.isArray(t.address)?t.address.forEach(a):a(t.address),r.length&&await Promise.all(r),n.address=Rp(s.map(o=>o.toLowerCase()))}return{filter:n,tag:Ph("event",n),type:"event"}}V(!1,"unknown ProviderEvent","event",i)}function Np(){return new Date().getTime()}const t2={cacheTimeout:250,pollingInterval:4e3};class n2{#e;#t;#n;#i;#s;#a;#r;#o;#f;#l;#p;#A;constructor(e,t){if(this.#A=Object.assign({},t2,t||{}),e==="any")this.#a=!0,this.#s=null;else if(e){const n=ii.from(e);this.#a=!1,this.#s=Promise.resolve(n),setTimeout(()=>{this.emit("network",n,null)},0)}else this.#a=!1,this.#s=null;this.#o=-1,this.#r=new Map,this.#e=new Map,this.#t=new Map,this.#n=null,this.#i=!1,this.#f=1,this.#l=new Map,this.#p=!1}get pollingInterval(){return this.#A.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#t.values())}attachPlugin(e){if(this.#t.get(e.name))throw new Error(`cannot replace existing plugin: ${e.name} `);return this.#t.set(e.name,e.connect(this)),this}getPlugin(e){return this.#t.get(e)||null}get disableCcipRead(){return this.#p}set disableCcipRead(e){this.#p=!!e}async#c(e){const t=this.#A.cacheTimeout;if(t<0)return await this._perform(e);const n=Ph(e.method,e);let s=this.#r.get(n);return s||(s=this._perform(e),this.#r.set(n,s),setTimeout(()=>{this.#r.get(n)===s&&this.#r.delete(n)},t)),await s}async ccipReadFetch(e,t,n){if(this.disableCcipRead||n.length===0||e.to==null)return null;const s=e.to.toLowerCase(),r=t.toLowerCase(),a=[];for(let o=0;o<n.length;o++){const c=n[o],l=c.replace("{sender}",s).replace("{data}",r),h=new zi(l);c.indexOf("{data}")===-1&&(h.body={data:r,sender:s}),this.emit("debug",{action:"sendCcipReadFetchRequest",request:h,index:o,urls:n});let u="unknown error",d;try{d=await h.send()}catch(f){a.push(f.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:h,result:{error:f}});continue}try{const f=d.bodyJson;if(f.data)return this.emit("debug",{action:"receiveCcipReadFetchResult",request:h,result:f}),f.data;f.message&&(u=f.message),this.emit("debug",{action:"receiveCcipReadFetchError",request:h,result:f})}catch{}pe(d.statusCode<400||d.statusCode>=500,`response not found during CCIP fetch: ${u}`,"OFFCHAIN_FAULT",{reason:"404_MISSING_RESOURCE",transaction:e,info:{url:c,errorMessage:u}}),a.push(u)}pe(!1,`error encountered during CCIP fetch: ${a.map(o=>JSON.stringify(o)).join(", ")}`,"OFFCHAIN_FAULT",{reason:"500_SERVER_ERROR",transaction:e,info:{urls:n,errorMessages:a}})}_wrapBlock(e,t){return new yL(QL(e),this)}_wrapLog(e,t){return new fc(UL(e),this)}_wrapTransactionReceipt(e,t){return new ME(VL(e),this)}_wrapTransactionResponse(e,t){return new pc(VE(e),this)}_detectNetwork(){pe(!1,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(e){pe(!1,`unsupported method: ${e.method}`,"UNSUPPORTED_OPERATION",{operation:e.method,info:e})}async getBlockNumber(){const e=dt(await this.#c({method:"getBlockNumber"}),"%response");return this.#o>=0&&(this.#o=e),e}_getAddress(e){return Wn(e,this)}_getBlockTag(e){if(e==null)return"latest";switch(e){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return e}if(Pt(e))return Pt(e,32)?e:Ri(e);if(typeof e=="bigint"&&(e=dt(e,"blockTag")),typeof e=="number")return e>=0?Ri(e):this.#o>=0?Ri(this.#o+e):this.getBlockNumber().then(t=>Ri(t+e));V(!1,"invalid blockTag","blockTag",e)}_getFilter(e){const t=(e.topics||[]).map(c=>c==null?null:Array.isArray(c)?Rp(c.map(l=>l.toLowerCase())):c.toLowerCase()),n="blockHash"in e?e.blockHash:void 0,s=(c,l,h)=>{let u;switch(c.length){case 0:break;case 1:u=c[0];break;default:c.sort(),u=c}if(n&&(l!=null||h!=null))throw new Error("invalid filter");const d={};return u&&(d.address=u),t.length&&(d.topics=t),l&&(d.fromBlock=l),h&&(d.toBlock=h),n&&(d.blockHash=n),d};let r=[];if(e.address)if(Array.isArray(e.address))for(const c of e.address)r.push(this._getAddress(c));else r.push(this._getAddress(e.address));let a;"fromBlock"in e&&(a=this._getBlockTag(e.fromBlock));let o;return"toBlock"in e&&(o=this._getBlockTag(e.toBlock)),r.filter(c=>typeof c!="string").length||a!=null&&typeof a!="string"||o!=null&&typeof o!="string"?Promise.all([Promise.all(r),a,o]).then(c=>s(c[0],c[1],c[2])):s(r,a,o)}_getTransactionRequest(e){const t=Bh(e),n=[];if(["to","from"].forEach(s=>{if(t[s]==null)return;const r=Wn(t[s],this);Lh(r)?n.push((async function(){t[s]=await r})()):t[s]=r}),t.blockTag!=null){const s=this._getBlockTag(t.blockTag);Lh(s)?n.push((async function(){t.blockTag=await s})()):t.blockTag=s}return n.length?(async function(){return await Promise.all(n),t})():t}async getNetwork(){if(this.#s==null){const s=(async()=>{try{const r=await this._detectNetwork();return this.emit("network",r,null),r}catch(r){throw this.#s===s&&(this.#s=null),r}})();return this.#s=s,(await s).clone()}const e=this.#s,[t,n]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==n.chainId&&(this.#a?(this.emit("network",n,t),this.#s===e&&(this.#s=Promise.resolve(n))):pe(!1,`network changed: ${t.chainId} => ${n.chainId} `,"NETWORK_ERROR",{event:"changed"})),t.clone()}async getFeeData(){const e=await this.getNetwork(),t=async()=>{const{_block:s,gasPrice:r,priorityFee:a}=await Hn({_block:this.#x("latest",!1),gasPrice:(async()=>{try{const h=await this.#c({method:"getGasPrice"});return Ne(h,"%response")}catch{}return null})(),priorityFee:(async()=>{try{const h=await this.#c({method:"getPriorityFee"});return Ne(h,"%response")}catch{}return null})()});let o=null,c=null;const l=this._wrapBlock(s,e);return l&&l.baseFeePerGas&&(c=a??BigInt("1000000000"),o=l.baseFeePerGas*ZL+c),new SE(r,o,c)},n=e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");if(n){const s=new zi(n.url),r=await n.processFunc(t,this,s);return new SE(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return Lh(t)&&(t=await t),Ne(await this.#c({method:"estimateGas",transaction:t}),"%response")}async#h(e,t,n){pe(n<$L,"CCIP read exceeded maximum redirections","OFFCHAIN_FAULT",{reason:"TOO_MANY_REDIRECTS",transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});const s=Bh(e);try{return Ce(await this._perform({method:"call",transaction:s,blockTag:t}))}catch(r){if(!this.disableCcipRead&&Rf(r)&&r.data&&n>=0&&t==="latest"&&s.to!=null&&Kt(r.data,0,4)==="0x556f1830"){const a=r.data,o=await Wn(s.to,this);let c;try{c=o2(Kt(r.data,4))}catch(u){pe(!1,u.message,"OFFCHAIN_FAULT",{reason:"BAD_DATA",transaction:s,info:{data:a}})}pe(c.sender.toLowerCase()===o.toLowerCase(),"CCIP Read sender mismatch","CALL_EXCEPTION",{action:"call",data:a,reason:"OffchainLookup",transaction:s,invocation:null,revert:{signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",name:"OffchainLookup",args:c.errorArgs}});const l=await this.ccipReadFetch(s,c.calldata,c.urls);pe(l!=null,"CCIP Read failed to fetch data","OFFCHAIN_FAULT",{reason:"FETCH_FAILED",transaction:s,info:{data:r.data,errorArgs:c.errorArgs}});const h={to:o,data:Gt([c.selector,a2([l,c.extraData])])};this.emit("debug",{action:"sendCcipReadCall",transaction:h});try{const u=await this.#h(h,t,n+1);return this.emit("debug",{action:"receiveCcipReadCallResult",transaction:Object.assign({},h),result:u}),u}catch(u){throw this.emit("debug",{action:"receiveCcipReadCallError",transaction:Object.assign({},h),error:u}),u}}throw r}}async#u(e){const{value:t}=await Hn({network:this.getNetwork(),value:e});return t}async call(e){const{tx:t,blockTag:n}=await Hn({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await this.#u(this.#h(t,n,e.enableCcipRead?0:-1))}async#d(e,t,n){let s=this._getAddress(t),r=this._getBlockTag(n);return(typeof s!="string"||typeof r!="string")&&([s,r]=await Promise.all([s,r])),await this.#u(this.#c(Object.assign(e,{address:s,blockTag:r})))}async getBalance(e,t){return Ne(await this.#d({method:"getBalance"},e,t),"%response")}async getTransactionCount(e,t){return dt(await this.#d({method:"getTransactionCount"},e,t),"%response")}async getCode(e,t){return Ce(await this.#d({method:"getCode"},e,t))}async getStorage(e,t,n){const s=Ne(t,"position");return Ce(await this.#d({method:"getStorage",position:s},e,n))}async broadcastTransaction(e){const{blockNumber:t,hash:n,network:s}=await Hn({blockNumber:this.getBlockNumber(),hash:this._perform({method:"broadcastTransaction",signedTransaction:e}),network:this.getNetwork()}),r=Ni.from(e);if(r.hash!==n)throw new Error("@TODO: the returned hash did not match");return this._wrapTransactionResponse(r,s).replaceableTransaction(t)}async#x(e,t){if(Pt(e,32))return await this.#c({method:"getBlock",blockHash:e,includeTransactions:t});let n=this._getBlockTag(e);return typeof n!="string"&&(n=await n),await this.#c({method:"getBlock",blockTag:n,includeTransactions:t})}async getBlock(e,t){const{network:n,params:s}=await Hn({network:this.getNetwork(),params:this.#x(e,!!t)});return s==null?null:this._wrapBlock(s,n)}async getTransaction(e){const{network:t,params:n}=await Hn({network:this.getNetwork(),params:this.#c({method:"getTransaction",hash:e})});return n==null?null:this._wrapTransactionResponse(n,t)}async getTransactionReceipt(e){const{network:t,params:n}=await Hn({network:this.getNetwork(),params:this.#c({method:"getTransactionReceipt",hash:e})});if(n==null)return null;if(n.gasPrice==null&&n.effectiveGasPrice==null){const s=await this.#c({method:"getTransaction",hash:e});if(s==null)throw new Error("report this; could not find tx or effectiveGasPrice");n.effectiveGasPrice=s.gasPrice}return this._wrapTransactionReceipt(n,t)}async getTransactionResult(e){const{result:t}=await Hn({network:this.getNetwork(),result:this.#c({method:"getTransactionResult",hash:e})});return t==null?null:Ce(t)}async getLogs(e){let t=this._getFilter(e);Lh(t)&&(t=await t);const{network:n,params:s}=await Hn({network:this.getNetwork(),params:this.#c({method:"getLogs",filter:t})});return s.map(r=>this._wrapLog(r,n))}_getProvider(e){pe(!1,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async getResolver(e){return await Ya.fromName(this,e)}async getAvatar(e){const t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e){const t=await this.getResolver(e);return t?await t.getAddress():null}async lookupAddress(e){e=St(e);const t=mp(e.substring(2).toLowerCase()+".addr.reverse");try{const n=await Ya.getEnsAddress(this),r=await new Gr(n,["function resolver(bytes32) view returns (address)"],this).resolver(t);if(r==null||r===rc)return null;const o=await new Gr(r,["function name(bytes32) view returns (string)"],this).name(t);return await this.resolveName(o)!==e?null:o}catch(n){if(Tn(n,"BAD_DATA")&&n.value==="0x"||Tn(n,"CALL_EXCEPTION"))return null;throw n}return null}async waitForTransaction(e,t,n){const s=t??1;return s===0?this.getTransactionReceipt(e):new Promise(async(r,a)=>{let o=null;const c=(async l=>{try{const h=await this.getTransactionReceipt(e);if(h!=null&&l-h.blockNumber+1>=s){r(h),o&&(clearTimeout(o),o=null);return}}catch(h){console.log("EEE",h)}this.once("block",c)});n!=null&&(o=setTimeout(()=>{o!=null&&(o=null,this.off("block",c),a(Qt("timeout","TIMEOUT",{reason:"timeout"})))},n)),c(await this.getBlockNumber())})}async waitForBlock(e){pe(!1,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(e){const t=this.#l.get(e);t&&(t.timer&&clearTimeout(t.timer),this.#l.delete(e))}_setTimeout(e,t){t==null&&(t=0);const n=this.#f++,s=()=>{this.#l.delete(n),e()};if(this.paused)this.#l.set(n,{timer:null,func:s,time:t});else{const r=setTimeout(s,t);this.#l.set(n,{timer:r,func:s,time:Np()})}return n}_forEachSubscriber(e){for(const t of this.#e.values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case"debug":case"error":case"network":return new jE(e.type);case"block":{const t=new jL(this);return t.pollingInterval=this.pollingInterval,t}case"safe":case"finalized":return new XL(this,e.type);case"event":return new Tp(this,e.filter);case"transaction":return new JL(this,e.hash);case"orphan":return new YL(this,e.filter)}throw new Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(const n of this.#e.values())if(n.subscriber===e){n.started&&n.subscriber.stop(),n.subscriber=t,n.started&&t.start(),this.#n!=null&&t.pause(this.#n);break}}async#g(e,t){let n=await Fp(e,this);return n.type==="event"&&t&&t.length>0&&t[0].removed===!0&&(n=await Fp({orphan:"drop-log",log:t[0]},this)),this.#e.get(n.tag)||null}async#m(e){const t=await Fp(e,this),n=t.tag;let s=this.#e.get(n);return s||(s={subscriber:this._getSubscriber(t),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#e.set(n,s)),s}async on(e,t){const n=await this.#m(e);return n.listeners.push({listener:t,once:!1}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async once(e,t){const n=await this.#m(e);return n.listeners.push({listener:t,once:!0}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async emit(e,...t){const n=await this.#g(e,t);if(!n||n.listeners.length===0)return!1;const s=n.listeners.length;return n.listeners=n.listeners.filter(({listener:r,once:a})=>{const o=new dx(this,a?null:r,e);try{r.call(this,...t,o)}catch{}return!a}),n.listeners.length===0&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),s>0}async listenerCount(e){if(e){const n=await this.#g(e);return n?n.listeners.length:0}let t=0;for(const{listeners:n}of this.#e.values())t+=n.length;return t}async listeners(e){if(e){const n=await this.#g(e);return n?n.listeners.map(({listener:s})=>s):[]}let t=[];for(const{listeners:n}of this.#e.values())t=t.concat(n.map(({listener:s})=>s));return t}async off(e,t){const n=await this.#g(e);if(!n)return this;if(t){const s=n.listeners.map(({listener:r})=>r).indexOf(t);s>=0&&n.listeners.splice(s,1)}return(!t||n.listeners.length===0)&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),this}async removeAllListeners(e){if(e){const{tag:t,started:n,subscriber:s}=await this.#m(e);n&&s.stop(),this.#e.delete(t)}else for(const[t,{started:n,subscriber:s}]of this.#e)n&&s.stop(),this.#e.delete(t);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return this.#i}destroy(){this.removeAllListeners();for(const e of this.#l.keys())this._clearTimeout(e);this.#i=!0}get paused(){return this.#n!=null}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(this.#o=-1,this.#n!=null){if(this.#n==!!e)return;pe(!1,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(t=>t.pause(e)),this.#n=!!e;for(const t of this.#l.values())t.timer&&clearTimeout(t.timer),t.time=Np()-t.time}resume(){if(this.#n!=null){this._forEachSubscriber(e=>e.resume()),this.#n=null;for(const e of this.#l.values()){let t=e.time;t<0&&(t=0),e.time=Np(),setTimeout(e.func,t)}}}}function i2(i,e){try{const t=Dp(i,e);if(t)return rh(t)}catch{}return null}function Dp(i,e){if(i==="0x")return null;try{const t=dt(Kt(i,e,e+32)),n=dt(Kt(i,t,t+32));return Kt(i,t+32,t+32+n)}catch{}return null}function XE(i){const e=rn(i);if(e.length>32)throw new Error("internal; should not happen");const t=new Uint8Array(32);return t.set(e,32-e.length),t}function s2(i){if(i.length%32===0)return i;const e=new Uint8Array(Math.ceil(i.length/32)*32);return e.set(i),e}const r2=new Uint8Array([]);function a2(i){const e=[];let t=0;for(let n=0;n<i.length;n++)e.push(r2),t+=32;for(let n=0;n<i.length;n++){const s=ut(i[n]);e[n]=XE(t),e.push(XE(s.length)),e.push(s2(s)),t+=32+Math.ceil(s.length/32)*32}return Gt(e)}const YE="0x0000000000000000000000000000000000000000000000000000000000000000";function o2(i){const e={sender:"",urls:[],calldata:"",selector:"",extraData:"",errorArgs:[]};pe(ka(i)>=160,"insufficient OffchainLookup data","OFFCHAIN_FAULT",{reason:"insufficient OffchainLookup data"});const t=Kt(i,0,32);pe(Kt(t,0,12)===Kt(YE,0,12),"corrupt OffchainLookup sender","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup sender"}),e.sender=Kt(t,12);try{const n=[],s=dt(Kt(i,32,64)),r=dt(Kt(i,s,s+32)),a=Kt(i,s+32);for(let o=0;o<r;o++){const c=i2(a,o*32);if(c==null)throw new Error("abort");n.push(c)}e.urls=n}catch{pe(!1,"corrupt OffchainLookup urls","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup urls"})}try{const n=Dp(i,64);if(n==null)throw new Error("abort");e.calldata=n}catch{pe(!1,"corrupt OffchainLookup calldata","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup calldata"})}pe(Kt(i,100,128)===Kt(YE,0,28),"corrupt OffchainLookup callbaackSelector","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup callbaackSelector"}),e.selector=Kt(i,96,100);try{const n=Dp(i,128);if(n==null)throw new Error("abort");e.extraData=n}catch{pe(!1,"corrupt OffchainLookup extraData","OFFCHAIN_FAULT",{reason:"corrupt OffchainLookup extraData"})}return e.errorArgs="sender,urls,calldata,selector,extraData".split(/,/).map(n=>e[n]),e}function Hr(i,e){if(i.provider)return i.provider;pe(!1,"missing provider","UNSUPPORTED_OPERATION",{operation:e})}async function JE(i,e){let t=Bh(e);if(t.to!=null&&(t.to=Wn(t.to,i)),t.from!=null){const n=t.from;t.from=Promise.all([i.getAddress(),Wn(n,i)]).then(([s,r])=>(V(s.toLowerCase()===r.toLowerCase(),"transaction from mismatch","tx.from",r),s))}else t.from=i.getAddress();return await Hn(t)}class c2{provider;constructor(e){Ye(this,{provider:e||null})}async getNonce(e){return Hr(this,"getTransactionCount").getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await JE(this,e)}async populateTransaction(e){const t=Hr(this,"populateTransaction"),n=await JE(this,e);n.nonce==null&&(n.nonce=await this.getNonce("pending")),n.gasLimit==null&&(n.gasLimit=await this.estimateGas(n));const s=await this.provider.getNetwork();if(n.chainId!=null){const a=Ne(n.chainId);V(a===s.chainId,"transaction chainId mismatch","tx.chainId",e.chainId)}else n.chainId=s.chainId;const r=n.maxFeePerGas!=null||n.maxPriorityFeePerGas!=null;if(n.gasPrice!=null&&(n.type===2||r)?V(!1,"eip-1559 transaction do not support gasPrice","tx",e):(n.type===0||n.type===1)&&r&&V(!1,"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","tx",e),(n.type===2||n.type==null)&&n.maxFeePerGas!=null&&n.maxPriorityFeePerGas!=null)n.type=2;else if(n.type===0||n.type===1){const a=await t.getFeeData();pe(a.gasPrice!=null,"network does not support gasPrice","UNSUPPORTED_OPERATION",{operation:"getGasPrice"}),n.gasPrice==null&&(n.gasPrice=a.gasPrice)}else{const a=await t.getFeeData();if(n.type==null)if(a.maxFeePerGas!=null&&a.maxPriorityFeePerGas!=null)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,n.gasPrice!=null){const o=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=o,n.maxPriorityFeePerGas=o}else n.maxFeePerGas==null&&(n.maxFeePerGas=a.maxFeePerGas),n.maxPriorityFeePerGas==null&&(n.maxPriorityFeePerGas=a.maxPriorityFeePerGas);else a.gasPrice!=null?(pe(!r,"network does not support EIP-1559","UNSUPPORTED_OPERATION",{operation:"populateTransaction"}),n.gasPrice==null&&(n.gasPrice=a.gasPrice),n.type=0):pe(!1,"failed to get consistent fee data","UNSUPPORTED_OPERATION",{operation:"signer.getFeeData"});else(n.type===2||n.type===3||n.type===4)&&(n.maxFeePerGas==null&&(n.maxFeePerGas=a.maxFeePerGas),n.maxPriorityFeePerGas==null&&(n.maxPriorityFeePerGas=a.maxPriorityFeePerGas))}return await Hn(n)}async populateAuthorization(e){const t=Object.assign({},e);return t.chainId==null&&(t.chainId=(await Hr(this,"getNetwork").getNetwork()).chainId),t.nonce==null&&(t.nonce=await this.getNonce()),t}async estimateGas(e){return Hr(this,"estimateGas").estimateGas(await this.populateCall(e))}async call(e){return Hr(this,"call").call(await this.populateCall(e))}async resolveName(e){return await Hr(this,"resolveName").resolveName(e)}async sendTransaction(e){const t=Hr(this,"sendTransaction"),n=await this.populateTransaction(e);delete n.from;const s=Ni.from(n);return await t.broadcastTransaction(await this.signTransaction(s))}authorize(e){pe(!1,"authorization not implemented for this signer","UNSUPPORTED_OPERATION",{operation:"authorize"})}}function l2(i){return JSON.parse(JSON.stringify(i))}class ZE{#e;#t;#n;#i;#s;#a;constructor(e){this.#e=e,this.#t=null,this.#n=this.#r.bind(this),this.#i=!1,this.#s=null,this.#a=!1}_subscribe(e){throw new Error("subclasses must override this")}_emitResults(e,t){throw new Error("subclasses must override this")}_recover(e){throw new Error("subclasses must override this")}async#r(e){try{this.#t==null&&(this.#t=this._subscribe(this.#e));let t=null;try{t=await this.#t}catch(r){if(!Tn(r,"UNSUPPORTED_OPERATION")||r.operation!=="eth_newFilter")throw r}if(t==null){this.#t=null,this.#e._recoverSubscriber(this,this._recover(this.#e));return}const n=await this.#e.getNetwork();if(this.#s||(this.#s=n),this.#s.chainId!==n.chainId)throw new Error("chaid changed");if(this.#a)return;const s=await this.#e.send("eth_getFilterChanges",[t]);await this._emitResults(this.#e,s)}catch(t){console.log("@TODO",t)}this.#e.once("block",this.#n)}#o(){const e=this.#t;e&&(this.#t=null,e.then(t=>{this.#e.destroyed||this.#e.send("eth_uninstallFilter",[t])}))}start(){this.#i||(this.#i=!0,this.#r(-2))}stop(){this.#i&&(this.#i=!1,this.#a=!0,this.#o(),this.#e.off("block",this.#n))}pause(e){e&&this.#o(),this.#e.off("block",this.#n)}resume(){this.start()}}class h2 extends ZE{#e;constructor(e,t){super(e),this.#e=l2(t)}_recover(e){return new Tp(e,this.#e)}async _subscribe(e){return await e.send("eth_newFilter",[this.#e])}async _emitResults(e,t){for(const n of t)e.emit(this.#e,e._wrapLog(n,e._network))}}class u2 extends ZE{async _subscribe(e){return await e.send("eth_newPendingTransactionFilter",[])}async _emitResults(e,t){for(const n of t)e.emit("pending",n)}}const d2="bigint,boolean,function,number,string,symbol".split(/,/g);function kh(i){if(i==null||d2.indexOf(typeof i)>=0||typeof i.getAddress=="function")return i;if(Array.isArray(i))return i.map(kh);if(typeof i=="object")return Object.keys(i).reduce((e,t)=>(e[t]=i[t],e),{});throw new Error(`should not happen: ${i} (${typeof i})`)}function f2(i){return new Promise(e=>{setTimeout(e,i)})}function Za(i){return i&&i.toLowerCase()}function $E(i){return i&&typeof i.pollingInterval=="number"}const ey={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3};class Lp extends c2{address;constructor(e,t){super(e),t=St(t),Ye(this,{address:t})}connect(e){pe(!1,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){const t=kh(e),n=[];if(t.from){const r=t.from;n.push((async()=>{const a=await Wn(r,this.provider);V(a!=null&&a.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=a})())}else t.from=this.address;if(t.gasLimit==null&&n.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),t.to!=null){const r=t.to;n.push((async()=>{t.to=await Wn(r,this.provider)})())}n.length&&await Promise.all(n);const s=this.provider.getRpcTransaction(t);return this.provider.send("eth_sendTransaction",[s])}async sendTransaction(e){const t=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(e);return await new Promise((s,r)=>{const a=[1e3,100];let o=0;const c=async()=>{try{const l=await this.provider.getTransaction(n);if(l!=null){s(l.replaceableTransaction(t));return}}catch(l){if(Tn(l,"CANCELLED")||Tn(l,"BAD_DATA")||Tn(l,"NETWORK_ERROR")||Tn(l,"UNSUPPORTED_OPERATION")){l.info==null&&(l.info={}),l.info.sendTransactionHash=n,r(l);return}if(Tn(l,"INVALID_ARGUMENT")&&(o++,l.info==null&&(l.info={}),l.info.sendTransactionHash=n,o>10)){r(l);return}this.provider.emit("error",Qt("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:l}))}this.provider._setTimeout(()=>{c()},a.pop()||4e3)};c()})}async signTransaction(e){const t=kh(e);if(t.from){const s=await Wn(t.from,this.provider);V(s!=null&&s.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",e),t.from=s}else t.from=this.address;const n=this.provider.getRpcTransaction(t);return await this.provider.send("eth_signTransaction",[n])}async signMessage(e){const t=typeof e=="string"?ds(e):e;return await this.provider.send("personal_sign",[Ce(t),this.address.toLowerCase()])}async signTypedData(e,t,n){const s=kh(n),r=await ti.resolveNames(e,t,s,async a=>{const o=await Wn(a);return V(o!=null,"TypedData does not support null address","value",a),o});return await this.provider.send("eth_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(ti.getPayload(r.domain,t,r.value))])}async unlock(e){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){const t=typeof e=="string"?ds(e):e;return await this.provider.send("eth_sign",[this.address.toLowerCase(),Ce(t)])}}class p2 extends n2{#e;#t;#n;#i;#s;#a;#r;#o(){if(this.#i)return;const e=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#i=setTimeout(()=>{this.#i=null;const t=this.#n;for(this.#n=[];t.length;){const n=[t.shift()];for(;t.length&&n.length!==this.#e.batchMaxCount;)if(n.push(t.shift()),JSON.stringify(n.map(r=>r.payload)).length>this.#e.batchMaxSize){t.unshift(n.pop());break}(async()=>{const s=n.length===1?n[0].payload:n.map(r=>r.payload);this.emit("debug",{action:"sendRpcPayload",payload:s});try{const r=await this._send(s);this.emit("debug",{action:"receiveRpcResult",result:r});for(const{resolve:a,reject:o,payload:c}of n){if(this.destroyed){o(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:c.method}));continue}const l=r.filter(h=>h.id===c.id)[0];if(l==null){const h=Qt("missing response for request","BAD_DATA",{value:r,info:{payload:c}});this.emit("error",h),o(h);continue}if("error"in l){o(this.getRpcError(c,l));continue}a(l.result)}}catch(r){this.emit("debug",{action:"receiveRpcError",error:r});for(const{reject:a}of n)a(r)}})()}},e)}constructor(e,t){super(e,t),this.#t=1,this.#e=Object.assign({},ey,t||{}),this.#n=[],this.#i=null,this.#a=null,this.#r=null;{let s=null;const r=new Promise(a=>{s=a});this.#s={promise:r,resolve:s}}const n=this._getOption("staticNetwork");typeof n=="boolean"?(V(!n||e!=="any","staticNetwork cannot be used on special network 'any'","options",t),n&&e!=null&&(this.#a=ii.from(e))):n&&(V(e==null||n.matches(e),"staticNetwork MUST match network object","options",t),this.#a=n)}_getOption(e){return this.#e[e]}get _network(){return pe(this.#a,"network is not available yet","NETWORK_ERROR"),this.#a}async _perform(e){if(e.method==="call"||e.method==="estimateGas"){let n=e.transaction;if(n&&n.type!=null&&Ne(n.type)&&n.maxFeePerGas==null&&n.maxPriorityFeePerGas==null){const s=await this.getFeeData();s.maxFeePerGas==null&&s.maxPriorityFeePerGas==null&&(e=Object.assign({},e,{transaction:Object.assign({},n,{type:void 0})}))}}const t=this.getRpcRequest(e);return t!=null?await this.send(t.method,t.args):super._perform(e)}async _detectNetwork(){const e=this._getOption("staticNetwork");if(e)if(e===!0){if(this.#a)return this.#a}else return e;return this.#r?await this.#r:this.ready?(this.#r=(async()=>{try{const t=ii.from(Ne(await this.send("eth_chainId",[])));return this.#r=null,t}catch(t){throw this.#r=null,t}})(),await this.#r):(this.#r=(async()=>{const t={id:this.#t++,method:"eth_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",{action:"sendRpcPayload",payload:t});let n;try{n=(await this._send(t))[0],this.#r=null}catch(s){throw this.#r=null,this.emit("debug",{action:"receiveRpcError",error:s}),s}if(this.emit("debug",{action:"receiveRpcResult",result:n}),"result"in n)return ii.from(Ne(n.result));throw this.getRpcError(t,n)})(),await this.#r)}_start(){this.#s==null||this.#s.resolve==null||(this.#s.resolve(),this.#s=null,(async()=>{for(;this.#a==null&&!this.destroyed;)try{this.#a=await this._detectNetwork()}catch(e){if(this.destroyed)break;console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"),this.emit("error",Qt("failed to bootstrap network detection","NETWORK_ERROR",{event:"initial-network-discovery",info:{error:e}})),await f2(1e3)}this.#o()})())}async _waitUntilReady(){if(this.#s!=null)return await this.#s.promise}_getSubscriber(e){return e.type==="pending"?new u2(this):e.type==="event"?this._getOption("polling")?new Tp(this,e.filter):new h2(this,e.filter):e.type==="orphan"&&e.filter.orphan==="drop-log"?new jE("orphan"):super._getSubscriber(e)}get ready(){return this.#s==null}getRpcTransaction(e){const t={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(n=>{if(e[n]==null)return;let s=n;n==="gasLimit"&&(s="gas"),t[s]=Ri(Ne(e[n],`tx.${n}`))}),["from","to","data"].forEach(n=>{e[n]!=null&&(t[n]=Ce(e[n]))}),e.accessList&&(t.accessList=Tr(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map(n=>n.toLowerCase())),e.authorizationList&&(t.authorizationList=e.authorizationList.map(n=>{const s=vb(n);return{address:s.address,nonce:Ri(s.nonce),chainId:Ri(s.chainId),yParity:Ri(s.signature.yParity),r:Ri(s.signature.r),s:Ri(s.signature.s)}})),t}getRpcRequest(e){switch(e.method){case"chainId":return{method:"eth_chainId",args:[]};case"getBlockNumber":return{method:"eth_blockNumber",args:[]};case"getGasPrice":return{method:"eth_gasPrice",args:[]};case"getPriorityFee":return{method:"eth_maxPriorityFeePerGas",args:[]};case"getBalance":return{method:"eth_getBalance",args:[Za(e.address),e.blockTag]};case"getTransactionCount":return{method:"eth_getTransactionCount",args:[Za(e.address),e.blockTag]};case"getCode":return{method:"eth_getCode",args:[Za(e.address),e.blockTag]};case"getStorage":return{method:"eth_getStorageAt",args:[Za(e.address),"0x"+e.position.toString(16),e.blockTag]};case"broadcastTransaction":return{method:"eth_sendRawTransaction",args:[e.signedTransaction]};case"getBlock":if("blockTag"in e)return{method:"eth_getBlockByNumber",args:[e.blockTag,!!e.includeTransactions]};if("blockHash"in e)return{method:"eth_getBlockByHash",args:[e.blockHash,!!e.includeTransactions]};break;case"getTransaction":return{method:"eth_getTransactionByHash",args:[e.hash]};case"getTransactionReceipt":return{method:"eth_getTransactionReceipt",args:[e.hash]};case"call":return{method:"eth_call",args:[this.getRpcTransaction(e.transaction),e.blockTag]};case"estimateGas":return{method:"eth_estimateGas",args:[this.getRpcTransaction(e.transaction)]};case"getLogs":return e.filter&&e.filter.address!=null&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(Za):e.filter.address=Za(e.filter.address)),{method:"eth_getLogs",args:[e.filter]}}return null}getRpcError(e,t){const{method:n}=e,{error:s}=t;if(n==="eth_estimateGas"&&s.message){const o=s.message;if(!o.match(/revert/i)&&o.match(/insufficient funds/i))return Qt("insufficient funds","INSUFFICIENT_FUNDS",{transaction:e.params[0],info:{payload:e,error:s}});if(o.match(/nonce/i)&&o.match(/too low/i))return Qt("nonce has already been used","NONCE_EXPIRED",{transaction:e.params[0],info:{payload:e,error:s}})}if(n==="eth_call"||n==="eth_estimateGas"){const o=Pp(s),c=ja.getBuiltinCallException(n==="eth_call"?"call":"estimateGas",e.params[0],o?o.data:null);return c.info={error:s,payload:e},c}const r=JSON.stringify(A2(s));if(typeof s.message=="string"&&s.message.match(/user denied|ethers-user-denied/i))return Qt("user rejected action","ACTION_REJECTED",{action:{eth_sign:"signMessage",personal_sign:"signMessage",eth_signTypedData_v4:"signTypedData",eth_signTransaction:"signTransaction",eth_sendTransaction:"sendTransaction",eth_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"}[n]||"unknown",reason:"rejected",info:{payload:e,error:s}});if(n==="eth_sendRawTransaction"||n==="eth_sendTransaction"){const o=e.params[0];if(r.match(/insufficient funds|base fee exceeds gas limit/i))return Qt("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:o,info:{error:s}});if(r.match(/nonce/i)&&r.match(/too low/i))return Qt("nonce has already been used","NONCE_EXPIRED",{transaction:o,info:{error:s}});if(r.match(/replacement transaction/i)&&r.match(/underpriced/i))return Qt("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:o,info:{error:s}});if(r.match(/only replay-protected/i))return Qt("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:n,info:{transaction:o,info:{error:s}}})}let a=!!r.match(/the method .* does not exist/i);return a||s&&s.details&&s.details.startsWith("Unauthorized method:")&&(a=!0),a?Qt("unsupported operation","UNSUPPORTED_OPERATION",{operation:e.method,info:{error:s,payload:e}}):Qt("could not coalesce error","UNKNOWN_ERROR",{error:s,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e}));const n=this.#t++,s=new Promise((r,a)=>{this.#n.push({resolve:r,reject:a,payload:{method:e,params:t,id:n,jsonrpc:"2.0"}})});return this.#o(),s}async getSigner(e){e==null&&(e=0);const t=this.send("eth_accounts",[]);if(typeof e=="number"){const s=await t;if(e>=s.length)throw new Error("no such account");return new Lp(this,s[e])}const{accounts:n}=await Hn({network:this.getNetwork(),accounts:t});e=St(e);for(const s of n)if(St(s)===e)return new Lp(this,e);throw new Error("invalid account")}async listAccounts(){return(await this.send("eth_accounts",[])).map(t=>new Lp(this,t))}destroy(){this.#i&&(clearTimeout(this.#i),this.#i=null);for(const{payload:e,reject:t}of this.#n)t(Qt("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:e.method}));this.#n=[],super.destroy()}}class ty extends p2{#e;constructor(e,t){super(e,t);let n=this._getOption("pollingInterval");n==null&&(n=ey.pollingInterval),this.#e=n}_getSubscriber(e){const t=super._getSubscriber(e);return $E(t)&&(t.pollingInterval=this.#e),t}get pollingInterval(){return this.#e}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw new Error("invalid interval");this.#e=e,this._forEachSubscriber(t=>{$E(t)&&(t.pollingInterval=this.#e)})}}class ny extends ty{#e;constructor(e,t,n){e==null&&(e="http://localhost:8545"),super(t,n),typeof e=="string"?this.#e=new zi(e):this.#e=e.clone()}_getConnection(){return this.#e.clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){const t=this._getConnection();t.body=JSON.stringify(e),t.setHeader("content-type","application/json");const n=await t.send();n.assertOk();let s=n.bodyJson;return Array.isArray(s)||(s=[s]),s}}function Pp(i){if(i==null)return null;if(typeof i.message=="string"&&i.message.match(/revert/i)&&Pt(i.data))return{message:i.message,data:i.data};if(typeof i=="object"){for(const e in i){const t=Pp(i[e]);if(t)return t}return null}if(typeof i=="string")try{return Pp(JSON.parse(i))}catch{}return null}function kp(i,e){if(i!=null){if(typeof i.message=="string"&&e.push(i.message),typeof i=="object")for(const t in i)kp(i[t],e);if(typeof i=="string")try{return kp(JSON.parse(i),e)}catch{}}}function A2(i){const e=[];return kp(i,e),e}class zr extends ty{#e;#t;constructor(e,t,n){const s=Object.assign({},n??{},{batchMaxCount:1});V(e&&e.request,"invalid EIP-1193 provider","ethereum",e),super(t,s),this.#t=null,n&&n.providerInfo&&(this.#t=n.providerInfo),this.#e=async(r,a)=>{const o={method:r,params:a};this.emit("debug",{action:"sendEip1193Request",payload:o});try{const c=await e.request(o);return this.emit("debug",{action:"receiveEip1193Result",result:c}),c}catch(c){const l=new Error(c.message);throw l.code=c.code,l.data=c.data,l.payload=o,this.emit("debug",{action:"receiveEip1193Error",error:l}),l}}}get providerInfo(){return this.#t}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){V(!Array.isArray(e),"EIP-1193 does not support batch request","payload",e);try{const t=await this.#e(e.method,e.params||[]);return[{id:e.id,result:t}]}catch(t){return[{id:e.id,error:{code:t.code,data:t.data,message:t.message}}]}}getRpcError(e,t){switch(t=JSON.parse(JSON.stringify(t)),t.error.code||-1){case 4001:t.error.message=`ethers-user-denied: ${t.error.message}`;break;case 4200:t.error.message=`ethers-unsupported: ${t.error.message}`;break}return super.getRpcError(e,t)}async hasSigner(e){e==null&&(e=0);const t=await this.send("eth_accounts",[]);return typeof e=="number"?t.length>e:(e=e.toLowerCase(),t.filter(n=>n.toLowerCase()===e).length!==0)}async getSigner(e){if(e==null&&(e=0),!await this.hasSigner(e))try{await this.#e("eth_requestAccounts",[])}catch(t){const n=t.payload;throw this.getRpcError(n,{id:n.id,error:t})}return await super.getSigner(e)}static async discover(e){if(e==null&&(e={}),e.provider)return new zr(e.provider);const t=e.window?e.window:typeof window<"u"?window:null;if(t==null)return null;const n=e.anyProvider;if(n&&t.ethereum)return new zr(t.ethereum);if(!("addEventListener"in t&&"dispatchEvent"in t&&"removeEventListener"in t))return null;const s=e.timeout?e.timeout:300;return s===0?null:await new Promise((r,a)=>{let o=[];const c=u=>{o.push(u.detail),n&&l()},l=()=>{if(clearTimeout(h),o.length)if(e&&e.filter){const u=e.filter(o.map(d=>Object.assign({},d.info)));if(u==null)r(null);else if(u instanceof zr)r(u);else{let d=null;if(u.uuid&&(d=o.filter(p=>u.uuid===p.info.uuid)[0]),d){const{provider:f,info:p}=d;r(new zr(f,void 0,{providerInfo:p}))}else a(Qt("filter returned unknown info","UNSUPPORTED_OPERATION",{value:u}))}}else{const{provider:u,info:d}=o[0];r(new zr(u,void 0,{providerInfo:d}))}else r(null);t.removeEventListener("eip6963:announceProvider",c)},h=setTimeout(()=>{l()},s);t.addEventListener("eip6963:announceProvider",c),t.dispatchEvent(new Event("eip6963:requestProvider"))})}}const iy=["function register() external returns (uint256 agentId)","function register(string agentURI) external returns (uint256 agentId)","function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)","function setAgentURI(uint256 agentId, string newURI) external","function tokenURI(uint256 tokenId) external view returns (string)","function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external","function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)","function getAgentWallet(uint256 agentId) external view returns (address)","function ownerOf(uint256 tokenId) external view returns (address)","function balanceOf(address owner) external view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)","function totalSupply() external view returns (uint256)","function name() external view returns (string)","function symbol() external view returns (string)","function getVersion() external pure returns (string)","function transferFrom(address from, address to, uint256 tokenId) external","function safeTransferFrom(address from, address to, uint256 tokenId) external","function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) external","function approve(address to, uint256 tokenId) external","function setApprovalForAll(address operator, bool approved) external","event Registered(uint256 indexed agentId, string agentURI, address indexed owner)","event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"],Vr={identityRegistry:"0x8004A818BFB912233c491871b3d84c89A494BD9e",reputationRegistry:"0x8004B663056A597Dffe9eCcC1965A193B7388713",validationRegistry:"0x8004Cb1BF31DAf7788923b405b754f57acEB4272"},Kn={identityRegistry:"0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",reputationRegistry:"0x8004BAa17C55a88189AE136b182e5fdA19dE9b63",validationRegistry:""},Uh={1:Kn,10:Kn,56:Kn,100:Kn,137:Kn,250:Kn,324:Kn,1284:Kn,5e3:Kn,8453:Kn,42161:Kn,42220:Kn,43114:Kn,59144:Kn,534352:Kn,97:Vr,11155111:Vr,84532:Vr,421614:Vr,11155420:Vr,80002:Vr,43113:Vr};function g2(i,e){return`eip155:${i}:${e}`}const sy={1:{name:"Ethereum",shortName:"ETH",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://ethereum-rpc.publicnode.com",explorer:"https://etherscan.io",testnet:!1},10:{name:"Optimism",shortName:"OP",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.optimism.io",explorer:"https://optimistic.etherscan.io",testnet:!1},56:{name:"BNB Chain",shortName:"BSC",currency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrl:"https://bsc-dataseed.bnbchain.org",explorer:"https://bscscan.com",testnet:!1},100:{name:"Gnosis",shortName:"GNO",currency:{name:"xDAI",symbol:"xDAI",decimals:18},rpcUrl:"https://rpc.gnosischain.com",explorer:"https://gnosisscan.io",testnet:!1},137:{name:"Polygon",shortName:"POL",currency:{name:"POL",symbol:"POL",decimals:18},rpcUrl:"https://polygon-rpc.com",explorer:"https://polygonscan.com",testnet:!1},250:{name:"Fantom",shortName:"FTM",currency:{name:"Fantom",symbol:"FTM",decimals:18},rpcUrl:"https://rpc.ftm.tools",explorer:"https://ftmscan.com",testnet:!1},324:{name:"zkSync Era",shortName:"zkSync",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.era.zksync.io",explorer:"https://explorer.zksync.io",testnet:!1},1284:{name:"Moonbeam",shortName:"GLMR",currency:{name:"Glimmer",symbol:"GLMR",decimals:18},rpcUrl:"https://rpc.api.moonbeam.network",explorer:"https://moonbeam.moonscan.io",testnet:!1},5e3:{name:"Mantle",shortName:"MNT",currency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrl:"https://rpc.mantle.xyz",explorer:"https://explorer.mantle.xyz",testnet:!1},8453:{name:"Base",shortName:"Base",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://mainnet.base.org",explorer:"https://basescan.org",testnet:!1},42161:{name:"Arbitrum One",shortName:"ARB",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://arb1.arbitrum.io/rpc",explorer:"https://arbiscan.io",testnet:!1},42220:{name:"Celo",shortName:"CELO",currency:{name:"Celo",symbol:"CELO",decimals:18},rpcUrl:"https://forno.celo.org",explorer:"https://celoscan.io",testnet:!1},43114:{name:"Avalanche",shortName:"AVAX",currency:{name:"Avax",symbol:"AVAX",decimals:18},rpcUrl:"https://api.avax.network/ext/bc/C/rpc",explorer:"https://snowtrace.io",testnet:!1},59144:{name:"Linea",shortName:"Linea",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://rpc.linea.build",explorer:"https://lineascan.build",testnet:!1},534352:{name:"Scroll",shortName:"Scroll",currency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrl:"https://rpc.scroll.io",explorer:"https://scrollscan.com",testnet:!1},97:{name:"BSC Testnet",shortName:"BSCt",currency:{name:"tBNB",symbol:"tBNB",decimals:18},rpcUrl:"https://bsc-testnet-rpc.publicnode.com",explorer:"https://testnet.bscscan.com",testnet:!0},11155111:{name:"Ethereum Sepolia",shortName:"Sep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://ethereum-sepolia-rpc.publicnode.com",explorer:"https://sepolia.etherscan.io",testnet:!0},84532:{name:"Base Sepolia",shortName:"BaseSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia.base.org",explorer:"https://sepolia.basescan.org",testnet:!0},421614:{name:"Arbitrum Sepolia",shortName:"ArbSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia-rollup.arbitrum.io/rpc",explorer:"https://sepolia.arbiscan.io",testnet:!0},11155420:{name:"Optimism Sepolia",shortName:"OpSep",currency:{name:"SepETH",symbol:"ETH",decimals:18},rpcUrl:"https://sepolia.optimism.io",explorer:"https://sepolia-optimism.etherscan.io",testnet:!0},80002:{name:"Polygon Amoy",shortName:"Amoy",currency:{name:"POL",symbol:"POL",decimals:18},rpcUrl:"https://rpc-amoy.polygon.technology",explorer:"https://amoy.polygonscan.com",testnet:!0},43113:{name:"Avalanche Fuji",shortName:"Fuji",currency:{name:"Avax",symbol:"AVAX",decimals:18},rpcUrl:"https://api.avax-test.network/ext/bc/C/rpc",explorer:"https://testnet.snowtrace.io",testnet:!0}};function m2(i,e){if(e)return new zr(e);const t=sy[i];if(!t)throw new Error(`No RPC configured for chainId ${i}`);return new ny(t.rpcUrl,i)}function x2(i,e){const t=Uh[i];if(!t||!t.identityRegistry)throw new Error(`No Identity Registry for chainId ${i}`);const n=m2(i,e);return new Gr(t.identityRegistry,iy,n)}async function b2({chainId:i,agentId:e,ethProvider:t}){const n=x2(i,t),[s,r]=await Promise.all([n.ownerOf(e).catch(()=>null),n.tokenURI(e).catch(()=>null)]);return{agentId:BigInt(e),owner:s,uri:r}}function ry(i){if(!i||typeof i!="object")return null;const e=Array.isArray(i.services)?i.services:[];for(const n of e){if(!n||typeof n!="object")continue;const s=String(n.endpoint||"").trim();if(!s)continue;const r=String(n.name||"").toLowerCase(),a=String(n.version||"").toLowerCase();if(r==="avatar"||r==="avatar-3d"||a.startsWith("gltf")||/\.(glb|gltf)(\?|#|$)/i.test(s))return s}const t=String(i.image||"").trim();return/\.(glb|gltf)(\?|#|$)/i.test(t)?t:null}async function E2(i){if(!i)return{ok:!1,error:"empty uri"};if(i.startsWith("data:"))try{const t=i.match(/^data:application\/json(?:;base64)?,(.*)$/);if(!t)return{ok:!1,error:"unsupported data URI"};const n=/;base64,/.test(i)?atob(t[1]):decodeURIComponent(t[1]);return{ok:!0,data:JSON.parse(n),resolvedUrl:i}}catch(t){return{ok:!1,error:"data URI parse failed: "+t.message}}let e=i;i.startsWith("ipfs://")?e="https://ipfs.io/ipfs/"+i.slice(7):i.startsWith("ar://")&&(e="https://arweave.net/"+i.slice(5));try{const t=await fetch(e);return t.ok?{ok:!0,data:await t.json(),resolvedUrl:e}:{ok:!1,error:`HTTP ${t.status}`,resolvedUrl:e}}catch(t){return{ok:!1,error:t.message,resolvedUrl:e}}}const y2={base:8453,"base-mainnet":8453,"base-sepolia":84532,ethereum:1,mainnet:1},_2={8453:"https://mainnet.base.org",84532:"https://sepolia.base.org",1:"https://eth.llamarpc.com"};async function Ec(i,{rpcURL:e,registry:t}={}){if(!i)throw new Error("loadManifest: source required");if(i.startsWith("agent://"))return w2(i,{rpcURL:e,registryOverride:t});if(i.startsWith("ipfs://")||i.startsWith("ar://")){const n=hs(i),s=await Up(n);return Oh(s,{baseURI:Op(n)})}if(i.startsWith("http")){const n=await Up(i);return Oh(n,{baseURI:Op(i)})}throw new Error(`Unsupported manifest source: ${i}`)}async function w2(i,{rpcURL:e,registryOverride:t}){const n=i.match(/^agent:\/\/([^/]+)\/(\d+)$/);if(!n)throw new Error(`Malformed agent URI: ${i}`);const[,s,r]=n,a=y2[s.toLowerCase()]||Number(s);if(!a)throw new Error(`Unknown chain: ${s}`);const o=Uh[a],c=t||o?.identityRegistry;if(!c)throw new Error(`No registry deployed on chain ${a}. Pass registry= override.`);const l=new ny(e||_2[a]),h=new Gr(c,iy,l),u=BigInt(r),d=await h.tokenURI(u);if(!d)throw new Error(`Agent ${r} on chain ${a} has no URI`);const f=hs(d),p=await Up(f),m=Oh(p,{baseURI:Op(f)});return m.id={...m.id,chain:s,chainId:a,registry:c,agentId:r},m}async function Up(i){let e;try{e=await fetch(i)}catch{e=await J0(i)}if(!e.ok)throw new Error(`Manifest fetch failed: ${i} (${e.status})`);return e.json()}function Oh(i,{baseURI:e=""}={}){if(i.spec&&i.spec.startsWith("agent-manifest/")){const t={...i,_baseURI:e};return t.body=t.body||{},!t.body.uri&&t.image&&(t.body.uri=t.image),t}if(i.type&&i.type.includes("eip-8004")){const t=i.registrations?.[0]||{},n=ry(i);return{spec:"agent-manifest/0.1",_baseURI:e,_source:"erc8004-registration",id:{agentId:t.agentId?.toString()},name:i.name,description:i.description,image:i.image,body:{uri:hs(n||i.image||""),format:"gltf-binary"},brain:{provider:"none"},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:[],memory:{mode:"local"},tools:["wave","lookAt","play_clip","setExpression"],version:"0.1.0",services:Array.isArray(i.services)?i.services:[],x402Support:!!i.x402Support,embedPolicy:i.embedPolicy||null}}return{spec:"agent-manifest/0.1",_baseURI:e,name:i.name||"Unnamed agent",description:i.description||"",body:{uri:i.body?.uri||i.image||i.model||"",format:i.body?.format||"gltf-binary"},brain:i.brain||{provider:"none"},voice:i.voice||{tts:{provider:"browser"},stt:{provider:"browser"}},skills:i.skills||[],memory:i.memory||{mode:"local"},tools:i.tools||["wave","lookAt","play_clip","setExpression"],version:i.version||"0.1.0"}}function Op(i){const e=i.lastIndexOf("/");return e>=0?i.slice(0,e+1):i}async function ay(i,e){if(!i._baseURI)return null;try{const t=new URL(e,i._baseURI).href,n=await fetch(t);return n.ok?n.text():null}catch{return null}}class Dn extends Error{constructor(e,t,{status:n}={}){super(t),this.name="AgentResolveError",this.code=e,n!==void 0&&(this.status=n)}}async function oy(i,{fetchFn:e}){let t;try{t=await e(i,{credentials:"include"})}catch(n){throw new Dn("network",`network error fetching ${i}: ${n.message||n}`)}if(t.status===401||t.status===403)throw new Dn("unauthorized",`unauthorized fetching ${i} (${t.status})`,{status:t.status});if(t.status===404)throw new Dn("not_found",`resource not found: ${i}`,{status:404});if(!t.ok)throw new Dn("network",`request failed: ${i} (${t.status})`,{status:t.status});try{return await t.json()}catch(n){throw new Dn("network",`invalid JSON from ${i}: ${n.message||n}`)}}const $a=new Map,v2=100;async function C2(i,e){if(!i)throw new Dn("not-found","agentId required");if($a.has(i))return $a.get(i);const t=typeof location<"u"?location.origin:"",n=`${t}/api/agents/${encodeURIComponent(i)}`;let s;try{s=await fetch(n,{credentials:"include",signal:e})}catch(c){throw c?.name==="AbortError"?c:new Dn("network",`network error fetching ${n}: ${c.message||c}`)}if(s.status===404)throw new Dn("not-found",`agent ${i} not found`,{status:404});if(s.status===401||s.status===403)throw new Dn("unauthorized",`unauthorized (${s.status})`,{status:s.status});if(!s.ok)throw new Dn("network",`request failed (${s.status})`,{status:s.status});let r;try{r=await s.json()}catch{throw new Dn("network",`invalid JSON from ${n}`)}const a=r?.agent?.manifestUrl??null;let o=null;if(a)try{o=new URL(a,t).href}catch{o=a}return $a.size>=v2&&$a.delete($a.keys().next().value),$a.set(i,o),o}async function I2(i,{origin:e=typeof location<"u"?location.origin:"",fetchFn:t=fetch}={}){if(!i)throw new Dn("not_found","agentId required");const n=t.bind(typeof globalThis<"u"?globalThis:void 0),r=(await oy(`${e}/api/agents/${encodeURIComponent(i)}`,{fetchFn:n}))?.agent;if(!r)throw new Dn("not_found",`agent ${i} not found`);if(!r.avatar_id)throw new Dn("no_avatar",`agent ${i} has no avatar bound`);const o=(await oy(`${e}/api/avatars/${encodeURIComponent(r.avatar_id)}`,{fetchFn:n}))?.avatar;if(!o||!o.url)throw new Dn("no_avatar",`avatar ${r.avatar_id} has no url`);const c=Array.isArray(r.skills)?r.skills.map(l=>typeof l=="string"?{name:l}:l).filter(Boolean):[];return{spec:"agent-manifest/0.1",name:r.name||"Agent",description:r.description||"",id:{agentId:r.id,owner:r.wallet_address,chainId:r.chain_id,walletAddress:r.wallet_address},body:{uri:o.url,format:"gltf-binary"},brain:{},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:c,memory:{mode:"remote",namespace:r.id},tools:["wave","lookAt","play_clip","setExpression","speak","remember"],version:"0.1.0",_baseURI:`${e}/agent/${r.id}/`,_source:"agent-id"}}function cy(i){if(!i)return null;if(typeof i=="object")return i.chainId&&i.agentId!==void 0?{chainId:Number(i.chainId),agentId:String(i.agentId),registry:i.registry||void 0}:null;const e=String(i).trim();if(!e)return null;let t=e.match(/^eip155:(\d+):(0x[0-9a-fA-F]{40}):(\d+)$/);return t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:(t=e.match(/^eip155:(\d+)\/erc721:(0x[0-9a-fA-F]{40})\/(\d+)$/),t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:(t=e.match(/^onchain:(\d+):(\d+)$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^agent:\/\/(\d+)\/(\d+)$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^\/?a\/(\d+)\/(\d+)(?:\/(embed))?\/?$/),t?{chainId:Number(t[1]),agentId:t[2]}:(t=e.match(/^\/?a\/(\d+)\/(0x[0-9a-fA-F]{40})\/(\d+)\/?$/),t?{chainId:Number(t[1]),registry:t[2],agentId:t[3]}:null)))))}function S2(i){const e=i.registry||Uh[i.chainId]?.identityRegistry;return e?`eip155:${i.chainId}:${e}:${i.agentId}`:`onchain:${i.chainId}:${i.agentId}`}function M2(i,{embed:e=!1,origin:t}={}){return`${t||(typeof location<"u"?location.origin:"")}/a/${i.chainId}/${i.agentId}${e?"/embed":""}`}const B2=["https://ipfs.io/ipfs/","https://dweb.link/ipfs/","https://cloudflare-ipfs.com/ipfs/","https://gateway.pinata.cloud/ipfs/"],T2="https://arweave.net/";function ly(i){return i?i.startsWith("ipfs://")?B2[0]+i.slice(7):i.startsWith("ar://")?T2+i.slice(5):i:""}const yc=new Map;function R2(i){return`${i.chainId}:${i.agentId}`}async function F2(i,{ethProvider:e,fresh:t=!1}={}){const n=cy(i);if(!n)throw new Error(`Unrecognised agent reference: ${i}`);const s={chainId:n.chainId,agentId:String(n.agentId),registry:n.registry||Uh[n.chainId]?.identityRegistry||null};if(!s.registry)throw new Error(`No registry deployed on chain ${s.chainId}`);const r=R2(s);if(!t&&yc.has(r))return yc.get(r);const a=sy[s.chainId]||null,o={ref:s,caip:S2(s),publicUrl:typeof location<"u"?M2(s):`/a/${s.chainId}/${s.agentId}`,chain:a?{name:a.name,testnet:!!a.testnet,explorer:a.explorer}:null,onchain:{owner:null,uri:null},metadata:null,metadataUrl:null,image:null,glbUrl:null,name:`Agent #${s.agentId}`,description:"",services:[]};try{const{owner:c,uri:l}=await b2({chainId:s.chainId,agentId:s.agentId,ethProvider:e});if(o.onchain={owner:c,uri:l},!l)return o.error="agentURI not set",yc.set(r,o),o;const h=await E2(l);if(!h.ok)return o.error=h.error,o.metadataUrl=h.resolvedUrl||null,yc.set(r,o),o;const u=h.data;o.metadata=u,o.metadataUrl=h.resolvedUrl||null,o.name=u?.name&&String(u.name)||o.name,o.description=u?.description&&String(u.description)||"",o.image=u?.image?String(u.image):null,o.services=Array.isArray(u?.services)?u.services:[],o.glbUrl=ry(u)}catch(c){o.error=c.message||String(c)}return yc.set(r,o),o}function N2(i){const e=Array.isArray(i.services)?i.services:[],t=e.find(a=>/brain|llm|chat/i.test(a?.name||a?.type||"")),n=e.filter(a=>/skill/i.test(a?.name||a?.type||"")),s=i.glbUrl?ly(i.glbUrl):"",r=i.image?ly(i.image):"";return{spec:"agent-manifest/0.1",_baseURI:i.metadataUrl?D2(i.metadataUrl):"",_source:"erc8004-resolver",id:{agentId:i.ref.agentId,chainId:i.ref.chainId,registry:i.ref.registry,owner:i.onchain.owner||void 0,walletAddress:i.onchain.owner||void 0,caip:i.caip,agentRegistry:g2(i.ref.chainId,i.ref.registry)},name:i.name,description:i.description,image:r,body:{uri:s||r,format:"gltf-binary"},brain:t?{provider:"remote",endpoint:t.endpoint}:{provider:"none"},voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:n.map(a=>({name:a.name,uri:a.endpoint})),memory:{mode:"local",namespace:i.caip},tools:["wave","lookAt","play_clip","setExpression"],version:"0.1.0",services:e,x402Support:!!(i.metadata?.x402Support||i.metadata?.x402),embedPolicy:i.metadata?.embedPolicy||null}}function D2(i){const e=i.lastIndexOf("/");return e>=0?i.slice(0,e+1):i}const hy=1,L2=256;function Qh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}const Qp={speak:"speak",gesture:"gesture",emote:"emote",look:"look-at"};class P2{constructor({protocol:e,avatar:t=null,manifest:n,window:s}){this._protocol=e,this._avatar=t,this._manifest=n,this._win=s,this._subscribed=!1,this._evtQueue=[],this._running=!1,this._onMessage=this._handleMessage.bind(this),this._onAction=this._handleAction.bind(this)}start(){if(this._running)return;this._running=!0,this._win.addEventListener("message",this._onMessage),this._protocol.on("*",this._onAction);const e=this._manifest?.id?.agentId||this._manifest?.agentId||"",t=[...Object.keys(Qp),"setAgent","ping","subscribe"];this._toParent({kind:"event",op:"ready",payload:{agentId:e,capabilities:t}})}stop(){this._running&&(this._running=!1,this._win.removeEventListener("message",this._onMessage),this._protocol.off("*",this._onAction),this._evtQueue=[])}_allowedOrigins(){const e=this._manifest?.policy;if(!e)return[];const t=e.origins||e.allowlist||[];return Array.isArray(t)?t:[t]}_originAllowed(e){const t=this._allowedOrigins();return t.length===0?!0:t.some(n=>{if(n==="*")return!0;try{return new URL(n).origin===e}catch{return n===e}})}_toParent(e){this._win.parent.postMessage({...e,v:hy,source:"agent-3d",id:e.id||Qh()},"*")}_reply(e,t){this._toParent({id:Qh(),inReplyTo:e.id,kind:"response",op:e.op==="ping"?"pong":e.op,payload:t})}_replyError(e,t,n){this._toParent({id:Qh(),inReplyTo:e.id,kind:"response",op:e.op,payload:{error:`${t}: ${n}`}})}_handleMessage(e){if(e.source!==this._win.parent||!this._originAllowed(e.origin))return;const t=e.data;if(!t||t.v!==hy||t.source!=="agent-host"||t.kind!=="request")return;const{op:n,payload:s={}}=t;if(n==="ping"){this._reply(t,{capabilities:[...Object.keys(Qp),"subscribe"]});return}if(n==="subscribe"){this._subscribed=!0,this._reply(t,{ok:!0});for(const a of this._evtQueue)this._toParent(a);this._evtQueue=[];return}if(n==="setAgent"){this._replyError(t,"not_supported","setAgent requires host to update the iframe src");return}const r=Qp[n];if(!r){this._replyError(t,"unknown_op",`Unknown op "${n}"`);return}try{this._protocol.emit({type:r,payload:s}),this._reply(t,{ok:!0})}catch(a){this._replyError(t,"emit_failed",a?.message||String(a))}}_handleAction(e){if(!this._running)return;const t={id:Qh(),kind:"event",op:"action",payload:{type:e.type,payload:e.payload,agentId:e.agentId}};if(!this._subscribed){this._evtQueue.length>=L2&&this._evtQueue.shift(),this._evtQueue.push(t);return}this._toParent(t)}}class k2 extends EventTarget{constructor(){super(),this._history=[],this._maxHistory=200}emit(e){const t={type:e.type,payload:e.payload||{},timestamp:Date.now(),agentId:e.agentId||"default",sourceSkill:e.sourceSkill||null};this._history.push(t),this._history.length>this._maxHistory&&this._history.shift(),this.dispatchEvent(new CustomEvent(t.type,{detail:t})),this.dispatchEvent(new CustomEvent("*",{detail:t}))}on(e,t){this._wrap(e,t,!1)}once(e,t){this._wrap(e,t,!0)}off(e,t){t.__protocolWrapped?this.removeEventListener(e,t.__protocolWrapped):this.removeEventListener(e,t)}get history(){return this._history.slice()}recent(e,t=10){return this._history.filter(n=>n.type===e).slice(-t)}_wrap(e,t,n){const s=r=>t(r.detail);t.__protocolWrapped=s,n?this.addEventListener(e,s,{once:!0}):this.addEventListener(e,s)}}const U2=new k2,O2=["inline","floating","section","fullscreen"],uy=(()=>{try{return new URL(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:nr&&nr.tagName.toUpperCase()==="SCRIPT"&&nr.src||new URL("agent-3d.umd.cjs",document.baseURI).href).origin}catch{return""}})();function Q2(i,e,t=[]){if(!i)return!1;let n;try{n=new URL(i).hostname.toLowerCase()}catch{return!1}if(t.some(o=>n===o||n.endsWith("."+o)))return!0;const s=e?.origins?.hosts??[],r=e?.origins?.mode??"allowlist",a=s.some(o=>{const c=o.toLowerCase();return c.startsWith("*.")?n.endsWith(c.slice(1))&&n!==c.slice(2):n===c});return r==="allowlist"?a:!a}const G2=`
:host {
display: block;
position: relative;
@@ -4189,7 +4189,7 @@ ${this.instructions}
padding: 16px;
font: 14px var(--agent-chat-font);
}
-`;class Gp extends HTMLElement{static get observedAttributes(){return["src","manifest","body","agent-id","mode","position","width","height","voice","api-key","key-proxy","responsive"]}constructor(){super(),this.attachShadow({mode:"open"}),this._viewer=null,this._scene=null,this._runtime=null,this._memory=null,this._skills=null,this._manifest=null,this._mounted=!1,this._booting=!1,this._listening=!1,this._pillActive=!1,this._mqNarrow=null,this._mqNarrowHandler=null,this._ro=null,this._outsideTapHandler=null,this._autoResolvedManifest=!1,this._suppressAttrChange=!1}connectedCallback(){this._renderShell(),this._applyLayout(),this._setupResponsive(),this._observeViewport(),this.hasAttribute("eager")&&this._boot()}disconnectedCallback(){this._teardown()}attributeChangedCallback(e,t,n){!this._mounted||this._suppressAttrChange||(["mode","position","width","height","responsive"].includes(e)&&this._applyLayout(),["src","manifest","body","agent-id"].includes(e)&&(this._teardown(),this._boot()))}_renderShell(){const e=document.createElement("style");e.textContent=H2,this.shadowRoot.appendChild(e);const t=document.createElement("div");t.className="stage",t.part="stage",this.shadowRoot.appendChild(t),this._stageEl=t;const n=document.createElement("div");n.className="poster",this.getAttribute("poster")&&(n.style.backgroundImage=`url(${this.getAttribute("poster")})`),this.shadowRoot.appendChild(n),this._posterEl=n;const s=document.createElement("div");s.className="loading",s.textContent="Loading...",s.hidden=!0,this.shadowRoot.appendChild(s),this._loadingEl=s;const r=document.createElement("button");r.className="pill-btn",r.setAttribute("aria-label","Open agent"),r.addEventListener("click",()=>this._expandPill()),r.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),this._expandPill())}),this.shadowRoot.appendChild(r),this._pillBtn=r;const a=document.createElement("div");if(a.className="pill-drag",this.shadowRoot.appendChild(a),this._pillDrag=a,!this.hasAttribute("kiosk")){const o=document.createElement("div");o.className="chrome",o.part="chrome";const c=document.createElement("div");c.className="chat",c.part="chat";const l=document.createElement("div");l.className="input-row";const h=document.createElement("input");h.type="text",h.placeholder="Say something...",h.addEventListener("keydown",d=>{if(d.key==="Enter"&&h.value.trim()){const f=h.value.trim();h.value="",this.say(f)}});const u=document.createElement("button");u.className="icon mic",u.title="Push to talk",u.innerHTML="🎙",u.addEventListener("click",()=>this._toggleMic()),l.appendChild(h),l.appendChild(u),o.appendChild(c),o.appendChild(l),this.shadowRoot.appendChild(o),this._chatEl=c,this._inputEl=h,this._micEl=u}}_isResponsive(){return this.getAttribute("responsive")!=="false"}_clampWidth(e){const t=_parsePx(e);if(!t)return e;const n=Math.round(Math.max(160,t*.65)),s=Math.round(t/1440*100);return`clamp(${n}px, ${s}vw, ${t}px)`}_clampHeight(e){const t=_parsePx(e);if(!t)return e;const n=Math.round(Math.max(200,t*.65)),s=Math.round(t/900*100);return`clamp(${n}px, ${s}vh, ${t}px)`}_applyLayout(){const e=this.getAttribute("mode")||"inline";if(!Q2.includes(e))return;const t=this._isResponsive();if(e==="floating"){if(!this._pillActive){const r=this.getAttribute("position")||"bottom-right",a=(this.getAttribute("offset")||"24px 24px").split(/\s+/),[o,c]=[a[0],a[1]||a[0]];this.style.top=this.style.bottom=this.style.left=this.style.right="",r.includes("top")?this.style.top=o:this.style.bottom=o,r.includes("left")?this.style.left=c:r.includes("right")?this.style.right=c:r.includes("center")&&(this.style.left="50%",this.style.transform="translateX(-50%)")}const n=this.getAttribute("width")||"320px",s=this.getAttribute("height")||"420px";this.style.setProperty("--agent-width",t?this._clampWidth(n):n),this.style.setProperty("--agent-height",t?this._clampHeight(s):s)}else{this.style.top=this.style.bottom=this.style.left=this.style.right=this.style.transform="";const n=this.getAttribute("width"),s=this.getAttribute("height");e==="inline"&&(n&&(this.style.width=t?this._clampWidth(n):n),s?(this.style.height=s,this.removeAttribute("data-responsive")):t&&n&&(this.style.height="",this.setAttribute("data-responsive",""))),n&&this.style.setProperty("--agent-width",t?this._clampWidth(n):n),s&&this.style.setProperty("--agent-height",t?this._clampHeight(s):s)}}_setupResponsive(){const e=this.getAttribute("mode")||"inline";e==="inline"&&typeof ResizeObserver<"u"&&(this._ro=new ResizeObserver(()=>this._applyLayout()),this._ro.observe(this)),e==="floating"&&this._isResponsive()&&typeof window<"u"&&(this._mqNarrow=window.matchMedia("(max-width: 479px)"),this._mqNarrowHandler=n=>this._updatePillState(n.matches),this._mqNarrow.addEventListener("change",this._mqNarrowHandler),this._updatePillState(this._mqNarrow.matches));let t=0;this.shadowRoot.addEventListener("touchstart",n=>{t=n.touches[0].clientY},{passive:!0}),this.shadowRoot.addEventListener("touchend",n=>{n.changedTouches[0].clientY-t>60&&this._pillActive&&this.getAttribute("aria-expanded")==="true"&&this._collapsePill()},{passive:!0})}_updatePillState(e){e&&!this._pillActive?(this._pillActive=!0,this._collapsePill()):!e&&this._pillActive&&(this._pillActive=!1,this._restoreFromPill())}_collapsePill(){this.style.width="56px",this.style.height="56px",this.style.borderRadius="50%",this.setAttribute("aria-expanded","false"),this._pillBtn.style.display="block",this._pillDrag.style.display="none";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display="none"),this._stageEl.style.display="none",this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null)}_expandPill(){if(!this._pillActive)return;this.style.width="100vw",this.style.height="70vh",this.style.borderRadius="16px 16px 0 0",this.style.bottom="0",this.style.top="auto",this.style.left="0",this.style.right="0",this.style.transform="none",this.setAttribute("aria-expanded","true"),this._pillBtn.style.display="none",this._pillDrag.style.display="block";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display=""),this._stageEl.style.display="",this._outsideTapHandler=t=>{t.composedPath().includes(this)||this._collapsePill()},setTimeout(()=>document.addEventListener("pointerdown",this._outsideTapHandler),0)}_restoreFromPill(){this.removeAttribute("aria-expanded"),this._pillBtn.style.display="none",this._pillDrag.style.display="none";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display=""),this._stageEl.style.display="",this.style.width=this.style.height=this.style.borderRadius="",this.style.bottom=this.style.top=this.style.left=this.style.right=this.style.transform="",this._applyLayout(),this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null)}_observeViewport(){if(!this.hasAttribute("eager")){if(typeof IntersectionObserver>"u"){this._boot();return}this._io=new IntersectionObserver(e=>{e.some(t=>t.isIntersecting)&&(this._io.disconnect(),this._boot())}),this._io.observe(this)}}async _boot(){if(!(this._booting||this._mounted)){this._booting=!0;try{this._loadingEl.hidden=!1,this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"manifest",pct:.1}}));const e=await this._resolveManifest();if(this._manifest=e,this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"manifest",pct:.3}})),typeof e.brain?.instructions=="string"&&e.brain.instructions.endsWith(".md")){const l=await ay(e,e.brain.instructions);l&&(e.instructions=z2(l))}else e.brain?.instructions&&(e.instructions=e.brain.instructions);const t=(()=>{const l=this.getAttribute("agent-id")||e.id?.agentId||"";return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)?l:null})();if(t)try{const l=dy||window.location.origin,h=await fetch(`${l}/api/agents/${t}/embed-policy`,{credentials:"omit"});if(h.ok){const{policy:u}=await h.json();if(u){if(u.surfaces?.script===!1){this._fail("embed_denied_surface","This agent disallows the script-tag embed.");return}const d=["3dagent.vercel.app","localhost"],f=window.location.origin;if(!f.startsWith("http://localhost")&&!G2(f,u,d)){this._fail("embed_denied_origin",`This agent isn't permitted on ${f}.`);return}}}}catch(l){console.warn("[agent-3d] embed-policy fetch failed; continuing",l)}this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"body",pct:.45}}));const n=new Bf(this._stageEl,{kiosk:this.hasAttribute("kiosk")});this._viewer=n;const s=hs(e.body?.uri);s&&await n.load(s,"",new Map),this._scene=new $0(n),this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"memory",pct:.6}}));const r=e.id?.agentId||this.getAttribute("memory-key")||e.name||"anon";this._memory=await Bi.load({mode:this.getAttribute("memory")||e.memory?.mode||"local",namespace:r,manifestURI:e._baseURI+"manifest.json",fetchFn:fetch.bind(globalThis)}),this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"skills",pct:.75}})),this._skills=new ix({trust:this.getAttribute("skill-trust")||"owned-only",ownerAddress:e.id?.owner});const a=e.skills||[];for(const l of a)try{const h=await this._skills.install(l,{bundleBase:e._baseURI});this.dispatchEvent(new CustomEvent("skill:loaded",{detail:{name:h.name,uri:h.uri}}))}catch(h){console.warn("[agent-3d] skill load failed",l,h)}this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"brain",pct:.9}}));const o={apiKey:this.getAttribute("api-key")||void 0,proxyURL:this.getAttribute("key-proxy")||void 0,agentId:t||void 0,apiOrigin:dy||window.location.origin},c=this._parseTTSAttribute();c&&(e.voice=e.voice||{},e.voice.tts={...e.voice.tts||{},...c}),this._runtime=new Y0({manifest:e,viewer:this._scene,memory:this._memory,skills:this._skills,providerConfig:o});for(const l of["brain:thinking","brain:message","skill:tool-called","voice:speech-start","voice:speech-end","voice:transcript","voice:listen-start","memory:write"])this._runtime.addEventListener(l,h=>{this.dispatchEvent(new CustomEvent(l,{detail:h.detail,bubbles:!0,composed:!0})),l==="brain:message"&&this._chatEl&&this._renderMessage(h.detail)});this._mounted=!0,window!==window.parent&&(this._embedBridge=new k2({protocol:uy,manifest:this._manifest,window}),this._embedBridge.start()),this._loadingEl.hidden=!0,this._pillActive||(this._posterEl.style.opacity="0"),this.dispatchEvent(new CustomEvent("agent:ready",{detail:{agent:this,manifest:e},bubbles:!0,composed:!0}))}catch(e){if(console.error("[agent-3d] boot failed",e),this._loadingEl.hidden=!0,e instanceof Dn&&e.code==="not-found"){const t=document.createElement("div");t.className="agent-3d-error",t.textContent="Agent not found",this.shadowRoot.appendChild(t)}else this._showError(e);this.dispatchEvent(new CustomEvent("agent:error",{detail:{phase:"boot",error:e},bubbles:!0,composed:!0}))}finally{this._booting=!1}}}async _resolveManifest(){const e=this.getAttribute("src"),t=this.getAttribute("manifest"),n=this.getAttribute("body"),s=this.getAttribute("agent-id"),r=this.getAttribute("chain-id");if(e)return s&&console.warn("[agent-3d] both src and agent-id provided; using src"),Ec(e,{rpcURL:this.getAttribute("rpc-url"),registry:this.getAttribute("registry")});if(s){const a=r?{chainId:Number(r),agentId:s,registry:this.getAttribute("registry")||void 0}:s,o=cy(a);if(o){const l=await N2(o);if(l.error&&!l.glbUrl)throw new Error(`On-chain resolve failed: ${l.error}`);return D2(l)}if(t)return Ec(t);const c=await I2(s);return c?(this._autoResolvedManifest=!0,this.setAttribute("manifest",c),Ec(c)):S2(s)}if(t)return Ec(t);if(n){const a=this.getAttribute("instructions");return{spec:"agent-manifest/0.1",_baseURI:"",name:this.getAttribute("name")||"Agent",body:{uri:n,format:"gltf-binary"},brain:{provider:this.getAttribute("brain")?"anthropic":"none",model:this.getAttribute("brain")||void 0,instructions:a||"You are an embodied 3D agent."},instructions:a||"You are an embodied 3D agent.",voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:(this.getAttribute("skills")||"").split(",").map(o=>o.trim()).filter(Boolean).map(o=>({uri:o})),memory:{mode:this.getAttribute("memory")||"local"},tools:["wave","lookAt","play_clip","setExpression","speak","remember"],version:"0.1.0"}}throw new Error("<agent-3d> requires src=, manifest=, or body= attribute")}_renderMessage({role:e,content:t}){if(!this._chatEl||!t)return;const n=document.createElement("div");n.className="msg",n.innerHTML=`<div class="role">${e}</div><div class="body"></div>`,n.querySelector(".body").textContent=t,this._chatEl.appendChild(n),this._chatEl.scrollTop=this._chatEl.scrollHeight}_showError(e){const t=document.createElement("div");t.className="error",t.textContent=`Couldn't load agent: ${e.message||e}`,this.shadowRoot.appendChild(t)}_fail(e,t){this._loadingEl.hidden=!0;const n=document.createElement("div");n.className="error",n.textContent=t,this.shadowRoot.appendChild(n),this.dispatchEvent(new CustomEvent("agent:error",{detail:{phase:"policy",error:{code:e,message:t}},bubbles:!0,composed:!0}))}async _toggleMic(){if(this._runtime){if(this._listening){this._runtime.stt?.stop(),this._listening=!1,this._micEl.dataset.listening="false";return}this._listening=!0,this._micEl.dataset.listening="true";try{const e=await this._runtime.listen();e&&await this.say(e,{voice:!0})}catch(e){console.warn("[agent-3d] listen failed",e)}finally{this._listening=!1,this._micEl.dataset.listening="false"}}}_teardown(){if(this._autoResolvedManifest){this._suppressAttrChange=!0;try{this.removeAttribute("manifest")}finally{this._suppressAttrChange=!1}this._autoResolvedManifest=!1}try{this._io?.disconnect()}catch{}try{this._ro?.disconnect()}catch{}try{this._mqNarrow&&this._mqNarrowHandler&&this._mqNarrow.removeEventListener("change",this._mqNarrowHandler)}catch{}this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null),this._embedBridge?.stop(),this._embedBridge=null;try{this._runtime?.destroy()}catch{}try{this._viewer?.dispose?.()}catch{}this._mounted=!1,this._pillActive=!1,this._runtime=this._viewer=this._scene=this._memory=this._skills=null}async say(e,t={}){return this._runtime||await this._waitForReady(),this._runtime.send(e,{voice:t.voice??this.hasAttribute("voice")})}speak(e,t={}){uy.emit(U2.SPEAK,{text:e,sentiment:t.sentiment??0})}async ask(e,t={}){return(await this.say(e,t))?.text||""}clearConversation(){this._runtime?.clearConversation()}async wave(e){return this._scene?.playAnimationByHint("wave",e)}async lookAt(e){return this._scene?.lookAt(e)}async play(e,t){return this._scene?.playClipByName(e,t)}async installSkill(e){if(!this._skills)throw new Error("Agent not mounted");return this._skills.install({uri:e})}uninstallSkill(e){return this._skills?.uninstall(e)}get skills(){return this._skills?.all()||[]}get memory(){return this._memory}get manifest(){return this._manifest}get runtime(){return this._runtime}setMode(e){this.setAttribute("mode",e)}setPosition(e,t){this.setAttribute("position",e),t&&this.setAttribute("offset",t)}setSize(e,t){this.setAttribute("width",e),this.setAttribute("height",t)}pause(){this._runtime?.pause()}resume(){}destroy(){this._teardown()}_waitForReady(){return this._mounted?Promise.resolve():new Promise(e=>{const t=()=>{this.removeEventListener("agent:ready",t),e()};this.addEventListener("agent:ready",t),this._booting||this._boot()})}}function z2(i){const e=i.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);return e?e[1]:i}customElements.get("agent-3d")||customElements.define("agent-3d",Gp);const V2=["row","circle","freeform"],W2=`
+`;class Gp extends HTMLElement{static get observedAttributes(){return["src","manifest","body","agent-id","mode","position","width","height","voice","api-key","key-proxy","responsive"]}constructor(){super(),this.attachShadow({mode:"open"}),this._viewer=null,this._scene=null,this._runtime=null,this._memory=null,this._skills=null,this._manifest=null,this._mounted=!1,this._booting=!1,this._listening=!1,this._pillActive=!1,this._mqNarrow=null,this._mqNarrowHandler=null,this._ro=null,this._outsideTapHandler=null,this._autoResolvedManifest=!1,this._suppressAttrChange=!1}connectedCallback(){this._renderShell(),this._applyLayout(),this._setupResponsive(),this._observeViewport(),this.hasAttribute("eager")&&this._boot()}disconnectedCallback(){this._teardown()}attributeChangedCallback(e,t,n){!this._mounted||this._suppressAttrChange||(["mode","position","width","height","responsive"].includes(e)&&this._applyLayout(),["src","manifest","body","agent-id"].includes(e)&&(this._teardown(),this._boot()))}_renderShell(){const e=document.createElement("style");e.textContent=G2,this.shadowRoot.appendChild(e);const t=document.createElement("div");t.className="stage",t.part="stage",this.shadowRoot.appendChild(t),this._stageEl=t;const n=document.createElement("div");n.className="poster",this.getAttribute("poster")&&(n.style.backgroundImage=`url(${this.getAttribute("poster")})`),this.shadowRoot.appendChild(n),this._posterEl=n;const s=document.createElement("div");s.className="loading",s.textContent="Loading...",s.hidden=!0,this.shadowRoot.appendChild(s),this._loadingEl=s;const r=document.createElement("button");r.className="pill-btn",r.setAttribute("aria-label","Open agent"),r.addEventListener("click",()=>this._expandPill()),r.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),this._expandPill())}),this.shadowRoot.appendChild(r),this._pillBtn=r;const a=document.createElement("div");if(a.className="pill-drag",this.shadowRoot.appendChild(a),this._pillDrag=a,!this.hasAttribute("kiosk")){const o=document.createElement("div");o.className="chrome",o.part="chrome";const c=document.createElement("div");c.className="chat",c.part="chat";const l=document.createElement("div");l.className="input-row";const h=document.createElement("input");h.type="text",h.placeholder="Say something...",h.addEventListener("keydown",d=>{if(d.key==="Enter"&&h.value.trim()){const f=h.value.trim();h.value="",this.say(f)}});const u=document.createElement("button");u.className="icon mic",u.title="Push to talk",u.innerHTML="🎙",u.addEventListener("click",()=>this._toggleMic()),l.appendChild(h),l.appendChild(u),o.appendChild(c),o.appendChild(l),this.shadowRoot.appendChild(o),this._chatEl=c,this._inputEl=h,this._micEl=u}}_isResponsive(){return this.getAttribute("responsive")!=="false"}_clampWidth(e){const t=_parsePx(e);if(!t)return e;const n=Math.round(Math.max(160,t*.65)),s=Math.round(t/1440*100);return`clamp(${n}px, ${s}vw, ${t}px)`}_clampHeight(e){const t=_parsePx(e);if(!t)return e;const n=Math.round(Math.max(200,t*.65)),s=Math.round(t/900*100);return`clamp(${n}px, ${s}vh, ${t}px)`}_applyLayout(){const e=this.getAttribute("mode")||"inline";if(!O2.includes(e))return;const t=this._isResponsive();if(e==="floating"){if(!this._pillActive){const r=this.getAttribute("position")||"bottom-right",a=(this.getAttribute("offset")||"24px 24px").split(/\s+/),[o,c]=[a[0],a[1]||a[0]];this.style.top=this.style.bottom=this.style.left=this.style.right="",r.includes("top")?this.style.top=o:this.style.bottom=o,r.includes("left")?this.style.left=c:r.includes("right")?this.style.right=c:r.includes("center")&&(this.style.left="50%",this.style.transform="translateX(-50%)")}const n=this.getAttribute("width")||"320px",s=this.getAttribute("height")||"420px";this.style.setProperty("--agent-width",t?this._clampWidth(n):n),this.style.setProperty("--agent-height",t?this._clampHeight(s):s)}else{this.style.top=this.style.bottom=this.style.left=this.style.right=this.style.transform="";const n=this.getAttribute("width"),s=this.getAttribute("height");e==="inline"&&(n&&(this.style.width=t?this._clampWidth(n):n),s?(this.style.height=s,this.removeAttribute("data-responsive")):t&&n&&(this.style.height="",this.setAttribute("data-responsive",""))),n&&this.style.setProperty("--agent-width",t?this._clampWidth(n):n),s&&this.style.setProperty("--agent-height",t?this._clampHeight(s):s)}}_setupResponsive(){const e=this.getAttribute("mode")||"inline";e==="inline"&&typeof ResizeObserver<"u"&&(this._ro=new ResizeObserver(()=>this._applyLayout()),this._ro.observe(this)),e==="floating"&&this._isResponsive()&&typeof window<"u"&&(this._mqNarrow=window.matchMedia("(max-width: 479px)"),this._mqNarrowHandler=n=>this._updatePillState(n.matches),this._mqNarrow.addEventListener("change",this._mqNarrowHandler),this._updatePillState(this._mqNarrow.matches));let t=0;this.shadowRoot.addEventListener("touchstart",n=>{t=n.touches[0].clientY},{passive:!0}),this.shadowRoot.addEventListener("touchend",n=>{n.changedTouches[0].clientY-t>60&&this._pillActive&&this.getAttribute("aria-expanded")==="true"&&this._collapsePill()},{passive:!0})}_updatePillState(e){e&&!this._pillActive?(this._pillActive=!0,this._collapsePill()):!e&&this._pillActive&&(this._pillActive=!1,this._restoreFromPill())}_collapsePill(){this.style.width="56px",this.style.height="56px",this.style.borderRadius="50%",this.setAttribute("aria-expanded","false"),this._pillBtn.style.display="block",this._pillDrag.style.display="none";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display="none"),this._stageEl.style.display="none",this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null)}_expandPill(){if(!this._pillActive)return;this.style.width="100vw",this.style.height="70vh",this.style.borderRadius="16px 16px 0 0",this.style.bottom="0",this.style.top="auto",this.style.left="0",this.style.right="0",this.style.transform="none",this.setAttribute("aria-expanded","true"),this._pillBtn.style.display="none",this._pillDrag.style.display="block";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display=""),this._stageEl.style.display="",this._outsideTapHandler=t=>{t.composedPath().includes(this)||this._collapsePill()},setTimeout(()=>document.addEventListener("pointerdown",this._outsideTapHandler),0)}_restoreFromPill(){this.removeAttribute("aria-expanded"),this._pillBtn.style.display="none",this._pillDrag.style.display="none";const e=this.shadowRoot.querySelector(".chrome");e&&(e.style.display=""),this._stageEl.style.display="",this.style.width=this.style.height=this.style.borderRadius="",this.style.bottom=this.style.top=this.style.left=this.style.right=this.style.transform="",this._applyLayout(),this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null)}_observeViewport(){if(!this.hasAttribute("eager")){if(typeof IntersectionObserver>"u"){this._boot();return}this._io=new IntersectionObserver(e=>{e.some(t=>t.isIntersecting)&&(this._io.disconnect(),this._boot())}),this._io.observe(this)}}async _boot(){if(!(this._booting||this._mounted)){this._booting=!0;try{this._loadingEl.hidden=!1,this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"manifest",pct:.1}}));const e=await this._resolveManifest();if(this._manifest=e,this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"manifest",pct:.3}})),typeof e.brain?.instructions=="string"&&e.brain.instructions.endsWith(".md")){const l=await ay(e,e.brain.instructions);l&&(e.instructions=H2(l))}else e.brain?.instructions&&(e.instructions=e.brain.instructions);const t=(()=>{const l=this.getAttribute("agent-id")||e.id?.agentId||"";return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)?l:null})();if(t)try{const l=uy||window.location.origin,h=await fetch(`${l}/api/agents/${t}/embed-policy`,{credentials:"omit"});if(h.ok){const{policy:u}=await h.json();if(u){if(u.surfaces?.script===!1){this._fail("embed_denied_surface","This agent disallows the script-tag embed.");return}const d=["3dagent.vercel.app","localhost"],f=window.location.origin;if(!f.startsWith("http://localhost")&&!Q2(f,u,d)){this._fail("embed_denied_origin",`This agent isn't permitted on ${f}.`);return}}}}catch(l){console.warn("[agent-3d] embed-policy fetch failed; continuing",l)}this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"body",pct:.45}}));const n=new Bf(this._stageEl,{kiosk:this.hasAttribute("kiosk")});this._viewer=n;const s=hs(e.body?.uri);s&&await n.load(s,"",new Map),this._scene=new $0(n),this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"memory",pct:.6}}));const r=e.id?.agentId||this.getAttribute("memory-key")||e.name||"anon";this._memory=await Bi.load({mode:this.getAttribute("memory")||e.memory?.mode||"local",namespace:r,manifestURI:e._baseURI+"manifest.json",fetchFn:fetch.bind(globalThis)}),this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"skills",pct:.75}})),this._skills=new ix({trust:this.getAttribute("skill-trust")||"owned-only",ownerAddress:e.id?.owner});const a=e.skills||[];for(const l of a)try{const h=await this._skills.install(l,{bundleBase:e._baseURI});this.dispatchEvent(new CustomEvent("skill:loaded",{detail:{name:h.name,uri:h.uri}}))}catch(h){console.warn("[agent-3d] skill load failed",l,h)}this.dispatchEvent(new CustomEvent("agent:load-progress",{detail:{phase:"brain",pct:.9}}));const o={apiKey:this.getAttribute("api-key")||void 0,proxyURL:this.getAttribute("key-proxy")||void 0,agentId:t||void 0,apiOrigin:uy||window.location.origin},c=this._parseTTSAttribute();c&&(e.voice=e.voice||{},e.voice.tts={...e.voice.tts||{},...c}),this._runtime=new Y0({manifest:e,viewer:this._scene,memory:this._memory,skills:this._skills,providerConfig:o});for(const l of["brain:thinking","brain:message","skill:tool-called","voice:speech-start","voice:speech-end","voice:transcript","voice:listen-start","memory:write"])this._runtime.addEventListener(l,h=>{this.dispatchEvent(new CustomEvent(l,{detail:h.detail,bubbles:!0,composed:!0})),l==="brain:message"&&this._chatEl&&this._renderMessage(h.detail)});this._mounted=!0,window!==window.parent&&(this._embedBridge=new P2({protocol:U2,manifest:this._manifest,window}),this._embedBridge.start()),this._loadingEl.hidden=!0,this._pillActive||(this._posterEl.style.opacity="0"),this.dispatchEvent(new CustomEvent("agent:ready",{detail:{agent:this,manifest:e},bubbles:!0,composed:!0}))}catch(e){if(console.error("[agent-3d] boot failed",e),this._loadingEl.hidden=!0,e instanceof Dn&&e.code==="not-found"){const t=document.createElement("div");t.className="agent-3d-error",t.textContent="Agent not found",this.shadowRoot.appendChild(t)}else this._showError(e);this.dispatchEvent(new CustomEvent("agent:error",{detail:{phase:"boot",error:e},bubbles:!0,composed:!0}))}finally{this._booting=!1}}}async _resolveManifest(){const e=this.getAttribute("src"),t=this.getAttribute("manifest"),n=this.getAttribute("body"),s=this.getAttribute("agent-id"),r=this.getAttribute("chain-id");if(e)return s&&console.warn("[agent-3d] both src and agent-id provided; using src"),Ec(e,{rpcURL:this.getAttribute("rpc-url"),registry:this.getAttribute("registry")});if(s){const a=r?{chainId:Number(r),agentId:s,registry:this.getAttribute("registry")||void 0}:s,o=cy(a);if(o){const l=await F2(o);if(l.error&&!l.glbUrl)throw new Error(`On-chain resolve failed: ${l.error}`);return N2(l)}if(t)return Ec(t);const c=await C2(s);return c?(this._autoResolvedManifest=!0,this.setAttribute("manifest",c),Ec(c)):I2(s)}if(t)return Ec(t);if(n){const a=this.getAttribute("instructions");return{spec:"agent-manifest/0.1",_baseURI:"",name:this.getAttribute("name")||"Agent",body:{uri:n,format:"gltf-binary"},brain:{provider:this.getAttribute("brain")?"anthropic":"none",model:this.getAttribute("brain")||void 0,instructions:a||"You are an embodied 3D agent."},instructions:a||"You are an embodied 3D agent.",voice:{tts:{provider:"browser"},stt:{provider:"browser"}},skills:(this.getAttribute("skills")||"").split(",").map(o=>o.trim()).filter(Boolean).map(o=>({uri:o})),memory:{mode:this.getAttribute("memory")||"local"},tools:["wave","lookAt","play_clip","setExpression","speak","remember"],version:"0.1.0"}}throw new Error("<agent-3d> requires src=, manifest=, or body= attribute")}_renderMessage({role:e,content:t}){if(!this._chatEl||!t)return;const n=document.createElement("div");n.className="msg",n.innerHTML=`<div class="role">${e}</div><div class="body"></div>`,n.querySelector(".body").textContent=t,this._chatEl.appendChild(n),this._chatEl.scrollTop=this._chatEl.scrollHeight}_showError(e){const t=document.createElement("div");t.className="error",t.textContent=`Couldn't load agent: ${e.message||e}`,this.shadowRoot.appendChild(t)}_fail(e,t){this._loadingEl.hidden=!0;const n=document.createElement("div");n.className="error",n.textContent=t,this.shadowRoot.appendChild(n),this.dispatchEvent(new CustomEvent("agent:error",{detail:{phase:"policy",error:{code:e,message:t}},bubbles:!0,composed:!0}))}async _toggleMic(){if(this._runtime){if(this._listening){this._runtime.stt?.stop(),this._listening=!1,this._micEl.dataset.listening="false";return}this._listening=!0,this._micEl.dataset.listening="true";try{const e=await this._runtime.listen();e&&await this.say(e,{voice:!0})}catch(e){console.warn("[agent-3d] listen failed",e)}finally{this._listening=!1,this._micEl.dataset.listening="false"}}}_teardown(){if(this._autoResolvedManifest){this._suppressAttrChange=!0;try{this.removeAttribute("manifest")}finally{this._suppressAttrChange=!1}this._autoResolvedManifest=!1}try{this._io?.disconnect()}catch{}try{this._ro?.disconnect()}catch{}try{this._mqNarrow&&this._mqNarrowHandler&&this._mqNarrow.removeEventListener("change",this._mqNarrowHandler)}catch{}this._outsideTapHandler&&(document.removeEventListener("pointerdown",this._outsideTapHandler),this._outsideTapHandler=null),this._embedBridge?.stop(),this._embedBridge=null;try{this._runtime?.destroy()}catch{}try{this._viewer?.dispose?.()}catch{}this._mounted=!1,this._pillActive=!1,this._runtime=this._viewer=this._scene=this._memory=this._skills=null}async say(e,t={}){return this._runtime||await this._waitForReady(),this._runtime.send(e,{voice:t.voice??this.hasAttribute("voice")})}speak(e,t={}){const n=Math.max(1.5,(e?.split(" ").length??3)*.3),s=this._scene;s&&(s.playAnimationByHint("talk",{duration:n})||s.playAnimationByHint("yes",{duration:n})||s.playAnimationByHint("wave",{duration:n}))}async ask(e,t={}){return(await this.say(e,t))?.text||""}clearConversation(){this._runtime?.clearConversation()}async wave(e){return this._scene?.playAnimationByHint("wave",e)}async lookAt(e){return this._scene?.lookAt(e)}async play(e,t){return this._scene?.playClipByName(e,t)}async installSkill(e){if(!this._skills)throw new Error("Agent not mounted");return this._skills.install({uri:e})}uninstallSkill(e){return this._skills?.uninstall(e)}get skills(){return this._skills?.all()||[]}get memory(){return this._memory}get manifest(){return this._manifest}get runtime(){return this._runtime}setMode(e){this.setAttribute("mode",e)}setPosition(e,t){this.setAttribute("position",e),t&&this.setAttribute("offset",t)}setSize(e,t){this.setAttribute("width",e),this.setAttribute("height",t)}pause(){this._runtime?.pause()}resume(){}destroy(){this._teardown()}_waitForReady(){return this._mounted?Promise.resolve():new Promise(e=>{const t=()=>{this.removeEventListener("agent:ready",t),e()};this.addEventListener("agent:ready",t),this._booting||this._boot()})}}function H2(i){const e=i.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);return e?e[1]:i}customElements.get("agent-3d")||customElements.define("agent-3d",Gp);const z2=["row","circle","freeform"],V2=`
:host {
display: block;
position: relative;
@@ -4209,4 +4209,4 @@ ${this.instructions}
position: absolute;
pointer-events: none;
}
-`;class fy extends HTMLElement{static get observedAttributes(){return["formation"]}constructor(){super(),this.attachShadow({mode:"open"}),this._viewer=null,this._agents=[],this._initialized=!1}connectedCallback(){this._renderShell(),this._initViewer(),this._mo=new MutationObserver(()=>this._repositionAll()),this._mo.observe(this,{childList:!0})}disconnectedCallback(){try{this._mo?.disconnect()}catch{}for(const e of[...this._agents])this.unregisterAgent(e.element);try{this._viewer?.dispose?.()}catch{}this._viewer=null,this._initialized=!1}attributeChangedCallback(e){e==="formation"&&this._repositionAll()}get formation(){const e=this.getAttribute("formation")||"row";return V2.includes(e)?e:"row"}get viewer(){return this._viewer}_renderShell(){const e=document.createElement("style");e.textContent=W2,this.shadowRoot.appendChild(e);const t=document.createElement("div");t.className="stage-canvas",t.part="stage",this.shadowRoot.appendChild(t),this._canvasBox=t;const n=document.createElement("slot");this.shadowRoot.appendChild(n)}_initViewer(){if(!this._initialized){this._viewer=new Bf(this._canvasBox,{kiosk:!0}),this._viewer.defaultCamera.position.set(0,1.55,3.4),this._viewer.defaultCamera.lookAt(0,1.2,0),this._viewer.controls.target.set(0,1.2,0),this._viewer.controls.update();try{this._viewer.updateLights?.()}catch{}try{this._viewer.updateEnvironment?.()}catch{}this._viewer.invalidate(),this._initialized=!0}}registerAgent(e,{id:t,group:n,manifest:s}){const r=this._uniqueId(t||s?.name||"agent"),a={id:r,element:e,group:n,manifest:s};return this._agents.push(a),this._viewer?.scene.add(n),this._repositionAll(),this.dispatchEvent(new CustomEvent("stage:agent-joined",{detail:{agentId:r,element:e,manifest:s},bubbles:!0,composed:!0})),r}unregisterAgent(e){const t=this._agents.findIndex(s=>s.element===e);if(t<0)return;const[n]=this._agents.splice(t,1);try{this._viewer?.scene.remove(n.group)}catch{}q2(n.group),this._repositionAll(),this.dispatchEvent(new CustomEvent("stage:agent-left",{detail:{agentId:n.id,element:n.element},bubbles:!0,composed:!0}))}_uniqueId(e){let t=e,n=1;const s=new Set(this._agents.map(r=>r.id));for(;s.has(t);)t=`${e}-${n++}`;return t}getAgents(){return this._agents.map(({id:e,group:t,manifest:n,element:s})=>({agentId:e,name:n?.name||e,position:[+t.position.x.toFixed(3),+t.position.y.toFixed(3),+t.position.z.toFixed(3)],element:s}))}broadcast(e,t){const n={from:e,event:t};for(const s of this._agents)s.id!==e&&s.element.dispatchEvent(new CustomEvent("stage:message",{detail:n}));this.dispatchEvent(new CustomEvent("stage:message",{detail:n,bubbles:!0,composed:!0}))}async routeMessage(e,t,n){const s=this._agents.find(r=>r.id===t);if(!s)return{ok:!1,error:`No agent "${t}" on stage`};try{return{ok:!0,reply:(await s.element.say(`[from ${e}] ${n}`))?.text||""}}catch(r){return{ok:!1,error:r?.message||String(r)}}}async addAgent(e){const t=document.createElement("agent-3d");return e&&typeof e=="object"&&(t._inlineManifest=e),t.hasAttribute("eager")||t.setAttribute("eager",""),this.appendChild(t),t}removeAgent(e){const t=this._agents.find(n=>n.id===e);t&&t.element.remove()}_repositionAll(){const e=this._agents.length;if(!(!e||!this._viewer)){for(let t=0;t<e;t++){const{element:n,group:s,manifest:r}=this._agents[t],a=this._slotFor(t,e);s.position.copy(a.world),s.lookAt(0,a.world.y+1,a.world.z+5),n.style.position="absolute",n.style.left=a.dom.left,n.style.top=a.dom.top,n.style.width=a.dom.width,n.style.height=a.dom.height,n.style.pointerEvents="none"}this._viewer.invalidate()}}_slotFor(e,t){const n=this.formation,s=1/Math.max(t,1);if(n==="circle"){const o=e/t*Math.PI*2,c=Math.max(.8,.4*t);return{world:new G(Math.sin(o)*c,0,-Math.cos(o)*c+c*.5),dom:{left:`${e*s*100}%`,top:"0",width:`${s*100}%`,height:"100%"}}}if(n==="freeform")return{world:new G(0,0,0),dom:{left:"0",top:"0",width:"100%",height:"100%"}};const a=(e-(t-1)/2)*1.1;return{world:new G(a,0,0),dom:{left:`${e*s*100}%`,top:"0",width:`${s*100}%`,height:"100%"}}}}function q2(i){i.traverse(e=>{if(e.geometry)try{e.geometry.dispose()}catch{}if(e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const n of t){for(const s of Object.keys(n)){const r=n[s];if(r&&r.isTexture)try{r.dispose()}catch{}}try{n.dispose()}catch{}}}}),i.parent&&i.parent.remove(i)}customElements.get("agent-stage")||customElements.define("agent-stage",fy);const K2=(i="agent-3d")=>{customElements.get(i)||customElements.define(i,Gp)};on.Agent3DElement=Gp,on.AgentStageElement=fy,on.Memory=Bi,on.Runtime=Y0,on.SceneController=$0,on.Skill=nx,on.SkillRegistry=ix,on.Viewer=Bf,on.defineElement=K2,on.fetchRelative=ay,on.fetchWithFallback=J0,on.loadManifest=Ec,on.normalize=Oh,on.resolveURI=hs,Object.defineProperty(on,Symbol.toStringTag,{value:"Module"})}));
+`;class dy extends HTMLElement{static get observedAttributes(){return["formation"]}constructor(){super(),this.attachShadow({mode:"open"}),this._viewer=null,this._agents=[],this._initialized=!1}connectedCallback(){this._renderShell(),this._initViewer(),this._mo=new MutationObserver(()=>this._repositionAll()),this._mo.observe(this,{childList:!0})}disconnectedCallback(){try{this._mo?.disconnect()}catch{}for(const e of[...this._agents])this.unregisterAgent(e.element);try{this._viewer?.dispose?.()}catch{}this._viewer=null,this._initialized=!1}attributeChangedCallback(e){e==="formation"&&this._repositionAll()}get formation(){const e=this.getAttribute("formation")||"row";return z2.includes(e)?e:"row"}get viewer(){return this._viewer}_renderShell(){const e=document.createElement("style");e.textContent=V2,this.shadowRoot.appendChild(e);const t=document.createElement("div");t.className="stage-canvas",t.part="stage",this.shadowRoot.appendChild(t),this._canvasBox=t;const n=document.createElement("slot");this.shadowRoot.appendChild(n)}_initViewer(){if(!this._initialized){this._viewer=new Bf(this._canvasBox,{kiosk:!0}),this._viewer.defaultCamera.position.set(0,1.55,3.4),this._viewer.defaultCamera.lookAt(0,1.2,0),this._viewer.controls.target.set(0,1.2,0),this._viewer.controls.update();try{this._viewer.updateLights?.()}catch{}try{this._viewer.updateEnvironment?.()}catch{}this._viewer.invalidate(),this._initialized=!0}}registerAgent(e,{id:t,group:n,manifest:s}){const r=this._uniqueId(t||s?.name||"agent"),a={id:r,element:e,group:n,manifest:s};return this._agents.push(a),this._viewer?.scene.add(n),this._repositionAll(),this.dispatchEvent(new CustomEvent("stage:agent-joined",{detail:{agentId:r,element:e,manifest:s},bubbles:!0,composed:!0})),r}unregisterAgent(e){const t=this._agents.findIndex(s=>s.element===e);if(t<0)return;const[n]=this._agents.splice(t,1);try{this._viewer?.scene.remove(n.group)}catch{}W2(n.group),this._repositionAll(),this.dispatchEvent(new CustomEvent("stage:agent-left",{detail:{agentId:n.id,element:n.element},bubbles:!0,composed:!0}))}_uniqueId(e){let t=e,n=1;const s=new Set(this._agents.map(r=>r.id));for(;s.has(t);)t=`${e}-${n++}`;return t}getAgents(){return this._agents.map(({id:e,group:t,manifest:n,element:s})=>({agentId:e,name:n?.name||e,position:[+t.position.x.toFixed(3),+t.position.y.toFixed(3),+t.position.z.toFixed(3)],element:s}))}broadcast(e,t){const n={from:e,event:t};for(const s of this._agents)s.id!==e&&s.element.dispatchEvent(new CustomEvent("stage:message",{detail:n}));this.dispatchEvent(new CustomEvent("stage:message",{detail:n,bubbles:!0,composed:!0}))}async routeMessage(e,t,n){const s=this._agents.find(r=>r.id===t);if(!s)return{ok:!1,error:`No agent "${t}" on stage`};try{return{ok:!0,reply:(await s.element.say(`[from ${e}] ${n}`))?.text||""}}catch(r){return{ok:!1,error:r?.message||String(r)}}}async addAgent(e){const t=document.createElement("agent-3d");return e&&typeof e=="object"&&(t._inlineManifest=e),t.hasAttribute("eager")||t.setAttribute("eager",""),this.appendChild(t),t}removeAgent(e){const t=this._agents.find(n=>n.id===e);t&&t.element.remove()}_repositionAll(){const e=this._agents.length;if(!(!e||!this._viewer)){for(let t=0;t<e;t++){const{element:n,group:s,manifest:r}=this._agents[t],a=this._slotFor(t,e);s.position.copy(a.world),s.lookAt(0,a.world.y+1,a.world.z+5),n.style.position="absolute",n.style.left=a.dom.left,n.style.top=a.dom.top,n.style.width=a.dom.width,n.style.height=a.dom.height,n.style.pointerEvents="none"}this._viewer.invalidate()}}_slotFor(e,t){const n=this.formation,s=1/Math.max(t,1);if(n==="circle"){const o=e/t*Math.PI*2,c=Math.max(.8,.4*t);return{world:new G(Math.sin(o)*c,0,-Math.cos(o)*c+c*.5),dom:{left:`${e*s*100}%`,top:"0",width:`${s*100}%`,height:"100%"}}}if(n==="freeform")return{world:new G(0,0,0),dom:{left:"0",top:"0",width:"100%",height:"100%"}};const a=(e-(t-1)/2)*1.1;return{world:new G(a,0,0),dom:{left:`${e*s*100}%`,top:"0",width:`${s*100}%`,height:"100%"}}}}function W2(i){i.traverse(e=>{if(e.geometry)try{e.geometry.dispose()}catch{}if(e.material){const t=Array.isArray(e.material)?e.material:[e.material];for(const n of t){for(const s of Object.keys(n)){const r=n[s];if(r&&r.isTexture)try{r.dispose()}catch{}}try{n.dispose()}catch{}}}}),i.parent&&i.parent.remove(i)}customElements.get("agent-stage")||customElements.define("agent-stage",dy);const q2=(i="agent-3d")=>{customElements.get(i)||customElements.define(i,Gp)};on.Agent3DElement=Gp,on.AgentStageElement=dy,on.Memory=Bi,on.Runtime=Y0,on.SceneController=$0,on.Skill=nx,on.SkillRegistry=ix,on.Viewer=Bf,on.defineElement=q2,on.fetchRelative=ay,on.fetchWithFallback=J0,on.loadManifest=Ec,on.normalize=Oh,on.resolveURI=hs,Object.defineProperty(on,Symbol.toStringTag,{value:"Module"})}));
diff --git a/dist-lib/agent/index.html b/dist-lib/agent/index.html
index 11517c91a..e0e1009bb 100644
--- a/dist-lib/agent/index.html
+++ b/dist-lib/agent/index.html
@@ -437,6 +437,220 @@
margin: 0;
line-height: 1.5;
}
+
+ /* ── Manage Permissions Panel ────────────────────────────────────────── */
+
+ .mp-panel {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .mp-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0.618rem;
+ }
+
+ .mp-title {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ .mp-refresh-btn {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.3);
+ cursor: pointer;
+ padding: 0.2rem;
+ border-radius: 4px;
+ line-height: 0;
+ transition: color 0.15s;
+ }
+
+ .mp-refresh-btn:hover { color: rgba(255, 255, 255, 0.7); }
+
+ .mp-loading, .mp-error {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.3);
+ padding: 1rem 0;
+ }
+
+ .mp-error { color: #fca5a5; }
+
+ .mp-empty {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.3);
+ padding: 1rem 0;
+ text-align: center;
+ }
+
+ .mp-empty p { margin: 0 0 0.618rem; }
+
+ .mp-grant-btn {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.7);
+ font-size: 0.718rem;
+ font-family: inherit;
+ padding: 0.382rem 0.75rem;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+ }
+
+ .mp-grant-btn:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.95);
+ }
+
+ .mp-card {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 10px;
+ padding: 0.75rem 1rem;
+ margin-bottom: 0.618rem;
+ transition: border-color 0.2s;
+ }
+
+ .mp-card--active { border-color: rgba(134, 239, 172, 0.15); }
+ .mp-card--revoked { opacity: 0.5; }
+ .mp-card--expired { border-color: rgba(251, 191, 36, 0.15); }
+
+ .mp-card-top {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ margin-bottom: 0.382rem;
+ }
+
+ .mp-badge {
+ font-size: 0.618rem;
+ padding: 0.1rem 0.45rem;
+ border-radius: 999px;
+ font-weight: 500;
+ }
+
+ .mp-badge--active { background: rgba(134, 239, 172, 0.15); color: #86efac; }
+ .mp-badge--revoked { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.4); }
+ .mp-badge--expired { background: rgba(251, 191, 36, 0.12); color: #fbbf24; }
+
+ .mp-chain-chip {
+ font-size: 0.618rem;
+ background: rgba(255,255,255,0.07);
+ color: rgba(255,255,255,0.5);
+ padding: 0.1rem 0.45rem;
+ border-radius: 999px;
+ }
+
+ .mp-indexer-pending {
+ font-size: 0.618rem;
+ color: rgba(251, 191, 36, 0.7);
+ font-style: italic;
+ }
+
+ .mp-card-scope {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.8);
+ margin-bottom: 0.236rem;
+ line-height: 1.4;
+ }
+
+ .mp-card-hash {
+ font-size: 0.618rem;
+ font-family: monospace;
+ color: rgba(255, 255, 255, 0.25);
+ margin-bottom: 0.236rem;
+ }
+
+ .mp-card-usage {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.35);
+ margin-bottom: 0.5rem;
+ }
+
+ .mp-card-addresses {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ margin-bottom: 0.5rem;
+ }
+
+ .mp-addr-link {
+ font-size: 0.618rem;
+ font-family: monospace;
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ }
+
+ .mp-addr-link:hover { color: rgba(255, 255, 255, 0.8); }
+
+ .mp-addr-arrow {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.2);
+ }
+
+ .mp-card-actions { display: flex; gap: 0.5rem; }
+
+ .mp-revoke-btn {
+ background: rgba(239, 68, 68, 0.1);
+ border: 1px solid rgba(239, 68, 68, 0.25);
+ color: #f87171;
+ font-size: 0.718rem;
+ font-family: inherit;
+ padding: 0.3rem 0.7rem;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.15s;
+ }
+
+ .mp-revoke-btn:hover:not(:disabled) {
+ background: rgba(239, 68, 68, 0.2);
+ }
+
+ .mp-revoke-btn:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+
+ .mp-card-error {
+ font-size: 0.618rem;
+ color: #fca5a5;
+ margin-top: 0.382rem;
+ }
+
+ .mp-card-pending {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.5);
+ margin-top: 0.382rem;
+ }
+
+ .mp-tx-link {
+ color: rgba(255,255,255,0.4);
+ text-decoration: none;
+ }
+
+ .mp-tx-link:hover { color: rgba(255,255,255,0.8); }
+
+ @keyframes mp-spin {
+ to { transform: rotate(360deg); }
+ }
+
+ .mp-spinner {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ border: 1.5px solid rgba(255,255,255,0.15);
+ border-top-color: rgba(255,255,255,0.6);
+ border-radius: 50%;
+ animation: mp-spin 0.7s linear infinite;
+ }
</style>
</head>
<body>
@@ -456,6 +670,9 @@
</div>
</div>
+ <!-- Permissions panel (owner only, mounted by JS) -->
+ <div id="agent-permissions-mount"></div>
+
<!-- Skills catalog -->
<div class="agent-skills-full" id="agent-skills-section" style="display: none">
<div class="agent-skills-title">Skills</div>
@@ -498,6 +715,7 @@
import { AgentHome } from '/src/agent-home.js';
import { protocol } from '/src/agent-protocol.js';
import { renderHubActions } from '/src/agent-hub-actions.js';
+ import { mountManagePanel } from '/src/permissions/manage-panel.js';
// Pull agent id from URL: /agent/:id
const agentId = location.pathname.split('/').filter(Boolean).pop();
@@ -540,6 +758,10 @@
if (isOwner) {
const panel = container.querySelector('.agent-home-panel');
if (panel) renderHubActions(panel, identity, rawAgent);
+
+ // Mount the permissions management panel below the agent card
+ const permMount = document.getElementById('agent-permissions-mount');
+ if (permMount) mountManagePanel({ container: permMount, agentId });
}
// Render skills catalog
diff --git a/dist-lib/dashboard/index.html b/dist-lib/dashboard/index.html
index 3299709d8..f3344ae7b 100644
--- a/dist-lib/dashboard/index.html
+++ b/dist-lib/dashboard/index.html
@@ -646,6 +646,7 @@
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
></script>
+ <script type="module" src="/session-client.js"></script>
</head>
<body>
<header>
diff --git a/dist-lib/lobehub/iframe/index.html b/dist-lib/lobehub/iframe/index.html
index ac90ba666..5a777d6de 100644
--- a/dist-lib/lobehub/iframe/index.html
+++ b/dist-lib/lobehub/iframe/index.html
@@ -42,7 +42,12 @@
const CDN = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';
const h = location.hostname;
const isLocal = h === 'localhost' || h === '127.0.0.1' || h.endsWith('.github.dev') || h.endsWith('.local');
- import(isLocal ? '/src/lib.js' : CDN);
+ if (isLocal) {
+ const { defineElement } = await import('/src/lib.js');
+ defineElement();
+ } else {
+ await import(CDN);
+ }
</script>
</head>
<body>
diff --git a/dist-lib/login.html b/dist-lib/login.html
index 72e521536..56ea7b494 100644
--- a/dist-lib/login.html
+++ b/dist-lib/login.html
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Sign in · 3D Agent</title>
<link rel="icon" href="/favicon.ico" />
- <meta name="privy-app-id" content="" />
+ <link rel="stylesheet" href="/wallet-connect.css" />
<style>
:root {
color-scheme: dark;
@@ -111,21 +111,6 @@
color: var(--accent);
margin: 0 0 8px;
}
- .wallet-btn {
- background: #1c1c28;
- border: 1px solid #2a2a36;
- color: #eee;
- font-weight: 500;
- margin-top: 12px;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 8px;
- }
- .wallet-btn:hover {
- background: #22222e;
- border-color: var(--accent);
- }
.divider {
display: flex;
align-items: center;
@@ -143,10 +128,6 @@
height: 1px;
background: #2a2a36;
}
- .wallet-icon {
- width: 18px;
- height: 18px;
- }
</style>
</head>
<body>
@@ -166,45 +147,7 @@
/>
<button id="submit" type="submit">Sign in</button>
<div class="divider">or</div>
- <button
- id="privy"
- type="button"
- class="wallet-btn"
- style="
- background: linear-gradient(135deg, var(--accent), var(--accent2));
- border-color: transparent;
- color: #fff;
- "
- >
- <svg
- class="wallet-icon"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <circle cx="12" cy="8" r="4" />
- <path d="M20 21a8 8 0 0 0-16 0" />
- </svg>
- Sign in with Privy
- </button>
- <button id="wallet" type="button" class="wallet-btn">
- <svg
- class="wallet-icon"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <rect x="2" y="6" width="20" height="14" rx="2" />
- <path d="M16 12h2" />
- </svg>
- Sign in with MetaMask
- </button>
+ <div id="wallet-mount"></div>
<div class="err" id="err"></div>
<p class="foot">No account? <a href="/register">Create one</a></p>
</form>
diff --git a/dist-lib/session-client.js b/dist-lib/session-client.js
new file mode 100644
index 000000000..e122c73cb
--- /dev/null
+++ b/dist-lib/session-client.js
@@ -0,0 +1,114 @@
+// Wallet-disconnect UX for pages where the user is already signed in.
+// Listens for MetaMask accountsChanged events and shows a non-blocking toast
+// prompting sign-out if the wallet that was used to SIWE-auth disconnects.
+//
+// Add to authenticated pages:
+// <script type="module" src="/session-client.js"></script>
+//
+// Does NOT auto-sign-out — SIWE proved ownership at sign-in; the user may
+// intentionally disconnect for privacy. The choice is always theirs.
+
+(function initSessionClient() {
+ if (!window.ethereum) return;
+
+ // Fetch the current session address once so we can detect relevant disconnects.
+ let siweAddress = null;
+ fetch('/api/auth/me', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => {
+ // me.js returns { user: { wallet_address, ... } } — use that if present.
+ siweAddress = data?.user?.wallet_address?.toLowerCase() || null;
+ })
+ .catch(() => {});
+
+ let toastEl = null;
+
+ function showDisconnectToast() {
+ if (toastEl) return; // already showing
+
+ toastEl = document.createElement('div');
+ toastEl.setAttribute('role', 'status');
+ toastEl.setAttribute('aria-live', 'polite');
+ Object.assign(toastEl.style, {
+ position: 'fixed',
+ bottom: '20px',
+ right: '20px',
+ background: '#1c1c28',
+ border: '1px solid #2a2a36',
+ borderRadius: '10px',
+ padding: '12px 16px',
+ color: '#eee',
+ fontSize: '14px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ zIndex: '9999',
+ boxShadow: '0 4px 24px rgba(0,0,0,0.5)',
+ maxWidth: '340px',
+ });
+
+ const msg = document.createElement('span');
+ msg.textContent = 'MetaMask disconnected — you\u2019re still signed in.';
+
+ const signOutBtn = document.createElement('button');
+ signOutBtn.textContent = 'Sign out';
+ Object.assign(signOutBtn.style, {
+ background: 'transparent',
+ border: '1px solid #3a3a4a',
+ borderRadius: '6px',
+ color: '#9a8cff',
+ cursor: 'pointer',
+ padding: '4px 10px',
+ fontSize: '13px',
+ whiteSpace: 'nowrap',
+ });
+ signOutBtn.onclick = () => {
+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(() => {
+ location.href = '/login';
+ });
+ };
+
+ const dismissBtn = document.createElement('button');
+ dismissBtn.textContent = '×';
+ dismissBtn.setAttribute('aria-label', 'Dismiss');
+ Object.assign(dismissBtn.style, {
+ background: 'transparent',
+ border: 'none',
+ color: '#666',
+ cursor: 'pointer',
+ fontSize: '18px',
+ padding: '0 2px',
+ lineHeight: '1',
+ });
+ dismissBtn.onclick = () => dismissToast();
+
+ toastEl.appendChild(msg);
+ toastEl.appendChild(signOutBtn);
+ toastEl.appendChild(dismissBtn);
+ document.body.appendChild(toastEl);
+ }
+
+ function dismissToast() {
+ if (toastEl) {
+ toastEl.remove();
+ toastEl = null;
+ }
+ }
+
+ function onAccountsChanged(accounts) {
+ if (accounts.length === 0) {
+ // Wallet fully disconnected — show toast only if this session used SIWE.
+ // If siweAddress is null the user logged in via email; no toast needed.
+ if (siweAddress) showDisconnectToast();
+ } else {
+ // Wallet reconnected or account switched — dismiss any toast.
+ dismissToast();
+ siweAddress = accounts[0].toLowerCase();
+ }
+ }
+
+ window.ethereum.on('accountsChanged', onAccountsChanged);
+ window.addEventListener('pagehide', () => {
+ window.ethereum?.removeListener('accountsChanged', onAccountsChanged);
+ });
+})();
diff --git a/dist-lib/skills-index.json b/dist-lib/skills-index.json
index bdd8084de..0a757ce24 100644
--- a/dist-lib/skills-index.json
+++ b/dist-lib/skills-index.json
@@ -22,5 +22,14 @@
"version": "0.3.0",
"uri": "https://skills.3d-agent.io/[email protected]",
"author": "3d-agent"
+ },
+ {
+ "id": "dca",
+ "name": "DCA",
+ "description": "Dollar-cost average USDC into WETH on a schedule via Uniswap V3.",
+ "version": "0.1.0",
+ "uri": "skills/dca/",
+ "author": "3d-agent",
+ "tags": ["defi", "uniswap", "metamask", "permissions"]
}
]
diff --git a/dist-lib/skills/dca/SKILL.md b/dist-lib/skills/dca/SKILL.md
new file mode 100644
index 000000000..fc93b0d4d
--- /dev/null
+++ b/dist-lib/skills/dca/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: dca
+version: 0.1.0
+description: Dollar-cost average a fixed USDC amount into WETH on a recurring schedule via Uniswap V3.
+trust: owned-only
+permissions_required: true
+default_scope_preset:
+ token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+ maxAmount: "100000000"
+ period: "daily"
+ targets:
+ - "0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"
+ - "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+ selectors:
+ - "0x04e45aaf"
+ - "0x095ea7b3"
+ expiry_days: 30
+---
+
+# DCA (Dollar-Cost Averaging)
+
+You help the owner set up an automated dollar-cost averaging strategy that periodically swaps
+a fixed USDC amount into WETH using Uniswap V3 on Base Sepolia.
+
+## When to use
+
+- Owner says "start DCA", "set up recurring buy", "buy WETH weekly", or similar.
+- Owner asks to list, pause, or cancel their DCA strategies.
+
+## Actions
+
+Call `start_dca` when the owner wants to configure a new strategy. It will:
+1. Prompt for amount (USDC), token out (default WETH), and frequency.
+2. Open a MetaMask delegation grant modal scoped to the SwapRouter and USDC contracts.
+3. Store the strategy once the delegation is signed.
+
+Call `list_dca_strategies` to show the owner their active strategies.
+
+Call `stop_dca` when the owner wants to cancel a strategy by ID.
+
+## Safety rules (always follow)
+
+- Only the agent owner may call these tools. Refuse if the caller is not the owner.
+- Default slippage is 0.5% (50 bps). Never accept slippage_bps > 500.
+- Network defaults to Base Sepolia (chainId 84532). Require explicit owner confirmation to use mainnet (chainId 8453).
+- Never reveal delegation private keys or relayer tokens.
diff --git a/dist-lib/skills/dca/manifest.json b/dist-lib/skills/dca/manifest.json
new file mode 100644
index 000000000..2d815a424
--- /dev/null
+++ b/dist-lib/skills/dca/manifest.json
@@ -0,0 +1,19 @@
+{
+ "spec": "skill/0.1",
+ "name": "dca",
+ "version": "0.1.0",
+ "description": "Dollar-cost averaging: swap a fixed USDC amount into WETH on a schedule via Uniswap V3.",
+ "author": "3d-agent",
+ "license": "MIT",
+ "tags": ["defi", "dca", "uniswap", "metamask", "permissions"],
+ "trust": "owned-only",
+ "requires": {
+ "rig": ["any"],
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": ["start_dca", "list_dca_strategies", "stop_dca"],
+ "triggers": ["dca", "recurring_swap", "dollar_cost_average"]
+ }
+}
diff --git a/dist-lib/skills/dca/skill.js b/dist-lib/skills/dca/skill.js
new file mode 100644
index 000000000..f6c10090b
--- /dev/null
+++ b/dist-lib/skills/dca/skill.js
@@ -0,0 +1,189 @@
+// DCA skill — client-side setup and execute handlers.
+// Server-side execution (onPeriod) lives in api/cron/run-dca.js.
+
+// ── Per-chain config ──────────────────────────────────────────────────────────
+
+const CHAIN_CONFIG = {
+ // Base Sepolia — default for all v0.1 strategies
+ 84532: {
+ name: 'Base Sepolia',
+ swap_router: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
+ quoter_v2: '0xC5290058841028F1614F3A6F0F5816cAd0df5E27',
+ usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
+ tokens: {
+ WETH: '0x4200000000000000000000000000000000000006',
+ cbBTC: null, // not deployed on Sepolia
+ USDT: null,
+ },
+ },
+ // Base Mainnet — requires explicit owner opt-in
+ 8453: {
+ name: 'Base Mainnet',
+ swap_router: '0x2626664c2603336E57B271c5C0b26F421741e481',
+ quoter_v2: '0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a',
+ usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ tokens: {
+ WETH: '0x4200000000000000000000000000000000000006',
+ cbBTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
+ },
+ },
+};
+
+// ERC-20 USDC has 6 decimals
+const USDC_DECIMALS = 6;
+
+// Function selectors
+const SEL_EXACT_INPUT_SINGLE = '0x04e45aaf';
+const SEL_APPROVE = '0x095ea7b3';
+
+// ── Scope preset builder ──────────────────────────────────────────────────────
+
+function buildScopePreset(chainId, amountPerExecution, periodSeconds) {
+ const cfg = CHAIN_CONFIG[chainId];
+ return {
+ token: cfg.usdc,
+ maxAmount: amountPerExecution,
+ period: periodSeconds <= 86400 ? 'daily' : 'weekly',
+ targets: [cfg.swap_router, cfg.usdc],
+ selectors: [SEL_EXACT_INPUT_SINGLE, SEL_APPROVE],
+ expiry_days: 30,
+ };
+}
+
+// ── setup ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Called once when the skill loads. Registers a "Start DCA" action visible only
+ * to the agent owner.
+ * @param {{ agent: object, host: object }} ctx
+ */
+export function setup({ agent, host }) {
+ if (!host?.registerOwnerAction) return;
+ host.registerOwnerAction({
+ id: 'start_dca',
+ label: 'Start DCA',
+ description: 'Set up an automated USDC → WETH recurring swap via Uniswap V3.',
+ icon: '🔄',
+ handler: (args) => execute({ agent, host, args }),
+ });
+}
+
+// ── execute ───────────────────────────────────────────────────────────────────
+
+/**
+ * Owner-facing: prompts for config, opens grant modal, stores strategy.
+ * @param {{ agent: object, host: object, args: object }} ctx
+ */
+export async function execute({ agent, host, args = {} }) {
+ const {
+ amount_usdc = '10',
+ token_out = 'WETH',
+ frequency = 'daily',
+ slippage_bps = 50,
+ chain_id = 84532,
+ } = args;
+
+ // Mainnet guard — require explicit confirmation
+ if (chain_id === 8453) {
+ const confirmed = await host?.confirm(
+ 'You are about to set up a DCA strategy on Base Mainnet with real funds. Confirm?',
+ );
+ if (!confirmed) return { ok: false, code: 'mainnet_not_confirmed' };
+ }
+
+ const cfg = CHAIN_CONFIG[chain_id];
+ if (!cfg) return { ok: false, code: 'unsupported_chain', message: `Chain ${chain_id} not supported` };
+
+ const tokenOutAddress = cfg.tokens[token_out];
+ if (!tokenOutAddress) {
+ return {
+ ok: false,
+ code: 'unsupported_token',
+ message: `${token_out} is not available on ${cfg.name}`,
+ };
+ }
+
+ // Clamp slippage
+ const slippage = Math.min(500, Math.max(10, Number(slippage_bps)));
+
+ // Convert USDC amount to 6-decimal wei
+ const amountPerExecution = String(
+ Math.round(parseFloat(amount_usdc) * 10 ** USDC_DECIMALS),
+ );
+
+ const periodSeconds = frequency === 'weekly' ? 7 * 86400 : 86400;
+
+ const scopePreset = buildScopePreset(chain_id, amountPerExecution, periodSeconds);
+
+ // Open delegation grant modal
+ let delegationId;
+ try {
+ const grant = await host.openGrantModal({
+ scope: scopePreset,
+ description: `Allow agent to swap ${amount_usdc} USDC → ${token_out} ${frequency} for 30 days`,
+ });
+ if (!grant?.delegationId) {
+ return { ok: false, code: 'grant_cancelled', message: 'Grant was not signed' };
+ }
+ delegationId = grant.delegationId;
+ } catch (err) {
+ return { ok: false, code: 'grant_error', message: err.message };
+ }
+
+ // Store strategy server-side
+ const res = await fetch('/api/dca-strategies', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ agent_id: agent.id,
+ delegation_id: delegationId,
+ token_in: cfg.usdc,
+ token_out: tokenOutAddress,
+ token_out_symbol: token_out,
+ amount_per_execution: amountPerExecution,
+ period_seconds: periodSeconds,
+ slippage_bps: slippage,
+ chain_id,
+ }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ return { ok: false, code: body.error || 'api_error', message: body.error_description };
+ }
+
+ const data = await res.json();
+ return {
+ ok: true,
+ strategy_id: data.id,
+ message: `DCA strategy created — ${amount_usdc} USDC → ${token_out} ${frequency} on ${cfg.name}.`,
+ };
+}
+
+// ── Tool handlers (LLM-callable) ──────────────────────────────────────────────
+
+export async function start_dca(args, ctx) {
+ return execute({ agent: ctx.agent, host: ctx.host, args });
+}
+
+export async function list_dca_strategies(args, ctx) {
+ const agentId = args.agent_id || ctx.agent?.id;
+ if (!agentId) return { ok: false, error: 'agent_id required' };
+
+ const res = await ctx.fetch(`/api/dca-strategies?agent_id=${encodeURIComponent(agentId)}`);
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ return res.json();
+}
+
+export async function stop_dca(args, ctx) {
+ const { strategy_id } = args;
+ if (!strategy_id) return { ok: false, error: 'strategy_id required' };
+
+ const res = await ctx.fetch(`/api/dca-strategies/${encodeURIComponent(strategy_id)}`, {
+ method: 'DELETE',
+ });
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ return { ok: true };
+}
diff --git a/dist-lib/skills/dca/tools.json b/dist-lib/skills/dca/tools.json
new file mode 100644
index 000000000..99e42f90c
--- /dev/null
+++ b/dist-lib/skills/dca/tools.json
@@ -0,0 +1,71 @@
+{
+ "tools": [
+ {
+ "name": "start_dca",
+ "description": "Configure a new dollar-cost averaging strategy. Opens the MetaMask delegation grant modal and stores the strategy once the owner signs.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "amount_usdc": {
+ "type": "string",
+ "description": "USDC amount per execution in human-readable form, e.g. '10' for 10 USDC."
+ },
+ "token_out": {
+ "type": "string",
+ "enum": ["WETH", "cbBTC", "USDT"],
+ "default": "WETH",
+ "description": "Token to receive."
+ },
+ "frequency": {
+ "type": "string",
+ "enum": ["daily", "weekly"],
+ "default": "daily",
+ "description": "How often to execute the swap."
+ },
+ "slippage_bps": {
+ "type": "integer",
+ "minimum": 10,
+ "maximum": 500,
+ "default": 50,
+ "description": "Slippage tolerance in basis points (50 = 0.5%)."
+ },
+ "chain_id": {
+ "type": "integer",
+ "enum": [84532, 8453],
+ "default": 84532,
+ "description": "Chain to execute on. 84532 = Base Sepolia (default), 8453 = Base Mainnet (requires extra confirmation)."
+ }
+ },
+ "required": ["amount_usdc"]
+ }
+ },
+ {
+ "name": "list_dca_strategies",
+ "description": "List the owner's active DCA strategies.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "agent_id": {
+ "type": "string",
+ "description": "Agent ID to query strategies for."
+ }
+ },
+ "required": ["agent_id"]
+ }
+ },
+ {
+ "name": "stop_dca",
+ "description": "Cancel an active DCA strategy by ID.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "strategy_id": {
+ "type": "string",
+ "description": "UUID of the strategy to cancel."
+ }
+ },
+ "required": ["strategy_id"]
+ }
+ }
+ ]
+}
diff --git a/dist-lib/skills/subscription/SKILL.md b/dist-lib/skills/subscription/SKILL.md
new file mode 100644
index 000000000..e6366d970
--- /dev/null
+++ b/dist-lib/skills/subscription/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: subscription
+version: 0.1.0
+trust: owned-only
+permissions_required: true
+default_scope_preset:
+ token: "<USDC>"
+ maxAmount: "5000000"
+ period: "weekly"
+ targets: ["<subscription executor contract>"]
+ expiry_days: 90
+---
+
+# Subscription
+
+Allow a viewer to subscribe to this agent for recurring USDC payments. The agent charges 5 USDC per week automatically — no re-signing needed — until the viewer revokes or the delegation expires (90 days).
+
+## Flow
+
+1. Viewer clicks **Subscribe · 5 USDC / week**.
+2. MetaMask opens pre-filled with the scope (5 USDC / week cap, 90-day expiry).
+3. Viewer approves once. No further wallet prompts.
+4. The server cron fires every hour; weekly charges are applied automatically via the ERC-7710 relayer.
+5. Viewer can revoke at any time from the Manage panel — this pauses the subscription.
+
+## onPeriod
+
+`onPeriod` is **server-side only**. The cron at `/api/cron/run-subscriptions` imports it via dynamic `import()` and calls it once per subscription per period. It builds a single ERC-20 `transfer` call for `amountPerPeriod` and redeems it through the relayer endpoint.
+
+**Never call `onPeriod` from the browser.**
+
+## Error behaviour
+
+- Revoked delegation → subscription status flips to `paused`, visible in the Manage panel.
+- Expired delegation → same.
+- Failed redemption → `paused` + `last_error` stored; no silent retry.
diff --git a/dist-lib/skills/subscription/skill.js b/dist-lib/skills/subscription/skill.js
new file mode 100644
index 000000000..5f29ca91e
--- /dev/null
+++ b/dist-lib/skills/subscription/skill.js
@@ -0,0 +1,182 @@
+/**
+ * Subscription skill — recurring USDC payments via ERC-7710 delegation.
+ *
+ * Exports:
+ * setup — browser: attach "Subscribe" action to agent UI
+ * execute — browser: open grant modal, register subscription via API
+ * onPeriod — server-side only: charge the period amount via the relayer
+ *
+ * onPeriod is imported by api/cron/run-subscriptions.js via dynamic import.
+ * It must never be invoked from a browser context.
+ */
+
+const SKILL_ID = 'subscription';
+
+// USDC contract addresses by chain ID.
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
+};
+
+/**
+ * Build an ERC-20 transfer(address,uint256) calldata bundle.
+ * Pure function — no imports required.
+ *
+ * @param {string} tokenAddr - ERC-20 contract address
+ * @param {string} recipient - recipient address (EIP-55 or lowercase)
+ * @param {string} amountBaseUnits - amount in base units (string)
+ * @returns {{ to: string, value: string, data: string }}
+ */
+export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
+ // transfer(address,uint256) selector
+ const selector = 'a9059cbb';
+ const paddedAddr = recipient.toLowerCase().replace('0x', '').padStart(64, '0');
+ const paddedAmt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
+ return {
+ to: tokenAddr,
+ value: '0',
+ data: '0x' + selector + paddedAddr + paddedAmt,
+ };
+}
+
+/**
+ * Attaches the "Subscribe · 5 USDC / week" action to the agent UI.
+ *
+ * @param {{ agent: object, host: object }} opts
+ */
+export async function setup({ agent, host }) {
+ host.attachAction({
+ id: SKILL_ID,
+ label: 'Subscribe · 5 USDC / week',
+ skillId: SKILL_ID,
+ });
+}
+
+/**
+ * Viewer's initial subscription action — runs in the browser only.
+ *
+ * 1. Opens the grant modal pre-filled with the weekly 5 USDC scope.
+ * 2. On successful grant, POSTs to /api/subscriptions.
+ * 3. Confirms in chat with the expiry date.
+ *
+ * @param {{ agent: object, host: object, args: object }} opts
+ */
+export async function execute({ agent, host, args }) {
+ const agentId = agent.agentId ?? agent.id;
+ const chainId = agent.chainId ?? 84532;
+
+ const scopePreset = {
+ token: USDC_BY_CHAIN[chainId] ?? USDC_BY_CHAIN[84532],
+ maxAmount: '5000000',
+ period: 'weekly',
+ targets: [],
+ expiry_days: 90,
+ };
+
+ let delegation;
+ try {
+ const { openGrantModal } = await import('../../src/permissions/grant-modal.js');
+ delegation = await openGrantModal({ agent, scopePreset });
+ } catch {
+ host.speak('Permission request is not available in this context.');
+ return { ok: false, code: 'modal_unavailable' };
+ }
+
+ if (!delegation) {
+ host.speak('Subscription cancelled.');
+ return { ok: false, code: 'user_cancelled' };
+ }
+
+ const periodSeconds = 7 * 24 * 3600;
+
+ try {
+ const res = await fetch('/api/subscriptions', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ agentId,
+ delegationId: delegation.id,
+ periodSeconds,
+ amountPerPeriod: scopePreset.maxAmount,
+ }),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error_description ?? `HTTP ${res.status}`);
+ }
+
+ const expiry = new Date(Date.now() + 90 * 24 * 3600 * 1000).toLocaleDateString();
+ host.speak(`You're subscribed until ${expiry}. Revoke anytime in the Manage panel.`);
+ return { ok: true };
+ } catch (err) {
+ host.speak('Failed to record subscription. Please try again.');
+ return { ok: false, code: 'api_error', message: err.message };
+ }
+}
+
+/**
+ * Periodic charge handler — server-side only, called by api/cron/run-subscriptions.js.
+ *
+ * Builds a single ERC-20 transfer call for amountPerPeriod and redeems it
+ * through the relayer endpoint (equivalent to redeemFromSkill with mode:'relayer').
+ *
+ * @param {{
+ * agent: {
+ * agentId: string,
+ * chainId: number,
+ * ownerAddress: string,
+ * usdcAddress: string,
+ * relayerToken: string,
+ * origin: string,
+ * },
+ * subscription: {
+ * id: string,
+ * delegationId: string,
+ * amountPerPeriod: string,
+ * }
+ * }} opts
+ * @returns {Promise<{ ok: boolean, txHash?: string, code?: string, message?: string }>}
+ */
+export async function onPeriod({ agent, subscription }) {
+ const { agentId, chainId, ownerAddress, usdcAddress, relayerToken, origin } = agent;
+ const { delegationId, amountPerPeriod } = subscription;
+
+ const call = buildERC20Transfer(usdcAddress, ownerAddress, amountPerPeriod);
+
+ let res;
+ try {
+ res = await fetch(`${origin}/api/permissions/redeem`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${relayerToken}`,
+ },
+ body: JSON.stringify({
+ id: delegationId,
+ calls: [call],
+ agentId,
+ chainId: String(chainId),
+ skillId: SKILL_ID,
+ }),
+ });
+ } catch (err) {
+ return { ok: false, code: 'fetch_error', message: err.message };
+ }
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ return {
+ ok: false,
+ code: body.error ?? `http_${res.status}`,
+ message: body.error_description ?? `HTTP ${res.status}`,
+ };
+ }
+
+ const data = await res.json().catch(() => ({}));
+ if (!data.txHash) {
+ return { ok: false, code: 'no_tx_hash', message: 'Relayer returned no txHash' };
+ }
+
+ return { ok: true, txHash: data.txHash };
+}
diff --git a/dist-lib/skills/tip-jar/README.md b/dist-lib/skills/tip-jar/README.md
new file mode 100644
index 000000000..bc81e18c7
--- /dev/null
+++ b/dist-lib/skills/tip-jar/README.md
@@ -0,0 +1,101 @@
+# Tip Jar Skill
+
+Lets a viewer send a USDC tip directly to the agent's creator wallet via an
+ERC-7710 scoped delegation — no intermediary custody, no wallet pop-up after the
+initial grant.
+
+## Scope requested
+
+| Field | Value |
+| ----------- | -------------------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract on the active chain |
+| expiry_days | 30 |
+
+Base Sepolia USDC: `0x036CbD53842c5426634e7929541eC2318f3dCF7e`
+
+## Happy-path flow
+
+```
+Viewer clicks "Tip the creator"
+ │
+ ▼
+Amount picker (1 / 5 / 10 USDC or custom ≤ 10)
+ │ viewer selects amount
+ ▼
+buildERC20Transfer(usdcAddr, agent.ownerAddress, amountBaseUnits)
+ → { to: usdcAddr, value: '0x0', data: 0xa9059cbb + paddedAddr + paddedAmt }
+ │
+ ▼
+redeemFromSkill({ agentId, chainId, skillId: 'tip-jar', calls: [call] })
+ │
+ ▼
+DelegationManager.redeemDelegations() on Base Sepolia (ERC-7710)
+ │
+ ▼
+USDC transfer: viewer delegated wallet → agent.ownerAddress ✓
+ │
+ ▼
+host.speak("Thank you for the tip!")
+protocol.emit({ type: 'tip.received', payload: { agentId, amountUsdc, txHash } })
+```
+
+## No-delegation path
+
+```
+redeemFromSkill → error: no_delegation
+ │
+ ├─ viewer is NOT owner → "The creator hasn't enabled tipping on this device yet."
+ │
+ └─ viewer IS owner → attachAction("Grant tipping")
+ │
+ ▼
+ openGrantModal({ preset: { token, maxAmount: '10000000', ... } })
+ │
+ ▼
+ MetaMask ERC-7715 permission request
+ │
+ ▼
+ delegation stored → tip flow retried
+```
+
+## ERC-20 calldata format
+
+```
+selector : 0xa9059cbb (keccak256("transfer(address,uint256)")[0:4])
+arg[0] : recipient address, zero-padded left to 32 bytes
+arg[1] : amount in base units, big-endian uint256 padded to 32 bytes
+
+Example — 5 USDC to 0x1234...5678:
+0xa9059cbb
+0000000000000000000000001234567890123456789012345678901234567890
+00000000000000000000000000000000000000000000000000000000004c4b40
+```
+
+## Files
+
+| File | Purpose |
+| ------------ | ------------------------------------------ |
+| `SKILL.md` | LLM instructions + scope declaration |
+| `manifest.json` | Skill metadata, sandboxPolicy, permissions |
+| `skill.js` | `setup` / `execute` exports + pure helpers |
+| `skill.css` | Tip-amount picker modal styles |
+
+## Dependencies (lazy-loaded at runtime)
+
+- **task 13** — `src/runtime/delegation-redeem.js` → `redeemFromSkill`
+- **task 10** — `src/permissions/grant-modal.js` → `openGrantModal`
+
+If either module is absent the skill degrades gracefully: it loads without errors
+and surfaces a human-readable message instead of crashing.
+
+## Skill registry
+
+No standalone registry file exists in this repo. To activate the tip-jar for an
+agent, add an entry to that agent's `manifest.json` `skills` array:
+
+```json
+{ "uri": "/skills/tip-jar/", "version": "0.1.0" }
+```
diff --git a/dist-lib/skills/tip-jar/SKILL.md b/dist-lib/skills/tip-jar/SKILL.md
new file mode 100644
index 000000000..7481a9a79
--- /dev/null
+++ b/dist-lib/skills/tip-jar/SKILL.md
@@ -0,0 +1,41 @@
+---
+name: tip-jar
+version: 0.1.0
+description: Let viewers send a USDC tip directly to the agent creator.
+trust: owned-only
+permissions_required: true
+cost: medium
+triggers:
+ - tip_request
+ - viewer_appreciation
+default_scope_preset: '{"token":"chain-specific-usdc","maxAmount":"10000000","period":"daily","targets":["usdc-contract"],"expiry_days":30}'
+---
+
+# Tip Jar
+
+Allows viewers to send a USDC tip directly to the agent's creator wallet. No intermediary
+holds the funds — the ERC-7710 delegation redeems a transfer straight from the viewer's
+delegated allowance to `agent.ownerAddress`.
+
+When a viewer expresses appreciation or asks how to support the creator, invoke
+`tip_jar_send`. Tip options are 1, 5, or 10 USDC (up to the daily cap of 10 USDC).
+
+On success, thank the viewer warmly.
+
+## Scope requested
+
+| Field | Value |
+| ----------- | ----------------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract address on the active chain |
+| expiry_days | 30 |
+
+## Error cases
+
+- **no_delegation / delegation_not_found** — Creator hasn't granted tipping permissions.
+ Tell the viewer: "The creator hasn't enabled tipping on this device yet."
+ If the current viewer is the owner, surface a "Grant tipping" button.
+- **scope_exceeded** — Daily cap reached. Tell the viewer to try again tomorrow.
+- **delegation_expired / delegation_revoked** — Surface the error code to the viewer.
diff --git a/dist-lib/skills/tip-jar/manifest.json b/dist-lib/skills/tip-jar/manifest.json
new file mode 100644
index 000000000..f7aa7da51
--- /dev/null
+++ b/dist-lib/skills/tip-jar/manifest.json
@@ -0,0 +1,29 @@
+{
+ "spec": "skill/0.1",
+ "name": "tip-jar",
+ "version": "0.1.0",
+ "description": "Let viewers send a USDC tip directly to the agent creator via ERC-7710 delegation.",
+ "license": "MIT",
+ "tags": ["payments", "usdc", "erc7710", "tip"],
+ "sandboxPolicy": "trusted-main-thread",
+ "requires": {
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": [],
+ "triggers": ["tip_request"]
+ },
+ "permissions": {
+ "spec": "erc-7715/0.1",
+ "default_scope_preset": {
+ "token": {
+ "84532": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
+ "8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
+ },
+ "maxAmount": "10000000",
+ "period": "daily",
+ "expiry_days": 30
+ }
+ }
+}
diff --git a/dist-lib/skills/tip-jar/skill.css b/dist-lib/skills/tip-jar/skill.css
new file mode 100644
index 000000000..f62add60a
--- /dev/null
+++ b/dist-lib/skills/tip-jar/skill.css
@@ -0,0 +1,116 @@
+.tip-jar-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 9999;
+}
+
+.tip-jar-modal {
+ background: #1a1a2e;
+ border: 1px solid #334466;
+ border-radius: 12px;
+ padding: 24px;
+ min-width: 260px;
+ color: #e0e0f0;
+ font-family: inherit;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
+}
+
+.tip-jar-title {
+ margin: 0;
+ font-size: 1rem;
+ font-weight: 600;
+ text-align: center;
+}
+
+.tip-jar-options {
+ display: flex;
+ gap: 8px;
+ justify-content: center;
+}
+
+.tip-jar-btn {
+ flex: 1;
+ padding: 8px 4px;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ background: #222244;
+ color: #b0b8d8;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+}
+
+.tip-jar-btn:hover {
+ background: #2a2a5a;
+ color: #ffffff;
+}
+
+.tip-jar-btn.selected {
+ background: #4a4afa;
+ border-color: #7a7aff;
+ color: #ffffff;
+}
+
+.tip-jar-custom {
+ width: 100%;
+ padding: 8px 10px;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ background: #111122;
+ color: #e0e0f0;
+ font-size: 0.9rem;
+ box-sizing: border-box;
+ outline: none;
+}
+
+.tip-jar-custom:focus {
+ border-color: #7a7aff;
+}
+
+.tip-jar-footer {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+}
+
+.tip-jar-send {
+ padding: 8px 18px;
+ background: #4a4afa;
+ border: none;
+ border-radius: 8px;
+ color: #ffffff;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s;
+}
+
+.tip-jar-send:hover:not(:disabled) {
+ background: #6060ff;
+}
+
+.tip-jar-send:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.tip-jar-cancel {
+ padding: 8px 14px;
+ background: transparent;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ color: #aaaacc;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s;
+}
+
+.tip-jar-cancel:hover {
+ background: #222233;
+}
diff --git a/dist-lib/skills/tip-jar/skill.js b/dist-lib/skills/tip-jar/skill.js
new file mode 100644
index 000000000..6bd03ac69
--- /dev/null
+++ b/dist-lib/skills/tip-jar/skill.js
@@ -0,0 +1,266 @@
+/**
+ * tip-jar/skill.js — trusted-main-thread UI skill
+ *
+ * Attaches a "Tip the creator" button to the agent's chat UI and executes an
+ * ERC-7710 delegation redemption to transfer USDC directly to agent.ownerAddress.
+ *
+ * Runtime dependencies loaded lazily (tasks 10 + 13 must be deployed):
+ * /src/runtime/delegation-redeem.js → redeemFromSkill
+ * /src/permissions/grant-modal.js → openGrantModal
+ *
+ * Host contract (provided by the embedding runtime):
+ * host.attachAction({ id, label, icon, handler, oneShot? })
+ * host.speak(text)
+ * host.showMessage(text)
+ * host.isOwner — true when the current viewer owns this agent
+ */
+
+/** USDC contract addresses indexed by EVM chainId. */
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base mainnet
+};
+
+const TIP_OPTIONS = [1, 5, 10]; // USDC display amounts
+const USDC_DECIMALS = 6;
+
+// ── Pure helper ──────────────────────────────────────────────────────────────
+
+/**
+ * Build ERC-20 transfer calldata without any external dependency.
+ *
+ * Equivalent to:
+ * new Interface(['function transfer(address,uint256)'])
+ * .encodeFunctionData('transfer', [recipient, amountBaseUnits])
+ *
+ * ABI encoding:
+ * selector = keccak256("transfer(address,uint256)")[0..4] = 0xa9059cbb
+ * arg[0] = recipient address, zero-padded left to 32 bytes
+ * arg[1] = amountBaseUnits as big-endian uint256, zero-padded to 32 bytes
+ *
+ * @param {string} tokenAddr ERC-20 contract address (checksummed or lower)
+ * @param {string} recipient Destination address
+ * @param {string|bigint} amountBaseUnits Token-native units (e.g. 5000000 for 5 USDC)
+ * @returns {{ to: string, value: string, data: string }}
+ */
+export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
+ const addr = recipient.replace(/^0x/i, '').toLowerCase().padStart(64, '0');
+ const amt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
+ return {
+ to: tokenAddr,
+ value: '0x0',
+ data: '0xa9059cbb' + addr + amt,
+ };
+}
+
+// ── Skill lifecycle ──────────────────────────────────────────────────────────
+
+/**
+ * Called once when the skill is installed into an agent session.
+ * Attaches the tip button to the agent's action bar.
+ *
+ * @param {{ agent: Object, host: Object }} ctx
+ */
+export async function setup({ agent, host }) {
+ host.attachAction({
+ id: 'tip-jar:tip',
+ label: 'Tip the creator',
+ icon: '💝',
+ handler: () => execute({ agent, host, args: {} }),
+ });
+}
+
+/**
+ * Invoked when the viewer clicks "Tip the creator".
+ *
+ * @param {{ agent: Object, host: Object, args: Object }} ctx
+ */
+export async function execute({ agent, host, args: _args }) {
+ const chainId = agent.chainId ?? 84532;
+ const usdcAddr = USDC_BY_CHAIN[chainId];
+
+ if (!usdcAddr) {
+ _notify(host, `Chain ${chainId} is not supported for tipping.`);
+ return;
+ }
+
+ // 1. Ask viewer for amount
+ const amount = await _pickAmount();
+ if (amount === null) return; // cancelled
+
+ const amountBase = String(BigInt(Math.round(amount)) * BigInt(10 ** USDC_DECIMALS));
+ const call = buildERC20Transfer(usdcAddr, agent.ownerAddress, amountBase);
+
+ // 2. Lazy-load delegation-redeem (task 13)
+ let redeemFromSkill;
+ try {
+ ({ redeemFromSkill } = await import('/src/runtime/delegation-redeem.js'));
+ } catch {
+ _notify(host, 'Tipping is not available yet on this install.');
+ return;
+ }
+
+ // 3. Execute the delegated transfer
+ try {
+ const result = await redeemFromSkill({
+ agentId: agent.id,
+ chainId,
+ skillId: 'tip-jar',
+ calls: [call],
+ mode: 'auto',
+ });
+
+ if (!result.ok) {
+ const err = new Error(result.error);
+ err.code = result.error;
+ throw err;
+ }
+
+ // 4. Success
+ host.speak('Thank you for the tip!');
+ _emitTipReceived(agent, amount, result.txHash);
+ _notify(host, `Tip sent! Tx: ${result.txHash}`);
+
+ } catch (err) {
+ const code = err.code ?? err.message;
+
+ if (code === 'delegation_not_found' || code === 'no_delegation') {
+ await _handleNoDelegation({ agent, host, chainId, usdcAddr });
+ } else if (code === 'scope_exceeded') {
+ _notify(host, 'Daily tipping cap reached — try again tomorrow.');
+ } else {
+ _notify(host, `Tip failed: ${code}`);
+ }
+ }
+}
+
+// ── Private helpers ──────────────────────────────────────────────────────────
+
+/** Render a small amount-picker modal; resolves with the chosen number or null on cancel. */
+function _pickAmount() {
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'tip-jar-overlay';
+ overlay.innerHTML = `
+ <div class="tip-jar-modal">
+ <p class="tip-jar-title">Choose a tip amount</p>
+ <div class="tip-jar-options">
+ ${TIP_OPTIONS.map((v) => `<button class="tip-jar-btn" data-v="${v}">${v} USDC</button>`).join('')}
+ </div>
+ <input
+ class="tip-jar-custom"
+ type="number"
+ min="0.01"
+ max="10"
+ step="1"
+ placeholder="Custom (max 10 USDC)"
+ />
+ <div class="tip-jar-footer">
+ <button class="tip-jar-send" disabled>Send tip</button>
+ <button class="tip-jar-cancel">Cancel</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const sendBtn = overlay.querySelector('.tip-jar-send');
+ const cancelBtn = overlay.querySelector('.tip-jar-cancel');
+ const customInput = overlay.querySelector('.tip-jar-custom');
+ let selected = null;
+
+ const select = (val) => {
+ selected = val;
+ overlay.querySelectorAll('.tip-jar-btn').forEach(
+ (b) => b.classList.toggle('selected', Number(b.dataset.v) === val),
+ );
+ sendBtn.disabled = false;
+ };
+
+ overlay.querySelectorAll('.tip-jar-btn').forEach((btn) =>
+ btn.addEventListener('click', () => {
+ customInput.value = '';
+ select(Number(btn.dataset.v));
+ }),
+ );
+
+ customInput.addEventListener('input', () => {
+ const val = parseFloat(customInput.value);
+ if (val > 0 && val <= 10) {
+ overlay.querySelectorAll('.tip-jar-btn').forEach((b) => b.classList.remove('selected'));
+ select(val);
+ } else {
+ selected = null;
+ sendBtn.disabled = true;
+ }
+ });
+
+ const done = (val) => { document.body.removeChild(overlay); resolve(val); };
+ sendBtn.addEventListener('click', () => done(selected));
+ cancelBtn.addEventListener('click', () => done(null));
+ });
+}
+
+/**
+ * Handle the no-delegation error path.
+ * - Non-owner: display friendly copy.
+ * - Owner: surface a one-shot "Grant tipping" action that opens the grant modal.
+ */
+async function _handleNoDelegation({ agent, host, chainId, usdcAddr }) {
+ const baseMsg = "The creator hasn't enabled tipping on this device yet.";
+
+ if (!host.isOwner) {
+ _notify(host, baseMsg);
+ return;
+ }
+
+ // Owner only: load grant modal (task 10)
+ let openGrantModal;
+ try {
+ ({ openGrantModal } = await import('/src/permissions/grant-modal.js'));
+ } catch {
+ _notify(host, `${baseMsg} (Grant modal not available — task 10 pending.)`);
+ return;
+ }
+
+ host.attachAction({
+ id: 'tip-jar:grant',
+ label: 'Grant tipping',
+ icon: '🔑',
+ oneShot: true,
+ handler: () =>
+ openGrantModal({
+ agentId: agent.id,
+ chainId,
+ preset: {
+ token: usdcAddr,
+ maxAmount: '10000000',
+ period: 'daily',
+ targets: [usdcAddr],
+ expiry_days: 30,
+ },
+ }),
+ });
+
+ _notify(host, `${baseMsg} Click "Grant tipping" to enable it.`);
+}
+
+/** Emit tip.received on the global protocol bus (non-fatal if unavailable). */
+function _emitTipReceived(agent, amountUsdc, txHash) {
+ try {
+ const bus = globalThis.__agentProtocol ?? globalThis.VIEWER?.agent_protocol;
+ if (bus) {
+ bus.emit({
+ type: 'tip.received',
+ payload: { agentId: agent.id, amountUsdc, txHash },
+ agentId: agent.id,
+ sourceSkill: 'tip-jar',
+ });
+ }
+ } catch { /* protocol is optional */ }
+}
+
+/** Surface a message via host.showMessage if available, otherwise log. */
+function _notify(host, text) {
+ if (typeof host?.showMessage === 'function') host.showMessage(text);
+ else console.info('[tip-jar]', text);
+}
diff --git a/dist-lib/wallet-connect-demo.html b/dist-lib/wallet-connect-demo.html
new file mode 100644
index 000000000..ea3e2f7ff
--- /dev/null
+++ b/dist-lib/wallet-connect-demo.html
@@ -0,0 +1,115 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Wallet Connect — QA Demo</title>
+ <link rel="stylesheet" href="/wallet-connect.css" />
+ <style>
+ :root { color-scheme: dark; }
+ body {
+ font: 15px/1.5 system-ui, sans-serif;
+ background: #0b0b10;
+ color: #eee;
+ margin: 0;
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 32px;
+ padding: 32px;
+ }
+ h1 { margin: 0; font-size: 20px; }
+ .demo-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ gap: 24px;
+ width: 100%;
+ max-width: 800px;
+ }
+ .demo-card {
+ background: #14141c;
+ border: 1px solid #22222e;
+ border-radius: 12px;
+ padding: 20px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .demo-card h2 { margin: 0; font-size: 14px; color: #aaa; text-transform: uppercase; letter-spacing: 0.06em; }
+ .log {
+ font-size: 12px;
+ font-family: monospace;
+ color: #666;
+ min-height: 40px;
+ word-break: break-all;
+ }
+ </style>
+ </head>
+ <body>
+ <h1>Wallet Connect — QA Demo</h1>
+ <p style="color:#666;margin:0;font-size:13px;">Manual test page — not linked from site nav.</p>
+
+ <div class="demo-grid">
+ <div class="demo-card">
+ <h2>Sign in</h2>
+ <div id="mount-signin"></div>
+ <div class="log" id="log-signin">State: idle</div>
+ </div>
+ <div class="demo-card">
+ <h2>Link additional wallet</h2>
+ <div id="mount-link"></div>
+ <div class="log" id="log-link">State: idle</div>
+ </div>
+ <div class="demo-card">
+ <h2>Register agent (ERC-8004)</h2>
+ <div id="mount-agent"></div>
+ <div class="log" id="log-agent">State: idle</div>
+ </div>
+ </div>
+
+ <script type="module">
+ import { createConnectWalletButton } from '/wallet/connect-button.js';
+
+ const params = new URLSearchParams(location.search);
+ const next = params.get('next') || '/dashboard/';
+
+ function wire(mountId, logId, opts) {
+ const mountEl = document.getElementById(mountId);
+ const logEl = document.getElementById(logId);
+ const ctrl = createConnectWalletButton(mountEl, opts);
+ ctrl.addEventListener('change', (e) => {
+ const { status, address, error } = e.detail;
+ logEl.textContent = `State: ${status}${address ? ` · ${address.slice(0,6)}…${address.slice(-4)}` : ''}${error ? ` · ${error.message}` : ''}`;
+ });
+ return ctrl;
+ }
+
+ wire('mount-signin', 'log-signin', {
+ verifyUrl: '/api/auth/siwe/verify',
+ labels: { idle: 'Connect wallet', connected: null },
+ onSuccess: () => {
+ document.getElementById('log-signin').textContent = 'Success — redirecting…';
+ setTimeout(() => location.href = next, 800);
+ },
+ });
+
+ wire('mount-link', 'log-link', {
+ verifyUrl: '/api/auth/wallet/link',
+ labels: { idle: 'Link wallet', signing: 'Sign to link…', success: 'Wallet linked' },
+ onSuccess: () => {
+ document.getElementById('log-link').textContent = 'Wallet linked successfully.';
+ },
+ });
+
+ wire('mount-agent', 'log-agent', {
+ verifyUrl: '/api/auth/siwe/verify',
+ labels: { idle: 'Connect for ERC-8004', signing: 'Sign to register…', success: 'Ready' },
+ onSuccess: () => {
+ document.getElementById('log-agent').textContent = 'Connected — ready for on-chain registration.';
+ },
+ });
+ </script>
+ </body>
+</html>
diff --git a/dist-lib/wallet-connect.css b/dist-lib/wallet-connect.css
new file mode 100644
index 000000000..7787eb4ec
--- /dev/null
+++ b/dist-lib/wallet-connect.css
@@ -0,0 +1,85 @@
+/* Wallet connect button — scoped via .cwb-btn and [data-state] attribute. */
+
+.cwb-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ width: 100%;
+ padding: 10px 18px;
+ font: inherit;
+ font-size: 14px;
+ font-weight: 500;
+ border-radius: 8px;
+ border: 1px solid #2a2a36;
+ background: #1c1c28;
+ color: #eee;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, opacity 0.15s;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cwb-btn:hover:not(:disabled) {
+ background: #22222e;
+ border-color: #6a5cff;
+}
+
+.cwb-btn:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+}
+
+/* State variants */
+.cwb-btn[data-state="connected"] {
+ border-color: #2a5c2a;
+ background: #141c14;
+ color: #7ddf7d;
+}
+
+.cwb-btn[data-state="wrong_chain"] {
+ border-color: #7a5a00;
+ background: #1c1800;
+ color: #f0c040;
+}
+
+.cwb-btn[data-state="error"] {
+ border-color: #5c2a2a;
+ background: #1c1414;
+ color: #df7d7d;
+}
+
+.cwb-btn[data-state="success"] {
+ border-color: #2a5c2a;
+ background: #141c14;
+ color: #7ddf7d;
+ cursor: default;
+}
+
+.cwb-btn[data-state="no_provider"] {
+ border-color: #f6851b;
+ color: #f6851b;
+}
+
+.cwb-btn[data-state="no_provider"]:hover {
+ background: #1c1710;
+ border-color: #f6851b;
+}
+
+/* Async spinner — simple border animation */
+.cwb-btn[aria-busy="true"]::before {
+ content: '';
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ border: 2px solid currentColor;
+ border-top-color: transparent;
+ border-radius: 50%;
+ animation: cwb-spin 0.7s linear infinite;
+ flex-shrink: 0;
+}
+
+@keyframes cwb-spin {
+ to { transform: rotate(360deg); }
+}
diff --git a/dist-lib/wallet-login.js b/dist-lib/wallet-login.js
index ba7fdb5cf..7bfbf64d5 100644
--- a/dist-lib/wallet-login.js
+++ b/dist-lib/wallet-login.js
@@ -1,149 +1,39 @@
-// Client-side wallet authentication.
-// Used by /login and /register pages. Supports two paths:
-// 1. Privy — email/social/wallet login with auto-created embedded wallets
-// 2. Raw MetaMask/SIWE — direct Sign-In with Ethereum for existing wallets
-//
+// Client-side wallet authentication (SIWE / MetaMask).
// Loaded as a module from login.html — imports from CDN so it works outside Vite.
-import { BrowserProvider } from 'https://esm.sh/[email protected]';
+import { createConnectWalletButton } from '/wallet/connect-button.js';
const params = new URLSearchParams(location.search);
const next = params.get('next') || '/dashboard/';
-// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var). The
-// meta tag is a local-dev fallback — prod should rely on the fetched config.
-let PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';
-const configReady = fetch('/api/config', { credentials: 'omit' })
- .then((r) => r.ok ? r.json() : null)
- .then((cfg) => { if (cfg?.privyAppId) PRIVY_APP_ID = cfg.privyAppId; })
- .catch(() => {});
-
-// ── UI helpers ──────────────────────────────────────────────────────────────
-
-function ui() {
- const walletBtn = document.getElementById('wallet');
- const privyBtn = document.getElementById('privy');
- const err = document.getElementById('err');
- return {
- walletBtn, privyBtn, err,
- setErr: (m) => { if (err) { err.textContent = m; err.style.display = 'block'; } },
- clearErr: () => { if (err) { err.style.display = 'none'; } },
- };
+function setErr(m) {
+ const el = document.getElementById('err');
+ if (el) { el.textContent = m; el.style.display = 'block'; }
}
-
-// ── Privy login (primary path) ─────────────────────────────────────────────
-// Privy handles email + social + wallet login. On success it provides an
-// EIP-1193 provider (embedded or external) which we SIWE-verify against our
-// backend exactly like a raw MetaMask login.
-
-async function signInWithPrivy() {
- const { privyBtn, setErr, clearErr } = ui();
- await configReady;
- if (!PRIVY_APP_ID) { setErr('Privy not configured.'); return; }
-
- clearErr();
- if (privyBtn) { privyBtn.disabled = true; privyBtn.textContent = 'Loading Privy…'; }
-
- try {
- const mod = await import('https://esm.sh/@privy-io/js-sdk-core@latest');
- const PrivyClient = mod.PrivyClient || mod.default;
- const privy = new PrivyClient({ appId: PRIVY_APP_ID });
-
- if (privyBtn) privyBtn.textContent = 'Opening login…';
- await privy.login({ loginMethods: ['wallet', 'email', 'google'] });
-
- if (privyBtn) privyBtn.textContent = 'Connecting wallet…';
- const eip1193 = await privy.getEthereumProvider();
- if (!eip1193) throw new Error('No wallet provider returned by Privy.');
-
- const provider = new BrowserProvider(eip1193);
- await completeSignIn(provider, privyBtn);
- } catch (e) {
- const msg = e?.message || String(e);
- setErr(msg === 'user rejected action' || msg.includes('cancelled') ? 'Login cancelled.' : msg);
- if (privyBtn) { privyBtn.disabled = false; privyBtn.textContent = 'Sign in with Privy'; }
- }
-}
-
-// ── Raw MetaMask / SIWE (fallback path) ────────────────────────────────────
-
-async function signInWithWallet() {
- const { walletBtn, setErr, clearErr } = ui();
-
- if (!window.ethereum) {
- setErr('No wallet detected. Install MetaMask or another Ethereum wallet.');
- return;
- }
-
- clearErr();
- if (walletBtn) { walletBtn.disabled = true; walletBtn.textContent = 'Connecting…'; }
- const original = walletBtn?.innerHTML;
-
- try {
- const provider = new BrowserProvider(window.ethereum);
- await provider.send('eth_requestAccounts', []);
- await completeSignIn(provider, walletBtn);
- } catch (e) {
- const msg = e?.info?.error?.message || e?.message || String(e);
- setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);
- if (walletBtn) { walletBtn.disabled = false; walletBtn.innerHTML = original; }
- }
+function clearErr() {
+ const el = document.getElementById('err');
+ if (el) el.style.display = 'none';
}
-// ── Shared SIWE flow ───────────────────────────────────────────────────────
-// Both Privy and raw wallet paths use this to complete the login.
-
-async function completeSignIn(provider, btn) {
- const signer = await provider.getSigner();
- const address = await signer.getAddress();
- const network = await provider.getNetwork();
- const chainId = Number(network.chainId);
-
- if (btn) btn.textContent = 'Requesting nonce…';
- const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });
- if (!nonceRes.ok) throw new Error('Failed to get nonce');
- const { nonce, csrf } = await nonceRes.json();
-
- const domain = location.host;
- const uri = location.origin;
- const issuedAt = new Date().toISOString();
- const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();
-
- const message = [
- `${domain} wants you to sign in with your Ethereum account:`,
- address,
- '',
- 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',
- '',
- `URI: ${uri}`,
- 'Version: 1',
- `Chain ID: ${chainId}`,
- `Nonce: ${nonce}`,
- `Issued At: ${issuedAt}`,
- `Expiration Time: ${expirationTime}`,
- ].join('\n');
-
- if (btn) btn.textContent = 'Check your wallet…';
- const signature = await signer.signMessage(message);
-
- if (btn) btn.textContent = 'Verifying…';
- const verifyRes = await fetch('/api/auth/siwe/verify', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
- body: JSON.stringify({ message, signature }),
+const walletMount = document.getElementById('wallet-mount');
+if (walletMount) {
+ const ctrl = createConnectWalletButton(walletMount, {
+ verifyUrl: '/api/auth/siwe/verify',
+ onSuccess: () => {
+ try {
+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() }));
+ } catch { /* ignore */ }
+ location.href = next;
+ },
});
- const data = await verifyRes.json();
- if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');
-
- try { localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() })); } catch { /* ignore */ }
- location.href = next;
-}
-// ── Bind buttons ────────────────────────────────────────────────────────────
-
-const walletBtn = document.getElementById('wallet');
-const privyBtn = document.getElementById('privy');
-
-if (walletBtn) walletBtn.addEventListener('click', signInWithWallet);
-if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);
+ ctrl.addEventListener('change', (e) => {
+ const { status, error } = e.detail;
+ if (status === 'error') {
+ const msg = error?.message || 'Sign in failed.';
+ setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);
+ } else {
+ clearErr();
+ }
+ });
+}
\ No newline at end of file
diff --git a/dist-lib/wallet/connect-button.js b/dist-lib/wallet/connect-button.js
new file mode 100644
index 000000000..7cb222b23
--- /dev/null
+++ b/dist-lib/wallet/connect-button.js
@@ -0,0 +1,258 @@
+// Unified wallet connect controller + button factory (CDN-compatible).
+// Mirrors src/wallet/connect-button.js but imports ethers from esm.sh.
+// Loaded as a plain ES module from public pages outside Vite bundling.
+
+import { BrowserProvider } from 'https://esm.sh/[email protected]';
+import { STATES, initialState, reduce } from './state.js';
+
+const DEFAULT_CHAIN_IDS = [1, 8453, 10, 42161, 11155111, 84532];
+
+const CHAIN_NAMES = {
+ 1: 'Mainnet',
+ 8453: 'Base',
+ 10: 'Optimism',
+ 42161: 'Arbitrum One',
+ 11155111: 'Sepolia',
+ 84532: 'Base Sepolia',
+};
+
+const ASYNC_STATES = new Set([
+ STATES.DETECTING,
+ STATES.REQUESTING_ACCOUNTS,
+ STATES.SIGNING,
+ STATES.VERIFYING,
+]);
+
+function defaultMessageBuilder(address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) {
+ return [
+ `${domain} wants you to sign in with your Ethereum account:`,
+ address,
+ '',
+ 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',
+ '',
+ `URI: ${uri}`,
+ 'Version: 1',
+ `Chain ID: ${chainId}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${issuedAt}`,
+ `Expiration Time: ${expirationTime}`,
+ ].join('\n');
+}
+
+export class ConnectWalletController extends EventTarget {
+ #s;
+ #opts;
+ #onAccountsChanged;
+ #onChainChanged;
+
+ constructor(opts = {}) {
+ super();
+ this.#opts = {
+ allowedChainIds: DEFAULT_CHAIN_IDS,
+ nonceUrl: '/api/auth/siwe/nonce',
+ verifyUrl: '/api/auth/siwe/verify',
+ messageBuilder: defaultMessageBuilder,
+ onSuccess: null,
+ autoDetect: false,
+ labels: {},
+ ...opts,
+ };
+ this.#s = initialState();
+
+ this.#onAccountsChanged = (accounts) => this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });
+ this.#onChainChanged = (chainIdHex) => {
+ const chainId = parseInt(chainIdHex, 16);
+ this.#dispatch({ type: 'CHAIN_CHANGED', chainId });
+ if (!this.#opts.allowedChainIds.includes(chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ } else if (this.#s.status === STATES.WRONG_CHAIN) {
+ this.#dispatch({ type: 'CHAIN_OK' });
+ }
+ };
+
+ if (window.ethereum) {
+ window.ethereum.on('accountsChanged', this.#onAccountsChanged);
+ window.ethereum.on('chainChanged', this.#onChainChanged);
+ }
+ }
+
+ get state() { return this.#s.status; }
+ get address() { return this.#s.address; }
+ get chainId() { return this.#s.chainId; }
+ get error() { return this.#s.error; }
+
+ #dispatch(action) {
+ const next = reduce(this.#s, action);
+ if (next === this.#s) return;
+ this.#s = next;
+ this.dispatchEvent(new CustomEvent('change', { detail: { ...next } }));
+ }
+
+ async connect() {
+ if (this.#s.status !== STATES.IDLE) return;
+ this.#dispatch({ type: 'CONNECT' });
+
+ if (!window.ethereum) {
+ this.#dispatch({ type: 'NO_PROVIDER' });
+ return;
+ }
+ this.#dispatch({ type: 'HAS_PROVIDER' });
+
+ try {
+ const provider = new BrowserProvider(window.ethereum);
+ await provider.send('eth_requestAccounts', []);
+ const signer = await provider.getSigner();
+ const address = await signer.getAddress();
+ const network = await provider.getNetwork();
+ const chainId = Number(network.chainId);
+ this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });
+
+ if (!this.#opts.allowedChainIds.includes(chainId)) {
+ this.#dispatch({ type: 'WRONG_CHAIN' });
+ await this.#trySwitchChain(provider);
+ }
+ } catch (e) {
+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ }
+ }
+
+ async #trySwitchChain(provider) {
+ const target = this.#opts.allowedChainIds[0];
+ const hex = '0x' + target.toString(16);
+ try {
+ await provider.send('wallet_switchEthereumChain', [{ chainId: hex }]);
+ } catch (e) {
+ if (e?.code === 4902) {
+ this.#dispatch({
+ type: 'ERROR',
+ error: new Error(`Chain ${CHAIN_NAMES[target] || target} not in wallet. Add it manually.`),
+ });
+ } else if (e?.code !== 4001) {
+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ }
+ }
+ }
+
+ async signAndVerify() {
+ if (this.#s.status !== STATES.CONNECTED && this.#s.status !== STATES.WRONG_CHAIN) return;
+ this.#dispatch({ type: 'SIGN' });
+
+ try {
+ const provider = new BrowserProvider(window.ethereum);
+ const signer = await provider.getSigner();
+ const address = await signer.getAddress();
+
+ const nonceRes = await fetch(this.#opts.nonceUrl, { credentials: 'include' });
+ if (!nonceRes.ok) throw new Error('Failed to get nonce');
+ const { nonce, csrf } = await nonceRes.json();
+
+ const domain = location.host;
+ const uri = location.origin;
+ const issuedAt = new Date().toISOString();
+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();
+
+ const message = this.#opts.messageBuilder(address, this.#s.chainId, nonce, {
+ domain,
+ uri,
+ issuedAt,
+ expirationTime,
+ });
+
+ const signature = await signer.signMessage(message);
+ this.#dispatch({ type: 'SIGNATURE_OBTAINED' });
+
+ const verifyRes = await fetch(this.#opts.verifyUrl, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ message, signature }),
+ });
+ const data = await verifyRes.json();
+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');
+
+ this.#dispatch({ type: 'SUCCESS' });
+ if (this.#opts.onSuccess) this.#opts.onSuccess(data);
+ } catch (e) {
+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ }
+ }
+
+ reset() { this.#dispatch({ type: 'RESET' }); }
+
+ dispose() {
+ if (window.ethereum) {
+ window.ethereum.removeListener('accountsChanged', this.#onAccountsChanged);
+ window.ethereum.removeListener('chainChanged', this.#onChainChanged);
+ }
+ }
+}
+
+const LABEL_DEFAULTS = {
+ idle: 'Connect wallet',
+ detecting: 'Detecting…',
+ no_provider: 'Install MetaMask',
+ requesting_accounts: 'Check your wallet…',
+ signing: 'Sign in your wallet…',
+ verifying: 'Verifying…',
+ success: 'Signed in',
+ error: 'Retry',
+};
+
+export function createConnectWalletButton(mountEl, opts = {}) {
+ const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };
+ const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;
+ const ctrl = new ConnectWalletController({ ...opts, allowedChainIds });
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'cwb-btn';
+
+ function render(detail) {
+ const s = detail.status;
+ btn.setAttribute('data-state', s);
+ btn.disabled = ASYNC_STATES.has(s) || s === STATES.SUCCESS;
+ btn.setAttribute('aria-busy', ASYNC_STATES.has(s) ? 'true' : 'false');
+
+ if (s === STATES.CONNECTED || s === STATES.WRONG_CHAIN) {
+ const addr = detail.address || '';
+ const short = addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : '';
+ const chainName = CHAIN_NAMES[detail.chainId] || `Chain ${detail.chainId}`;
+ btn.textContent =
+ s === STATES.WRONG_CHAIN
+ ? `Switch to ${CHAIN_NAMES[allowedChainIds[0]] || 'Mainnet'}`
+ : `${short} · ${chainName}`;
+ } else if (s === STATES.ERROR) {
+ btn.textContent = labels.error;
+ } else {
+ btn.textContent = labels[s] || s;
+ }
+ }
+
+ function updateClickHandler(status) {
+ btn.onclick = null;
+ if (status === STATES.NO_PROVIDER) {
+ btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');
+ } else if (status === STATES.CONNECTED) {
+ btn.onclick = () => ctrl.signAndVerify();
+ } else if (status === STATES.WRONG_CHAIN) {
+ btn.onclick = () => ctrl.connect();
+ } else if (status === STATES.ERROR) {
+ btn.onclick = () => { ctrl.reset(); ctrl.connect(); };
+ } else if (status === STATES.IDLE) {
+ btn.onclick = () => ctrl.connect();
+ }
+ }
+
+ ctrl.addEventListener('change', (e) => {
+ render(e.detail);
+ updateClickHandler(e.detail.status);
+ });
+
+ render({ status: ctrl.state, address: ctrl.address, chainId: ctrl.chainId, error: ctrl.error });
+ updateClickHandler(ctrl.state);
+
+ mountEl.innerHTML = '';
+ mountEl.appendChild(btn);
+
+ return ctrl;
+}
diff --git a/dist-lib/wallet/state.js b/dist-lib/wallet/state.js
new file mode 100644
index 000000000..63816be2c
--- /dev/null
+++ b/dist-lib/wallet/state.js
@@ -0,0 +1,55 @@
+// Pure state machine for the wallet connect flow (CDN-compatible, no imports).
+// Kept in sync with src/wallet/state.js — no external dependencies.
+
+export const STATES = Object.freeze({
+ IDLE: 'idle',
+ DETECTING: 'detecting',
+ NO_PROVIDER: 'no_provider',
+ REQUESTING_ACCOUNTS: 'requesting_accounts',
+ CONNECTED: 'connected',
+ WRONG_CHAIN: 'wrong_chain',
+ SIGNING: 'signing',
+ VERIFYING: 'verifying',
+ SUCCESS: 'success',
+ ERROR: 'error',
+});
+
+export function initialState() {
+ return { status: STATES.IDLE, address: null, chainId: null, error: null };
+}
+
+export function reduce(state, action) {
+ switch (action.type) {
+ case 'CONNECT':
+ if (state.status !== STATES.IDLE) return state;
+ return { ...state, status: STATES.DETECTING, error: null };
+ case 'NO_PROVIDER':
+ return { ...state, status: STATES.NO_PROVIDER };
+ case 'HAS_PROVIDER':
+ return { ...state, status: STATES.REQUESTING_ACCOUNTS };
+ case 'ACCOUNTS_RESOLVED':
+ return { ...state, status: STATES.CONNECTED, address: action.address, chainId: action.chainId };
+ case 'WRONG_CHAIN':
+ return { ...state, status: STATES.WRONG_CHAIN };
+ case 'CHAIN_OK':
+ return { ...state, status: STATES.CONNECTED };
+ case 'SIGN':
+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN) return state;
+ return { ...state, status: STATES.SIGNING };
+ case 'SIGNATURE_OBTAINED':
+ return { ...state, status: STATES.VERIFYING };
+ case 'SUCCESS':
+ return { ...state, status: STATES.SUCCESS };
+ case 'ERROR':
+ return { ...state, status: STATES.ERROR, error: action.error ?? null };
+ case 'RESET':
+ return initialState();
+ case 'ACCOUNTS_CHANGED':
+ if (!action.accounts || action.accounts.length === 0) return initialState();
+ return { ...state, address: action.accounts[0], chainId: state.chainId, status: STATES.CONNECTED };
+ case 'CHAIN_CHANGED':
+ return { ...state, chainId: action.chainId };
+ default:
+ return state;
+ }
+}
diff --git a/features.css b/features.css
index 82a68d316..883e9b48c 100644
--- a/features.css
+++ b/features.css
@@ -282,6 +282,22 @@
transform: translateX(3px);
}
+.hero-signin-hint {
+ margin: calc(var(--space-md) * -0.5) 0 var(--space-xl);
+ font-size: var(--text-sm);
+ color: rgba(255, 255, 255, 0.38);
+}
+
+.hero-signin-link {
+ color: rgba(255, 255, 255, 0.6);
+ text-decoration: none;
+ transition: color 0.2s;
+}
+
+.hero-signin-link:hover {
+ color: #fff;
+}
+
.hero-proof {
list-style: none;
padding: 0;
diff --git a/index.html b/index.html
index cc63153c0..5f2b01083 100644
--- a/index.html
+++ b/index.html
@@ -540,6 +540,7 @@
>Try the viewer →</a
>
</div>
+ <p class="hero-signin-hint scroll-reveal" id="hero-signin-hint">Already have an account? <a href="/login" class="hero-signin-link">Sign in →</a></p>
<ul
class="hero-proof scroll-reveal"
aria-label="Supported formats and standards"
@@ -895,13 +896,17 @@
// Auth-aware nav
(function () {
try {
- const token =
- localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
- if (token) {
- const el = document.getElementById('nav-sign-in');
- if (el) {
- el.textContent = 'Dashboard';
- el.href = '/dashboard';
+ const raw = localStorage.getItem('3dagent:auth-hint');
+ if (raw) {
+ const { authed } = JSON.parse(raw);
+ if (authed) {
+ const el = document.getElementById('nav-sign-in');
+ if (el) {
+ el.textContent = 'Dashboard';
+ el.href = '/dashboard';
+ }
+ const heroSignin = document.getElementById('hero-signin-hint');
+ if (heroSignin) heroSignin.hidden = true;
}
}
} catch (_) {}
diff --git a/prompts/permissions/00-README.md b/prompts/permissions/00-README.md
new file mode 100644
index 000000000..0e86ce123
--- /dev/null
+++ b/prompts/permissions/00-README.md
@@ -0,0 +1,167 @@
+# Band 7 — MetaMask Advanced Permissions (ERC-7715 / ERC-7710)
+
+## The end state
+
+An agent deployed on-chain can be granted **scoped, time-bound, revocable permissions** by its owner via MetaMask. Once granted, the agent can execute transactions within that scope — from any host (Claude artifact, LobeHub plugin, embed iframe) — without the user needing to sign each transaction. Users can revoke at any time.
+
+End-to-end flow:
+
+1. User creates agent + deploys on-chain (band 6, already built).
+2. User clicks **Grant permissions** → MetaMask opens → user sees human-readable scope (token, daily cap, expiry, target contracts) → approves once.
+3. A signed ERC-7710 delegation is pinned, stamped into the agent manifest, and recorded in our DB.
+4. When a skill running inside a Claude / LobeHub embed needs an on-chain action, the runtime calls `redeemDelegation(...)` against the ERC-7710 `DelegationManager` on-chain. The action executes. No popup.
+5. User opens the manage panel → sees active delegations, usage counters, revoke button. Revoke is an on-chain write; the DB mirrors the state via the indexer cron.
+
+## Why this is one coherent band
+
+Scoped on-chain permissions are a primitive — the grant + storage + redemption + revoke loop must all work or none of it is useful. Each task in this band builds one slice; tasks are **independent** and can be done in parallel by 20 agents without blocking.
+
+## Canonical shapes (all tasks converge on these)
+
+> Every task references this section. Do not invent alternative shapes — consistency is why parallel work converges.
+
+### DB — `agent_delegations` table
+
+```sql
+CREATE TABLE agent_delegations (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ chain_id INTEGER NOT NULL,
+ delegator_address TEXT NOT NULL, -- EIP-55 checksummed user wallet
+ delegate_address TEXT NOT NULL, -- EIP-55 checksummed agent smart account
+ delegation_hash TEXT NOT NULL UNIQUE, -- keccak256 of the delegation envelope
+ delegation_json JSONB NOT NULL, -- full signed ERC-7710 delegation envelope
+ scope JSONB NOT NULL, -- { token, maxAmount, targets[], expiry, period }
+ status TEXT NOT NULL DEFAULT 'active', -- active | revoked | expired
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ revoked_at TIMESTAMPTZ,
+ tx_hash_revoke TEXT,
+ last_redeemed_at TIMESTAMPTZ,
+ redemption_count INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX idx_delegations_agent ON agent_delegations(agent_id);
+CREATE INDEX idx_delegations_status ON agent_delegations(status) WHERE status = 'active';
+CREATE INDEX idx_delegations_delegator ON agent_delegations(delegator_address);
+```
+
+### API — endpoints under `/api/permissions/`
+
+| Method | Path | Body / Query | Response |
+| ------ | ---------------------------------- | -------------------------------------------------------------- | ----------------------------------- |
+| POST | `/api/permissions/grant` | `{ agentId, chainId, delegation, scope }` | `{ ok, id, delegationHash }` |
+| GET | `/api/permissions/list` | `?agentId=X` or `?delegator=0x...` | `{ ok, delegations: [...] }` |
+| POST | `/api/permissions/revoke` | `{ id, txHash }` | `{ ok, status: 'revoked' }` |
+| POST | `/api/permissions/redeem` | `{ id, calls: [{to,value,data}] }` (auth: agent bearer token) | `{ ok, txHash, receipt }` |
+| GET | `/api/permissions/metadata` | `?agentId=X` (public, cached) | `{ ok, delegations: [public view] }`|
+| GET | `/api/permissions/verify` | `?hash=0x...&chainId=N` | `{ ok, valid, reason? }` |
+
+All responses follow `{ ok: true, ... }` / `{ ok: false, error: 'code', message: '...' }` per [api/CLAUDE.md](../../api/CLAUDE.md).
+
+### Manifest — `permissions` field on `manifest.json`
+
+```jsonc
+"permissions": {
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...", // DelegationManager address on the target chain
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0x...", // EIP-55 checksummed
+ "delegate": "0x...", // EIP-55 checksummed agent account
+ "hash": "0x...", // delegation envelope keccak256
+ "uri": "ipfs://bafy...", // pinned envelope (or inline under "envelope")
+ "scope": {
+ "token": "0x...", // ERC-20 address, or "native"
+ "maxAmount": "10000000", // base units, string
+ "period": "daily", // daily|weekly|once
+ "targets": ["0x..."], // allow-listed contracts
+ "expiry": 1775250000 // unix seconds
+ }
+ }
+ ]
+}
+```
+
+### JS modules — canonical exports
+
+```js
+// src/erc7710/abi.js
+export const DELEGATION_MANAGER_DEPLOYMENTS = { 84532: '0x...', 1: '0x...', ... };
+export const DELEGATION_MANAGER_ABI = [ /* human-readable ethers v6 strings */ ];
+export const EIP7710_TYPEHASH = '0x...';
+
+// src/permissions/toolkit.js
+export async function encodeScopedDelegation({ delegator, delegate, caveats, expiry, chainId }) { /* */ }
+export async function signDelegation(delegation, signer) { /* */ }
+export async function redeemDelegation({ delegation, calls, signer, chainId }) { /* */ }
+export async function isDelegationValid({ hash, chainId }) { /* */ }
+export function delegationToManifestEntry(signedDelegation) { /* */ }
+
+// src/runtime/delegation-redeem.js
+export async function redeemFromSkill({ agentId, chainId, calls, skillId }) { /* */ }
+export async function getActiveDelegation({ agentId, chainId }) { /* */ }
+```
+
+### Error codes (string, OAuth-style)
+
+`delegation_expired`, `delegation_revoked`, `scope_exceeded`, `target_not_allowed`, `delegation_not_found`, `signature_invalid`, `chain_not_supported`, `rate_limited`.
+
+## Off-limits
+
+- **No mainnet defaults.** Base Sepolia / Sepolia only unless the user explicitly opts in through the UI.
+- **No mock signatures.** Delegations must be real EIP-712 signatures from the user's wallet, verifiable on-chain.
+- **No custodial keys.** We never hold the delegator's key. The agent's smart account key may be held server-side only if the task explicitly says so (task 09 defines this trust boundary).
+- **No bypassing scope.** The redeem path must call the real ERC-7710 `DelegationManager.redeemDelegations(...)`; never execute calls that fall outside the signed caveats.
+- **No silent auto-grants.** Every delegation must be explicitly approved by the user in MetaMask. Scope must be human-readable before approval.
+
+## Reference
+
+- MetaMask docs: <https://docs.metamask.io/delegation-toolkit/> (verify package name + contract addresses there — do not guess; if the docs say `@metamask/delegation-toolkit`, use exactly that)
+- EIP-7710: <https://eips.ethereum.org/EIPS/eip-7710>
+- EIP-7715: <https://eips.ethereum.org/EIPS/eip-7715>
+- Existing on-chain plumbing: [src/erc8004/](../../src/erc8004/)
+- Existing auth: [api/\_lib/auth.js](../../api/_lib/auth.js)
+
+## Tasks (independent — run in any order)
+
+| # | File | Area |
+| --- | --------------------------------------------------------------------- | ------------------------------ |
+| 01 | [01-permissions-spec.md](./01-permissions-spec.md) | specs (new doc) |
+| 02 | [02-manifest-permissions-field.md](./02-manifest-permissions-field.md)| specs (append) |
+| 03 | [03-erc7710-abi.md](./03-erc7710-abi.md) | src/erc7710/ |
+| 04 | [04-delegation-toolkit.md](./04-delegation-toolkit.md) | src/permissions/toolkit.js |
+| 05 | [05-db-schema.md](./05-db-schema.md) | schema + migration |
+| 06 | [06-api-grant.md](./06-api-grant.md) | api/permissions/grant.js |
+| 07 | [07-api-list.md](./07-api-list.md) | api/permissions/list.js |
+| 08 | [08-api-revoke.md](./08-api-revoke.md) | api/permissions/revoke.js |
+| 09 | [09-api-redeem.md](./09-api-redeem.md) | api/permissions/redeem.js |
+| 10 | [10-grant-ui.md](./10-grant-ui.md) | src/permissions/grant-modal.js |
+| 11 | [11-manage-ui.md](./11-manage-ui.md) | src/permissions/manage-panel.js|
+| 12 | [12-api-metadata.md](./12-api-metadata.md) | api/permissions/metadata.js |
+| 13 | [13-runtime-redeem-hook.md](./13-runtime-redeem-hook.md) | src/runtime/ |
+| 14 | [14-skill-tip-jar.md](./14-skill-tip-jar.md) | public/skills/tip-jar/ |
+| 15 | [15-skill-subscription.md](./15-skill-subscription.md) | public/skills/subscription/ |
+| 16 | [16-skill-dca.md](./16-skill-dca.md) | public/skills/dca/ |
+| 17 | [17-embed-spec-delegation.md](./17-embed-spec-delegation.md) | specs (append) |
+| 18 | [18-sdk-permissions.md](./18-sdk-permissions.md) | sdk/ |
+| 19 | [19-indexer-cron.md](./19-indexer-cron.md) | api/cron/ |
+| 20 | [20-verify-endpoint.md](./20-verify-endpoint.md) | api/permissions/verify.js |
+
+All tasks reference the Canonical Shapes section above. None depend on another task being done first — each ships its own slice. Collisions on existing files are limited to `specs/AGENT_MANIFEST.md` (task 02) and `specs/EMBED_SPEC.md` (task 17), which are different files.
+
+## Done = merged when
+
+- Owner opens their agent page → **Grant permissions** → MetaMask prompt shows the exact scope in plain English → they approve → the delegation is stored (DB + pinned) and appears in the manifest.
+- A skill running inside the Claude artifact can call `redeemFromSkill(...)` and an on-chain transaction lands within the scope with no wallet popup.
+- Revoke button calls `DelegationManager.disableDelegation(...)` on-chain; the indexer picks up the event; the UI marks the delegation as revoked.
+- `forge test` (contracts), `npm run build`, and `npx prettier --write` all pass.
+- Every endpoint is rate-limited + authenticated per `api/CLAUDE.md` patterns.
+
+## Reporting (every task ends with this)
+
+- Files changed (paths + line counts)
+- Commands run + their output (node --check, npm run build, forge test if touched)
+- A single screenshot or transcript of the happy path for your slice
+- Anything skipped, any deviation from the canonical shapes (must justify)
+- Unrelated bugs observed (don't fix them — note them)
diff --git a/prompts/permissions/01-permissions-spec.md b/prompts/permissions/01-permissions-spec.md
new file mode 100644
index 000000000..084d810ba
--- /dev/null
+++ b/prompts/permissions/01-permissions-spec.md
@@ -0,0 +1,51 @@
+# Task 01 — Write `specs/PERMISSIONS_SPEC.md`
+
+## Why
+
+The permissions band needs a canonical, versioned spec the way `AGENT_MANIFEST.md`, `SKILL_SPEC.md`, `EMBED_SPEC.md`, and `MEMORY_SPEC.md` are canonical. Other tasks in this band reference this spec; the SDK, embed hosts, and contract auditors will too. Writing a real doc — not a stub — anchors the design.
+
+## Read first
+
+- [00-README.md](./00-README.md) — **Canonical shapes** section. Lift the shapes verbatim into the spec; do not invent variants.
+- [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md) — prose style, section depth
+- [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) — how optional fields are marked
+- [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — how hosts are described
+- EIP-7710 + EIP-7715 — summarize them accurately, cite the EIP numbers inline
+
+## Build this
+
+Create `specs/PERMISSIONS_SPEC.md` with these sections:
+
+1. **Overview** — one paragraph: what an advanced permission is, why agents need them, the relation to ERC-8004 identity. Include the trust model summary: user signs once, contracts enforce scope, agent redeems at will within scope.
+2. **Delegation envelope** — the full ERC-7710 delegation struct (delegate, authority, caveats, salt, signature), as used in this project. Link to the MetaMask Delegation Toolkit docs. Explicitly document which fields are EIP-712 hashed.
+3. **Scope vocabulary** — all valid `scope` keys (`token`, `maxAmount`, `period`, `targets`, `expiry`, `selectors`). For each: type, range, constraints, example. Document how caveats map to these keys (ERC-20 allowance caveat, target-allow-list caveat, period caveat, expiry caveat).
+4. **Manifest integration** — reproduce the `permissions` field from the canonical shapes. Explain that `uri` resolves to a pinned envelope (IPFS), and inline `envelope` is allowed for embed contexts where IPFS isn't reachable.
+5. **API surface** — table of the six endpoints from the canonical shapes. Link to `api/CLAUDE.md` for shared conventions (auth, CORS, rate limits).
+6. **Redemption flow** — step-by-step: skill calls `redeemFromSkill` → runtime loads delegation from DB → builds `redeemDelegations(...)` call → submits via relayer (or the agent's smart account) → returns receipt. Clearly label which steps require what keys.
+7. **Revocation** — on-chain via `DelegationManager.disableDelegation(delegationHash)`, mirrored off-chain by the indexer cron. Document race conditions (redemption in flight during revoke) and the caveat that on-chain is authoritative.
+8. **Error codes** — reproduce the canonical list. For each: when it's returned, how a client should recover.
+9. **Versioning** — this spec is `permissions/0.1`. Any breaking change bumps the minor. Agents must advertise supported versions in their manifest.
+10. **Security considerations** — replay protection (salt + chain id), phishing (why we show scope in English before the MetaMask prompt), compromised agent key (scope + expiry limit blast radius), relayer trust (if the redeem endpoint is used).
+
+Keep prose tight. Spec style, not tutorial style. No emojis.
+
+## Don't do this
+
+- Don't speculate about features not in the canonical shapes (batched delegations, meta-delegations, etc.). If you think one is needed, note it in your report; don't add it.
+- Don't copy-paste the MetaMask docs. Link to them, summarize, cite EIP numbers.
+- Don't include code snippets longer than ~10 lines — this is a spec, not a tutorial.
+- Don't invent new error codes. If one feels missing, flag it in your report.
+
+## Acceptance
+
+- [ ] `specs/PERMISSIONS_SPEC.md` exists, ~300–500 lines, no TODOs.
+- [ ] Sections 1–10 present and non-empty.
+- [ ] All canonical shapes from `00-README.md` are reproduced verbatim.
+- [ ] `npx prettier --write specs/PERMISSIONS_SPEC.md` passes.
+- [ ] No dead links.
+
+## Reporting
+
+- Link the file.
+- List any canonical-shape additions you felt were needed but did not add (escalations, not changes).
+- Commands run + output.
diff --git a/prompts/permissions/02-manifest-permissions-field.md b/prompts/permissions/02-manifest-permissions-field.md
new file mode 100644
index 000000000..52f12b230
--- /dev/null
+++ b/prompts/permissions/02-manifest-permissions-field.md
@@ -0,0 +1,50 @@
+# Task 02 — Add `permissions` field to Agent Manifest spec
+
+## Why
+
+The agent manifest is the portable, on-chain-addressable description of an agent. For embeds (Claude artifact, LobeHub plugin) to execute scoped on-chain actions without contacting our server, the signed delegation — or a resolvable pointer to it — must live in the manifest itself.
+
+## Read first
+
+- [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md) — the file you are editing (the full thing)
+- [00-README.md](./00-README.md) — **Canonical shapes → Manifest `permissions` field**. Copy it exactly.
+- [src/runtime/](../../src/runtime/) — to understand how the runtime reads the manifest today; your edit must not break existing consumers
+
+## Build this
+
+Append — do not rewrite — a section to `specs/AGENT_MANIFEST.md` titled **`permissions` (optional, v0.1+)**.
+
+Contents:
+
+1. One-paragraph intro: scoped on-chain permissions granted to the agent by its owner via ERC-7710 delegations. Optional — agents without on-chain identity omit the field entirely. Link to `specs/PERMISSIONS_SPEC.md` (task 01 creates it; if not present yet, link anyway — this is a spec cross-reference).
+2. The canonical JSON block verbatim from the `00-README.md` Canonical Shapes.
+3. **Field reference** — table with `delegationManager`, `delegations[]`, and for each nested field: type, required?, example, constraints.
+4. **Resolution order** — how a host resolves a delegation:
+ 1. If `envelope` is inline → use it.
+ 2. Else fetch `uri` (IPFS gateway, Arweave, HTTPS — same resolution rules as `body.uri`).
+ 3. Verify `hash` matches `keccak256(envelope)`.
+ 4. Verify signature on-chain against the delegator address before trusting.
+5. **Backwards compatibility** — manifests without `permissions` are valid; hosts must treat absence as "no on-chain permissions granted". Hosts MUST NOT fall back to asking the user to sign per-tx if the field is absent unless the skill itself requests it.
+6. **Size budget** — keep envelope inline only when <8 KB; above that, pin to IPFS and reference via `uri` to keep the manifest lean.
+
+Also bump the `spec` version in the top-level schema block from `agent-manifest/0.1` → `agent-manifest/0.2` and add a `## Changelog` entry at the bottom (or insert into the existing changelog if present) documenting the addition.
+
+## Don't do this
+
+- Don't reorder or edit unrelated sections.
+- Don't delete the `0.1` example. Add `0.2` alongside.
+- Don't speculate about future fields (e.g. `delegationChains`, `nestedDelegations`). File those as notes in your report.
+- Don't include actual signed example data in the spec — just structural examples with `0x...` placeholders.
+
+## Acceptance
+
+- [ ] `specs/AGENT_MANIFEST.md` contains a new `permissions` section with all six subsections above.
+- [ ] Top-level `spec` bumped to `agent-manifest/0.2`.
+- [ ] `## Changelog` entry added for `0.2`.
+- [ ] Canonical shape reproduced exactly (byte-for-byte identical to `00-README.md`).
+- [ ] `npx prettier --write specs/AGENT_MANIFEST.md` passes.
+
+## Reporting
+
+- Diff of the spec file.
+- Any spec conflicts you noticed (e.g. an older version comment that now contradicts).
diff --git a/prompts/permissions/03-erc7710-abi.md b/prompts/permissions/03-erc7710-abi.md
new file mode 100644
index 000000000..2df80b704
--- /dev/null
+++ b/prompts/permissions/03-erc7710-abi.md
@@ -0,0 +1,61 @@
+# Task 03 — ERC-7710 `DelegationManager` ABIs and chain meta
+
+## Why
+
+Every other task that touches on-chain delegation (grant UI, redeem hook, revoke endpoint, indexer, verify endpoint) needs a single source of truth for the `DelegationManager` address per chain and the ABI fragments used. Mirrors the pattern in [src/erc8004/abi.js](../../src/erc8004/abi.js).
+
+## Read first
+
+- [src/erc8004/abi.js](../../src/erc8004/abi.js) — use this as the template for structure, comment style, and human-readable ethers v6 strings
+- [src/erc8004/chain-meta.js](../../src/erc8004/chain-meta.js) — see how chain metadata is organized; reuse constants where possible
+- MetaMask Delegation Toolkit docs (<https://docs.metamask.io/delegation-toolkit/>) — authoritative source for contract addresses per chain and ABI. **Do not guess addresses.** If the docs don't list a chain, do not include it.
+- [00-README.md](./00-README.md) — canonical exports from `src/erc7710/abi.js`
+
+## Build this
+
+Create `src/erc7710/abi.js` with:
+
+1. `DELEGATION_MANAGER_DEPLOYMENTS` — object keyed by numeric chainId, values are EIP-55 checksummed addresses. Include at minimum: Base Sepolia (84532), Sepolia (11155111), Base mainnet (8453), Ethereum mainnet (1). Source addresses from the MetaMask docs; comment each with the date you fetched and the docs URL section.
+2. `DELEGATION_MANAGER_ABI` — ethers v6 human-readable string array. Include at least: `redeemDelegations`, `disableDelegation`, `isDelegationDisabled`, `getDelegationHash`, and the events `DelegationRedeemed`, `DelegationDisabled`. Verify signatures against the MetaMask docs/Solidity source.
+3. `CAVEAT_ENFORCERS` — object mapping enforcer name (`AllowedTargetsEnforcer`, `ERC20LimitEnforcer`, `TimestampEnforcer`, `NonceEnforcer`, etc.) → per-chain address map. Same EIP-55 checksumming.
+4. `EIP712_DOMAIN({ chainId, verifyingContract })` helper returning the domain separator fields used for delegation signing.
+5. `encodeCaveats(caveats)` — pure function that ABI-encodes an array of caveats (`{ enforcer, terms, args }`) into the on-chain format. Use ethers `AbiCoder`.
+6. Optional: `DELEGATION_TYPES` — the EIP-712 `types` object for signing (keys: `Delegation`, `Caveat`).
+
+File conventions:
+
+- ESM only. Match prettier style (tabs, single quotes, 100 cols).
+- No runtime dependencies other than `ethers` (already in the project).
+- Export each symbol as a named export.
+- Every exported constant has a 1-line comment above it documenting its purpose + source.
+
+Add a second file `src/erc7710/README.md` (15–40 lines) listing: what this module is, what's NOT in it (no signing, no RPC — just constants + pure encoders), and how `src/permissions/toolkit.js` consumes it.
+
+Finally add a self-check script `scripts/check-erc7710-addresses.js` that:
+
+- Imports `DELEGATION_MANAGER_DEPLOYMENTS`.
+- For each chain, calls `eth_getCode` via the public RPC (pull URL from `src/erc8004/chain-meta.js` if present; else inline Base/Sepolia public RPCs).
+- Fails non-zero if any address returns `0x` (i.e. not a contract).
+- Run it yourself; paste the output in the reporting block.
+
+## Don't do this
+
+- Do not invent contract addresses. If MetaMask docs don't list Base mainnet yet, omit it with a comment.
+- Do not pull in the full `@metamask/delegation-toolkit` in this file — that goes in `src/permissions/toolkit.js` (task 04). This file is constants + pure encoders only.
+- Do not use ABI JSON. Stick to human-readable strings for consistency with the rest of the repo.
+- Do not mix checksummed and lower-cased addresses in the same map.
+
+## Acceptance
+
+- [ ] `src/erc7710/abi.js` exists with all six exports from the canonical shapes.
+- [ ] `src/erc7710/README.md` exists and is accurate.
+- [ ] `scripts/check-erc7710-addresses.js` runs without errors and reports `0x...` bytecode > 2 chars for every listed chain.
+- [ ] `node --check src/erc7710/abi.js` passes.
+- [ ] `npm run build` passes.
+- [ ] `npx prettier --write src/erc7710/ scripts/check-erc7710-addresses.js` passes.
+
+## Reporting
+
+- The chain-address table with `eth_getCode` length per chain.
+- Citation to the exact MetaMask doc section you copied addresses from (URL + fetch date).
+- Any chain omitted, with justification.
diff --git a/prompts/permissions/04-delegation-toolkit.md b/prompts/permissions/04-delegation-toolkit.md
new file mode 100644
index 000000000..44fa959e5
--- /dev/null
+++ b/prompts/permissions/04-delegation-toolkit.md
@@ -0,0 +1,61 @@
+# Task 04 — `src/permissions/toolkit.js` wrapper over MetaMask Delegation Toolkit
+
+## Why
+
+Every UI + runtime path needs a single, well-typed (JSDoc) facade over the MetaMask Delegation Toolkit. Consumers should never import the toolkit directly — they import from `src/permissions/toolkit.js`. This keeps the toolkit version controlled, the scope-builder output consistent, and any future switch to another SDK (or a direct ethers implementation) isolated to this file.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical `src/permissions/toolkit.js` exports
+- MetaMask Delegation Toolkit docs (<https://docs.metamask.io/delegation-toolkit/>) — **authoritative source for package name and APIs**. If the package name is `@metamask/delegation-toolkit`, use exactly that. If the docs show a different package, use the one in the docs.
+- [src/erc7710/abi.js](../../src/erc7710/abi.js) — constants you depend on (task 03 creates it; if missing at your start, you may inline the `DELEGATION_MANAGER_DEPLOYMENTS` map from `00-README.md` canonical shapes — they should match)
+- [package.json](../../package.json) — add the toolkit as a runtime dep only after verifying license + size + maintenance
+
+## Build this
+
+1. **Add the dependency.** `npm install @metamask/delegation-toolkit` (or whatever the MetaMask docs specify). Commit the `package.json` + `package-lock.json` update together. If the toolkit pulls in >5 MB of transitive deps, stop and report — we may need to pick a leaner path (direct ethers).
+2. **Create `src/permissions/toolkit.js`** with the canonical exports from `00-README.md`:
+
+ - `encodeScopedDelegation({ delegator, delegate, caveats, expiry, chainId })` — returns an unsigned delegation object ready to sign. Build the caveats using `CAVEAT_ENFORCERS` from `src/erc7710/abi.js`. Enforce: `expiry > now + 60`, `caveats.length >= 1`, `delegate !== delegator`.
+ - `signDelegation(delegation, signer)` — uses the toolkit's EIP-712 signing, or falls back to `signer.signTypedData(domain, types, value)` with `EIP712_DOMAIN` + `DELEGATION_TYPES` from `abi.js`. Returns `{ ...delegation, signature, hash }`.
+ - `redeemDelegation({ delegation, calls, signer, chainId })` — builds the `redeemDelegations` call with the provided `calls` array (`{ to, value, data }`), submits it via `signer`, waits for receipt, returns `{ txHash, receipt }`. **Must verify on-chain** that `isDelegationDisabled(hash)` is false before submitting; throw `delegation_revoked` if true.
+ - `isDelegationValid({ hash, chainId, rpcUrl? })` — read-only; returns `{ valid: boolean, reason?: string }`. Checks: not disabled on-chain, not expired (uses `caveats.expiry`), signature recovers to `delegator`.
+ - `delegationToManifestEntry(signedDelegation)` — maps a signed delegation into the `permissions.delegations[]` shape from the manifest spec (task 02). Pure, no I/O.
+
+3. **Error surface.** Throw typed errors matching canonical error codes (`delegation_expired`, `signature_invalid`, `chain_not_supported`, etc.). Use a small helper:
+
+ ```js
+ export class PermissionError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+ }
+ ```
+
+4. **No network I/O in pure helpers.** `encodeScopedDelegation`, `delegationToManifestEntry` are synchronous + pure. `isDelegationValid`, `redeemDelegation`, `signDelegation` do I/O.
+5. **JSDoc everything exported.** Param types, return types, thrown codes.
+6. **Self-check**: add `scripts/test-toolkit.js` — runs `encodeScopedDelegation` with fixture data, runs `delegationToManifestEntry` on a pre-signed fixture, asserts shapes. No network. `node scripts/test-toolkit.js` must exit 0.
+
+## Don't do this
+
+- Do not build a mock signer path. If the caller doesn't pass a signer, throw — don't silently no-op.
+- Do not accept addresses that aren't checksummed. Validate and re-checksum on entry.
+- Do not reimplement EIP-712 hashing by hand — use ethers or the toolkit.
+- Do not import React / viewer modules. This file is pure library code usable in both browser and node.
+- Do not log signed delegations or signatures. Log the `hash` only.
+
+## Acceptance
+
+- [ ] `src/permissions/toolkit.js` exports all five canonical functions + `PermissionError`.
+- [ ] `scripts/test-toolkit.js` passes with fixture data.
+- [ ] `node --check src/permissions/toolkit.js` passes.
+- [ ] `npm run build` passes.
+- [ ] Dependency added to `package.json`, lockfile updated.
+- [ ] No direct imports of `@metamask/delegation-toolkit` outside this file (grep to confirm).
+
+## Reporting
+
+- `npm ls @metamask/delegation-toolkit` output.
+- Bundle size delta from `npm run build` (`dist/` size before/after).
+- Any toolkit API you could not use (with the error you got).
diff --git a/prompts/permissions/05-db-schema.md b/prompts/permissions/05-db-schema.md
new file mode 100644
index 000000000..19904f3e1
--- /dev/null
+++ b/prompts/permissions/05-db-schema.md
@@ -0,0 +1,57 @@
+# Task 05 — `agent_delegations` DB schema + migration
+
+## Why
+
+Every API endpoint in this band reads or writes `agent_delegations`. One task owns the schema; all other API tasks assume the shape exists exactly as canonicalized in `00-README.md`.
+
+## Read first
+
+- [00-README.md](./00-README.md) — **Canonical shapes → DB `agent_delegations` table**. Reproduce it exactly.
+- [specs/schema/](../../specs/schema/) — existing schema files, style guide (idempotent, documented, indexed)
+- [scripts/](../../scripts/) — the existing "apply schema" script pattern (there is a schema-apply script; match its style)
+- [api/\_lib/db.js](../../api/_lib/db.js) — how `sql` tagged templates are used (does not matter for this task beyond confirming column naming is snake_case)
+
+## Build this
+
+1. **Create `specs/schema/agent_delegations.sql`** containing:
+
+ - `CREATE TABLE IF NOT EXISTS agent_delegations (...)` with the exact columns from the canonical shape.
+ - All three indexes from the canonical shape.
+ - A `CHECK` constraint on `status` (`status IN ('active','revoked','expired')`).
+ - A `CHECK` on `chain_id > 0`.
+ - A `CHECK` ensuring `delegator_address` and `delegate_address` are 42 characters starting with `0x`.
+ - A trigger OR a comment explaining that `redemption_count` and `last_redeemed_at` are updated by the redeem endpoint (task 09) — no DB-side trigger needed.
+ - Header comment with the spec version (`permissions/0.1`) and the task reference.
+ - Fully idempotent: re-running the file against a DB that already has the table is a no-op (use `IF NOT EXISTS` / `DO $$ ... $$` blocks for indexes that already exist).
+
+2. **Create a migration script `scripts/apply-delegations-schema.js`** following the pattern of any existing schema-apply script in `scripts/` (grep for `apply` or `schema`):
+
+ - Reads `specs/schema/agent_delegations.sql`.
+ - Uses `DATABASE_URL` from env (same env var the rest of the project uses).
+ - Executes the SQL, prints a summary (row count of `agent_delegations` after apply, index list).
+ - Exits non-zero on any SQL error.
+
+3. **Run the migration** against the Neon dev branch (env var `DATABASE_URL` points to it locally, via `.env.local` — use `node -r dotenv/config scripts/apply-delegations-schema.js` or the repo's existing pattern). Paste the output in the reporting block. If you do not have DB credentials available, stop and say so explicitly — **do not fake the output.**
+
+4. **Document the table** in `specs/schema/README.md` (append a short row if the file exists; create it if not). One sentence per column.
+
+## Don't do this
+
+- Do not alter other tables. If you think `agents` needs a column (`has_permissions`, a count cache, etc.), note it in your report — don't add it.
+- Do not use `UUID` generation that depends on `uuid-ossp` unless the rest of the schema uses it; prefer `gen_random_uuid()` (pgcrypto) — check what sibling `.sql` files use.
+- Do not add FK cascades beyond `agents(id) ON DELETE CASCADE`. Revocations and expirations are status changes, not deletes.
+- Do not embed example `INSERT` statements in the production schema file. Fixtures belong in `scripts/seed-*.js`.
+
+## Acceptance
+
+- [ ] `specs/schema/agent_delegations.sql` matches canonical shape byte-for-byte on columns and indexes.
+- [ ] `scripts/apply-delegations-schema.js` exists and is idempotent.
+- [ ] Migration applied against dev DB; `\d agent_delegations` output captured.
+- [ ] `specs/schema/README.md` updated.
+- [ ] `node --check scripts/apply-delegations-schema.js` passes.
+
+## Reporting
+
+- Full `\d+ agent_delegations` output post-migration.
+- `EXPLAIN` output of `SELECT * FROM agent_delegations WHERE agent_id = $1 AND status = 'active'` confirming index use.
+- If DB access unavailable, say so and paste only the SQL file contents.
diff --git a/prompts/permissions/06-api-grant.md b/prompts/permissions/06-api-grant.md
new file mode 100644
index 000000000..eb1aefa76
--- /dev/null
+++ b/prompts/permissions/06-api-grant.md
@@ -0,0 +1,58 @@
+# Task 06 — `POST /api/permissions/grant`
+
+## Why
+
+This is the write endpoint: a signed ERC-7710 delegation arrives from the grant UI, the server verifies its signature on-chain-style (EIP-712 recover) + checks the delegator matches the agent's owner wallet, then persists it and returns the row id. Without this endpoint the UI has nothing to post to.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint shape + error codes
+- [api/CLAUDE.md](../../api/CLAUDE.md) — conventions (`json`, `error`, `wrap`, `cors`, `limits`, `getSessionUser`)
+- [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/auth.js](../../api/_lib/auth.js), [api/\_lib/db.js](../../api/_lib/db.js) — actual helpers you must use
+- [api/\_lib/ratelimits.js](../../api/_lib/ratelimits.js) or wherever rate-limit presets live — grep for `limits.` usage
+- [api/avatars/](../../api/avatars/) — a good example of an owner-gated write endpoint to mirror
+
+## Build this
+
+Create `api/permissions/grant.js` exporting a default handler (Vercel function signature `(req, res)`) wired via `wrap()` with:
+
+1. **Method gate** — POST only, else `405 method_not_allowed`.
+2. **CORS** — the shared `cors()` helper.
+3. **Rate limit** — a strict preset (e.g. `limits.write` or `limits.strict`) keyed on `userId`. Grant writes should be infrequent.
+4. **Auth** — `getSessionUser(req)`; reject with `401 unauthorized` if absent.
+5. **Input validation** — body must contain:
+ - `agentId` (UUID)
+ - `chainId` (positive int, must be a key in `DELEGATION_MANAGER_DEPLOYMENTS` from `src/erc7710/abi.js`)
+ - `delegation` (object with `delegator`, `delegate`, `caveats`, `salt`, `signature`, `hash`)
+ - `scope` (matches canonical scope shape — `token`, `maxAmount`, `period`, `targets[]`, `expiry`)
+6. **Owner gate** — query `agents` for the row, assert `agent.owner_user_id === user.id`. Return `403 not_owner` on mismatch.
+7. **Wallet linkage** — confirm `delegation.delegator` equals the user's linked wallet address (join to `users` or `user_wallets`, whatever exists). If not linked, return `409 wallet_not_linked`.
+8. **Signature verification** — import `isDelegationValid` (task 04) and call it with `{ hash: delegation.hash, chainId }`. If invalid → return `400 signature_invalid` (or whatever code the toolkit returned). Also re-derive `hash` from `delegation` and compare; reject mismatch.
+9. **Scope sanity** — `expiry > now + 60`, `expiry < now + 365 days`, `maxAmount > 0`, `targets.length >= 1`, each target a checksummed 0x address.
+10. **Persist** — insert into `agent_delegations` using tagged-template `sql` from `api/_lib/db.js`. `delegation_hash` is UNIQUE → on conflict, return `409 duplicate_delegation` with the existing id.
+11. **Respond** — `{ ok: true, id, delegationHash, expiresAt }`.
+12. **Usage event** — emit a row into `usage_events` (same pattern the MCP endpoints use — grep `usage_events` for an example) with event type `permissions.grant`.
+
+## Don't do this
+
+- Don't skip EIP-712 hash re-derivation — trusting the client-supplied `hash` opens replay across chains.
+- Don't store the raw signature separately from `delegation_json`. It's part of the envelope.
+- Don't log `delegation.signature`; log only `delegation.hash`.
+- Don't add a custom JWT path — use `getSessionUser`.
+- Don't allow a delegator != owner's linked wallet even if the delegator signed correctly — policy.
+
+## Acceptance
+
+- [ ] `api/permissions/grant.js` exists and is wired per `api/CLAUDE.md`.
+- [ ] Happy path: valid signed delegation → row inserted → 200 response with id.
+- [ ] Owner mismatch → 403.
+- [ ] Bad signature → 400.
+- [ ] Duplicate hash → 409.
+- [ ] Rate-limit returns 429 after threshold.
+- [ ] `node --check api/permissions/grant.js` passes.
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- `curl` transcripts for: happy path, owner mismatch, bad signature, duplicate.
+- The DB row after a successful grant (redact signature bytes to the first 10 chars).
diff --git a/prompts/permissions/07-api-list.md b/prompts/permissions/07-api-list.md
new file mode 100644
index 000000000..e6d65aa82
--- /dev/null
+++ b/prompts/permissions/07-api-list.md
@@ -0,0 +1,71 @@
+# Task 07 — `GET /api/permissions/list`
+
+## Why
+
+The manage panel (task 11), the SDK (task 18), and the dashboard all need to enumerate delegations for a given agent or a given delegator wallet. One read endpoint with consistent filtering keeps those callers simple.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint signature
+- [api/CLAUDE.md](../../api/CLAUDE.md) — `json` / `error` / `wrap` / `cors`
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — session + bearer auth helpers
+- Existing list endpoints in [api/agents.js](../../api/agents.js) or similar — pagination + filtering patterns
+
+## Build this
+
+Create `api/permissions/list.js` (GET only):
+
+1. **Method gate** — GET, else 405.
+2. **CORS + rate limit** — standard `limits.read` preset.
+3. **Auth mode** — two paths:
+ - `?agentId=<uuid>` — public view. Return only non-sensitive fields (no `delegation_json.signature`, no internal ids). Anyone can read — this is what the embed uses.
+ - `?delegator=0x...` or no filter — **session required**. Only the logged-in user may list their own delegations. Optionally admins (if `isAdmin` helper exists) may list any delegator.
+4. **Query params**:
+ - `agentId` (uuid) OR `delegator` (address)
+ - `status` (optional, `active|revoked|expired|all`, default `active`)
+ - `chainId` (optional int)
+ - `limit` (default 50, max 200), `offset` (default 0)
+5. **SQL** — tagged-template via `sql` from `api/_lib/db.js`. Build a `WHERE` with the supplied filters. Order by `created_at DESC`. Use the indexes from task 05.
+6. **Public view shape** (when agentId-only, no auth):
+ ```jsonc
+ {
+ "id": "...",
+ "chainId": 84532,
+ "delegator": "0x...",
+ "delegate": "0x...",
+ "delegationHash": "0x...",
+ "scope": {
+ /* from column */
+ },
+ "status": "active",
+ "expiresAt": "...",
+ "createdAt": "...",
+ "lastRedeemedAt": "...",
+ "redemptionCount": 3
+ }
+ ```
+ Never return `delegation_json` in the public view.
+7. **Authenticated view** — same as public, plus `delegationJson` (full envelope including signature) so the owner can re-pin if needed.
+8. **Response shape** — `{ ok: true, delegations: [...], nextOffset?: number }`. Include `nextOffset` if `result.length === limit`.
+9. **Cache headers** on public agentId view: `Cache-Control: public, max-age=30, s-maxage=60`. Not on authenticated view.
+
+## Don't do this
+
+- Don't run unfiltered queries. `agentId` or `delegator` is required — return 400 `missing_filter` if neither is supplied.
+- Don't return `delegation_json.signature` to anonymous callers.
+- Don't support a global list (all delegations). Even admins must scope to one agent or one delegator.
+- Don't paginate with cursors — offset is fine at our scale.
+
+## Acceptance
+
+- [ ] `api/permissions/list.js` wired per conventions.
+- [ ] Public `agentId` path returns redacted entries without auth.
+- [ ] `delegator` path returns 401 unauthenticated / 403 if someone else's address.
+- [ ] Filters `status`, `chainId` work.
+- [ ] Cache header present on public responses.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- `curl` transcripts: public agent view, owner-authenticated delegator view, cross-user 403, bad-filter 400.
+- Timing: `EXPLAIN ANALYZE` of the list query for a seeded agent.
diff --git a/prompts/permissions/08-api-revoke.md b/prompts/permissions/08-api-revoke.md
new file mode 100644
index 000000000..27152941d
--- /dev/null
+++ b/prompts/permissions/08-api-revoke.md
@@ -0,0 +1,51 @@
+# Task 08 — `POST /api/permissions/revoke`
+
+## Why
+
+Revocation is the trust anchor of the whole system. On-chain truth is `DelegationManager.disableDelegation(hash)`, but we must mirror that off-chain so the UI + indexer + metadata endpoint reflect it instantly. The client calls the contract; the server records the tx hash and flips `status='revoked'` after verifying the on-chain state.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint shape + error codes
+- [src/erc7710/abi.js](../../src/erc7710/abi.js) — `DELEGATION_MANAGER_ABI` (has `isDelegationDisabled`)
+- [api/CLAUDE.md](../../api/CLAUDE.md) — conventions
+- [api/\_lib/chain.js](../../api/_lib/chain.js) if present, or wherever read-only RPC calls are made; otherwise use `ethers.JsonRpcProvider` directly with a public RPC URL from `src/erc8004/chain-meta.js`
+
+## Build this
+
+Create `api/permissions/revoke.js` (POST only):
+
+1. Standard gates: POST, CORS, `limits.write`, `getSessionUser` (401 on absent).
+2. **Body**: `{ id: uuid, txHash: '0x...' }` — both required.
+3. **Lookup**: `SELECT * FROM agent_delegations WHERE id = $1`. 404 `delegation_not_found` if missing.
+4. **Authorization**: Only the delegator (the wallet that signed the grant) or the agent owner may revoke. Verify by joining `agents.owner_user_id == user.id` OR `row.delegator_address == user.linked_wallet`. Else 403.
+5. **On-chain verification (the key step)**:
+ - Build a read-only provider for `row.chain_id`.
+ - Fetch the receipt for `txHash`. If null → 400 `tx_not_found`.
+ - Decode the `DelegationDisabled` event from the receipt's logs; compare its `delegationHash` to `row.delegation_hash`. Mismatch → 400 `tx_mismatch`.
+ - Call `DelegationManager.isDelegationDisabled(row.delegation_hash)` as a second confirmation. Must return `true`. Else 400 `not_yet_disabled` (receipt may be pending on the indexed chain replica).
+6. **Persist**: `UPDATE agent_delegations SET status='revoked', revoked_at=NOW(), tx_hash_revoke=$1 WHERE id=$2 AND status='active'`. If 0 rows updated → 409 `already_revoked`.
+7. **Response**: `{ ok: true, status: 'revoked', revokedAt }`.
+8. **Usage event**: emit `permissions.revoke`.
+
+## Don't do this
+
+- Don't trust `txHash` without fetching the receipt and decoding the event. Anyone could post a random hash otherwise.
+- Don't run the revocation on-chain from the server side. The user initiates the on-chain write from the UI with their wallet; the server only mirrors.
+- Don't allow status transitions other than `active → revoked` here.
+- Don't hammer the RPC. One `getTransactionReceipt` + one `eth_call` per request is fine; if you add retries, cap to 3.
+
+## Acceptance
+
+- [ ] Happy path: row flips to `revoked` with `tx_hash_revoke` stored.
+- [ ] Non-owner/non-delegator → 403.
+- [ ] Bad tx hash → 400.
+- [ ] Tx doesn't actually revoke this delegation → 400 `tx_mismatch`.
+- [ ] Already revoked → 409.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Receipt-decoding snippet you used.
+- `curl` transcript of happy path with a real Base Sepolia revocation tx.
+- Explorer link for the tx.
diff --git a/prompts/permissions/09-api-redeem.md b/prompts/permissions/09-api-redeem.md
new file mode 100644
index 000000000..3475a9991
--- /dev/null
+++ b/prompts/permissions/09-api-redeem.md
@@ -0,0 +1,70 @@
+# Task 09 — `POST /api/permissions/redeem` (optional relayer path)
+
+## Why
+
+Skills running inside a host iframe (Claude artifact, LobeHub) may not have access to a signer that can pay gas. This endpoint lets the agent's server-side runtime redeem a delegation on its behalf: the server holds the **agent's** smart-account key (never the user's), pays gas, and submits `redeemDelegations(...)` within the caveats. This is opt-in per agent; agents that prefer a pure client-side flow simply never call this.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint + error codes, trust model callout ("the agent's smart account key may be held server-side only if the task explicitly says so — this is that task")
+- [api/CLAUDE.md](../../api/CLAUDE.md) — `authenticateBearer` for agent-scope tokens (not user sessions)
+- [src/permissions/toolkit.js](../../src/permissions/toolkit.js) — `redeemDelegation`, `isDelegationValid` (task 04)
+- [api/\_lib/db.js](../../api/_lib/db.js) — persistence
+- `.env.example` — add the new env vars here (do not commit real values)
+
+## Build this
+
+1. **Env**: add these to `.env.example` and read them via `process.env`:
+ - `AGENT_RELAYER_KEY` — hex private key of a relayer EOA (server-held) that submits `redeemDelegations` on behalf of agents. One key per environment; rotate via Vercel env.
+ - `AGENT_RELAYER_ADDRESS` — derived; used as the `delegate` for any delegation the relayer can redeem.
+ - `RPC_URL_<CHAINID>` — per-chain RPC (e.g. `RPC_URL_84532`). Reuse existing RPC env vars if already defined in the project; grep first.
+ - A feature flag `PERMISSIONS_RELAYER_ENABLED=true|false`. Default false. Endpoint 503s if false.
+
+2. **Create `api/permissions/redeem.js`** (POST only):
+ - Method/CORS/rate-limit (`limits.strict` — this one costs gas).
+ - Auth: `authenticateBearer(req)` against `api_keys` table (agent-scope bearer; scope must include `permissions:redeem`). No user sessions here — this is a machine endpoint.
+ - Body: `{ id: uuid, calls: [{ to, value, data }] }`, max 4 calls. Validate each call: `to` checksummed, `value` stringified wei, `data` hex.
+ - Load the delegation row. 404 if missing. Reject if `status !== 'active'`.
+ - Reject if `expires_at <= NOW()` and flip status to `expired` in a side-effect UPDATE.
+ - Scope check (server-side, before touching chain):
+ - For each call, `calls[i].to` must appear in `scope.targets`.
+ - If `scope.token` is an ERC-20, reject any call with non-zero `value`.
+ - If `scope.token == 'native'`, sum of `value` this period must stay ≤ `scope.maxAmount`. Compute period window from `scope.period` and `last_redeemed_at` trail (query recent rows).
+ - If `scope.token` is an ERC-20 contract, decode the ERC-20 `transfer`/`transferFrom` call selector from `calls[i].data` and check the amount argument; sum across calls + period history.
+ - Build signer from `AGENT_RELAYER_KEY` against `new JsonRpcProvider(RPC_URL_<chainId>)`.
+ - Call `redeemDelegation({ delegation: row.delegation_json, calls, signer, chainId })` from the toolkit.
+ - On success: `UPDATE agent_delegations SET redemption_count = redemption_count + 1, last_redeemed_at = NOW() WHERE id = $1`.
+ - Emit `usage_events` row with event `permissions.redeem`, cost = gas used.
+ - Respond `{ ok: true, txHash, receipt }` (trim receipt to `{ status, blockNumber, gasUsed }`).
+
+3. **Failure modes**:
+ - Toolkit throws `PermissionError` with code `delegation_revoked` → 409.
+ - RPC error → 502 `rpc_error`.
+ - Scope exceeded (our own check) → 403 `scope_exceeded`.
+ - Target not allowed → 403 `target_not_allowed`.
+ - Rate-limited → 429.
+
+4. **Idempotency**: accept optional `Idempotency-Key` header; if supplied and a recent row exists for (`id`, key) → return the cached `txHash` instead of submitting a second tx. Keep the map in memory for 10 minutes or in a `permissions_idempotency` small table if you prefer durability — pick one and stick to it.
+
+## Don't do this
+
+- Do not hold the user's key. Ever. Only the relayer EOA.
+- Do not skip scope verification on the server just because caveats are enforced on-chain. Our server checks are cheap and prevent paying gas on a doomed tx.
+- Do not allow `calls.length > 4`. Batched delegation chains are out of scope for v0.1.
+- Do not log `AGENT_RELAYER_KEY` or any intermediate signer state.
+- Do not put this on the public MCP route — it's a bearer-token endpoint only.
+
+## Acceptance
+
+- [ ] Endpoint submits a real Base Sepolia tx given a valid active delegation.
+- [ ] Scope violations return 403 without touching the chain.
+- [ ] Expired delegation is auto-flipped to `expired`.
+- [ ] Idempotency-Key prevents double-submit.
+- [ ] `node --check` + `npm run build` pass.
+- [ ] `.env.example` documents all new vars.
+
+## Reporting
+
+- Transcript of a real Base Sepolia redemption (tx hash + explorer link).
+- The `scope_exceeded` response body when you intentionally over-spend.
+- Gas-used delta of a typical redemption.
diff --git a/prompts/permissions/10-grant-ui.md b/prompts/permissions/10-grant-ui.md
new file mode 100644
index 000000000..c617a6b18
--- /dev/null
+++ b/prompts/permissions/10-grant-ui.md
@@ -0,0 +1,73 @@
+# Task 10 — Grant Permissions modal (`src/permissions/grant-modal.js`)
+
+## Why
+
+This is the user-facing surface where permissions are born. The modal shows the scope in **plain English first**, then opens MetaMask, then posts the signed delegation to `/api/permissions/grant`. The quality of this UI is load-bearing for trust — a confusing scope screen = user declines = the whole band fails.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical scope shape, API contract
+- [src/permissions/toolkit.js](../../src/permissions/toolkit.js) — `encodeScopedDelegation`, `signDelegation`, `delegationToManifestEntry` (task 04)
+- [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) — existing modal pattern; match the visual style and modal framing
+- [src/components/](../../src/components/) — any shared modal / button primitives to reuse
+- [src/CLAUDE.md](../../src/CLAUDE.md) — viewer/agent layering rules (permissions UI lives in the agent half)
+
+## Build this
+
+1. **Module**: `src/permissions/grant-modal.js` (vhtml JSX `.jsx` if the sibling UI files use it — match the local convention; check existing `src/permissions/*` files if any, else check `src/erc8004/register-ui.js`).
+2. **Public API**: a default export class `GrantPermissionsModal` with:
+ - `constructor({ agentId, chainId, delegatorAddress, delegateAddress, presets? })`
+ - `async open()` returning `Promise<{ ok: true, id, delegationHash } | { ok: false, reason }>`
+ - `close()` for imperative close
+3. **Modal flow (three steps, single modal, progress breadcrumb at top):**
+
+ **Step 1 — Scope builder.** Form with:
+
+ - **Token** — radio of common tokens for the chain (native, USDC, WETH) + a custom address input
+ - **Max amount** — numeric + unit dropdown (token decimals resolved via an on-chain `decimals()` call or a hardcoded table for the well-known set)
+ - **Period** — `once | daily | weekly`
+ - **Expiry** — preset pills (`24h | 7d | 30d | custom`) + custom datetime
+ - **Allowed targets** — multi-entry address list with a helper "Add from known contracts" dropdown (populate with well-known DEX / tip-jar addresses; else "Custom" only)
+ - Presets from the constructor pre-fill the form (e.g. Tip Jar skill passes a preset).
+
+ **Step 2 — Plain-English review.**
+
+ - A single sentence per caveat, generated from the form values, e.g. "This agent can spend up to **10 USDC per day** on **Uniswap V3 Router (0x68b...)** until **Apr 18, 2026**."
+ - Red warning if any target isn't allow-listed.
+ - "Back" and "Continue to MetaMask" buttons.
+
+ **Step 3 — Sign + submit.**
+
+ - Call `encodeScopedDelegation(...)` with form values + `delegatorAddress` + `delegateAddress` + `chainId`.
+ - Call `signDelegation(delegation, signer)`. Use the project's existing wallet-provider helper (grep `BrowserProvider` or `connectWallet` in `src/erc8004/`) to get the signer. **Do not create a second wallet-connection path.**
+ - On signature success, `POST /api/permissions/grant` with `{ agentId, chainId, delegation, scope }`.
+ - Show status transitions: "Waiting for signature…", "Submitting…", "Granted ✓" / "Failed: <server error code>".
+ - On 200, resolve `{ ok: true, id, delegationHash }` and auto-close after 1.5s.
+ - On failure, surface the server `error` string verbatim; offer retry (without re-signing — same signature can be resubmitted until it 409s).
+
+4. **Styling**: use existing CSS variables / classes from the project (grep for `.modal` usage). No new CSS framework. Tabs, 4-wide, single quotes, 100 cols.
+5. **Accessibility**: focus trap, `aria-modal`, Esc closes, tab order sensible.
+6. **Entry point**: export a convenience `window.openGrantPermissions = (opts) => new GrantPermissionsModal(opts).open()` for the manage panel and skills to call — only exposed when `window.AGENT_DEBUG` is true OR via explicit `import`. Do not overwrite an existing global.
+
+## Don't do this
+
+- Do not build a new wallet-connect path. Reuse the existing one.
+- Do not auto-approve anything — every button is user-initiated.
+- Do not show USD conversions. Show token units only (avoids stale price oracles).
+- Do not submit the signature more than once automatically.
+- Do not introduce new npm deps.
+- Do not leak signatures to analytics / console.
+
+## Acceptance
+
+- [ ] Modal opens from the manage panel and from a skill preset.
+- [ ] All three steps are keyboard-navigable.
+- [ ] Real MetaMask signature prompt shows the correct domain + message (verify via MM's "Signature details" expand).
+- [ ] Happy path ends with a toast and the manage panel refreshes.
+- [ ] Reject/close paths resolve cleanly, no zombie listeners.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Screenshot of each of the three steps + the MetaMask signature view.
+- Transcript of the `POST /api/permissions/grant` happy path and one rejected case.
diff --git a/prompts/permissions/11-manage-ui.md b/prompts/permissions/11-manage-ui.md
new file mode 100644
index 000000000..037682cbe
--- /dev/null
+++ b/prompts/permissions/11-manage-ui.md
@@ -0,0 +1,57 @@
+# Task 11 — Manage Permissions panel (`src/permissions/manage-panel.js`)
+
+## Why
+
+Owners need a single surface to see every active delegation, how much has been used against the scope, and revoke any of them with one click. This is the flip-side of task 10 — grant in, manage out.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical `GET /api/permissions/list` + `POST /api/permissions/revoke` shapes
+- [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) — owner-only surface pattern + wallet helpers
+- [src/account.js](../../src/account.js) or the dashboard entry point — mount this panel where "on-chain" chip already lives
+- [src/erc7710/abi.js](../../src/erc7710/abi.js) — need `DELEGATION_MANAGER_ABI` to call `disableDelegation` on-chain
+
+## Build this
+
+1. **Module**: `src/permissions/manage-panel.js`.
+2. **Public API**: `mountManagePanel({ container, agentId })` — renders into the given element; returns an `unmount()` function.
+3. **Data flow**:
+ - On mount: `GET /api/permissions/list?agentId=...&status=all&limit=200`.
+ - For each row, render a card with:
+ - Scope in the same plain-English sentence as task 10 ("Up to 10 USDC per day on Uniswap V3 Router until Apr 18, 2026")
+ - Badges: `active` (green), `revoked` (gray), `expired` (amber)
+ - Chain chip (use existing chain chip from `src/erc8004/chain-meta.js`)
+ - Usage line: `X redemptions · last used Y ago`
+ - Actions: **Revoke** button (only if active and user is delegator or owner)
+ - Explorer link to the delegator + delegate addresses
+4. **Revoke action**:
+ - Require connected wallet = delegator address (guard; prompt "Connect with <0xabc…> to revoke").
+ - Call `DelegationManager.disableDelegation(delegationHash)` via ethers signer.
+ - Show tx-pending state (spinner + explorer link to the pending tx).
+ - On receipt: `POST /api/permissions/revoke` with `{ id, txHash }`.
+ - On success: flip the card UI to `revoked` without a full refetch; optimistic plus background refetch.
+ - On any error: surface verbatim, keep the card in the active state.
+5. **Empty state**: "No permissions granted yet. [Grant permissions]" — the button opens the grant modal (task 10) via `window.openGrantPermissions` if available, else a static hint.
+6. **Polling / refresh**: refetch on window focus (lightweight). No constant polling.
+7. **Styling**: reuse existing card / button primitives. Match the dashboard.
+8. **Wire-up point**: add a mount call on the agent page (`src/agent-home.js` or the dashboard — grep for where the on-chain chip renders today; add the panel directly below it). Guard with the same owner gate already in use.
+
+## Don't do this
+
+- Do not revoke via server first. On-chain is the source of truth; server mirrors. Doing it server-first creates desync.
+- Do not silently skip cards when the hash is unknown to the indexer — show them anyway with a "pending indexer" sub-label.
+- Do not show the full signature or `delegation_json`; just hash + scope + status.
+- Do not add pagination yet. Cap at 200; if a user hits that we'll deal with it.
+
+## Acceptance
+
+- [ ] Panel mounts on agent page for owners only.
+- [ ] Lists active + revoked + expired correctly.
+- [ ] Revoke submits real tx → server mirror flips status → UI updates.
+- [ ] Disconnected wallet path guides user to connect (no crash).
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Screenshots: full panel, revoke pending state, post-revoke state.
+- The happy-path `POST /api/permissions/revoke` transcript.
diff --git a/prompts/permissions/12-api-metadata.md b/prompts/permissions/12-api-metadata.md
new file mode 100644
index 000000000..2309e8041
--- /dev/null
+++ b/prompts/permissions/12-api-metadata.md
@@ -0,0 +1,73 @@
+# Task 12 — `GET /api/permissions/metadata` (public, embed-facing)
+
+## Why
+
+An embed (Claude artifact, LobeHub plugin, iframe on a random site) needs a CORS-open, unauthenticated way to learn what delegations an agent holds so its skills can decide whether to offer a "Tip the creator" or "Subscribe" button, and so the SDK can pre-seed its delegation cache. This is distinct from `/list` — metadata is cacheable, always public-view only, and is the canonical input to the manifest-derived `permissions` field.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint
+- [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md) — task 02 adds the `permissions.delegations[]` shape; mirror it in the response
+- [api/agent-oembed.js](../../api/agent-oembed.js) — good example of a public embed-facing GET endpoint with aggressive cache headers
+- [api/\_lib/http.js](../../api/_lib/http.js) — `json`, `cors`, `wrap`
+
+## Build this
+
+Create `api/permissions/metadata.js` (GET only):
+
+1. Method/CORS (wide-open: `*`)/rate-limit (`limits.read` or looser, this is cache-friendly).
+2. **Query**: `agentId` (uuid) — required. Optional `chainId` (int) filter.
+3. **SQL**: select only `active` delegations for that agent, ordered `expires_at DESC`. Do NOT return revoked/expired ones — the embed only cares about what's currently usable.
+4. **Shape** (must match `specs/AGENT_MANIFEST.md` `permissions.delegations[]`):
+ ```jsonc
+ {
+ "ok": true,
+ "agentId": "...",
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...", // resolved from abi.js per chainId
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0x...",
+ "delegate": "0x...",
+ "hash": "0x...",
+ "scope": {
+ /* from column, redacted signatures */
+ },
+ "expiresAt": "...",
+ "createdAt": "...",
+ "envelope": {
+ /* full signed envelope INCLUDING signature — it's on-chain verifiable, not secret */
+ }
+ }
+ ]
+ }
+ ```
+ Signatures are NOT secret — they're meant to be on-chain-verifiable. Including the envelope is what lets an embed redeem without a round-trip. This is the intentional difference from `/list`'s public view.
+5. **Cache**: `Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=600`. Set `ETag` from a hash of the JSON response.
+6. **CORS**: `Access-Control-Allow-Origin: *`. This endpoint is the fastest path for embeds.
+7. **404** if agentId doesn't exist; return `{ ok: false, error: 'agent_not_found' }`.
+8. **Empty `delegations: []`** is not an error — just return `ok: true` with an empty array.
+9. **Add a `Last-Modified`** header derived from `MAX(created_at, revoked_at)` of the agent's delegations.
+
+## Don't do this
+
+- Do not require auth. This is the public metadata path. (If you think a particular agent should be private → that's an agent-level privacy flag, not this endpoint's job.)
+- Do not return `id` (the internal UUID) — embeds don't need it and it's an internal handle. `hash` is the stable identifier.
+- Do not return `delegation_json` minus signature — always send the full signed envelope or nothing.
+- Do not do per-chain pagination. If an agent has >50 delegations across chains, respond with all of them.
+
+## Acceptance
+
+- [ ] Endpoint responds CORS-open, cacheable.
+- [ ] Envelope shape matches manifest spec byte-compatible.
+- [ ] ETag / Last-Modified / Cache-Control all set correctly.
+- [ ] Empty-agent case returns `[]`, not 404.
+- [ ] Unknown agent returns 404 with `agent_not_found`.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- `curl -I` output showing all cache headers.
+- `curl` of a seeded agent showing the full response.
+- Time-to-first-byte measurement (should be sub-200ms from a warm cache).
diff --git a/prompts/permissions/13-runtime-redeem-hook.md b/prompts/permissions/13-runtime-redeem-hook.md
new file mode 100644
index 000000000..598238fb0
--- /dev/null
+++ b/prompts/permissions/13-runtime-redeem-hook.md
@@ -0,0 +1,64 @@
+# Task 13 — Runtime delegation-redeem hook (`src/runtime/delegation-redeem.js`)
+
+## Why
+
+Skills are the primary consumer of delegations. A skill ("tip the creator", "subscribe", "execute DCA") calls a single runtime function to do an on-chain action, and the runtime figures out the right delegation, the right path (relayer or local signer), and the right error surfacing. Without this, every skill would have to reinvent the plumbing.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical `src/runtime/delegation-redeem.js` exports
+- [src/runtime/](../../src/runtime/) — the existing runtime module structure (scene controller, protocol bus)
+- [src/agent-protocol.js](../../src/agent-protocol.js) — `ACTION_TYPES` and how the event bus is typed; we will emit new events from this module
+- [src/permissions/toolkit.js](../../src/permissions/toolkit.js) — `redeemDelegation`, `isDelegationValid` (task 04)
+- [src/agent-skills.js](../../src/agent-skills.js) — how skills are invoked today, to confirm the interface will fit
+
+## Build this
+
+Create `src/runtime/delegation-redeem.js` exporting:
+
+1. **`async getActiveDelegation({ agentId, chainId, scopeHint? })`**
+ - Fetches `/api/permissions/metadata?agentId=...&chainId=...`.
+ - Filters to the delegation whose `scope` best matches `scopeHint` (if provided: prefer a scope with the right `token` and enough remaining `maxAmount`).
+ - Returns the envelope or `null` if none match.
+ - Caches the response in-memory for 60 seconds keyed by `{agentId, chainId}`. Cache is invalidated on a successful revoke event via the protocol bus.
+
+2. **`async redeemFromSkill({ agentId, chainId, calls, skillId, mode? })`**
+ - `mode` is `'client' | 'relayer' | 'auto'` (default `'auto'`).
+ - `'client'`: get a signer from the host page's wallet helper (same one task 10 uses) and call `redeemDelegation` from the toolkit directly.
+ - `'relayer'`: `POST /api/permissions/redeem` with a bearer token pulled from the agent's runtime config (the host is responsible for providing the bearer; if missing, throw `no_relayer_token`).
+ - `'auto'`: prefer `'client'` if a wallet is connected, else `'relayer'` if a token is available, else throw `no_redemption_path`.
+ - Pre-flight: call `getActiveDelegation`; throw `no_delegation` if none.
+ - Pre-flight: validate each call against `scope.targets` and (rough) amount limits. Cheap, prevents wasted gas.
+ - Emit `protocol.emit('permissions.redeem.start', {...})` before submission.
+ - On success, emit `permissions.redeem.success` with `{ txHash, skillId, delegationHash }`.
+ - On failure, emit `permissions.redeem.error` with `{ code, message, skillId }`.
+ - Return `{ ok: true, txHash }` or `{ ok: false, code, message }`.
+
+3. **`subscribeRedeemEvents(handler)`** — small helper that returns an `unsubscribe` for tests / UI surfaces that want to react to redemptions in the conversation stream.
+
+4. **Rate limiting in the runtime itself**: a skill must not be able to trigger >5 redemption attempts per minute from a single tab. Use a simple token bucket. Exceeding it throws `rate_limited` without hitting the network. This protects against runaway skill loops (per `src/CLAUDE.md` warnings).
+
+5. **Register new action types** in `src/agent-protocol.js` (append to `ACTION_TYPES`): `PERMISSIONS_REDEEM_START`, `PERMISSIONS_REDEEM_SUCCESS`, `PERMISSIONS_REDEEM_ERROR`. Touch this file minimally — just add the strings.
+
+## Don't do this
+
+- Do not hold a long-lived signer. Always fetch it lazily.
+- Do not bypass the runtime rate limiter. It's the backstop for buggy skills.
+- Do not import viewer modules (`SceneController`, three.js) — this is runtime-layer, not viewer-layer.
+- Do not cache the signed envelope across tabs (localStorage). Memory only.
+- Do not retry failed redemptions automatically — that's the skill's call.
+
+## Acceptance
+
+- [ ] `redeemFromSkill` works in `client` mode against Base Sepolia with a real delegation.
+- [ ] `relayer` mode posts to `/api/permissions/redeem` and returns the tx hash.
+- [ ] `auto` mode picks correctly when only one path is available.
+- [ ] Runaway skill (6 calls in 10s) trips the internal rate limiter.
+- [ ] Protocol events fire on the bus with correct payloads.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Transcript of a real redemption in `client` mode (tx hash on explorer).
+- Transcript of a real redemption in `relayer` mode.
+- The `ACTION_TYPES` diff on `src/agent-protocol.js`.
diff --git a/prompts/permissions/14-skill-tip-jar.md b/prompts/permissions/14-skill-tip-jar.md
new file mode 100644
index 000000000..6d4c72b00
--- /dev/null
+++ b/prompts/permissions/14-skill-tip-jar.md
@@ -0,0 +1,68 @@
+# Task 14 — Reference skill: Tip Jar (`public/skills/tip-jar/`)
+
+## Why
+
+The simplest useful permission-consumer. A viewer tips the creator with USDC (or native ETH) up to a pre-approved daily cap. It's the proof-of-life for the entire band — if this works from a Claude artifact embed, the rest of the surface area follows.
+
+## Read first
+
+- [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) — authoritative skill bundle layout + `SKILL.md` frontmatter
+- [public/skills/](../../public/skills/) — any existing reference skills (copy their structure)
+- [00-README.md](./00-README.md) — canonical scope shape
+- [src/runtime/delegation-redeem.js](../../src/runtime/delegation-redeem.js) — task 13; the skill calls `redeemFromSkill`
+- [src/permissions/grant-modal.js](../../src/permissions/grant-modal.js) — task 10; the skill opens this modal with a preset if no delegation exists
+
+## Build this
+
+Create `public/skills/tip-jar/` with:
+
+1. **`SKILL.md`** — frontmatter per `SKILL_SPEC.md`:
+ - `name: tip-jar`
+ - `version: 0.1.0`
+ - `trust: owned-only` (per repo invariant)
+ - `permissions_required: true`
+ - `default_scope_preset`:
+ ```jsonc
+ {
+ "token": "<USDC address per chain>",
+ "maxAmount": "10000000", // 10 USDC (6 decimals)
+ "period": "daily",
+ "targets": ["<this skill's executor contract>"],
+ "expiry_days": 30
+ }
+ ```
+ - Body: short human description of what it does.
+2. **`skill.js`** — ESM module exporting:
+ - `async setup({ agent, host })` — attaches a "Tip the creator" button to the agent's chat UI via `host.attachAction(...)` (use whichever existing API skills use; grep `setup({` in current `public/skills/` or `src/agent-skills.js`).
+ - `async execute({ agent, host, args })` — entry point invoked when the viewer clicks the button:
+ 1. Ask the viewer for an amount (max = scope.maxAmount remaining). Render a small tip-amount picker (1 / 5 / 10 USDC or custom).
+ 2. Call `redeemFromSkill({ agentId, chainId: agent.chainId, skillId: 'tip-jar', calls: [ buildERC20Transfer(usdcAddr, agent.ownerAddress, amount) ], mode: 'auto' })`.
+ 3. On success, say a canned line via `host.speak('Thank you for the tip!')` and emit a confetti event on the protocol bus (`tip.received`).
+ 4. On `no_delegation` error, prompt "The creator hasn't enabled tipping on this device yet." and expose a "Grant tipping" action — owner-only, opens the grant modal with the preset above.
+ - `buildERC20Transfer(tokenAddr, recipient, amountBaseUnits)` — pure helper returning `{ to, value: '0', data: <ERC-20 transfer calldata> }` using ethers Interface.
+3. **`skill.css`** — tiny, optional. Follow the existing skill CSS pattern.
+4. **`README.md`** — how the skill works end-to-end, the scope it requests, the happy-path flow diagram in ASCII (5-7 lines).
+5. **Manifest reference** — add the skill's relative path to the **Tip Jar** entry in the agent manifest fixture at wherever the skill registry lives; if there's no registry file, mention in your report but don't create one.
+
+## Don't do this
+
+- Do not take custody of funds. Transfer direct from delegator → owner; the skill never holds USDC.
+- Do not hardcode the owner's address — pull from `agent.ownerAddress` (the agent manifest already knows this).
+- Do not embed a price oracle or USD display. Token units only.
+- Do not let a non-owner grant the delegation — the "Grant tipping" path is gated on ownership.
+- Do not introduce React or any templating lib. Use the same vhtml / vanilla pattern other skills use.
+
+## Acceptance
+
+- [ ] Skill loads inside the main app (`npm run dev`) without errors.
+- [ ] With a live delegation, a tip actually lands on Base Sepolia (tx hash in reporting).
+- [ ] Without a delegation, owner can click "Grant tipping" → grant modal → new tip → success.
+- [ ] Non-owner viewer without a delegation gets the friendly "not enabled yet" copy.
+- [ ] `node --check public/skills/tip-jar/skill.js` passes.
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- Explorer link to a real Base Sepolia tip tx.
+- Screenshot of the tip UI in the viewer.
+- The exact calldata you built for the ERC-20 transfer (hex).
diff --git a/prompts/permissions/15-skill-subscription.md b/prompts/permissions/15-skill-subscription.md
new file mode 100644
index 000000000..030496ffa
--- /dev/null
+++ b/prompts/permissions/15-skill-subscription.md
@@ -0,0 +1,77 @@
+# Task 15 — Reference skill: Subscription (`public/skills/subscription/`)
+
+## Why
+
+The marquee use case from the MetaMask Advanced Permissions announcement: recurring on-chain payments that work without the user re-signing every period. A subscribed viewer grants a monthly cap; the skill triggers a `transfer` on each period boundary via the relayer path until revoked or expired.
+
+## Read first
+
+- [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) — skill frontmatter + lifecycle hooks
+- [public/skills/tip-jar/](../../public/skills/tip-jar/) — sibling skill (task 14); share the helper pattern for ERC-20 calldata
+- [00-README.md](./00-README.md) — scope shape (`period: 'weekly'` / `'daily'`)
+- [src/runtime/delegation-redeem.js](../../src/runtime/delegation-redeem.js) — `redeemFromSkill` with `mode: 'relayer'` — subscriptions need the server path because they fire when the user isn't present
+- [api/cron/](../../api/cron/) — the existing cron endpoint pattern, since we'll register a cron trigger for the subscription
+- [vercel.json](../../vercel.json) — cron schedule declaration
+
+## Build this
+
+Create `public/skills/subscription/` with:
+
+1. **`SKILL.md`** with frontmatter:
+ - `name: subscription`
+ - `version: 0.1.0`
+ - `trust: owned-only`
+ - `permissions_required: true`
+ - `default_scope_preset`:
+ ```jsonc
+ {
+ "token": "<USDC>",
+ "maxAmount": "5000000", // 5 USDC
+ "period": "weekly",
+ "targets": ["<subscription executor contract>"],
+ "expiry_days": 90
+ }
+ ```
+2. **`skill.js`** — ESM exporting:
+ - `async setup({ agent, host })` — attaches a "Subscribe · 5 USDC / week" action to the agent UI.
+ - `async execute({ agent, host, args })` — for the viewer's initial subscription action:
+ 1. Opens the grant modal (task 10) pre-filled with `default_scope_preset`.
+ 2. On successful grant, calls `POST /api/subscriptions` (new endpoint, below) with `{ agentId, delegationId, periodSeconds: 7*24*3600, amountPerPeriod }`.
+ 3. Confirms in the chat: "You're subscribed until <date>. Revoke anytime in the Manage panel."
+ - `async onPeriod({ agent, subscription })` — invoked by the server-side cron (via a dynamic import); does NOT run in the browser. Calls `redeemFromSkill(..., mode: 'relayer')` with a single ERC-20 `transfer` call for the period amount. Returns `{ ok, txHash }` to the cron.
+3. **New endpoint `api/subscriptions.js`**:
+ - POST: records `{ agentId, delegationId, periodSeconds, amountPerPeriod, nextChargeAt }` in a new `agent_subscriptions` table (add a tiny schema file `specs/schema/agent_subscriptions.sql` following task 05's style). Keep this schema self-contained; do not modify task 05's file.
+ - GET: list for the authenticated user.
+ - DELETE: soft-cancel a subscription (sets `status='canceled'`). Does NOT revoke the delegation — revocation is a separate user action in the manage panel.
+4. **New cron `api/cron/run-subscriptions.js`**:
+ - Scheduled hourly via `vercel.json` `crons` entry.
+ - Selects `agent_subscriptions` rows with `status='active' AND next_charge_at <= NOW()`.
+ - For each, loads the delegation row, confirms `status='active'` and not expired.
+ - Calls the skill's `onPeriod` handler (via dynamic `import` from the skill's `skill.js` — the cron is server-side, the import is server-side).
+ - On success, updates `last_charge_at` + advances `next_charge_at`.
+ - On failure (revoked/expired/scope_exceeded): marks the subscription `status='paused'` with a `last_error` column; does not retry automatically.
+ - Emits `usage_events` rows.
+5. **Manifest reference** — same note as task 14.
+
+## Don't do this
+
+- Do not invoke the skill's `onPeriod` from the browser. Browser path only initiates the subscription; recurrence is strictly server-side.
+- Do not retry failed charges silently. `paused` + user notification (email out of scope; surface in the manage panel) is correct.
+- Do not run the cron every minute. Hourly is plenty; weekly subscriptions don't need minute precision.
+- Do not charge more than `amountPerPeriod` per period, even if the delegation would allow it.
+- Do not persist the delegator's private key or bearer tokens in `agent_subscriptions` — reference `delegationId` only.
+
+## Acceptance
+
+- [ ] Viewer subscribes → grant modal → signature → DB row created → weekly cron picks it up.
+- [ ] Successful period charge lands on Base Sepolia via the relayer endpoint.
+- [ ] Revoked delegation flips the subscription to `paused`.
+- [ ] Expired delegation flips to `paused`.
+- [ ] Cron idempotent — re-running within the same period doesn't double-charge (enforced by `next_charge_at`).
+- [ ] `node --check` on all new JS + `npm run build` pass.
+
+## Reporting
+
+- Explorer link to a real period-charge tx.
+- Cron log transcript (success + one intentional failure case).
+- Screenshot of the subscription's manage panel card showing `active → paused` after an intentional revoke.
diff --git a/prompts/permissions/16-skill-dca.md b/prompts/permissions/16-skill-dca.md
new file mode 100644
index 000000000..0c78edd62
--- /dev/null
+++ b/prompts/permissions/16-skill-dca.md
@@ -0,0 +1,71 @@
+# Task 16 — Reference skill: DCA (`public/skills/dca/`)
+
+## Why
+
+The third canonical MetaMask announcement use case: an autonomous DCA (dollar-cost averaging) strategy that swaps a fixed USDC amount into WETH on a schedule. This is the first skill that calls a DEX (Uniswap V3 SwapRouter), so it exercises `scope.targets` for contract allow-listing and `scope.selectors` for function-level scoping.
+
+## Read first
+
+- [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) — skill layout
+- [public/skills/subscription/](../../public/skills/subscription/) — cron pattern; DCA reuses the same cron infrastructure (task 15) — if task 15's `api/cron/run-subscriptions.js` exists, extend it with a type discriminator; else create a dedicated `api/cron/run-dca.js`
+- [00-README.md](./00-README.md) — scope shape, note `selectors` field is optional; use it here
+- Uniswap V3 SwapRouter addresses per chain — verify from Uniswap docs, do not guess
+- [src/runtime/delegation-redeem.js](../../src/runtime/delegation-redeem.js) — `redeemFromSkill({ mode: 'relayer' })`
+
+## Build this
+
+Create `public/skills/dca/`:
+
+1. **`SKILL.md`** frontmatter:
+ - `name: dca`
+ - `version: 0.1.0`
+ - `trust: owned-only`
+ - `permissions_required: true`
+ - `default_scope_preset`:
+ ```jsonc
+ {
+ "token": "<USDC>",
+ "maxAmount": "100000000", // 100 USDC per day cap
+ "period": "daily",
+ "targets": ["<Uniswap V3 SwapRouter address>"],
+ "selectors": ["0x04e45aaf"], // exactInputSingle selector — verify from Uniswap ABI
+ "expiry_days": 30
+ }
+ ```
+2. **`skill.js`**:
+ - `setup({ agent, host })` — exposes a "Start DCA" action to the owner only.
+ - `execute({ agent, host, args })` (owner-facing):
+ 1. Prompts for: tokenIn (USDC fixed for v0.1), tokenOut (default WETH), amountPerExecution, frequency (`daily|weekly`).
+ 2. Opens the grant modal with the preset. Waits for signed delegation.
+ 3. `POST /api/dca-strategies` with `{ agentId, delegationId, tokenIn, tokenOut, amountPerExecution, periodSeconds, slippageBps }`.
+ - `onPeriod({ strategy })` (server-side, invoked by cron):
+ 1. Builds an `exactInputSingle` calldata for Uniswap V3 with current best quote. Use the existing quoter or fetch from the public Uniswap quoter contract; do not require a 3rd-party price API.
+ 2. Applies `slippageBps` to the quote to get `amountOutMinimum`.
+ 3. Calls `redeemFromSkill({ mode: 'relayer', calls: [ approveCall, swapCall ] })`. The approve call targets the USDC contract to approve SwapRouter for `amountPerExecution` — include USDC in `scope.targets` in the preset (fix: preset `targets` above should include **both** SwapRouter and USDC; update the preset to include `[SwapRouter, USDC]` and selectors for `approve` + `exactInputSingle`).
+ 4. Records the execution + resulting WETH amount in `dca_executions` table (new, small, per task 15's schema pattern).
+3. **New endpoint `api/dca-strategies.js`**:
+ - POST / GET / DELETE paralleling `api/subscriptions.js`. Small table `specs/schema/dca_strategies.sql` (new file, self-contained).
+4. **Cron**: extend task 15's cron if present, or add `api/cron/run-dca.js`. Hourly. Picks rows where `next_execution_at <= NOW()`.
+5. **Safety preset**: `slippageBps` default 50 (0.5%). Max 500 (5%) at the UI level.
+
+## Don't do this
+
+- Do not build our own routing logic. Use the Uniswap V3 quoter directly.
+- Do not skip the `approve` step. USDC requires allowance to the router per swap — reuse the approval where safe but re-approve if insufficient.
+- Do not allow arbitrary tokenOut at v0.1. Whitelist WETH and a small set of well-known tokens per chain (hardcoded).
+- Do not run DCA on mainnet by default. Base Sepolia first; owner must explicitly opt into mainnet with an extra confirmation in the UI.
+- Do not execute if the quote is >1% off a recent Coingecko check — optional safety, but at minimum check the Uniswap quoter twice 15s apart and abort if they diverge >0.5%.
+
+## Acceptance
+
+- [ ] Owner configures DCA → grant modal → delegation stored → strategy row inserted.
+- [ ] Next cron tick executes a real swap on Base Sepolia (tx hash in reporting).
+- [ ] Slippage-exceeded scenario aborts cleanly without redeeming.
+- [ ] Delegation expiry pauses the strategy.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Explorer link to a real DCA swap tx (Base Sepolia).
+- The quoter vs. executed-swap amounts + slippage used.
+- Screenshot of the strategy config UI.
diff --git a/prompts/permissions/17-embed-spec-delegation.md b/prompts/permissions/17-embed-spec-delegation.md
new file mode 100644
index 000000000..df68d6dce
--- /dev/null
+++ b/prompts/permissions/17-embed-spec-delegation.md
@@ -0,0 +1,64 @@
+# Task 17 — Embed Spec: delegation surface for hosts
+
+## Why
+
+The `<agent-3d>` embed and the Claude/LobeHub host integrations need documented, versioned rules for how they learn about an agent's delegations and which host capabilities let a skill redeem without a wallet popup. Without this, third-party hosts will either ignore the field or misuse it.
+
+## Read first
+
+- [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — the file you are editing
+- [specs/CLAUDE_ARTIFACT.md](../../specs/CLAUDE_ARTIFACT.md) — the Claude-artifact host profile
+- [specs/EMBED_HOST_PROTOCOL.md](../../specs/EMBED_HOST_PROTOCOL.md) — host→embed message protocol, if present
+- [00-README.md](./00-README.md) — canonical manifest `permissions` field + `/api/permissions/metadata` shape
+- [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md) — where task 02 adds the manifest field
+
+## Build this
+
+Append a new section to `specs/EMBED_SPEC.md` titled **Delegations (optional, v0.2+)** containing:
+
+1. **How the embed discovers delegations (two paths):**
+ - **Manifest path** — if the loaded `manifest.json` contains `permissions.delegations[]`, the embed uses that array directly. No network call needed.
+ - **Metadata path** — if the manifest omits `permissions` (e.g. it was pinned before permissions were granted), the embed MAY call `GET /api/permissions/metadata?agentId=...` to hydrate. Hosts must cache this for at least 60s.
+2. **Host attributes / init options** the embed surface exposes:
+ - `permissions="readonly" | "interactive" | "relayer"` — host's stance:
+ - `readonly` (default) — embed shows delegations, never initiates redemption
+ - `interactive` — embed may prompt for a signer (the host must provide one via `host.getSigner()`)
+ - `relayer` — embed may call `/api/permissions/redeem` with a bearer token the host has provisioned
+ - `permissions-bearer` — when `permissions="relayer"`, the bearer token scoped to `permissions:redeem` (per task 09). Opaque string, host is responsible for rotation.
+3. **Host → embed messages** (post-message protocol):
+ - `permissions.query` (host→embed): request a list of active delegations matching a filter
+ - `permissions.redeem` (host→embed): ask the embed to initiate a redemption on the host's behalf
+ - `permissions.redeemed` (embed→host): announce a successful redemption with tx hash
+ - `permissions.error` (embed→host): announce a failed redemption with code + message
+
+ Shapes documented inline, copy the error codes verbatim from the canonical shapes.
+4. **Claude artifact profile**:
+ - Default `permissions="readonly"`. Claude artifacts can render tipping UIs and show status, but a skill that needs to actually transact must request `permissions="relayer"` and the agent owner must provision a bearer token at embed time.
+ - Document that the artifact has no persistent wallet connection — `interactive` is not supported in the Claude profile.
+5. **LobeHub profile**:
+ - Supports all three modes. `interactive` is the default on LobeHub since LobeHub users typically have wallets configured.
+6. **Security**:
+ - Embeds MUST verify `delegation.hash === keccak256(delegation.envelope)` before trusting.
+ - Embeds MUST verify the delegator's signature recovers correctly before offering a redeem action (use `isDelegationValid` from the toolkit).
+ - Embeds MUST NOT persist the envelope to storage that is shared across origins.
+ - Hosts MUST NOT embed with `permissions="relayer"` without an owner-provided bearer; fall back to `readonly` if absent.
+7. **Version bump** — update the `EMBED_SPEC.md` top-level version from 0.1 → 0.2 and add a changelog entry.
+
+## Don't do this
+
+- Do not extend the post-message protocol with arbitrary new messages. Only the four listed above.
+- Do not speculate about multi-delegation chaining, session keys, or WebAuthn-gated redemption. Note as future work only.
+- Do not redefine the manifest shape here; reference `specs/AGENT_MANIFEST.md`.
+- Do not copy-paste the toolkit API into this spec — link to `specs/PERMISSIONS_SPEC.md` (task 01) for library contracts.
+
+## Acceptance
+
+- [ ] `specs/EMBED_SPEC.md` has a new **Delegations** section with all seven subsections.
+- [ ] Version bumped to `embed/0.2` with a changelog line.
+- [ ] Host-profile subsections for Claude + LobeHub exist.
+- [ ] `npx prettier --write specs/EMBED_SPEC.md` passes.
+
+## Reporting
+
+- Diff of the spec file.
+- Any inconsistencies you noticed vs. the existing `EMBED_HOST_PROTOCOL.md` (document, don't fix).
diff --git a/prompts/permissions/18-sdk-permissions.md b/prompts/permissions/18-sdk-permissions.md
new file mode 100644
index 000000000..6700563cc
--- /dev/null
+++ b/prompts/permissions/18-sdk-permissions.md
@@ -0,0 +1,101 @@
+# Task 18 — `@3dagent/sdk` permissions module
+
+## Why
+
+Third-party developers integrating agents into their own apps need a typed SDK entry point for listing, granting, and redeeming delegations. The raw REST endpoints are fine but a typed SDK is what unlocks partner integrations.
+
+## Read first
+
+- [sdk/](../../sdk/) — layout, tsconfig, existing module style (TS is OK here — the SDK is a separate package)
+- [sdk/package.json](../../sdk/package.json) — deps, scripts
+- [00-README.md](./00-README.md) — canonical API surface
+- [src/permissions/toolkit.js](../../src/permissions/toolkit.js) — task 04; the SDK may re-export selected helpers
+- [specs/PERMISSIONS_SPEC.md](../../specs/PERMISSIONS_SPEC.md) — task 01; SDK JSDoc must match types here
+
+## Build this
+
+1. **New module** `sdk/src/permissions.ts` (TS if the SDK is TS; match local convention — check sibling files).
+2. **Exports**:
+
+ ```ts
+ export interface DelegationPublic {
+ /* ... matches metadata endpoint shape ... */
+ }
+ export interface ScopePreset {
+ token: string;
+ maxAmount: string;
+ period: 'once' | 'daily' | 'weekly';
+ targets: string[];
+ expiryDays: number;
+ }
+ export class PermissionsClient {
+ constructor(opts: { baseUrl?: string; bearer?: string });
+
+ listDelegations(params: { agentId?: string; delegator?: string; status?: string }): Promise<DelegationPublic[]>;
+
+ getMetadata(agentId: string): Promise<{ spec: string; delegations: DelegationPublic[] }>;
+
+ // Browser only — throws in Node
+ async grant(params: {
+ agentId: string;
+ chainId: number;
+ preset: ScopePreset;
+ signer: ethers.Signer;
+ }): Promise<{ id: string; delegationHash: string }>;
+
+ async redeem(params: { id: string; calls: Array<{ to: string; value?: string; data: string }> }): Promise<{
+ txHash: string;
+ }>;
+
+ async revoke(params: { id: string; signer: ethers.Signer }): Promise<{ status: 'revoked'; txHash: string }>;
+
+ async verify(hash: string, chainId: number): Promise<{ valid: boolean; reason?: string }>;
+ }
+ ```
+
+ - `grant` wraps: encode → sign via the toolkit → POST `/api/permissions/grant`.
+ - `redeem` POSTs `/api/permissions/redeem` (requires bearer).
+ - `revoke` builds and sends `DelegationManager.disableDelegation(hash)` via the signer, then POSTs `/api/permissions/revoke` with the resulting tx hash.
+ - `verify` hits `/api/permissions/verify`.
+
+3. **Re-export** selected toolkit helpers (`encodeScopedDelegation`, `isDelegationValid`, `delegationToManifestEntry`) from `sdk/src/permissions.ts` for advanced users — but behind `sdk/src/permissions/advanced.ts` sub-entry so tree-shaking works.
+
+4. **Types**: every field documented with JSDoc. Error types mirror canonical error codes.
+
+5. **`sdk/README.md`** — add a **Permissions** section with a 10-line example:
+
+ ```ts
+ const client = new AgentSdk({ baseUrl: 'https://3dagent.vercel.app' }).permissions;
+ const metadata = await client.getMetadata(agentId);
+ // ...
+ ```
+
+6. **Tests**: add `sdk/test/permissions.test.ts` (or `.js` matching convention) covering:
+ - URL construction for each method
+ - Bearer header is sent when set
+ - Error surface: a 403 from the server becomes a thrown `PermissionError` with the right code
+
+ Use `fetch` mocking (`undici` MockAgent or an inline `global.fetch` mock). No network calls in tests.
+
+7. **Build + publish dry run**: `npm pack --dry-run` from the `sdk/` folder; the module must include `permissions.d.ts` in the output. Paste the manifest in the reporting block.
+
+## Don't do this
+
+- Do not duplicate the toolkit implementation in the SDK — import from `src/permissions/toolkit.js` via a relative path or via a `paths` alias if TS. If it's awkward, copy the _types_ but not the implementation.
+- Do not bundle ethers into the SDK. Mark it a peer dep.
+- Do not add a `broadcastDelegation` / `createAccount` convenience. Those are host concerns.
+- Do not inline private keys in the test fixtures.
+
+## Acceptance
+
+- [ ] `PermissionsClient` exported from the SDK's main entry.
+- [ ] All five methods have types + docstrings + tests.
+- [ ] `npm test` in `sdk/` passes.
+- [ ] `npm pack --dry-run` shows `permissions.js`, `permissions.d.ts`, `permissions/advanced.*`.
+- [ ] `npm run build:lib` (root) still passes if the SDK is referenced from there.
+
+## Reporting
+
+- `npm pack --dry-run` output.
+- Test run transcript.
+- Example code diff in the README.
diff --git a/prompts/permissions/19-indexer-cron.md b/prompts/permissions/19-indexer-cron.md
new file mode 100644
index 000000000..672f72ca9
--- /dev/null
+++ b/prompts/permissions/19-indexer-cron.md
@@ -0,0 +1,68 @@
+# Task 19 — Delegation event indexer (`api/cron/index-delegations.js`)
+
+## Why
+
+Users can revoke on-chain anytime (via MetaMask directly, or via another dapp). Our DB must catch up. The indexer cron polls each supported chain for `DelegationDisabled` and `DelegationRedeemed` events, reconciles against `agent_delegations`, and updates `status`, `redemption_count`, `last_redeemed_at`. Without this, the UI can show "active" for delegations that are actually revoked — a trust failure.
+
+## Read first
+
+- [api/cron/](../../api/cron/) — existing cron endpoint structure + auth (they're typically called by Vercel cron with a shared secret)
+- [vercel.json](../../vercel.json) — existing cron schedules
+- [src/erc7710/abi.js](../../src/erc7710/abi.js) — task 03; has event ABIs
+- [api/\_lib/db.js](../../api/_lib/db.js) — `sql`
+- [00-README.md](./00-README.md) — status enum
+
+## Build this
+
+1. **New cron endpoint** `api/cron/index-delegations.js`:
+ - Auth: verify `Authorization: Bearer ${process.env.CRON_SECRET}` (or whatever the project's existing cron auth is — grep sibling cron files).
+ - For each chainId in `DELEGATION_MANAGER_DEPLOYMENTS`:
+ - Read `last_indexed_block` from a tiny `indexer_state` table keyed by `(contract, chainId)`. Init to "now - 1 day" on first run.
+ - Fetch logs via RPC `eth_getLogs({ address: delegationManager, topics: [<DelegationDisabled or DelegationRedeemed topic>], fromBlock, toBlock: 'latest' })`.
+ - Cap `toBlock - fromBlock` at 2000 per call; loop until caught up.
+ - For each `DelegationDisabled` log: `UPDATE agent_delegations SET status='revoked', revoked_at=<block timestamp>, tx_hash_revoke=<txHash> WHERE delegation_hash=<hash> AND status='active'`.
+ - For each `DelegationRedeemed` log: `UPDATE agent_delegations SET redemption_count = redemption_count + 1, last_redeemed_at=<block timestamp> WHERE delegation_hash=<hash>`.
+ - Advance `last_indexed_block` to the last `toBlock`.
+ - Also run a **sweep**: `UPDATE agent_delegations SET status='expired' WHERE status='active' AND expires_at < NOW()`. Cheap, idempotent, catches expirations.
+ - Emit a summary row into `usage_events` (`permissions.indexer.tick`) with counts.
+2. **Schema**: add `specs/schema/indexer_state.sql` (self-contained, tiny):
+ ```sql
+ CREATE TABLE IF NOT EXISTS indexer_state (
+ id SERIAL PRIMARY KEY,
+ contract TEXT NOT NULL,
+ chain_id INTEGER NOT NULL,
+ last_indexed_block BIGINT NOT NULL DEFAULT 0,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (contract, chain_id)
+ );
+ ```
+ Apply via `scripts/apply-indexer-schema.js` mirroring task 05's script.
+3. **Cron registration** in `vercel.json` — add an entry to run `/api/cron/index-delegations` every 5 minutes. Do not collide with existing cron entries (check the file first; the subscription cron from task 15 is hourly, this is 5-minutely — different paths).
+4. **Protocol-bus event**: after a successful revoke sync, emit (server-side, via a lightweight in-memory channel or a DB notification) so the runtime cache (task 13) can invalidate. Low priority — document how a future enhancement would plumb this.
+5. **Resilience**:
+ - RPC failure for one chain must not abort the whole run. Try/catch per chain.
+ - Dedup: if the same `txHash` is indexed twice (re-org or overlap), the UPDATEs are naturally idempotent — no side effects.
+ - Log a structured summary: `{ chainId, fromBlock, toBlock, revokedCount, redeemedCount, elapsedMs }` to stderr for Vercel logs.
+
+## Don't do this
+
+- Do not use `eth_subscribe` / WebSockets — Vercel cron is stateless.
+- Do not process more than 2000 blocks per RPC call — public RPCs will 429.
+- Do not delete rows. Status flips only.
+- Do not call the indexer on a request path — strictly cron.
+- Do not rely on block timestamps being accurate to the second; ±30s is fine.
+
+## Acceptance
+
+- [ ] `api/cron/index-delegations.js` deployed and reachable.
+- [ ] `vercel.json` registers the 5-minute cron.
+- [ ] A manually triggered on-chain revoke is reflected in the DB within one cron cycle.
+- [ ] A manually triggered on-chain redeem bumps `redemption_count` + sets `last_redeemed_at`.
+- [ ] Expired sweep flips expired rows.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Paste a full log line from one successful run.
+- Paste the DB state before + after a real revoke.
+- Any RPC errors + how you handled them.
diff --git a/prompts/permissions/20-verify-endpoint.md b/prompts/permissions/20-verify-endpoint.md
new file mode 100644
index 000000000..2f40eb32b
--- /dev/null
+++ b/prompts/permissions/20-verify-endpoint.md
@@ -0,0 +1,61 @@
+# Task 20 — `GET /api/permissions/verify`
+
+## Why
+
+Embeds, SDK callers, and third-party hosts need a CORS-open, unauthenticated way to verify a delegation is still valid — signature recovers, not disabled on-chain, not expired — without having to spin up their own RPC client or ABI. This is the public "is this delegation usable right now?" oracle.
+
+## Read first
+
+- [00-README.md](./00-README.md) — canonical endpoint shape + error codes
+- [src/permissions/toolkit.js](../../src/permissions/toolkit.js) — task 04; `isDelegationValid` already exists server-usable
+- [src/erc7710/abi.js](../../src/erc7710/abi.js) — `DELEGATION_MANAGER_ABI`
+- [api/\_lib/http.js](../../api/_lib/http.js) — `json`, `cors`
+
+## Build this
+
+Create `api/permissions/verify.js` (GET only):
+
+1. Method gate / CORS (`*`) / rate limit (`limits.read` — this can be hot).
+2. **Query params**: `hash` (required, 0x + 64 hex), `chainId` (required, positive int, must exist in `DELEGATION_MANAGER_DEPLOYMENTS`).
+3. **Short-circuit via DB**: `SELECT status, expires_at, delegation_json FROM agent_delegations WHERE delegation_hash = $1 AND chain_id = $2`.
+ - If `status='revoked'` → return `{ ok: true, valid: false, reason: 'delegation_revoked' }`.
+ - If `expires_at <= NOW()` or `status='expired'` → `{ ok: true, valid: false, reason: 'delegation_expired' }`.
+ - Status `active` → continue to on-chain check.
+ - Row missing → continue to on-chain check **anyway** (the delegation may have been granted outside our system — the delegator is free to grant off-platform).
+4. **On-chain check** via `isDelegationValid({ hash, chainId })` (task 04):
+ - Uses a read-only provider pinned to `RPC_URL_<chainId>` env var.
+ - Calls `DelegationManager.isDelegationDisabled(hash)`.
+ - If disabled on-chain but our DB still says `active`, **self-heal**: fire-and-forget `UPDATE agent_delegations SET status='revoked', revoked_at=NOW() WHERE delegation_hash=$1 AND status='active'`. Do not block the response on this.
+5. **Response**:
+ - Valid: `{ ok: true, valid: true, checkedAt: <iso>, chainId, hash }`.
+ - Invalid: `{ ok: true, valid: false, reason: <canonical error code>, checkedAt, chainId, hash }`.
+ - Errors in the check itself: `{ ok: false, error: 'rpc_error', message }` with 502.
+6. **Caching**:
+ - Valid responses: `Cache-Control: public, max-age=30, s-maxage=60`.
+ - Invalid responses: `Cache-Control: public, max-age=300, s-maxage=600` (revoked/expired won't un-revoke).
+ - `ETag` from the response JSON hash.
+7. **No enumeration**: don't let this endpoint be a way to learn which hashes exist in our DB. Response for an unknown hash that is also NOT disabled on-chain is `{ ok: true, valid: true, reason: 'unknown_to_platform', ... }` — explicitly mark that we didn't authenticate the grant ourselves. Clients can decide what to do.
+
+## Don't do this
+
+- Do not require auth. This endpoint's whole point is being universally callable.
+- Do not do the expensive EIP-712 signature recovery on every call — the on-chain disabled check + DB expiry check is sufficient. The signature was verified at grant time; if it's in our DB, the signature recovered at grant time.
+- Do not fall over if one RPC is slow; use a 5s timeout + return `rpc_error`.
+- Do not write through non-canonical error codes.
+
+## Acceptance
+
+- [ ] Valid delegation → `valid: true`.
+- [ ] Revoked (DB only) → `valid: false, reason: 'delegation_revoked'`.
+- [ ] Disabled on-chain but `active` in DB → returns `valid: false, reason: 'delegation_revoked'` AND self-heals the row.
+- [ ] Expired → `valid: false, reason: 'delegation_expired'`.
+- [ ] Unknown hash with on-chain not-disabled → `valid: true, reason: 'unknown_to_platform'`.
+- [ ] Bad query params → 400 with canonical error.
+- [ ] Cache headers set correctly per case.
+- [ ] `node --check` + `npm run build` pass.
+
+## Reporting
+
+- Four `curl` transcripts: valid, revoked, expired, unknown.
+- The self-heal UPDATE log from a test case.
+- p50 / p95 latency across ~20 calls.
diff --git a/public/agent/index.html b/public/agent/index.html
index 11517c91a..e0e1009bb 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -437,6 +437,220 @@
margin: 0;
line-height: 1.5;
}
+
+ /* ── Manage Permissions Panel ────────────────────────────────────────── */
+
+ .mp-panel {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .mp-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0.618rem;
+ }
+
+ .mp-title {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ .mp-refresh-btn {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.3);
+ cursor: pointer;
+ padding: 0.2rem;
+ border-radius: 4px;
+ line-height: 0;
+ transition: color 0.15s;
+ }
+
+ .mp-refresh-btn:hover { color: rgba(255, 255, 255, 0.7); }
+
+ .mp-loading, .mp-error {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.3);
+ padding: 1rem 0;
+ }
+
+ .mp-error { color: #fca5a5; }
+
+ .mp-empty {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.3);
+ padding: 1rem 0;
+ text-align: center;
+ }
+
+ .mp-empty p { margin: 0 0 0.618rem; }
+
+ .mp-grant-btn {
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.7);
+ font-size: 0.718rem;
+ font-family: inherit;
+ padding: 0.382rem 0.75rem;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+ }
+
+ .mp-grant-btn:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.95);
+ }
+
+ .mp-card {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 10px;
+ padding: 0.75rem 1rem;
+ margin-bottom: 0.618rem;
+ transition: border-color 0.2s;
+ }
+
+ .mp-card--active { border-color: rgba(134, 239, 172, 0.15); }
+ .mp-card--revoked { opacity: 0.5; }
+ .mp-card--expired { border-color: rgba(251, 191, 36, 0.15); }
+
+ .mp-card-top {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ margin-bottom: 0.382rem;
+ }
+
+ .mp-badge {
+ font-size: 0.618rem;
+ padding: 0.1rem 0.45rem;
+ border-radius: 999px;
+ font-weight: 500;
+ }
+
+ .mp-badge--active { background: rgba(134, 239, 172, 0.15); color: #86efac; }
+ .mp-badge--revoked { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.4); }
+ .mp-badge--expired { background: rgba(251, 191, 36, 0.12); color: #fbbf24; }
+
+ .mp-chain-chip {
+ font-size: 0.618rem;
+ background: rgba(255,255,255,0.07);
+ color: rgba(255,255,255,0.5);
+ padding: 0.1rem 0.45rem;
+ border-radius: 999px;
+ }
+
+ .mp-indexer-pending {
+ font-size: 0.618rem;
+ color: rgba(251, 191, 36, 0.7);
+ font-style: italic;
+ }
+
+ .mp-card-scope {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.8);
+ margin-bottom: 0.236rem;
+ line-height: 1.4;
+ }
+
+ .mp-card-hash {
+ font-size: 0.618rem;
+ font-family: monospace;
+ color: rgba(255, 255, 255, 0.25);
+ margin-bottom: 0.236rem;
+ }
+
+ .mp-card-usage {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.35);
+ margin-bottom: 0.5rem;
+ }
+
+ .mp-card-addresses {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ margin-bottom: 0.5rem;
+ }
+
+ .mp-addr-link {
+ font-size: 0.618rem;
+ font-family: monospace;
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ }
+
+ .mp-addr-link:hover { color: rgba(255, 255, 255, 0.8); }
+
+ .mp-addr-arrow {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.2);
+ }
+
+ .mp-card-actions { display: flex; gap: 0.5rem; }
+
+ .mp-revoke-btn {
+ background: rgba(239, 68, 68, 0.1);
+ border: 1px solid rgba(239, 68, 68, 0.25);
+ color: #f87171;
+ font-size: 0.718rem;
+ font-family: inherit;
+ padding: 0.3rem 0.7rem;
+ border-radius: 999px;
+ cursor: pointer;
+ transition: background 0.15s;
+ }
+
+ .mp-revoke-btn:hover:not(:disabled) {
+ background: rgba(239, 68, 68, 0.2);
+ }
+
+ .mp-revoke-btn:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+
+ .mp-card-error {
+ font-size: 0.618rem;
+ color: #fca5a5;
+ margin-top: 0.382rem;
+ }
+
+ .mp-card-pending {
+ display: flex;
+ align-items: center;
+ gap: 0.382rem;
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.5);
+ margin-top: 0.382rem;
+ }
+
+ .mp-tx-link {
+ color: rgba(255,255,255,0.4);
+ text-decoration: none;
+ }
+
+ .mp-tx-link:hover { color: rgba(255,255,255,0.8); }
+
+ @keyframes mp-spin {
+ to { transform: rotate(360deg); }
+ }
+
+ .mp-spinner {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ border: 1.5px solid rgba(255,255,255,0.15);
+ border-top-color: rgba(255,255,255,0.6);
+ border-radius: 50%;
+ animation: mp-spin 0.7s linear infinite;
+ }
</style>
</head>
<body>
@@ -456,6 +670,9 @@
</div>
</div>
+ <!-- Permissions panel (owner only, mounted by JS) -->
+ <div id="agent-permissions-mount"></div>
+
<!-- Skills catalog -->
<div class="agent-skills-full" id="agent-skills-section" style="display: none">
<div class="agent-skills-title">Skills</div>
@@ -498,6 +715,7 @@
import { AgentHome } from '/src/agent-home.js';
import { protocol } from '/src/agent-protocol.js';
import { renderHubActions } from '/src/agent-hub-actions.js';
+ import { mountManagePanel } from '/src/permissions/manage-panel.js';
// Pull agent id from URL: /agent/:id
const agentId = location.pathname.split('/').filter(Boolean).pop();
@@ -540,6 +758,10 @@
if (isOwner) {
const panel = container.querySelector('.agent-home-panel');
if (panel) renderHubActions(panel, identity, rawAgent);
+
+ // Mount the permissions management panel below the agent card
+ const permMount = document.getElementById('agent-permissions-mount');
+ if (permMount) mountManagePanel({ container: permMount, agentId });
}
// Render skills catalog
diff --git a/public/login.html b/public/login.html
index 753eff11a..56ea7b494 100644
--- a/public/login.html
+++ b/public/login.html
@@ -6,7 +6,6 @@
<title>Sign in · 3D Agent</title>
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/wallet-connect.css" />
- <meta name="privy-app-id" content="" />
<style>
:root {
color-scheme: dark;
@@ -112,21 +111,6 @@
color: var(--accent);
margin: 0 0 8px;
}
- .wallet-btn {
- background: #1c1c28;
- border: 1px solid #2a2a36;
- color: #eee;
- font-weight: 500;
- margin-top: 12px;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 8px;
- }
- .wallet-btn:hover {
- background: #22222e;
- border-color: var(--accent);
- }
.divider {
display: flex;
align-items: center;
@@ -144,10 +128,6 @@
height: 1px;
background: #2a2a36;
}
- .wallet-icon {
- width: 18px;
- height: 18px;
- }
</style>
</head>
<body>
@@ -167,30 +147,6 @@
/>
<button id="submit" type="submit">Sign in</button>
<div class="divider">or</div>
- <button
- id="privy"
- type="button"
- class="wallet-btn"
- style="
- background: linear-gradient(135deg, var(--accent), var(--accent2));
- border-color: transparent;
- color: #fff;
- "
- >
- <svg
- class="wallet-icon"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="2"
- stroke-linecap="round"
- stroke-linejoin="round"
- >
- <circle cx="12" cy="8" r="4" />
- <path d="M20 21a8 8 0 0 0-16 0" />
- </svg>
- Sign in with Privy
- </button>
<div id="wallet-mount"></div>
<div class="err" id="err"></div>
<p class="foot">No account? <a href="/register">Create one</a></p>
diff --git a/public/skills-index.json b/public/skills-index.json
index bdd8084de..0a757ce24 100644
--- a/public/skills-index.json
+++ b/public/skills-index.json
@@ -22,5 +22,14 @@
"version": "0.3.0",
"uri": "https://skills.3d-agent.io/[email protected]",
"author": "3d-agent"
+ },
+ {
+ "id": "dca",
+ "name": "DCA",
+ "description": "Dollar-cost average USDC into WETH on a schedule via Uniswap V3.",
+ "version": "0.1.0",
+ "uri": "skills/dca/",
+ "author": "3d-agent",
+ "tags": ["defi", "uniswap", "metamask", "permissions"]
}
]
diff --git a/public/skills/dca/SKILL.md b/public/skills/dca/SKILL.md
new file mode 100644
index 000000000..fc93b0d4d
--- /dev/null
+++ b/public/skills/dca/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: dca
+version: 0.1.0
+description: Dollar-cost average a fixed USDC amount into WETH on a recurring schedule via Uniswap V3.
+trust: owned-only
+permissions_required: true
+default_scope_preset:
+ token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+ maxAmount: "100000000"
+ period: "daily"
+ targets:
+ - "0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"
+ - "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+ selectors:
+ - "0x04e45aaf"
+ - "0x095ea7b3"
+ expiry_days: 30
+---
+
+# DCA (Dollar-Cost Averaging)
+
+You help the owner set up an automated dollar-cost averaging strategy that periodically swaps
+a fixed USDC amount into WETH using Uniswap V3 on Base Sepolia.
+
+## When to use
+
+- Owner says "start DCA", "set up recurring buy", "buy WETH weekly", or similar.
+- Owner asks to list, pause, or cancel their DCA strategies.
+
+## Actions
+
+Call `start_dca` when the owner wants to configure a new strategy. It will:
+1. Prompt for amount (USDC), token out (default WETH), and frequency.
+2. Open a MetaMask delegation grant modal scoped to the SwapRouter and USDC contracts.
+3. Store the strategy once the delegation is signed.
+
+Call `list_dca_strategies` to show the owner their active strategies.
+
+Call `stop_dca` when the owner wants to cancel a strategy by ID.
+
+## Safety rules (always follow)
+
+- Only the agent owner may call these tools. Refuse if the caller is not the owner.
+- Default slippage is 0.5% (50 bps). Never accept slippage_bps > 500.
+- Network defaults to Base Sepolia (chainId 84532). Require explicit owner confirmation to use mainnet (chainId 8453).
+- Never reveal delegation private keys or relayer tokens.
diff --git a/public/skills/dca/manifest.json b/public/skills/dca/manifest.json
new file mode 100644
index 000000000..2d815a424
--- /dev/null
+++ b/public/skills/dca/manifest.json
@@ -0,0 +1,19 @@
+{
+ "spec": "skill/0.1",
+ "name": "dca",
+ "version": "0.1.0",
+ "description": "Dollar-cost averaging: swap a fixed USDC amount into WETH on a schedule via Uniswap V3.",
+ "author": "3d-agent",
+ "license": "MIT",
+ "tags": ["defi", "dca", "uniswap", "metamask", "permissions"],
+ "trust": "owned-only",
+ "requires": {
+ "rig": ["any"],
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": ["start_dca", "list_dca_strategies", "stop_dca"],
+ "triggers": ["dca", "recurring_swap", "dollar_cost_average"]
+ }
+}
diff --git a/public/skills/dca/skill.js b/public/skills/dca/skill.js
new file mode 100644
index 000000000..f6c10090b
--- /dev/null
+++ b/public/skills/dca/skill.js
@@ -0,0 +1,189 @@
+// DCA skill — client-side setup and execute handlers.
+// Server-side execution (onPeriod) lives in api/cron/run-dca.js.
+
+// ── Per-chain config ──────────────────────────────────────────────────────────
+
+const CHAIN_CONFIG = {
+ // Base Sepolia — default for all v0.1 strategies
+ 84532: {
+ name: 'Base Sepolia',
+ swap_router: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
+ quoter_v2: '0xC5290058841028F1614F3A6F0F5816cAd0df5E27',
+ usdc: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
+ tokens: {
+ WETH: '0x4200000000000000000000000000000000000006',
+ cbBTC: null, // not deployed on Sepolia
+ USDT: null,
+ },
+ },
+ // Base Mainnet — requires explicit owner opt-in
+ 8453: {
+ name: 'Base Mainnet',
+ swap_router: '0x2626664c2603336E57B271c5C0b26F421741e481',
+ quoter_v2: '0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a',
+ usdc: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ tokens: {
+ WETH: '0x4200000000000000000000000000000000000006',
+ cbBTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
+ },
+ },
+};
+
+// ERC-20 USDC has 6 decimals
+const USDC_DECIMALS = 6;
+
+// Function selectors
+const SEL_EXACT_INPUT_SINGLE = '0x04e45aaf';
+const SEL_APPROVE = '0x095ea7b3';
+
+// ── Scope preset builder ──────────────────────────────────────────────────────
+
+function buildScopePreset(chainId, amountPerExecution, periodSeconds) {
+ const cfg = CHAIN_CONFIG[chainId];
+ return {
+ token: cfg.usdc,
+ maxAmount: amountPerExecution,
+ period: periodSeconds <= 86400 ? 'daily' : 'weekly',
+ targets: [cfg.swap_router, cfg.usdc],
+ selectors: [SEL_EXACT_INPUT_SINGLE, SEL_APPROVE],
+ expiry_days: 30,
+ };
+}
+
+// ── setup ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Called once when the skill loads. Registers a "Start DCA" action visible only
+ * to the agent owner.
+ * @param {{ agent: object, host: object }} ctx
+ */
+export function setup({ agent, host }) {
+ if (!host?.registerOwnerAction) return;
+ host.registerOwnerAction({
+ id: 'start_dca',
+ label: 'Start DCA',
+ description: 'Set up an automated USDC → WETH recurring swap via Uniswap V3.',
+ icon: '🔄',
+ handler: (args) => execute({ agent, host, args }),
+ });
+}
+
+// ── execute ───────────────────────────────────────────────────────────────────
+
+/**
+ * Owner-facing: prompts for config, opens grant modal, stores strategy.
+ * @param {{ agent: object, host: object, args: object }} ctx
+ */
+export async function execute({ agent, host, args = {} }) {
+ const {
+ amount_usdc = '10',
+ token_out = 'WETH',
+ frequency = 'daily',
+ slippage_bps = 50,
+ chain_id = 84532,
+ } = args;
+
+ // Mainnet guard — require explicit confirmation
+ if (chain_id === 8453) {
+ const confirmed = await host?.confirm(
+ 'You are about to set up a DCA strategy on Base Mainnet with real funds. Confirm?',
+ );
+ if (!confirmed) return { ok: false, code: 'mainnet_not_confirmed' };
+ }
+
+ const cfg = CHAIN_CONFIG[chain_id];
+ if (!cfg) return { ok: false, code: 'unsupported_chain', message: `Chain ${chain_id} not supported` };
+
+ const tokenOutAddress = cfg.tokens[token_out];
+ if (!tokenOutAddress) {
+ return {
+ ok: false,
+ code: 'unsupported_token',
+ message: `${token_out} is not available on ${cfg.name}`,
+ };
+ }
+
+ // Clamp slippage
+ const slippage = Math.min(500, Math.max(10, Number(slippage_bps)));
+
+ // Convert USDC amount to 6-decimal wei
+ const amountPerExecution = String(
+ Math.round(parseFloat(amount_usdc) * 10 ** USDC_DECIMALS),
+ );
+
+ const periodSeconds = frequency === 'weekly' ? 7 * 86400 : 86400;
+
+ const scopePreset = buildScopePreset(chain_id, amountPerExecution, periodSeconds);
+
+ // Open delegation grant modal
+ let delegationId;
+ try {
+ const grant = await host.openGrantModal({
+ scope: scopePreset,
+ description: `Allow agent to swap ${amount_usdc} USDC → ${token_out} ${frequency} for 30 days`,
+ });
+ if (!grant?.delegationId) {
+ return { ok: false, code: 'grant_cancelled', message: 'Grant was not signed' };
+ }
+ delegationId = grant.delegationId;
+ } catch (err) {
+ return { ok: false, code: 'grant_error', message: err.message };
+ }
+
+ // Store strategy server-side
+ const res = await fetch('/api/dca-strategies', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ agent_id: agent.id,
+ delegation_id: delegationId,
+ token_in: cfg.usdc,
+ token_out: tokenOutAddress,
+ token_out_symbol: token_out,
+ amount_per_execution: amountPerExecution,
+ period_seconds: periodSeconds,
+ slippage_bps: slippage,
+ chain_id,
+ }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ return { ok: false, code: body.error || 'api_error', message: body.error_description };
+ }
+
+ const data = await res.json();
+ return {
+ ok: true,
+ strategy_id: data.id,
+ message: `DCA strategy created — ${amount_usdc} USDC → ${token_out} ${frequency} on ${cfg.name}.`,
+ };
+}
+
+// ── Tool handlers (LLM-callable) ──────────────────────────────────────────────
+
+export async function start_dca(args, ctx) {
+ return execute({ agent: ctx.agent, host: ctx.host, args });
+}
+
+export async function list_dca_strategies(args, ctx) {
+ const agentId = args.agent_id || ctx.agent?.id;
+ if (!agentId) return { ok: false, error: 'agent_id required' };
+
+ const res = await ctx.fetch(`/api/dca-strategies?agent_id=${encodeURIComponent(agentId)}`);
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ return res.json();
+}
+
+export async function stop_dca(args, ctx) {
+ const { strategy_id } = args;
+ if (!strategy_id) return { ok: false, error: 'strategy_id required' };
+
+ const res = await ctx.fetch(`/api/dca-strategies/${encodeURIComponent(strategy_id)}`, {
+ method: 'DELETE',
+ });
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ return { ok: true };
+}
diff --git a/public/skills/dca/tools.json b/public/skills/dca/tools.json
new file mode 100644
index 000000000..99e42f90c
--- /dev/null
+++ b/public/skills/dca/tools.json
@@ -0,0 +1,71 @@
+{
+ "tools": [
+ {
+ "name": "start_dca",
+ "description": "Configure a new dollar-cost averaging strategy. Opens the MetaMask delegation grant modal and stores the strategy once the owner signs.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "amount_usdc": {
+ "type": "string",
+ "description": "USDC amount per execution in human-readable form, e.g. '10' for 10 USDC."
+ },
+ "token_out": {
+ "type": "string",
+ "enum": ["WETH", "cbBTC", "USDT"],
+ "default": "WETH",
+ "description": "Token to receive."
+ },
+ "frequency": {
+ "type": "string",
+ "enum": ["daily", "weekly"],
+ "default": "daily",
+ "description": "How often to execute the swap."
+ },
+ "slippage_bps": {
+ "type": "integer",
+ "minimum": 10,
+ "maximum": 500,
+ "default": 50,
+ "description": "Slippage tolerance in basis points (50 = 0.5%)."
+ },
+ "chain_id": {
+ "type": "integer",
+ "enum": [84532, 8453],
+ "default": 84532,
+ "description": "Chain to execute on. 84532 = Base Sepolia (default), 8453 = Base Mainnet (requires extra confirmation)."
+ }
+ },
+ "required": ["amount_usdc"]
+ }
+ },
+ {
+ "name": "list_dca_strategies",
+ "description": "List the owner's active DCA strategies.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "agent_id": {
+ "type": "string",
+ "description": "Agent ID to query strategies for."
+ }
+ },
+ "required": ["agent_id"]
+ }
+ },
+ {
+ "name": "stop_dca",
+ "description": "Cancel an active DCA strategy by ID.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "strategy_id": {
+ "type": "string",
+ "description": "UUID of the strategy to cancel."
+ }
+ },
+ "required": ["strategy_id"]
+ }
+ }
+ ]
+}
diff --git a/public/skills/subscription/SKILL.md b/public/skills/subscription/SKILL.md
new file mode 100644
index 000000000..e6366d970
--- /dev/null
+++ b/public/skills/subscription/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: subscription
+version: 0.1.0
+trust: owned-only
+permissions_required: true
+default_scope_preset:
+ token: "<USDC>"
+ maxAmount: "5000000"
+ period: "weekly"
+ targets: ["<subscription executor contract>"]
+ expiry_days: 90
+---
+
+# Subscription
+
+Allow a viewer to subscribe to this agent for recurring USDC payments. The agent charges 5 USDC per week automatically — no re-signing needed — until the viewer revokes or the delegation expires (90 days).
+
+## Flow
+
+1. Viewer clicks **Subscribe · 5 USDC / week**.
+2. MetaMask opens pre-filled with the scope (5 USDC / week cap, 90-day expiry).
+3. Viewer approves once. No further wallet prompts.
+4. The server cron fires every hour; weekly charges are applied automatically via the ERC-7710 relayer.
+5. Viewer can revoke at any time from the Manage panel — this pauses the subscription.
+
+## onPeriod
+
+`onPeriod` is **server-side only**. The cron at `/api/cron/run-subscriptions` imports it via dynamic `import()` and calls it once per subscription per period. It builds a single ERC-20 `transfer` call for `amountPerPeriod` and redeems it through the relayer endpoint.
+
+**Never call `onPeriod` from the browser.**
+
+## Error behaviour
+
+- Revoked delegation → subscription status flips to `paused`, visible in the Manage panel.
+- Expired delegation → same.
+- Failed redemption → `paused` + `last_error` stored; no silent retry.
diff --git a/public/skills/subscription/skill.js b/public/skills/subscription/skill.js
new file mode 100644
index 000000000..5f29ca91e
--- /dev/null
+++ b/public/skills/subscription/skill.js
@@ -0,0 +1,182 @@
+/**
+ * Subscription skill — recurring USDC payments via ERC-7710 delegation.
+ *
+ * Exports:
+ * setup — browser: attach "Subscribe" action to agent UI
+ * execute — browser: open grant modal, register subscription via API
+ * onPeriod — server-side only: charge the period amount via the relayer
+ *
+ * onPeriod is imported by api/cron/run-subscriptions.js via dynamic import.
+ * It must never be invoked from a browser context.
+ */
+
+const SKILL_ID = 'subscription';
+
+// USDC contract addresses by chain ID.
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
+};
+
+/**
+ * Build an ERC-20 transfer(address,uint256) calldata bundle.
+ * Pure function — no imports required.
+ *
+ * @param {string} tokenAddr - ERC-20 contract address
+ * @param {string} recipient - recipient address (EIP-55 or lowercase)
+ * @param {string} amountBaseUnits - amount in base units (string)
+ * @returns {{ to: string, value: string, data: string }}
+ */
+export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
+ // transfer(address,uint256) selector
+ const selector = 'a9059cbb';
+ const paddedAddr = recipient.toLowerCase().replace('0x', '').padStart(64, '0');
+ const paddedAmt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
+ return {
+ to: tokenAddr,
+ value: '0',
+ data: '0x' + selector + paddedAddr + paddedAmt,
+ };
+}
+
+/**
+ * Attaches the "Subscribe · 5 USDC / week" action to the agent UI.
+ *
+ * @param {{ agent: object, host: object }} opts
+ */
+export async function setup({ agent, host }) {
+ host.attachAction({
+ id: SKILL_ID,
+ label: 'Subscribe · 5 USDC / week',
+ skillId: SKILL_ID,
+ });
+}
+
+/**
+ * Viewer's initial subscription action — runs in the browser only.
+ *
+ * 1. Opens the grant modal pre-filled with the weekly 5 USDC scope.
+ * 2. On successful grant, POSTs to /api/subscriptions.
+ * 3. Confirms in chat with the expiry date.
+ *
+ * @param {{ agent: object, host: object, args: object }} opts
+ */
+export async function execute({ agent, host, args }) {
+ const agentId = agent.agentId ?? agent.id;
+ const chainId = agent.chainId ?? 84532;
+
+ const scopePreset = {
+ token: USDC_BY_CHAIN[chainId] ?? USDC_BY_CHAIN[84532],
+ maxAmount: '5000000',
+ period: 'weekly',
+ targets: [],
+ expiry_days: 90,
+ };
+
+ let delegation;
+ try {
+ const { openGrantModal } = await import('../../src/permissions/grant-modal.js');
+ delegation = await openGrantModal({ agent, scopePreset });
+ } catch {
+ host.speak('Permission request is not available in this context.');
+ return { ok: false, code: 'modal_unavailable' };
+ }
+
+ if (!delegation) {
+ host.speak('Subscription cancelled.');
+ return { ok: false, code: 'user_cancelled' };
+ }
+
+ const periodSeconds = 7 * 24 * 3600;
+
+ try {
+ const res = await fetch('/api/subscriptions', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ agentId,
+ delegationId: delegation.id,
+ periodSeconds,
+ amountPerPeriod: scopePreset.maxAmount,
+ }),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.error_description ?? `HTTP ${res.status}`);
+ }
+
+ const expiry = new Date(Date.now() + 90 * 24 * 3600 * 1000).toLocaleDateString();
+ host.speak(`You're subscribed until ${expiry}. Revoke anytime in the Manage panel.`);
+ return { ok: true };
+ } catch (err) {
+ host.speak('Failed to record subscription. Please try again.');
+ return { ok: false, code: 'api_error', message: err.message };
+ }
+}
+
+/**
+ * Periodic charge handler — server-side only, called by api/cron/run-subscriptions.js.
+ *
+ * Builds a single ERC-20 transfer call for amountPerPeriod and redeems it
+ * through the relayer endpoint (equivalent to redeemFromSkill with mode:'relayer').
+ *
+ * @param {{
+ * agent: {
+ * agentId: string,
+ * chainId: number,
+ * ownerAddress: string,
+ * usdcAddress: string,
+ * relayerToken: string,
+ * origin: string,
+ * },
+ * subscription: {
+ * id: string,
+ * delegationId: string,
+ * amountPerPeriod: string,
+ * }
+ * }} opts
+ * @returns {Promise<{ ok: boolean, txHash?: string, code?: string, message?: string }>}
+ */
+export async function onPeriod({ agent, subscription }) {
+ const { agentId, chainId, ownerAddress, usdcAddress, relayerToken, origin } = agent;
+ const { delegationId, amountPerPeriod } = subscription;
+
+ const call = buildERC20Transfer(usdcAddress, ownerAddress, amountPerPeriod);
+
+ let res;
+ try {
+ res = await fetch(`${origin}/api/permissions/redeem`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${relayerToken}`,
+ },
+ body: JSON.stringify({
+ id: delegationId,
+ calls: [call],
+ agentId,
+ chainId: String(chainId),
+ skillId: SKILL_ID,
+ }),
+ });
+ } catch (err) {
+ return { ok: false, code: 'fetch_error', message: err.message };
+ }
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ return {
+ ok: false,
+ code: body.error ?? `http_${res.status}`,
+ message: body.error_description ?? `HTTP ${res.status}`,
+ };
+ }
+
+ const data = await res.json().catch(() => ({}));
+ if (!data.txHash) {
+ return { ok: false, code: 'no_tx_hash', message: 'Relayer returned no txHash' };
+ }
+
+ return { ok: true, txHash: data.txHash };
+}
diff --git a/public/skills/tip-jar/README.md b/public/skills/tip-jar/README.md
new file mode 100644
index 000000000..bc81e18c7
--- /dev/null
+++ b/public/skills/tip-jar/README.md
@@ -0,0 +1,101 @@
+# Tip Jar Skill
+
+Lets a viewer send a USDC tip directly to the agent's creator wallet via an
+ERC-7710 scoped delegation — no intermediary custody, no wallet pop-up after the
+initial grant.
+
+## Scope requested
+
+| Field | Value |
+| ----------- | -------------------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract on the active chain |
+| expiry_days | 30 |
+
+Base Sepolia USDC: `0x036CbD53842c5426634e7929541eC2318f3dCF7e`
+
+## Happy-path flow
+
+```
+Viewer clicks "Tip the creator"
+ │
+ ▼
+Amount picker (1 / 5 / 10 USDC or custom ≤ 10)
+ │ viewer selects amount
+ ▼
+buildERC20Transfer(usdcAddr, agent.ownerAddress, amountBaseUnits)
+ → { to: usdcAddr, value: '0x0', data: 0xa9059cbb + paddedAddr + paddedAmt }
+ │
+ ▼
+redeemFromSkill({ agentId, chainId, skillId: 'tip-jar', calls: [call] })
+ │
+ ▼
+DelegationManager.redeemDelegations() on Base Sepolia (ERC-7710)
+ │
+ ▼
+USDC transfer: viewer delegated wallet → agent.ownerAddress ✓
+ │
+ ▼
+host.speak("Thank you for the tip!")
+protocol.emit({ type: 'tip.received', payload: { agentId, amountUsdc, txHash } })
+```
+
+## No-delegation path
+
+```
+redeemFromSkill → error: no_delegation
+ │
+ ├─ viewer is NOT owner → "The creator hasn't enabled tipping on this device yet."
+ │
+ └─ viewer IS owner → attachAction("Grant tipping")
+ │
+ ▼
+ openGrantModal({ preset: { token, maxAmount: '10000000', ... } })
+ │
+ ▼
+ MetaMask ERC-7715 permission request
+ │
+ ▼
+ delegation stored → tip flow retried
+```
+
+## ERC-20 calldata format
+
+```
+selector : 0xa9059cbb (keccak256("transfer(address,uint256)")[0:4])
+arg[0] : recipient address, zero-padded left to 32 bytes
+arg[1] : amount in base units, big-endian uint256 padded to 32 bytes
+
+Example — 5 USDC to 0x1234...5678:
+0xa9059cbb
+0000000000000000000000001234567890123456789012345678901234567890
+00000000000000000000000000000000000000000000000000000000004c4b40
+```
+
+## Files
+
+| File | Purpose |
+| ------------ | ------------------------------------------ |
+| `SKILL.md` | LLM instructions + scope declaration |
+| `manifest.json` | Skill metadata, sandboxPolicy, permissions |
+| `skill.js` | `setup` / `execute` exports + pure helpers |
+| `skill.css` | Tip-amount picker modal styles |
+
+## Dependencies (lazy-loaded at runtime)
+
+- **task 13** — `src/runtime/delegation-redeem.js` → `redeemFromSkill`
+- **task 10** — `src/permissions/grant-modal.js` → `openGrantModal`
+
+If either module is absent the skill degrades gracefully: it loads without errors
+and surfaces a human-readable message instead of crashing.
+
+## Skill registry
+
+No standalone registry file exists in this repo. To activate the tip-jar for an
+agent, add an entry to that agent's `manifest.json` `skills` array:
+
+```json
+{ "uri": "/skills/tip-jar/", "version": "0.1.0" }
+```
diff --git a/public/skills/tip-jar/SKILL.md b/public/skills/tip-jar/SKILL.md
new file mode 100644
index 000000000..7481a9a79
--- /dev/null
+++ b/public/skills/tip-jar/SKILL.md
@@ -0,0 +1,41 @@
+---
+name: tip-jar
+version: 0.1.0
+description: Let viewers send a USDC tip directly to the agent creator.
+trust: owned-only
+permissions_required: true
+cost: medium
+triggers:
+ - tip_request
+ - viewer_appreciation
+default_scope_preset: '{"token":"chain-specific-usdc","maxAmount":"10000000","period":"daily","targets":["usdc-contract"],"expiry_days":30}'
+---
+
+# Tip Jar
+
+Allows viewers to send a USDC tip directly to the agent's creator wallet. No intermediary
+holds the funds — the ERC-7710 delegation redeems a transfer straight from the viewer's
+delegated allowance to `agent.ownerAddress`.
+
+When a viewer expresses appreciation or asks how to support the creator, invoke
+`tip_jar_send`. Tip options are 1, 5, or 10 USDC (up to the daily cap of 10 USDC).
+
+On success, thank the viewer warmly.
+
+## Scope requested
+
+| Field | Value |
+| ----------- | ----------------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract address on the active chain |
+| expiry_days | 30 |
+
+## Error cases
+
+- **no_delegation / delegation_not_found** — Creator hasn't granted tipping permissions.
+ Tell the viewer: "The creator hasn't enabled tipping on this device yet."
+ If the current viewer is the owner, surface a "Grant tipping" button.
+- **scope_exceeded** — Daily cap reached. Tell the viewer to try again tomorrow.
+- **delegation_expired / delegation_revoked** — Surface the error code to the viewer.
diff --git a/public/skills/tip-jar/manifest.json b/public/skills/tip-jar/manifest.json
new file mode 100644
index 000000000..f7aa7da51
--- /dev/null
+++ b/public/skills/tip-jar/manifest.json
@@ -0,0 +1,29 @@
+{
+ "spec": "skill/0.1",
+ "name": "tip-jar",
+ "version": "0.1.0",
+ "description": "Let viewers send a USDC tip directly to the agent creator via ERC-7710 delegation.",
+ "license": "MIT",
+ "tags": ["payments", "usdc", "erc7710", "tip"],
+ "sandboxPolicy": "trusted-main-thread",
+ "requires": {
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": [],
+ "triggers": ["tip_request"]
+ },
+ "permissions": {
+ "spec": "erc-7715/0.1",
+ "default_scope_preset": {
+ "token": {
+ "84532": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
+ "8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
+ },
+ "maxAmount": "10000000",
+ "period": "daily",
+ "expiry_days": 30
+ }
+ }
+}
diff --git a/public/skills/tip-jar/skill.css b/public/skills/tip-jar/skill.css
new file mode 100644
index 000000000..f62add60a
--- /dev/null
+++ b/public/skills/tip-jar/skill.css
@@ -0,0 +1,116 @@
+.tip-jar-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 9999;
+}
+
+.tip-jar-modal {
+ background: #1a1a2e;
+ border: 1px solid #334466;
+ border-radius: 12px;
+ padding: 24px;
+ min-width: 260px;
+ color: #e0e0f0;
+ font-family: inherit;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
+}
+
+.tip-jar-title {
+ margin: 0;
+ font-size: 1rem;
+ font-weight: 600;
+ text-align: center;
+}
+
+.tip-jar-options {
+ display: flex;
+ gap: 8px;
+ justify-content: center;
+}
+
+.tip-jar-btn {
+ flex: 1;
+ padding: 8px 4px;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ background: #222244;
+ color: #b0b8d8;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+}
+
+.tip-jar-btn:hover {
+ background: #2a2a5a;
+ color: #ffffff;
+}
+
+.tip-jar-btn.selected {
+ background: #4a4afa;
+ border-color: #7a7aff;
+ color: #ffffff;
+}
+
+.tip-jar-custom {
+ width: 100%;
+ padding: 8px 10px;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ background: #111122;
+ color: #e0e0f0;
+ font-size: 0.9rem;
+ box-sizing: border-box;
+ outline: none;
+}
+
+.tip-jar-custom:focus {
+ border-color: #7a7aff;
+}
+
+.tip-jar-footer {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+}
+
+.tip-jar-send {
+ padding: 8px 18px;
+ background: #4a4afa;
+ border: none;
+ border-radius: 8px;
+ color: #ffffff;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s;
+}
+
+.tip-jar-send:hover:not(:disabled) {
+ background: #6060ff;
+}
+
+.tip-jar-send:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.tip-jar-cancel {
+ padding: 8px 14px;
+ background: transparent;
+ border: 1px solid #445566;
+ border-radius: 8px;
+ color: #aaaacc;
+ cursor: pointer;
+ font-size: 0.9rem;
+ transition: background 0.15s;
+}
+
+.tip-jar-cancel:hover {
+ background: #222233;
+}
diff --git a/public/skills/tip-jar/skill.js b/public/skills/tip-jar/skill.js
new file mode 100644
index 000000000..6bd03ac69
--- /dev/null
+++ b/public/skills/tip-jar/skill.js
@@ -0,0 +1,266 @@
+/**
+ * tip-jar/skill.js — trusted-main-thread UI skill
+ *
+ * Attaches a "Tip the creator" button to the agent's chat UI and executes an
+ * ERC-7710 delegation redemption to transfer USDC directly to agent.ownerAddress.
+ *
+ * Runtime dependencies loaded lazily (tasks 10 + 13 must be deployed):
+ * /src/runtime/delegation-redeem.js → redeemFromSkill
+ * /src/permissions/grant-modal.js → openGrantModal
+ *
+ * Host contract (provided by the embedding runtime):
+ * host.attachAction({ id, label, icon, handler, oneShot? })
+ * host.speak(text)
+ * host.showMessage(text)
+ * host.isOwner — true when the current viewer owns this agent
+ */
+
+/** USDC contract addresses indexed by EVM chainId. */
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base mainnet
+};
+
+const TIP_OPTIONS = [1, 5, 10]; // USDC display amounts
+const USDC_DECIMALS = 6;
+
+// ── Pure helper ──────────────────────────────────────────────────────────────
+
+/**
+ * Build ERC-20 transfer calldata without any external dependency.
+ *
+ * Equivalent to:
+ * new Interface(['function transfer(address,uint256)'])
+ * .encodeFunctionData('transfer', [recipient, amountBaseUnits])
+ *
+ * ABI encoding:
+ * selector = keccak256("transfer(address,uint256)")[0..4] = 0xa9059cbb
+ * arg[0] = recipient address, zero-padded left to 32 bytes
+ * arg[1] = amountBaseUnits as big-endian uint256, zero-padded to 32 bytes
+ *
+ * @param {string} tokenAddr ERC-20 contract address (checksummed or lower)
+ * @param {string} recipient Destination address
+ * @param {string|bigint} amountBaseUnits Token-native units (e.g. 5000000 for 5 USDC)
+ * @returns {{ to: string, value: string, data: string }}
+ */
+export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
+ const addr = recipient.replace(/^0x/i, '').toLowerCase().padStart(64, '0');
+ const amt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
+ return {
+ to: tokenAddr,
+ value: '0x0',
+ data: '0xa9059cbb' + addr + amt,
+ };
+}
+
+// ── Skill lifecycle ──────────────────────────────────────────────────────────
+
+/**
+ * Called once when the skill is installed into an agent session.
+ * Attaches the tip button to the agent's action bar.
+ *
+ * @param {{ agent: Object, host: Object }} ctx
+ */
+export async function setup({ agent, host }) {
+ host.attachAction({
+ id: 'tip-jar:tip',
+ label: 'Tip the creator',
+ icon: '💝',
+ handler: () => execute({ agent, host, args: {} }),
+ });
+}
+
+/**
+ * Invoked when the viewer clicks "Tip the creator".
+ *
+ * @param {{ agent: Object, host: Object, args: Object }} ctx
+ */
+export async function execute({ agent, host, args: _args }) {
+ const chainId = agent.chainId ?? 84532;
+ const usdcAddr = USDC_BY_CHAIN[chainId];
+
+ if (!usdcAddr) {
+ _notify(host, `Chain ${chainId} is not supported for tipping.`);
+ return;
+ }
+
+ // 1. Ask viewer for amount
+ const amount = await _pickAmount();
+ if (amount === null) return; // cancelled
+
+ const amountBase = String(BigInt(Math.round(amount)) * BigInt(10 ** USDC_DECIMALS));
+ const call = buildERC20Transfer(usdcAddr, agent.ownerAddress, amountBase);
+
+ // 2. Lazy-load delegation-redeem (task 13)
+ let redeemFromSkill;
+ try {
+ ({ redeemFromSkill } = await import('/src/runtime/delegation-redeem.js'));
+ } catch {
+ _notify(host, 'Tipping is not available yet on this install.');
+ return;
+ }
+
+ // 3. Execute the delegated transfer
+ try {
+ const result = await redeemFromSkill({
+ agentId: agent.id,
+ chainId,
+ skillId: 'tip-jar',
+ calls: [call],
+ mode: 'auto',
+ });
+
+ if (!result.ok) {
+ const err = new Error(result.error);
+ err.code = result.error;
+ throw err;
+ }
+
+ // 4. Success
+ host.speak('Thank you for the tip!');
+ _emitTipReceived(agent, amount, result.txHash);
+ _notify(host, `Tip sent! Tx: ${result.txHash}`);
+
+ } catch (err) {
+ const code = err.code ?? err.message;
+
+ if (code === 'delegation_not_found' || code === 'no_delegation') {
+ await _handleNoDelegation({ agent, host, chainId, usdcAddr });
+ } else if (code === 'scope_exceeded') {
+ _notify(host, 'Daily tipping cap reached — try again tomorrow.');
+ } else {
+ _notify(host, `Tip failed: ${code}`);
+ }
+ }
+}
+
+// ── Private helpers ──────────────────────────────────────────────────────────
+
+/** Render a small amount-picker modal; resolves with the chosen number or null on cancel. */
+function _pickAmount() {
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'tip-jar-overlay';
+ overlay.innerHTML = `
+ <div class="tip-jar-modal">
+ <p class="tip-jar-title">Choose a tip amount</p>
+ <div class="tip-jar-options">
+ ${TIP_OPTIONS.map((v) => `<button class="tip-jar-btn" data-v="${v}">${v} USDC</button>`).join('')}
+ </div>
+ <input
+ class="tip-jar-custom"
+ type="number"
+ min="0.01"
+ max="10"
+ step="1"
+ placeholder="Custom (max 10 USDC)"
+ />
+ <div class="tip-jar-footer">
+ <button class="tip-jar-send" disabled>Send tip</button>
+ <button class="tip-jar-cancel">Cancel</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const sendBtn = overlay.querySelector('.tip-jar-send');
+ const cancelBtn = overlay.querySelector('.tip-jar-cancel');
+ const customInput = overlay.querySelector('.tip-jar-custom');
+ let selected = null;
+
+ const select = (val) => {
+ selected = val;
+ overlay.querySelectorAll('.tip-jar-btn').forEach(
+ (b) => b.classList.toggle('selected', Number(b.dataset.v) === val),
+ );
+ sendBtn.disabled = false;
+ };
+
+ overlay.querySelectorAll('.tip-jar-btn').forEach((btn) =>
+ btn.addEventListener('click', () => {
+ customInput.value = '';
+ select(Number(btn.dataset.v));
+ }),
+ );
+
+ customInput.addEventListener('input', () => {
+ const val = parseFloat(customInput.value);
+ if (val > 0 && val <= 10) {
+ overlay.querySelectorAll('.tip-jar-btn').forEach((b) => b.classList.remove('selected'));
+ select(val);
+ } else {
+ selected = null;
+ sendBtn.disabled = true;
+ }
+ });
+
+ const done = (val) => { document.body.removeChild(overlay); resolve(val); };
+ sendBtn.addEventListener('click', () => done(selected));
+ cancelBtn.addEventListener('click', () => done(null));
+ });
+}
+
+/**
+ * Handle the no-delegation error path.
+ * - Non-owner: display friendly copy.
+ * - Owner: surface a one-shot "Grant tipping" action that opens the grant modal.
+ */
+async function _handleNoDelegation({ agent, host, chainId, usdcAddr }) {
+ const baseMsg = "The creator hasn't enabled tipping on this device yet.";
+
+ if (!host.isOwner) {
+ _notify(host, baseMsg);
+ return;
+ }
+
+ // Owner only: load grant modal (task 10)
+ let openGrantModal;
+ try {
+ ({ openGrantModal } = await import('/src/permissions/grant-modal.js'));
+ } catch {
+ _notify(host, `${baseMsg} (Grant modal not available — task 10 pending.)`);
+ return;
+ }
+
+ host.attachAction({
+ id: 'tip-jar:grant',
+ label: 'Grant tipping',
+ icon: '🔑',
+ oneShot: true,
+ handler: () =>
+ openGrantModal({
+ agentId: agent.id,
+ chainId,
+ preset: {
+ token: usdcAddr,
+ maxAmount: '10000000',
+ period: 'daily',
+ targets: [usdcAddr],
+ expiry_days: 30,
+ },
+ }),
+ });
+
+ _notify(host, `${baseMsg} Click "Grant tipping" to enable it.`);
+}
+
+/** Emit tip.received on the global protocol bus (non-fatal if unavailable). */
+function _emitTipReceived(agent, amountUsdc, txHash) {
+ try {
+ const bus = globalThis.__agentProtocol ?? globalThis.VIEWER?.agent_protocol;
+ if (bus) {
+ bus.emit({
+ type: 'tip.received',
+ payload: { agentId: agent.id, amountUsdc, txHash },
+ agentId: agent.id,
+ sourceSkill: 'tip-jar',
+ });
+ }
+ } catch { /* protocol is optional */ }
+}
+
+/** Surface a message via host.showMessage if available, otherwise log. */
+function _notify(host, text) {
+ if (typeof host?.showMessage === 'function') host.showMessage(text);
+ else console.info('[tip-jar]', text);
+}
diff --git a/public/wallet-login.js b/public/wallet-login.js
index 07bbaf7c2..7bfbf64d5 100644
--- a/public/wallet-login.js
+++ b/public/wallet-login.js
@@ -1,122 +1,22 @@
-// Client-side wallet authentication.
-// Used by /login page. Supports two paths:
-// 1. Privy — email/social/wallet login with auto-created embedded wallets
-// 2. Raw MetaMask/SIWE — via ConnectWalletController (unified state machine)
-//
+// Client-side wallet authentication (SIWE / MetaMask).
// Loaded as a module from login.html — imports from CDN so it works outside Vite.
-import { BrowserProvider } from 'https://esm.sh/[email protected]';
import { createConnectWalletButton } from '/wallet/connect-button.js';
const params = new URLSearchParams(location.search);
const next = params.get('next') || '/dashboard/';
-// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var).
-let PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';
-const configReady = fetch('/api/config', { credentials: 'omit' })
- .then((r) => (r.ok ? r.json() : null))
- .then((cfg) => { if (cfg?.privyAppId) PRIVY_APP_ID = cfg.privyAppId; })
- .catch(() => {});
-
-// ── UI helpers ──────────────────────────────────────────────────────────────
-
-function ui() {
- const privyBtn = document.getElementById('privy');
- const errEl = document.getElementById('err');
- return {
- privyBtn,
- errEl,
- setErr: (m) => { if (errEl) { errEl.textContent = m; errEl.style.display = 'block'; } },
- clearErr: () => { if (errEl) errEl.style.display = 'none'; },
- };
+function setErr(m) {
+ const el = document.getElementById('err');
+ if (el) { el.textContent = m; el.style.display = 'block'; }
}
-
-// ── Privy login (primary path — unchanged from original) ──────────────────
-
-async function signInWithPrivy() {
- const { privyBtn, setErr, clearErr } = ui();
- await configReady;
- if (!PRIVY_APP_ID) { setErr('Privy not configured.'); return; }
-
- clearErr();
- if (privyBtn) { privyBtn.disabled = true; privyBtn.textContent = 'Loading Privy…'; }
-
- try {
- const mod = await import('https://esm.sh/@privy-io/js-sdk-core@latest');
- const PrivyClient = mod.PrivyClient || mod.default;
- const privy = new PrivyClient({ appId: PRIVY_APP_ID });
-
- if (privyBtn) privyBtn.textContent = 'Opening login…';
- await privy.login({ loginMethods: ['wallet', 'email', 'google'] });
-
- if (privyBtn) privyBtn.textContent = 'Connecting wallet…';
- const eip1193 = await privy.getEthereumProvider();
- if (!eip1193) throw new Error('No wallet provider returned by Privy.');
-
- const provider = new BrowserProvider(eip1193);
- await completePrivySignIn(provider, privyBtn);
- } catch (e) {
- const msg = e?.message || String(e);
- setErr(msg === 'user rejected action' || msg.includes('cancelled') ? 'Login cancelled.' : msg);
- if (privyBtn) { privyBtn.disabled = false; privyBtn.textContent = 'Sign in with Privy'; }
- }
-}
-
-// Privy-specific SIWE completion (kept separate from the controller flow).
-async function completePrivySignIn(provider, btn) {
- const signer = await provider.getSigner();
- const address = await signer.getAddress();
- const network = await provider.getNetwork();
- const chainId = Number(network.chainId);
-
- if (btn) btn.textContent = 'Requesting nonce…';
- const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });
- if (!nonceRes.ok) throw new Error('Failed to get nonce');
- const { nonce, csrf } = await nonceRes.json();
-
- const domain = location.host;
- const uri = location.origin;
- const issuedAt = new Date().toISOString();
- const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();
-
- const message = [
- `${domain} wants you to sign in with your Ethereum account:`,
- address,
- '',
- 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',
- '',
- `URI: ${uri}`,
- 'Version: 1',
- `Chain ID: ${chainId}`,
- `Nonce: ${nonce}`,
- `Issued At: ${issuedAt}`,
- `Expiration Time: ${expirationTime}`,
- ].join('\n');
-
- if (btn) btn.textContent = 'Check your wallet…';
- const signature = await signer.signMessage(message);
-
- if (btn) btn.textContent = 'Verifying…';
- const verifyRes = await fetch('/api/auth/siwe/verify', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
- body: JSON.stringify({ message, signature }),
- });
- const data = await verifyRes.json();
- if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');
-
- try {
- localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() }));
- } catch { /* ignore */ }
- location.href = next;
+function clearErr() {
+ const el = document.getElementById('err');
+ if (el) el.style.display = 'none';
}
-// ── Raw MetaMask / SIWE — unified controller ───────────────────────────────
-
const walletMount = document.getElementById('wallet-mount');
if (walletMount) {
- const { setErr, clearErr } = ui();
const ctrl = createConnectWalletButton(walletMount, {
verifyUrl: '/api/auth/siwe/verify',
onSuccess: () => {
@@ -136,9 +36,4 @@ if (walletMount) {
clearErr();
}
});
-}
-
-// ── Privy button ────────────────────────────────────────────────────────────
-
-const privyBtn = document.getElementById('privy');
-if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);
+}
\ No newline at end of file
diff --git a/scripts/apply-delegations-schema.js b/scripts/apply-delegations-schema.js
new file mode 100644
index 000000000..68775bab5
--- /dev/null
+++ b/scripts/apply-delegations-schema.js
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+// Applies specs/schema/agent_delegations.sql to the Neon dev database.
+// Idempotent — safe to re-run.
+// Usage: node scripts/apply-delegations-schema.js
+// node -r dotenv/config scripts/apply-delegations-schema.js
+
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Pool, neonConfig } from '@neondatabase/serverless';
+import ws from 'ws';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = resolve(__dirname, '..');
+
+function loadEnvFile(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf8');
+ } catch {
+ return;
+ }
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
+ if (!m) continue;
+ const [, k, v] = m;
+ if (process.env[k]) continue;
+ process.env[k] = v.replace(/^["']|["']$/g, '');
+ }
+}
+loadEnvFile(resolve(root, '.env.local'));
+loadEnvFile(resolve(root, '.env'));
+
+const url = process.env.DATABASE_URL;
+if (!url) {
+ console.error('DATABASE_URL not set');
+ process.exit(1);
+}
+
+neonConfig.webSocketConstructor = ws;
+
+const schema = readFileSync(resolve(root, 'specs/schema/agent_delegations.sql'), 'utf8');
+const host = new URL(url).host;
+
+console.log(`Applying agent_delegations schema to ${host} …`);
+
+const pool = new Pool({ connectionString: url });
+try {
+ await pool.query(schema);
+ console.log('✓ schema applied');
+
+ const countResult = await pool.query(
+ 'SELECT COUNT(*) AS count FROM agent_delegations'
+ );
+ console.log(` agent_delegations row count: ${countResult.rows[0].count}`);
+
+ const indexResult = await pool.query(`
+ SELECT indexname, indexdef
+ FROM pg_indexes
+ WHERE tablename = 'agent_delegations'
+ ORDER BY indexname
+ `);
+ console.log(` indexes (${indexResult.rows.length}):`);
+ for (const row of indexResult.rows) {
+ console.log(` ${row.indexname}`);
+ }
+} catch (err) {
+ console.error('✗ schema failed:', err.message);
+ process.exitCode = 1;
+} finally {
+ await pool.end();
+}
diff --git a/scripts/apply-indexer-schema.js b/scripts/apply-indexer-schema.js
new file mode 100644
index 000000000..95b47b136
--- /dev/null
+++ b/scripts/apply-indexer-schema.js
@@ -0,0 +1,59 @@
+#!/usr/bin/env node
+// Applies specs/schema/indexer_state.sql to the Neon dev database.
+// Idempotent — safe to re-run.
+// Usage: node scripts/apply-indexer-schema.js
+// node -r dotenv/config scripts/apply-indexer-schema.js
+
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Pool, neonConfig } from '@neondatabase/serverless';
+import ws from 'ws';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = resolve(__dirname, '..');
+
+function loadEnvFile(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf8');
+ } catch {
+ return;
+ }
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
+ if (!m) continue;
+ const [, k, v] = m;
+ if (process.env[k]) continue;
+ process.env[k] = v.replace(/^["']|["']$/g, '');
+ }
+}
+loadEnvFile(resolve(root, '.env.local'));
+loadEnvFile(resolve(root, '.env'));
+
+const url = process.env.DATABASE_URL;
+if (!url) {
+ console.error('DATABASE_URL not set');
+ process.exit(1);
+}
+
+neonConfig.webSocketConstructor = ws;
+
+const schema = readFileSync(resolve(root, 'specs/schema/indexer_state.sql'), 'utf8');
+const host = new URL(url).host;
+
+console.log(`Applying indexer_state schema to ${host} …`);
+
+const pool = new Pool({ connectionString: url });
+try {
+ await pool.query(schema);
+ console.log('✓ schema applied');
+
+ const countResult = await pool.query('SELECT COUNT(*) AS count FROM indexer_state');
+ console.log(` indexer_state row count: ${countResult.rows[0].count}`);
+} catch (err) {
+ console.error('✗ schema failed:', err.message);
+ process.exitCode = 1;
+} finally {
+ await pool.end();
+}
diff --git a/scripts/check-erc7710-addresses.js b/scripts/check-erc7710-addresses.js
new file mode 100644
index 000000000..0157630a5
--- /dev/null
+++ b/scripts/check-erc7710-addresses.js
@@ -0,0 +1,68 @@
+#!/usr/bin/env node
+// Verifies that every address in DELEGATION_MANAGER_DEPLOYMENTS is a deployed contract.
+// Calls eth_getCode via public RPC for each chain; exits non-zero if any returns '0x'.
+
+import { DELEGATION_MANAGER_DEPLOYMENTS } from '../src/erc7710/abi.js';
+import { CHAIN_META } from '../src/erc8004/chain-meta.js';
+
+const FALLBACK_RPCS = {
+ 1: 'https://ethereum-rpc.publicnode.com',
+ 8453: 'https://mainnet.base.org',
+ 11155111: 'https://ethereum-sepolia-rpc.publicnode.com',
+ 84532: 'https://sepolia.base.org',
+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
+ 11155420: 'https://sepolia.optimism.io',
+};
+
+async function getCode(rpcUrl, address) {
+ const body = JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'eth_getCode',
+ params: [address, 'latest'],
+ });
+ const res = await fetch(rpcUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body,
+ });
+ const json = await res.json();
+ if (json.error) throw new Error(json.error.message);
+ return json.result;
+}
+
+let failed = false;
+
+console.log('Checking DelegationManager deployments...\n');
+console.log('chainId | address | bytecode len | status');
+console.log('---------|--------------------------------------------|--------------|---------');
+
+for (const [chainIdStr, address] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {
+ const chainId = Number(chainIdStr);
+ const rpcUrl = CHAIN_META[chainId]?.rpcUrl ?? FALLBACK_RPCS[chainId];
+ if (!rpcUrl) {
+ console.log(`${String(chainId).padEnd(8)} | ${address} | n/a | SKIP (no RPC)`);
+ continue;
+ }
+ try {
+ const code = await getCode(rpcUrl, address);
+ const byteLen = (code.length - 2) / 2; // strip 0x, each byte = 2 hex chars
+ const ok = code !== '0x' && byteLen > 0;
+ if (!ok) failed = true;
+ const status = ok ? 'OK' : 'FAIL (empty)';
+ console.log(
+ `${String(chainId).padEnd(8)} | ${address} | ${String(byteLen).padStart(12)} | ${status}`,
+ );
+ } catch (err) {
+ failed = true;
+ console.log(`${String(chainId).padEnd(8)} | ${address} | ERROR | ${err.message}`);
+ }
+}
+
+console.log('');
+if (failed) {
+ console.error('One or more addresses failed the bytecode check.');
+ process.exit(1);
+} else {
+ console.log('All addresses verified — bytecode present on every listed chain.');
+}
diff --git a/scripts/test-toolkit.js b/scripts/test-toolkit.js
new file mode 100644
index 000000000..89aafba2b
--- /dev/null
+++ b/scripts/test-toolkit.js
@@ -0,0 +1,141 @@
+/**
+ * Self-check for src/permissions/toolkit.js — pure functions only, no network.
+ * Usage: node scripts/test-toolkit.js
+ */
+
+import assert from 'assert';
+import { CAVEAT_ENFORCERS } from '../src/erc7710/abi.js';
+import {
+ delegationToManifestEntry,
+ encodeScopedDelegation,
+ PermissionError,
+} from '../src/permissions/toolkit.js';
+
+const CHAIN_ID = 84532; // Base Sepolia
+const DELEGATOR = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'; // EIP-55 checksummed
+const DELEGATE = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
+const EXPIRY = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
+
+// CAVEAT_ENFORCERS is keyed enforcer → { chainId → address }
+const caveats = [
+ {
+ enforcer: CAVEAT_ENFORCERS.AllowedTargetsEnforcer[CHAIN_ID],
+ terms: '0x000000000000000000000000' + DELEGATE.slice(2).toLowerCase(),
+ args: '0x',
+ },
+];
+
+// ─── encodeScopedDelegation: happy path ──────────────────────────────────────
+
+const delegation = encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: CHAIN_ID });
+
+assert.strictEqual(delegation.delegate, DELEGATE, 'delegate address');
+assert.strictEqual(delegation.delegator, DELEGATOR, 'delegator address');
+assert.strictEqual(
+ delegation.authority,
+ '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
+ 'ROOT_AUTHORITY',
+);
+assert.strictEqual(typeof delegation.salt, 'bigint', 'salt is bigint');
+assert.strictEqual(delegation.caveats.length, 1, 'one caveat');
+assert.strictEqual(delegation.caveats[0].args, '0x', 'args default');
+assert.strictEqual(delegation.chainId, CHAIN_ID, 'chainId');
+console.log('✓ encodeScopedDelegation — happy path');
+
+// ─── encodeScopedDelegation: non-checksummed input is accepted + checksummed ─
+
+const lower = encodeScopedDelegation({
+ delegator: DELEGATOR.toLowerCase(),
+ delegate: DELEGATE.toLowerCase(),
+ caveats,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+});
+assert.strictEqual(lower.delegator, DELEGATOR, 'delegator auto-checksummed');
+assert.strictEqual(lower.delegate, DELEGATE, 'delegate auto-checksummed');
+console.log('✓ encodeScopedDelegation — address checksumming');
+
+// ─── encodeScopedDelegation: error cases ─────────────────────────────────────
+
+assert.throws(
+ () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATOR, caveats, expiry: EXPIRY, chainId: CHAIN_ID }),
+ (e) => e instanceof PermissionError && e.code === 'signature_invalid',
+ 'delegate === delegator must throw signature_invalid',
+);
+
+assert.throws(
+ () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats: [], expiry: EXPIRY, chainId: CHAIN_ID }),
+ (e) => e instanceof PermissionError,
+ 'empty caveats must throw',
+);
+
+assert.throws(
+ () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: Math.floor(Date.now() / 1000) + 30, chainId: CHAIN_ID }),
+ (e) => e instanceof PermissionError && e.code === 'delegation_expired',
+ 'near-future expiry must throw delegation_expired',
+);
+
+assert.throws(
+ () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: 999999 }),
+ (e) => e instanceof PermissionError && e.code === 'chain_not_supported',
+ 'unsupported chain (999999) must throw chain_not_supported',
+);
+
+assert.throws(
+ () => encodeScopedDelegation({ delegator: 'not-an-address', delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: CHAIN_ID }),
+ (e) => e instanceof PermissionError && e.code === 'signature_invalid',
+ 'invalid address must throw signature_invalid',
+);
+console.log('✓ encodeScopedDelegation — error cases');
+
+// ─── delegationToManifestEntry: with full scope ───────────────────────────────
+
+const signed = {
+ ...delegation,
+ signature: '0x' + 'ab'.repeat(65),
+ hash: '0x' + 'cd'.repeat(32),
+ uri: 'ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
+ scope: {
+ token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
+ maxAmount: '1000000',
+ period: 'daily',
+ targets: [DELEGATE],
+ expiry: EXPIRY,
+ },
+};
+
+const entry = delegationToManifestEntry(signed);
+assert.strictEqual(entry.chainId, CHAIN_ID, 'entry.chainId');
+assert.strictEqual(entry.delegator, DELEGATOR, 'entry.delegator');
+assert.strictEqual(entry.delegate, DELEGATE, 'entry.delegate');
+assert.strictEqual(entry.hash, signed.hash, 'entry.hash');
+assert.strictEqual(entry.uri, signed.uri, 'entry.uri');
+assert.strictEqual(entry.scope.token, signed.scope.token, 'entry.scope.token');
+assert.strictEqual(entry.scope.maxAmount, '1000000', 'entry.scope.maxAmount');
+assert.strictEqual(entry.scope.period, 'daily', 'entry.scope.period');
+assert.deepStrictEqual(entry.scope.targets, [DELEGATE], 'entry.scope.targets');
+assert.strictEqual(entry.scope.expiry, EXPIRY, 'entry.scope.expiry');
+// signature must NOT be in the manifest entry
+assert.strictEqual('signature' in entry, false, 'signature must not appear in manifest entry');
+console.log('✓ delegationToManifestEntry — with scope');
+
+// ─── delegationToManifestEntry: without scope (defaults) ─────────────────────
+
+const noScope = delegationToManifestEntry({ ...signed, scope: undefined, uri: undefined });
+assert.ok(noScope.scope, 'default scope present');
+assert.strictEqual(noScope.scope.token, 'native', 'default token = native');
+assert.strictEqual(noScope.scope.period, 'once', 'default period = once');
+assert.strictEqual('uri' in noScope, false, 'no uri when not provided');
+console.log('✓ delegationToManifestEntry — defaults');
+
+// ─── PermissionError shape ────────────────────────────────────────────────────
+
+const err = new PermissionError('delegation_revoked', 'test revoke');
+assert.ok(err instanceof Error, 'is Error');
+assert.ok(err instanceof PermissionError, 'is PermissionError');
+assert.strictEqual(err.code, 'delegation_revoked', 'err.code');
+assert.strictEqual(err.name, 'PermissionError', 'err.name');
+assert.strictEqual(err.message, 'test revoke', 'err.message');
+console.log('✓ PermissionError shape');
+
+console.log('\nAll tests passed.');
diff --git a/sdk/README.md b/sdk/README.md
index f27f84473..4c89ef16e 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -111,6 +111,42 @@ export const REGISTRY_DEPLOYMENTS = {
};
```
+## Permissions
+
+Grant, list, redeem, and revoke ERC-7710 scoped delegations via the `PermissionsClient`.
+`grant` and `revoke` require a browser wallet (MetaMask / any injected ethers v6 Signer).
+
+```ts
+import { AgentKit } from '@nirholas/agent-kit';
+import { PermissionsClient } from '@nirholas/agent-kit/permissions';
+
+const client = new PermissionsClient({ baseUrl: 'https://3dagent.vercel.app' });
+
+// Fetch active delegations for an agent
+const { spec, delegations } = await client.getMetadata(agentId);
+
+// Grant a new delegation (browser only — needs MetaMask)
+const { id, delegationHash } = await client.grant({
+ agentId,
+ chainId: 84532,
+ preset: { token: 'native', maxAmount: '1000000', period: 'daily', targets: ['0xTarget'], expiryDays: 30 },
+ delegate: agentSmartAccountAddress,
+ signer, // ethers v6 Signer from connectWallet()
+});
+
+// Verify on-chain that a delegation is still active
+const { valid, reason } = await client.verify(delegationHash, 84532);
+
+// Revoke (browser only)
+await client.revoke({ id, delegationHash, signer });
+```
+
+For advanced use (direct toolkit access with tree-shaking):
+
+```ts
+import { encodeScopedDelegation, isDelegationValid } from '@nirholas/agent-kit/permissions/advanced';
+```
+
## License
MIT
diff --git a/sdk/package.json b/sdk/package.json
index e88ba4ef3..44a21b4f6 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -12,11 +12,24 @@
"import": "./src/index.js",
"default": "./src/index.js"
},
+ "./permissions": {
+ "types": "./src/permissions.d.ts",
+ "import": "./src/permissions.js",
+ "default": "./src/permissions.js"
+ },
+ "./permissions/advanced": {
+ "types": "./src/permissions/advanced.d.ts",
+ "import": "./src/permissions/advanced.js",
+ "default": "./src/permissions/advanced.js"
+ },
"./styles": "./src/styles.css"
},
"files": [
"src"
],
+ "scripts": {
+ "test": "node --test 'test/**/*.test.js'"
+ },
"keywords": [
"erc-8004",
"agent",
diff --git a/sdk/src/index.d.ts b/sdk/src/index.d.ts
index c4893b1b4..911c1b456 100644
--- a/sdk/src/index.d.ts
+++ b/sdk/src/index.d.ts
@@ -239,3 +239,16 @@ export interface RegistryDeployment {
export const REGISTRY_DEPLOYMENTS: Record<number, RegistryDeployment>;
export function agentRegistryId(chainId: number, registryAddress: string): string;
+
+// ---------------------------------------------------------------------------
+// Permissions — re-exported from ./permissions.js
+// ---------------------------------------------------------------------------
+
+export {
+ DelegationScope,
+ DelegationPublic,
+ ScopePreset,
+ PermissionError,
+ PermissionsClientOptions,
+ PermissionsClient,
+} from './permissions';
diff --git a/sdk/src/index.js b/sdk/src/index.js
index 0d0f6ffd5..6d57cf068 100644
--- a/sdk/src/index.js
+++ b/sdk/src/index.js
@@ -35,6 +35,7 @@ export {
getIdentityRegistry,
} from './erc8004/registry.js';
export { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './erc8004/abi.js';
+export { PermissionsClient, PermissionError } from './permissions.js';
import { AgentPanel } from './panel.js';
import { agentRegistration, agentCard, aiPlugin } from './manifests.js';
diff --git a/sdk/src/permissions.d.ts b/sdk/src/permissions.d.ts
new file mode 100644
index 000000000..e0c5aa472
--- /dev/null
+++ b/sdk/src/permissions.d.ts
@@ -0,0 +1,179 @@
+/**
+ * @nirholas/agent-kit — Permissions module types
+ */
+
+import type { Signer } from 'ethers';
+
+// ---------------------------------------------------------------------------
+// Shared shapes
+// ---------------------------------------------------------------------------
+
+/** Scope of a single delegation, matching the DB `scope` JSONB field. */
+export interface DelegationScope {
+ /** ERC-20 token address or `"native"` for ETH */
+ token: string;
+ /** Maximum spend in token base units (string to avoid BigInt serialisation issues) */
+ maxAmount: string;
+ /** Period for resetting the spend limit */
+ period: 'once' | 'daily' | 'weekly';
+ /** EIP-55 checksummed target contract addresses */
+ targets: string[];
+ /** Delegation expiry as a Unix timestamp (seconds) */
+ expiry: number;
+}
+
+/**
+ * Public delegation record returned by the list and metadata endpoints.
+ * Matches the `toPublicShape` / `toAuthShape` responses from the API.
+ */
+export interface DelegationPublic {
+ /** UUID primary key */
+ id: string;
+ /** Agent UUID this delegation is granted to */
+ agentId: string;
+ /** EVM chain ID */
+ chainId: number;
+ /** EIP-55 checksummed address of the human delegator */
+ delegatorAddress: string;
+ /** EIP-55 checksummed address of the agent's smart account (delegate) */
+ delegateAddress: string;
+ /** keccak256 hash of the signed delegation envelope */
+ delegationHash: string;
+ /** Scope restrictions applied to this delegation */
+ scope: DelegationScope;
+ /** Current lifecycle status */
+ status: 'active' | 'revoked' | 'expired';
+ /** ISO-8601 timestamp when this delegation expires */
+ expiresAt: string;
+ /** ISO-8601 timestamp when this delegation was created */
+ createdAt: string;
+ /** ISO-8601 timestamp when this delegation was revoked (if applicable) */
+ revokedAt?: string;
+ /** ISO-8601 timestamp of the last successful redemption */
+ lastRedeemedAt?: string;
+ /** Total number of successful redemptions */
+ redemptionCount: number;
+}
+
+/**
+ * Human-friendly preset that the SDK translates into ERC-7710 caveats.
+ * Use this instead of building raw `Caveat[]` structs.
+ */
+export interface ScopePreset {
+ /** ERC-20 token address or `"native"` */
+ token: string;
+ /** Maximum spend in token base units */
+ maxAmount: string;
+ /** Spend-limit reset period */
+ period: 'once' | 'daily' | 'weekly';
+ /** EIP-55 checksummed target addresses that the agent is allowed to call */
+ targets: string[];
+ /** Days from now until the delegation expires */
+ expiryDays: number;
+}
+
+// ---------------------------------------------------------------------------
+// Error
+// ---------------------------------------------------------------------------
+
+/**
+ * Thrown for all permissions-related errors.
+ *
+ * Error codes mirror the canonical vocabulary from PERMISSIONS_SPEC.md §8:
+ * `delegation_expired` | `delegation_revoked` | `scope_exceeded` | `target_not_allowed`
+ * | `delegation_not_found` | `signature_invalid` | `chain_not_supported` | `rate_limited`
+ * | `browser_only` | `unknown_error`
+ */
+export class PermissionError extends Error {
+ /** Canonical error code */
+ code: string;
+ constructor(code: string, message: string);
+}
+
+// ---------------------------------------------------------------------------
+// Client
+// ---------------------------------------------------------------------------
+
+export interface PermissionsClientOptions {
+ /** API base URL (default: https://3dagent.vercel.app) */
+ baseUrl?: string;
+ /** Bearer token for authenticated endpoints */
+ bearer?: string;
+}
+
+/**
+ * HTTP client for the 3D Agent permissions API.
+ *
+ * `grant` and `revoke` are browser-only — they require a wallet-connected
+ * `ethers.Signer` and will throw `PermissionError('browser_only', …)` in Node.js.
+ */
+export class PermissionsClient {
+ constructor(opts?: PermissionsClientOptions);
+
+ /**
+ * List delegations for an agent or delegator.
+ *
+ * Passing only `agentId` is public (no auth).
+ * Passing `delegator` requires a bearer token or session.
+ */
+ listDelegations(params?: {
+ agentId?: string;
+ delegator?: string;
+ status?: string;
+ }): Promise<DelegationPublic[]>;
+
+ /**
+ * Fetch public permissions metadata for an agent,
+ * including all active delegations and the spec version.
+ */
+ getMetadata(agentId: string): Promise<{
+ spec: string;
+ delegations: DelegationPublic[];
+ }>;
+
+ /**
+ * Grant a scoped ERC-7710 delegation to an agent. **Browser only.**
+ *
+ * Builds an unsigned delegation from `preset`, signs it via EIP-712 using
+ * `signer` (the human owner / delegator), then POSTs to `/api/permissions/grant`.
+ *
+ * @param delegate - The agent's smart account address (obtain from the manifest or `getMetadata`)
+ */
+ grant(params: {
+ agentId: string;
+ chainId: number;
+ preset: ScopePreset;
+ /** Agent's smart account address (delegate in the ERC-7710 envelope) */
+ delegate: string;
+ signer: Signer;
+ }): Promise<{ id: string; delegationHash: string }>;
+
+ /**
+ * Redeem a delegation to execute on-chain calls.
+ * Executed server-side via a relayer; requires a bearer token.
+ */
+ redeem(params: {
+ id: string;
+ calls: Array<{ to: string; value?: string; data: string }>;
+ }): Promise<{ txHash: string }>;
+
+ /**
+ * Revoke a delegation on-chain and mirror to the server. **Browser only.**
+ *
+ * Sends `DelegationManager.disableDelegation(delegationHash)` via `signer`,
+ * then POSTs the tx hash to `/api/permissions/revoke`.
+ *
+ * Obtain `delegationHash` from `DelegationPublic.delegationHash` before calling.
+ */
+ revoke(params: {
+ id: string;
+ /** keccak256 hash of the delegation (from `DelegationPublic.delegationHash`) */
+ delegationHash: string;
+ signer: Signer;
+ }): Promise<{ status: 'revoked'; txHash: string }>;
+
+ /**
+ * Verify that a delegation hash is valid on-chain via the `/api/permissions/verify` endpoint.
+ */
+ verify(hash: string, chainId: number): Promise<{ valid: boolean; reason?: string }>;
+}
diff --git a/sdk/src/permissions.js b/sdk/src/permissions.js
new file mode 100644
index 000000000..7c4bda4e6
--- /dev/null
+++ b/sdk/src/permissions.js
@@ -0,0 +1,248 @@
+/**
+ * @nirholas/agent-kit — Permissions module
+ *
+ * ERC-7710 scoped delegation client for 3D Agent.
+ *
+ * Quick start:
+ * import { PermissionsClient } from '@nirholas/agent-kit/permissions';
+ * const client = new PermissionsClient({ baseUrl: 'https://3dagent.vercel.app' });
+ * const { delegations } = await client.getMetadata(agentId);
+ */
+
+const DEFAULT_BASE = 'https://3dagent.vercel.app';
+
+/**
+ * Typed error class for permission operations.
+ * The `code` property maps to canonical error codes from PERMISSIONS_SPEC.md §8.
+ *
+ * Codes: delegation_expired | delegation_revoked | scope_exceeded | target_not_allowed
+ * | delegation_not_found | signature_invalid | chain_not_supported | rate_limited
+ */
+export class PermissionError extends Error {
+ /**
+ * @param {string} code Canonical error code from the spec
+ * @param {string} message Human-readable description
+ */
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ this.name = 'PermissionError';
+ }
+}
+
+/**
+ * HTTP client for the 3D Agent permissions API.
+ *
+ * Methods `grant` and `revoke` require a browser-connected ethers v6 Signer and will
+ * throw `PermissionError('browser_only', ...)` when called in a Node.js environment.
+ */
+export class PermissionsClient {
+ /**
+ * @param {object} [opts]
+ * @param {string} [opts.baseUrl] API base URL (default: https://3dagent.vercel.app)
+ * @param {string} [opts.bearer] Bearer token for authenticated endpoints (redeem, private list)
+ */
+ constructor({ baseUrl = DEFAULT_BASE, bearer } = {}) {
+ this._base = baseUrl.replace(/\/$/, '');
+ this._bearer = bearer ?? null;
+ }
+
+ /** @returns {Record<string, string>} */
+ _headers() {
+ const h = { 'Content-Type': 'application/json' };
+ if (this._bearer) h['Authorization'] = `Bearer ${this._bearer}`;
+ return h;
+ }
+
+ /**
+ * @param {string} url
+ * @param {RequestInit} [opts]
+ * @returns {Promise<any>}
+ */
+ async _request(url, opts = {}) {
+ const res = await fetch(url, { ...opts, headers: this._headers() });
+ const body = await res.json();
+ if (!body.ok) {
+ throw new PermissionError(
+ body.error ?? 'unknown_error',
+ body.message ?? body.error ?? 'Request failed',
+ );
+ }
+ return body;
+ }
+
+ /**
+ * List delegations for an agent or delegator.
+ *
+ * Public path (agentId only) returns active delegations without auth.
+ * Private path (delegator) requires a bearer token or session.
+ *
+ * @param {{ agentId?: string; delegator?: string; status?: string }} [params]
+ * @returns {Promise<DelegationPublic[]>}
+ */
+ async listDelegations({ agentId, delegator, status } = {}) {
+ const url = new URL(`${this._base}/api/permissions/list`);
+ if (agentId) url.searchParams.set('agentId', agentId);
+ if (delegator) url.searchParams.set('delegator', delegator);
+ if (status) url.searchParams.set('status', status);
+ const data = await this._request(url.toString());
+ return data.delegations ?? [];
+ }
+
+ /**
+ * Fetch public permissions metadata for an agent.
+ * Returns the spec version and the agent's active delegations.
+ *
+ * @param {string} agentId
+ * @returns {Promise<{ spec: string; delegations: DelegationPublic[] }>}
+ */
+ async getMetadata(agentId) {
+ const url = `${this._base}/api/permissions/metadata?agentId=${encodeURIComponent(agentId)}`;
+ const data = await this._request(url);
+ return { spec: data.spec, delegations: data.delegations ?? [] };
+ }
+
+ /**
+ * Grant a scoped ERC-7710 delegation to an agent. **Browser only.**
+ *
+ * Flow: build unsigned delegation → EIP-712 sign via signer → POST /api/permissions/grant.
+ *
+ * The `delegate` param is the agent's smart account address (obtained from the agent manifest
+ * or from `getMetadata`). The signer must be the human owner (delegator) wallet.
+ *
+ * @param {{
+ * agentId: string;
+ * chainId: number;
+ * preset: ScopePreset;
+ * delegate: string;
+ * signer: import('ethers').Signer;
+ * }} params
+ * @returns {Promise<{ id: string; delegationHash: string }>}
+ * @throws {PermissionError} 'browser_only' when called in Node.js
+ */
+ async grant({ agentId, chainId, preset, delegate, signer }) {
+ if (typeof window === 'undefined') {
+ throw new PermissionError(
+ 'browser_only',
+ 'grant() requires a browser environment with a wallet — not available in Node.js',
+ );
+ }
+ // Dynamic import keeps ethers + toolkit out of the Node.js bundle.
+ const { encodeScopedDelegation, signDelegation } = await import(
+ '../../src/permissions/toolkit.js'
+ );
+ const { CAVEAT_ENFORCERS, encodeCaveats } = await import('../../src/erc7710/abi.js');
+
+ const delegatorAddr = await signer.getAddress();
+ const expiry = Math.floor(Date.now() / 1000) + preset.expiryDays * 86400;
+
+ const caveats = [
+ {
+ enforcer: CAVEAT_ENFORCERS.AllowedTargetsEnforcer[chainId],
+ terms: encodeCaveats(preset.targets.map((t) => ({ enforcer: t, terms: '0x', args: '0x' }))),
+ args: '0x',
+ },
+ {
+ enforcer: CAVEAT_ENFORCERS.ERC20LimitEnforcer[chainId],
+ terms: preset.maxAmount,
+ args: '0x',
+ },
+ {
+ enforcer: CAVEAT_ENFORCERS.TimestampEnforcer[chainId],
+ terms: String(expiry),
+ args: '0x',
+ },
+ ];
+
+ const unsigned = encodeScopedDelegation({ delegator: delegatorAddr, delegate, caveats, expiry, chainId });
+ const signed = await signDelegation(unsigned, signer);
+
+ const data = await this._request(`${this._base}/api/permissions/grant`, {
+ method: 'POST',
+ body: JSON.stringify({
+ agentId,
+ chainId,
+ delegation: signed,
+ scope: {
+ token: preset.token,
+ maxAmount: preset.maxAmount,
+ period: preset.period,
+ targets: preset.targets,
+ expiryDays: preset.expiryDays,
+ },
+ }),
+ });
+ return { id: data.id, delegationHash: data.delegationHash };
+ }
+
+ /**
+ * Redeem a delegation to execute on-chain calls. Requires a bearer token.
+ *
+ * The redemption is executed server-side via a relayer. The bearer token must
+ * carry a scope that includes permission to redeem on behalf of the agent.
+ *
+ * @param {{ id: string; calls: Array<{ to: string; value?: string; data: string }> }} params
+ * @returns {Promise<{ txHash: string }>}
+ */
+ async redeem({ id, calls }) {
+ const data = await this._request(`${this._base}/api/permissions/redeem`, {
+ method: 'POST',
+ body: JSON.stringify({ id, calls }),
+ });
+ return { txHash: data.txHash };
+ }
+
+ /**
+ * Revoke a delegation on-chain and mirror the revocation to the server. **Browser only.**
+ *
+ * Flow: send `DelegationManager.disableDelegation(delegationHash)` tx via signer
+ * → POST /api/permissions/revoke with the resulting tx hash.
+ *
+ * Obtain `delegationHash` from the `DelegationPublic` returned by `listDelegations`
+ * or `getMetadata` before calling this method.
+ *
+ * @param {{ id: string; delegationHash: string; signer: import('ethers').Signer }} params
+ * @returns {Promise<{ status: 'revoked'; txHash: string }>}
+ * @throws {PermissionError} 'browser_only' when called in Node.js
+ * @throws {PermissionError} 'chain_not_supported' if no DelegationManager for the signer's chain
+ */
+ async revoke({ id, delegationHash, signer }) {
+ if (typeof window === 'undefined') {
+ throw new PermissionError(
+ 'browser_only',
+ 'revoke() requires a browser environment with a wallet — not available in Node.js',
+ );
+ }
+ const { Contract } = await import('ethers');
+ const { DELEGATION_MANAGER_ABI, DELEGATION_MANAGER_DEPLOYMENTS } = await import(
+ '../../src/erc7710/abi.js'
+ );
+ const network = await signer.provider.getNetwork();
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[Number(network.chainId)];
+ if (!managerAddr) {
+ throw new PermissionError('chain_not_supported', `no DelegationManager for chain ${network.chainId}`);
+ }
+ const dm = new Contract(managerAddr, DELEGATION_MANAGER_ABI, signer);
+ const tx = await dm.disableDelegation(delegationHash);
+ await tx.wait();
+ await this._request(`${this._base}/api/permissions/revoke`, {
+ method: 'POST',
+ body: JSON.stringify({ id, txHash: tx.hash }),
+ });
+ return { status: 'revoked', txHash: tx.hash };
+ }
+
+ /**
+ * Verify that a delegation hash is valid on-chain.
+ * Makes a real-time read from the DelegationManager contract.
+ *
+ * @param {string} hash Delegation hash (keccak256, hex-encoded)
+ * @param {number} chainId Chain ID where the delegation was created
+ * @returns {Promise<{ valid: boolean; reason?: string }>}
+ */
+ async verify(hash, chainId) {
+ const url = `${this._base}/api/permissions/verify?hash=${encodeURIComponent(hash)}&chainId=${chainId}`;
+ const data = await this._request(url);
+ return data.reason !== undefined ? { valid: data.valid, reason: data.reason } : { valid: data.valid };
+ }
+}
diff --git a/sdk/src/permissions/advanced.d.ts b/sdk/src/permissions/advanced.d.ts
new file mode 100644
index 000000000..20175c308
--- /dev/null
+++ b/sdk/src/permissions/advanced.d.ts
@@ -0,0 +1,90 @@
+/**
+ * @nirholas/agent-kit/permissions/advanced — TypeScript definitions
+ */
+
+import type { Signer } from 'ethers';
+
+// ---------------------------------------------------------------------------
+// encodeScopedDelegation
+// ---------------------------------------------------------------------------
+
+export interface UnsignedDelegation {
+ delegate: string;
+ delegator: string;
+ /** EIP-712 authority hash — ZeroHash for root delegations */
+ authority: string;
+ caveats: Caveat[];
+ salt: bigint;
+ chainId: number;
+}
+
+export interface Caveat {
+ /** Caveat enforcer contract address */
+ enforcer: string;
+ /** ABI-encoded terms bytes */
+ terms: string;
+ /** ABI-encoded args bytes */
+ args?: string;
+}
+
+/**
+ * Build an unsigned delegation envelope ready to be signed via `signDelegation`.
+ *
+ * @throws {PermissionError} 'validation_error' if inputs are invalid
+ */
+export function encodeScopedDelegation(opts: {
+ delegator: string;
+ delegate: string;
+ caveats: Caveat[];
+ expiry: number;
+ chainId: number;
+}): UnsignedDelegation;
+
+// ---------------------------------------------------------------------------
+// isDelegationValid
+// ---------------------------------------------------------------------------
+
+/**
+ * Check on-chain whether a delegation is still active (not disabled).
+ * Requires an RPC URL — either passed directly or via `RPC_URL_<chainId>` env var.
+ *
+ * @throws {PermissionError} 'chain_not_supported' if no RPC URL is available
+ */
+export function isDelegationValid(opts: {
+ hash: string;
+ chainId: number;
+ rpcUrl?: string;
+}): Promise<{ valid: boolean; reason?: string }>;
+
+// ---------------------------------------------------------------------------
+// delegationToManifestEntry
+// ---------------------------------------------------------------------------
+
+export interface ManifestDelegationEntry {
+ chainId: number;
+ delegator: string;
+ delegate: string;
+ hash: string;
+ scope: Record<string, unknown>;
+}
+
+/**
+ * Convert a signed delegation to the `permissions.delegations[]` entry shape
+ * used in the agent manifest (`agent-manifest/0.2`).
+ */
+export function delegationToManifestEntry(signedDelegation: {
+ chainId: number;
+ delegator: string;
+ delegate: string;
+ hash: string;
+ scope?: Record<string, unknown>;
+}): ManifestDelegationEntry;
+
+// ---------------------------------------------------------------------------
+// PermissionError (re-exported for convenience)
+// ---------------------------------------------------------------------------
+
+export class PermissionError extends Error {
+ code: string;
+ constructor(code: string, message: string);
+}
diff --git a/sdk/src/permissions/advanced.js b/sdk/src/permissions/advanced.js
new file mode 100644
index 000000000..5a6726375
--- /dev/null
+++ b/sdk/src/permissions/advanced.js
@@ -0,0 +1,18 @@
+/**
+ * @nirholas/agent-kit/permissions/advanced
+ *
+ * Re-exports low-level ERC-7710 delegation helpers from the toolkit for
+ * advanced consumers who need direct control over delegation encoding.
+ *
+ * Tree-shaking note: import from this sub-entry instead of the main package
+ * entry to avoid pulling in the full PermissionsClient:
+ *
+ * import { encodeScopedDelegation } from '@nirholas/agent-kit/permissions/advanced';
+ */
+
+export {
+ encodeScopedDelegation,
+ isDelegationValid,
+ delegationToManifestEntry,
+ PermissionError,
+} from '../../../src/permissions/toolkit.js';
diff --git a/sdk/test/permissions.test.js b/sdk/test/permissions.test.js
new file mode 100644
index 000000000..11b787581
--- /dev/null
+++ b/sdk/test/permissions.test.js
@@ -0,0 +1,247 @@
+/**
+ * PermissionsClient — unit tests
+ *
+ * Uses Node.js built-in test runner (node:test) with an inline global.fetch mock.
+ * No network calls are made.
+ */
+
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import { PermissionsClient, PermissionError } from '../src/permissions.js';
+
+// ---------------------------------------------------------------------------
+// Fetch mock helpers
+// ---------------------------------------------------------------------------
+
+let _lastRequest = null;
+
+/**
+ * Install a one-shot fetch mock that captures the URL/options and returns
+ * the supplied JSON body.
+ * @param {object} responseBody
+ */
+function mockFetch(responseBody) {
+ global.fetch = async (url, opts = {}) => {
+ _lastRequest = { url: String(url), opts };
+ return { json: async () => responseBody };
+ };
+}
+
+const originalFetch = global.fetch;
+after(() => {
+ global.fetch = originalFetch;
+});
+
+// ---------------------------------------------------------------------------
+// listDelegations
+// ---------------------------------------------------------------------------
+
+test('listDelegations — constructs URL with agentId param', async () => {
+ mockFetch({ ok: true, delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ const result = await client.listDelegations({ agentId: 'agent-abc' });
+ assert.ok(_lastRequest.url.includes('/api/permissions/list'), 'should hit list endpoint');
+ assert.ok(_lastRequest.url.includes('agentId=agent-abc'), 'should include agentId param');
+ assert.deepEqual(result, []);
+});
+
+test('listDelegations — constructs URL with delegator and status params', async () => {
+ mockFetch({ ok: true, delegations: [{ id: '1' }] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await client.listDelegations({ delegator: '0xABC', status: 'active' });
+ assert.ok(_lastRequest.url.includes('delegator=0xABC'));
+ assert.ok(_lastRequest.url.includes('status=active'));
+});
+
+test('listDelegations — sends bearer header when set', async () => {
+ mockFetch({ ok: true, delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com', bearer: 'tok_test' });
+ await client.listDelegations({ agentId: 'x' });
+ assert.equal(_lastRequest.opts.headers['Authorization'], 'Bearer tok_test');
+});
+
+test('listDelegations — no Authorization header when bearer not set', async () => {
+ mockFetch({ ok: true, delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await client.listDelegations({ agentId: 'x' });
+ assert.equal(_lastRequest.opts.headers['Authorization'], undefined);
+});
+
+// ---------------------------------------------------------------------------
+// getMetadata
+// ---------------------------------------------------------------------------
+
+test('getMetadata — constructs URL with agentId', async () => {
+ mockFetch({ ok: true, spec: 'erc-7715/0.1', delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ const result = await client.getMetadata('my-agent');
+ assert.ok(_lastRequest.url.includes('/api/permissions/metadata'));
+ assert.ok(_lastRequest.url.includes('agentId=my-agent'));
+ assert.equal(result.spec, 'erc-7715/0.1');
+});
+
+test('getMetadata — URL-encodes agentId with special characters', async () => {
+ mockFetch({ ok: true, spec: 'erc-7715/0.1', delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await client.getMetadata('agent with spaces');
+ assert.ok(_lastRequest.url.includes('agentId=agent%20with%20spaces'));
+});
+
+test('getMetadata — trailing slash in baseUrl is stripped', async () => {
+ mockFetch({ ok: true, spec: 'erc-7715/0.1', delegations: [] });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com/' });
+ await client.getMetadata('ag');
+ assert.ok(!_lastRequest.url.includes('//api'), 'should not produce double slash');
+});
+
+// ---------------------------------------------------------------------------
+// redeem
+// ---------------------------------------------------------------------------
+
+test('redeem — POSTs to correct URL', async () => {
+ mockFetch({ ok: true, txHash: '0xdeadbeef' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com', bearer: 'tok_redeem' });
+ const result = await client.redeem({
+ id: 'uuid-1',
+ calls: [{ to: '0x1234', data: '0xabcd' }],
+ });
+ assert.ok(_lastRequest.url.includes('/api/permissions/redeem'));
+ assert.equal(_lastRequest.opts.method, 'POST');
+ assert.equal(result.txHash, '0xdeadbeef');
+});
+
+test('redeem — sends bearer header', async () => {
+ mockFetch({ ok: true, txHash: '0xabc' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com', bearer: 'my-bearer' });
+ await client.redeem({ id: 'uuid-2', calls: [] });
+ assert.equal(_lastRequest.opts.headers['Authorization'], 'Bearer my-bearer');
+});
+
+test('redeem — includes id and calls in POST body', async () => {
+ mockFetch({ ok: true, txHash: '0x1' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com', bearer: 'tok' });
+ const calls = [{ to: '0xTarget', value: '1000', data: '0x' }];
+ await client.redeem({ id: 'del-id', calls });
+ const body = JSON.parse(_lastRequest.opts.body);
+ assert.equal(body.id, 'del-id');
+ assert.deepEqual(body.calls, calls);
+});
+
+// ---------------------------------------------------------------------------
+// verify
+// ---------------------------------------------------------------------------
+
+test('verify — constructs URL with hash and chainId', async () => {
+ mockFetch({ ok: true, valid: true });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ const result = await client.verify('0xhashvalue', 84532);
+ assert.ok(_lastRequest.url.includes('/api/permissions/verify'));
+ assert.ok(_lastRequest.url.includes('hash=0xhashvalue'));
+ assert.ok(_lastRequest.url.includes('chainId=84532'));
+ assert.equal(result.valid, true);
+ assert.equal(result.reason, undefined);
+});
+
+test('verify — includes reason when server returns it', async () => {
+ mockFetch({ ok: true, valid: false, reason: 'delegation_revoked' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ const result = await client.verify('0xhash', 11155111);
+ assert.equal(result.valid, false);
+ assert.equal(result.reason, 'delegation_revoked');
+});
+
+// ---------------------------------------------------------------------------
+// grant — browser-only guard
+// ---------------------------------------------------------------------------
+
+test('grant — throws browser_only PermissionError in Node.js', async () => {
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ // typeof window === 'undefined' in Node — should throw immediately without fetch
+ await assert.rejects(
+ () =>
+ client.grant({
+ agentId: 'ag',
+ chainId: 84532,
+ preset: { token: '0x', maxAmount: '1', period: 'once', targets: [], expiryDays: 7 },
+ delegate: '0xDelegate',
+ signer: {},
+ }),
+ (err) => {
+ assert.ok(err instanceof PermissionError, 'should be PermissionError');
+ assert.equal(err.code, 'browser_only');
+ return true;
+ },
+ );
+});
+
+// ---------------------------------------------------------------------------
+// revoke — browser-only guard
+// ---------------------------------------------------------------------------
+
+test('revoke — throws browser_only PermissionError in Node.js', async () => {
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await assert.rejects(
+ () => client.revoke({ id: 'del-1', delegationHash: '0xhash', signer: {} }),
+ (err) => {
+ assert.ok(err instanceof PermissionError);
+ assert.equal(err.code, 'browser_only');
+ return true;
+ },
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Error surface — server errors become PermissionError
+// ---------------------------------------------------------------------------
+
+test('server 4xx ok:false → PermissionError with server error code', async () => {
+ mockFetch({ ok: false, error: 'delegation_not_found', message: 'No delegation found for that id' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await assert.rejects(
+ () => client.getMetadata('bad-agent'),
+ (err) => {
+ assert.ok(err instanceof PermissionError, `expected PermissionError, got ${err.constructor.name}`);
+ assert.equal(err.code, 'delegation_not_found');
+ assert.equal(err.message, 'No delegation found for that id');
+ return true;
+ },
+ );
+});
+
+test('403-style ok:false error uses error code when no message', async () => {
+ mockFetch({ ok: false, error: 'delegation_revoked' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await assert.rejects(
+ () => client.listDelegations({ agentId: 'x' }),
+ (err) => {
+ assert.ok(err instanceof PermissionError);
+ assert.equal(err.code, 'delegation_revoked');
+ return true;
+ },
+ );
+});
+
+test('rate_limited error code is preserved', async () => {
+ mockFetch({ ok: false, error: 'rate_limited', message: 'Too many requests' });
+ const client = new PermissionsClient({ baseUrl: 'https://example.com' });
+ await assert.rejects(
+ () => client.verify('0xhash', 84532),
+ (err) => {
+ assert.ok(err instanceof PermissionError);
+ assert.equal(err.code, 'rate_limited');
+ return true;
+ },
+ );
+});
+
+// ---------------------------------------------------------------------------
+// PermissionError shape
+// ---------------------------------------------------------------------------
+
+test('PermissionError has correct name, code, and message', () => {
+ const err = new PermissionError('scope_exceeded', 'Spend limit exceeded');
+ assert.equal(err.name, 'PermissionError');
+ assert.equal(err.code, 'scope_exceeded');
+ assert.equal(err.message, 'Spend limit exceeded');
+ assert.ok(err instanceof Error);
+});
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
index a3bc88510..10fa65a3f 100644
--- a/specs/AGENT_MANIFEST.md
+++ b/specs/AGENT_MANIFEST.md
@@ -33,8 +33,8 @@ Everything is optional except `manifest.json` and a `body` reference.
```jsonc
{
- "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",
- "spec": "agent-manifest/0.1",
+ "$schema": "https://3d-agent.io/schemas/manifest/0.2.json",
+ "spec": "agent-manifest/0.2",
// Identity — filled in after on-chain registration
"id": {
@@ -151,7 +151,9 @@ Skills load lazily. The `<agent-3d>` element emits `skill:loaded` events as each
Built-in scene-tools available without any skill installed. Additional tools come from skills' `tools.json`. Tool names are merged; skill tools override built-ins if names collide (with a console warning).
-## Worked example: Coach Leo
+## Worked examples
+
+### Coach Leo (v0.1 — no on-chain permissions)
```json
{
@@ -213,6 +215,67 @@ Reference what you remember from prior sessions (from memory/) naturally.
Never break character.
```
+### Coach Leo (v0.2 — with on-chain permissions)
+
+```json
+{
+ "spec": "agent-manifest/0.2",
+ "id": {
+ "chain": "base-sepolia",
+ "registry": "0xAbC...123",
+ "agentId": "42",
+ "owner": "0xDeadBeef..."
+ },
+ "name": "Coach Leo",
+ "description": "Football coach. Reviews your form, cheers you on.",
+ "image": "ipfs://bafy.../poster.webp",
+ "tags": ["coach", "football", "argentina"],
+ "body": {
+ "uri": "ipfs://bafy.../cz.glb",
+ "format": "gltf-binary",
+ "rig": "mixamo",
+ "boundingBoxHeight": 1.78
+ },
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.8
+ },
+ "voice": {
+ "tts": { "provider": "browser", "rate": 1.1 },
+ "stt": { "provider": "browser", "language": "en-US" }
+ },
+ "skills": [
+ { "uri": "skills/wave/", "version": "0.1.0" },
+ { "uri": "ipfs://bafy.../football-drills/", "version": "1.0.0" }
+ ],
+ "memory": { "mode": "local", "index": "memory/MEMORY.md", "maxTokens": 8192 },
+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak"],
+ "permissions": {
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...",
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0xDeadBeef...",
+ "delegate": "0xCafeBabe...",
+ "hash": "0x...",
+ "uri": "ipfs://bafy...",
+ "scope": {
+ "token": "native",
+ "maxAmount": "1000000000000000000",
+ "period": "daily",
+ "targets": ["0xDef1...1234"],
+ "expiry": 1775250000
+ }
+ }
+ ]
+ },
+ "version": "0.2.0"
+}
+```
+
## Resolution flow
```
@@ -246,6 +309,88 @@ Never break character.
- Manifest version: semver, author-controlled.
- Forward-compat: unknown fields are preserved on read + write (JSON pass-through), so newer runtimes can ignore older fields and older runtimes won't corrupt newer manifests.
+## `permissions` (optional, v0.2+)
+
+An agent registered on-chain under an ERC-8004 identity can be granted **scoped, time-bound, revocable permissions** via ERC-7710 delegations. These permissions allow the agent to execute transactions on behalf of its owner without requiring the owner to sign each transaction individually. The `permissions` field embeds signed delegation envelopes in the manifest, enabling hosts (Claude artifacts, LobeHub plugins, embed iframes) to execute on-chain actions without contacting a server. See [PERMISSIONS_SPEC.md](./PERMISSIONS_SPEC.md) for the full trust model, API surface, and redemption flow.
+
+### Canonical shape
+
+```jsonc
+"permissions": {
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...", // DelegationManager address on the target chain
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0x...", // EIP-55 checksummed
+ "delegate": "0x...", // EIP-55 checksummed agent account
+ "hash": "0x...", // delegation envelope keccak256
+ "uri": "ipfs://bafy...", // pinned envelope (or inline under "envelope")
+ "scope": {
+ "token": "0x...", // ERC-20 address, or "native"
+ "maxAmount": "10000000", // base units, string
+ "period": "daily", // daily|weekly|once
+ "targets": ["0x..."], // allow-listed contracts
+ "expiry": 1775250000 // unix seconds
+ }
+ }
+ ]
+}
+```
+
+### Field reference
+
+| Field | Type | Required? | Example | Constraints |
+| ------------------- | ---------- | --------- | ---------------------------- | -------------------------------------------------------------- |
+| `spec` | `string` | Yes | `"erc-7715/0.1"` | Delegation format version; clients must check |
+| `delegationManager` | `string` | Yes | `"0xAbC123..."` | EIP-55 checksummed address on the target chain |
+| `delegations` | `array` | Yes | `[{...}, {...}]` | Non-empty; each item is a delegation entry |
+| `chainId` | `number` | Yes | `84532` | EVM chain ID; must match the delegation envelope |
+| `delegator` | `string` | Yes | `"0xDeadBeef..."` | EIP-55 checksummed owner wallet; signs the envelope |
+| `delegate` | `string` | Yes | `"0xCafeBabe..."` | EIP-55 checksummed agent smart account |
+| `hash` | `string` | Yes | `"0x..."` | `keccak256` of the signed delegation envelope |
+| `uri` | `string` | No\* | `"ipfs://bafy..."` | IPFS gateway, Arweave, or HTTPS; resolved per `body.uri` rules |
+| `envelope` | `object` | No\* | `{delegate, delegator, ...}` | Inline envelope for IPFS-restricted environments |
+| `scope` | `object` | Yes | `{token, maxAmount, ...}` | Scope restrictions; see PERMISSIONS_SPEC.md §3 |
+| `token` | `string` | Yes | `"native"` or `"0x..."` | ERC-20 address (checksummed) or `"native"` |
+| `maxAmount` | `string` | Yes | `"10000000"` | Non-negative integer in base units; non-zero |
+| `period` | `string` | Yes | `"daily"` | One of: `"daily"`, `"weekly"`, `"once"` |
+| `targets` | `string[]` | Yes | `["0xDef1...", "0xAbC..."]` | Non-empty; each address EIP-55 checksummed |
+| `expiry` | `number` | Yes | `1775250000` | Unix timestamp (UTC seconds); must be in the future |
+
+\* Either `uri` or `envelope` must be present. When inline `envelope` is provided, `uri` is omitted.
+
+### Resolution order
+
+Hosts resolve a delegation in this order:
+
+1. **If `envelope` is present (inline)** — use it directly. Envelope was validated at grant time; treat as equivalent to the fetched form.
+2. **Else fetch from `uri`** — resolve via IPFS gateway (with fallback), Arweave, or HTTPS, using the same resolution rules as `body.uri`.
+3. **Verify `hash` matches** — compute `keccak256(envelope)` and compare to the `hash` field. Abort if mismatch.
+4. **Verify signature on-chain** — call `DelegationManager.isDelegationDisabled(hash)` to confirm the delegation has not been revoked, and verify the envelope's EIP-712 signature against the delegator address before trusting.
+
+Verification occurs before any redemption attempt. If any step fails, do not proceed to redeem.
+
+### Backwards compatibility
+
+Manifests without the `permissions` field are valid. Hosts must treat absence as "no on-chain permissions granted". Hosts MUST NOT fall back to asking the user to sign per-transaction if the field is absent, unless the skill itself explicitly requests it. Agents without on-chain identity omit the field entirely.
+
+### Size budget
+
+Keep delegation envelopes inline (under `envelope`) only when the envelope is <8 KB. For larger envelopes, pin to IPFS and reference via `uri` to keep the manifest JSON lean. This budget accounts for envelope bloat from nested caveats or long allow-lists.
+
+## Changelog
+
+### v0.2 (2026-04-18)
+
+- Added `permissions` field (optional) to embed signed ERC-7710 delegations in the manifest, enabling scoped on-chain actions without server contact.
+- Bumped schema version from `agent-manifest/0.1` to `agent-manifest/0.2`.
+- See [PERMISSIONS_SPEC.md](./PERMISSIONS_SPEC.md) for delegation envelope format, scope vocabulary, and redemption flow.
+
+### v0.1
+
+- Initial release: body, brain, voice, skills, memory, attestations, and scene-tools.
+
## See also
- [SKILL_SPEC.md](./SKILL_SPEC.md) — skill bundle format
diff --git a/specs/EMBED_HOST_PROTOCOL.md b/specs/EMBED_HOST_PROTOCOL.md
index 8949a0f7b..50a770a7f 100644
--- a/specs/EMBED_HOST_PROTOCOL.md
+++ b/specs/EMBED_HOST_PROTOCOL.md
@@ -290,6 +290,22 @@ Messages from non-parent frames are always rejected regardless of allowlist.
---
+## Permissions messages (v0.2+)
+
+Five additional types for delegation discovery and redemption, introduced alongside `embed/0.2` of the Embed Spec. They follow the same `host.*` / `embed.*` directional naming convention as all other types in this protocol. Implementors that do not support delegations MUST silently ignore them per the versioning policy below.
+
+Full shapes and semantics are defined in [EMBED_SPEC.md § Delegations](./EMBED_SPEC.md#delegations-optional-v02).
+
+| Type | Direction | Purpose |
+| ---------------------------- | ------------ | ------------------------------------------------- |
+| `host.permissions.query` | host → embed | Request the loaded delegation list (with filter) |
+| `embed.permissions.query` | embed → host | Reply to `host.permissions.query`; carries list |
+| `host.permissions.redeem` | host → embed | Initiate a redemption on the host's behalf |
+| `embed.permissions.redeemed` | embed → host | Redemption succeeded; carries `txHash` |
+| `embed.permissions.error` | embed → host | Redemption failed; carries canonical error `code` |
+
+---
+
## Versioning policy
- `v` is an integer incremented on **breaking changes** (field renames, removed types, changed semantics).
@@ -297,6 +313,12 @@ Messages from non-parent frames are always rejected regardless of allowlist.
- Deprecated types MUST be supported for one full minor version before removal.
- Receivers MUST silently ignore unknown types (log once; do not crash; do not send `embed.error` for unknown types from a higher version).
+## Changelog
+
+### v1 (current)
+
+- Added permissions messages (`host.permissions.query`, `embed.permissions.query`, `host.permissions.redeem`, `embed.permissions.redeemed`, `embed.permissions.error`) as non-breaking additions per the versioning policy above. Shapes in [EMBED_SPEC.md § Delegations](./EMBED_SPEC.md#delegations-optional-v02).
+
---
## Security notes
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index 577645f1d..b5d5c02f6 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -1,4 +1,4 @@
-# Embed Spec v0.1 — `<agent-3d>` Web Component
+# Embed Spec v0.2 — `<agent-3d>` Web Component
> **Placeholder tag**: `<agent-3d>`. The element name is one find/replace away from whatever you choose — the spec is tag-agnostic.
@@ -344,9 +344,19 @@ All bundle responses ship `access-control-allow-origin: *` and `cross-origin-res
## Versioning
-- Element spec: `embed/0.1` — breaking changes bump minor until 1.0.
+- Element spec: `embed/0.2` — breaking changes bump minor until 1.0.
- Bundle version: tracks `package.json` `version` of the main repo. Pinning a `<MAJOR>.<MINOR>.<PATCH>` URL is the only forever-stable option — moving channels can ship security fixes that may include behavior changes within their semver range.
+## Changelog
+
+### v0.2 (2026-04-18)
+
+- Added **Delegations (optional, v0.2+)** section: delegation discovery (manifest + metadata paths), host `permissions` / `permissions-bearer` attributes, five post-message types following the `host.*` / `embed.*` naming convention (`host.permissions.query`, `embed.permissions.query`, `host.permissions.redeem`, `embed.permissions.redeemed`, `embed.permissions.error`), Claude artifact and LobeHub host profiles, and security requirements.
+
+### v0.1
+
+- Initial release: attributes, modes, slots, events, JS API, CSS custom properties, shadow DOM, accessibility, resource policy, CSP guidance, progressive enhancement, editor mode, share routes, and embed policy.
+
## Share routes (on-chain agents)
Every on-chain agent has a canonical URL triad, plus companion endpoints for previews and oEmbed.
@@ -393,8 +403,218 @@ Parent host is determined from `window.location.ancestorOrigins` (Chromium) or `
**We ship permissionless by default.** On-chain identity is public — any embedder can show any agent unless the owner has explicitly set a policy. The policy path exists so owners _can_ restrict later; it doesn't gate the default experience.
+## Delegations (optional, v0.2+)
+
+The `<agent-3d>` embed can surface and redeem ERC-7710 delegations granted to an agent. This section specifies how the embed discovers delegations, which host configurations unlock redemption, and how hosts communicate with the embed over the post-message channel.
+
+### Discovery
+
+The embed resolves delegations through two paths, tried in order:
+
+**Manifest path** — if the loaded `manifest.json` contains a `permissions.delegations[]` array (see [AGENT_MANIFEST.md](./AGENT_MANIFEST.md)), the embed uses that array directly. No additional network call is needed.
+
+**Metadata path** — if the manifest omits `permissions` (e.g. it was pinned before permissions were granted), the embed MAY call:
+
+```
+GET /api/permissions/metadata?agentId=<id>
+```
+
+to hydrate the delegation list. Hosts MUST cache the response for at least 60 s.
+
+### Host attributes
+
+Two attributes on `<agent-3d>` govern the redemption surface the host exposes:
+
+| Attribute | Type / Values | Default | Notes |
+| -------------------- | ---------------------------------------- | ---------- | --------------------------------------------------- |
+| `permissions` | `readonly` \| `interactive` \| `relayer` | `readonly` | Host's redemption stance (see below) |
+| `permissions-bearer` | opaque string | none | Bearer token; required when `permissions="relayer"` |
+
+**`permissions` values:**
+
+- **`readonly`** (default) — embed renders delegation status and scope; never initiates a redemption. Safe default for any host that has not provisioned signing capability.
+- **`interactive`** — embed may prompt the end user for a wallet signer. The host MUST expose a `host.getSigner()` method that returns an ethers-compatible signer. Requires the host to have a wallet session available.
+- **`relayer`** — embed may call `POST /api/permissions/redeem` using the bearer token in `permissions-bearer`. No wallet popup. Requires the agent owner to have provisioned a bearer token scoped to `permissions:redeem` (per task 09).
+
+**`permissions-bearer`** is an opaque string. The host is responsible for rotation; the embed never stores it beyond the current page lifetime.
+
+### Post-message protocol
+
+The five message types below extend the `EMBED_HOST_PROTOCOL` v1 envelope (`{ v: 1, type, id?, payload }`), following the same `host.*` / `embed.*` directional naming convention used throughout that protocol. Hosts and embeds that do not support delegations MUST silently ignore unknown types per the existing protocol's versioning policy.
+
+#### `host.permissions.query` (host → embed)
+
+Request the list of delegations currently loaded by the embed.
+
+```json
+{
+ "v": 1,
+ "type": "host.permissions.query",
+ "id": "pq_001",
+ "payload": {
+ "filter": {
+ "chainId": 84532,
+ "status": "active"
+ }
+ }
+}
+```
+
+| Field | Required | Notes |
+| ---------------- | -------- | ----------------------------------------------- |
+| `payload.filter` | no | Narrows results; omit to return all delegations |
+| `filter.chainId` | no | Limit to a specific chain |
+| `filter.status` | no | `"active"` \| `"expired"` \| `"revoked"` |
+
+The embed replies with `embed.permissions.query` (below), correlating via the same `id`.
+
+#### `embed.permissions.query` (embed → host)
+
+Reply to `host.permissions.query`. Carries the filtered delegation list.
+
+```json
+{
+ "v": 1,
+ "type": "embed.permissions.query",
+ "id": "pq_001",
+ "payload": {
+ "delegations": [
+ {
+ "delegationId": "uuid-...",
+ "chainId": 84532,
+ "scope": {
+ "token": "native",
+ "maxAmount": "1000000000000000000",
+ "period": "daily",
+ "expiry": 1775250000
+ },
+ "status": "active"
+ }
+ ]
+ }
+}
+```
+
+| Field | Required | Notes |
+| --------------------- | -------- | ------------------------------------------------ |
+| `id` | yes | Matches the originating `host.permissions.query` |
+| `payload.delegations` | yes | Array of public delegation views; empty if none |
+
+#### `host.permissions.redeem` (host → embed)
+
+Ask the embed to initiate a redemption. The embed resolves the signer or bearer token based on the current `permissions` attribute value.
+
+```json
+{
+ "v": 1,
+ "type": "host.permissions.redeem",
+ "id": "pr_001",
+ "payload": {
+ "delegationId": "uuid-...",
+ "calls": [{ "to": "0x...", "value": "0", "data": "0x..." }]
+ }
+}
+```
+
+| Field | Required | Notes |
+| ---------------------- | -------- | ---------------------------------------------- |
+| `payload.delegationId` | yes | UUID from the delegation list |
+| `payload.calls` | yes | Array of `{ to, value, data }` — raw EVM calls |
+
+On completion the embed posts either `embed.permissions.redeemed` or `embed.permissions.error` with the matching `id`.
+
+#### `embed.permissions.redeemed` (embed → host)
+
+Announce a successful redemption.
+
+```json
+{
+ "v": 1,
+ "type": "embed.permissions.redeemed",
+ "id": "pr_001",
+ "payload": {
+ "delegationId": "uuid-...",
+ "txHash": "0x...",
+ "chainId": 84532
+ }
+}
+```
+
+| Field | Required | Notes |
+| ---------------------- | -------- | ------------------------------------------------- |
+| `payload.delegationId` | yes | Echoed from the `host.permissions.redeem` request |
+| `payload.txHash` | yes | Confirmed transaction hash |
+| `payload.chainId` | yes | Chain the transaction landed on |
+
+#### `embed.permissions.error` (embed → host)
+
+Announce a failed redemption. `code` is one of the canonical error codes; `message` is a human-readable description.
+
+```json
+{
+ "v": 1,
+ "type": "embed.permissions.error",
+ "id": "pr_001",
+ "payload": {
+ "delegationId": "uuid-...",
+ "code": "scope_exceeded",
+ "message": "Requested value exceeds the daily allowance."
+ }
+}
+```
+
+| Field | Required | Notes |
+| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `payload.delegationId` | yes | Echoed from the `host.permissions.redeem` request |
+| `payload.code` | yes | One of: `delegation_expired`, `delegation_revoked`, `scope_exceeded`, `target_not_allowed`, `delegation_not_found`, `signature_invalid`, `chain_not_supported`, `rate_limited` |
+| `payload.message` | yes | Human-readable description for display or logging |
+
+### Claude artifact profile
+
+In a Claude.ai artifact sandbox:
+
+- **Default mode**: `permissions="readonly"`. Artifacts can render tipping UIs, display delegation scope, and show status — but the embed never initiates a redemption automatically.
+- **Relayer mode**: if a skill needs to transact, the artifact HTML must include `permissions="relayer"` and the agent owner must have provisioned a `permissions-bearer` token at embed time. The owner provisions this once via the manage panel.
+- **Interactive mode is not supported.** Claude artifact iframes have no persistent wallet session. If `permissions="interactive"` is set inside the Claude profile, the embed MUST treat it as `"readonly"` and emit a console warning.
+
+Example Claude artifact embed with relayer mode:
+
+```html
+<agent-3d
+ src="agent://base/42"
+ permissions="relayer"
+ permissions-bearer="sk_perm_abc123"
+></agent-3d>
+```
+
+### LobeHub profile
+
+LobeHub supports all three modes. LobeHub users typically have wallets configured at the platform level, so the default is `permissions="interactive"`.
+
+| Mode | Supported | Notes |
+| ------------- | --------- | ------------------------------------------------------------- |
+| `readonly` | Yes | Explicit opt-in; disables all redemption UI |
+| `interactive` | Yes | **Default on LobeHub.** Host provides `getSigner()`. |
+| `relayer` | Yes | Agent owner provisions bearer; LobeHub injects at embed time. |
+
+When `interactive`, LobeHub's wallet bridge calls `host.getSigner()` and returns the user's connected wallet signer to the embed runtime.
+
+### Security
+
+**Envelope integrity** — embeds MUST verify `delegation.hash === keccak256(delegation.envelope)` before trusting any delegation loaded from the manifest or metadata endpoint. A mismatch MUST abort processing and log a warning; do not attempt redemption.
+
+**Signature verification** — embeds MUST call `isDelegationValid({ hash, chainId })` (from `src/permissions/toolkit.js`; see [PERMISSIONS_SPEC.md](./PERMISSIONS_SPEC.md) for the full library contract) before rendering a redeem action. An invalid or revoked delegation MUST render as inactive, not redeemable.
+
+**Origin isolation** — embeds MUST NOT write delegation envelopes to any storage (`localStorage`, `sessionStorage`, `IndexedDB`, cookies) that is shared across origins. In-memory only for the current page session.
+
+**Bearer token handling** — hosts MUST NOT set `permissions="relayer"` without a valid, owner-provided `permissions-bearer` value. If the attribute is absent or empty when `permissions="relayer"` is requested, the embed MUST silently fall back to `permissions="readonly"`.
+
+> **Future work (out of scope for v0.2):** multi-delegation chaining, session key delegation, and WebAuthn-gated redemption are explicitly deferred.
+
## See also
- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md)
- [SKILL_SPEC.md](./SKILL_SPEC.md)
- [MEMORY_SPEC.md](./MEMORY_SPEC.md)
+- [PERMISSIONS_SPEC.md](./PERMISSIONS_SPEC.md)
+- [EMBED_HOST_PROTOCOL.md](./EMBED_HOST_PROTOCOL.md)
diff --git a/specs/PERMISSIONS_SPEC.md b/specs/PERMISSIONS_SPEC.md
new file mode 100644
index 000000000..cc18f5cbe
--- /dev/null
+++ b/specs/PERMISSIONS_SPEC.md
@@ -0,0 +1,191 @@
+# Permissions Spec v0.1 — ERC-7715 / ERC-7710 Advanced Permissions
+
+## 1. Overview
+
+An **advanced permission** is a scoped, time-bound, revocable on-chain delegation that authorizes an agent's smart account to execute transactions on behalf of its owner — without requiring the owner to sign each transaction individually. Agents registered under ERC-8004 identities (see `AGENT_MANIFEST.md`) need this primitive so skills running inside Claude artifacts, LobeHub plugins, or embed iframes can take on-chain actions autonomously within the limits the owner approved once.
+
+The trust model is: the user signs once (EIP-712, via MetaMask), producing a delegation envelope that encodes the full scope. Smart contracts enforce that scope on every redemption. The agent redeems at will within scope — no further user interaction required. Revocation is an on-chain write; scope plus expiry cap the blast radius of a compromised agent key.
+
+This spec covers ERC-7710 (delegation envelope format and `DelegationManager` interface) as adopted in this project, and ERC-7715 (the `wallet_grantPermissions` JSON-RPC method used to trigger MetaMask's grant UI). EIP references are inline throughout.
+
+---
+
+## 2. Delegation Envelope
+
+A delegation is an ERC-7710 struct. Fields as used in this project:
+
+| Field | Type | Description |
+| ----------- | ---------- | --------------------------------------------------------------------------- |
+| `delegate` | `address` | Agent's smart account — the party authorized to redeem |
+| `delegator` | `address` | Owner wallet — the party granting authority |
+| `authority` | `bytes32` | `0xff...ff` for a root delegation; hash of parent for chained (unused here) |
+| `caveats` | `Caveat[]` | Array of `{ enforcer, terms }` structs encoding scope restrictions |
+| `salt` | `bytes32` | Random value for replay protection (combined with `chainId`) |
+| `signature` | `bytes` | EIP-712 signature over the struct hash, produced by the delegator |
+
+The signed envelope is pinned to IPFS and stored in the database as `delegation_json` (JSONB). The keccak256 of the EIP-712 struct hash is the `delegation_hash` used as the primary identifier across DB, manifest, and API.
+
+**EIP-712 hashing.** The following fields are included in the struct hash: `delegate`, `delegator`, `authority`, `caveats` (array hash), and `salt`. The domain separator includes `chainId` and the `DelegationManager` contract address, providing chain-binding and contract-binding replay protection.
+
+Reference: [EIP-7710](https://eips.ethereum.org/EIPS/eip-7710). Implementation utilities: [MetaMask Delegation Toolkit](https://docs.metamask.io/delegation-toolkit/) (`@metamask/delegation-toolkit` — verify exact package name and contract addresses in those docs before use).
+
+---
+
+## 3. Scope Vocabulary
+
+Scope is encoded as caveats on the delegation envelope. For off-chain indexing and manifest embedding, scope is also stored as a `scope` JSON object (`{ token, maxAmount, targets[], expiry, period }`). The table below covers all valid scope keys:
+
+| Key | Type | Range / Constraints | Caveat mapping | Example |
+| ----------- | ----------------- | ------------------------------------------------------- | ------------------------------------- | ------------------------------- |
+| `token` | `string` | ERC-20 address (EIP-55 checksummed) or `"native"` | ERC-20 allowance caveat | `"0xA0b8...eB48"` or `"native"` |
+| `maxAmount` | `string` | Non-negative integer in base units; `"0"` is disallowed | ERC-20 allowance caveat (spend limit) | `"10000000"` (10 USDC, 6 dec) |
+| `period` | `string` | `"daily"` \| `"weekly"` \| `"once"` | Period caveat (resets allowance) | `"daily"` |
+| `targets` | `string[]` | Non-empty; each entry EIP-55 checksummed address | Target allow-list caveat | `["0xDef1...1234"]` |
+| `expiry` | `number` | Unix seconds (UTC); must be in the future at grant time | Expiry caveat | `1775250000` |
+| `selectors` | `string[]` (opt.) | 4-byte hex selectors; if omitted, all selectors allowed | Selector allow-list caveat (optional) | `["0xa9059cbb"]` |
+
+**Caveat mapping detail:**
+
+- **ERC-20 allowance caveat** — enforcer checks that the total spend in `calls` does not exceed `maxAmount` for the given `token`. Paired with the period caveat to reset per cycle.
+- **Target allow-list caveat** — enforcer rejects any call whose `to` address is not in `targets`.
+- **Period caveat** — enforcer tracks cumulative spend within the current period window; resets the counter at the start of each new window.
+- **Expiry caveat** — enforcer calls `block.timestamp <= expiry`; reverts if past.
+- **Selector caveat** (optional) — enforcer rejects any call whose `data[:4]` is not in `selectors`.
+
+`selectors` is not in the current canonical `scope` JSON shape (see §4). It is noted here for completeness; treat as forward-reserved until the shape is updated.
+
+---
+
+## 4. Manifest Integration
+
+The `permissions` field on `manifest.json` (ERC-7715 / `spec: "erc-7715/0.1"`):
+
+```jsonc
+"permissions": {
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...", // DelegationManager address on the target chain
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0x...", // EIP-55 checksummed
+ "delegate": "0x...", // EIP-55 checksummed agent account
+ "hash": "0x...", // delegation envelope keccak256
+ "uri": "ipfs://bafy...", // pinned envelope (or inline under "envelope")
+ "scope": {
+ "token": "0x...", // ERC-20 address, or "native"
+ "maxAmount": "10000000", // base units, string
+ "period": "daily", // daily|weekly|once
+ "targets": ["0x..."], // allow-listed contracts
+ "expiry": 1775250000 // unix seconds
+ }
+ }
+ ]
+}
+```
+
+`uri` resolves to the full signed ERC-7710 delegation envelope, pinned on IPFS. The runtime fetches this to obtain the raw envelope before calling `DelegationManager.redeemDelegations(...)`.
+
+For embed contexts where IPFS is not reachable (restricted CSP, offline, iframe sandboxed without external network), `uri` may be omitted and the envelope included inline under `"envelope"` (same shape as the IPFS-pinned JSON). The inline form is validated at grant time; runtimes treat it as equivalent to the fetched form.
+
+---
+
+## 5. API Surface
+
+All endpoints are under `/api/permissions/`. Auth, CORS, error shape, and rate-limit conventions follow [api/CLAUDE.md](../api/CLAUDE.md).
+
+| Method | Path | Body / Query | Response |
+| ------ | --------------------------- | ------------------------------------------------------------- | ------------------------------------ |
+| POST | `/api/permissions/grant` | `{ agentId, chainId, delegation, scope }` | `{ ok, id, delegationHash }` |
+| GET | `/api/permissions/list` | `?agentId=X` or `?delegator=0x...` | `{ ok, delegations: [...] }` |
+| POST | `/api/permissions/revoke` | `{ id, txHash }` | `{ ok, status: 'revoked' }` |
+| POST | `/api/permissions/redeem` | `{ id, calls: [{to,value,data}] }` (auth: agent bearer token) | `{ ok, txHash, receipt }` |
+| GET | `/api/permissions/metadata` | `?agentId=X` (public, cached) | `{ ok, delegations: [public view] }` |
+| GET | `/api/permissions/verify` | `?hash=0x...&chainId=N` | `{ ok, valid, reason? }` |
+
+All responses follow `{ ok: true, ... }` on success and `{ ok: false, error: '<code>', message: '...' }` on failure, where `error` is one of the canonical codes in §8.
+
+---
+
+## 6. Redemption Flow
+
+Redemption is the path from a skill requesting an on-chain action to a confirmed transaction.
+
+1. **Skill calls `redeemFromSkill`** (`src/runtime/delegation-redeem.js`) with `{ agentId, chainId, calls, skillId }`. The caller is the agent's runtime; no user interaction at this step.
+2. **Runtime loads the active delegation** via `getActiveDelegation({ agentId, chainId })` — queries the DB for `status = 'active'` and `expires_at > NOW()`. Returns `null` if none found, surfacing `delegation_not_found`.
+3. **Runtime verifies scope** — checks that each call in `calls` targets an address in `scope.targets`, that the aggregate value does not exceed `maxAmount` for the period, and that `expiry` has not passed. Returns `scope_exceeded` or `target_not_allowed` without touching the chain.
+4. **Runtime builds the `redeemDelegations(...)` calldata** using the ABI from `src/erc7710/abi.js`. Input: the full signed delegation envelope (fetched from `delegation_json`) plus the `calls` array.
+5. **Runtime submits via relayer or the agent's smart account**. If the agent has a server-side signing key (task 09 trust boundary), the runtime signs and broadcasts directly. Otherwise, the call is sent to a relayer endpoint. This step requires: the delegation envelope, the agent's signing key (or relayer credentials), and the target chain RPC.
+6. **Transaction lands on-chain.** The `DelegationManager` contract enforces all caveats; if any caveat reverts, the transaction reverts and the error propagates back as `scope_exceeded`.
+7. **Runtime returns `{ ok, txHash, receipt }`** to the skill. The DB record is updated: `last_redeemed_at = NOW()`, `redemption_count++`.
+
+---
+
+## 7. Revocation
+
+**On-chain.** The owner calls `DelegationManager.disableDelegation(delegationHash)` (ERC-7710 interface). This is the authoritative revocation; once the transaction is confirmed, no further redemptions succeed.
+
+**Off-chain mirror.** The indexer cron (task 19) polls `DelegationManager` for `DelegationDisabled` events and updates `agent_delegations.status = 'revoked'`, `revoked_at = NOW()`, `tx_hash_revoke = <txHash>` in the DB. Until the indexer processes the event, the DB may still show `active` — this is the race window.
+
+**Race condition.** A redemption submitted before the revoke transaction confirms, but processed concurrently, may succeed on-chain. The on-chain caveats remain the authority: if the revoke confirms first, the redemption reverts. If the redemption confirms first, it is valid. There is no off-chain mechanism to prevent this window — operators should treat `scope + expiry` as the primary blast-radius control, not the race-free revocation guarantee.
+
+**Verify endpoint.** `GET /api/permissions/verify?hash=0x...&chainId=N` performs a real-time on-chain read (`DelegationManager.isDelegationDisabled(hash)`) before returning `{ valid }`, giving callers a fresh view independent of the indexer lag.
+
+---
+
+## 8. Error Codes
+
+All codes are strings, OAuth-style. Returned as `error` in `{ ok: false, error: '<code>', message: '...' }`.
+
+| Code | When returned | Client recovery |
+| ---------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- |
+| `delegation_expired` | `expiry` timestamp has passed at time of redemption or verify | Prompt user to grant a new delegation |
+| `delegation_revoked` | DB status is `revoked`, or on-chain `disableDelegation` confirmed | Prompt user to grant a new delegation |
+| `scope_exceeded` | Requested calls exceed `maxAmount` or period allowance | Reduce call value, or prompt user to update scope |
+| `target_not_allowed` | A `calls[].to` address is not in `scope.targets` | Restrict calls to allowed targets, or prompt scope update |
+| `delegation_not_found` | No active delegation found for `agentId` + `chainId` | Prompt user to grant permissions |
+| `signature_invalid` | EIP-712 signature verification fails on grant or verify | Reject the envelope; prompt user to re-sign |
+| `chain_not_supported` | `chainId` is not in `DELEGATION_MANAGER_DEPLOYMENTS` | Inform user; only Base Sepolia and Sepolia are supported |
+| `rate_limited` | Request rate exceeds per-agent or per-IP limit | Back off and retry with exponential delay |
+
+---
+
+## 9. Versioning
+
+This spec is `permissions/0.1`. Version is advertised in two places:
+
+- **Manifest**: `"permissions": { "spec": "erc-7715/0.1", ... }` — the `spec` string is the delegation format version, not the permissions spec version. These are currently aligned but may diverge if the delegation format changes independently of this spec.
+- **Agent manifest**: agents that support advanced permissions must include the `permissions` field in their `manifest.json`. Agents without this field are treated as having no delegations.
+
+Any breaking change to the canonical shapes in §4 or the API surface in §5 bumps the minor version (e.g., `permissions/0.2`). Non-breaking additions (new optional scope keys, new optional response fields) do not require a bump. The `spec` field in the manifest entry is the version agents and runtimes negotiate on.
+
+SDK consumers and embed hosts that read the `permissions` field must check `spec` and reject or warn on unknown versions rather than silently misinterpreting fields.
+
+---
+
+## 10. Security Considerations
+
+**Replay protection.** Each delegation envelope includes a `salt` (random `bytes32`) and the domain separator encodes `chainId` and the `DelegationManager` address. A signed envelope from chain A cannot be replayed on chain B, and a reused salt with the same parameters cannot produce a second valid delegation (the `DelegationManager` tracks disabled delegation hashes).
+
+**Phishing — scope shown in English before approval.** The grant modal (task 10) translates the `scope` object into a human-readable summary (e.g., "Up to 10 USDC per day, to 0xDef1...1234, expiring 2026-07-01") before `wallet_grantPermissions` (EIP-7715) opens the MetaMask prompt. This ensures the user sees the scope in a trusted application context before MetaMask shows the raw EIP-712 data. Never skip this pre-display step.
+
+**Compromised agent key.** If an agent's signing key is exposed, the attacker is limited to: the `targets` in the allow-list, the `maxAmount` per period, and the time window before `expiry`. Set `expiry` to the minimum useful duration. The `revoke` path lets the owner cut off access immediately.
+
+**Relayer trust.** When `POST /api/permissions/redeem` is used instead of direct on-chain submission, the relayer sees the raw calls before broadcasting. The relayer is trusted infrastructure — treat it with the same threat model as the agent's signing key. Scope is still enforced on-chain by the `DelegationManager` even if the relayer is compromised; the attacker cannot exceed the signed caveats. However, a compromised relayer can censor redemptions or front-run them.
+
+**No mainnet defaults.** Contract addresses in `DELEGATION_MANAGER_DEPLOYMENTS` must not include mainnet as a default. Base Sepolia (`84532`) and Sepolia are the supported chains. Mainnet support requires explicit opt-in through the agent owner's settings UI.
+
+**No mock signatures.** All delegations must be real EIP-712 signatures verifiable on-chain. The `signature_invalid` error code is returned for any envelope that fails verification; never store or redeem an unverified envelope.
+
+**No custodial delegator keys.** The delegator (owner) wallet key is never held server-side. The agent's smart account key may be held server-side only as defined in task 09's trust boundary documentation.
+
+---
+
+## See Also
+
+- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md) — manifest format; `permissions` field context
+- [EMBED_SPEC.md](./EMBED_SPEC.md) — embed host context; inline envelope for IPFS-restricted environments
+- [SKILL_SPEC.md](./SKILL_SPEC.md) — skill handler context; `redeemFromSkill` caller
+- [api/CLAUDE.md](../api/CLAUDE.md) — shared API conventions (auth, CORS, rate limits, error shape)
+- [EIP-7710](https://eips.ethereum.org/EIPS/eip-7710) — delegation envelope format and `DelegationManager` interface
+- [EIP-7715](https://eips.ethereum.org/EIPS/eip-7715) — `wallet_grantPermissions` JSON-RPC method
+- [MetaMask Delegation Toolkit](https://docs.metamask.io/delegation-toolkit/) — `@metamask/delegation-toolkit` package
diff --git a/specs/schema/README.md b/specs/schema/README.md
new file mode 100644
index 000000000..13f010874
--- /dev/null
+++ b/specs/schema/README.md
@@ -0,0 +1,31 @@
+# specs/schema — table documentation
+
+## agent_delegations
+
+Stores ERC-7710 signed delegation envelopes. Spec: `permissions/0.1`.
+
+| Column | Type | Description |
+|---|---|---|
+| `id` | UUID | Primary key, generated by `gen_random_uuid()`. |
+| `agent_id` | UUID | Foreign key to `agent_identities(id)`; cascades on agent delete. |
+| `chain_id` | INTEGER | EVM chain ID (must be > 0). |
+| `delegator_address` | TEXT | EIP-55 checksummed user wallet address (42 chars, `0x`-prefixed). |
+| `delegate_address` | TEXT | EIP-55 checksummed agent smart-account address (42 chars, `0x`-prefixed). |
+| `delegation_hash` | TEXT | keccak256 of the delegation envelope; unique across all rows. |
+| `delegation_json` | JSONB | Full signed ERC-7710 delegation envelope as returned by MetaMask. |
+| `scope` | JSONB | Permission scope: `{ token, maxAmount, targets[], expiry, period }`. |
+| `status` | TEXT | Lifecycle state: `active`, `revoked`, or `expired`. Default `active`. |
+| `expires_at` | TIMESTAMPTZ | Wall-clock expiry of the delegation (from the signed scope). |
+| `created_at` | TIMESTAMPTZ | Row creation time; set to `NOW()` on insert. |
+| `revoked_at` | TIMESTAMPTZ | Timestamp of on-chain revocation; NULL while active. |
+| `tx_hash_revoke` | TEXT | Transaction hash of the `disableDelegation` call; NULL until revoked. |
+| `last_redeemed_at` | TIMESTAMPTZ | Timestamp of most recent successful redemption; updated by task-09 redeem endpoint. |
+| `redemption_count` | INTEGER | Running count of successful redemptions; updated by task-09 redeem endpoint. Default 0. |
+
+### Indexes
+
+| Index | Covers |
+|---|---|
+| `idx_delegations_agent` | Lookups by `agent_id` (list + redeem flows). |
+| `idx_delegations_status` | Partial index on `status = 'active'` (active-delegation queries). |
+| `idx_delegations_delegator` | Lookups by `delegator_address` (user manage panel). |
diff --git a/specs/schema/agent_delegations.sql b/specs/schema/agent_delegations.sql
new file mode 100644
index 000000000..ed4c6c33f
--- /dev/null
+++ b/specs/schema/agent_delegations.sql
@@ -0,0 +1,62 @@
+-- spec: permissions/0.1 task: 05-db-schema
+-- agent_delegations — stores ERC-7710 signed delegation envelopes.
+-- Idempotent: safe to re-run against a database that already has this table.
+--
+-- redemption_count and last_redeemed_at are updated by the redeem endpoint
+-- (task 09) via UPDATE on each successful on-chain redemption. No DB trigger
+-- is needed — the redeem handler owns that write path exclusively.
+
+CREATE TABLE IF NOT EXISTS agent_delegations (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ chain_id INTEGER NOT NULL,
+ delegator_address TEXT NOT NULL, -- EIP-55 checksummed user wallet
+ delegate_address TEXT NOT NULL, -- EIP-55 checksummed agent smart account
+ delegation_hash TEXT NOT NULL UNIQUE, -- keccak256 of the delegation envelope
+ delegation_json JSONB NOT NULL, -- full signed ERC-7710 delegation envelope
+ scope JSONB NOT NULL, -- { token, maxAmount, targets[], expiry, period }
+ status TEXT NOT NULL DEFAULT 'active',
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ revoked_at TIMESTAMPTZ,
+ tx_hash_revoke TEXT,
+ last_redeemed_at TIMESTAMPTZ,
+ redemption_count INTEGER NOT NULL DEFAULT 0,
+
+ CONSTRAINT agent_delegations_status_check
+ CHECK (status IN ('active', 'revoked', 'expired')),
+ CONSTRAINT agent_delegations_chain_id_check
+ CHECK (chain_id > 0),
+ CONSTRAINT agent_delegations_delegator_address_check
+ CHECK (LENGTH(delegator_address) = 42 AND delegator_address LIKE '0x%'),
+ CONSTRAINT agent_delegations_delegate_address_check
+ CHECK (LENGTH(delegate_address) = 42 AND delegate_address LIKE '0x%')
+);
+
+-- Idempotent index creation via DO blocks.
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_delegations' AND indexname = 'idx_delegations_agent'
+ ) THEN
+ CREATE INDEX idx_delegations_agent ON agent_delegations(agent_id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_delegations' AND indexname = 'idx_delegations_status'
+ ) THEN
+ CREATE INDEX idx_delegations_status ON agent_delegations(status) WHERE status = 'active';
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_delegations' AND indexname = 'idx_delegations_delegator'
+ ) THEN
+ CREATE INDEX idx_delegations_delegator ON agent_delegations(delegator_address);
+ END IF;
+END $$;
diff --git a/specs/schema/agent_subscriptions.sql b/specs/schema/agent_subscriptions.sql
new file mode 100644
index 000000000..65b38b9c4
--- /dev/null
+++ b/specs/schema/agent_subscriptions.sql
@@ -0,0 +1,60 @@
+-- spec: permissions/0.1 task: 15-skill-subscription
+-- agent_subscriptions — recurring on-chain payment schedule backed by an ERC-7710 delegation.
+-- Idempotent: safe to re-run against a database that already has this table.
+--
+-- The cron at api/cron/run-subscriptions selects rows WHERE status='active' AND
+-- next_charge_at <= NOW(), fires onPeriod, then advances next_charge_at by
+-- period_seconds. On failure it sets status='paused' + last_error.
+--
+-- Cancellation (DELETE /api/subscriptions) sets status='canceled' but does NOT
+-- revoke the underlying delegation — revocation is a separate user action.
+
+CREATE TABLE IF NOT EXISTS agent_subscriptions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ delegation_id UUID NOT NULL REFERENCES agent_delegations(id) ON DELETE CASCADE,
+ period_seconds INTEGER NOT NULL,
+ amount_per_period TEXT NOT NULL, -- base units, string (≤ delegation scope.maxAmount)
+ next_charge_at TIMESTAMPTZ NOT NULL,
+ last_charge_at TIMESTAMPTZ,
+ status TEXT NOT NULL DEFAULT 'active',
+ last_error TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ canceled_at TIMESTAMPTZ,
+
+ CONSTRAINT agent_subscriptions_status_check
+ CHECK (status IN ('active', 'canceled', 'paused')),
+ CONSTRAINT agent_subscriptions_period_seconds_check
+ CHECK (period_seconds > 0)
+);
+
+-- Partial index for the cron hot path: only active rows ordered by charge time.
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_subscriptions' AND indexname = 'idx_subscriptions_due'
+ ) THEN
+ CREATE INDEX idx_subscriptions_due
+ ON agent_subscriptions(next_charge_at)
+ WHERE status = 'active';
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_subscriptions' AND indexname = 'idx_subscriptions_user'
+ ) THEN
+ CREATE INDEX idx_subscriptions_user ON agent_subscriptions(user_id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'agent_subscriptions' AND indexname = 'idx_subscriptions_agent'
+ ) THEN
+ CREATE INDEX idx_subscriptions_agent ON agent_subscriptions(agent_id);
+ END IF;
+END $$;
diff --git a/specs/schema/dca_strategies.sql b/specs/schema/dca_strategies.sql
new file mode 100644
index 000000000..467b7500f
--- /dev/null
+++ b/specs/schema/dca_strategies.sql
@@ -0,0 +1,79 @@
+-- spec: dca/0.1 task: 16-dca-skill
+-- dca_strategies — one row per owner-configured DCA schedule.
+-- dca_executions — one row per cron-triggered swap attempt.
+
+CREATE TABLE IF NOT EXISTS dca_strategies (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL,
+ delegation_id UUID NOT NULL, -- FK into agent_delegations.id
+ chain_id INTEGER NOT NULL DEFAULT 84532,
+ token_in TEXT NOT NULL, -- USDC contract address
+ token_out TEXT NOT NULL, -- WETH (or other whitelisted) address
+ token_out_symbol TEXT NOT NULL DEFAULT 'WETH',
+ amount_per_execution TEXT NOT NULL, -- uint256 in token_in decimals
+ period_seconds INTEGER NOT NULL, -- 86400=daily, 604800=weekly
+ slippage_bps INTEGER NOT NULL DEFAULT 50,
+ status TEXT NOT NULL DEFAULT 'active',
+ next_execution_at TIMESTAMPTZ NOT NULL,
+ last_execution_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ cancelled_at TIMESTAMPTZ,
+
+ CONSTRAINT dca_strategies_status_check
+ CHECK (status IN ('active', 'paused', 'expired', 'cancelled')),
+ CONSTRAINT dca_strategies_chain_id_check
+ CHECK (chain_id > 0),
+ CONSTRAINT dca_strategies_slippage_check
+ CHECK (slippage_bps BETWEEN 1 AND 500),
+ CONSTRAINT dca_strategies_period_check
+ CHECK (period_seconds IN (86400, 604800))
+);
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'dca_strategies' AND indexname = 'idx_dca_strategies_agent'
+ ) THEN
+ CREATE INDEX idx_dca_strategies_agent ON dca_strategies(agent_id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'dca_strategies' AND indexname = 'idx_dca_strategies_next_exec'
+ ) THEN
+ CREATE INDEX idx_dca_strategies_next_exec
+ ON dca_strategies(next_execution_at)
+ WHERE status = 'active';
+ END IF;
+END $$;
+
+-- ── dca_executions ────────────────────────────────────────────────────────────
+
+CREATE TABLE IF NOT EXISTS dca_executions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ strategy_id UUID NOT NULL REFERENCES dca_strategies(id) ON DELETE CASCADE,
+ chain_id INTEGER NOT NULL,
+ tx_hash TEXT,
+ amount_in TEXT NOT NULL, -- actual USDC spent (wei)
+ quote_amount_out TEXT, -- QuoterV2 estimate (wei)
+ amount_out TEXT, -- actual WETH received (wei)
+ slippage_bps_used INTEGER,
+ quote_divergence_bps INTEGER, -- abs((q2-q1)/q1 * 10000)
+ status TEXT NOT NULL DEFAULT 'pending',
+ error TEXT,
+ executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT dca_executions_status_check
+ CHECK (status IN ('pending', 'success', 'failed', 'aborted'))
+);
+
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_indexes
+ WHERE tablename = 'dca_executions' AND indexname = 'idx_dca_executions_strategy'
+ ) THEN
+ CREATE INDEX idx_dca_executions_strategy ON dca_executions(strategy_id);
+ END IF;
+END $$;
diff --git a/specs/schema/indexer_state.sql b/specs/schema/indexer_state.sql
new file mode 100644
index 000000000..4604e8a47
--- /dev/null
+++ b/specs/schema/indexer_state.sql
@@ -0,0 +1,14 @@
+-- spec: permissions/0.1 task: 19-indexer-cron
+-- indexer_state — cursor table for the delegation event indexer cron.
+-- Keyed by (contract, chain_id). last_indexed_block advances after each
+-- successfully processed batch so a timeout preserves partial progress.
+-- Idempotent: safe to re-run.
+
+CREATE TABLE IF NOT EXISTS indexer_state (
+ id SERIAL PRIMARY KEY,
+ contract TEXT NOT NULL,
+ chain_id INTEGER NOT NULL,
+ last_indexed_block BIGINT NOT NULL DEFAULT 0,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (contract, chain_id)
+);
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index 4e3535e3f..64f44612e 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -22,6 +22,9 @@ export const ACTION_TYPES = {
LOAD_END: 'load-end', // model/asset loading finished
VALIDATE: 'validate', // validation result (errors, warnings, hints)
PRESENCE: 'presence', // agent came online / went idle
+ PERMISSIONS_REDEEM_START: 'permissions.redeem.start',
+ PERMISSIONS_REDEEM_SUCCESS: 'permissions.redeem.success',
+ PERMISSIONS_REDEEM_ERROR: 'permissions.redeem.error',
};
/**
diff --git a/src/create.js b/src/create.js
index 45d01fe0b..126c57424 100644
--- a/src/create.js
+++ b/src/create.js
@@ -1,16 +1,14 @@
-import { apiFetch, getMe, saveRemoteGlbToAccount } from './account.js';
+import { apiFetch, saveRemoteGlbToAccount } from './account.js';
import { AvatarCreator } from './avatar-creator.js';
// GLB magic bytes: ASCII "glTF"
const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];
-async function boot() {
- const user = await getMe();
- if (!user) {
- window.location.href = '/login?next=/create';
- return;
- }
+function redirectToLogin() {
+ window.location.href = '/login?next=' + encodeURIComponent('/create');
+}
+async function boot() {
const creator = new AvatarCreator(document.body, (blob) =>
saveAndRedirect(blob, { source: 'avaturn' }),
);
@@ -73,6 +71,10 @@ async function saveAndRedirect(blob, meta = {}) {
const agent = await attachAvatarToAgent(avatar.id, meta.name);
window.location.href = '/agent/' + agent.id;
} catch (err) {
+ if (err.code === 'not_signed_in') {
+ redirectToLogin();
+ return;
+ }
if (!err.redirected) showStatus(err.message || 'Upload failed.', 'error');
}
}
diff --git a/src/erc7710/README.md b/src/erc7710/README.md
new file mode 100644
index 000000000..aefe0ec92
--- /dev/null
+++ b/src/erc7710/README.md
@@ -0,0 +1,55 @@
+# src/erc7710 — ERC-7710 DelegationManager constants & pure encoders
+
+## What this module is
+
+Constants and pure ABI-encoding helpers for the MetaMask DelegationManager contract
+(ERC-7710). It is the single source of truth for contract addresses and ABI fragments
+used across the permissions subsystem.
+
+All addresses are sourced from `@metamask/delegation-deployments` v1.2.0 (DEPLOYMENTS_1_3_0),
+verified 2026-04-18. All supported chains share the same CREATE2 addresses.
+
+## Exports
+
+| Export | Description |
+| ----------------------------------------------- | ---------------------------------------------------------- |
+| `DELEGATION_MANAGER_DEPLOYMENTS` | `{ chainId: address }` map for DelegationManager |
+| `DELEGATION_MANAGER_ABI` | ethers v6 human-readable ABI strings |
+| `CAVEAT_ENFORCERS` | `{ enforcerName: { chainId: address } }` map |
+| `EIP712_DOMAIN({ chainId, verifyingContract })` | Returns EIP-712 domain separator fields |
+| `DELEGATION_TYPES` | EIP-712 `types` object for `Delegation` + `Caveat` |
+| `encodeCaveats(caveats)` | ABI-encodes `{ enforcer, terms, args }[]` for on-chain use |
+
+## What is NOT in this module
+
+- **No signing** — `signTypedData` and wallet interaction live in `src/permissions/toolkit.js`.
+- **No RPC calls** — no `eth_call`, `eth_getCode`, or provider logic here.
+- **No redemption logic** — `redeemDelegations` call construction is in `src/permissions/toolkit.js`.
+- **No UI** — grant/manage modals are in `src/permissions/`.
+
+## How `src/permissions/toolkit.js` consumes this module
+
+```js
+import {
+ DELEGATION_MANAGER_DEPLOYMENTS,
+ DELEGATION_MANAGER_ABI,
+ EIP712_DOMAIN,
+ DELEGATION_TYPES,
+ encodeCaveats,
+} from '../erc7710/abi.js';
+
+// Get the DelegationManager address for the active chain
+const managerAddress = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
+
+// Build an ethers Contract instance
+const manager = new ethers.Contract(managerAddress, DELEGATION_MANAGER_ABI, signer);
+
+// Sign a delegation
+const domain = EIP712_DOMAIN({ chainId, verifyingContract: managerAddress });
+const sig = await signer.signTypedData(domain, DELEGATION_TYPES, delegationObject);
+
+// Encode caveats before constructing the delegation struct
+const encodedCaveats = encodeCaveats([
+ { enforcer: CAVEAT_ENFORCERS.TimestampEnforcer[chainId], terms: '0x...', args: '0x' },
+]);
+```
diff --git a/src/erc7710/abi.js b/src/erc7710/abi.js
new file mode 100644
index 000000000..e9561267b
--- /dev/null
+++ b/src/erc7710/abi.js
@@ -0,0 +1,155 @@
+/**
+ * ERC-7710 DelegationManager ABIs and canonical deployments.
+ *
+ * Addresses sourced from @metamask/delegation-deployments v1.2.0 (DEPLOYMENTS_1_3_0).
+ * ABI verified against @metamask/delegation-abis v1.0.0 DelegationManager.cjs.
+ * No mainnet defaults per project policy.
+ *
+ * Only constants and pure encoders live here — no signing, no RPC calls.
+ * See src/permissions/toolkit.js for signing + redemption logic.
+ */
+
+import { AbiCoder } from 'ethers';
+
+// DelegationManager deployment addresses, keyed by numeric chainId.
+// All supported chains use the same address (CREATE2 deterministic, DEPLOYMENTS_1_3_0).
+// Source: @metamask/delegation-deployments v1.2.0, fetched 2026-04-18.
+export const DELEGATION_MANAGER_DEPLOYMENTS = {
+ // Mainnets
+ 1: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Ethereum mainnet
+ 8453: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Base mainnet
+ // Testnets
+ 84532: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Base Sepolia
+ 11155111: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Sepolia
+ 421614: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Arbitrum Sepolia
+ 11155420: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3', // Optimism Sepolia
+};
+
+// Human-readable ethers v6 ABI strings for DelegationManager.
+// Verified against @metamask/delegation-abis v1.0.0.
+export const DELEGATION_MANAGER_ABI = [
+ // Redeem one or more delegations to execute calls
+ 'function redeemDelegations(bytes[] _permissionContexts, bytes32[] _modes, bytes[] _executionCallDatas) external',
+
+ // Disable (revoke) a delegation — caller must be the delegator
+ 'function disableDelegation(tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) _delegation) external',
+
+ // Public mapping: true if the delegation hash has been disabled on-chain
+ // (on-chain name is disabledDelegations; isDelegationDisabled in task spec maps here)
+ 'function disabledDelegations(bytes32 delegationHash) external view returns (bool isDisabled)',
+
+ // Returns the keccak256 hash for a delegation (used for revoke checks and signing)
+ 'function getDelegationHash(tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) _input) external pure returns (bytes32)',
+
+ // --- Events ---
+ 'event RedeemedDelegation(address indexed rootDelegator, address indexed redeemer, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',
+ 'event DisabledDelegation(bytes32 indexed delegationHash, address indexed delegator, address indexed delegate, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',
+ 'event EnabledDelegation(bytes32 indexed delegationHash, address indexed delegator, address indexed delegate, tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature) delegation)',
+];
+
+// Caveat enforcer addresses per chain — enforcer name → { chainId: address }.
+// Addresses are identical on all supported chains (CREATE2 deterministic, DEPLOYMENTS_1_3_0).
+// Source: @metamask/delegation-deployments v1.2.0, fetched 2026-04-18.
+const _CHAINS = [1, 8453, 11155111, 84532, 421614, 11155420];
+const _addr = (a) => Object.fromEntries(_CHAINS.map((id) => [id, a]));
+export const CAVEAT_ENFORCERS = {
+ AllowedCalldataEnforcer: _addr('0xc2b0d624c1c4319760C96503BA27C347F3260f55'),
+ AllowedMethodsEnforcer: _addr('0x2c21fD0Cb9DC8445CB3fb0DC5E7Bb0Aca01842B5'),
+ AllowedTargetsEnforcer: _addr('0x7F20f61b1f09b08D970938F6fa563634d65c4EeB'),
+ ERC20TransferAmountEnforcer: _addr('0xf100b0819427117EcF76Ed94B358B1A5b5C6D2Fc'),
+ ERC20PeriodTransferEnforcer: _addr('0x474e3Ae7E169e940607cC624Da8A15Eb120139aB'),
+ LimitedCallsEnforcer: _addr('0x04658B29F6b82ed55274221a06Fc97D318E25416'),
+ NativeTokenTransferAmountEnforcer: _addr('0xF71af580b9c3078fbc2BBF16FbB8EEd82b330320'),
+ NativeTokenPeriodTransferEnforcer: _addr('0x9BC0FAf4Aca5AE429F4c06aEEaC517520CB16BD9'),
+ TimestampEnforcer: _addr('0x1046bb45C8d673d4ea75321280DB34899413c069'),
+ NonceEnforcer: _addr('0xDE4f2FAC4B3D87A1d9953Ca5FC09FCa7F366254f'),
+ ValueLteEnforcer: _addr('0x92Bf12322527cAA612fd31a0e810472BBB106A8F'),
+};
+
+// bytes32 sentinel used as `authority` for root (non-chained) delegations.
+export const ROOT_AUTHORITY = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
+
+// EIP-712 type hashes (from @metamask/delegation-core v1.1.0).
+export const DELEGATION_TYPEHASH =
+ '0x88c1d2ecf185adf710588203a5f263f0ff61be0d33da39792cde19ba9aa4331e';
+export const CAVEAT_TYPEHASH = '0x80ad7e1b04ee6d994a125f4714ca0720908bd80ed16063ec8aee4b88e9253e2d';
+
+// EIP-712 domain builder for delegation signing.
+// NAME = 'DelegationManager', DOMAIN_VERSION = '1' per on-chain constants.
+export function EIP712_DOMAIN({ chainId, verifyingContract }) {
+ return {
+ name: 'DelegationManager',
+ version: '1',
+ chainId,
+ verifyingContract,
+ };
+}
+
+// EIP-712 type definitions for signing delegations.
+// `signature` is excluded — it is what we are computing.
+export const DELEGATION_TYPES = {
+ Delegation: [
+ { name: 'delegate', type: 'address' },
+ { name: 'delegator', type: 'address' },
+ { name: 'authority', type: 'bytes32' },
+ { name: 'caveats', type: 'Caveat[]' },
+ { name: 'salt', type: 'uint256' },
+ ],
+ Caveat: [
+ { name: 'enforcer', type: 'address' },
+ { name: 'terms', type: 'bytes' },
+ { name: 'args', type: 'bytes' },
+ ],
+};
+
+/**
+ * ABI-encode an array of caveats into the on-chain format.
+ * @param {{ enforcer: string, terms: string, args: string }[]} caveats
+ * @returns {string} ABI-encoded bytes
+ */
+export function encodeCaveats(caveats) {
+ const coder = AbiCoder.defaultAbiCoder();
+ return coder.encode(
+ ['tuple(address enforcer, bytes terms, bytes args)[]'],
+ [caveats.map((c) => [c.enforcer, c.terms || '0x', c.args || '0x'])],
+ );
+}
+
+/**
+ * ABI-encode a delegation chain (array of signed delegations) into the bytes
+ * format expected by DelegationManager.redeemDelegations permissionContexts[i].
+ * For a direct root delegation, pass a single-element array.
+ * @param {{ delegate: string, delegator: string, authority: string, caveats: object[], salt: string|bigint, signature: string }[]} delegations
+ * @returns {string} ABI-encoded bytes
+ */
+export function encodePermissionContext(delegations) {
+ const coder = AbiCoder.defaultAbiCoder();
+ const tuples = delegations.map((d) => [
+ d.delegate,
+ d.delegator,
+ d.authority || ROOT_AUTHORITY,
+ (d.caveats || []).map((c) => [c.enforcer, c.terms || '0x', c.args || '0x']),
+ BigInt(d.salt ?? 0),
+ d.signature || '0x',
+ ]);
+ return coder.encode(
+ [
+ 'tuple(address delegate, address delegator, bytes32 authority, tuple(address enforcer, bytes terms, bytes args)[] caveats, uint256 salt, bytes signature)[]',
+ ],
+ [tuples],
+ );
+}
+
+/**
+ * ABI-encode a batch of calls into the Execution[] format expected by
+ * DelegationManager.redeemDelegations executionCallDatas[i].
+ * @param {{ to: string, value: string, data: string }[]} calls
+ * @returns {{ to: string, value: bigint, data: string }[]} tuple array (passed directly, not encoded)
+ */
+export function buildExecutionTuples(calls) {
+ return calls.map((c) => ({
+ to: c.to,
+ value: BigInt(c.value || '0'),
+ data: c.data || '0x',
+ }));
+}
diff --git a/src/permissions/grant-modal.js b/src/permissions/grant-modal.js
new file mode 100644
index 000000000..8d2a54a40
--- /dev/null
+++ b/src/permissions/grant-modal.js
@@ -0,0 +1,942 @@
+/**
+ * Grant Permissions Modal — 3-step scope builder, plain-English review, and
+ * MetaMask EIP-712 sign flow for ERC-7710 delegations.
+ *
+ * Public API:
+ * new GrantPermissionsModal({ agentId, chainId, delegatorAddress,
+ * delegateAddress, presets? }).open()
+ * → Promise<{ ok: true, id, delegationHash } | { ok: false, reason }>
+ */
+
+import { AbiCoder, getAddress } from 'ethers';
+import { connectWallet } from '../erc8004/agent-registry.js';
+import { encodeScopedDelegation, signDelegation } from './toolkit.js';
+import { CAVEAT_ENFORCERS } from '../erc7710/abi.js';
+
+// ── Token tables ──────────────────────────────────────────────────────────────
+
+const TOKENS = {
+ 84532: [
+ { symbol: 'ETH', address: 'native', decimals: 18 },
+ { symbol: 'USDC', address: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', decimals: 6 },
+ { symbol: 'WETH', address: '0x4200000000000000000000000000000000000006', decimals: 18 },
+ ],
+ 11155111: [
+ { symbol: 'ETH', address: 'native', decimals: 18 },
+ { symbol: 'USDC', address: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', decimals: 6 },
+ { symbol: 'WETH', address: '0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9', decimals: 18 },
+ ],
+ 1: [
+ { symbol: 'ETH', address: 'native', decimals: 18 },
+ { symbol: 'USDC', address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6 },
+ { symbol: 'WETH', address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', decimals: 18 },
+ ],
+};
+
+const KNOWN_CONTRACTS = {
+ 84532: [
+ { name: 'Uniswap V3 Router', address: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4' },
+ ],
+ 11155111: [
+ { name: 'Uniswap V3 Router', address: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48' },
+ ],
+ 1: [
+ { name: 'Uniswap V3 Router', address: '0xE592427A0AEce92De3Edee1F18E0157C05861564' },
+ { name: 'Uniswap V2 Router', address: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },
+ ],
+};
+
+const EXPIRY_OFFSETS = { '24h': 86400, '7d': 604800, '30d': 2592000 };
+const ZERO_ADDR = '0x' + '0'.repeat(40);
+
+// ── Pure helpers ──────────────────────────────────────────────────────────────
+
+function escapeHtml(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#039;');
+}
+
+function formatAddress(addr) {
+ if (!addr || addr === 'native') return addr;
+ return addr.slice(0, 6) + '…' + addr.slice(-4);
+}
+
+function formatAmount(raw, decimals) {
+ if (!raw) return '0';
+ const n = Number(raw) / 10 ** decimals;
+ return n % 1 === 0 ? String(n) : n.toFixed(6).replace(/\.?0+$/, '');
+}
+
+function toBaseUnits(display, decimals) {
+ const n = parseFloat(display) || 0;
+ return BigInt(Math.round(n * 10 ** decimals)).toString();
+}
+
+function tokensForChain(chainId) {
+ return TOKENS[chainId] ?? [{ symbol: 'ETH', address: 'native', decimals: 18 }];
+}
+
+function knownContractsForChain(chainId) {
+ return KNOWN_CONTRACTS[chainId] ?? [];
+}
+
+function resolveExpiry(preset, custom) {
+ if (preset === 'custom') {
+ const ts = custom ? Math.floor(new Date(custom).getTime() / 1000) : 0;
+ return ts;
+ }
+ return Math.floor(Date.now() / 1000) + (EXPIRY_OFFSETS[preset] ?? EXPIRY_OFFSETS['24h']);
+}
+
+function resolveTokenMeta(token, chainId) {
+ const list = tokensForChain(chainId);
+ return list.find((t) => t.address.toLowerCase() === token.toLowerCase()) ?? null;
+}
+
+function isKnownTarget(addr, chainId) {
+ const list = knownContractsForChain(chainId);
+ return list.some((c) => c.address.toLowerCase() === addr.toLowerCase());
+}
+
+function buildReviewLines(form, chainId) {
+ const meta = resolveTokenMeta(form.token, chainId);
+ const symbol = meta ? meta.symbol : formatAddress(form.token);
+ const decimals = meta ? meta.decimals : 18;
+ const amount = form.amount ? formatAmount(toBaseUnits(form.amount, decimals), decimals) : '?';
+
+ const periodLabel = { once: 'in total', daily: 'per day', weekly: 'per week' }[form.period] ?? '';
+
+ const expiryTs = resolveExpiry(form.expiry, form.customExpiry);
+ const expiryDate = expiryTs
+ ? new Date(expiryTs * 1000).toLocaleDateString('en-US', {
+ month: 'short', day: 'numeric', year: 'numeric',
+ })
+ : 'an unknown date';
+
+ const lines = [];
+
+ const targetNames = form.targets.map((addr) => {
+ const known = knownContractsForChain(chainId).find(
+ (c) => c.address.toLowerCase() === addr.toLowerCase(),
+ );
+ return known ? `${known.name} (${formatAddress(addr)})` : formatAddress(addr);
+ });
+
+ const targetDesc =
+ form.targets.length === 0
+ ? 'any contract'
+ : targetNames.join(', ');
+
+ lines.push(
+ `This agent can spend up to <strong>${escapeHtml(amount)} ${escapeHtml(symbol)}</strong>` +
+ ` ${escapeHtml(periodLabel)} on <strong>${escapeHtml(targetDesc)}</strong>` +
+ ` until <strong>${escapeHtml(expiryDate)}</strong>.`,
+ );
+
+ return lines;
+}
+
+function buildScopeCaveats(scope, chainId) {
+ const coder = AbiCoder.defaultAbiCoder();
+ const e = (key) => CAVEAT_ENFORCERS[key]?.[chainId] ?? ZERO_ADDR;
+
+ const tokenAddr = scope.token === 'native' ? ZERO_ADDR : getAddress(scope.token);
+
+ const caveats = [
+ {
+ enforcer: e('ERC20LimitEnforcer'),
+ terms: coder.encode(['address', 'uint256'], [tokenAddr, BigInt(scope.maxAmount)]),
+ args: '0x',
+ },
+ {
+ enforcer: e('TimestampEnforcer'),
+ terms: coder.encode(['uint128', 'uint128'], [0n, BigInt(scope.expiry)]),
+ args: '0x',
+ },
+ ];
+
+ if (scope.targets && scope.targets.length > 0) {
+ caveats.push({
+ enforcer: e('AllowedTargetsEnforcer'),
+ terms: coder.encode(['address[]'], [scope.targets.map((a) => getAddress(a))]),
+ args: '0x',
+ });
+ }
+
+ return caveats;
+}
+
+// ── CSS injection (once per page) ─────────────────────────────────────────────
+
+const STYLE_ID = 'gm-styles';
+
+function injectStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.gm-overlay{position:fixed;inset:0;z-index:130;display:flex;align-items:center;
+ justify-content:center;background:rgba(0,0,0,.85);backdrop-filter:blur(18px);
+ -webkit-backdrop-filter:blur(18px);animation:gm-fadein .2s ease}
+@keyframes gm-fadein{from{opacity:0}to{opacity:1}}
+.gm-modal{width:92vw;max-width:520px;max-height:88vh;display:flex;
+ flex-direction:column;background:rgba(10,10,10,.97);
+ border:1px solid rgba(255,255,255,.08);border-radius:var(--radius-lg);
+ overflow:hidden;box-shadow:0 16px 64px rgba(0,0,0,.7);color:#e0e0e0}
+.gm-header{display:flex;align-items:center;justify-content:space-between;
+ padding:var(--space-sm) var(--space-lg);border-bottom:1px solid rgba(255,255,255,.06);
+ flex-shrink:0}
+.gm-title{font-size:var(--text-lg);font-weight:500;color:#fff;letter-spacing:.03em}
+.gm-close{background:none;border:none;color:rgba(255,255,255,.4);
+ font-size:var(--text-2xl);cursor:pointer;padding:0;line-height:1;transition:color .2s}
+.gm-close:hover{color:#fff}
+.gm-breadcrumb{display:flex;align-items:center;gap:var(--space-xs);
+ padding:var(--space-xs) var(--space-lg);background:rgba(255,255,255,.02);
+ border-bottom:1px solid rgba(255,255,255,.04);flex-shrink:0}
+.gm-bc-step{font-size:var(--text-sm);color:rgba(255,255,255,.35);white-space:nowrap}
+.gm-bc-step--active{color:#fff;font-weight:500}
+.gm-bc-sep{color:rgba(255,255,255,.2);font-size:var(--text-xs)}
+.gm-body{padding:var(--space-lg);overflow-y:auto;flex:1;min-height:0}
+.gm-field{margin-bottom:var(--space-lg)}
+.gm-label{display:block;font-size:var(--text-sm);color:rgba(255,255,255,.6);
+ margin-bottom:var(--space-xs)}
+.gm-input{width:100%;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);
+ border-radius:var(--radius-md);color:#e0e0e0;padding:var(--space-xs) var(--space-sm);
+ font-size:var(--text-sm);font-family:var(--font-body);outline:none;transition:border .2s}
+.gm-input:focus{border-color:var(--accent)}
+.gm-input[type=number]{-moz-appearance:textfield}
+.gm-fieldset{border:none;padding:0;margin:0 0 var(--space-lg)}
+.gm-legend{font-size:var(--text-sm);color:rgba(255,255,255,.6);margin-bottom:var(--space-xs)}
+.gm-radio-group{display:flex;flex-wrap:wrap;gap:var(--space-xs)}
+.gm-radio-label{display:flex;align-items:center;gap:var(--space-xs);cursor:pointer;
+ font-size:var(--text-sm);color:#e0e0e0}
+.gm-radio-label input[type=radio]{accent-color:var(--accent)}
+.gm-amount-row{display:flex;align-items:center;gap:var(--space-xs)}
+.gm-amount-row .gm-input{flex:1}
+.gm-token-unit{font-size:var(--text-sm);color:rgba(255,255,255,.5);white-space:nowrap;
+ min-width:3rem;text-align:right}
+.gm-pills{display:flex;gap:var(--space-xs);flex-wrap:wrap;margin-bottom:var(--space-xs)}
+.gm-pill{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);
+ border-radius:20px;color:rgba(255,255,255,.7);font-size:var(--text-sm);
+ padding:var(--space-2xs) var(--space-sm);cursor:pointer;transition:all .15s}
+.gm-pill:hover{border-color:var(--accent);color:#fff}
+.gm-pill--active{background:var(--accent-soft);border-color:var(--accent);color:#fff}
+.gm-targets-list{display:flex;flex-direction:column;gap:var(--space-xs);
+ margin-bottom:var(--space-xs)}
+.gm-target-row{display:flex;align-items:center;gap:var(--space-xs);
+ background:rgba(255,255,255,.04);border-radius:var(--radius-md);
+ padding:var(--space-2xs) var(--space-sm)}
+.gm-target-addr{font-size:var(--text-sm);font-family:var(--font-mono);flex:1;
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.gm-target-name{font-size:var(--text-xs);color:rgba(255,255,255,.45)}
+.gm-target-remove{background:none;border:none;color:rgba(255,255,255,.35);cursor:pointer;
+ font-size:var(--text-base);line-height:1;padding:0;transition:color .15s}
+.gm-target-remove:hover{color:#e06c75}
+.gm-targets-add{display:flex;gap:var(--space-xs);flex-wrap:wrap;align-items:center}
+.gm-select{background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);
+ border-radius:var(--radius-md);color:#e0e0e0;padding:var(--space-2xs) var(--space-sm);
+ font-size:var(--text-sm);cursor:pointer;outline:none}
+.gm-actions{display:flex;justify-content:flex-end;gap:var(--space-sm);
+ padding-top:var(--space-lg);border-top:1px solid rgba(255,255,255,.06)}
+.gm-btn{padding:var(--space-xs) var(--space-lg);border-radius:var(--radius-md);
+ font-size:var(--text-sm);font-family:var(--font-body);cursor:pointer;
+ border:1px solid transparent;transition:all .15s;line-height:1.5}
+.gm-btn--primary{background:var(--accent);border-color:var(--accent);color:#fff}
+.gm-btn--primary:hover{filter:brightness(1.15)}
+.gm-btn--primary:disabled{opacity:.5;cursor:not-allowed;filter:none}
+.gm-btn--ghost{background:transparent;border-color:rgba(255,255,255,.2);
+ color:rgba(255,255,255,.7)}
+.gm-btn--ghost:hover{border-color:rgba(255,255,255,.5);color:#fff}
+.gm-btn--sm{padding:var(--space-2xs) var(--space-sm);font-size:var(--text-xs)}
+.gm-review-list{list-style:none;padding:0;margin:0 0 var(--space-lg);
+ display:flex;flex-direction:column;gap:var(--space-sm)}
+.gm-review-item{font-size:var(--text-sm);line-height:var(--leading-loose);
+ padding:var(--space-sm) var(--space-md);background:rgba(255,255,255,.04);
+ border-radius:var(--radius-md);border-left:3px solid var(--accent)}
+.gm-warning{font-size:var(--text-sm);color:#e06c75;padding:var(--space-xs) var(--space-sm);
+ background:rgba(224,108,117,.08);border:1px solid rgba(224,108,117,.3);
+ border-radius:var(--radius-md);margin-bottom:var(--space-md)}
+.gm-status{display:flex;flex-direction:column;align-items:center;gap:var(--space-md);
+ padding:var(--space-xl) 0;text-align:center}
+.gm-status-icon{font-size:2.5rem;line-height:1}
+.gm-status-text{font-size:var(--text-sm);color:rgba(255,255,255,.75)}
+.gm-status--success .gm-status-text{color:#98c379}
+.gm-status--error .gm-status-text{color:#e06c75}
+.gm-error-detail{font-size:var(--text-xs);color:rgba(255,255,255,.4);
+ font-family:var(--font-mono);word-break:break-all;text-align:left;
+ background:rgba(0,0,0,.3);padding:var(--space-xs);border-radius:var(--radius-md);
+ max-width:100%}
+.gm-custom-token-row{margin-top:var(--space-xs)}
+`;
+ document.head.appendChild(style);
+}
+
+// ── Main class ────────────────────────────────────────────────────────────────
+
+export class GrantPermissionsModal {
+ /**
+ * @param {{ agentId: string, chainId: number, delegatorAddress: string,
+ * delegateAddress: string, presets?: object }} opts
+ */
+ constructor({ agentId, chainId, delegatorAddress, delegateAddress, presets = {} }) {
+ this._agentId = agentId;
+ this._chainId = chainId;
+ this._delegatorAddress = delegatorAddress;
+ this._delegateAddress = delegateAddress;
+
+ this._step = 1;
+ this._form = {
+ token: presets.token ?? 'native',
+ customToken: '',
+ amount: presets.amount ?? '',
+ period: presets.period ?? 'once',
+ expiry: presets.expiry ?? '24h',
+ customExpiry: '',
+ targets: Array.isArray(presets.targets) ? [...presets.targets] : [],
+ };
+
+ this._signedDelegation = null;
+ this._lastScope = null;
+
+ this.overlay = null;
+ this._modal = null;
+ this._body = null;
+ this._resolve = null;
+ this._previouslyFocused = null;
+ this._onKeyDown = null;
+ this._onOverlayClick = null;
+ this._onTrapFocus = null;
+ }
+
+ /**
+ * Open the modal and return a promise that resolves when the user completes
+ * or cancels the flow.
+ * @returns {Promise<{ ok: true, id: string, delegationHash: string } | { ok: false, reason: string }>}
+ */
+ open() {
+ if (this.overlay) return Promise.resolve({ ok: false, reason: 'already_open' });
+ return new Promise((resolve) => {
+ this._resolve = resolve;
+ this._previouslyFocused = document.activeElement;
+ injectStyles();
+ this._build();
+ this._wireGlobal();
+ this._renderStep(1);
+ this._focusFirst();
+ });
+ }
+
+ close() {
+ this._settle({ ok: false, reason: 'closed' });
+ this._cleanup();
+ }
+
+ // ── Build / teardown ───────────────────────────────────────────────────────
+
+ _build() {
+ this.overlay = document.createElement('div');
+ this.overlay.className = 'gm-overlay';
+ this.overlay.setAttribute('role', 'dialog');
+ this.overlay.setAttribute('aria-modal', 'true');
+ this.overlay.setAttribute('aria-labelledby', 'gm-title');
+ this.overlay.innerHTML = `
+ <div class="gm-modal">
+ <div class="gm-header">
+ <span class="gm-title" id="gm-title">Grant Permissions</span>
+ <button type="button" class="gm-close" aria-label="Close">&times;</button>
+ </div>
+ <nav class="gm-breadcrumb" aria-label="Steps">
+ <span class="gm-bc-step" data-step="1">1. Scope</span>
+ <span class="gm-bc-sep" aria-hidden="true">›</span>
+ <span class="gm-bc-step" data-step="2">2. Review</span>
+ <span class="gm-bc-sep" aria-hidden="true">›</span>
+ <span class="gm-bc-step" data-step="3">3. Sign</span>
+ </nav>
+ <div class="gm-body"></div>
+ </div>
+ `;
+ document.body.appendChild(this.overlay);
+ this._modal = this.overlay.querySelector('.gm-modal');
+ this._body = this.overlay.querySelector('.gm-body');
+ this.overlay.querySelector('.gm-close').addEventListener('click', () => this.close());
+ }
+
+ _wireGlobal() {
+ this._onOverlayClick = (e) => {
+ if (e.target === this.overlay) this.close();
+ };
+ this.overlay.addEventListener('click', this._onOverlayClick);
+
+ this._onKeyDown = (e) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ this.close();
+ }
+ };
+ document.addEventListener('keydown', this._onKeyDown);
+
+ this._onTrapFocus = (e) => {
+ if (e.key !== 'Tab') return;
+ const items = this._focusables();
+ if (!items.length) return;
+ const first = items[0];
+ const last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+ this.overlay.addEventListener('keydown', this._onTrapFocus);
+ }
+
+ _cleanup() {
+ if (!this.overlay) return;
+ if (this._onKeyDown) document.removeEventListener('keydown', this._onKeyDown);
+ this.overlay.remove();
+ this.overlay = null;
+ this._modal = null;
+ this._body = null;
+ this._onKeyDown = null;
+ this._onOverlayClick = null;
+ this._onTrapFocus = null;
+ const prev = this._previouslyFocused;
+ this._previouslyFocused = null;
+ if (prev && typeof prev.focus === 'function' && document.contains(prev)) {
+ try { prev.focus(); } catch (_) {}
+ }
+ }
+
+ _settle(result) {
+ if (!this._resolve) return;
+ const fn = this._resolve;
+ this._resolve = null;
+ fn(result);
+ }
+
+ // ── Step routing ───────────────────────────────────────────────────────────
+
+ _renderStep(n) {
+ this._step = n;
+ this._body.innerHTML = '';
+ this._updateBreadcrumb(n);
+ if (n === 1) this._renderStep1();
+ else if (n === 2) this._renderStep2();
+ else this._renderStep3();
+ }
+
+ _updateBreadcrumb(active) {
+ this.overlay.querySelectorAll('.gm-bc-step').forEach((el) => {
+ el.classList.toggle('gm-bc-step--active', Number(el.dataset.step) === active);
+ });
+ }
+
+ // ── Step 1: Scope builder ─────────────────────────────────────────────────
+
+ _renderStep1() {
+ const tokens = tokensForChain(this._chainId);
+ const contracts = knownContractsForChain(this._chainId);
+ const currentToken = this._form.token;
+ const isCustomToken = !tokens.find((t) => t.address === currentToken);
+ const currentMeta = tokens.find((t) => t.address === currentToken);
+ const unitLabel = currentMeta ? currentMeta.symbol : 'tokens';
+
+ const tokenRadios = tokens
+ .map(
+ (t) => `
+ <label class="gm-radio-label">
+ <input type="radio" name="gm-token" value="${escapeHtml(t.address)}"
+ ${currentToken === t.address ? 'checked' : ''}>
+ ${escapeHtml(t.symbol)}
+ </label>`,
+ )
+ .join('');
+
+ const periodRadios = ['once', 'daily', 'weekly']
+ .map(
+ (p) => `
+ <label class="gm-radio-label">
+ <input type="radio" name="gm-period" value="${p}"
+ ${this._form.period === p ? 'checked' : ''}>
+ ${p.charAt(0).toUpperCase() + p.slice(1)}
+ </label>`,
+ )
+ .join('');
+
+ const expiryPills = ['24h', '7d', '30d', 'custom']
+ .map(
+ (k) => `
+ <button type="button" class="gm-pill ${this._form.expiry === k ? 'gm-pill--active' : ''}"
+ data-expiry="${k}">${k === '24h' ? '24 h' : k === '7d' ? '7 d' : k === '30d' ? '30 d' : 'Custom'}
+ </button>`,
+ )
+ .join('');
+
+ const targetRows = this._form.targets
+ .map((addr) => {
+ const known = contracts.find(
+ (c) => c.address.toLowerCase() === addr.toLowerCase(),
+ );
+ return `
+ <div class="gm-target-row" data-addr="${escapeHtml(addr)}">
+ <span class="gm-target-addr" title="${escapeHtml(addr)}">${escapeHtml(addr)}</span>
+ ${known ? `<span class="gm-target-name">${escapeHtml(known.name)}</span>` : ''}
+ <button type="button" class="gm-target-remove" aria-label="Remove target"
+ data-addr="${escapeHtml(addr)}">×</button>
+ </div>`;
+ })
+ .join('');
+
+ const knownOptions = contracts
+ .map(
+ (c) =>
+ `<option value="${escapeHtml(c.address)}">${escapeHtml(c.name)}</option>`,
+ )
+ .join('');
+
+ this._body.innerHTML = `
+ <form id="gm-scope-form" novalidate>
+ <fieldset class="gm-fieldset">
+ <legend class="gm-legend">Token</legend>
+ <div class="gm-radio-group">
+ ${tokenRadios}
+ <label class="gm-radio-label">
+ <input type="radio" name="gm-token" value="custom"
+ ${isCustomToken || currentToken === 'custom' ? 'checked' : ''}>
+ Custom
+ </label>
+ </div>
+ <div class="gm-custom-token-row" id="gm-custom-token-row"
+ ${!isCustomToken && currentToken !== 'custom' ? 'hidden' : ''}>
+ <input type="text" class="gm-input" id="gm-custom-token-input"
+ placeholder="0x… ERC-20 address"
+ value="${escapeHtml(isCustomToken ? currentToken : '')}">
+ </div>
+ </fieldset>
+
+ <div class="gm-field">
+ <label class="gm-label" for="gm-amount">Max amount</label>
+ <div class="gm-amount-row">
+ <input type="number" class="gm-input" id="gm-amount" min="0" step="any"
+ placeholder="0.00" value="${escapeHtml(this._form.amount)}">
+ <span class="gm-token-unit" id="gm-token-unit">${escapeHtml(unitLabel)}</span>
+ </div>
+ </div>
+
+ <fieldset class="gm-fieldset">
+ <legend class="gm-legend">Period</legend>
+ <div class="gm-radio-group">${periodRadios}</div>
+ </fieldset>
+
+ <div class="gm-field">
+ <label class="gm-label">Expiry</label>
+ <div class="gm-pills">${expiryPills}</div>
+ <input type="datetime-local" class="gm-input" id="gm-expiry-custom"
+ value="${escapeHtml(this._form.customExpiry)}"
+ ${this._form.expiry !== 'custom' ? 'hidden' : ''}>
+ </div>
+
+ <div class="gm-field">
+ <label class="gm-label">Allowed targets</label>
+ <div class="gm-targets-list" id="gm-targets-list">${targetRows}</div>
+ <div class="gm-targets-add">
+ ${
+ contracts.length
+ ? `<select class="gm-select" id="gm-known-select">
+ <option value="">Add known contract…</option>
+ ${knownOptions}
+ </select>`
+ : ''
+ }
+ <button type="button" class="gm-btn gm-btn--ghost gm-btn--sm"
+ id="gm-add-custom-btn">+ Custom address</button>
+ </div>
+ <input type="text" class="gm-input" id="gm-custom-target-input"
+ placeholder="0x… target address" style="margin-top:var(--space-xs)" hidden>
+ </div>
+
+ <div class="gm-actions">
+ <button type="button" class="gm-btn gm-btn--ghost" id="gm-cancel-btn">
+ Cancel
+ </button>
+ <button type="submit" class="gm-btn gm-btn--primary">
+ Review →
+ </button>
+ </div>
+ </form>
+ `;
+
+ this._bindStep1();
+ }
+
+ _bindStep1() {
+ const form = this._body.querySelector('#gm-scope-form');
+ const customTokenRow = form.querySelector('#gm-custom-token-row');
+ const customTokenInput = form.querySelector('#gm-custom-token-input');
+ const unitLabel = form.querySelector('#gm-token-unit');
+ const expiryCustom = form.querySelector('#gm-expiry-custom');
+ const targetsList = form.querySelector('#gm-targets-list');
+ const knownSelect = form.querySelector('#gm-known-select');
+ const addCustomBtn = form.querySelector('#gm-add-custom-btn');
+ const customTargetInput = form.querySelector('#gm-custom-target-input');
+
+ form.querySelectorAll('input[name="gm-token"]').forEach((radio) => {
+ radio.addEventListener('change', () => {
+ const isCustom = radio.value === 'custom';
+ customTokenRow.hidden = !isCustom;
+ if (!isCustom) {
+ const meta = tokensForChain(this._chainId).find(
+ (t) => t.address === radio.value,
+ );
+ unitLabel.textContent = meta ? meta.symbol : 'tokens';
+ } else {
+ unitLabel.textContent = 'tokens';
+ }
+ });
+ });
+
+ form.querySelectorAll('.gm-pill[data-expiry]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ form.querySelectorAll('.gm-pill[data-expiry]').forEach((b) =>
+ b.classList.remove('gm-pill--active'),
+ );
+ btn.classList.add('gm-pill--active');
+ expiryCustom.hidden = btn.dataset.expiry !== 'custom';
+ });
+ });
+
+ if (knownSelect) {
+ knownSelect.addEventListener('change', () => {
+ const addr = knownSelect.value;
+ if (!addr) return;
+ knownSelect.value = '';
+ this._addTarget(addr, targetsList);
+ });
+ }
+
+ addCustomBtn.addEventListener('click', () => {
+ customTargetInput.hidden = !customTargetInput.hidden;
+ if (!customTargetInput.hidden) {
+ customTargetInput.focus();
+ }
+ });
+
+ customTargetInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ const val = customTargetInput.value.trim();
+ if (val) {
+ try {
+ const addr = getAddress(val);
+ this._addTarget(addr, targetsList);
+ customTargetInput.value = '';
+ customTargetInput.hidden = true;
+ } catch (_) {
+ customTargetInput.style.borderColor = '#e06c75';
+ setTimeout(() => (customTargetInput.style.borderColor = ''), 1500);
+ }
+ }
+ }
+ });
+
+ targetsList.addEventListener('click', (e) => {
+ const btn = e.target.closest('.gm-target-remove');
+ if (!btn) return;
+ const addr = btn.dataset.addr;
+ this._form.targets = this._form.targets.filter(
+ (t) => t.toLowerCase() !== addr.toLowerCase(),
+ );
+ btn.closest('.gm-target-row').remove();
+ });
+
+ form.querySelector('#gm-cancel-btn').addEventListener('click', () => this.close());
+
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ this._collectStep1(form);
+ this._renderStep(2);
+ });
+ }
+
+ _addTarget(addr, listEl) {
+ if (
+ this._form.targets.some((t) => t.toLowerCase() === addr.toLowerCase())
+ ) return;
+ this._form.targets.push(addr);
+ const known = knownContractsForChain(this._chainId).find(
+ (c) => c.address.toLowerCase() === addr.toLowerCase(),
+ );
+ const row = document.createElement('div');
+ row.className = 'gm-target-row';
+ row.dataset.addr = addr;
+ row.innerHTML = `
+ <span class="gm-target-addr" title="${escapeHtml(addr)}">${escapeHtml(addr)}</span>
+ ${known ? `<span class="gm-target-name">${escapeHtml(known.name)}</span>` : ''}
+ <button type="button" class="gm-target-remove" aria-label="Remove target"
+ data-addr="${escapeHtml(addr)}">×</button>
+ `;
+ listEl.appendChild(row);
+ }
+
+ _collectStep1(form) {
+ const checkedToken = form.querySelector('input[name="gm-token"]:checked');
+ const tokenVal = checkedToken ? checkedToken.value : 'native';
+ if (tokenVal === 'custom') {
+ const raw = form.querySelector('#gm-custom-token-input').value.trim();
+ this._form.token = raw || 'native';
+ } else {
+ this._form.token = tokenVal;
+ }
+ this._form.amount = form.querySelector('#gm-amount').value.trim();
+ const checkedPeriod = form.querySelector('input[name="gm-period"]:checked');
+ this._form.period = checkedPeriod ? checkedPeriod.value : 'once';
+ const activePill = form.querySelector('.gm-pill--active[data-expiry]');
+ this._form.expiry = activePill ? activePill.dataset.expiry : '24h';
+ this._form.customExpiry = form.querySelector('#gm-expiry-custom').value;
+ }
+
+ // ── Step 2: Plain-English review ──────────────────────────────────────────
+
+ _renderStep2() {
+ const lines = buildReviewLines(this._form, this._chainId);
+ const hasUnknown = this._form.targets.some(
+ (addr) => !isKnownTarget(addr, this._chainId),
+ );
+
+ const lineItems = lines
+ .map((l) => `<li class="gm-review-item">${l}</li>`)
+ .join('');
+
+ this._body.innerHTML = `
+ <ul class="gm-review-list" role="list">${lineItems}</ul>
+ ${
+ hasUnknown
+ ? `<div class="gm-warning" role="alert">
+ ⚠ One or more target addresses are not on the known-contracts list.
+ Verify them before continuing.
+ </div>`
+ : ''
+ }
+ <div class="gm-actions">
+ <button type="button" class="gm-btn gm-btn--ghost" id="gm-back-btn">
+ ← Back
+ </button>
+ <button type="button" class="gm-btn gm-btn--primary" id="gm-continue-btn">
+ Continue to MetaMask →
+ </button>
+ </div>
+ `;
+
+ this._body.querySelector('#gm-back-btn').addEventListener('click', () =>
+ this._renderStep(1),
+ );
+ this._body.querySelector('#gm-continue-btn').addEventListener('click', () =>
+ this._renderStep(3),
+ );
+ }
+
+ // ── Step 3: Sign + submit ─────────────────────────────────────────────────
+
+ _renderStep3() {
+ this._body.innerHTML = `
+ <div class="gm-status" id="gm-status" role="status" aria-live="polite">
+ <div class="gm-status-icon" id="gm-status-icon">⏳</div>
+ <div class="gm-status-text" id="gm-status-text">Preparing…</div>
+ </div>
+ <div class="gm-actions" id="gm-sign-actions"></div>
+ `;
+ this._signAndSubmit();
+ }
+
+ _setStatus(icon, text, className = '') {
+ const status = this._body?.querySelector('#gm-status');
+ if (!status) return;
+ status.className = 'gm-status' + (className ? ` ${className}` : '');
+ const iconEl = status.querySelector('#gm-status-icon');
+ const textEl = status.querySelector('#gm-status-text');
+ if (iconEl) iconEl.textContent = icon;
+ if (textEl) textEl.textContent = text;
+ }
+
+ _setActions(html) {
+ const el = this._body?.querySelector('#gm-sign-actions');
+ if (el) el.innerHTML = html;
+ }
+
+ async _signAndSubmit() {
+ this._setStatus('⏳', 'Connecting wallet…');
+
+ let signer;
+ try {
+ const wallet = await connectWallet();
+ signer = wallet.signer;
+ } catch (err) {
+ this._setStatus('✗', `Wallet connection failed: ${err.message}`, 'gm-status--error');
+ this._setActions(
+ `<button class="gm-btn gm-btn--ghost" id="gm-retry-conn">Retry</button>`,
+ );
+ this._body.querySelector('#gm-retry-conn')?.addEventListener('click', () =>
+ this._signAndSubmit(),
+ );
+ return;
+ }
+
+ const meta = tokensForChain(this._chainId).find(
+ (t) => t.address === this._form.token,
+ );
+ const decimals = meta ? meta.decimals : 18;
+ const maxAmount = toBaseUnits(this._form.amount || '0', decimals);
+ const expiry = resolveExpiry(this._form.expiry, this._form.customExpiry);
+
+ const scope = {
+ token: this._form.token,
+ maxAmount,
+ period: this._form.period,
+ targets: [...this._form.targets],
+ expiry,
+ };
+ this._lastScope = scope;
+
+ let signed = this._signedDelegation;
+
+ if (!signed) {
+ this._setStatus('⏳', 'Waiting for signature…');
+
+ let delegation;
+ try {
+ const caveats = buildScopeCaveats(scope, this._chainId);
+ delegation = encodeScopedDelegation({
+ delegator: this._delegatorAddress,
+ delegate: this._delegateAddress,
+ caveats,
+ expiry,
+ chainId: this._chainId,
+ });
+ } catch (err) {
+ this._setStatus('✗', `Scope error: ${err.message}`, 'gm-status--error');
+ this._setActions(
+ `<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>`,
+ );
+ this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
+ this._renderStep(1),
+ );
+ return;
+ }
+
+ try {
+ signed = await signDelegation({ ...delegation, scope }, signer);
+ this._signedDelegation = signed;
+ } catch (err) {
+ const reason = err?.code === 4001 || err?.code === 'ACTION_REJECTED'
+ ? 'Signature rejected.'
+ : `Signature failed: ${err.message}`;
+ this._setStatus('✗', reason, 'gm-status--error');
+ this._setActions(`
+ <button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>
+ <button class="gm-btn gm-btn--primary" id="gm-retry-sign">Retry</button>
+ `);
+ this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
+ this._renderStep(1),
+ );
+ this._body.querySelector('#gm-retry-sign')?.addEventListener('click', () => {
+ this._signedDelegation = null;
+ this._signAndSubmit();
+ });
+ return;
+ }
+ }
+
+ await this._submitDelegation(signed, scope);
+ }
+
+ async _submitDelegation(signed, scope) {
+ this._setStatus('⏳', 'Submitting…');
+ this._setActions('');
+
+ let data;
+ try {
+ const res = await fetch('/api/permissions/grant', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agentId: this._agentId,
+ chainId: this._chainId,
+ delegation: signed,
+ scope,
+ }),
+ });
+ data = await res.json();
+
+ if (!res.ok) {
+ const msg = data?.message || data?.error || `HTTP ${res.status}`;
+ throw Object.assign(new Error(msg), { statusCode: res.status });
+ }
+ } catch (err) {
+ const msg = err.message || String(err);
+ const isConflict = err.statusCode === 409;
+
+ this._setStatus('✗', isConflict ? 'Already granted.' : `Failed: ${msg}`,
+ 'gm-status--error');
+
+ const detail = document.createElement('div');
+ detail.className = 'gm-error-detail';
+ detail.textContent = msg;
+ this._body.querySelector('#gm-status')?.appendChild(detail);
+
+ const retryHtml = isConflict
+ ? `<button class="gm-btn gm-btn--ghost" id="gm-done-err">Close</button>`
+ : `<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>
+ <button class="gm-btn gm-btn--primary" id="gm-retry-submit">Retry submit</button>`;
+ this._setActions(retryHtml);
+
+ this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
+ this._renderStep(1),
+ );
+ this._body.querySelector('#gm-retry-submit')?.addEventListener('click', () =>
+ this._submitDelegation(signed, scope),
+ );
+ this._body.querySelector('#gm-done-err')?.addEventListener('click', () =>
+ this.close(),
+ );
+ return;
+ }
+
+ this._setStatus('✓', 'Granted ✓', 'gm-status--success');
+ this._settle({ ok: true, id: data.id, delegationHash: data.delegationHash });
+
+ setTimeout(() => this._cleanup(), 1500);
+ }
+
+ // ── Utilities ──────────────────────────────────────────────────────────────
+
+ _focusFirst() {
+ const items = this._focusables();
+ if (items.length) {
+ try { items[0].focus(); } catch (_) {}
+ }
+ }
+
+ _focusables() {
+ if (!this.overlay) return [];
+ return Array.from(
+ this.overlay.querySelectorAll(
+ 'button:not([disabled]), input:not([disabled]):not([hidden]), ' +
+ 'select:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ ),
+ ).filter((el) => !el.closest('[hidden]'));
+ }
+}
+
+// ── Convenience global (debug or explicit import only) ─────────────────────────
+
+if (typeof window !== 'undefined') {
+ if (window.AGENT_DEBUG && !window.openGrantPermissions) {
+ window.openGrantPermissions = (opts) => new GrantPermissionsModal(opts).open();
+ }
+}
diff --git a/src/permissions/manage-panel.js b/src/permissions/manage-panel.js
new file mode 100644
index 000000000..24fea4744
--- /dev/null
+++ b/src/permissions/manage-panel.js
@@ -0,0 +1,339 @@
+/**
+ * Manage Permissions Panel
+ *
+ * Renders a list of all delegations granted for an agent, with revoke support.
+ *
+ * Public API:
+ * mountManagePanel({ container, agentId }) → { unmount }
+ */
+
+import { BrowserProvider, Contract } from 'ethers';
+import { CHAIN_META, addressExplorerUrl, txExplorerUrl } from '../erc8004/chain-meta.js';
+import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../erc7710/abi.js';
+
+// ── Public API ────────────────────────────────────────────────────────────────
+
+/**
+ * @param {{ container: HTMLElement, agentId: string }} opts
+ * @returns {{ unmount: () => void }}
+ */
+export function mountManagePanel({ container, agentId }) {
+ const panel = new ManagePanel(container, agentId);
+ panel.mount();
+ return { unmount: () => panel.unmount() };
+}
+
+// ── Panel class ───────────────────────────────────────────────────────────────
+
+class ManagePanel {
+ constructor(container, agentId) {
+ this._container = container;
+ this._agentId = agentId;
+ this._root = null;
+ this._delegations = [];
+ this._onFocus = null;
+ }
+
+ mount() {
+ this._root = document.createElement('div');
+ this._root.className = 'mp-panel';
+ this._root.innerHTML = `
+ <div class="mp-header">
+ <span class="mp-title">Permissions</span>
+ <button class="mp-refresh-btn" title="Refresh">
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M17.65 6.35A7.958 7.958 0 0 0 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0 1 12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
+ </svg>
+ </button>
+ </div>
+ <div class="mp-list" id="mp-list-${this._agentId}">
+ <div class="mp-loading">Loading…</div>
+ </div>
+ `;
+ this._container.appendChild(this._root);
+
+ this._root.querySelector('.mp-refresh-btn').addEventListener('click', () => this._load());
+
+ this._onFocus = () => this._load();
+ window.addEventListener('focus', this._onFocus);
+
+ this._load();
+ }
+
+ unmount() {
+ if (this._onFocus) window.removeEventListener('focus', this._onFocus);
+ this._root?.remove();
+ }
+
+ async _load() {
+ try {
+ const res = await fetch(
+ `/api/permissions/list?agentId=${encodeURIComponent(this._agentId)}&status=all&limit=200`,
+ { credentials: 'include' },
+ );
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ if (!data.ok) throw new Error(data.message || 'list failed');
+ this._delegations = data.delegations || [];
+ this._render();
+ } catch (err) {
+ this._listEl().innerHTML = `<div class="mp-error">Failed to load: ${_esc(err.message)}</div>`;
+ }
+ }
+
+ _render() {
+ const el = this._listEl();
+ if (!this._delegations.length) {
+ el.innerHTML = `
+ <div class="mp-empty">
+ <p>No permissions granted yet.</p>
+ <button class="mp-grant-btn" id="mp-grant-btn">Grant permissions</button>
+ </div>
+ `;
+ el.querySelector('#mp-grant-btn').addEventListener('click', () => {
+ if (typeof window.openGrantPermissions === 'function') {
+ window.openGrantPermissions(this._agentId);
+ }
+ });
+ return;
+ }
+
+ el.innerHTML = '';
+ for (const d of this._delegations) {
+ el.appendChild(this._buildCard(d));
+ }
+ }
+
+ _buildCard(d) {
+ const card = document.createElement('div');
+ card.className = `mp-card mp-card--${d.status}`;
+ card.dataset.id = d.id;
+
+ const chainMeta = CHAIN_META[d.chain_id];
+ const chainName = chainMeta?.shortName ?? `${d.chain_id}`;
+ const explorerBase = chainMeta?.explorer ?? '';
+
+ const delegatorUrl = explorerBase ? addressExplorerUrl(d.chain_id, d.delegator_address) : '#';
+ const delegateUrl = explorerBase ? addressExplorerUrl(d.chain_id, d.delegate_address) : '#';
+
+ const scopeText = _scopeSentence(d.scope);
+ const usageLine = _usageLine(d.redemption_count, d.last_redeemed_at);
+ const badgeClass = { active: 'mp-badge--active', revoked: 'mp-badge--revoked', expired: 'mp-badge--expired' }[d.status] || '';
+ const hashShort = d.delegation_hash
+ ? `${d.delegation_hash.slice(0, 8)}…${d.delegation_hash.slice(-6)}`
+ : 'unknown hash';
+ const isPendingIndexer = !d.delegation_hash;
+
+ card.innerHTML = `
+ <div class="mp-card-top">
+ <span class="mp-badge ${badgeClass}">${d.status}</span>
+ <span class="mp-chain-chip">${_esc(chainName)}</span>
+ ${isPendingIndexer ? '<span class="mp-indexer-pending">pending indexer</span>' : ''}
+ </div>
+ <div class="mp-card-scope">${_esc(scopeText)}</div>
+ <div class="mp-card-hash">${_esc(hashShort)}</div>
+ <div class="mp-card-usage">${_esc(usageLine)}</div>
+ <div class="mp-card-addresses">
+ <a class="mp-addr-link" href="${_esc(delegatorUrl)}" target="_blank" rel="noopener noreferrer"
+ title="Delegator">
+ ${_shortAddr(d.delegator_address)}
+ </a>
+ <span class="mp-addr-arrow" aria-hidden="true">→</span>
+ <a class="mp-addr-link" href="${_esc(delegateUrl)}" target="_blank" rel="noopener noreferrer"
+ title="Delegate (agent)">
+ ${_shortAddr(d.delegate_address)}
+ </a>
+ </div>
+ <div class="mp-card-actions">
+ ${d.status === 'active'
+ ? `<button class="mp-revoke-btn" data-id="${_esc(d.id)}" data-hash="${_esc(d.delegation_hash || '')}" data-chain="${d.chain_id}">Revoke</button>`
+ : ''}
+ </div>
+ <div class="mp-card-error" style="display:none"></div>
+ <div class="mp-card-pending" style="display:none"></div>
+ `;
+
+ const revokeBtn = card.querySelector('.mp-revoke-btn');
+ if (revokeBtn) {
+ revokeBtn.addEventListener('click', () => this._handleRevoke(card, d));
+ }
+
+ return card;
+ }
+
+ async _handleRevoke(card, d) {
+ const revokeBtn = card.querySelector('.mp-revoke-btn');
+ const errorEl = card.querySelector('.mp-card-error');
+ const pendingEl = card.querySelector('.mp-card-pending');
+
+ const _showError = (msg) => {
+ errorEl.textContent = msg;
+ errorEl.style.display = '';
+ revokeBtn.disabled = false;
+ revokeBtn.textContent = 'Revoke';
+ };
+
+ errorEl.style.display = 'none';
+ pendingEl.style.display = 'none';
+
+ if (!window.ethereum) {
+ _showError('No wallet detected. Please install MetaMask.');
+ return;
+ }
+
+ let provider, signer, signerAddress;
+ try {
+ provider = new BrowserProvider(window.ethereum);
+ await provider.send('eth_requestAccounts', []);
+ signer = await provider.getSigner();
+ signerAddress = (await signer.getAddress()).toLowerCase();
+ } catch (err) {
+ _showError(`Wallet connect failed: ${err.message}`);
+ return;
+ }
+
+ const delegatorAddr = (d.delegator_address || '').toLowerCase();
+ if (signerAddress !== delegatorAddr) {
+ _showError(
+ `Connect with ${_shortAddr(d.delegator_address)} to revoke.`,
+ );
+ return;
+ }
+
+ if (!d.delegation_hash) {
+ _showError('Delegation hash unknown — cannot revoke on-chain yet.');
+ return;
+ }
+
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[d.chain_id];
+ if (!managerAddr) {
+ _showError(`No DelegationManager deployment for chain ${d.chain_id}.`);
+ return;
+ }
+
+ // Switch to the correct chain
+ try {
+ const network = await provider.getNetwork();
+ if (Number(network.chainId) !== d.chain_id) {
+ await provider.send('wallet_switchEthereumChain', [
+ { chainId: '0x' + d.chain_id.toString(16) },
+ ]);
+ }
+ } catch (err) {
+ _showError(`Chain switch failed: ${err.message}`);
+ return;
+ }
+
+ revokeBtn.disabled = true;
+ revokeBtn.textContent = 'Sending…';
+
+ let tx;
+ try {
+ const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, signer);
+ tx = await manager.disableDelegation(d.delegation_hash);
+ } catch (err) {
+ _showError(err.message);
+ return;
+ }
+
+ // Show pending state with explorer link
+ const explorerTxUrl = txExplorerUrl(d.chain_id, tx.hash);
+ pendingEl.innerHTML = `
+ <span class="mp-spinner" aria-hidden="true"></span>
+ Revoking…
+ ${explorerTxUrl ? `<a href="${_esc(explorerTxUrl)}" target="_blank" rel="noopener noreferrer" class="mp-tx-link">view tx</a>` : ''}
+ `;
+ pendingEl.style.display = '';
+ revokeBtn.textContent = 'Pending…';
+
+ try {
+ await tx.wait();
+ } catch (err) {
+ pendingEl.style.display = 'none';
+ _showError(`Transaction failed: ${err.message}`);
+ return;
+ }
+
+ // Mirror to server
+ try {
+ const res = await fetch('/api/permissions/revoke', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ id: d.id, txHash: tx.hash }),
+ });
+ const data = await res.json();
+ if (!data.ok) throw new Error(data.message || 'revoke mirror failed');
+ } catch (err) {
+ // Server mirror failure is non-fatal — on-chain is source of truth.
+ console.warn('[manage-panel] server mirror failed:', err.message);
+ }
+
+ // Flip card to revoked optimistically
+ pendingEl.style.display = 'none';
+ card.classList.remove('mp-card--active');
+ card.classList.add('mp-card--revoked');
+ card.querySelector('.mp-badge').className = 'mp-badge mp-badge--revoked';
+ card.querySelector('.mp-badge').textContent = 'revoked';
+ revokeBtn.remove();
+
+ // Background refetch to sync any other changes
+ setTimeout(() => this._load(), 2000);
+ }
+
+ _listEl() {
+ return this._root.querySelector(`#mp-list-${this._agentId}`);
+ }
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function _esc(str) {
+ return String(str ?? '').replace(
+ /[<>&"]/g,
+ (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c],
+ );
+}
+
+function _shortAddr(addr) {
+ if (!addr) return 'unknown';
+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
+}
+
+function _scopeSentence(scope) {
+ if (!scope) return 'Unknown scope';
+ const { token, maxAmount, period, targets, expiry } = scope;
+ const tokenLabel = token && token !== 'native' ? _shortAddr(token) : (token === 'native' ? 'native token' : 'token');
+ const amountLabel = maxAmount ? _formatAmount(maxAmount) : '?';
+ const periodLabel = { daily: 'per day', weekly: 'per week', once: 'once' }[period] || period || '';
+ const targetLabel = targets?.length === 1 ? `on ${_shortAddr(targets[0])}` : targets?.length > 1 ? `on ${targets.length} contracts` : '';
+ const expiryLabel = expiry ? `until ${_formatDate(expiry)}` : '';
+ const parts = [`Up to ${amountLabel} ${tokenLabel}`, periodLabel, targetLabel, expiryLabel].filter(Boolean);
+ return parts.join(' ');
+}
+
+function _formatAmount(raw) {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return raw;
+ // Assume 6 decimals (USDC-style) for display. Real code would look up token decimals.
+ const display = n / 1e6;
+ return display >= 1 ? display.toLocaleString() : raw;
+}
+
+function _formatDate(unixSeconds) {
+ const d = new Date(unixSeconds * 1000);
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
+}
+
+function _usageLine(count, lastAt) {
+ const c = count ?? 0;
+ const redemptionPart = `${c} redemption${c !== 1 ? 's' : ''}`;
+ if (!lastAt) return redemptionPart;
+ const diff = Date.now() - new Date(lastAt).getTime();
+ let ago;
+ if (diff < 60_000) ago = 'just now';
+ else if (diff < 3_600_000) ago = `${Math.floor(diff / 60_000)}m ago`;
+ else if (diff < 86_400_000) ago = `${Math.floor(diff / 3_600_000)}h ago`;
+ else ago = _formatDate(Math.floor(new Date(lastAt).getTime() / 1000));
+ return `${redemptionPart} · last used ${ago}`;
+}
diff --git a/src/permissions/toolkit.js b/src/permissions/toolkit.js
new file mode 100644
index 000000000..1676c2fd3
--- /dev/null
+++ b/src/permissions/toolkit.js
@@ -0,0 +1,353 @@
+/**
+ * ERC-7710 delegation toolkit — single facade over all delegation operations.
+ * Consumers import from here; never import @metamask/delegation-toolkit directly.
+ * Usable in both browser (wallet signer) and Node (relayer signer).
+ *
+ * Uses ethers v6 directly — @metamask/delegation-toolkit transitive deps exceed
+ * 5 MB threshold (@metamask/delegation-abis alone is 6.2 MB unpacked).
+ */
+
+import { AbiCoder, Contract, getAddress, JsonRpcProvider, randomBytes, TypedDataEncoder } from 'ethers';
+import {
+ CAVEAT_ENFORCERS,
+ DELEGATION_MANAGER_ABI,
+ DELEGATION_MANAGER_DEPLOYMENTS,
+ DELEGATION_TYPES,
+ EIP712_DOMAIN,
+ ROOT_AUTHORITY,
+} from '../erc7710/abi.js';
+
+// ─── Error type ──────────────────────────────────────────────────────────────
+
+/**
+ * Typed error for all delegation operations.
+ * `code` matches the canonical OAuth-style error codes from 00-README.md.
+ */
+export class PermissionError extends Error {
+ /**
+ * @param {string} code - delegation_expired | delegation_revoked | scope_exceeded |
+ * target_not_allowed | delegation_not_found | signature_invalid |
+ * chain_not_supported | rate_limited
+ * @param {string} message
+ */
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ this.name = 'PermissionError';
+ }
+}
+
+// ─── Internal helpers ────────────────────────────────────────────────────────
+
+/**
+ * @param {unknown} addr
+ * @param {string} label
+ * @returns {string} EIP-55 checksummed address
+ * @throws {PermissionError} signature_invalid
+ */
+function checksum(addr, label) {
+ try {
+ return getAddress(/** @type {string} */ (addr));
+ } catch {
+ throw new PermissionError('signature_invalid', `Invalid address for ${label}: ${addr}`);
+ }
+}
+
+/**
+ * @param {number} chainId
+ * @returns {string} DelegationManager address
+ * @throws {PermissionError} chain_not_supported
+ */
+function managerAddress(chainId) {
+ const addr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
+ if (!addr) throw new PermissionError('chain_not_supported', `No DelegationManager deployment for chain ${chainId}`);
+ return addr;
+}
+
+/**
+ * ABI-encode a delegation array into the bytes expected by permissionContexts[i].
+ * Format: abi.encode(Delegation[]) per @metamask/delegation-core DELEGATION_ARRAY_ABI_TYPES.
+ * @param {object[]} delegations
+ * @returns {string} 0x-prefixed hex
+ */
+function encodePermissionContext(delegations) {
+ const coder = AbiCoder.defaultAbiCoder();
+ const tuples = delegations.map((d) => [
+ d.delegate,
+ d.delegator,
+ d.authority ?? ROOT_AUTHORITY,
+ (d.caveats ?? []).map((c) => [c.enforcer, c.terms ?? '0x', c.args ?? '0x']),
+ d.salt ?? 0n,
+ d.signature ?? '0x',
+ ]);
+ return coder.encode(
+ ['tuple(address,address,bytes32,tuple(address,bytes,bytes)[],uint256,bytes)[]'],
+ [tuples],
+ );
+}
+
+/**
+ * ERC-7579 packed execution calldata for a single call.
+ * encodePacked(address target, uint256 value, bytes callData)
+ * @param {string} to
+ * @param {bigint|number|string} value
+ * @param {string} data
+ * @returns {string} 0x-prefixed hex
+ */
+function encodeSingleExecution(to, value, data) {
+ const coder = AbiCoder.defaultAbiCoder();
+ // abi.encode is safe here — ERC-7579's decodeSingle uses byte-slice offsets
+ // but the MetaMask DelegationManager accepts standard abi.encode for single mode.
+ return coder.encode(['address', 'uint256', 'bytes'], [to, value ?? 0n, data ?? '0x']);
+}
+
+// ERC-7579 single-call, default execution mode (callType=0x01, execType=0x00).
+const SINGLE_DEFAULT_MODE = '0x0100000000000000000000000000000000000000000000000000000000000000';
+
+// ─── Public API ──────────────────────────────────────────────────────────────
+
+/**
+ * Build an unsigned delegation envelope ready to be EIP-712 signed.
+ * Pure and synchronous — no network I/O.
+ *
+ * @param {{
+ * delegator: string,
+ * delegate: string,
+ * caveats: Array<{ enforcer: string, terms: string, args?: string }>,
+ * expiry: number,
+ * chainId: number,
+ * }} opts
+ * @returns {{
+ * delegate: string,
+ * delegator: string,
+ * authority: string,
+ * caveats: Array<{ enforcer: string, terms: string, args: string }>,
+ * salt: bigint,
+ * expiry: number,
+ * chainId: number,
+ * }}
+ * @throws {PermissionError} signature_invalid | delegation_expired | chain_not_supported
+ */
+export function encodeScopedDelegation({ delegator, delegate, caveats, expiry, chainId }) {
+ const delegatorAddr = checksum(delegator, 'delegator');
+ const delegateAddr = checksum(delegate, 'delegate');
+
+ if (delegateAddr === delegatorAddr) {
+ throw new PermissionError('signature_invalid', 'delegate must differ from delegator');
+ }
+ if (!Array.isArray(caveats) || caveats.length < 1) {
+ throw new PermissionError('signature_invalid', 'at least one caveat is required');
+ }
+ if (expiry <= Math.floor(Date.now() / 1000) + 60) {
+ throw new PermissionError('delegation_expired', 'expiry must be at least 60 seconds in the future');
+ }
+
+ managerAddress(chainId); // throws chain_not_supported if unknown
+
+ const normalizedCaveats = caveats.map((c, i) => ({
+ enforcer: checksum(c.enforcer, `caveats[${i}].enforcer`),
+ terms: c.terms ?? '0x',
+ args: c.args ?? '0x',
+ }));
+
+ // Cryptographically random 32-byte salt to prevent replay.
+ const salt = BigInt('0x' + Buffer.from(randomBytes(32)).toString('hex'));
+
+ return {
+ delegate: delegateAddr,
+ delegator: delegatorAddr,
+ authority: ROOT_AUTHORITY,
+ caveats: normalizedCaveats,
+ salt,
+ expiry,
+ chainId,
+ };
+}
+
+/**
+ * Sign a delegation using EIP-712.
+ * Returns the delegation enriched with `signature` and `hash`.
+ * Only the hash is safe to log — never log the signature itself.
+ *
+ * @param {{
+ * delegate: string,
+ * delegator: string,
+ * authority: string,
+ * caveats: Array<{ enforcer: string, terms: string, args: string }>,
+ * salt: bigint,
+ * chainId: number,
+ * }} delegation - unsigned delegation from encodeScopedDelegation
+ * @param {import('ethers').Signer} signer - ethers v6 signer (must support signTypedData)
+ * @returns {Promise<{ signature: string, hash: string } & typeof delegation>}
+ * @throws {PermissionError} chain_not_supported | signature_invalid
+ */
+export async function signDelegation(delegation, signer) {
+ if (!signer) throw new PermissionError('signature_invalid', 'signer is required');
+
+ const verifyingContract = managerAddress(delegation.chainId);
+ const domain = EIP712_DOMAIN({ chainId: delegation.chainId, verifyingContract });
+
+ const typedValue = {
+ delegate: delegation.delegate,
+ delegator: delegation.delegator,
+ authority: delegation.authority ?? ROOT_AUTHORITY,
+ caveats: delegation.caveats,
+ salt: delegation.salt ?? 0n,
+ };
+
+ let signature;
+ try {
+ signature = await signer.signTypedData(domain, DELEGATION_TYPES, typedValue);
+ } catch (err) {
+ throw new PermissionError('signature_invalid', `EIP-712 signing failed: ${err.message}`);
+ }
+
+ // Compute hash locally using the same encoder ethers uses for signTypedData.
+ const hash = TypedDataEncoder.hash(domain, DELEGATION_TYPES, typedValue);
+
+ return { ...delegation, signature, hash };
+}
+
+/**
+ * Redeem a signed delegation by submitting redeemDelegations to the DelegationManager.
+ * Verifies on-chain that the delegation is not revoked before spending gas.
+ *
+ * @param {{
+ * delegation: object,
+ * calls: Array<{ to: string, value?: bigint|number|string, data?: string }>,
+ * signer: import('ethers').Signer,
+ * chainId: number,
+ * }} opts
+ * @returns {Promise<{ txHash: string, receipt: object }>}
+ * @throws {PermissionError} delegation_revoked | chain_not_supported | signature_invalid
+ */
+export async function redeemDelegation({ delegation, calls, signer, chainId }) {
+ if (!signer) throw new PermissionError('signature_invalid', 'signer is required');
+ if (!signer.provider) throw new PermissionError('chain_not_supported', 'signer has no provider attached');
+
+ const addr = managerAddress(chainId);
+
+ // Pre-flight: check delegation is not disabled on-chain.
+ const dmRead = new Contract(addr, DELEGATION_MANAGER_ABI, signer.provider);
+ const disabled = await dmRead.disabledDelegations(delegation.hash);
+ if (disabled) throw new PermissionError('delegation_revoked', 'delegation has been revoked on-chain');
+
+ // Build permissionContexts: one entry per call, each wrapping the same delegation chain.
+ const permissionContext = encodePermissionContext([delegation]);
+ const permissionContexts = calls.map(() => permissionContext);
+ const modes = calls.map(() => SINGLE_DEFAULT_MODE);
+ const executionCallDatas = calls.map((c) =>
+ encodeSingleExecution(checksum(c.to, 'calls[].to'), c.value ?? 0n, c.data ?? '0x'),
+ );
+
+ const dmWrite = new Contract(addr, DELEGATION_MANAGER_ABI, signer);
+ const tx = await dmWrite.redeemDelegations(permissionContexts, modes, executionCallDatas);
+ const receipt = await tx.wait();
+
+ return {
+ txHash: tx.hash,
+ receipt: {
+ status: receipt.status,
+ blockNumber: receipt.blockNumber,
+ gasUsed: receipt.gasUsed.toString(),
+ },
+ };
+}
+
+/**
+ * Read-only check that a delegation hash is valid on-chain.
+ * Checks: not disabled on-chain. Pass `delegation` for expiry + signature checks.
+ *
+ * @param {{
+ * hash: string,
+ * chainId: number,
+ * rpcUrl?: string,
+ * delegation?: object,
+ * }} opts
+ * @returns {Promise<{ valid: boolean, reason?: string }>}
+ * @throws {PermissionError} chain_not_supported (if chain unknown)
+ */
+export async function isDelegationValid({ hash, chainId, rpcUrl, delegation }) {
+ const addr = managerAddress(chainId); // throws if unsupported
+
+ const url = rpcUrl ?? (typeof process !== 'undefined' ? process.env[`RPC_URL_${chainId}`] : undefined);
+ if (!url) return { valid: false, reason: 'no rpcUrl provided for on-chain check' };
+
+ try {
+ const provider = new JsonRpcProvider(url);
+ const dm = new Contract(addr, DELEGATION_MANAGER_ABI, provider);
+
+ const disabled = await dm.disabledDelegations(hash);
+ if (disabled) return { valid: false, reason: 'delegation_revoked' };
+
+ // Expiry check if full delegation object available.
+ if (delegation?.expiry) {
+ if (delegation.expiry <= Math.floor(Date.now() / 1000)) {
+ return { valid: false, reason: 'delegation_expired' };
+ }
+ }
+
+ // Signature recovery check if full delegation object available.
+ if (delegation?.signature && delegation?.delegator) {
+ const verifyingContract = addr;
+ const domain = EIP712_DOMAIN({ chainId, verifyingContract });
+ const typedValue = {
+ delegate: delegation.delegate,
+ delegator: delegation.delegator,
+ authority: delegation.authority ?? ROOT_AUTHORITY,
+ caveats: delegation.caveats,
+ salt: delegation.salt,
+ };
+ const recovered = TypedDataEncoder.recoverAddress(domain, DELEGATION_TYPES, typedValue, delegation.signature);
+ if (recovered.toLowerCase() !== delegation.delegator.toLowerCase()) {
+ return { valid: false, reason: 'signature_invalid' };
+ }
+ }
+
+ return { valid: true };
+ } catch (err) {
+ return { valid: false, reason: err.message };
+ }
+}
+
+/**
+ * Map a signed delegation into the manifest permissions.delegations[] shape.
+ * Pure and synchronous — no network I/O.
+ *
+ * @param {{
+ * chainId: number,
+ * delegator: string,
+ * delegate: string,
+ * hash: string,
+ * uri?: string,
+ * scope?: { token: string, maxAmount: string, period: string, targets: string[], expiry: number },
+ * expiry?: number,
+ * }} signedDelegation
+ * @returns {{
+ * chainId: number,
+ * delegator: string,
+ * delegate: string,
+ * hash: string,
+ * uri?: string,
+ * scope: { token: string, maxAmount: string, period: string, targets: string[], expiry: number },
+ * }}
+ */
+export function delegationToManifestEntry(signedDelegation) {
+ const { chainId, delegator, delegate, hash, uri, scope, expiry } = signedDelegation;
+ return {
+ chainId,
+ delegator,
+ delegate,
+ hash,
+ ...(uri ? { uri } : {}),
+ scope: scope ?? {
+ token: 'native',
+ maxAmount: '0',
+ period: 'once',
+ targets: [],
+ expiry: expiry ?? 0,
+ },
+ };
+}
+
+export { CAVEAT_ENFORCERS };
diff --git a/src/runtime/delegation-redeem.js b/src/runtime/delegation-redeem.js
new file mode 100644
index 000000000..33c1b36c5
--- /dev/null
+++ b/src/runtime/delegation-redeem.js
@@ -0,0 +1,386 @@
+/**
+ * Delegation Redeem Hook
+ * ----------------------
+ * Runtime adapter: skills call redeemFromSkill() and this module handles
+ * delegation lookup, path selection (client vs relayer), pre-flight validation,
+ * protocol bus events, and a per-tab rate limiter.
+ *
+ * Does NOT import viewer or three.js modules.
+ * Does NOT use localStorage — cache is in-memory only.
+ */
+
+import { protocol, ACTION_TYPES } from '../agent-protocol.js';
+
+// ── Rate limiter (token bucket, per tab) ──────────────────────────────────────
+
+const RATE_LIMIT_MAX = 5;
+const RATE_LIMIT_WINDOW_MS = 60_000;
+
+/** @type {{ timestamps: number[] }} */
+const _rateState = { timestamps: [] };
+
+function _checkRateLimit() {
+ const now = Date.now();
+ const cutoff = now - RATE_LIMIT_WINDOW_MS;
+ _rateState.timestamps = _rateState.timestamps.filter((t) => t > cutoff);
+ if (_rateState.timestamps.length >= RATE_LIMIT_MAX) {
+ throw new Error('rate_limited');
+ }
+ _rateState.timestamps.push(now);
+}
+
+// ── Delegation cache (memory-only, 60s TTL) ───────────────────────────────────
+
+const CACHE_TTL_MS = 60_000;
+
+/** @type {Map<string, { envelopes: any[], ts: number }>} */
+const _delegationCache = new Map();
+
+// Invalidate on successful revoke events from the bus
+protocol.on('permissions.revoke', (action) => {
+ const { agentId, chainId } = action.payload || {};
+ if (agentId && chainId) {
+ _delegationCache.delete(`${agentId}:${chainId}`);
+ }
+});
+
+// ── Delegation selection ──────────────────────────────────────────────────────
+
+/**
+ * @param {any[]} envelopes
+ * @param {{ token?: string, maxAmount?: string | bigint } | undefined} scopeHint
+ */
+function _pickBestDelegation(envelopes, scopeHint) {
+ if (!envelopes?.length) return null;
+ if (!scopeHint) return envelopes[0];
+
+ const { token, maxAmount } = scopeHint;
+ const scored = envelopes
+ .map((env) => {
+ const scope = env.scope || {};
+ const tokenMatch = !token || scope.token === token;
+ let amountOk = true;
+ if (maxAmount && scope.maxAmount) {
+ try {
+ amountOk = BigInt(scope.maxAmount) >= BigInt(maxAmount);
+ } catch {
+ amountOk = false;
+ }
+ }
+ return { env, rank: (tokenMatch ? 2 : 0) + (amountOk ? 1 : 0) };
+ })
+ .sort((a, b) => b.rank - a.rank);
+
+ return scored[0].rank > 0 ? scored[0].env : null;
+}
+
+// ── Public: getActiveDelegation ───────────────────────────────────────────────
+
+/**
+ * Fetch the best matching delegation for an agent, with 60s cache.
+ * @param {{ agentId: string, chainId: string|number, scopeHint?: { token?: string, maxAmount?: string } }} opts
+ * @returns {Promise<object|null>}
+ */
+export async function getActiveDelegation({ agentId, chainId, scopeHint } = {}) {
+ const key = `${agentId}:${chainId}`;
+ const cached = _delegationCache.get(key);
+ if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {
+ return _pickBestDelegation(cached.envelopes, scopeHint);
+ }
+
+ const url = `/api/permissions/metadata?agentId=${encodeURIComponent(agentId)}&chainId=${encodeURIComponent(chainId)}`;
+ let res;
+ try {
+ res = await fetch(url);
+ } catch (err) {
+ return null;
+ }
+ if (!res.ok) return null;
+
+ const data = await res.json().catch(() => null);
+ if (!data) return null;
+
+ const envelopes = Array.isArray(data) ? data : (data.delegations ?? []);
+ _delegationCache.set(key, { envelopes, ts: Date.now() });
+ return _pickBestDelegation(envelopes, scopeHint);
+}
+
+// ── Pre-flight scope validation ───────────────────────────────────────────────
+
+/**
+ * Returns an error string if any call violates the delegation scope, else null.
+ * @param {any[]} calls
+ * @param {object | undefined} scope
+ */
+function _validateCallsAgainstScope(calls, scope) {
+ if (!scope || !calls?.length) return null;
+
+ const { targets, maxAmount } = scope;
+ for (const call of calls) {
+ if (targets?.length && call.to && !targets.includes(call.to)) {
+ return `Call target ${call.to} not in allowed scope targets`;
+ }
+ if (maxAmount && call.value != null) {
+ try {
+ if (BigInt(call.value) > BigInt(maxAmount)) {
+ return `Call value ${call.value} exceeds scope maxAmount ${maxAmount}`;
+ }
+ } catch {
+ // non-parseable — skip amount check
+ }
+ }
+ }
+ return null;
+}
+
+// ── Relayer token resolution ──────────────────────────────────────────────────
+
+function _getRelayerToken(agentId) {
+ if (typeof window === 'undefined') return null;
+ return (
+ window.__AGENT_RUNTIME_CONFIG__?.[agentId]?.relayerToken ??
+ window.__AGENT_RUNTIME_CONFIG__?.relayerToken ??
+ null
+ );
+}
+
+// ── Client-mode redemption ────────────────────────────────────────────────────
+
+async function _redeemClient(delegation, calls) {
+ // Prefer the permissions toolkit when available (task 04)
+ try {
+ const { redeemDelegation } = await import('../permissions/toolkit.js');
+ return redeemDelegation(delegation, calls);
+ } catch {
+ // Toolkit not yet installed — fall back to direct ethers call
+ }
+
+ if (typeof window === 'undefined' || !window.ethereum) {
+ throw new Error('no_wallet');
+ }
+
+ const { ethers } = await import('ethers');
+ const provider = new ethers.BrowserProvider(window.ethereum);
+ const signer = await provider.getSigner();
+
+ // Minimal ERC-7710 redeemDelegations call
+ const abi = [
+ 'function redeemDelegations(bytes[] calldata _permissionContexts, bytes32[] calldata _modes, bytes[] calldata _executionCallDatas) external payable',
+ ];
+ const contract = new ethers.Contract(delegation.delegatorAddress, abi, signer);
+
+ const encodedDelegation = ethers.hexlify(
+ typeof delegation.envelope === 'string'
+ ? ethers.toUtf8Bytes(delegation.envelope)
+ : delegation.envelope,
+ );
+
+ const encodedCalls = calls.map((c) => {
+ const target = c.to ?? c.target ?? ethers.ZeroAddress;
+ const value = c.value ?? 0n;
+ const data = c.data ?? '0x';
+ return ethers.AbiCoder.defaultAbiCoder().encode(
+ ['address', 'uint256', 'bytes'],
+ [target, value, data],
+ );
+ });
+
+ // SINGLE execution mode (0x01000000)
+ const modes = calls.map(() => ethers.zeroPadValue('0x01000000', 32));
+
+ const tx = await contract.redeemDelegations(
+ [encodedDelegation],
+ modes,
+ encodedCalls,
+ );
+ const receipt = await tx.wait();
+ return receipt.hash;
+}
+
+// ── Relayer-mode redemption ───────────────────────────────────────────────────
+
+async function _redeemRelayer(delegation, calls, agentId, chainId, skillId) {
+ const token = _getRelayerToken(agentId);
+ if (!token) throw new Error('no_relayer_token');
+
+ const res = await fetch('/api/permissions/redeem', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({ delegation, calls, agentId, chainId, skillId }),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({ message: res.statusText }));
+ throw new Error(body.message || `Relayer returned ${res.status}`);
+ }
+
+ const data = await res.json();
+ if (!data.txHash) throw new Error('Relayer response missing txHash');
+ return data.txHash;
+}
+
+// ── Public: redeemFromSkill ───────────────────────────────────────────────────
+
+/**
+ * The main entrypoint for skills. Handles path selection, pre-flight, events, and errors.
+ * @param {{
+ * agentId: string,
+ * chainId: string|number,
+ * calls: Array<{ to: string, value?: bigint, data?: string }>,
+ * skillId: string,
+ * mode?: 'client' | 'relayer' | 'auto',
+ * }} opts
+ * @returns {Promise<{ ok: true, txHash: string } | { ok: false, code: string, message: string }>}
+ */
+export async function redeemFromSkill({ agentId, chainId, calls, skillId, mode = 'auto' } = {}) {
+ // Rate limit — never hits the network when exceeded
+ try {
+ _checkRateLimit();
+ } catch {
+ const code = 'rate_limited';
+ const message = 'Too many redemption attempts — max 5 per minute per tab';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message };
+ }
+
+ // Pre-flight: delegation existence
+ const delegation = await getActiveDelegation({ agentId, chainId });
+ if (!delegation) {
+ const code = 'no_delegation';
+ const message = 'No active delegation found for this agent/chain';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message };
+ }
+
+ // Pre-flight: scope validation (cheap, prevents wasted gas)
+ const scopeErr = _validateCallsAgainstScope(calls, delegation.scope);
+ if (scopeErr) {
+ const code = 'scope_violation';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message: scopeErr, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message: scopeErr };
+ }
+
+ // Resolve auto mode
+ let resolvedMode = mode;
+ if (mode === 'auto') {
+ const hasWallet = typeof window !== 'undefined' && !!window.ethereum;
+ const hasToken = !!_getRelayerToken(agentId);
+ if (hasWallet) resolvedMode = 'client';
+ else if (hasToken) resolvedMode = 'relayer';
+ else {
+ const code = 'no_redemption_path';
+ const message = 'No wallet connected and no relayer token available';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message };
+ }
+ }
+
+ if (resolvedMode === 'client' && (typeof window === 'undefined' || !window.ethereum)) {
+ const code = 'no_wallet';
+ const message = 'client mode requires a connected wallet';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message };
+ }
+
+ if (resolvedMode === 'relayer' && !_getRelayerToken(agentId)) {
+ const code = 'no_relayer_token';
+ const message = 'relayer mode requires a bearer token in runtime config';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message };
+ }
+
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_START,
+ payload: {
+ agentId,
+ chainId,
+ skillId,
+ mode: resolvedMode,
+ delegationHash: delegation.hash,
+ },
+ agentId,
+ sourceSkill: skillId,
+ });
+
+ try {
+ let txHash;
+ if (resolvedMode === 'client') {
+ txHash = await _redeemClient(delegation, calls);
+ } else {
+ txHash = await _redeemRelayer(delegation, calls, agentId, chainId, skillId);
+ }
+
+ // Invalidate cache — balance has changed
+ _delegationCache.delete(`${agentId}:${chainId}`);
+
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_SUCCESS,
+ payload: { txHash, skillId, delegationHash: delegation.hash },
+ agentId,
+ sourceSkill: skillId,
+ });
+
+ return { ok: true, txHash };
+ } catch (err) {
+ const code = err.message || 'unknown_error';
+ protocol.emit({
+ type: ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ payload: { code, message: err.message, skillId },
+ agentId,
+ sourceSkill: skillId,
+ });
+ return { ok: false, code, message: err.message };
+ }
+}
+
+// ── Public: subscribeRedeemEvents ─────────────────────────────────────────────
+
+/**
+ * Subscribe to all redemption lifecycle events. Returns an unsubscribe function.
+ * @param {(action: import('../agent-protocol.js').ActionPayload) => void} handler
+ * @returns {() => void} unsubscribe
+ */
+export function subscribeRedeemEvents(handler) {
+ const types = [
+ ACTION_TYPES.PERMISSIONS_REDEEM_START,
+ ACTION_TYPES.PERMISSIONS_REDEEM_SUCCESS,
+ ACTION_TYPES.PERMISSIONS_REDEEM_ERROR,
+ ];
+ // Use addEventListener directly to avoid __protocolWrapped collision across types
+ const wrapped = (e) => handler(e.detail);
+ types.forEach((t) => protocol.addEventListener(t, wrapped));
+ return () => types.forEach((t) => protocol.removeEventListener(t, wrapped));
+}
diff --git a/vercel.json b/vercel.json
index 3a329c677..fb3e1426e 100644
--- a/vercel.json
+++ b/vercel.json
@@ -106,6 +106,9 @@
{ "src": "/api/erc8004/hydrate", "dest": "/api/erc8004/hydrate.js" },
{ "src": "/api/erc8004/import", "dest": "/api/erc8004/import.js" },
+ { "src": "/api/dca-strategies/([^/]+)", "dest": "/api/dca-strategies?id=$1" },
+ { "src": "/api/dca-strategies", "dest": "/api/dca-strategies" },
+
{ "src": "/discover", "dest": "/public/discover/index.html" },
{ "src": "/discover/", "dest": "/public/discover/index.html" },
@@ -167,5 +170,10 @@
{ "src": "/a/(.*)", "dest": "/app.html" },
{ "src": "/(.*)", "dest": "/public/$1" }
],
- "crons": [{ "path": "/api/cron/erc8004-crawl", "schedule": "*/15 * * * *" }]
+ "crons": [
+ { "path": "/api/cron/erc8004-crawl", "schedule": "*/15 * * * *" },
+ { "path": "/api/cron/index-delegations", "schedule": "*/5 * * * *" },
+ { "path": "/api/cron/run-dca", "schedule": "0 * * * *" },
+ { "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" }
+ ]
}