Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: monetization v2, eth vanity chains/wordlist, artifact viewer, validation, marketplace overhaul
nirholase6d7674121fb
diff --git a/api/_lib/csrf.js b/api/_lib/csrf.jsnew file mode 100644index 000000000..e7a98975f--- /dev/null+++ b/api/_lib/csrf.js@@ -0,0 +1,54 @@+// CSRF protection — double-submit cookie pattern.+//+// Issue a token via GET /api/csrf-token (also returns it via Set-Cookie). Clients+// must echo the same token in the X-CSRF-Token header on state-changing POSTs.+// Tokens are bound to user_id and expire after 1 hour.++import crypto from 'node:crypto';+import { sql } from './db.js';+import { error } from './http.js';++const TTL_SECONDS = 3600;++export async function issueCsrf(userId) {+ const token = crypto.randomBytes(32).toString('hex');+ await sql`+ INSERT INTO csrf_tokens (token, user_id, expires_at)+ VALUES (${token}, ${userId}, now() + interval '1 hour')+ `;+ return { token, expiresIn: TTL_SECONDS };+}++// Middleware: returns true on success (handler may proceed), or sends a 403+// and returns false. Skips enforcement if CSRF_DISABLED=1 (escape hatch for+// machine-to-machine bearer auth which can't carry a CSRF token).+export async function requireCsrf(req, res, userId) {+ if (process.env.CSRF_DISABLED === '1') return true;++ // Bearer-token requests are exempt: the token itself is the proof of intent+ // and bearer tokens aren't auto-attached by browsers like cookies are.+ const authHeader = req.headers?.authorization || '';+ if (authHeader.startsWith('Bearer ')) return true;++ const sent =+ req.headers['x-csrf-token'] ||+ req.headers['X-CSRF-Token'] ||+ (typeof req.body === 'object' && req.body?._csrf);+ if (!sent || typeof sent !== 'string') {+ error(res, 403, 'csrf_missing', 'X-CSRF-Token header required');+ return false;+ }++ const [row] = await sql`+ SELECT user_id FROM csrf_tokens+ WHERE token = ${sent} AND expires_at > now()+ `;+ if (!row || row.user_id !== userId) {+ error(res, 403, 'csrf_invalid', 'CSRF token invalid or expired');+ return false;+ }++ // One-time use: best-effort delete (don't fail the request if delete has issues)+ sql`DELETE FROM csrf_tokens WHERE token = ${sent}`.catch(() => {});+ return true;+}diff --git a/api/_lib/migrations/2026-05-10-monetization-v2.sql b/api/_lib/migrations/2026-05-10-monetization-v2.sqlnew file mode 100644index 000000000..4a09e4bbf--- /dev/null+++ b/api/_lib/migrations/2026-05-10-monetization-v2.sql@@ -0,0 +1,85 @@+-- Migration: monetization v2 — trials, time-based access, mint decimals,+-- pending expiry, mismatch handling, A/B-pricing-friendly status enum.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-10-monetization-v2.sql+-- Idempotent.++begin;++-- ── agent_skill_prices: cache mint decimals (A2) and trial allowance (C2) ──+alter table agent_skill_prices+ add column if not exists mint_decimals smallint not null default 6,+ add column if not exists trial_uses integer not null default 0;++-- ── skill_purchases: add trial / time-window / expiry / mismatch state ────+alter table skill_purchases+ add column if not exists expires_at timestamptz, -- A3 pending TTL+ add column if not exists valid_until timestamptz, -- C3 time-bounded access+ add column if not exists trial_remaining integer, -- C2 trial counter+ add column if not exists tipped_amount bigint, -- A6 mismatch-as-tip+ add column if not exists referrer_user_id uuid references users(id), -- C6 referral attribution+ add column if not exists kind text not null default 'purchase'+ check (kind in ('purchase', 'trial', 'time_pass'));++-- Expand status to include the new lifecycle states. Drop the old check first.+do $$ begin+ alter table skill_purchases drop constraint skill_purchases_status_check;+exception when undefined_object then null; end $$;++alter table skill_purchases+ add constraint skill_purchases_status_check+ check (status in ('pending', 'confirmed', 'failed', 'expired', 'tipped', 'trial'));++-- The unique-confirmed-per-user index needs to also count 'trial' as ownership+-- so a user can't have both a confirmed purchase AND an active trial duplicating it.+drop index if exists skill_purchases_one_confirmed_per_user;+create unique index if not exists skill_purchases_one_active_per_user+ on skill_purchases (user_id, agent_id, skill)+ where status in ('confirmed', 'trial');++create index if not exists skill_purchases_expires_at+ on skill_purchases (expires_at)+ where status = 'pending' and expires_at is not null;++-- ── purchase_receipts: signed, append-only receipts (C4) ──────────────────+create table if not exists purchase_receipts (+ id uuid primary key default gen_random_uuid(),+ purchase_id uuid not null references skill_purchases(id) on delete cascade,+ receipt_json jsonb not null,+ signature text not null, -- HMAC-SHA256 over canonical receipt_json+ created_at timestamptz not null default now(),+ unique (purchase_id)+);++create index if not exists purchase_receipts_created_at+ on purchase_receipts (created_at desc);++-- ── purchase_events: funnel telemetry (Phase D / professional grade) ──────+create table if not exists purchase_events (+ id bigserial primary key,+ purchase_id uuid references skill_purchases(id) on delete cascade,+ event text not null,+ payload jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++create index if not exists purchase_events_purchase+ on purchase_events (purchase_id, created_at desc);++create index if not exists purchase_events_event_time+ on purchase_events (event, created_at desc);++-- ── csrf_tokens: lightweight double-submit cookie pattern (A5) ────────────+create table if not exists csrf_tokens (+ token text primary key,+ user_id uuid not null references users(id) on delete cascade,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists csrf_tokens_user+ on csrf_tokens (user_id, expires_at desc);++create index if not exists csrf_tokens_expires+ on csrf_tokens (expires_at);++commit;diff --git a/api/_lib/model-inspect.js b/api/_lib/model-inspect.jsindex 37597b0f3..fa6fe500c 100644--- a/api/_lib/model-inspect.js+++ b/api/_lib/model-inspect.js@@ -1,232 +1,5 @@-// Model inspection + optimization suggestions using glTF-Transform.-//-// Runs in a Vercel Node function. Input is raw bytes (Uint8Array) of either-// a binary GLB or a JSON glTF. Output is a structured summary suitable for-// MCP tool responses.+// Server-side re-export of the isomorphic glTF inspector. The canonical+// implementation lives in src/gltf-inspect.js so the browser /validation page+// and Vercel serverless functions share one code path.-import { WebIO } from '@gltf-transform/core';-import { ALL_EXTENSIONS } from '@gltf-transform/extensions';--const GLB_MAGIC = 0x46546c67; // "glTF"--function isGLB(bytes) {- if (!bytes || bytes.byteLength < 4) return false;- const view = new DataView(bytes.buffer, bytes.byteOffset, Math.min(4, bytes.byteLength));- return view.getUint32(0, true) === GLB_MAGIC;-}--async function readDocument(bytes) {- const io = new WebIO().registerExtensions(ALL_EXTENSIONS);- if (isGLB(bytes)) return io.readBinary(bytes);- // Fall back to JSON glTF (rare, usually requires external buffers we don't have).- const text = new TextDecoder().decode(bytes);- let json;- try {- json = JSON.parse(text);- } catch {- throw new Error('input is not a valid GLB or JSON glTF');- }- return io.readJSON({ json, resources: {} });-}--/**- * Inspect a model's structure. Pure stats — no optimization advice.- * @param {Uint8Array} bytes- * @param {{ fileSize?: number }} opts- */-export async function inspectModel(bytes, opts = {}) {- const doc = await readDocument(bytes);- const root = doc.getRoot();- const asset = root.getAsset();-- const meshes = root.listMeshes();- const materials = root.listMaterials();- const textures = root.listTextures();- const animations = root.listAnimations();- const nodes = root.listNodes();- const scenes = root.listScenes();- const skins = root.listSkins();-- let totalVertices = 0;- let totalTriangles = 0;- let indexedPrimitives = 0;- let nonIndexedPrimitives = 0;- const primitiveModes = new Set();-- for (const mesh of meshes) {- for (const prim of mesh.listPrimitives()) {- const pos = prim.getAttribute('POSITION');- const verts = pos ? pos.getCount() : 0;- totalVertices += verts;- const idx = prim.getIndices();- if (idx) {- indexedPrimitives++;- totalTriangles += Math.floor(idx.getCount() / 3);- } else {- nonIndexedPrimitives++;- totalTriangles += Math.floor(verts / 3);- }- primitiveModes.add(prim.getMode());- }- }-- const textureDetails = textures.map((tex) => {- const img = tex.getImage();- const size = tex.getSize();- const [w, h] = size || [0, 0];- return {- name: tex.getName() || null,- mimeType: tex.getMimeType(),- width: w,- height: h,- byteSize: img ? img.byteLength : 0,- };- });-- const materialSummary = materials.map((m) => ({- name: m.getName() || null,- alphaMode: m.getAlphaMode(),- doubleSided: m.getDoubleSided(),- hasBaseColorTexture: !!m.getBaseColorTexture(),- hasNormalTexture: !!m.getNormalTexture(),- hasMetallicRoughnessTexture: !!m.getMetallicRoughnessTexture(),- hasEmissiveTexture: !!m.getEmissiveTexture(),- hasOcclusionTexture: !!m.getOcclusionTexture(),- }));-- return {- fileSize: opts.fileSize ?? bytes.byteLength,- container: isGLB(bytes) ? 'glb' : 'gltf',- generator: asset.generator || null,- version: asset.version || null,- copyright: asset.copyright || null,- extensionsUsed: root.listExtensionsUsed().map((x) => x.extensionName),- extensionsRequired: root.listExtensionsRequired().map((x) => x.extensionName),- counts: {- scenes: scenes.length,- nodes: nodes.length,- meshes: meshes.length,- materials: materials.length,- textures: textures.length,- animations: animations.length,- skins: skins.length,- totalVertices,- totalTriangles,- indexedPrimitives,- nonIndexedPrimitives,- },- primitiveModes: [...primitiveModes],- textures: textureDetails,- materials: materialSummary,- };-}--/**- * Offer optimization suggestions based on structural analysis.- * Each suggestion has a severity (info|warn|critical), id, message, and- * optional estimate of impact.- *- * @param {Awaited<ReturnType<typeof inspectModel>>} info- * @returns {Array<{ id: string, severity: 'info'|'warn'|'critical', message: string, estimate?: string }>}- */-export function suggestOptimizations(info) {- const out = [];- const c = info.counts;-- if (c.totalTriangles > 500_000) {- out.push({- id: 'tri_budget',- severity: 'warn',- message: `Model has ${c.totalTriangles.toLocaleString()} triangles — consider mesh decimation or LODs for web delivery.`,- });- }-- if (!info.extensionsUsed.includes('KHR_draco_mesh_compression') && c.totalVertices > 50_000) {- out.push({- id: 'draco',- severity: 'info',- message: 'Apply Draco compression to geometry for ~60-80% smaller vertex buffers.',- estimate: `~${Math.round((c.totalVertices * 12) / 1024)} KB potential savings`,- });- }-- if (!info.extensionsUsed.includes('EXT_meshopt_compression') && c.totalVertices > 50_000) {- out.push({- id: 'meshopt',- severity: 'info',- message:- 'Meshopt compression can reduce vertex+index size with faster decode than Draco.',- });- }-- const bigTextures = info.textures.filter((t) => Math.max(t.width, t.height) >= 4096);- if (bigTextures.length > 0) {- out.push({- id: 'texture_oversized',- severity: 'warn',- message: `${bigTextures.length} texture(s) at ≥4K. Resize to 2048px for web unless hero detail is required.`,- });- }-- const pngTextures = info.textures.filter((t) => t.mimeType === 'image/png');- if (pngTextures.length > 0 && !info.extensionsUsed.includes('KHR_texture_basisu')) {- out.push({- id: 'texture_basisu',- severity: 'info',- message:- 'Transcode PNG textures to KTX2 (Basis Universal) for GPU-direct upload and smaller download.',- });- }-- if (c.nonIndexedPrimitives > 0) {- out.push({- id: 'non_indexed',- severity: 'info',- message: `${c.nonIndexedPrimitives} primitive(s) are non-indexed — re-indexing typically reduces vertex count by 2-3×.`,- });- }-- const unusedMaterials = info.materials.length - Math.min(info.materials.length, c.meshes);- if (info.materials.length > c.meshes * 2 && c.meshes > 0) {- out.push({- id: 'too_many_materials',- severity: 'info',- message: `${info.materials.length} materials for ${c.meshes} meshes. Merging identical materials can reduce draw calls.`,- });- }-- const totalTextureBytes = info.textures.reduce((a, t) => a + t.byteSize, 0);- if (totalTextureBytes > 20 * 1024 * 1024) {- out.push({- id: 'texture_weight',- severity: 'warn',- message: `Textures alone weigh ${(totalTextureBytes / 1024 / 1024).toFixed(1)} MB — combine with KTX2 compression and resize for web.`,- });- }-- if (info.fileSize > 25 * 1024 * 1024) {- out.push({- id: 'file_size',- severity: 'warn',- message: `Overall file size ${(info.fileSize / 1024 / 1024).toFixed(1)} MB is heavy for web delivery; target <10 MB.`,- });- }-- if (c.animations > 0 && c.skins === 0) {- out.push({- id: 'anim_without_skin',- severity: 'info',- message: `${c.animations} animation(s) without skins — confirm these are node-level and not orphan data.`,- });- }-- if (out.length === 0) {- out.push({- id: 'ok',- severity: 'info',- message: 'Model looks well-optimized for web delivery — no suggestions flagged.',- });- }-- return out;-}+export { inspectModel, suggestOptimizations } from '../../src/gltf-inspect.js';diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsnew file mode 100644index 000000000..0f8fbccfb--- /dev/null+++ b/api/_lib/purchase-confirm.js@@ -0,0 +1,327 @@+// Skill-purchase confirmation pipeline.+//+// Both /api/marketplace/purchase/:reference/confirm and the off-web webhook+// at /api/webhooks/solana-pay execute the same critical-path logic:+//+// 1. Resolve the purchase + payout wallet.+// 2. Locate the on-chain tx via Solana Pay reference.+// 3. validateTransfer (strict).+// ✓ match — atomic confirm + ledger writes + receipts + notifications + referral split.+// ✗ found-but-mismatched — fall back to inspecting the parsed tx; if any USDC of any+// amount actually moved to the seller's wallet attached to our reference, mark the+// row 'tipped' with the actual amount and notify the seller. Buyer's funds did not+// vanish — pretending they did is a worse failure than acknowledging it.+// 4. Emit a signed receipt (HMAC-SHA256 over canonical JSON).+//+// Called from server endpoints; not user-facing.++import crypto from 'node:crypto';+import { PublicKey } from '@solana/web3.js';+import { findReference, validateTransfer } from '@solana/pay';+import BigNumber from 'bignumber.js';++import { sql } from './db.js';+import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';+import { insertNotification } from './notify.js';++let _rpc;+function rpc() {+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });+ return _rpc;+}++// HMAC key for receipts. Falls back to a derived value off SESSION_SECRET if+// PURCHASE_RECEIPT_KEY isn't set, so receipts still work in dev.+function receiptKey() {+ return (+ process.env.PURCHASE_RECEIPT_KEY ||+ crypto.createHash('sha256').update((process.env.SESSION_SECRET || 'dev') + ':receipts').digest('hex')+ );+}++// Default referral commission: 5%. Set REFERRAL_COMMISSION_BPS in env to tune.+function referralBps() {+ const v = parseInt(process.env.REFERRAL_COMMISSION_BPS || '500', 10);+ return Number.isFinite(v) && v >= 0 && v <= 10000 ? v : 500;+}++export async function logEvent(referenceOrPurchaseId, event, payload = {}) {+ try {+ await sql`+ INSERT INTO purchase_events (purchase_id, event, payload)+ VALUES (+ (SELECT id FROM skill_purchases+ WHERE reference = ${referenceOrPurchaseId} OR id::text = ${referenceOrPurchaseId}+ LIMIT 1),+ ${event},+ ${JSON.stringify(payload)}::jsonb+ )+ `;+ } catch (e) {+ console.error('[purchase-confirm] logEvent', e?.message);+ }+}++// Public: resolve the seller's payout address for an agent + chain. Used by+// purchase create AND confirm so a single source of truth.+export async function resolvePayoutAddress(agentId, chain) {+ const [row] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = ${chain}+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;+ return row?.address ?? null;+}++// Sign a receipt body. The signature covers the canonical JSON (sorted keys).+function signReceipt(body) {+ const canonical = JSON.stringify(body, Object.keys(body).sort());+ return crypto.createHmac('sha256', receiptKey()).update(canonical).digest('hex');+}++async function emitReceipt(purchase, txSignature, payoutAddress, kind) {+ const body = {+ v: 1,+ kind,+ purchase_id: purchase.id,+ reference: purchase.reference,+ user_id: purchase.user_id,+ agent_id: purchase.agent_id,+ skill: purchase.skill,+ amount: String(purchase.amount),+ currency_mint: purchase.currency_mint,+ chain: purchase.chain,+ recipient: payoutAddress,+ tx_signature: txSignature,+ issued_at: new Date().toISOString(),+ };+ const signature = signReceipt(body);+ await sql`+ INSERT INTO purchase_receipts (purchase_id, receipt_json, signature)+ VALUES (${purchase.id}, ${JSON.stringify(body)}::jsonb, ${signature})+ ON CONFLICT (purchase_id) DO NOTHING+ `;+ return { body, signature };+}++// Inspect an actual transfer instruction on-chain so we can tell if the buyer+// paid SOMETHING with our reference, even if the amount/mint didn't match.+async function findReferencedTransferAmount(txSignature, recipient, splTokenMint) {+ const tx = await rpc().withFallback((conn) =>+ conn.getParsedTransaction(txSignature, {+ commitment: 'confirmed',+ maxSupportedTransactionVersion: 0,+ }),+ );+ if (!tx || tx.meta?.err) return null;++ const recipientStr = recipient.toBase58();+ const mintStr = splTokenMint.toBase58();++ const ixs = tx.transaction.message.instructions;+ for (const ix of ixs) {+ if (!('parsed' in ix)) continue;+ const t = ix.parsed?.type;+ const info = ix.parsed?.info;+ if (!info) continue;+ const goesToOurWallet =+ info.destination === recipientStr || info.destinationOwner === recipientStr;+ if (!goesToOurWallet) continue;++ if (t === 'transferChecked' && info.mint === mintStr) {+ return BigInt(info.tokenAmount?.amount ?? '0');+ }+ if (t === 'transfer') {+ // Untyped SPL transfer — amount is in raw units. Trust the mint match+ // must come from the validateTransfer pre-check; here we just record.+ return BigInt(info.amount ?? '0');+ }+ }+ return null;+}++/**+ * Run confirm for a single skill_purchases row.+ * @param {object} pur — the row, must include id, user_id, agent_id, skill,+ * amount, currency_mint, chain, mint_decimals, status,+ * referrer_user_id (optional).+ * @returns {Promise<{ status: 'pending' | 'confirmed' | 'tipped' | 'mismatch' | 'expired',+ * tx_signature?: string, tipped_amount?: string, message?: string }>}+ */+export async function confirmSkillPurchase(pur) {+ if (pur.status === 'confirmed') {+ return { status: 'confirmed', tx_signature: pur.tx_signature };+ }+ if (pur.status === 'expired' || (pur.expires_at && new Date(pur.expires_at) < new Date())) {+ return { status: 'expired' };+ }+ if (pur.chain !== 'solana') {+ throw new Error(`chain '${pur.chain}' not supported`);+ }++ const payoutAddress = await resolvePayoutAddress(pur.agent_id, pur.chain);+ if (!payoutAddress) throw new Error('payout wallet not configured');++ const refKey = new PublicKey(pur.reference);+ const recipient = new PublicKey(payoutAddress);+ const splToken = new PublicKey(pur.currency_mint);+ const decimals = pur.mint_decimals ?? 6;+ const expectedAmount = new BigNumber(pur.amount).dividedBy(new BigNumber(10).pow(decimals));++ // 1. Find the on-chain tx via reference.+ let signatureInfo;+ try {+ signatureInfo = await rpc().withFallback((conn) =>+ findReference(conn, refKey, { finality: 'confirmed' }),+ );+ } catch (e) {+ if (/FindReferenceError|not found/i.test(e?.message || '')) {+ return { status: 'pending' };+ }+ throw e;+ }+ const txSignature = signatureInfo.signature;++ // 2. Strict validation.+ try {+ await rpc().withFallback((conn) =>+ validateTransfer(+ conn,+ txSignature,+ { recipient, amount: expectedAmount, splToken, reference: refKey },+ { commitment: 'confirmed' },+ ),+ );+ } catch (e) {+ // 2a. Mismatch — but the transfer happened. Mark as tipped if we can pin down+ // the actual amount that hit the seller's wallet.+ const actual = await findReferencedTransferAmount(txSignature, recipient, splToken);+ if (actual !== null) {+ await sql`+ UPDATE skill_purchases+ SET status = 'tipped', tx_signature = ${txSignature},+ tipped_amount = ${actual.toString()}, confirmed_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ await emitReceipt(pur, txSignature, payoutAddress, 'tipped');+ await logEvent(pur.id, 'tipped', { actual: actual.toString(), expected: pur.amount, reason: e.message });+ // Notify seller — they got SOMETHING; let them know it was a mismatch+ // so they can decide whether to grant access manually.+ await getSellerUserId(pur.agent_id).then((sellerId) => {+ if (!sellerId) return;+ return insertNotification(sellerId, 'skill_payment_mismatch', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ expected_amount: String(pur.amount),+ actual_amount: actual.toString(),+ tx_signature: txSignature,+ purchase_id: pur.id,+ });+ });+ return { status: 'tipped', tx_signature: txSignature, tipped_amount: actual.toString(), message: e.message };+ }++ // 2b. No matching transfer at all — mark failed, no on-chain side effect.+ await sql`+ UPDATE skill_purchases+ SET status = 'failed', tx_signature = ${txSignature}+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ await logEvent(pur.id, 'mismatch_no_transfer', { reason: e.message });+ return { status: 'mismatch', message: e.message };+ }++ // 3. Match. Atomic confirm + ledger writes.+ const intentId = `sp_${pur.id}`;+ const updated = await sql`+ UPDATE skill_purchases+ SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ RETURNING id+ `;+ if (updated.length > 0) {+ await sql`+ INSERT INTO agent_payment_intents+ (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at,+ cluster, tx_signature, paid_at, payload)+ VALUES+ (${intentId}, ${pur.user_id}, ${pur.agent_id}, ${pur.currency_mint},+ ${String(pur.amount)}, 'confirmed', now() + interval '30 days',+ 'mainnet', ${txSignature}, now(),+ ${JSON.stringify({ kind: 'skill_purchase', skill: pur.skill, reference: pur.reference })}::jsonb)+ ON CONFLICT (id) DO NOTHING+ `;++ // 3a. Referral commission split (C6).+ const grossAmt = BigInt(pur.amount);+ let referralAmt = 0n;+ if (pur.referrer_user_id) {+ referralAmt = (grossAmt * BigInt(referralBps())) / 10000n;+ }+ const netAmt = grossAmt - referralAmt;+ await sql`+ INSERT INTO agent_revenue_events+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,+ currency_mint, chain, payer_address)+ VALUES+ (${pur.agent_id}, ${intentId}, ${pur.skill},+ ${grossAmt.toString()}, ${referralAmt.toString()}, ${netAmt.toString()},+ ${pur.currency_mint}, ${pur.chain}, ${payoutAddress})+ `;+ if (pur.referrer_user_id && referralAmt > 0n) {+ // Track the referrer's accrued earnings. Real payout happens via the+ // existing withdrawal flow keyed off this column.+ await sql`+ UPDATE users+ SET referral_earnings_total = COALESCE(referral_earnings_total, 0) + ${Number(referralAmt)}+ WHERE id = ${pur.referrer_user_id}+ `;+ }++ await emitReceipt(pur, txSignature, payoutAddress, 'purchase');+ await logEvent(pur.id, 'confirmed', { tx_signature: txSignature });++ // 3b. Notifications.+ const sellerId = await getSellerUserId(pur.agent_id);+ if (sellerId) {+ await insertNotification(sellerId, 'skill_purchased', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ gross_amount: grossAmt.toString(),+ net_amount: netAmt.toString(),+ currency_mint: pur.currency_mint,+ tx_signature: txSignature,+ purchase_id: pur.id,+ });+ }+ await insertNotification(pur.user_id, 'skill_purchase_confirmed', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ amount: grossAmt.toString(),+ currency_mint: pur.currency_mint,+ tx_signature: txSignature,+ purchase_id: pur.id,+ });+ if (pur.referrer_user_id && referralAmt > 0n) {+ await insertNotification(pur.referrer_user_id, 'referral_earned', {+ skill: pur.skill,+ amount: referralAmt.toString(),+ currency_mint: pur.currency_mint,+ purchase_id: pur.id,+ });+ }+ }++ return { status: 'confirmed', tx_signature: txSignature };+}++async function getSellerUserId(agentId) {+ const [row] = await sql`SELECT user_id FROM agent_identities WHERE id = ${agentId}`;+ return row?.user_id ?? null;+}diff --git a/api/_lib/skill-access.js b/api/_lib/skill-access.jsnew file mode 100644index 000000000..4498bd518--- /dev/null+++ b/api/_lib/skill-access.js@@ -0,0 +1,69 @@+// Skill access — single source of truth for "does user X own skill Y on agent Z?".+//+// Usage: every server endpoint that executes a paid skill should call hasSkillAccess+// before doing the work. Agent-to-agent x402 callers go through verifyPaid in x402.js+// instead; this helper covers the human-buyer / direct-API path.+//+// Returns { paid, owned, price?, reason? }+// paid — boolean: is this skill priced (i.e. requires payment)?+// owned — boolean: does the user have a confirmed (or active trial / valid time-window) purchase?+// price — { skill, amount, currency_mint, chain } when paid; undefined otherwise+// reason — short string when access is denied ('not_purchased' | 'trial_exhausted' | 'expired')++import { sql } from './db.js';++export async function hasSkillAccess(userId, agentId, skill) {+ const [price] = await sql`+ SELECT skill, amount, currency_mint, chain+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill = ${skill} AND is_active = true+ `;+ if (!price) return { paid: false, owned: true };++ if (!userId) return { paid: true, owned: false, price, reason: 'not_purchased' };++ const [purchase] = await sql`+ SELECT status, valid_until, trial_remaining+ FROM skill_purchases+ WHERE user_id = ${userId} AND agent_id = ${agentId} AND skill = ${skill}+ AND status IN ('confirmed', 'trial')+ ORDER BY+ (status = 'confirmed') DESC, -- confirmed beats trial+ confirmed_at DESC NULLS LAST,+ created_at DESC+ LIMIT 1+ `;++ if (!purchase) return { paid: true, owned: false, price, reason: 'not_purchased' };++ if (purchase.status === 'confirmed') {+ // Time-limited access (C3): if valid_until is set, it must be in the future.+ if (purchase.valid_until && new Date(purchase.valid_until) <= new Date()) {+ return { paid: true, owned: false, price, reason: 'expired' };+ }+ return { paid: true, owned: true, price };+ }++ // Trial mode (C2)+ if (purchase.status === 'trial') {+ if ((purchase.trial_remaining ?? 0) <= 0) {+ return { paid: true, owned: false, price, reason: 'trial_exhausted' };+ }+ return { paid: true, owned: true, price, trial: true, trial_remaining: purchase.trial_remaining };+ }++ return { paid: true, owned: false, price, reason: 'not_purchased' };+}++// Decrement trial counter atomically. Caller invokes after a successful trial use.+// Returns the new remaining count, or null if no trial row matched.+export async function consumeTrialUse(userId, agentId, skill) {+ const [row] = await sql`+ UPDATE skill_purchases+ SET trial_remaining = trial_remaining - 1, updated_at = now()+ WHERE user_id = ${userId} AND agent_id = ${agentId} AND skill = ${skill}+ AND status = 'trial' AND trial_remaining > 0+ RETURNING trial_remaining+ `;+ return row?.trial_remaining ?? null;+}diff --git a/api/agent-strategy.js b/api/agent-strategy.jsindex dc760f80c..528a68930 100644--- a/api/agent-strategy.js+++ b/api/agent-strategy.js@@ -1,33 +1,66 @@+/**+ * GET /api/agent-strategy?id=<agent_id> — fetch the strategy JSON stored on this agent.+ * POST /api/agent-strategy?id=<agent_id> — replace it. Body: { strategy: <any JSON> }+ *+ * The strategy is stored under agent_identities.meta.strategy. Owner-only.+ * For typed strategy execution (DCA, etc.) see api/cron/run-dca and the+ * dca_strategies table. This endpoint is the generic "freeform agent+ * configuration" slot.+ */+import { sql } from './_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';+import { cors, error, json, method, readJson, wrap } from './_lib/http.js';+import { clientIp, limits } from './_lib/rate-limit.js';-import { xyz } from '../../src/xyz.js';-import { getDB, send } from '../../_lib/db.js';--export default async function handler(req, res) {- const db = await getDB();- const { id } = req.query;-- if (req.method === 'GET') {- const strategy = await db.collection('strategies').findOne({ agentId: id });- if (!strategy) {- return send(res, 404, { error: 'Strategy not found' });- }- return send(res, 200, strategy);- }-- if (req.method === 'POST' || req.method === 'PUT') {- const { strategy } = req.body;- if (!strategy) {- return send(res, 400, { error: 'Strategy is required' });- }-- const result = await db.collection('strategies').updateOne(- { agentId: id },- { $set: { strategy } },- { upsert: true }- );-- return send(res, 200, { success: true, result });- }-- return send(res, 405, { error: 'Method not allowed' });+async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'PUT'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('id');+ if (!agentId) return error(res, 400, 'validation_error', 'id query param required');++ const [agent] = await sql`+ SELECT id, user_id, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ if (req.method === 'GET') {+ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const strategy = agent.meta?.strategy ?? null;+ if (strategy === null) return error(res, 404, 'not_found', 'no strategy set');+ return json(res, 200, { data: { strategy } });+ }++ // POST / PUT — replace+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = await readJson(req).catch(() => null);+ if (!body || body.strategy === undefined) {+ return error(res, 400, 'validation_error', 'request body must include `strategy`');+ }++ const nextMeta = { ...(agent.meta || {}), strategy: body.strategy };+ await sql`+ UPDATE agent_identities SET meta = ${JSON.stringify(nextMeta)}::jsonb, updated_at = now()+ WHERE id = ${agentId}+ `;++ return json(res, 200, { data: { ok: true, strategy: body.strategy } });+});diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.jsindex 188584e2b..0aee7eb77 100644--- a/api/agents/[id]/memory-seed-x.js+++ b/api/agents/[id]/memory-seed-x.js@@ -4,7 +4,6 @@// Auth: session user must own the agent AND have an active 'x' social_connection.// Rate limit: 1 seed per agent per 6 hours.-import Anthropic from '@anthropic-ai/sdk';import { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';@@ -61,40 +60,54 @@ async function getAccessToken(conn) {// ── Distil tweets → facts via Claude ─────────────────────────────────────────async function distilFacts(profile, tweets) {- const client = new Anthropic({ apiKey: env.ANTHROPIC_API_KEY });const tweetLines = tweets.map((t) => t.text).join('\n');- const msg = await client.messages.create({- model: 'claude-haiku-4-5-20251001',- max_tokens: 1024,- system: 'You distill tweets into concise memory facts for an AI agent. Focus on: recurring topics, strong opinions, projects, communication style, humor.',- messages: [- {- role: 'user',- content: `Profile: @${profile.username} | ${profile.description || ''} | ${profile.public_metrics?.followers_count ?? 0} followers\n\nRecent tweets (newest first):\n${tweetLines}`,- },- ],- tools: [- {- name: 'extract_memory_facts',- description: 'Extract up to 15 concise single-sentence memory facts from the tweets.',- input_schema: {- type: 'object',- properties: {- facts: {- type: 'array',- items: { type: 'string' },- maxItems: 15,+ const res = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'x-api-key': env.ANTHROPIC_API_KEY,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 1024,+ system:+ 'You distill tweets into concise memory facts for an AI agent. ' ++ 'Focus on: recurring topics, strong opinions, projects, communication style, humor.',+ messages: [+ {+ role: 'user',+ content:+ `Profile: @${profile.username} | ${profile.description || ''} | ` ++ `${profile.public_metrics?.followers_count ?? 0} followers\n\n` ++ `Recent tweets (newest first):\n${tweetLines}`,+ },+ ],+ tools: [+ {+ name: 'extract_memory_facts',+ description: 'Extract up to 15 concise single-sentence memory facts from the tweets.',+ input_schema: {+ type: 'object',+ properties: {+ facts: { type: 'array', items: { type: 'string' }, maxItems: 15 },},+ required: ['facts'],},- required: ['facts'],},- },- ],- tool_choice: { type: 'tool', name: 'extract_memory_facts' },+ ],+ tool_choice: { type: 'tool', name: 'extract_memory_facts' },+ }),});- const toolUse = msg.content.find((b) => b.type === 'tool_use');+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new Error(`Claude API error ${res.status}: ${text.slice(0, 200)}`);+ }++ const data = await res.json();+ const toolUse = (data.content || []).find((b) => b.type === 'tool_use');return toolUse?.input?.facts ?? [];}diff --git a/api/agents/eth-vanity.js b/api/agents/eth-vanity.jsindex 5f752e122..6ecbbad41 100644--- a/api/agents/eth-vanity.js+++ b/api/agents/eth-vanity.js@@ -1,27 +1,31 @@// /api/agents/:id/eth-vanity — assign / read / delete a CREATE2 vanity record.+// /api/agents/:id/eth-vanity/deployed — record an on-chain deployment.//// Stores the salt + factory + initCode(Hash) the owner ground in the-// browser at /eth-vanity. Unlike the Solana custodial wallet, this record-// holds NO secret material — the predicted address is just a deterministic-// function of (deployer, salt, initCodeHash). The owner deploys the-// contract themselves with their own EVM signer.+// browser at /eth-vanity. No secret material — the predicted address+// is a deterministic function of (deployer, salt, initCodeHash).+//+// Server invariants enforced on POST:+// • predicted_address == keccak256(0xff‖deployer‖salt‖init_code_hash)[12:]+// • if init_code is provided, keccak256(init_code) == init_code_hash+//+// Server invariants enforced on POST /deployed:+// • the chain RPC must return non-empty bytecode at predicted_address.+// No trust in the client's claim — we verify.//// Persisted under agent_identities.meta.eth_vanity:// {-// deployer: "0x…20 bytes…",-// init_code_hash: "0x…32 bytes…",-// init_code: "0x…" | null, // optional raw bytecode for deploy convenience-// salt: "0x…32 bytes…",-// predicted_address: "0x…20 bytes…",-// prefix: "beef" | null,-// suffix: "cafe" | null,-// deployer_label: "CreateX" | null,-// created_at: ISO,-// deployed: {-// chain_id: 8453,-// tx_hash: "0x…",-// at: ISO-// } | null+// deployer: "0x…20 bytes…",+// init_code_hash: "0x…32 bytes…",+// init_code: "0x…" | null,+// salt: "0x…32 bytes…",+// predicted_address: "0x…20 bytes…",+// prefix: "beef" | "Beef" | null,+// suffix: "cafe" | null,+// deployer_label: "CreateX" | null,+// case_sensitive: boolean,+// created_at: ISO,+// deployments: [{ chain_id, tx_hash, at, verified: bool }]// }import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';@@ -30,10 +34,28 @@ import { cors, json, method, error, readJson } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { keccak_256 } from '@noble/hashes/sha3';-const HEX_RE = /^0x[0-9a-f]+$/i;-const ADDR_RE = /^0x[0-9a-f]{40}$/i;-const HASH_RE = /^0x[0-9a-f]{64}$/i;-const TX_RE = /^0x[0-9a-f]{64}$/i;+const HEX_RE = /^0x[0-9a-f]+$/i;+const ADDR_RE = /^0x[0-9a-f]{40}$/i;+const HASH_RE = /^0x[0-9a-f]{64}$/i;+const TX_RE = /^0x[0-9a-f]{64}$/i;++/**+ * Curated list of known-good public RPCs. We don't hold secrets here, and+ * anyone can spam these — but they're rate-limited per chain, and we only+ * call them on deploy confirmation (rare). If a chain isn't listed, the+ * deploy is recorded *unverified* with a warning flag.+ */+const RPCS = {+ 1: 'https://cloudflare-eth.com',+ 8453: 'https://mainnet.base.org',+ 10: 'https://mainnet.optimism.io',+ 42161: 'https://arb1.arbitrum.io/rpc',+ 137: 'https://polygon-rpc.com',+ 56: 'https://bsc-dataseed.bnbchain.org',+ 43114: 'https://api.avax.network/ext/bc/C/rpc',+ 11155111: 'https://ethereum-sepolia-rpc.publicnode.com',+ 84532: 'https://sepolia.base.org',+};async function resolveAuth(req) {const session = await getSessionUser(req);@@ -54,11 +76,6 @@ function _bytesToHex(b) {return s;}-/**- * Re-derive the CREATE2 address server-side and verify it matches the- * client-supplied prediction. Anyone can claim "this salt produces that- * address"; we don't take their word for it.- */function _verifyCreate2(deployer, salt, initCodeHash, predicted) {const buf = new Uint8Array(85);buf[0] = 0xff;@@ -70,6 +87,42 @@ function _verifyCreate2(deployer, salt, initCodeHash, predicted) {return derived.toLowerCase() === predicted.toLowerCase();}+/**+ * Verify on-chain that bytecode exists at `address` on `chainId`. Uses+ * eth_getCode against a public RPC. Returns:+ * { ok: true, bytecodeHash } → contract is deployed+ * { ok: false, reason } → not deployed / RPC unreachable / wrong chain+ *+ * We don't hard-fail when the chain isn't in our RPC table — the caller+ * can choose to record the deployment as unverified.+ */+async function _verifyDeployed(chainId, address) {+ const rpc = RPCS[Number(chainId)];+ if (!rpc) return { ok: false, reason: 'unsupported_chain', supported: Object.keys(RPCS).map(Number) };+ try {+ const r = await fetch(rpc, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getCode', params: [address, 'latest'] }),+ });+ if (!r.ok) return { ok: false, reason: `rpc_${r.status}` };+ const data = await r.json();+ if (data.error) return { ok: false, reason: data.error.message || 'rpc_error' };+ const code = String(data.result || '0x');+ if (code === '0x' || code === '0x0') return { ok: false, reason: 'no_code_at_address' };+ // Use the keccak hash of the runtime bytecode as a stable identifier+ // so we can detect cross-chain divergence later.+ try {+ const bytes = _hexToBytes(code);+ return { ok: true, bytecodeHash: '0x' + _bytesToHex(keccak_256(bytes)) };+ } catch {+ return { ok: true, bytecodeHash: null };+ }+ } catch (e) {+ return { ok: false, reason: e?.message || 'rpc_unreachable' };+ }+}+export default async function handler(req, res, id, action) {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;@@ -97,50 +150,72 @@ export default async function handler(req, res, id, action) {if (req.method === 'POST') {const body = await readJson(req).catch(() => ({}));- // "Mark as deployed" sub-action — record an on-chain deployment of the- // existing saved record. Owner deploys with their own signer; this is- // just metadata we use to hide the Deploy button afterwards.+ // ── Sub-action: record an on-chain deployment ───────────────────────if (action === 'deployed' || body.mark_deployed) {if (!meta.eth_vanity) return error(res, 404, 'not_found', 'no vanity record to mark deployed');const chainId = Number(body.chain_id);const txHash = String(body.tx_hash || '');if (!Number.isInteger(chainId) || chainId <= 0) return error(res, 400, 'validation_error', 'chain_id must be a positive integer');if (!TX_RE.test(txHash)) return error(res, 400, 'validation_error', 'tx_hash must be 0x + 64 hex');++ // Verify bytecode is actually present at the predicted address on+ // the claimed chain. Defends against malicious clients faking+ // deploys to spoof badge / passport state.+ const v = await _verifyDeployed(chainId, meta.eth_vanity.predicted_address);+ const verified = v.ok;+ const reason = v.ok ? null : v.reason;++ const existing = Array.isArray(meta.eth_vanity.deployments) ? meta.eth_vanity.deployments : [];+ // Replace any prior unverified record for the same chain rather than duplicating.+ const others = existing.filter((d) => d.chain_id !== chainId);+ const entry = {+ chain_id: chainId,+ tx_hash: txHash.toLowerCase(),+ at: new Date().toISOString(),+ verified,+ bytecode_hash: v.bytecodeHash || null,+ ...(reason ? { unverified_reason: reason } : {}),+ };meta.eth_vanity = {...meta.eth_vanity,- deployed: { chain_id: chainId, tx_hash: txHash.toLowerCase(), at: new Date().toISOString() },+ deployments: [...others, entry].sort((a, b) => a.chain_id - b.chain_id),+ // Back-compat: keep the legacy single-deploy field set to the latest verified.+ deployed: verified ? entry : meta.eth_vanity.deployed || null,};await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;- return json(res, 200, { data: meta.eth_vanity });+ return json(res, verified ? 200 : 202, {+ data: { record: meta.eth_vanity, verified, reason },+ });}- // Save / replace.+ // ── Save / replace ─────────────────────────────────────────────────const deployer = String(body.deployer || '').toLowerCase();const salt = String(body.salt || '').toLowerCase();const ich = String(body.init_code_hash || body.initCodeHash || '').toLowerCase();const pred = String(body.predicted_address || body.address || '').toLowerCase();const initCode = body.init_code || body.initCode || null;- const prefix = body.prefix ? String(body.prefix).toLowerCase().replace(/^0x/, '') : null;- const suffix = body.suffix ? String(body.suffix).toLowerCase().replace(/^0x/, '') : null;+ const prefixIn = body.prefix ? String(body.prefix) : null;+ const suffixIn = body.suffix ? String(body.suffix) : null;const label = body.deployer_label ? String(body.deployer_label).slice(0, 64) : null;+ const caseSensitive = !!body.case_sensitive;- if (!ADDR_RE.test(deployer)) return error(res, 400, 'validation_error', 'deployer must be 0x + 40 hex');- if (!HASH_RE.test(salt)) return error(res, 400, 'validation_error', 'salt must be 0x + 64 hex');- if (!HASH_RE.test(ich)) return error(res, 400, 'validation_error', 'init_code_hash must be 0x + 64 hex');- if (!ADDR_RE.test(pred)) return error(res, 400, 'validation_error', 'predicted_address must be 0x + 40 hex');+ if (!ADDR_RE.test(deployer)) return error(res, 400, 'validation_error', 'deployer must be 0x + 40 hex');+ if (!HASH_RE.test(salt)) return error(res, 400, 'validation_error', 'salt must be 0x + 64 hex');+ if (!HASH_RE.test(ich)) return error(res, 400, 'validation_error', 'init_code_hash must be 0x + 64 hex');+ if (!ADDR_RE.test(pred)) return error(res, 400, 'validation_error', 'predicted_address must be 0x + 40 hex');if (initCode != null && (typeof initCode !== 'string' || !HEX_RE.test(initCode))) {return error(res, 400, 'validation_error', 'init_code must be a 0x-prefixed hex string');}- if (prefix && !/^[0-9a-f]+$/.test(prefix)) return error(res, 400, 'validation_error', 'prefix must be hex');- if (suffix && !/^[0-9a-f]+$/.test(suffix)) return error(res, 400, 'validation_error', 'suffix must be hex');+ // Patterns: allow either case (case-sensitive grinding preserves casing).+ const prefix = prefixIn ? prefixIn.replace(/^0x/i, '') : null;+ const suffix = suffixIn ? suffixIn.replace(/^0x/i, '') : null;+ if (prefix && !/^[0-9a-fA-F]+$/.test(prefix)) return error(res, 400, 'validation_error', 'prefix must be hex');+ if (suffix && !/^[0-9a-fA-F]+$/.test(suffix)) return error(res, 400, 'validation_error', 'suffix must be hex');- // Re-derive server-side — refuse the request if the supplied address- // doesn't actually match (deployer, salt, initCodeHash).if (!_verifyCreate2(deployer, salt, ich, pred)) {return error(res, 400, 'validation_error', 'predicted_address does not match keccak256(0xff‖deployer‖salt‖init_code_hash)');}- // If raw init_code was supplied, verify its hash matches.if (initCode) {const computed = '0x' + _bytesToHex(keccak_256(_hexToBytes(initCode)));if (computed.toLowerCase() !== ich) {@@ -148,8 +223,6 @@ export default async function handler(req, res, id, action) {}}- // If the agent already has a vanity record, require explicit DELETE first- // (matches the Solana wallet semantics).if (meta.eth_vanity) {return error(res, 409, 'conflict', 'agent already has an eth vanity record — DELETE /api/agents/:id/eth-vanity first to replace');}@@ -163,14 +236,20 @@ export default async function handler(req, res, id, action) {prefix,suffix,deployer_label: label,+ case_sensitive: caseSensitive,created_at: new Date().toISOString(),- deployed: null,+ deployments: [],+ deployed: null, // legacy};await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;return json(res, 201, { data: meta.eth_vanity });}- // GET+ // ── GET ─────────────────────────────────────────────────────────────────if (!meta.eth_vanity) return error(res, 404, 'not_found', 'agent has no eth vanity record');return json(res, 200, { data: meta.eth_vanity });}++// Re-exported so the test suite can hit the verifier directly without+// spinning up the full Vercel handler shape.+export const __test__ = { _verifyCreate2, _verifyDeployed };diff --git a/api/artifact.js b/api/artifact.jsindex 278e25091..aeba62671 100644--- a/api/artifact.js+++ b/api/artifact.js@@ -1,17 +1,26 @@-// GET /api/artifact?agent=<agentId> — self-contained HTML for Claude.ai artifacts-// GET /api/artifact?model=<glbUrl> — viewer-only (no agent overlay)+// GET /api/artifact?agent=<agentId> — self-contained HTML for Claude.ai artifacts+// GET /api/artifact?model=<glbUrl> — viewer-only, no agent persona//-// Returns text/html, not JSON. res.end(html) is intentional here — the "no res.end"-// rule in CLAUDE.md applies to JSON responses; HTML documents are returned raw.+// Returns a single self-contained HTML document. Every byte the document+// needs (three.js + GLTFLoader + viewer + GLB) is inlined, because Claude.ai's+// artifact sandbox CSP blocks all external script and fetch to non-pyodide+// origins. See public/artifact/README.md and specs/CLAUDE_ARTIFACT.md.+//+// res.end(html) is intentional — the "no res.end" rule in CLAUDE.md applies+// to JSON responses; HTML documents are returned raw.+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve as pathResolve } from 'node:path';import { sql } from './_lib/db.js';import { error, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';-import { env } from './_lib/env.js';+import { getObjectBuffer } from './_lib/r2.js';const AGENT_ID_RE = /^[a-z0-9_-]{3,64}$/i;-// Whitelisted origins for ?model= URLs (must be https, must match one of these)+// Whitelisted origins for ?model= URLs (must be https). Server-side fetched,+// then inlined — Claude's sandbox can't reach these directly.const ALLOWED_MODEL_ORIGINS = [/^https:\/\/[^/]+\.r2\.cloudflarestorage\.com$/,/^https:\/\/[^/]+\.amazonaws\.com$/,@@ -22,15 +31,49 @@ const ALLOWED_MODEL_ORIGINS = [/^https:\/\/[^/]+\.vercel\.app$/,];+// Hard cap on GLB size. Claude's artifact runtime tolerates several MB of+// inlined HTML; beyond ~6 MB raw (≈8 MB base64) responses become slow to paste+// and risk the artifact panel timing out before first paint.+const MAX_GLB_BYTES = 6 * 1024 * 1024;+const FETCH_TIMEOUT_MS = 8000;++// Mirrors the actual CSP Claude.ai applies to artifact iframes (scraped at+// github.com/simonw/scrape-claude-artifacts). Setting the same response CSP+// means the document behaves identically when iframed directly from your own+// site — no surprises between standalone preview and live Claude rendering.+// `frame-ancestors *` is loosened so embedders other than Claude can still+// iframe the response.const CSP = [- "default-src 'self' https://three.ws/",- "script-src 'self' 'unsafe-inline' https://three.ws/",- 'img-src * data: blob:',- 'connect-src *',- "style-src 'self' 'unsafe-inline'",+ "default-src 'none'",+ "script-src 'unsafe-inline'",+ "style-src 'unsafe-inline'",+ 'img-src data: blob:',+ "connect-src 'self'",+ 'font-src data:',+ "base-uri 'none'",+ "form-action 'none'",+ "object-src 'none'",'frame-ancestors *',].join('; ');+// Read the prebuilt artifact viewer bundle once. `npm run build:artifact-viewer`+// regenerates it from scripts/artifact-viewer/src.js.+const __dirname = dirname(fileURLToPath(import.meta.url));+const BUNDLE_PATH = pathResolve(__dirname, '../public/artifact-viewer.bundle.js');+let _bundle;+function getBundle() {+ if (_bundle === undefined) {+ try {+ _bundle = readFileSync(BUNDLE_PATH, 'utf8');+ } catch (err) {+ throw new Error(+ `artifact-viewer bundle missing at ${BUNDLE_PATH} — run "npm run build:artifact-viewer"`,+ );+ }+ }+ return _bundle;+}+function validateModelUrl(raw) {let url;try {@@ -39,27 +82,107 @@ function validateModelUrl(raw) {return null;}if (url.protocol !== 'https:') return null;- const origin = url.origin;- if (!ALLOWED_MODEL_ORIGINS.some((pat) => pat.test(origin))) return null;+ if (!ALLOWED_MODEL_ORIGINS.some((pat) => pat.test(url.origin))) return null;return url.toString();}-function buildHtml({ title, element, appOrigin }) {+async function fetchExternalGlb(url) {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow' });+ if (!res.ok) throw new Error(`upstream ${res.status}`);+ const len = Number(res.headers.get('content-length') || 0);+ if (len && len > MAX_GLB_BYTES) {+ throw new Error(`model ${(len / 1024 / 1024).toFixed(1)} MB exceeds ${MAX_GLB_BYTES / 1024 / 1024} MB limit`);+ }+ const buf = Buffer.from(await res.arrayBuffer());+ if (buf.byteLength > MAX_GLB_BYTES) {+ throw new Error(`model ${(buf.byteLength / 1024 / 1024).toFixed(1)} MB exceeds limit`);+ }+ return buf;+ } finally {+ clearTimeout(timer);+ }+}++function buildHtml({ title, config }) {+ const cfgJson = JSON.stringify(config)+ .replace(/</g, '\\u003c')+ .replace(/-->/g, '--\\>')+ .replace(/<\/script/gi, '<\\/script');+return `<!doctype html><html lang="en">- <head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width,initial-scale=1">- <title>${title}</title>- <style>html,body{margin:0;height:100%;background:#080814;}agent-3d{display:block;width:100%;height:100%}</style>- </head>- <body>- ${element}- <script type="module" src="${appOrigin}/dist-lib/agent-3d.js"></script>- </body>+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>${escHtml(title)}</title>+<style>+html,body{margin:0;height:100%;background:${escAttr(config.bg ? '#' + config.bg : '#0a0e27')};font-family:system-ui,-apple-system,sans-serif}+#artifact-stage{position:absolute;inset:0;overflow:hidden}+</style>+</head>+<body>+<div id="artifact-stage"></div>+<script type="application/json" id="artifact-config">${cfgJson}</script>+<script>${getBundle()}</script>+</body></html>`;}+async function loadAgentArtifactConfig(agentId, opts) {+ const [row] = await sql`+ SELECT+ a.id, a.name,+ av.storage_key+ FROM agent_identities a+ LEFT JOIN avatars av ON av.id = a.avatar_id AND av.deleted_at IS NULL+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL+ LIMIT 1+ `;+ if (!row) return { error: { status: 404, code: 'not_found', msg: 'agent not found' } };+ if (!row.storage_key) {+ return { error: { status: 422, code: 'no_avatar', msg: 'agent has no avatar yet' } };+ }++ const buf = await getObjectBuffer(row.storage_key);+ if (buf.byteLength > MAX_GLB_BYTES) {+ return {+ error: {+ status: 413,+ code: 'too_large',+ msg: `agent avatar is ${(buf.byteLength / 1024 / 1024).toFixed(1)} MB — Claude artifact limit is ${MAX_GLB_BYTES / 1024 / 1024} MB`,+ },+ };+ }++ return {+ title: `${row.name} — three.ws`,+ config: {+ name: row.name,+ glb: buf.toString('base64'),+ theme: opts.theme,+ idle: opts.idle,+ bg: opts.bg,+ },+ };+}++async function loadModelArtifactConfig(modelUrl, opts) {+ const buf = await fetchExternalGlb(modelUrl);+ return {+ title: 'three.ws Viewer',+ config: {+ name: '',+ glb: buf.toString('base64'),+ theme: opts.theme,+ idle: opts.idle,+ bg: opts.bg,+ },+ };+}+export default wrap(async (req, res) => {if (req.method !== 'GET' && req.method !== 'HEAD') {res.setHeader('allow', 'GET, HEAD');@@ -74,76 +197,47 @@ export default wrap(async (req, res) => {const agentId = params.get('agent');const modelUrl = params.get('model');const theme = params.get('theme') === 'light' ? 'light' : 'dark';- const idle = params.get('idle') || '';- const bg = params.get('bg') || '';+ const idle = (params.get('idle') || '').slice(0, 64);+ const bg = (params.get('bg') || '').replace(/^#/, '').match(/^[0-9a-f]{6}$/i)?.[0] || '';- const appOrigin = env.APP_ORIGIN;+ if ((agentId === null) === (modelUrl === null)) {+ return error(res, 400, 'invalid_request', 'provide exactly one of ?agent=<id> or ?model=<url>');+ }- let html;+ const opts = { theme, idle, bg };+ let result;if (agentId !== null) {if (!AGENT_ID_RE.test(agentId)) {- return error(- res,- 400,- 'invalid_request',- 'agent id must be 3–64 alphanumeric/hyphen/underscore chars',- );+ return error(res, 400, 'invalid_request', 'agent id must be 3–64 alphanumeric/hyphen/underscore chars');}-- const [row] = await sql`- SELECT id, name FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL- `;- if (!row) return error(res, 404, 'not_found', 'agent not found');-- const attrs = [- `agent="${escAttr(row.id)}"`,- 'eager',- theme === 'light' ? 'theme="light"' : '',- idle ? `idle="${escAttr(idle)}"` : '',- bg ? `bg="${escAttr(bg)}"` : '',- ]- .filter(Boolean)- .join(' ');-- html = buildHtml({- title: `${row.name} — three.ws`,- element: `<agent-3d ${attrs}></agent-3d>`,- appOrigin,- });- } else if (modelUrl !== null) {+ result = await loadAgentArtifactConfig(agentId, opts);+ } else {const safeUrl = validateModelUrl(modelUrl);if (!safeUrl) {- return error(- res,- 400,- 'invalid_request',- 'model must be an https URL from a whitelisted origin',- );+ return error(res, 400, 'invalid_request', 'model must be an https URL from a whitelisted origin');+ }+ try {+ result = await loadModelArtifactConfig(safeUrl, opts);+ } catch (err) {+ return error(res, 502, 'upstream_error', err.message || 'model fetch failed');}-- const attrs = [- `src="${escAttr(safeUrl)}"`,- theme === 'light' ? 'theme="light"' : '',- bg ? `bg="${escAttr(bg)}"` : '',- ]- .filter(Boolean)- .join(' ');-- html = buildHtml({- title: 'three.ws Viewer',- element: `<agent-3d ${attrs}></agent-3d>`,- appOrigin,- });- } else {- return error(res, 400, 'invalid_request', 'provide ?agent=<id> or ?model=<url>');}+ if (result.error) return error(res, result.error.status, result.error.code, result.error.msg);++ const html = buildHtml(result);+res.statusCode = 200;res.setHeader('content-type', 'text/html; charset=utf-8');res.setHeader('content-security-policy', CSP);res.setHeader('cache-control', 'public, max-age=60, s-maxage=60, stale-while-revalidate=3600');res.setHeader('x-frame-options', 'ALLOWALL');+ if (req.method === 'HEAD') {+ res.setHeader('content-length', Buffer.byteLength(html).toString());+ res.end();+ return;+ }res.end(html);});@@ -154,3 +248,7 @@ function escAttr(s) {.replace(/</g, '<').replace(/>/g, '>');}++function escHtml(s) {+ return String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]);+}diff --git a/api/csrf-token.js b/api/csrf-token.jsnew file mode 100644index 000000000..482d17229--- /dev/null+++ b/api/csrf-token.js@@ -0,0 +1,17 @@+// GET /api/csrf-token — issue a single-use CSRF token bound to the session user.+import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';+import { cors, error, json, method, wrap } from './_lib/http.js';+import { issueCsrf } from './_lib/csrf.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id || bearer?.userId;+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');++ const { token, expiresIn } = await issueCsrf(userId);+ return json(res, 200, { data: { token, expires_in: expiresIn } });+});diff --git a/api/explore.js b/api/explore.jsindex a9b2cb6b2..893aef958 100644--- a/api/explore.js+++ b/api/explore.js@@ -8,8 +8,22 @@* cursor=<iso> — created_at/registered_at ISO string for pagination* limit=<int> — page size, default 24, max 60* source=<all|onchain|avatar> — restrict feed to one source. Default 'all'.+ * quality=<all|high> — avatar quality filter. 'high' (default) hides+ * autonamed/filename-like junk and surfaces named+ * community + curated avatars first.*/+// Names we never want surfaced in marketplace-quality views. Mirrors the+// auto-naming patterns used by the avatar editor and by raw filename uploads+// (mo-prefixed short IDs, draft slugs, UUIDs, "Avatar #abcd12", etc.).+const NAME_AUTONAMED_RE =+ /^(Avatar #[0-9a-f]{6}|Avatar \d+\/\d+\/\d{4}.*|mo[a-z0-9]{4,}|draft-[a-z0-9]+|[a-f0-9-]{30,}|new_project_\d+|TEST|test|Untitled.*)$/i;++function isAutoNamed(name) {+ if (!name || !name.trim()) return true;+ return NAME_AUTONAMED_RE.test(name.trim());+}+import { sql } from './_lib/db.js';import { cors, json, method, wrap, error } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';@@ -31,6 +45,7 @@ export default wrap(async (req, res) => {const cursor = url.searchParams.get('cursor');const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 60);const sourceFilter = url.searchParams.get('source') || 'all';+ const quality = url.searchParams.get('quality') === 'all' ? 'all' : 'high';const cursorDate = cursor ? new Date(cursor) : null;if (cursor && isNaN(cursorDate?.getTime())) {@@ -65,17 +80,22 @@ export default wrap(async (req, res) => {const avatarRows = includeAvatars? await sql`- SELECT id, slug, name, description, storage_key, thumbnail_key, tags, created_at- FROM avatars- WHERE deleted_at IS NULL- AND visibility = 'public'+ SELECT a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,+ a.tags, a.created_at, a.source,+ u.username AS owner_username,+ u.display_name AS owner_display_name,+ u.wallet_address AS owner_wallet+ FROM avatars a+ LEFT JOIN users u ON u.id = a.owner_id AND u.deleted_at IS NULL+ WHERE a.deleted_at IS NULL+ AND a.visibility = 'public'AND (${q || null}::text IS NULL OR (- coalesce(name,'') ILIKE ${'%' + q + '%'}- OR coalesce(description,'') ILIKE ${'%' + q + '%'}+ coalesce(a.name,'') ILIKE ${'%' + q + '%'}+ OR coalesce(a.description,'') ILIKE ${'%' + q + '%'}))- AND (${cursorDate ? cursorDate.toISOString() : null}::timestamptz IS NULL OR created_at < ${cursorDate ? cursorDate.toISOString() : null}::timestamptz)- ORDER BY created_at DESC- LIMIT ${limit + 1}+ AND (${cursorDate ? cursorDate.toISOString() : null}::timestamptz IS NULL OR a.created_at < ${cursorDate ? cursorDate.toISOString() : null}::timestamptz)+ ORDER BY a.created_at DESC+ LIMIT ${(limit + 1) * 3}`: [];@@ -108,8 +128,13 @@ export default wrap(async (req, res) => {};});- const avatarItems = avatarRows.map((r) => {+ let avatarItems = avatarRows.map((r) => {const glb = publicUrl(r.storage_key);+ const handle = r.owner_username+ ? `@${r.owner_username}`+ : r.owner_wallet+ ? shortAddr(r.owner_wallet)+ : null;return {kind: 'avatar',sortDate: r.created_at,@@ -121,11 +146,29 @@ export default wrap(async (req, res) => {glbUrl: glb,has3d: true,tags: r.tags || [],+ source: r.source || null,createdAt: r.created_at,viewerUrl: `/#model=${encodeURIComponent(glb)}`,+ author: handle+ ? {+ handle,+ displayName: r.owner_display_name || r.owner_username || handle,+ profileUrl: r.owner_username ? `/u/${r.owner_username}` : null,+ }+ : null,+ autoNamed: isAutoNamed(r.name),};});+ // Quality filter: hide auto-named/junk by default. The marketplace UI uses+ // quality=high to populate a "Community Avatars" wall that should look+ // curated, not like a debug dump.+ if (includeAvatars && quality === 'high') {+ avatarItems = avatarItems.filter((a) => !a.autoNamed);+ }+ // Cap to requested limit after filtering (we overfetch above).+ if (avatarItems.length > limit + 1) avatarItems = avatarItems.slice(0, limit + 1);+// Inject demo avatars on the first page when the source allows avatars.// Filter by query if one is set so search still feels correct.if (includeAvatars && !cursorDate) {diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex a61a0a420..dabc9d5e7 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -16,21 +16,14 @@* Routed via vercel.json rewrites — see project root.*/-import { Keypair, PublicKey } from '@solana/web3.js';-import { findReference, validateTransfer } from '@solana/pay';-import BigNumber from 'bignumber.js';+import { Keypair } from '@solana/web3.js';import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';-import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';--let _rpc;-function rpc() {- if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });- return _rpc;-}+import { confirmSkillPurchase, logEvent, resolvePayoutAddress } from '../_lib/purchase-confirm.js';+import { requireCsrf } from '../_lib/csrf.js';const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58 Pubkey@@ -73,6 +66,8 @@ async function handleCreate(req, res) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ if (!(await requireCsrf(req, res, auth.userId))) return;+const rl = await limits.authIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');@@ -85,13 +80,13 @@ async function handleCreate(req, res) {// Look up the active price for this skill on this agent.const [price] = await sql`- SELECT amount, currency_mint, chain+ SELECT amount, currency_mint, chain, mint_decimals, trial_usesFROM agent_skill_pricesWHERE agent_id = ${agentId} AND skill = ${skill} AND is_active = true`;if (!price) return error(res, 404, 'not_found', 'this skill is not for sale');- // Look up the agent owner's payout wallet for the relevant chain.+ // Resolve the agent owner's payout wallet for the relevant chain.const [payout] = await sql`SELECT pw.addressFROM agent_identities a@@ -107,13 +102,15 @@ async function handleCreate(req, res) {return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');}- // Block double-purchase: if the buyer already has a confirmed purchase- // for this (agent, skill), return it as-is rather than minting a new ref.+ // Already-owned short-circuit: any active access (confirmed purchase, live trial,+ // unexpired time-pass) returns the existing row so the buyer doesn't pay twice.const [existing] = await sql`- SELECT reference, status, tx_signature, confirmed_at+ SELECT reference, status, tx_signature, confirmed_at, valid_until, trial_remaining, kindFROM skill_purchasesWHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skill}- AND status = 'confirmed'+ AND status IN ('confirmed', 'trial')+ AND (valid_until IS NULL OR valid_until > now())+ ORDER BY (status = 'confirmed') DESC, confirmed_at DESC NULLS LASTLIMIT 1`;if (existing) {@@ -124,25 +121,48 @@ async function handleCreate(req, res) {status: existing.status,tx_signature: existing.tx_signature,confirmed_at: existing.confirmed_at,+ valid_until: existing.valid_until,+ trial_remaining: existing.trial_remaining,+ kind: existing.kind,},});}- const reference = Keypair.generate().publicKey.toBase58();+ // Idempotent create (A4): reuse a fresh pending row for the same (user, agent, skill)+ // rather than minting a new reference on every retry click.+ const referrerUserId = await resolveReferrer(req, auth.userId);+ const [pending] = await sql`+ SELECT reference, amount, currency_mint, chain, expires_at+ FROM skill_purchases+ WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skill}+ AND status = 'pending'+ AND expires_at > now()+ ORDER BY created_at DESC+ LIMIT 1+ `;+ const reference = pending?.reference ?? Keypair.generate().publicKey.toBase58();const label = `Skill: ${skill.slice(0, 40)}`;const message = `Unlock '${skill}' for this agent`;- const [row] = await sql`- INSERT INTO skill_purchases (- user_id, agent_id, skill, status, reference,- amount, currency_mint, chain- )- VALUES (- ${auth.userId}, ${agentId}, ${skill}, 'pending', ${reference},- ${price.amount}, ${price.currency_mint}, ${price.chain}- )- RETURNING reference, amount, currency_mint, chain, created_at- `;+ let row = pending;+ if (!pending) {+ const inserted = await sql`+ INSERT INTO skill_purchases (+ user_id, agent_id, skill, status, reference,+ amount, currency_mint, chain, expires_at, kind, referrer_user_id+ )+ VALUES (+ ${auth.userId}, ${agentId}, ${skill}, 'pending', ${reference},+ ${price.amount}, ${price.currency_mint}, ${price.chain},+ now() + interval '30 minutes', 'purchase', ${referrerUserId}+ )+ RETURNING reference, amount, currency_mint, chain, expires_at+ `;+ row = inserted[0];+ await logEvent(row.reference, 'created', { agent_id: agentId, skill });+ } else {+ await logEvent(pending.reference, 'create_idempotent_hit', { agent_id: agentId, skill });+ }return json(res, 201, {data: {@@ -151,6 +171,8 @@ async function handleCreate(req, res) {amount: String(row.amount),currency_mint: row.currency_mint,chain: row.chain,+ mint_decimals: price.mint_decimals,+ expires_at: row.expires_at,label,message,},@@ -189,110 +211,65 @@ async function handleConfirm(req, res, reference) {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ if (!(await requireCsrf(req, res, auth.userId))) return;+const rl = await limits.authIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const [pur] = await sql`- SELECT id, user_id, agent_id, skill, status, amount, currency_mint, chain, tx_signature- FROM skill_purchases- WHERE reference = ${reference} AND user_id = ${auth.userId}+ SELECT sp.id, sp.user_id, sp.agent_id, sp.skill, sp.status,+ sp.amount, sp.currency_mint, sp.chain, sp.tx_signature,+ sp.expires_at, sp.referrer_user_id,+ COALESCE(asp.mint_decimals, 6) AS mint_decimals+ FROM skill_purchases sp+ LEFT JOIN agent_skill_prices asp+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill+ WHERE sp.reference = ${reference} AND sp.user_id = ${auth.userId}`;if (!pur) return error(res, 404, 'not_found', 'purchase not found');if (pur.status === 'confirmed') {return json(res, 200, { data: { status: 'confirmed', tx_signature: pur.tx_signature } });}+ if (pur.status === 'expired' || (pur.expires_at && new Date(pur.expires_at) < new Date())) {+ return error(res, 410, 'purchase_expired', 'this pending purchase expired; please start a new one');+ }if (pur.chain !== 'solana') {return error(res, 501, 'not_implemented', `chain '${pur.chain}' confirmation not yet supported`);}- // Resolve the agent owner's payout wallet again — it must match what the- // buyer paid to. Re-resolving on confirm protects against owner key- // rotation between create and confirm.- const [payout] = await sql`- SELECT pw.address- FROM agent_identities a- JOIN agent_payout_wallets pw- ON pw.user_id = a.user_id- AND pw.chain = ${pur.chain}- AND (pw.agent_id = a.id OR pw.is_default = true)- WHERE a.id = ${pur.agent_id}- ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC- LIMIT 1- `;- if (!payout?.address) {- return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');+ const result = await confirmSkillPurchase({ ...pur, reference });+ if (result.status === 'pending') {+ return json(res, 200, { data: { status: 'pending' } });}-- const refKey = new PublicKey(reference);- const recipient = new PublicKey(payout.address);- const splToken = new PublicKey(pur.currency_mint);- const expectedAmount = new BigNumber(pur.amount).dividedBy(1e6); // assume 6 decimals (USDC)-- let signatureInfo;- try {- signatureInfo = await rpc().withFallback((conn) => findReference(conn, refKey, { finality: 'confirmed' }));- } catch (e) {- // Solana Pay throws FindReferenceError when no tx is found yet.- if (/FindReferenceError|not found/i.test(e?.message || '')) {- return json(res, 200, { data: { status: 'pending' } });- }- throw e;+ if (result.status === 'tipped') {+ return error(res, 409, 'transfer_mismatch', result.message || 'on-chain transfer did not match expected', {+ status: 'tipped',+ tipped_amount: result.tipped_amount,+ tx_signature: result.tx_signature,+ });}-- const txSignature = signatureInfo.signature;-- try {- await rpc().withFallback((conn) =>- validateTransfer(- conn,- txSignature,- { recipient, amount: expectedAmount, splToken, reference: refKey },- { commitment: 'confirmed' },- ),- );- } catch (e) {- // Transfer was found but doesn't match — mark failed so the user can retry.- await sql`- UPDATE skill_purchases- SET status = 'failed', tx_signature = ${txSignature}- WHERE id = ${pur.id} AND status = 'pending'- `;- return error(res, 409, 'transfer_mismatch', `on-chain transfer did not match expected: ${e.message}`);+ if (result.status === 'mismatch') {+ return error(res, 409, 'transfer_mismatch', result.message || 'no matching transfer found');}-- // Atomic confirm + revenue ledger. The status='pending' guard keeps concurrent- // confirms idempotent: the second one updates 0 rows and skips the ledger writes.- // agent_revenue_events.intent_id has a FK to agent_payment_intents, so we- // synthesize a payment-intent row keyed off the skill_purchase id.- const intentId = `sp_${pur.id}`;- const updated = await sql`- UPDATE skill_purchases- SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()- WHERE id = ${pur.id} AND status = 'pending'- RETURNING id- `;- if (updated.length > 0) {- await sql`- INSERT INTO agent_payment_intents- (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at,- cluster, tx_signature, paid_at, payload)- VALUES- (${intentId}, ${pur.user_id}, ${pur.agent_id}, ${pur.currency_mint},- ${String(pur.amount)}, 'confirmed', now() + interval '30 days',- 'mainnet', ${txSignature}, now(),- ${JSON.stringify({ kind: 'skill_purchase', skill: pur.skill, reference })}::jsonb)- ON CONFLICT (id) DO NOTHING- `;- await sql`- INSERT INTO agent_revenue_events- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,- currency_mint, chain, payer_address)- VALUES- (${pur.agent_id}, ${intentId}, ${pur.skill},- ${pur.amount}, 0, ${pur.amount},- ${pur.currency_mint}, ${pur.chain}, ${payout.address})- `;+ if (result.status === 'expired') {+ return error(res, 410, 'purchase_expired', 'this pending purchase expired; please start a new one');}+ return json(res, 200, { data: { status: 'confirmed', tx_signature: result.tx_signature } });+}- return json(res, 200, { data: { status: 'confirmed', tx_signature: txSignature } });+// ── Helpers ────────────────────────────────────────────────────────────────++// Look up the referrer who sent the buyer here. Two paths:+// 1. ?ref=<code> querystring — buyer arrived via a referral link.+// 2. users.referred_by_id — buyer signed up under someone.+async function resolveReferrer(req, buyerUserId) {+ const url = new URL(req.url, 'http://x');+ const code = url.searchParams.get('ref');+ if (code) {+ const [u] = await sql`SELECT id FROM users WHERE referral_code = ${code} LIMIT 1`;+ if (u && u.id !== buyerUserId) return u.id;+ }+ const [me] = await sql`SELECT referred_by_id FROM users WHERE id = ${buyerUserId}`;+ if (me?.referred_by_id && me.referred_by_id !== buyerUserId) return me.referred_by_id;+ return null;}diff --git a/api/scene/gate-check.js b/api/scene/gate-check.jsindex 9d7cf8a15..367b6c1b1 100644--- a/api/scene/gate-check.js+++ b/api/scene/gate-check.js@@ -1,11 +1,11 @@import { z } from 'zod';import { verifyMessage } from 'ethers';-import { sql } from '../../_lib/db.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { randomToken } from '../../_lib/crypto.js';-import { verifySiwsSignature } from '../../_lib/siws.js';-import { parse } from '../../_lib/validate.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { randomToken } from '../_lib/crypto.js';+import { verifySiwsSignature } from '../_lib/siws.js';+import { parse } from '../_lib/validate.js';const NONCE_TTL_SEC = 10 * 60;diff --git a/api/scene/gate-create.js b/api/scene/gate-create.jsindex 3db8d036f..303f5df5f 100644--- a/api/scene/gate-create.js+++ b/api/scene/gate-create.js@@ -1,11 +1,11 @@import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { env } from '../../_lib/env.js';-import { parse } from '../../_lib/validate.js';-import { randomToken } from '../../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { parse } from '../_lib/validate.js';+import { randomToken } from '../_lib/crypto.js';const bodySchema = z.object({sceneRef: z.string().trim().min(1).max(8000),diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 1493cac6d..d3311caf2 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -30,6 +30,7 @@ import {} from '@solana/spl-token';import bs58 from 'bs58';+import { Redis } from '@upstash/redis';import { cors, json, readJson, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import {@@ -39,6 +40,95 @@ import {NETWORK_SOLANA_MAINNET,} from './_lib/x402-spec.js';import { dispatch } from './_mcp/dispatch.js';+import { env } from './_lib/env.js';++// ---- Persistent feed of recent paid calls -------------------------------+// Backed by Upstash Redis when available; falls back to an in-memory ring+// in dev so the feed still works locally.+const FEED_KEY = 'x402:pay:feed';+const FEED_MAX = 50;+const memFeed = [];++let _redis = null;+function redis() {+ if (_redis !== null) return _redis;+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {+ _redis = new Redis({+ url: env.UPSTASH_REDIS_REST_URL,+ token: env.UPSTASH_REDIS_REST_TOKEN,+ });+ } else {+ _redis = false;+ }+ return _redis;+}++async function recordFeedEntry(entry) {+ const r = redis();+ if (r) {+ try {+ await r.lpush(FEED_KEY, JSON.stringify(entry));+ await r.ltrim(FEED_KEY, 0, FEED_MAX - 1);+ } catch {}+ }+ memFeed.unshift(entry);+ if (memFeed.length > FEED_MAX) memFeed.length = FEED_MAX;+}++async function readFeed(limit = 25) {+ const r = redis();+ if (r) {+ try {+ const rows = await r.lrange(FEED_KEY, 0, limit - 1);+ return rows+ .map((row) => {+ if (typeof row === 'string') {+ try { return JSON.parse(row); } catch { return null; }+ }+ return row;+ })+ .filter(Boolean);+ } catch {}+ }+ return memFeed.slice(0, limit);+}++// Per-tx record so /pay/calls/<tx> can show the full receipt + tool result.+const memCalls = new Map();+const CALL_KEY = (tx) => `x402:pay:call:${tx}`;+const CALL_TTL_SECONDS = 60 * 60 * 24 * 30; // 30 days++async function persistCall(tx, record) {+ const r = redis();+ if (r) {+ try { await r.set(CALL_KEY(tx), JSON.stringify(record), { ex: CALL_TTL_SECONDS }); }+ catch {}+ }+ memCalls.set(tx, record);+}++async function readCall(tx) {+ const r = redis();+ if (r) {+ try {+ const row = await r.get(CALL_KEY(tx));+ if (typeof row === 'string') { try { return JSON.parse(row); } catch {} }+ else if (row && typeof row === 'object') return row;+ } catch {}+ }+ return memCalls.get(tx) || null;+}++function summarizeArgs(args) {+ if (!args || typeof args !== 'object') return '';+ if (args.url) {+ try { return new URL(args.url).pathname.split('/').pop() || args.url; }+ catch { return args.url.slice(0, 40); }+ }+ if (args.q) return `q=${String(args.q).slice(0, 24)}`;+ const keys = Object.keys(args);+ return keys.length ? keys.map((k) => `${k}=${String(args[k]).slice(0,16)}`).join(' ') : '';+}const ALLOWED_TOOLS = new Set(['tools/list',@@ -218,6 +308,28 @@ async function runFlow({ tool, args, emit }) {explorer: settled.transaction ? `https://solscan.io/tx/${settled.transaction}` : null,});+ // Persist a feed entry + per-tx record for the public feed and /pay/calls/<tx>.+ const feedEntry = {+ ts: Date.now(),+ tool,+ argsSummary: summarizeArgs(args),+ tx: settled.transaction || null,+ network: settled.network || accept.network,+ amount: accept.amount,+ };+ void recordFeedEntry(feedEntry).catch(() => {});+ if (settled.transaction) {+ void persistCall(settled.transaction, {+ ...feedEntry,+ args,+ result: rpcResp?.result ?? rpcResp,+ payer: verified.payer || buyer.publicKey.toBase58(),+ payTo: accept.payTo,+ asset: accept.asset,+ explorer: `https://solscan.io/tx/${settled.transaction}`,+ }).catch(() => {});+ }+const total_ms = tSettled - t0;emit('result', {ok: true,@@ -255,6 +367,17 @@ export default wrap(async (req, res) => {return json(res, err.status || 500, { error: err.message });}}+ if (u.searchParams.get('feed') === '1') {+ const limit = Math.max(1, Math.min(50, Number(u.searchParams.get('limit') || 25)));+ const items = await readFeed(limit);+ return json(res, 200, { items });+ }+ const txParam = u.searchParams.get('call');+ if (txParam) {+ const record = await readCall(txParam);+ if (!record) return json(res, 404, { error: 'call_not_found' });+ return json(res, 200, record);+ }return json(res, 404, { error: 'not_found' });}if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });diff --git a/api/x402-pay/og.js b/api/x402-pay/og.jsnew file mode 100644index 000000000..ca9bf3af5--- /dev/null+++ b/api/x402-pay/og.js@@ -0,0 +1,192 @@+// GET /api/x402-pay/og?tx=<signature>+// Dynamic 1200×630 PNG card for /pay/calls/<tx> permalinks. When pasted into+// X / Slack / Discord / iMessage, the link expands to a branded summary of the+// paid x402 call (tool, amount, payer, timestamp).++import sharp from 'sharp';+import { Redis } from '@upstash/redis';+import { env } from '../_lib/env.js';++const FALLBACK_TITLE = 'three.ws · pay-per-call (x402)';+const FALLBACK_SUB = 'Live demo — agent pays $0.001 USDC per MCP tool call.';++let _redis = null;+function redis() {+ if (_redis !== null) return _redis;+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {+ _redis = new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });+ } else _redis = false;+ return _redis;+}++async function readCall(tx) {+ const r = redis();+ if (!r) return null;+ try {+ const row = await r.get(`x402:pay:call:${tx}`);+ if (typeof row === 'string') { try { return JSON.parse(row); } catch {} }+ else if (row && typeof row === 'object') return row;+ } catch {}+ return null;+}++function escapeSvg(s) {+ return String(s).replace(/[<>&"]/g, (c) => ({+ '<': '<', '>': '>', '&': '&', '"': '"',+ }[c]));+}++function shortTx(tx) {+ if (!tx) return '—';+ return `${tx.slice(0, 10)}…${tx.slice(-6)}`;+}++function shortAddr(a) {+ if (!a) return '—';+ return `${a.slice(0, 6)}…${a.slice(-4)}`;+}++function relativeAgo(ts) {+ if (!ts) return '';+ const d = Math.max(0, Date.now() - ts);+ if (d < 60_000) return `${Math.floor(d / 1000)}s ago`;+ if (d < 3_600_000) return `${Math.floor(d / 60_000)}m ago`;+ if (d < 86_400_000) return `${Math.floor(d / 3_600_000)}h ago`;+ return `${Math.floor(d / 86_400_000)}d ago`;+}++function svgFor(record, txParam) {+ const tool = record?.tool || 'paid call';+ const args = record?.argsSummary || '';+ const tx = record?.tx || txParam || '';+ const payer = record?.payer || '';+ const amount = ((Number(record?.amount || 1000)) / 1e6).toFixed(6);+ const ago = relativeAgo(record?.ts);++ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#0a0b10"/>+ <stop offset="1" stop-color="#14161f"/>+ </linearGradient>+ <radialGradient id="glow1" cx="0.18" cy="0.18" r="0.55">+ <stop offset="0" stop-color="#8b5cf6" stop-opacity="0.45"/>+ <stop offset="1" stop-color="#8b5cf6" stop-opacity="0"/>+ </radialGradient>+ <radialGradient id="glow2" cx="0.85" cy="0.92" r="0.5">+ <stop offset="0" stop-color="#22d3ee" stop-opacity="0.32"/>+ <stop offset="1" stop-color="#22d3ee" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="logoG" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#8b5cf6"/>+ <stop offset="1" stop-color="#22d3ee"/>+ </linearGradient>+ <linearGradient id="accent" x1="0" y1="0" x2="1" y2="0">+ <stop offset="0" stop-color="#8b5cf6"/>+ <stop offset="1" stop-color="#22d3ee"/>+ </linearGradient>+ </defs>++ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect width="1200" height="630" fill="url(#glow1)"/>+ <rect width="1200" height="630" fill="url(#glow2)"/>++ <!-- top brand row -->+ <g transform="translate(72 72)">+ <rect x="0" y="0" width="44" height="44" rx="11" fill="url(#logoG)"/>+ <text x="60" y="22" font-family="-apple-system, system-ui, Inter, Helvetica, Arial, sans-serif" font-size="18" font-weight="700" fill="#e6e8f0" letter-spacing="-0.2">three.ws</text>+ <text x="60" y="42" font-family="ui-monospace, Menlo, monospace" font-size="14" fill="#8a90a8">pay-per-call · x402</text>+ </g>++ <!-- settled badge -->+ <g transform="translate(972 80)">+ <rect x="0" y="0" width="156" height="40" rx="20" fill="#22c55e" fill-opacity="0.14" stroke="#22c55e" stroke-opacity="0.6" stroke-width="1"/>+ <circle cx="22" cy="20" r="5" fill="#22c55e"/>+ <text x="38" y="25" font-family="ui-monospace, Menlo, monospace" font-size="13" fill="#22c55e" letter-spacing="1.3">SETTLED ON-CHAIN</text>+ </g>++ <!-- main title block -->+ <g transform="translate(72 200)">+ <rect x="0" y="-36" width="6" height="56" fill="url(#accent)" rx="3"/>+ <text x="22" y="0" font-family="ui-monospace, Menlo, monospace" font-size="46" font-weight="700" fill="#e6e8f0">${escapeSvg(tool)}</text>+ ${args ? `<text x="22" y="36" font-family="-apple-system, system-ui, Inter, Helvetica, Arial, sans-serif" font-size="22" fill="#8a90a8">${escapeSvg(args.slice(0, 80))}</text>` : ''}+ </g>++ <!-- stat strip -->+ <g transform="translate(72 320)" font-family="ui-monospace, Menlo, monospace">+ <g>+ <text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">AMOUNT</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${amount} USDC</text>+ </g>+ <g transform="translate(280 0)">+ <text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">NETWORK</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">Solana mainnet</text>+ </g>+ <g transform="translate(660 0)">+ <text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">PAYER</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${escapeSvg(shortAddr(payer))}</text>+ </g>+ ${ago ? `<g transform="translate(900 0)">+ <text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">WHEN</text>+ <text x="0" y="30" font-size="28" fill="#e6e8f0" font-weight="600">${escapeSvg(ago)}</text>+ </g>` : ''}+ </g>++ <!-- tx hash -->+ <g transform="translate(72 430)" font-family="ui-monospace, Menlo, monospace">+ <text x="0" y="0" font-size="13" fill="#8a90a8" letter-spacing="1.6">TX</text>+ <text x="0" y="30" font-size="22" fill="#22d3ee">${escapeSvg(shortTx(tx))}</text>+ </g>++ <!-- footer -->+ <g transform="translate(72 540)" font-family="-apple-system, system-ui, Inter, Helvetica, Arial, sans-serif">+ <text x="0" y="0" font-size="22" fill="#e6e8f0" font-weight="500">No keys. No signup. $0.001 per call, settled per request.</text>+ <text x="0" y="34" font-size="18" fill="#8a90a8">three.ws/pay → try it yourself</text>+ </g>+</svg>`;+}++function fallbackSvg() {+ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0a0b10"/><stop offset="1" stop-color="#14161f"/></linearGradient>+ <linearGradient id="logoG" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8b5cf6"/><stop offset="1" stop-color="#22d3ee"/></linearGradient>+ </defs>+ <rect width="1200" height="630" fill="url(#bg)"/>+ <g transform="translate(120 240)">+ <rect x="0" y="0" width="60" height="60" rx="14" fill="url(#logoG)"/>+ <text x="80" y="40" font-family="-apple-system, system-ui, sans-serif" font-size="46" font-weight="700" fill="#e6e8f0">${escapeSvg(FALLBACK_TITLE)}</text>+ <text x="80" y="78" font-family="-apple-system, system-ui, sans-serif" font-size="22" fill="#8a90a8">${escapeSvg(FALLBACK_SUB)}</text>+ </g>+ <text x="120" y="540" font-family="-apple-system, system-ui, sans-serif" font-size="20" fill="#22d3ee">three.ws/pay</text>+</svg>`;+}++export default async function handler(req, res) {+ res.setHeader('access-control-allow-origin', '*');+ if (req.method === 'OPTIONS') { res.statusCode = 204; return res.end(); }+ if (req.method !== 'GET') { res.statusCode = 405; return res.end(); }++ const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);+ const tx = url.searchParams.get('tx') || '';++ let record = null;+ if (tx && /^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(tx)) {+ record = await readCall(tx);+ }+ const svg = record ? svgFor(record, tx) : fallbackSvg();++ try {+ const png = await sharp(Buffer.from(svg)).png({ compressionLevel: 6 }).toBuffer();+ res.statusCode = 200;+ res.setHeader('content-type', 'image/png');+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400');+ return res.end(png);+ } catch (err) {+ // Graceful fallback to SVG if sharp can't render (some envs).+ res.statusCode = 200;+ res.setHeader('content-type', 'image/svg+xml');+ res.setHeader('cache-control', 'public, max-age=300');+ return res.end(svg);+ }+}diff --git a/marketplace.css b/marketplace.cssindex 0e2c3768a..6554dcc61 100644--- a/marketplace.css+++ b/marketplace.css@@ -1350,3 +1350,548 @@ body.market-page {position: static;}}++/* ── WIP banner dismiss ──────────────────────────────────────────── */++.market-wip-dismiss {+ background: transparent;+ border: 0;+ color: #fde68a;+ opacity: 0.6;+ cursor: pointer;+ font-size: 18px;+ line-height: 1;+ padding: 4px 8px;+ border-radius: 6px;+ transition: opacity 0.15s, background 0.15s;+}+.market-wip-dismiss:hover {+ opacity: 1;+ background: rgba(253, 224, 71, 0.08);+}++/* ── Hero carousel (live 3D) ──────────────────────────────────── */++.market-hero {+ display: grid;+ grid-template-columns: minmax(280px, 480px) 1fr;+ gap: 32px;+ padding: 32px 28px;+ border-bottom: 1px solid var(--mk-border);+ background:+ radial-gradient(ellipse at top right, rgba(125, 211, 252, 0.04), transparent 60%),+ radial-gradient(ellipse at bottom left, rgba(253, 224, 71, 0.03), transparent 50%),+ var(--mk-bg);+ min-height: 360px;+ position: relative;+ overflow: hidden;+}++.market-hero-stage {+ position: relative;+ border-radius: var(--mk-radius);+ background:+ radial-gradient(ellipse at center, rgba(255, 255, 255, 0.04), transparent 70%),+ var(--mk-panel);+ border: 1px solid var(--mk-border);+ overflow: hidden;+ min-height: 320px;+ aspect-ratio: 1 / 1;+ max-width: 480px;+}++.market-hero-stage model-viewer {+ width: 100%;+ height: 100%;+ background: transparent;+ --poster-color: transparent;+ opacity: 0;+ transition: opacity 0.45s ease;+ position: absolute;+ inset: 0;+}++.market-hero-stage model-viewer.active {+ opacity: 1;+}++.market-hero-meta {+ display: flex;+ flex-direction: column;+ justify-content: center;+ gap: 14px;+ min-width: 0;+}++.market-hero-eyebrow {+ font-size: 11px;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: #7dd3fc;+ font-weight: 600;+}++.market-hero-title {+ font-family: 'Space Grotesk', 'Inter', sans-serif;+ font-size: 36px;+ font-weight: 700;+ line-height: 1.1;+ margin: 0;+ color: var(--mk-text);+ letter-spacing: -0.02em;+}++.market-hero-desc {+ font-size: 15px;+ color: var(--mk-text-2);+ line-height: 1.5;+ margin: 0;+ max-width: 56ch;+ display: -webkit-box;+ -webkit-line-clamp: 3;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.market-hero-stats {+ display: flex;+ gap: 18px;+ flex-wrap: wrap;+ margin-top: 4px;+}+.market-hero-stat {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.market-hero-stat .num {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 22px;+ font-weight: 700;+ color: var(--mk-text);+ line-height: 1;+}+.market-hero-stat .lbl {+ font-size: 11px;+ color: var(--mk-text-3);+ letter-spacing: 0.04em;+ text-transform: uppercase;+}++.market-hero-actions {+ display: flex;+ gap: 10px;+ margin-top: 8px;+ flex-wrap: wrap;+}++.market-hero-cta,+.market-hero-secondary {+ border: 0;+ border-radius: 10px;+ padding: 10px 18px;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: transform 0.1s, background 0.15s, border-color 0.15s;+}+.market-hero-cta {+ background: var(--mk-text);+ color: #000;+}+.market-hero-cta:hover {+ transform: translateY(-1px);+}+.market-hero-secondary {+ background: transparent;+ color: var(--mk-text);+ border: 1px solid var(--mk-border-2);+}+.market-hero-secondary:hover {+ border-color: var(--mk-text-2);+}++.market-hero-dots {+ display: flex;+ gap: 6px;+ margin-top: 10px;+}+.market-hero-dot {+ width: 22px;+ height: 4px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.12);+ border: 0;+ cursor: pointer;+ padding: 0;+ transition: background 0.2s, width 0.2s;+}+.market-hero-dot.active {+ background: var(--mk-text);+ width: 36px;+}++/* ── Filter chips (All / Agents / Avatars) ──────────────────── */++.market-filter-chips {+ display: inline-flex;+ gap: 4px;+ padding: 4px;+ background: var(--mk-panel-2);+ border: 1px solid var(--mk-border);+ border-radius: 10px;+}+.market-chip {+ background: transparent;+ border: 0;+ color: var(--mk-text-3);+ padding: 6px 12px;+ font-size: 12px;+ font-weight: 600;+ border-radius: 7px;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+}+.market-chip:hover {+ color: var(--mk-text-2);+}+.market-chip.active {+ background: var(--mk-bg);+ color: var(--mk-text);+}++/* ── Skeleton loaders ───────────────────────────────────────── */++@keyframes mk-skel {+ 0% { background-position: -200px 0; }+ 100% { background-position: calc(200px + 100%) 0; }+}++.mk-skel-card {+ background: var(--mk-panel);+ border: 1px solid var(--mk-border);+ border-radius: var(--mk-radius);+ padding: 16px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ min-height: 200px;+}+.mk-skel-line {+ background: linear-gradient(90deg, #1a1a1a 0%, #232323 50%, #1a1a1a 100%);+ background-size: 200px 100%;+ animation: mk-skel 1.4s ease-in-out infinite;+ border-radius: 6px;+ height: 12px;+}+.mk-skel-thumb {+ background: linear-gradient(90deg, #1a1a1a 0%, #232323 50%, #1a1a1a 100%);+ background-size: 200px 100%;+ animation: mk-skel 1.4s ease-in-out infinite;+ aspect-ratio: 1 / 1;+ border-radius: 8px;+}+.mk-skel-line.w-60 { width: 60%; }+.mk-skel-line.w-40 { width: 40%; }+.mk-skel-line.w-80 { width: 80%; }+.mk-skel-line.tall { height: 18px; }++/* ── Hover 3D preview overlay on avatar cards ──────────────── */++.market-card-avatar .thumb {+ position: relative;+ overflow: hidden;+}+.market-card-avatar .thumb model-viewer {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ background: transparent;+ --poster-color: transparent;+ opacity: 0;+ transition: opacity 0.3s ease;+}+.market-card-avatar:hover .thumb model-viewer {+ opacity: 1;+}+.market-card-avatar .thumb-badge {+ position: absolute;+ top: 8px;+ right: 8px;+ background: rgba(0, 0, 0, 0.55);+ backdrop-filter: blur(6px);+ color: #fff;+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.04em;+ padding: 3px 8px;+ border-radius: 999px;+ z-index: 2;+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.2s ease;+}+.market-card-avatar:hover .thumb-badge {+ opacity: 1;+}++/* ── My Agents states ───────────────────────────────────────── */++.market-mine-head {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.market-mine-sub {+ font-size: 12px;+ color: var(--mk-text-3);+}++.market-mine-empty,+.market-mine-signin {+ grid-column: 1 / -1;+ padding: 60px 20px;+ text-align: center;+ color: var(--mk-text-2);+ font-size: 14px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 16px;+}+.market-mine-empty .icon,+.market-mine-signin .icon {+ font-size: 42px;+ opacity: 0.3;+}+.market-mine-empty h3,+.market-mine-signin h3 {+ margin: 0;+ font-size: 18px;+ font-weight: 600;+ color: var(--mk-text);+}+.market-mine-empty p,+.market-mine-signin p {+ margin: 0;+ max-width: 36ch;+ color: var(--mk-text-3);+}+.market-mine-cta {+ background: var(--mk-text);+ color: #000;+ border: 0;+ padding: 10px 20px;+ border-radius: 10px;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ margin-top: 8px;+}+.market-mine-cta:hover {+ transform: translateY(-1px);+}++/* ── Smart empty: category w/ 0 agents ──────────────────────── */++.market-empty-redirect {+ grid-column: 1 / -1;+ padding: 32px 20px;+ text-align: center;+ background: var(--mk-panel);+ border: 1px dashed var(--mk-border-2);+ border-radius: var(--mk-radius);+ margin-bottom: 16px;+ color: var(--mk-text-2);+ font-size: 14px;+}+.market-empty-redirect strong {+ color: var(--mk-text);+}+.market-empty-redirect button {+ background: transparent;+ border: 1px solid var(--mk-border-2);+ color: var(--mk-text);+ padding: 6px 14px;+ border-radius: 8px;+ font-size: 12px;+ font-weight: 600;+ cursor: pointer;+ margin-left: 12px;+}+.market-empty-redirect button:hover {+ border-color: var(--mk-text-2);+}++/* ── Hero responsive ────────────────────────────────────────── */++@media (max-width: 880px) {+ .market-hero {+ grid-template-columns: 1fr;+ padding: 20px 16px;+ min-height: auto;+ }+ .market-hero-stage {+ max-width: 100%;+ min-height: 260px;+ aspect-ratio: 4 / 3;+ }+ .market-hero-title {+ font-size: 26px;+ }+}++/* ── Avatar card body (byline, tags, footer) ──────────────────── */++.market-card-avatar .byline {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: var(--mk-text-3);+ min-width: 0;+}+.market-card-avatar .byline .dot { color: var(--mk-text-3); opacity: 0.6; }+.market-card-avatar .byline .when { color: var(--mk-text-3); }+.card-author {+ color: #7dd3fc;+ font-weight: 500;+ text-decoration: none;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 50%;+}+.card-author:hover { text-decoration: underline; }+.card-author.muted { color: var(--mk-text-3); font-weight: 400; font-style: italic; }++.market-card-avatar .card-tags {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ margin-top: 2px;+}+.market-card-avatar .card-tags .tag-pill {+ font-size: 10px;+ padding: 2px 7px;+ background: rgba(125, 211, 252, 0.07);+ color: rgba(125, 211, 252, 0.85);+ border-radius: 999px;+}++.market-card-avatar .footer {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 4px;+}+.market-card-avatar .footer .avatar-pill {+ background: rgba(125, 211, 252, 0.1);+ color: #7dd3fc;+ padding: 2px 8px;+ border-radius: 999px;+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.02em;+}+.market-card-avatar .footer .open-cta {+ font-size: 11px;+ color: var(--mk-text-3);+ font-weight: 500;+ transition: color 0.15s, transform 0.15s;+}+.market-card-avatar:hover .footer .open-cta {+ color: #f4f4f5;+ transform: translateX(2px);+}++.market-card-avatar .thumb-fallback {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 60px;+ color: rgba(255, 255, 255, 0.18);+ background: radial-gradient(circle at 50% 50%, rgba(125, 211, 252, 0.05), transparent 70%);+}++/* ── Card skeletons (initial load) ───────────────────────────── */++@keyframes mk-card-skel {+ 0% { opacity: 0.45; }+ 50% { opacity: 0.75; }+ 100% { opacity: 0.45; }+}+.market-card-skeleton {+ background: var(--mk-panel);+ border: 1px solid var(--mk-border);+ border-radius: var(--mk-radius);+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ min-height: 240px;+ animation: mk-card-skel 1.4s ease-in-out infinite;+}+.market-card-skeleton .sk-thumb {+ aspect-ratio: 1 / 1;+ background: linear-gradient(135deg, #161616, #1c1c1c);+ border-radius: 10px;+}+.market-card-skeleton .sk-line {+ height: 12px;+ background: #1a1a1a;+ border-radius: 4px;+ width: 100%;+}+.market-card-skeleton .sk-line.short { width: 55%; }++/* ── Avatar in-page modal (3D viewer + actions) ───────────────── */++.avatar-modal-overlay[hidden] { display: none; }++/* ── Sidebar nav: live counts ─────────────────────────────────── */++.market-nav .nav-count {+ margin-left: auto;+ font-size: 10px;+ font-weight: 600;+ color: var(--mk-text-3);+ background: var(--mk-panel-2);+ border-radius: 999px;+ padding: 2px 7px;+ font-variant-numeric: tabular-nums;+ min-width: 22px;+ text-align: center;+}+.market-nav .nav-count.hot {+ color: #7dd3fc;+ background: rgba(125, 211, 252, 0.12);+}+.market-nav a {+ display: flex;+ align-items: center;+ gap: 8px;+}++/* ── Submit Avatar CTA in topbar ──────────────────────────────── */++.market-submit-avatar-btn {+ background: rgba(125, 211, 252, 0.1);+ color: #7dd3fc;+ border: 1px solid rgba(125, 211, 252, 0.25);+ border-radius: 8px;+ padding: 7px 12px;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ white-space: nowrap;+ text-decoration: none;+ transition: background 0.15s, border-color 0.15s;+}+.market-submit-avatar-btn:hover {+ background: rgba(125, 211, 252, 0.18);+ border-color: rgba(125, 211, 252, 0.4);+}diff --git a/marketplace.html b/marketplace.htmlindex de8b9dfbe..e499b2b03 100644--- a/marketplace.html+++ b/marketplace.html@@ -135,6 +135,614 @@font-weight: 500;}+ .market-wip-dismiss {+ background: none;+ border: 0;+ color: rgba(253, 224, 71, 0.6);+ font-size: 18px;+ cursor: pointer;+ padding: 0 4px;+ line-height: 1;+ }+ .market-wip-dismiss:hover {+ color: #fde047;+ }++ /* ── Hero spotlight ───────────────────────────────────────────── */+ .market-hero {+ display: grid;+ grid-template-columns: 1.3fr 1fr;+ gap: 32px;+ margin: 16px 24px 0;+ padding: 28px;+ background:+ radial-gradient(ellipse at top right, rgba(125, 211, 252, 0.08), transparent 60%),+ radial-gradient(ellipse at bottom left, rgba(168, 85, 247, 0.06), transparent 50%),+ linear-gradient(180deg, #0e0e10, #0a0a0a);+ border: 1px solid #1f1f1f;+ border-radius: 20px;+ position: relative;+ overflow: hidden;+ min-height: 280px;+ }+ .market-hero-stage {+ position: relative;+ border-radius: 14px;+ overflow: hidden;+ background:+ radial-gradient(circle at 50% 60%, rgba(125, 211, 252, 0.05), transparent 70%),+ linear-gradient(180deg, #050505, #0d0d0d);+ border: 1px solid #1a1a1a;+ min-height: 240px;+ }+ .market-hero-stage model-viewer {+ width: 100%;+ height: 100%;+ --poster-color: transparent;+ background: transparent;+ }+ .market-hero-stage::after {+ content: '';+ position: absolute;+ inset: 0;+ pointer-events: none;+ background: linear-gradient(180deg, transparent 70%, rgba(0, 0, 0, 0.4));+ }+ .market-hero-meta {+ display: flex;+ flex-direction: column;+ justify-content: center;+ gap: 14px;+ min-width: 0;+ }+ .market-hero-eyebrow {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 11px;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: #7dd3fc;+ font-weight: 600;+ }+ .market-hero-title {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 32px;+ font-weight: 700;+ color: #fafafa;+ margin: 0;+ line-height: 1.1;+ word-break: break-word;+ }+ .market-hero-desc {+ font-size: 14px;+ color: #a1a1aa;+ margin: 0;+ line-height: 1.5;+ display: -webkit-box;+ -webkit-line-clamp: 3;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .market-hero-stats {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ }+ .market-hero-stats .stat-pill {+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid #1f1f1f;+ padding: 4px 10px;+ border-radius: 999px;+ font-size: 11px;+ color: #a1a1aa;+ }+ .market-hero-actions {+ display: flex;+ gap: 10px;+ margin-top: 4px;+ flex-wrap: wrap;+ }+ .market-hero-cta {+ background: #fafafa;+ color: #0a0a0a;+ border: 0;+ padding: 11px 18px;+ border-radius: 10px;+ font-weight: 600;+ font-size: 13px;+ cursor: pointer;+ transition: transform 0.15s ease, box-shadow 0.15s ease;+ }+ .market-hero-cta:hover {+ transform: translateY(-1px);+ box-shadow: 0 8px 20px rgba(255, 255, 255, 0.08);+ }+ .market-hero-secondary {+ background: rgba(255, 255, 255, 0.06);+ color: #fafafa;+ border: 1px solid #2a2a2a;+ padding: 10px 16px;+ border-radius: 10px;+ font-weight: 500;+ font-size: 13px;+ cursor: pointer;+ }+ .market-hero-secondary:hover {+ background: rgba(255, 255, 255, 0.1);+ }+ .market-hero-dots {+ display: flex;+ gap: 6px;+ margin-top: 10px;+ }+ .market-hero-dots button {+ width: 26px;+ height: 4px;+ border-radius: 2px;+ border: 0;+ background: rgba(255, 255, 255, 0.12);+ padding: 0;+ cursor: pointer;+ transition: background 0.2s ease;+ }+ .market-hero-dots button.active {+ background: #fafafa;+ }+ @media (max-width: 880px) {+ .market-hero {+ grid-template-columns: 1fr;+ }+ .market-hero-title {+ font-size: 24px;+ }+ }++ /* ── Filter chips ─────────────────────────────────────────────── */+ .market-filter-chips {+ display: flex;+ gap: 6px;+ align-items: center;+ }+ .market-chip {+ background: transparent;+ border: 1px solid #1f1f1f;+ color: #a1a1aa;+ padding: 6px 14px;+ border-radius: 999px;+ font-size: 12px;+ cursor: pointer;+ font-weight: 500;+ transition: all 0.15s ease;+ }+ .market-chip:hover {+ border-color: #2a2a2a;+ color: #f4f4f5;+ }+ .market-chip.active {+ background: #fafafa;+ color: #0a0a0a;+ border-color: #fafafa;+ }++ /* ── Live 3D card thumbnails ──────────────────────────────────── */+ .market-card-avatar .thumb model-viewer {+ width: 100%;+ height: 100%;+ --poster-color: transparent;+ background: transparent;+ }+ .market-card-avatar .thumb {+ position: relative;+ }+ .market-card-avatar .thumb-loader {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background:+ radial-gradient(circle at 50% 50%, rgba(125, 211, 252, 0.04), transparent 60%),+ linear-gradient(180deg, #050505, #0d0d0d);+ color: rgba(255, 255, 255, 0.2);+ font-size: 32px;+ transition: opacity 0.3s ease;+ pointer-events: none;+ }+ .market-card-avatar.loaded .thumb-loader {+ opacity: 0;+ }++ /* ── Skeleton loading ─────────────────────────────────────────── */+ @keyframes mk-skeleton-pulse {+ 0%,100% { opacity: 0.4; }+ 50% { opacity: 0.7; }+ }+ .market-skeleton {+ background: linear-gradient(90deg, #111 0%, #1a1a1a 50%, #111 100%);+ background-size: 200% 100%;+ border-radius: 14px;+ border: 1px solid #1a1a1a;+ min-height: 240px;+ animation: mk-skeleton-pulse 1.4s ease-in-out infinite;+ }+ .market-card-skeleton {+ background: #0c0c0c;+ border: 1px solid #1a1a1a;+ border-radius: 14px;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }+ .market-card-skeleton .sk-thumb {+ aspect-ratio: 1 / 1;+ background: linear-gradient(90deg, #111 0%, #1a1a1a 50%, #111 100%);+ background-size: 200% 100%;+ animation: mk-skeleton-pulse 1.4s ease-in-out infinite;+ }+ .market-card-skeleton .sk-line {+ height: 12px;+ margin: 12px 14px 0;+ border-radius: 4px;+ background: linear-gradient(90deg, #111 0%, #1a1a1a 50%, #111 100%);+ background-size: 200% 100%;+ animation: mk-skeleton-pulse 1.4s ease-in-out infinite;+ }+ .market-card-skeleton .sk-line.short {+ width: 50%;+ margin-bottom: 14px;+ }++ /* ── Avatar card details: byline, tags, footer cta ──────────── */+ .market-card-avatar .byline {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: #71717a;+ min-width: 0;+ flex-wrap: wrap;+ }+ .market-card-avatar .byline .card-author {+ color: #d4d4d8;+ text-decoration: none;+ font-weight: 500;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 100%;+ }+ .market-card-avatar .byline a.card-author:hover {+ color: #7dd3fc;+ text-decoration: underline;+ }+ .market-card-avatar .byline .card-author.muted {+ color: #71717a;+ font-style: italic;+ font-weight: 400;+ }+ .market-card-avatar .byline .dot {+ color: #3f3f46;+ }+ .market-card-avatar .card-tags {+ display: flex;+ gap: 4px;+ flex-wrap: wrap;+ margin-top: 2px;+ }+ .market-card-avatar .card-tags .tag-pill {+ background: rgba(125, 211, 252, 0.06);+ border: 1px solid rgba(125, 211, 252, 0.12);+ color: #7dd3fc;+ font-size: 10px;+ padding: 2px 7px;+ border-radius: 999px;+ font-weight: 500;+ }+ .market-card-avatar .footer .open-cta {+ color: #fafafa;+ font-weight: 500;+ font-size: 11px;+ opacity: 0.6;+ transition: opacity 0.15s ease, transform 0.15s ease;+ }+ .market-card-avatar:hover .footer .open-cta {+ opacity: 1;+ transform: translateX(2px);+ }+ .market-card-avatar .thumb-fallback {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 100%;+ height: 100%;+ font-size: 38px;+ color: rgba(255, 255, 255, 0.2);+ }++ /* ── Hero slides (cross-fade between featured avatars) ──────── */+ .market-hero-stage {+ display: block;+ }+ .market-hero-slide {+ position: absolute;+ inset: 0;+ opacity: 0;+ transition: opacity 0.6s ease;+ pointer-events: none;+ }+ .market-hero-slide.active {+ opacity: 1;+ pointer-events: auto;+ }+ .market-hero-slide model-viewer {+ width: 100%;+ height: 100%;+ }++ /* ── Avatar detail modal ──────────────────────────────────────── */+ .avatar-modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.78);+ backdrop-filter: blur(6px);+ z-index: 200;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ opacity: 0;+ transition: opacity 0.2s ease;+ }+ .avatar-modal-overlay.show {+ opacity: 1;+ }+ .avatar-modal {+ background: #0d0d0d;+ border: 1px solid #1f1f1f;+ border-radius: 18px;+ width: min(960px, 100%);+ max-height: 90vh;+ display: grid;+ grid-template-columns: 1.2fr 1fr;+ overflow: hidden;+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.5);+ }+ .avatar-modal-stage {+ background:+ radial-gradient(circle at 50% 60%, rgba(125, 211, 252, 0.06), transparent 70%),+ linear-gradient(180deg, #050505, #0a0a0a);+ min-height: 480px;+ position: relative;+ }+ .avatar-modal-stage model-viewer {+ width: 100%;+ height: 100%;+ --poster-color: transparent;+ background: transparent;+ }+ .avatar-modal-side {+ padding: 24px 26px;+ display: flex;+ flex-direction: column;+ gap: 14px;+ overflow-y: auto;+ min-width: 0;+ }+ .avatar-modal-eyebrow {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 10px;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: #7dd3fc;+ font-weight: 600;+ }+ .avatar-modal-title {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 24px;+ font-weight: 700;+ color: #fafafa;+ margin: 0;+ line-height: 1.2;+ word-break: break-word;+ }+ .avatar-modal-desc {+ color: #a1a1aa;+ font-size: 13px;+ line-height: 1.5;+ margin: 0;+ }+ .avatar-modal-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 4px;+ }+ .avatar-modal-meta .stat-pill {+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid #1f1f1f;+ padding: 3px 10px;+ border-radius: 999px;+ font-size: 11px;+ color: #a1a1aa;+ }+ .avatar-modal-actions {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-top: auto;+ padding-top: 16px;+ }+ .avatar-modal-actions button,+ .avatar-modal-actions a {+ width: 100%;+ padding: 12px 16px;+ border-radius: 10px;+ font-weight: 600;+ font-size: 13px;+ cursor: pointer;+ border: 1px solid transparent;+ text-align: center;+ text-decoration: none;+ display: block;+ transition: transform 0.15s ease, background 0.15s ease;+ }+ .avatar-modal-actions .btn-primary {+ background: #fafafa;+ color: #0a0a0a;+ border-color: #fafafa;+ }+ .avatar-modal-actions .btn-primary:hover {+ transform: translateY(-1px);+ }+ .avatar-modal-actions .btn-secondary {+ background: transparent;+ color: #fafafa;+ border-color: #2a2a2a;+ }+ .avatar-modal-actions .btn-secondary:hover {+ background: rgba(255, 255, 255, 0.05);+ }+ .avatar-modal-close {+ position: absolute;+ top: 12px;+ right: 14px;+ background: rgba(0, 0, 0, 0.4);+ border: 1px solid #1f1f1f;+ color: #fafafa;+ width: 30px;+ height: 30px;+ border-radius: 50%;+ cursor: pointer;+ font-size: 18px;+ line-height: 1;+ z-index: 2;+ }+ .avatar-modal-close:hover {+ background: rgba(0, 0, 0, 0.6);+ }+ @media (max-width: 760px) {+ .avatar-modal {+ grid-template-columns: 1fr;+ max-height: 95vh;+ }+ .avatar-modal-stage {+ min-height: 280px;+ }+ }++ /* ── Skills tab ───────────────────────────────────────────────── */+ .market-skills-tab {+ padding: 0 24px 32px;+ }+ .market-skill-card {+ background: var(--mk-panel, #111);+ border: 1px solid var(--mk-border, #1f1f1f);+ border-radius: 14px;+ padding: 16px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ cursor: pointer;+ transition: border-color 0.15s ease, transform 0.15s ease;+ }+ .market-skill-card:hover {+ border-color: var(--mk-border-2, #2a2a2a);+ transform: translateY(-1px);+ }+ .market-skill-card .skill-head {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 10px;+ }+ .market-skill-card .skill-name {+ font-size: 14px;+ font-weight: 600;+ color: #fafafa;+ word-break: break-word;+ min-width: 0;+ flex: 1;+ }+ .market-skill-card .skill-price {+ flex: 0 0 auto;+ font-family: 'Space Grotesk', sans-serif;+ font-weight: 700;+ font-size: 14px;+ }+ .market-skill-card .skill-price.free {+ color: #34d399;+ }+ .market-skill-card .skill-price.paid {+ color: #fde047;+ }+ .market-skill-card .skill-agent {+ display: flex;+ align-items: center;+ gap: 8px;+ color: #a1a1aa;+ font-size: 12px;+ }+ .market-skill-card .skill-agent .av {+ width: 22px;+ height: 22px;+ border-radius: 6px;+ background: #1a1a1a;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 11px;+ font-weight: 600;+ color: #fafafa;+ flex: 0 0 auto;+ }+ .market-skill-card .skill-cta {+ margin-top: auto;+ padding: 8px 12px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid #2a2a2a;+ border-radius: 8px;+ font-size: 12px;+ color: #fafafa;+ font-weight: 500;+ text-align: center;+ cursor: pointer;+ }+ .market-skill-card .skill-cta:hover {+ background: rgba(255, 255, 255, 0.08);+ }+ .market-skill-card .skill-cta.purchase {+ background: #fafafa;+ color: #0a0a0a;+ border-color: #fafafa;+ }++ /* ── Empty state CTA ──────────────────────────────────────────── */+ .market-empty-cta {+ grid-column: 1 / -1;+ padding: 48px 24px;+ text-align: center;+ color: #a1a1aa;+ }+ .market-empty-cta h3 {+ font-family: 'Space Grotesk', sans-serif;+ color: #fafafa;+ margin: 0 0 8px;+ font-size: 18px;+ }+ .market-empty-cta p {+ margin: 0 0 16px;+ font-size: 14px;+ }+ .market-empty-cta button {+ background: #fafafa;+ color: #0a0a0a;+ border: 0;+ padding: 10px 18px;+ border-radius: 10px;+ font-weight: 600;+ font-size: 13px;+ cursor: pointer;+ }+.price-badge {display: inline-block;margin-left: 8px;@@ -241,6 +849,7 @@<script src="https://unpkg.com/@solana/wallet-adapter-react@latest/lib/index.iife.js"></script><script src="https://unpkg.com/@solana/wallet-adapter-react-ui@latest/lib/index.iife.js"></script>+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script></head><body class="market-page"><aside class="market-sidebar" id="market-sidebar">@@ -249,40 +858,64 @@<span>Community</span></a><nav class="market-nav">- <a href="/" data-nav="home"><span class="ico">⌂</span> Home</a>- <a href="/marketplace" data-nav="agent" class="active"><span class="ico">▣</span> Agent</a>- <a href="/marketplace?tab=tools" data-nav="tools"><span class="ico">⚙</span> Tools</a>- <a href="/marketplace?tab=skills" data-nav="skills"><span class="ico">≡</span> Skills</a>- <a href="/dashboard" data-nav="model"><span class="ico">◉</span> Model</a>- <a href="/marketplace?tab=mine" data-nav="mine"><span class="ico">◱</span> My Agents</a>+ <a href="/" data-nav="home"><span class="ico">⌂</span> <span>Home</span></a>+ <a href="/marketplace" data-nav="agent" class="active"><span class="ico">▣</span> <span>Agent</span><span class="nav-count" id="nav-count-agent" hidden></span></a>+ <a href="/marketplace?tab=avatars" data-nav="avatars"><span class="ico">◉</span> <span>Avatars</span><span class="nav-count hot" id="nav-count-avatar" hidden></span></a>+ <a href="/marketplace?tab=tools" data-nav="tools"><span class="ico">⚙</span> <span>Tools</span></a>+ <a href="/marketplace?tab=skills" data-nav="skills"><span class="ico">≡</span> <span>Skills</span></a>+ <a href="/dashboard" data-nav="model"><span class="ico">◉</span> <span>Model</span></a>+ <a href="/marketplace?tab=mine" data-nav="mine"><span class="ico">◱</span> <span>My Agents</span></a></nav><button class="market-submit-btn market-sidebar-submit" id="market-submit-btn">+ Submit Agent</button></aside><main class="market-main" id="market-main">- <div class="market-wip-banner" role="status">+ <div class="market-wip-banner" id="market-wip-banner" role="status" hidden><span class="market-wip-icon" aria-hidden="true">!</span><div class="market-wip-text">- <strong>Work in progress.</strong>- This marketplace is still being built — features, paid skills, and listings may be incomplete or change.+ <strong>Marketplace is in beta.</strong>+ Avatars, chat, and forking are stable. <em>Paid skills, on-chain agent listings, and submission moderation are still landing</em> — expect rough edges.</div>+ <button class="market-wip-dismiss" id="market-wip-dismiss" aria-label="Dismiss">×</button></div><!-- Discovery view --><section class="market-discovery" id="market-discovery">+ <!-- Live 3D hero carousel -->+ <section class="market-hero" id="market-hero" hidden aria-label="Featured 3D avatars">+ <div class="market-hero-stage" id="market-hero-stage"></div>+ <div class="market-hero-meta">+ <div class="market-hero-eyebrow">Featured · Community Avatars</div>+ <h1 class="market-hero-title" id="market-hero-title">—</h1>+ <p class="market-hero-desc" id="market-hero-desc">—</p>+ <div class="market-hero-stats" id="market-hero-stats"></div>+ <div class="market-hero-actions">+ <button class="market-hero-cta" id="market-hero-view">View in 3D →</button>+ <button class="market-hero-secondary" id="market-hero-fork" hidden>Fork agent</button>+ </div>+ <div class="market-hero-dots" id="market-hero-dots"></div>+ </div>+ </section>+<header class="market-topbar"><inputid="market-search"type="search"- placeholder="Search by name, description, or keywords…"+ placeholder="Search agents and avatars…"autocomplete="off"/>+ <div class="market-filter-chips" id="market-filter-chips" role="tablist" aria-label="Filter">+ <button class="market-chip active" data-filter="all" role="tab">All</button>+ <button class="market-chip" data-filter="agents" role="tab">Agents</button>+ <button class="market-chip" data-filter="avatars" role="tab">Avatars</button>+ </div><select id="market-sort" class="market-sort"><option value="recommended">Recommended</option><option value="recent">Recent</option><option value="popular">Popular</option></select><button class="market-submit-btn" id="market-submit-btn-top">+ Submit Agent</button>+ <a class="market-submit-avatar-btn" href="/create" id="market-submit-avatar-btn">+ Create Avatar</a><div class="wallet-adapter-button-container"></div></header>@@ -379,7 +1012,10 @@<!-- My Agents tab --><section class="market-mine" id="market-mine" hidden><header class="market-topbar">- <h2 class="market-section-heading">My Agents</h2>+ <div class="market-mine-head">+ <h2 class="market-section-heading">My Agents</h2>+ <span class="market-mine-sub" id="mine-subtitle"></span>+ </div><button class="market-submit-btn" id="market-new-agent-btn">+ New Agent</button></header><div class="market-mine-body">@@ -387,6 +1023,33 @@</div></section>+ <!-- Skills tab -->+ <section class="market-skills-section" id="market-skills-section" hidden>+ <header class="market-topbar">+ <div class="market-mine-head">+ <h2 class="market-section-heading">Skills Marketplace</h2>+ <span class="market-mine-sub" id="skills-subtitle">Browse capabilities you can unlock or fork</span>+ </div>+ <input+ id="skills-search"+ type="search"+ placeholder="Search skills…"+ autocomplete="off"+ style="flex:1;max-width:320px"+ />+ <div class="market-filter-chips" role="tablist" aria-label="Skill filter">+ <button class="market-chip active" data-skill-filter="all" role="tab">All</button>+ <button class="market-chip" data-skill-filter="free" role="tab">Free</button>+ <button class="market-chip" data-skill-filter="paid" role="tab">Paid</button>+ </div>+ </header>+ <div class="market-skills-tab">+ <div class="market-grid" id="skills-grid">+ <div class="market-empty">Loading skills…</div>+ </div>+ </div>+ </section>+<!-- Plugins tab --><section class="market-tools" id="market-tools" hidden><header class="market-topbar plugins-topbar">@@ -512,6 +1175,26 @@<script src="/src/marketplace.js" type="module"></script>+ <!-- Avatar Detail Modal -->+ <div class="avatar-modal-overlay" id="avatar-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="avatar-modal-title">+ <div class="avatar-modal" role="document">+ <div class="avatar-modal-stage" id="avatar-modal-stage">+ <button class="avatar-modal-close" id="avatar-modal-close" aria-label="Close">×</button>+ </div>+ <div class="avatar-modal-side">+ <div class="avatar-modal-eyebrow">Community Avatar</div>+ <h2 class="avatar-modal-title" id="avatar-modal-title">—</h2>+ <p class="avatar-modal-desc" id="avatar-modal-desc"></p>+ <div class="avatar-modal-meta" id="avatar-modal-meta"></div>+ <div class="avatar-modal-actions">+ <button class="btn-primary" id="avatar-modal-use">Start an agent with this avatar</button>+ <a class="btn-secondary" id="avatar-modal-view" href="#" target="_blank" rel="noopener">Open in 3D viewer</a>+ <a class="btn-secondary" id="avatar-modal-download" href="#" download>Download GLB</a>+ </div>+ </div>+ </div>+ </div>+<!-- Payment Modal --><div class="market-modal-overlay" id="payment-modal-overlay" hidden aria-modal="true" role="dialog" aria-labelledby="payment-modal-title"><div class="market-modal">diff --git a/package.json b/package.jsonindex 82e6fc1bf..9d680e5ad 100644--- a/package.json+++ b/package.json@@ -45,6 +45,7 @@"dev:lib": "TARGET=lib vite","build": "vite build","build:animations": "node scripts/build-animations.mjs",+ "build:artifact-viewer": "node scripts/build-artifact-viewer.mjs","build:lib": "TARGET=lib vite build","build:lib:full": "TARGET=lib LIB_FORMATS=es,umd vite build","build:artifact": "vite build --config vite.config.artifact.js",diff --git a/public/artifact-viewer.bundle.js b/public/artifact-viewer.bundle.jsnew file mode 100644index 000000000..67d7bf6a6--- /dev/null+++ b/public/artifact-viewer.bundle.js@@ -0,0 +1,3822 @@+/* artifact-viewer bundle — three.js + GLTFLoader + viewer.+ * Built from scripts/artifact-viewer/src.js. Do not edit by hand.+ * Generated: 2026-05-10T00:35:56.186Z */+(()=>{var Gl=0,Fa=1,Wl=2;var Oa=1,Xl=2,vn=3,rn=0,Pt=1,Yt=2,Nn=0,ai=1,Ba=2,za=3,ka=4,ql=5,qn=100,Yl=101,Zl=102,Kl=103,Jl=104,$l=200,jl=201,Ql=202,eh=203,Nr=204,Fr=205,th=206,nh=207,ih=208,sh=209,rh=210,oh=211,ah=212,ch=213,lh=214,to=0,no=1,io=2,ci=3,so=4,ro=5,oo=6,ao=7,Va=0,hh=1,uh=2,Fn=0,dh=1,fh=2,ph=3,co=4,mh=5,gh=6,_h=7,Ra="attached",xh="detached",Ha=300,xi=301,yi=302,lo=303,ho=304,js=306,Yn=1e3,dn=1001,Hi=1002,yt=1003,uo=1004;var vi=1005;var Ct=1006,ts=1007;var ln=1008;var hn=1009,Ga=1010,Wa=1011,ns=1012,fo=1013,Jn=1014,Zt=1015,is=1016,po=1017,mo=1018,ss=1020,Xa=35902,qa=1021,Ya=1022,Ht=1023,Gi=1026,rs=1027,go=1028,_o=1029,Za=1030,xo=1031;var yo=1033,Qs=33776,er=33777,tr=33778,nr=33779,vo=35840,Mo=35841,So=35842,bo=35843,To=36196,Eo=37492,Ao=37496,wo=37808,Ro=37809,Co=37810,Io=37811,Po=37812,Lo=37813,Do=37814,Uo=37815,No=37816,Fo=37817,Oo=37818,Bo=37819,zo=37820,ko=37821,ir=36492,Vo=36494,Ho=36495,Ka=36283,Go=36284,Wo=36285,Xo=36286,yh=2200,vh=2201,Mh=2202,li=2300,hi=2301,Ur=2302,ri=2400,oi=2401,bs=2402,qo=2500,Sh=2501,Ja=0,sr=1,os=2,bh=3200,Th=3201;var $a=0,Eh=1,On="",lt="srgb",vt="srgb-linear",Ts="linear",je="srgb";var si=7680;var Ca=519,Ah=512,wh=513,Rh=514,ja=515,Ch=516,Ih=517,Ph=518,Lh=519,Or=35044;var Qa="300 es",fn=2e3,Es=2001;var pn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let i=n.slice(0);for(let r=0,o=i.length;r<o;r++)i[r].call(this,e);e.target=null}}},bt=["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"],ol=1234567,Ms=Math.PI/180,ui=180/Math.PI;function sn(){let s=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(bt[s&255]+bt[s>>8&255]+bt[s>>16&255]+bt[s>>24&255]+"-"+bt[e&255]+bt[e>>8&255]+"-"+bt[e>>16&15|64]+bt[e>>24&255]+"-"+bt[t&63|128]+bt[t>>8&255]+"-"+bt[t>>16&255]+bt[t>>24&255]+bt[n&255]+bt[n>>8&255]+bt[n>>16&255]+bt[n>>24&255]).toLowerCase()}function Fe(s,e,t){return Math.max(e,Math.min(t,s))}function ec(s,e){return(s%e+e)%e}function wu(s,e,t,n,i){return n+(s-e)*(i-n)/(t-e)}function Ru(s,e,t){return s!==e?(t-s)/(e-s):0}function Ss(s,e,t){return(1-t)*s+t*e}function Cu(s,e,t,n){return Ss(s,e,1-Math.exp(-t*n))}function Iu(s,e=1){return e-Math.abs(ec(s,e*2)-e)}function Pu(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*(3-2*s))}function Lu(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*s*(s*(s*6-15)+10))}function Du(s,e){return s+Math.floor(Math.random()*(e-s+1))}function Uu(s,e){return s+Math.random()*(e-s)}function Nu(s){return s*(.5-Math.random())}function Fu(s){s!==void 0&&(ol=s);let e=ol+=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 Ou(s){return s*Ms}function Bu(s){return s*ui}function zu(s){return(s&s-1)===0&&s!==0}function ku(s){return Math.pow(2,Math.ceil(Math.log(s)/Math.LN2))}function Vu(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function Hu(s,e,t,n,i){let r=Math.cos,o=Math.sin,a=r(t/2),c=o(t/2),l=r((e+n)/2),h=o((e+n)/2),u=r((e-n)/2),d=o((e-n)/2),p=r((n-e)/2),g=o((n-e)/2);switch(i){case"XYX":s.set(a*h,c*u,c*d,a*l);break;case"YZY":s.set(c*d,a*h,c*u,a*l);break;case"ZXZ":s.set(c*u,c*d,a*h,a*l);break;case"XZX":s.set(a*h,c*g,c*p,a*l);break;case"YXY":s.set(c*p,a*h,c*g,a*l);break;case"ZYZ":s.set(c*g,c*p,a*h,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function tn(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function $e(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}var tc={DEG2RAD:Ms,RAD2DEG:ui,generateUUID:sn,clamp:Fe,euclideanModulo:ec,mapLinear:wu,inverseLerp:Ru,lerp:Ss,damp:Cu,pingpong:Iu,smoothstep:Pu,smootherstep:Lu,randInt:Du,randFloat:Uu,randFloatSpread:Nu,seededRandom:Fu,degToRad:Ou,radToDeg:Bu,isPowerOfTwo:zu,ceilPowerOfTwo:ku,floorPowerOfTwo:Vu,setQuaternionFromProperEuler:Hu,normalize:$e,denormalize:tn},ze=class s{constructor(e=0,t=0){s.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){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[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=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(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){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Fe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let 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){let n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*i+e.x,this.y=r*i+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Pe=class s{constructor(e,t,n,i,r,o,a,c,l){s.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,r,o,a,c,l)}set(e,t,n,i,r,o,a,c,l){let h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=r,h[5]=c,h[6]=n,h[7]=o,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let 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){let 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){let n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],h=n[4],u=n[7],d=n[2],p=n[5],g=n[8],_=i[0],m=i[3],f=i[6],E=i[1],T=i[4],M=i[7],L=i[2],R=i[5],w=i[8];return r[0]=o*_+a*E+c*L,r[3]=o*m+a*T+c*R,r[6]=o*f+a*M+c*w,r[1]=l*_+h*E+u*L,r[4]=l*m+h*T+u*R,r[7]=l*f+h*M+u*w,r[2]=d*_+p*E+g*L,r[5]=d*m+p*T+g*R,r[8]=d*f+p*M+g*w,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8];return t*o*h-t*a*l-n*r*h+n*a*c+i*r*l-i*o*c}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=h*o-a*l,d=a*c-h*r,p=l*r-o*c,g=t*u+n*d+i*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/g;return e[0]=u*_,e[1]=(i*l-h*n)*_,e[2]=(a*n-i*o)*_,e[3]=d*_,e[4]=(h*t-i*c)*_,e[5]=(i*r-a*t)*_,e[6]=p*_,e[7]=(n*c-l*t)*_,e[8]=(o*t-n*r)*_,this}transpose(){let e,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){let 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,i,r,o,a){let c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(ia.makeScale(e,t)),this}rotate(e){return this.premultiply(ia.makeRotation(-e)),this}translate(e,t){return this.premultiply(ia.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){let 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){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])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){let 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)}},ia=new Pe;function nc(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function Wi(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}function Dh(){let s=Wi("canvas");return s.style.display="block",s}var al={};function rr(s){s in al||(al[s]=!0,console.warn(s))}function Uh(s,e,t){return new Promise(function(n,i){function r(){switch(s.clientWaitSync(e,s.SYNC_FLUSH_COMMANDS_BIT,0)){case s.WAIT_FAILED:i();break;case s.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}function Nh(s){let e=s.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 Fh(s){let e=s.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}var cl=new Pe().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ll=new Pe().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Gu(){let s={enabled:!0,workingColorSpace:vt,spaces:{},convert:function(i,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===je&&(i.r=In(i.r),i.g=In(i.g),i.b=In(i.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(i.applyMatrix3(this.spaces[r].toXYZ),i.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===je&&(i.r=Vi(i.r),i.g=Vi(i.g),i.b=Vi(i.b))),i},fromWorkingColorSpace:function(i,r){return this.convert(i,this.workingColorSpace,r)},toWorkingColorSpace:function(i,r){return this.convert(i,r,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===On?Ts:this.spaces[i].transfer},getLuminanceCoefficients:function(i,r=this.workingColorSpace){return i.fromArray(this.spaces[r].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,r,o){return i.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return s.define({[vt]:{primaries:e,whitePoint:n,transfer:Ts,toXYZ:cl,fromXYZ:ll,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:lt},outputColorSpaceConfig:{drawingBufferColorSpace:lt}},[lt]:{primaries:e,whitePoint:n,transfer:je,toXYZ:cl,fromXYZ:ll,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:lt}}}),s}var Be=Gu();function In(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function Vi(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}var Ri,Br=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{Ri===void 0&&(Ri=Wi("canvas")),Ri.width=e.width,Ri.height=e.height;let i=Ri.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=Ri}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){let t=Wi("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let o=0;o<r.length;o++)r[o]=In(r[o]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(In(t[n]/255)*255):t[n]=In(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}},Wu=0,Xi=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Wu++}),this.uuid=sn(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:""},i=this.data;if(i!==null){let r;if(Array.isArray(i)){r=[];for(let o=0,a=i.length;o<a;o++)i[o].isDataTexture?r.push(sa(i[o].image)):r.push(sa(i[o]))}else r=sa(i);n.url=r}return t||(e.images[this.uuid]=n),n}};function sa(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&s instanceof ImageBitmap?Br.getDataURL(s):s.data?{data:Array.from(s.data),width:s.width,height:s.height,type:s.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}var Xu=0,_t=class s extends pn{constructor(e=s.DEFAULT_IMAGE,t=s.DEFAULT_MAPPING,n=dn,i=dn,r=Ct,o=ln,a=Ht,c=hn,l=s.DEFAULT_ANISOTROPY,h=On){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Xu++}),this.uuid=sn(),this.name="",this.source=new Xi(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,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 Pe,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){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let 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!==Ha)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Yn:e.x=e.x-Math.floor(e.x);break;case dn:e.x=e.x<0?0:1;break;case Hi: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 Yn:e.y=e.y-Math.floor(e.y);break;case dn:e.y=e.y<0?0:1;break;case Hi: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++}};_t.DEFAULT_IMAGE=null;_t.DEFAULT_MAPPING=Ha;_t.DEFAULT_ANISOTROPY=1;var qe=class s{constructor(e=0,t=0,n=0,i=1){s.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}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,i){return this.x=e,this.y=t,this.z=n,this.w=i,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){let t=this.x,n=this.y,i=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*i+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*i+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*i+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*i+o[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);let 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,i,r,c=e.elements,l=c[0],h=c[4],u=c[8],d=c[1],p=c[5],g=c[9],_=c[2],m=c[6],f=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-_)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+_)<.1&&Math.abs(g+m)<.1&&Math.abs(l+p+f-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let T=(l+1)/2,M=(p+1)/2,L=(f+1)/2,R=(h+d)/4,w=(u+_)/4,N=(g+m)/4;return T>M&&T>L?T<.01?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(T),i=R/n,r=w/n):M>L?M<.01?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(M),n=R/i,r=N/i):L<.01?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(L),n=w/r,i=N/r),this.set(n,i,r,t),this}let E=Math.sqrt((m-g)*(m-g)+(u-_)*(u-_)+(d-h)*(d-h));return Math.abs(E)<.001&&(E=1),this.x=(m-g)/E,this.y=(u-_)/E,this.z=(d-h)/E,this.w=Math.acos((l+p+f-1)/2),this}setFromMatrixPosition(e){let 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=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this.z=Fe(this.z,e.z,t.z),this.w=Fe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this.z=Fe(this.z,e,t),this.w=Fe(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(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}},zr=class extends pn{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 qe(0,0,e,t),this.scissorTest=!1,this.viewport=new qe(0,0,e,t);let i={width:e,height:t,depth:this.depth};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ct,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,multiview:!1},n);let r=new _t(i,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=[];let o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].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 i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].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;let i=Object.assign({},e.textures[t].image);this.textures[t].source=new Xi(i)}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"})}},mn=class extends zr{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},As=class extends _t{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=yt,this.minFilter=yt,this.wrapR=dn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}};var kr=class extends _t{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=yt,this.minFilter=yt,this.wrapR=dn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var Rt=class{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,o,a){let c=n[i+0],l=n[i+1],h=n[i+2],u=n[i+3],d=r[o+0],p=r[o+1],g=r[o+2],_=r[o+3];if(a===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=p,e[t+2]=g,e[t+3]=_;return}if(u!==_||c!==d||l!==p||h!==g){let m=1-a,f=c*d+l*p+h*g+u*_,E=f>=0?1:-1,T=1-f*f;if(T>Number.EPSILON){let L=Math.sqrt(T),R=Math.atan2(L,f*E);m=Math.sin(m*R)/L,a=Math.sin(a*R)/L}let M=a*E;if(c=c*m+d*M,l=l*m+p*M,h=h*m+g*M,u=u*m+_*M,m===1-a){let L=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=L,l*=L,h*=L,u*=L}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,o){let a=n[i],c=n[i+1],l=n[i+2],h=n[i+3],u=r[o],d=r[o+1],p=r[o+2],g=r[o+3];return e[t]=a*g+h*u+c*p-l*d,e[t+1]=c*g+h*d+l*u-a*p,e[t+2]=l*g+h*p+a*d-c*u,e[t+3]=h*g-a*u-c*d-l*p,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,i){return this._x=e,this._y=t,this._z=n,this._w=i,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){let n=e._x,i=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),h=a(i/2),u=a(r/2),d=c(n/2),p=c(i/2),g=c(r/2);switch(o){case"XYZ":this._x=d*h*u+l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u-d*p*g;break;case"YXZ":this._x=d*h*u+l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u+d*p*g;break;case"ZXY":this._x=d*h*u-l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u-d*p*g;break;case"ZYX":this._x=d*h*u-l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u+d*p*g;break;case"YZX":this._x=d*h*u+l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u-d*p*g;break;case"XZY":this._x=d*h*u-l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u+d*p*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],h=t[6],u=t[10],d=n+a+u;if(d>0){let p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-c)*p,this._y=(r-l)*p,this._z=(o-i)*p}else if(n>a&&n>u){let p=2*Math.sqrt(1+n-a-u);this._w=(h-c)/p,this._x=.25*p,this._y=(i+o)/p,this._z=(r+l)/p}else if(a>u){let p=2*Math.sqrt(1+a-n-u);this._w=(r-l)/p,this._x=(i+o)/p,this._y=.25*p,this._z=(c+h)/p}else{let p=2*Math.sqrt(1+u-n-a);this._w=(o-i)/p,this._x=(r+l)/p,this._y=(c+h)/p,this._z=.25*p}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(Fe(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),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){let n=e._x,i=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+o*a+i*l-r*c,this._y=i*h+o*c+r*a-n*l,this._z=r*h+o*l+n*c-i*a,this._w=o*h-n*a-i*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,i=this._y,r=this._z,o=this._w,a=o*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=n,this._y=i,this._z=r,this;let c=1-a*a;if(c<=Number.EPSILON){let p=1-t;return this._w=p*o+t*this._w,this._x=p*n+t*this._x,this._y=p*i+t*this._y,this._z=p*r+t*this._z,this.normalize(),this}let l=Math.sqrt(c),h=Math.atan2(l,a),u=Math.sin((1-t)*h)/l,d=Math.sin(t*h)/l;return this._w=o*u+this._w*d,this._x=n*u+this._x*d,this._y=i*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(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*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}},P=class s{constructor(e=0,t=0,n=0){s.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(hl.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hl.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*o,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*i-a*n),h=2*(a*t-r*i),u=2*(r*n-o*t);return this.x=t+c*l+o*u-a*h,this.y=n+c*h+a*l-r*u,this.z=i+c*u+r*h-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,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=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this.z=Fe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this.z=Fe(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(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){let n=e.x,i=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=i*c-r*a,this.y=r*o-n*c,this.z=n*a-i*o,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return ra.copy(this).projectOnVector(e),this.sub(ra)}reflect(e){return this.sub(ra.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Fe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}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){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*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){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,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(){let 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}},ra=new P,hl=new Rt,It=class{constructor(e=new P(1/0,1/0,1/0),t=new P(-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(jt.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(jt.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){let n=jt.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);let n=e.geometry;if(n!==void 0){let r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,jt):jt.fromBufferAttribute(r,o),jt.applyMatrix4(e.matrixWorld),this.expandByPoint(jt);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),hr.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),hr.copy(n.boundingBox)),hr.applyMatrix4(e.matrixWorld),this.union(hr)}let i=e.children;for(let r=0,o=i.length;r<o;r++)this.expandByObject(i[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,jt),jt.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(fs),ur.subVectors(this.max,fs),Ci.subVectors(e.a,fs),Ii.subVectors(e.b,fs),Pi.subVectors(e.c,fs),zn.subVectors(Ii,Ci),kn.subVectors(Pi,Ii),ei.subVectors(Ci,Pi);let t=[0,-zn.z,zn.y,0,-kn.z,kn.y,0,-ei.z,ei.y,zn.z,0,-zn.x,kn.z,0,-kn.x,ei.z,0,-ei.x,-zn.y,zn.x,0,-kn.y,kn.x,0,-ei.y,ei.x,0];return!oa(t,Ci,Ii,Pi,ur)||(t=[1,0,0,0,1,0,0,0,1],!oa(t,Ci,Ii,Pi,ur))?!1:(dr.crossVectors(zn,kn),t=[dr.x,dr.y,dr.z],oa(t,Ci,Ii,Pi,ur))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,jt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(jt).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:(bn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),bn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),bn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),bn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),bn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),bn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),bn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),bn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(bn),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)}},bn=[new P,new P,new P,new P,new P,new P,new P,new P],jt=new P,hr=new It,Ci=new P,Ii=new P,Pi=new P,zn=new P,kn=new P,ei=new P,fs=new P,ur=new P,dr=new P,ti=new P;function oa(s,e,t,n,i){for(let r=0,o=s.length-3;r<=o;r+=3){ti.fromArray(s,r);let a=i.x*Math.abs(ti.x)+i.y*Math.abs(ti.y)+i.z*Math.abs(ti.z),c=e.dot(ti),l=t.dot(ti),h=n.dot(ti);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}var qu=new It,ps=new P,aa=new P,Dt=class{constructor(e=new P,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){let n=this.center;t!==void 0?n.copy(t):qu.setFromPoints(e).getCenter(n);let i=0;for(let r=0,o=e.length;r<o;r++)i=Math.max(i,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),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){let 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){let 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;ps.subVectors(e,this.center);let t=ps.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(ps,i/n),this.radius+=i}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):(aa.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ps.copy(e.center).add(aa)),this.expandByPoint(ps.copy(e.center).sub(aa))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},Tn=new P,ca=new P,fr=new P,Vn=new P,la=new P,pr=new P,ha=new P,di=class{constructor(e=new P,t=new P(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,Tn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let 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){let t=Tn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Tn.copy(this.origin).addScaledVector(this.direction,t),Tn.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){ca.copy(e).add(t).multiplyScalar(.5),fr.copy(t).sub(e).normalize(),Vn.copy(this.origin).sub(ca);let r=e.distanceTo(t)*.5,o=-this.direction.dot(fr),a=Vn.dot(this.direction),c=-Vn.dot(fr),l=Vn.lengthSq(),h=Math.abs(1-o*o),u,d,p,g;if(h>0)if(u=o*c-a,d=o*a-c,g=r*h,u>=0)if(d>=-g)if(d<=g){let _=1/h;u*=_,d*=_,p=u*(u+o*d+2*a)+d*(o*u+d+2*c)+l}else d=r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;else d=-r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;else d<=-g?(u=Math.max(0,-(-o*r+a)),d=u>0?-r:Math.min(Math.max(-r,-c),r),p=-u*u+d*(d+2*c)+l):d<=g?(u=0,d=Math.min(Math.max(-r,-c),r),p=d*(d+2*c)+l):(u=Math.max(0,-(o*r+a)),d=u>0?r:Math.min(Math.max(-r,-c),r),p=-u*u+d*(d+2*c)+l);else d=o>0?-r:r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(ca).addScaledVector(fr,d),p}intersectSphere(e,t){Tn.subVectors(e.center,this.origin);let n=Tn.dot(this.direction),i=Tn.dot(Tn)-n*n,r=e.radius*e.radius;if(i>r)return null;let o=Math.sqrt(r-i),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,o,a,c,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,i=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,i=(e.min.x-d.x)*l),h>=0?(r=(e.min.y-d.y)*h,o=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,o=(e.min.y-d.y)*h),n>o||r>i||((r>n||isNaN(n))&&(n=r),(o<i||isNaN(i))&&(i=o),u>=0?(a=(e.min.z-d.z)*u,c=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,c=(e.min.z-d.z)*u),n>c||a>i)||((a>n||n!==n)&&(n=a),(c<i||i!==i)&&(i=c),i<0)?null:this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,Tn)!==null}intersectTriangle(e,t,n,i,r){la.subVectors(t,e),pr.subVectors(n,e),ha.crossVectors(la,pr);let o=this.direction.dot(ha),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Vn.subVectors(this.origin,e);let c=a*this.direction.dot(pr.crossVectors(Vn,pr));if(c<0)return null;let l=a*this.direction.dot(la.cross(Vn));if(l<0||c+l>o)return null;let h=-a*Vn.dot(ha);return h<0?null:this.at(h/o,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)}},Ie=class s{constructor(e,t,n,i,r,o,a,c,l,h,u,d,p,g,_,m){s.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,i,r,o,a,c,l,h,u,d,p,g,_,m)}set(e,t,n,i,r,o,a,c,l,h,u,d,p,g,_,m){let f=this.elements;return f[0]=e,f[4]=t,f[8]=n,f[12]=i,f[1]=r,f[5]=o,f[9]=a,f[13]=c,f[2]=l,f[6]=h,f[10]=u,f[14]=d,f[3]=p,f[7]=g,f[11]=_,f[15]=m,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 s().fromArray(this.elements)}copy(e){let 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){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let 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){let t=this.elements,n=e.elements,i=1/Li.setFromMatrixColumn(e,0).length(),r=1/Li.setFromMatrixColumn(e,1).length(),o=1/Li.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,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]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,i=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(i),l=Math.sin(i),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let d=o*h,p=o*u,g=a*h,_=a*u;t[0]=c*h,t[4]=-c*u,t[8]=l,t[1]=p+g*l,t[5]=d-_*l,t[9]=-a*c,t[2]=_-d*l,t[6]=g+p*l,t[10]=o*c}else if(e.order==="YXZ"){let d=c*h,p=c*u,g=l*h,_=l*u;t[0]=d+_*a,t[4]=g*a-p,t[8]=o*l,t[1]=o*u,t[5]=o*h,t[9]=-a,t[2]=p*a-g,t[6]=_+d*a,t[10]=o*c}else if(e.order==="ZXY"){let d=c*h,p=c*u,g=l*h,_=l*u;t[0]=d-_*a,t[4]=-o*u,t[8]=g+p*a,t[1]=p+g*a,t[5]=o*h,t[9]=_-d*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){let d=o*h,p=o*u,g=a*h,_=a*u;t[0]=c*h,t[4]=g*l-p,t[8]=d*l+_,t[1]=c*u,t[5]=_*l+d,t[9]=p*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){let d=o*c,p=o*l,g=a*c,_=a*l;t[0]=c*h,t[4]=_-d*u,t[8]=g*u+p,t[1]=u,t[5]=o*h,t[9]=-a*h,t[2]=-l*h,t[6]=p*u+g,t[10]=d-_*u}else if(e.order==="XZY"){let d=o*c,p=o*l,g=a*c,_=a*l;t[0]=c*h,t[4]=-u,t[8]=l*h,t[1]=d*u+_,t[5]=o*h,t[9]=p*u-g,t[2]=g*u-p,t[6]=a*h,t[10]=_*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(Yu,e,Zu)}lookAt(e,t,n){let i=this.elements;return Bt.subVectors(e,t),Bt.lengthSq()===0&&(Bt.z=1),Bt.normalize(),Hn.crossVectors(n,Bt),Hn.lengthSq()===0&&(Math.abs(n.z)===1?Bt.x+=1e-4:Bt.z+=1e-4,Bt.normalize(),Hn.crossVectors(n,Bt)),Hn.normalize(),mr.crossVectors(Bt,Hn),i[0]=Hn.x,i[4]=mr.x,i[8]=Bt.x,i[1]=Hn.y,i[5]=mr.y,i[9]=Bt.y,i[2]=Hn.z,i[6]=mr.z,i[10]=Bt.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],h=n[1],u=n[5],d=n[9],p=n[13],g=n[2],_=n[6],m=n[10],f=n[14],E=n[3],T=n[7],M=n[11],L=n[15],R=i[0],w=i[4],N=i[8],S=i[12],v=i[1],C=i[5],q=i[9],z=i[13],W=i[2],J=i[6],G=i[10],Q=i[14],V=i[3],ie=i[7],he=i[11],_e=i[15];return r[0]=o*R+a*v+c*W+l*V,r[4]=o*w+a*C+c*J+l*ie,r[8]=o*N+a*q+c*G+l*he,r[12]=o*S+a*z+c*Q+l*_e,r[1]=h*R+u*v+d*W+p*V,r[5]=h*w+u*C+d*J+p*ie,r[9]=h*N+u*q+d*G+p*he,r[13]=h*S+u*z+d*Q+p*_e,r[2]=g*R+_*v+m*W+f*V,r[6]=g*w+_*C+m*J+f*ie,r[10]=g*N+_*q+m*G+f*he,r[14]=g*S+_*z+m*Q+f*_e,r[3]=E*R+T*v+M*W+L*V,r[7]=E*w+T*C+M*J+L*ie,r[11]=E*N+T*q+M*G+L*he,r[15]=E*S+T*z+M*Q+L*_e,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],h=e[2],u=e[6],d=e[10],p=e[14],g=e[3],_=e[7],m=e[11],f=e[15];return g*(+r*c*u-i*l*u-r*a*d+n*l*d+i*a*p-n*c*p)+_*(+t*c*p-t*l*d+r*o*d-i*o*p+i*l*h-r*c*h)+m*(+t*l*u-t*a*p-r*o*u+n*o*p+r*a*h-n*l*h)+f*(-i*a*h-t*c*u+t*a*d+i*o*u-n*o*d+n*c*h)}transpose(){let e=this.elements,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){let i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],p=e[11],g=e[12],_=e[13],m=e[14],f=e[15],E=u*m*l-_*d*l+_*c*p-a*m*p-u*c*f+a*d*f,T=g*d*l-h*m*l-g*c*p+o*m*p+h*c*f-o*d*f,M=h*_*l-g*u*l+g*a*p-o*_*p-h*a*f+o*u*f,L=g*u*c-h*_*c-g*a*d+o*_*d+h*a*m-o*u*m,R=t*E+n*T+i*M+r*L;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let w=1/R;return e[0]=E*w,e[1]=(_*d*r-u*m*r-_*i*p+n*m*p+u*i*f-n*d*f)*w,e[2]=(a*m*r-_*c*r+_*i*l-n*m*l-a*i*f+n*c*f)*w,e[3]=(u*c*r-a*d*r-u*i*l+n*d*l+a*i*p-n*c*p)*w,e[4]=T*w,e[5]=(h*m*r-g*d*r+g*i*p-t*m*p-h*i*f+t*d*f)*w,e[6]=(g*c*r-o*m*r-g*i*l+t*m*l+o*i*f-t*c*f)*w,e[7]=(o*d*r-h*c*r+h*i*l-t*d*l-o*i*p+t*c*p)*w,e[8]=M*w,e[9]=(g*u*r-h*_*r-g*n*p+t*_*p+h*n*f-t*u*f)*w,e[10]=(o*_*r-g*a*r+g*n*l-t*_*l-o*n*f+t*a*f)*w,e[11]=(h*a*r-o*u*r-h*n*l+t*u*l+o*n*p-t*a*p)*w,e[12]=L*w,e[13]=(h*_*i-g*u*i+g*n*d-t*_*d-h*n*m+t*u*m)*w,e[14]=(g*a*i-o*_*i-g*n*c+t*_*c+o*n*m-t*a*m)*w,e[15]=(o*u*i-h*a*i+h*n*c-t*u*c-o*n*d+t*a*d)*w,this}scale(e){let t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){let 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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}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){let 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){let 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){let 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){let n=Math.cos(t),i=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,h=r*a;return this.set(l*o+n,l*a-i*c,l*c+i*a,0,l*a+i*c,h*a+n,h*c-i*o,0,l*c-i*a,h*c+i*o,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,i,r,o){return this.set(1,n,r,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,h=o+o,u=a+a,d=r*l,p=r*h,g=r*u,_=o*h,m=o*u,f=a*u,E=c*l,T=c*h,M=c*u,L=n.x,R=n.y,w=n.z;return i[0]=(1-(_+f))*L,i[1]=(p+M)*L,i[2]=(g-T)*L,i[3]=0,i[4]=(p-M)*R,i[5]=(1-(d+f))*R,i[6]=(m+E)*R,i[7]=0,i[8]=(g+T)*w,i[9]=(m-E)*w,i[10]=(1-(d+_))*w,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements,r=Li.set(i[0],i[1],i[2]).length(),o=Li.set(i[4],i[5],i[6]).length(),a=Li.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Qt.copy(this);let l=1/r,h=1/o,u=1/a;return Qt.elements[0]*=l,Qt.elements[1]*=l,Qt.elements[2]*=l,Qt.elements[4]*=h,Qt.elements[5]*=h,Qt.elements[6]*=h,Qt.elements[8]*=u,Qt.elements[9]*=u,Qt.elements[10]*=u,t.setFromRotationMatrix(Qt),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,i,r,o,a=fn){let c=this.elements,l=2*r/(t-e),h=2*r/(n-i),u=(t+e)/(t-e),d=(n+i)/(n-i),p,g;if(a===fn)p=-(o+r)/(o-r),g=-2*o*r/(o-r);else if(a===Es)p=-o/(o-r),g=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);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]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,o,a=fn){let c=this.elements,l=1/(t-e),h=1/(n-i),u=1/(o-r),d=(t+e)*l,p=(n+i)*h,g,_;if(a===fn)g=(o+r)*u,_=-2*u;else if(a===Es)g=r*u,_=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);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]=-p,c[2]=0,c[6]=0,c[10]=_,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])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){let 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}},Li=new P,Qt=new Ie,Yu=new P(0,0,0),Zu=new P(1,1,1),Hn=new P,mr=new P,Bt=new P,ul=new Ie,dl=new Rt,on=class s{constructor(e=0,t=0,n=0,i=s.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}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,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,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){let i=e.elements,r=i[0],o=i[4],a=i[8],c=i[1],l=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(Fe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Fe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Fe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Fe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Fe(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(a,p));break;case"XZY":this._z=Math.asin(-Fe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,p),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 ul.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ul,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return dl.setFromEuler(this),this.setFromQuaternion(dl,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}};on.DEFAULT_ORDER="XYZ";var ws=class{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}},Ku=0,fl=new P,Di=new Rt,En=new Ie,gr=new P,ms=new P,Ju=new P,$u=new Rt,pl=new P(1,0,0),ml=new P(0,1,0),gl=new P(0,0,1),_l={type:"added"},ju={type:"removed"},Ui={type:"childadded",child:null},ua={type:"childremoved",child:null},rt=class s extends pn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Ku++}),this.uuid=sn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=s.DEFAULT_UP.clone();let e=new P,t=new on,n=new Rt,i=new P(1,1,1);function r(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(o),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:i},modelViewMatrix:{value:new Ie},normalMatrix:{value:new Pe}}),this.matrix=new Ie,this.matrixWorld=new Ie,this.matrixAutoUpdate=s.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=s.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ws,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 Di.setFromAxisAngle(e,t),this.quaternion.multiply(Di),this}rotateOnWorldAxis(e,t){return Di.setFromAxisAngle(e,t),this.quaternion.premultiply(Di),this}rotateX(e){return this.rotateOnAxis(pl,e)}rotateY(e){return this.rotateOnAxis(ml,e)}rotateZ(e){return this.rotateOnAxis(gl,e)}translateOnAxis(e,t){return fl.copy(e).applyQuaternion(this.quaternion),this.position.add(fl.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(pl,e)}translateY(e){return this.translateOnAxis(ml,e)}translateZ(e){return this.translateOnAxis(gl,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(En.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?gr.copy(e):gr.set(e,t,n);let i=this.parent;this.updateWorldMatrix(!0,!1),ms.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?En.lookAt(ms,gr,this.up):En.lookAt(gr,ms,this.up),this.quaternion.setFromRotationMatrix(En),i&&(En.extractRotation(i.matrixWorld),Di.setFromRotationMatrix(En),this.quaternion.premultiply(Di.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(_l),Ui.child=e,this.dispatchEvent(Ui),Ui.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}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(ju),ua.child=e,this.dispatchEvent(ua),ua.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),En.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),En.multiply(e.parent.matrixWorld)),e.applyMatrix4(En),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(_l),Ui.child=e,this.dispatchEvent(Ui),Ui.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,i=this.children.length;n<i;n++){let o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let i=this.children;for(let r=0,o=i.length;r<o;r++)i[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(ms,e,Ju),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ms,$u,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){let 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);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let 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){let i=this.children;for(let r=0,o=i.length;r<o;r++)i[r].updateWorldMatrix(!1,!0)}}toJSON(e){let 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"});let i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?{min:a.boundingBox.min.toArray(),max:a.boundingBox.max.toArray()}:void 0,boundingSphere:a.boundingSphere?{radius:a.boundingSphere.radius,center:a.boundingSphere.center.toArray()}:void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere={center:this.boundingSphere.center.toArray(),radius:this.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:this.boundingBox.min.toArray(),max:this.boundingBox.max.toArray()}));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){let u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(e.materials,this.material[c]));i.material=a}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){let c=this.animations[a];i.animations.push(r(e.animations,c))}}if(t){let a=o(e.geometries),c=o(e.materials),l=o(e.textures),h=o(e.images),u=o(e.shapes),d=o(e.skeletons),p=o(e.animations),g=o(e.nodes);a.length>0&&(n.geometries=a),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),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=i,n;function o(a){let c=[];for(let l in a){let h=a[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++){let i=e.children[n];this.add(i.clone())}return this}};rt.DEFAULT_UP=new P(0,1,0);rt.DEFAULT_MATRIX_AUTO_UPDATE=!0;rt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var en=new P,An=new P,da=new P,wn=new P,Ni=new P,Fi=new P,xl=new P,fa=new P,pa=new P,ma=new P,ga=new qe,_a=new qe,xa=new qe,Xn=class s{constructor(e=new P,t=new P,n=new P){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),en.subVectors(e,t),i.cross(en);let r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){en.subVectors(i,t),An.subVectors(n,t),da.subVectors(e,t);let o=en.dot(en),a=en.dot(An),c=en.dot(da),l=An.dot(An),h=An.dot(da),u=o*l-a*a;if(u===0)return r.set(0,0,0),null;let d=1/u,p=(l*c-a*h)*d,g=(o*h-a*c)*d;return r.set(1-p-g,g,p)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,wn)===null?!1:wn.x>=0&&wn.y>=0&&wn.x+wn.y<=1}static getInterpolation(e,t,n,i,r,o,a,c){return this.getBarycoord(e,t,n,i,wn)===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,wn.x),c.addScaledVector(o,wn.y),c.addScaledVector(a,wn.z),c)}static getInterpolatedAttribute(e,t,n,i,r,o){return ga.setScalar(0),_a.setScalar(0),xa.setScalar(0),ga.fromBufferAttribute(e,t),_a.fromBufferAttribute(e,n),xa.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(ga,r.x),o.addScaledVector(_a,r.y),o.addScaledVector(xa,r.z),o}static isFrontFacing(e,t,n,i){return en.subVectors(n,t),An.subVectors(e,t),en.cross(An).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),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 en.subVectors(this.c,this.b),An.subVectors(this.a,this.b),en.cross(An).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return s.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return s.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return s.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return s.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return s.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,o,a;Ni.subVectors(i,n),Fi.subVectors(r,n),fa.subVectors(e,n);let c=Ni.dot(fa),l=Fi.dot(fa);if(c<=0&&l<=0)return t.copy(n);pa.subVectors(e,i);let h=Ni.dot(pa),u=Fi.dot(pa);if(h>=0&&u<=h)return t.copy(i);let d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return o=c/(c-h),t.copy(n).addScaledVector(Ni,o);ma.subVectors(e,r);let p=Ni.dot(ma),g=Fi.dot(ma);if(g>=0&&p<=g)return t.copy(r);let _=p*l-c*g;if(_<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(Fi,a);let m=h*g-p*u;if(m<=0&&u-h>=0&&p-g>=0)return xl.subVectors(r,i),a=(u-h)/(u-h+(p-g)),t.copy(i).addScaledVector(xl,a);let f=1/(m+_+d);return o=_*f,a=d*f,t.copy(n).addScaledVector(Ni,o).addScaledVector(Fi,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Oh={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},Gn={h:0,s:0,l:0},_r={h:0,s:0,l:0};function ya(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}var be=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){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=lt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Be.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=Be.workingColorSpace){return this.r=e,this.g=t,this.b=n,Be.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=Be.workingColorSpace){if(e=ec(e,1),t=Fe(t,0,1),n=Fe(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=ya(o,r,e+1/3),this.g=ya(o,r,e),this.b=ya(o,r,e-1/3)}return Be.toWorkingColorSpace(this,i),this}setStyle(e,t=lt){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))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(a))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(a))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(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let r=i[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===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=lt){let n=Oh[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=In(e.r),this.g=In(e.g),this.b=In(e.b),this}copyLinearToSRGB(e){return this.r=Vi(e.r),this.g=Vi(e.g),this.b=Vi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=lt){return Be.fromWorkingColorSpace(Tt.copy(this),e),Math.round(Fe(Tt.r*255,0,255))*65536+Math.round(Fe(Tt.g*255,0,255))*256+Math.round(Fe(Tt.b*255,0,255))}getHexString(e=lt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Be.workingColorSpace){Be.fromWorkingColorSpace(Tt.copy(this),t);let n=Tt.r,i=Tt.g,r=Tt.b,o=Math.max(n,i,r),a=Math.min(n,i,r),c,l,h=(a+o)/2;if(a===o)c=0,l=0;else{let u=o-a;switch(l=h<=.5?u/(o+a):u/(2-o-a),o){case n:c=(i-r)/u+(i<r?6:0);break;case i:c=(r-n)/u+2;break;case r:c=(n-i)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=h,e}getRGB(e,t=Be.workingColorSpace){return Be.fromWorkingColorSpace(Tt.copy(this),t),e.r=Tt.r,e.g=Tt.g,e.b=Tt.b,e}getStyle(e=lt){Be.fromWorkingColorSpace(Tt.copy(this),e);let t=Tt.r,n=Tt.g,i=Tt.b;return e!==lt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(Gn),this.setHSL(Gn.h+e,Gn.s+t,Gn.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(Gn),e.getHSL(_r);let n=Ss(Gn.h,_r.h,t),i=Ss(Gn.s,_r.s,t),r=Ss(Gn.l,_r.l,t);return this.setHSL(n,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,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}},Tt=new be;be.NAMES=Oh;var Qu=0,Ut=class extends pn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Qu++}),this.uuid=sn(),this.name="",this.type="Material",this.blending=ai,this.side=rn,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Nr,this.blendDst=Fr,this.blendEquation=qn,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new be(0,0,0),this.blendAlpha=0,this.depthFunc=ci,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Ca,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=si,this.stencilZFail=si,this.stencilZPass=si,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(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let 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!==ai&&(n.blending=this.blending),this.side!==rn&&(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!==Nr&&(n.blendSrc=this.blendSrc),this.blendDst!==Fr&&(n.blendDst=this.blendDst),this.blendEquation!==qn&&(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!==ci&&(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!==si&&(n.stencilFail=this.stencilFail),this.stencilZFail!==si&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==si&&(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 i(r){let o=[];for(let a in r){let c=r[a];delete c.metadata,o.push(c)}return o}if(t){let r=i(e.textures),o=i(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}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;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let r=0;r!==i;++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++}},an=class extends Ut{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new be(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 on,this.combine=Va,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}};var ut=new P,xr=new ze,ed=0,ft=class{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:ed++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Or,this.updateRanges=[],this.gpuType=Zt,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 i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[n+i];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++)xr.fromBufferAttribute(this,t),xr.applyMatrix3(e),this.setXY(t,xr.x,xr.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)ut.fromBufferAttribute(this,t),ut.applyMatrix3(e),this.setXYZ(t,ut.x,ut.y,ut.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)ut.fromBufferAttribute(this,t),ut.applyMatrix4(e),this.setXYZ(t,ut.x,ut.y,ut.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ut.fromBufferAttribute(this,t),ut.applyNormalMatrix(e),this.setXYZ(t,ut.x,ut.y,ut.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ut.fromBufferAttribute(this,t),ut.transformDirection(e),this.setXYZ(t,ut.x,ut.y,ut.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=tn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=$e(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=tn(t,this.array)),t}setX(e,t){return this.normalized&&(t=$e(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=tn(t,this.array)),t}setY(e,t){return this.normalized&&(t=$e(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=tn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=$e(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=tn(t,this.array)),t}setW(e,t){return this.normalized&&(t=$e(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array),i=$e(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array),i=$e(i,this.array),r=$e(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,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(){let 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!==Or&&(e.usage=this.usage),e}};var Rs=class extends ft{constructor(e,t,n){super(new Uint16Array(e),t,n)}};var Cs=class extends ft{constructor(e,t,n){super(new Uint32Array(e),t,n)}};var kt=class extends ft{constructor(e,t,n){super(new Float32Array(e),t,n)}},td=0,qt=new Ie,va=new rt,Oi=new P,zt=new It,gs=new It,gt=new P,Vt=class s extends pn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:td++}),this.uuid=sn(),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(nc(e)?Cs:Rs)(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){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let r=new Pe().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}let i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return qt.makeRotationFromQuaternion(e),this.applyMatrix4(qt),this}rotateX(e){return qt.makeRotationX(e),this.applyMatrix4(qt),this}rotateY(e){return qt.makeRotationY(e),this.applyMatrix4(qt),this}rotateZ(e){return qt.makeRotationZ(e),this.applyMatrix4(qt),this}translate(e,t,n){return qt.makeTranslation(e,t,n),this.applyMatrix4(qt),this}scale(e,t,n){return qt.makeScale(e,t,n),this.applyMatrix4(qt),this}lookAt(e){return va.lookAt(e),va.updateMatrix(),this.applyMatrix4(va.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Oi).negate(),this.translate(Oi.x,Oi.y,Oi.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,r=e.length;i<r;i++){let o=e[i];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new kt(n,3))}else{let n=Math.min(e.length,t.count);for(let i=0;i<n;i++){let r=e[i];t.setXYZ(i,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 It);let 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 P(-1/0,-1/0,-1/0),new P(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let r=t[n];zt.setFromBufferAttribute(r),this.morphTargetsRelative?(gt.addVectors(this.boundingBox.min,zt.min),this.boundingBox.expandByPoint(gt),gt.addVectors(this.boundingBox.max,zt.max),this.boundingBox.expandByPoint(gt)):(this.boundingBox.expandByPoint(zt.min),this.boundingBox.expandByPoint(zt.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 Dt);let 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 P,1/0);return}if(e){let n=this.boundingSphere.center;if(zt.setFromBufferAttribute(e),t)for(let r=0,o=t.length;r<o;r++){let a=t[r];gs.setFromBufferAttribute(a),this.morphTargetsRelative?(gt.addVectors(zt.min,gs.min),zt.expandByPoint(gt),gt.addVectors(zt.max,gs.max),zt.expandByPoint(gt)):(zt.expandByPoint(gs.min),zt.expandByPoint(gs.max))}zt.getCenter(n);let i=0;for(let r=0,o=e.count;r<o;r++)gt.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(gt));if(t)for(let r=0,o=t.length;r<o;r++){let a=t[r],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)gt.fromBufferAttribute(a,l),c&&(Oi.fromBufferAttribute(e,l),gt.add(Oi)),i=Math.max(i,n.distanceToSquared(gt))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let 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}let n=t.position,i=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ft(new Float32Array(4*n.count),4));let o=this.getAttribute("tangent"),a=[],c=[];for(let N=0;N<n.count;N++)a[N]=new P,c[N]=new P;let l=new P,h=new P,u=new P,d=new ze,p=new ze,g=new ze,_=new P,m=new P;function f(N,S,v){l.fromBufferAttribute(n,N),h.fromBufferAttribute(n,S),u.fromBufferAttribute(n,v),d.fromBufferAttribute(r,N),p.fromBufferAttribute(r,S),g.fromBufferAttribute(r,v),h.sub(l),u.sub(l),p.sub(d),g.sub(d);let C=1/(p.x*g.y-g.x*p.y);isFinite(C)&&(_.copy(h).multiplyScalar(g.y).addScaledVector(u,-p.y).multiplyScalar(C),m.copy(u).multiplyScalar(p.x).addScaledVector(h,-g.x).multiplyScalar(C),a[N].add(_),a[S].add(_),a[v].add(_),c[N].add(m),c[S].add(m),c[v].add(m))}let E=this.groups;E.length===0&&(E=[{start:0,count:e.count}]);for(let N=0,S=E.length;N<S;++N){let v=E[N],C=v.start,q=v.count;for(let z=C,W=C+q;z<W;z+=3)f(e.getX(z+0),e.getX(z+1),e.getX(z+2))}let T=new P,M=new P,L=new P,R=new P;function w(N){L.fromBufferAttribute(i,N),R.copy(L);let S=a[N];T.copy(S),T.sub(L.multiplyScalar(L.dot(S))).normalize(),M.crossVectors(R,S);let C=M.dot(c[N])<0?-1:1;o.setXYZW(N,T.x,T.y,T.z,C)}for(let N=0,S=E.length;N<S;++N){let v=E[N],C=v.start,q=v.count;for(let z=C,W=C+q;z<W;z+=3)w(e.getX(z+0)),w(e.getX(z+1)),w(e.getX(z+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new ft(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,p=n.count;d<p;d++)n.setXYZ(d,0,0,0);let i=new P,r=new P,o=new P,a=new P,c=new P,l=new P,h=new P,u=new P;if(e)for(let d=0,p=e.count;d<p;d+=3){let g=e.getX(d+0),_=e.getX(d+1),m=e.getX(d+2);i.fromBufferAttribute(t,g),r.fromBufferAttribute(t,_),o.fromBufferAttribute(t,m),h.subVectors(o,r),u.subVectors(i,r),h.cross(u),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,_),l.fromBufferAttribute(n,m),a.add(h),c.add(h),l.add(h),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(_,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let d=0,p=t.count;d<p;d+=3)i.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),o.fromBufferAttribute(t,d+2),h.subVectors(o,r),u.subVectors(i,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(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)gt.fromBufferAttribute(e,t),gt.normalize(),e.setXYZ(t,gt.x,gt.y,gt.z)}toNonIndexed(){function e(a,c){let l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h),p=0,g=0;for(let _=0,m=c.length;_<m;_++){a.isInterleavedBufferAttribute?p=c[_]*a.data.stride+a.offset:p=c[_]*h;for(let f=0;f<h;f++)d[g++]=l[p++]}return new ft(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new s,n=this.index.array,i=this.attributes;for(let a in i){let c=i[a],l=e(c,n);t.setAttribute(a,l)}let r=this.morphAttributes;for(let a in r){let c=[],l=r[a];for(let h=0,u=l.length;h<u;h++){let d=l[h],p=e(d,n);c.push(p)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let a=0,c=o.length;a<c;a++){let l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){let 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){let c=this.parameters;for(let l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let c in n){let l=n[c];e.data.attributes[c]=l.toJSON(e.data)}let i={},r=!1;for(let c in this.morphAttributes){let l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){let p=l[u];h.push(p.toJSON(e.data))}h.length>0&&(i[c]=h,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.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;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let i=e.attributes;for(let l in i){let h=i[l];this.setAttribute(l,h.clone(t))}let r=e.morphAttributes;for(let l in r){let h=[],u=r[l];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[l]=h}this.morphTargetsRelative=e.morphTargetsRelative;let o=e.groups;for(let l=0,h=o.length;l<h;l++){let u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}let a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());let 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"})}},yl=new Ie,ni=new di,yr=new Dt,vl=new P,vr=new P,Mr=new P,Sr=new P,Ma=new P,br=new P,Ml=new P,Tr=new P,Mt=class extends rt{constructor(e=new Vt,t=new an){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(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r<o;r++){let a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let a=this.morphTargetInfluences;if(r&&a){br.set(0,0,0);for(let c=0,l=r.length;c<l;c++){let h=a[c],u=r[c];h!==0&&(Ma.fromBufferAttribute(u,e),o?br.addScaledVector(Ma,h):br.addScaledVector(Ma.sub(t),h))}t.add(br)}return t}raycast(e,t){let n=this.geometry,i=this.material,r=this.matrixWorld;i!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),yr.copy(n.boundingSphere),yr.applyMatrix4(r),ni.copy(e.ray).recast(e.near),!(yr.containsPoint(ni.origin)===!1&&(ni.intersectSphere(yr,vl)===null||ni.origin.distanceToSquared(vl)>(e.far-e.near)**2))&&(yl.copy(r).invert(),ni.copy(e.ray).applyMatrix4(yl),!(n.boundingBox!==null&&ni.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,ni)))}_computeIntersections(e,t,n){let i,r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,_=d.length;g<_;g++){let m=d[g],f=o[m.materialIndex],E=Math.max(m.start,p.start),T=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let M=E,L=T;M<L;M+=3){let R=a.getX(M),w=a.getX(M+1),N=a.getX(M+2);i=Er(this,f,e,n,l,h,u,R,w,N),i&&(i.faceIndex=Math.floor(M/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{let g=Math.max(0,p.start),_=Math.min(a.count,p.start+p.count);for(let m=g,f=_;m<f;m+=3){let E=a.getX(m),T=a.getX(m+1),M=a.getX(m+2);i=Er(this,o,e,n,l,h,u,E,T,M),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,_=d.length;g<_;g++){let m=d[g],f=o[m.materialIndex],E=Math.max(m.start,p.start),T=Math.min(c.count,Math.min(m.start+m.count,p.start+p.count));for(let M=E,L=T;M<L;M+=3){let R=M,w=M+1,N=M+2;i=Er(this,f,e,n,l,h,u,R,w,N),i&&(i.faceIndex=Math.floor(M/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{let g=Math.max(0,p.start),_=Math.min(c.count,p.start+p.count);for(let m=g,f=_;m<f;m+=3){let E=m,T=m+1,M=m+2;i=Er(this,o,e,n,l,h,u,E,T,M),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}}};function nd(s,e,t,n,i,r,o,a){let c;if(e.side===Pt?c=n.intersectTriangle(o,r,i,!0,a):c=n.intersectTriangle(i,r,o,e.side===rn,a),c===null)return null;Tr.copy(a),Tr.applyMatrix4(s.matrixWorld);let l=t.ray.origin.distanceTo(Tr);return l<t.near||l>t.far?null:{distance:l,point:Tr.clone(),object:s}}function Er(s,e,t,n,i,r,o,a,c,l){s.getVertexPosition(a,vr),s.getVertexPosition(c,Mr),s.getVertexPosition(l,Sr);let h=nd(s,e,t,n,vr,Mr,Sr,Ml);if(h){let u=new P;Xn.getBarycoord(Ml,vr,Mr,Sr,u),i&&(h.uv=Xn.getInterpolatedAttribute(i,a,c,l,u,new ze)),r&&(h.uv1=Xn.getInterpolatedAttribute(r,a,c,l,u,new ze)),o&&(h.normal=Xn.getInterpolatedAttribute(o,a,c,l,u,new P),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let d={a,b:c,c:l,normal:new P,materialIndex:0};Xn.getNormal(vr,Mr,Sr,d.normal),h.face=d,h.barycoord=u}return h}var qi=class s extends Vt{constructor(e=1,t=1,n=1,i=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:o};let a=this;i=Math.floor(i),r=Math.floor(r),o=Math.floor(o);let c=[],l=[],h=[],u=[],d=0,p=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,i,o,2),g("x","z","y",1,-1,e,n,-t,i,o,3),g("x","y","z",1,-1,e,t,n,i,r,4),g("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(c),this.setAttribute("position",new kt(l,3)),this.setAttribute("normal",new kt(h,3)),this.setAttribute("uv",new kt(u,2));function g(_,m,f,E,T,M,L,R,w,N,S){let v=M/w,C=L/N,q=M/2,z=L/2,W=R/2,J=w+1,G=N+1,Q=0,V=0,ie=new P;for(let he=0;he<G;he++){let _e=he*C-z;for(let Ne=0;Ne<J;Ne++){let et=Ne*v-q;ie[_]=et*E,ie[m]=_e*T,ie[f]=W,l.push(ie.x,ie.y,ie.z),ie[_]=0,ie[m]=0,ie[f]=R>0?1:-1,h.push(ie.x,ie.y,ie.z),u.push(Ne/w),u.push(1-he/N),Q+=1}}for(let he=0;he<N;he++)for(let _e=0;_e<w;_e++){let Ne=d+_e+J*he,et=d+_e+J*(he+1),X=d+(_e+1)+J*(he+1),ee=d+(_e+1)+J*he;c.push(Ne,et,ee),c.push(et,X,ee),V+=6}a.addGroup(p,V,S),p+=V,d+=Q}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new s(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function Mi(s){let e={};for(let t in s){e[t]={};for(let n in s[t]){let i=s[t][n];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=i.clone():Array.isArray(i)?e[t][n]=i.slice():e[t][n]=i}}return e}function Et(s){let e={};for(let t=0;t<s.length;t++){let n=Mi(s[t]);for(let i in n)e[i]=n[i]}return e}function id(s){let e=[];for(let t=0;t<s.length;t++)e.push(s[t].clone());return e}function ic(s){let e=s.getRenderTarget();return e===null?s.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Be.workingColorSpace}var Bh={clone:Mi,merge:Et},sd=`void main() {+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );+}`,rd=`void main() {+ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );+}`,cn=class extends Ut{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=sd,this.fragmentShader=rd,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=Mi(e.uniforms),this.uniformsGroups=id(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){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let i in this.uniforms){let o=this.uniforms[i].value;o&&o.isTexture?t.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[i]={type:"m4",value:o.toArray()}:t.uniforms[i]={value:o}}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;let n={};for(let i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Is=class extends rt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ie,this.projectionMatrix=new Ie,this.projectionMatrixInverse=new Ie,this.coordinateSystem=fn}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)}},Wn=new P,Sl=new ze,bl=new ze,dt=class extends Is{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,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){let t=.5*this.getFilmHeight()/e;this.fov=ui*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Ms*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ui*2*Math.atan(Math.tan(Ms*.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){Wn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Wn.x,Wn.y).multiplyScalar(-e/Wn.z),Wn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Wn.x,Wn.y).multiplyScalar(-e/Wn.z)}getViewSize(e,t){return this.getViewBounds(e,Sl,bl),t.subVectors(bl,Sl)}setViewOffset(e,t,n,i,r,o){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=i,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Ms*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i,o=this.view;if(this.view!==null&&this.view.enabled){let c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*i/c,t-=o.offsetY*n/l,i*=o.width/c,n*=o.height/l}let a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let 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}},Bi=-90,zi=1,Vr=class extends rt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new dt(Bi,zi,e,t);i.layers=this.layers,this.add(i);let r=new dt(Bi,zi,e,t);r.layers=this.layers,this.add(r);let o=new dt(Bi,zi,e,t);o.layers=this.layers,this.add(o);let a=new dt(Bi,zi,e,t);a.layers=this.layers,this.add(a);let c=new dt(Bi,zi,e,t);c.layers=this.layers,this.add(c);let l=new dt(Bi,zi,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,o,a,c]=t;for(let l of t)this.remove(l);if(e===fn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Es)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.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(let l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[r,o,a,c,l,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;let _=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,o),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,c),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=_,e.setRenderTarget(n,5,i),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}},Ps=class extends _t{constructor(e=[],t=xi,n,i,r,o,a,c,l,h){super(e,t,n,i,r,o,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Hr=class extends mn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Ps(i,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:Ct}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;let n={uniforms:{tEquirect:{value:null}},vertexShader:`++ varying vec3 vWorldDirection;++ vec3 transformDirection( in vec3 dir, in mat4 matrix ) {++ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );++ }++ void main() {++ vWorldDirection = transformDirection( position, modelMatrix );++ #include <begin_vertex>+ #include <project_vertex>++ }+ `,fragmentShader:`++ uniform sampler2D tEquirect;++ varying vec3 vWorldDirection;++ #include <common>++ void main() {++ vec3 direction = normalize( vWorldDirection );++ vec2 sampleUV = equirectUv( direction );++ gl_FragColor = texture2D( tEquirect, sampleUV );++ }+ `},i=new qi(5,5,5),r=new cn({name:"CubemapFromEquirect",uniforms:Mi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Pt,blending:Nn});r.uniforms.tEquirect.value=t;let o=new Mt(i,r),a=t.minFilter;return t.minFilter===ln&&(t.minFilter=Ct),new Vr(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(r)}},nn=class extends rt{constructor(){super(),this.isGroup=!0,this.type="Group"}},od={type:"move"},Yi=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new nn,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 nn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new P,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new P),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new nn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new P,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new P),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){let t=this._hand;if(t)for(let 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 i=null,r=null,o=null,a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(let _ of e.hand.values()){let m=t.getJointPose(_,n),f=this._getHandJoint(l,_);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}let h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,g=.005;l.inputState.pinching&&d>p+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=p-g&&(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));a!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null&&(i=r),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(od)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new nn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}};var Ls=class extends rt{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 on,this.environmentIntensity=1,this.environmentRotation=new on,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){let 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}},Zi=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Or,this.updateRanges=[],this.version=0,this.uuid=sn()}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 i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];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=sn()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let 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=sn()),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}}},wt=new P,Ki=class s{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}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++)wt.fromBufferAttribute(this,t),wt.applyMatrix4(e),this.setXYZ(t,wt.x,wt.y,wt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)wt.fromBufferAttribute(this,t),wt.applyNormalMatrix(e),this.setXYZ(t,wt.x,wt.y,wt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)wt.fromBufferAttribute(this,t),wt.transformDirection(e),this.setXYZ(t,wt.x,wt.y,wt.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=tn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=$e(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=$e(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=$e(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=$e(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=$e(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=tn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=tn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=tn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=tn(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array),i=$e(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=$e(t,this.array),n=$e(n,this.array),i=$e(i,this.array),r=$e(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,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.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return new ft(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 s(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.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+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}}};var Tl=new P,El=new qe,Al=new qe,ad=new P,wl=new Ie,Ar=new P,Sa=new Dt,Rl=new Ie,ba=new di,Ds=class extends Mt{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Ra,this.bindMatrix=new Ie,this.bindMatrixInverse=new Ie,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new It),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Ar),this.boundingBox.expandByPoint(Ar)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Dt),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Ar),this.boundingSphere.expandByPoint(Ar)}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){let n=this.material,i=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Sa.copy(this.boundingSphere),Sa.applyMatrix4(i),e.ray.intersectsSphere(Sa)!==!1&&(Rl.copy(i).invert(),ba.copy(e.ray).applyMatrix4(Rl),!(this.boundingBox!==null&&ba.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,ba)))}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(){let e=new qe,t=this.geometry.attributes.skinWeight;for(let n=0,i=t.count;n<i;n++){e.fromBufferAttribute(t,n);let 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===Ra?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===xh?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;El.fromBufferAttribute(i.attributes.skinIndex,e),Al.fromBufferAttribute(i.attributes.skinWeight,e),Tl.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let r=0;r<4;r++){let o=Al.getComponent(r);if(o!==0){let a=El.getComponent(r);wl.multiplyMatrices(n.bones[a].matrixWorld,n.boneInverses[a]),t.addScaledVector(ad.copy(Tl).applyMatrix4(wl),o)}}return t.applyMatrix4(this.bindMatrixInverse)}},Ji=class extends rt{constructor(){super(),this.isBone=!0,this.type="Bone"}},Us=class extends _t{constructor(e=null,t=1,n=1,i,r,o,a,c,l=yt,h=yt,u,d){super(null,o,a,c,l,h,i,r,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Cl=new Ie,cd=new Ie,Ns=class s{constructor(e=[],t=[]){this.uuid=sn(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let 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,i=this.bones.length;n<i;n++)this.boneInverses.push(new Ie)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new Ie;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++){let n=this.bones[e];n&&n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let 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(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let r=0,o=e.length;r<o;r++){let a=e[r]?e[r].matrixWorld:cd;Cl.multiplyMatrices(a,t[r]),Cl.toArray(n,r*16)}i!==null&&(i.needsUpdate=!0)}clone(){return new s(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new Us(t,e,e,Ht,Zt);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let i=this.bones[t];if(i.name===e)return i}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,i=e.bones.length;n<i;n++){let r=e.bones[n],o=t[r];o===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",r),o=new Ji),this.bones.push(o),this.boneInverses.push(new Ie().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let i=0,r=t.length;i<r;i++){let o=t[i];e.bones.push(o.uuid);let a=n[i];e.boneInverses.push(a.toArray())}return e}},Zn=class extends ft{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},ki=new Ie,Il=new Ie,wr=[],Pl=new It,ld=new Ie,_s=new Mt,xs=new Dt,Fs=class extends Mt{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Zn(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<n;i++)this.setMatrixAt(i,ld)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new It),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ki),Pl.copy(e.boundingBox).applyMatrix4(ki),this.boundingBox.union(Pl)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Dt),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ki),xs.copy(e.boundingSphere).applyMatrix4(ki),this.boundingSphere.union(xs)}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){let n=t.morphTargetInfluences,i=this.morphTexture.source.data.data,r=n.length+1,o=e*r+1;for(let a=0;a<n.length;a++)n[a]=i[o+a]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(_s.geometry=this.geometry,_s.material=this.material,_s.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),xs.copy(this.boundingSphere),xs.applyMatrix4(n),e.ray.intersectsSphere(xs)!==!1))for(let r=0;r<i;r++){this.getMatrixAt(r,ki),Il.multiplyMatrices(n,ki),_s.matrixWorld=Il,_s.raycast(e,wr);for(let o=0,a=wr.length;o<a;o++){let c=wr[o];c.instanceId=r,c.object=this,t.push(c)}wr.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new Zn(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){let n=t.morphTargetInfluences,i=n.length+1;this.morphTexture===null&&(this.morphTexture=new Us(new Float32Array(i*this.count),i,this.count,go,Zt));let r=this.morphTexture.source.data.data,o=0;for(let l=0;l<n.length;l++)o+=n[l];let a=this.geometry.morphTargetsRelative?1:1-o,c=i*e;r[c]=a,r.set(n,c+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},Ta=new P,hd=new P,ud=new Pe,un=class{constructor(e=new P(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,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=Ta.subVectors(n,t).cross(hd.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let 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){let n=e.delta(Ta),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){let 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){let n=t||ud.getNormalMatrix(e),i=this.coplanarPoint(Ta).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.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)}},ii=new Dt,Rr=new P,$i=class{constructor(e=new un,t=new un,n=new un,i=new un,r=new un,o=new un){this.planes=[e,t,n,i,r,o]}set(e,t,n,i,r,o){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(o),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=fn){let n=this.planes,i=e.elements,r=i[0],o=i[1],a=i[2],c=i[3],l=i[4],h=i[5],u=i[6],d=i[7],p=i[8],g=i[9],_=i[10],m=i[11],f=i[12],E=i[13],T=i[14],M=i[15];if(n[0].setComponents(c-r,d-l,m-p,M-f).normalize(),n[1].setComponents(c+r,d+l,m+p,M+f).normalize(),n[2].setComponents(c+o,d+h,m+g,M+E).normalize(),n[3].setComponents(c-o,d-h,m-g,M-E).normalize(),n[4].setComponents(c-a,d-u,m-_,M-T).normalize(),t===fn)n[5].setComponents(c+a,d+u,m+_,M+T).normalize();else if(t===Es)n[5].setComponents(a,u,_,T).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(),ii.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ii.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ii)}intersectsSprite(e){return ii.center.set(0,0,0),ii.radius=.7071067811865476,ii.applyMatrix4(e.matrixWorld),this.intersectsSphere(ii)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let i=t[n];if(Rr.x=i.normal.x>0?e.max.x:e.min.x,Rr.y=i.normal.y>0?e.max.y:e.min.y,Rr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Rr)<0)return!1}return!0}containsPoint(e){let 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)}};var ji=class extends Ut{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new be(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}},Gr=new P,Wr=new P,Ll=new Ie,ys=new di,Cr=new Dt,Ea=new P,Dl=new P,fi=class extends rt{constructor(e=new Vt,t=new ji){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(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let i=1,r=t.count;i<r;i++)Gr.fromBufferAttribute(t,i-1),Wr.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=Gr.distanceTo(Wr);e.setAttribute("lineDistance",new kt(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Cr.copy(n.boundingSphere),Cr.applyMatrix4(i),Cr.radius+=r,e.ray.intersectsSphere(Cr)===!1)return;Ll.copy(i).invert(),ys.copy(e.ray).applyMatrix4(Ll);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=n.index,d=n.attributes.position;if(h!==null){let p=Math.max(0,o.start),g=Math.min(h.count,o.start+o.count);for(let _=p,m=g-1;_<m;_+=l){let f=h.getX(_),E=h.getX(_+1),T=Ir(this,e,ys,c,f,E,_);T&&t.push(T)}if(this.isLineLoop){let _=h.getX(g-1),m=h.getX(p),f=Ir(this,e,ys,c,_,m,g-1);f&&t.push(f)}}else{let p=Math.max(0,o.start),g=Math.min(d.count,o.start+o.count);for(let _=p,m=g-1;_<m;_+=l){let f=Ir(this,e,ys,c,_,_+1,_);f&&t.push(f)}if(this.isLineLoop){let _=Ir(this,e,ys,c,g-1,p,g-1);_&&t.push(_)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r<o;r++){let a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};function Ir(s,e,t,n,i,r,o){let a=s.geometry.attributes.position;if(Gr.fromBufferAttribute(a,i),Wr.fromBufferAttribute(a,r),t.distanceSqToSegment(Gr,Wr,Ea,Dl)>n)return;Ea.applyMatrix4(s.matrixWorld);let l=e.ray.origin.distanceTo(Ea);if(!(l<e.near||l>e.far))return{distance:l,point:Dl.clone().applyMatrix4(s.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:s}}var Ul=new P,Nl=new P,Os=class extends fi{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let i=0,r=t.count;i<r;i+=2)Ul.fromBufferAttribute(t,i),Nl.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+Ul.distanceTo(Nl);e.setAttribute("lineDistance",new kt(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},Bs=class extends fi{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},Qi=class extends Ut{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new be(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}},Fl=new Ie,Ia=new di,Pr=new Dt,Lr=new P,zs=class extends rt{constructor(e=new Vt,t=new Qi){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){let n=this.geometry,i=this.matrixWorld,r=e.params.Points.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Pr.copy(n.boundingSphere),Pr.applyMatrix4(i),Pr.radius+=r,e.ray.intersectsSphere(Pr)===!1)return;Fl.copy(i).invert(),Ia.copy(e.ray).applyMatrix4(Fl);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=n.index,u=n.attributes.position;if(l!==null){let d=Math.max(0,o.start),p=Math.min(l.count,o.start+o.count);for(let g=d,_=p;g<_;g++){let m=l.getX(g);Lr.fromBufferAttribute(u,m),Ol(Lr,m,c,i,e,t,this)}}else{let d=Math.max(0,o.start),p=Math.min(u.count,o.start+o.count);for(let g=d,_=p;g<_;g++)Lr.fromBufferAttribute(u,g),Ol(Lr,g,c,i,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r<o;r++){let a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};function Ol(s,e,t,n,i,r,o){let a=Ia.distanceSqToPoint(s);if(a<t){let c=new P;Ia.closestPointToPoint(s,c),c.applyMatrix4(n);let l=i.ray.origin.distanceTo(c);if(l<i.near||l>i.far)return;r.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}var ks=class extends _t{constructor(e,t,n=Jn,i,r,o,a=yt,c=yt,l,h=Gi){if(h!==Gi&&h!==rs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,i,r,o,a,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 Xi(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}};var Vs=class s extends Vt{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};let r=e/2,o=t/2,a=Math.floor(n),c=Math.floor(i),l=a+1,h=c+1,u=e/a,d=t/c,p=[],g=[],_=[],m=[];for(let f=0;f<h;f++){let E=f*d-o;for(let T=0;T<l;T++){let M=T*u-r;g.push(M,-E,0),_.push(0,0,1),m.push(T/a),m.push(1-f/c)}}for(let f=0;f<c;f++)for(let E=0;E<a;E++){let T=E+l*f,M=E+l*(f+1),L=E+1+l*(f+1),R=E+1+l*f;p.push(T,M,R),p.push(M,L,R)}this.setIndex(p),this.setAttribute("position",new kt(g,3)),this.setAttribute("normal",new kt(_,3)),this.setAttribute("uv",new kt(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new s(e.width,e.height,e.widthSegments,e.heightSegments)}};var pi=class extends Ut{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new be(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 be(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=$a,this.normalScale=new ze(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 on,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}},Nt=class extends pi{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 ze(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Fe(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 be(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 be(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new be(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}};var Xr=class extends Ut{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=bh,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}},qr=class extends Ut{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 Dr(s,e){return!s||s.constructor===e?s:typeof e.BYTES_PER_ELEMENT=="number"?new e(s):Array.prototype.slice.call(s)}function dd(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function fd(s){function e(i,r){return s[i]-s[r]}let t=s.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(e),n}function Bl(s,e,t){let n=s.length,i=new s.constructor(n);for(let r=0,o=0;o!==n;++r){let a=t[r]*e;for(let c=0;c!==e;++c)i[o++]=s[a+c]}return i}function zh(s,e,t,n){let i=1,r=s[0];for(;r!==void 0&&r[n]===void 0;)r=s[i++];if(r===void 0)return;let o=r[n];if(o!==void 0)if(Array.isArray(o))do o=r[n],o!==void 0&&(e.push(r.time),t.push(...o)),r=s[i++];while(r!==void 0);else if(o.toArray!==void 0)do o=r[n],o!==void 0&&(e.push(r.time),o.toArray(t,t.length)),r=s[i++];while(r!==void 0);else do o=r[n],o!==void 0&&(e.push(r.time),t.push(o)),r=s[i++];while(r!==void 0)}var Pn=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],r=t[n-1];e:{t:{let o;n:{i:if(!(e<i)){for(let a=n+2;;){if(i===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=i,i=t[++n],e<i)break t}o=t.length;break n}if(!(e>=r)){let a=t[1];e<a&&(n=2,r=a);for(let c=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===c)break;if(i=r,r=t[--n-1],e>=r)break t}o=n,n=0;break n}break e}for(;n<o;){let a=n+o>>>1;e<t[a]?o=a:n=a+1}if(i=t[n],r=t[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i;for(let o=0;o!==i;++o)t[o]=n[r+o];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},Yr=class extends Pn{constructor(e,t,n,i){super(e,t,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:ri,endingEnd:ri}}intervalChanged_(e,t,n){let i=this.parameterPositions,r=e-2,o=e+1,a=i[r],c=i[o];if(a===void 0)switch(this.getSettings_().endingStart){case oi:r=e,a=2*t-n;break;case bs:r=i.length-2,a=t+i[r]-i[r+1];break;default:r=e,a=n}if(c===void 0)switch(this.getSettings_().endingEnd){case oi:o=e,c=2*n-t;break;case bs:o=1,c=n+i[1]-i[0];break;default:o=e-1,c=t}let l=(n-t)*.5,h=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(c-n),this._offsetPrev=r*h,this._offsetNext=o*h}interpolate_(e,t,n,i){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=e*a,l=c-a,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,p=this._weightNext,g=(n-t)/(i-t),_=g*g,m=_*g,f=-d*m+2*d*_-d*g,E=(1+d)*m+(-1.5-2*d)*_+(-.5+d)*g+1,T=(-1-p)*m+(1.5+p)*_+.5*g,M=p*m-p*_;for(let L=0;L!==a;++L)r[L]=f*o[h+L]+E*o[l+L]+T*o[c+L]+M*o[u+L];return r}},Hs=class extends Pn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=e*a,l=c-a,h=(n-t)/(i-t),u=1-h;for(let d=0;d!==a;++d)r[d]=o[l+d]*u+o[c+d]*h;return r}},Zr=class extends Pn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}},Ft=class{constructor(e,t,n,i){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=Dr(t,this.TimeBufferType),this.values=Dr(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Dr(e.times,Array),values:Dr(e.values,Array)};let i=e.getInterpolation();i!==e.DefaultInterpolation&&(n.interpolation=i)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Zr(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Hs(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Yr(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case li:t=this.InterpolantFactoryMethodDiscrete;break;case hi:t=this.InterpolantFactoryMethodLinear;break;case Ur:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let 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 li;case this.InterpolantFactoryMethodLinear:return hi;case this.InterpolantFactoryMethodSmooth:return Ur}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){let n=this.times,i=n.length,r=0,o=i-1;for(;r!==i&&n[r]<e;)++r;for(;o!==-1&&n[o]>t;)--o;if(++o,r!==0||o!==i){r>=o&&(o=Math.max(o,1),r=o-1);let a=this.getValueSize();this.times=n.slice(r,o),this.values=this.values.slice(r*a,o*a)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let o=null;for(let a=0;a!==r;a++){let c=n[a];if(typeof c=="number"&&isNaN(c)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,c),e=!1;break}if(o!==null&&o>c){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,c,o),e=!1;break}o=c}if(i!==void 0&&dd(i))for(let a=0,c=i.length;a!==c;++a){let l=i[a];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,l),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Ur,r=e.length-1,o=1;for(let a=1;a<r;++a){let c=!1,l=e[a],h=e[a+1];if(l!==h&&(a!==1||l!==e[0]))if(i)c=!0;else{let u=a*n,d=u-n,p=u+n;for(let g=0;g!==n;++g){let _=t[u+g];if(_!==t[d+g]||_!==t[p+g]){c=!0;break}}}if(c){if(a!==o){e[o]=e[a];let u=a*n,d=o*n;for(let p=0;p!==n;++p)t[d+p]=t[u+p]}++o}}if(r>0){e[o]=e[r];for(let a=r*n,c=o*n,l=0;l!==n;++l)t[c+l]=t[a+l];++o}return o!==e.length?(this.times=e.slice(0,o),this.values=t.slice(0,o*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}};Ft.prototype.ValueTypeName="";Ft.prototype.TimeBufferType=Float32Array;Ft.prototype.ValueBufferType=Float32Array;Ft.prototype.DefaultInterpolation=hi;var Ln=class extends Ft{constructor(e,t,n){super(e,t,n)}};Ln.prototype.ValueTypeName="bool";Ln.prototype.ValueBufferType=Array;Ln.prototype.DefaultInterpolation=li;Ln.prototype.InterpolantFactoryMethodLinear=void 0;Ln.prototype.InterpolantFactoryMethodSmooth=void 0;var Gs=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};Gs.prototype.ValueTypeName="color";var gn=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};gn.prototype.ValueTypeName="number";var Kr=class extends Pn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=(n-t)/(i-t),l=e*a;for(let h=l+a;l!==h;l+=4)Rt.slerpFlat(r,0,o,l-a,o,l,c);return r}},_n=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Kr(this.times,this.values,this.getValueSize(),e)}};_n.prototype.ValueTypeName="quaternion";_n.prototype.InterpolantFactoryMethodSmooth=void 0;var Dn=class extends Ft{constructor(e,t,n){super(e,t,n)}};Dn.prototype.ValueTypeName="string";Dn.prototype.ValueBufferType=Array;Dn.prototype.DefaultInterpolation=li;Dn.prototype.InterpolantFactoryMethodLinear=void 0;Dn.prototype.InterpolantFactoryMethodSmooth=void 0;var xn=class extends Ft{constructor(e,t,n,i){super(e,t,n,i)}};xn.prototype.ValueTypeName="vector";var mi=class{constructor(e="",t=-1,n=[],i=qo){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=sn(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let o=0,a=n.length;o!==a;++o)t.push(md(n[o]).scale(i));let r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let r=0,o=n.length;r!==o;++r)t.push(Ft.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,o=[];for(let a=0;a<r;a++){let c=[],l=[];c.push((a+r-1)%r,a,(a+1)%r),l.push(0,1,0);let h=fd(c);c=Bl(c,1,h),l=Bl(l,1,h),!i&&c[0]===0&&(c.push(r),l.push(l[0])),o.push(new gn(".morphTargetInfluences["+t[a].name+"]",c,l).scale(1/n))}return new this(e,-1,o)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let i=e;n=i.geometry&&i.geometry.animations||i.animations}for(let i=0;i<n.length;i++)if(n[i].name===t)return n[i];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let i={},r=/^([\w-]*?)([\d]+)$/;for(let a=0,c=e.length;a<c;a++){let l=e[a],h=l.name.match(r);if(h&&h.length>1){let u=h[1],d=i[u];d||(i[u]=d=[]),d.push(l)}}let o=[];for(let a in i)o.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return o}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;let n=function(u,d,p,g,_){if(p.length!==0){let m=[],f=[];zh(p,m,f,g),m.length!==0&&_.push(new u(d,m,f))}},i=[],r=e.name||"default",o=e.fps||30,a=e.blendMode,c=e.length||-1,l=e.hierarchy||[];for(let u=0;u<l.length;u++){let d=l[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){let p={},g;for(g=0;g<d.length;g++)if(d[g].morphTargets)for(let _=0;_<d[g].morphTargets.length;_++)p[d[g].morphTargets[_]]=-1;for(let _ in p){let m=[],f=[];for(let E=0;E!==d[g].morphTargets.length;++E){let T=d[g];m.push(T.time),f.push(T.morphTarget===_?1:0)}i.push(new gn(".morphTargetInfluence["+_+"]",m,f))}c=p.length*o}else{let p=".bones["+t[u].name+"]";n(xn,p+".position",d,"pos",i),n(_n,p+".quaternion",d,"rot",i),n(xn,p+".scale",d,"scl",i)}}return i.length===0?null:new this(r,c,i,a)}resetDuration(){let e=this.tracks,t=0;for(let n=0,i=e.length;n!==i;++n){let 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(){let 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 pd(s){switch(s.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return gn;case"vector":case"vector2":case"vector3":case"vector4":return xn;case"color":return Gs;case"quaternion":return _n;case"bool":case"boolean":return Ln;case"string":return Dn}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+s)}function md(s){if(s.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let e=pd(s.type);if(s.times===void 0){let t=[],n=[];zh(s.keys,t,n,"value"),s.times=t,s.values=n}return e.parse!==void 0?e.parse(s):new e(s.name,s.times,s.values,s.interpolation)}var Cn={enabled:!1,files:{},add:function(s,e){this.enabled!==!1&&(this.files[s]=e)},get:function(s){if(this.enabled!==!1)return this.files[s]},remove:function(s){delete this.files[s]},clear:function(){this.files={}}},Jr=class{constructor(e,t,n){let i=this,r=!1,o=0,a=0,c,l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(h){a++,r===!1&&i.onStart!==void 0&&i.onStart(h,o,a),r=!0},this.itemEnd=function(h){o++,i.onProgress!==void 0&&i.onProgress(h,o,a),o===a&&(r=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(h){i.onError!==void 0&&i.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){let 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){let p=l[u],g=l[u+1];if(p.global&&(p.lastIndex=0),p.test(h))return g}return null}}},kh=new Jr,yn=class{constructor(e){this.manager=e!==void 0?e:kh,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(i,r){n.load(e,i,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}};yn.DEFAULT_MATERIAL_NAME="__DEFAULT";var Rn={},Pa=class extends Error{constructor(e,t){super(e),this.response=t}},es=class extends yn{constructor(e){super(e),this.mimeType="",this.responseType=""}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let r=Cn.get(e);if(r!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(r),this.manager.itemEnd(e)},0),r;if(Rn[e]!==void 0){Rn[e].push({onLoad:t,onProgress:n,onError:i});return}Rn[e]=[],Rn[e].push({onLoad:t,onProgress:n,onError:i});let o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,c=this.responseType;fetch(o).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;let h=Rn[e],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),p=d?parseInt(d):0,g=p!==0,_=0,m=new ReadableStream({start(f){E();function E(){u.read().then(({done:T,value:M})=>{if(T)f.close();else{_+=M.byteLength;let L=new ProgressEvent("progress",{lengthComputable:g,loaded:_,total:p});for(let R=0,w=h.length;R<w;R++){let N=h[R];N.onProgress&&N.onProgress(L)}f.enqueue(M),E()}},T=>{f.error(T)})}}});return new Response(m)}else throw new Pa(`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,a));case"json":return l.json();default:if(a==="")return l.text();{let u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,p=new TextDecoder(d);return l.arrayBuffer().then(g=>p.decode(g))}}}).then(l=>{Cn.add(e,l);let h=Rn[e];delete Rn[e];for(let u=0,d=h.length;u<d;u++){let p=h[u];p.onLoad&&p.onLoad(l)}}).catch(l=>{let h=Rn[e];if(h===void 0)throw this.manager.itemError(e),l;delete Rn[e];for(let u=0,d=h.length;u<d;u++){let p=h[u];p.onError&&p.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}};var $r=class extends yn{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let r=this,o=Cn.get(e);if(o!==void 0)return r.manager.itemStart(e),setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0),o;let a=Wi("img");function c(){h(),Cn.add(e,this),t&&t(this),r.manager.itemEnd(e)}function l(u){h(),i&&i(u),r.manager.itemError(e),r.manager.itemEnd(e)}function h(){a.removeEventListener("load",c,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",c,!1),a.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(e),a.src=e,a}};var Ws=class extends yn{constructor(e){super(e)}load(e,t,n,i){let r=new _t,o=new $r(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(a){r.image=a,r.needsUpdate=!0,t!==void 0&&t(r)},n,i),r}},gi=class extends rt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new be(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){let 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}};var Aa=new Ie,zl=new P,kl=new P,Xs=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ze(512,512),this.mapType=hn,this.map=null,this.mapPass=null,this.matrix=new Ie,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new $i,this._frameExtents=new ze(1,1),this._viewportCount=1,this._viewports=[new qe(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;zl.setFromMatrixPosition(e.matrixWorld),t.position.copy(zl),kl.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(kl),t.updateMatrixWorld(),Aa.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Aa),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Aa)}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(){let 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}},La=class extends Xs{constructor(){super(new dt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,n=ui*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=e.distance||t.far;(n!==t.fov||i!==t.aspect||r!==t.far)&&(t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},qs=class extends gi{constructor(e,t,n=0,i=Math.PI/3,r=0,o=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(rt.DEFAULT_UP),this.updateMatrix(),this.target=new rt,this.distance=n,this.angle=i,this.penumbra=r,this.decay=o,this.map=null,this.shadow=new La}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}},Vl=new Ie,vs=new P,wa=new P,Da=class extends Xs{constructor(){super(new dt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new ze(4,2),this._viewportCount=6,this._viewports=[new qe(2,1,1,1),new qe(0,1,1,1),new qe(3,1,1,1),new qe(1,1,1,1),new qe(3,0,1,1),new qe(1,0,1,1)],this._cubeDirections=[new P(1,0,0),new P(-1,0,0),new P(0,0,1),new P(0,0,-1),new P(0,1,0),new P(0,-1,0)],this._cubeUps=[new P(0,1,0),new P(0,1,0),new P(0,1,0),new P(0,1,0),new P(0,0,1),new P(0,0,-1)]}updateMatrices(e,t=0){let n=this.camera,i=this.matrix,r=e.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),vs.setFromMatrixPosition(e.matrixWorld),n.position.copy(vs),wa.copy(n.position),wa.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(wa),n.updateMatrixWorld(),i.makeTranslation(-vs.x,-vs.y,-vs.z),Vl.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Vl)}},Ys=class extends gi{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Da}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}},_i=class extends Is{constructor(e=-1,t=1,n=1,i=-1,r=.1,o=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=i,this.near=r,this.far=o,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,i,r,o){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=i,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2,r=n-e,o=n+e,a=i+t,c=i-t;if(this.view!==null&&this.view.enabled){let 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,o=r+l*this.view.width,a-=h*this.view.offsetY,c=a-h*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let 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}},Ua=class extends Xs{constructor(){super(new _i(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Kn=class extends gi{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(rt.DEFAULT_UP),this.updateMatrix(),this.target=new rt,this.shadow=new Ua}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},Zs=class extends gi{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}};var Un=class{static extractUrlBase(e){let 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)}};var Ks=class extends yn{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,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let r=this,o=Cn.get(e);if(o!==void 0){if(r.manager.itemStart(e),o.then){o.then(l=>{t&&t(l),r.manager.itemEnd(e)}).catch(l=>{i&&i(l)});return}return setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0),o}let a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader;let c=fetch(e,a).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(l){return Cn.add(e,l),t&&t(l),r.manager.itemEnd(e),l}).catch(function(l){i&&i(l),Cn.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)});Cn.add(e,c),r.manager.itemStart(e)}};var jr=class extends dt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Js=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Hl(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=Hl();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Hl(){return performance.now()}var Qr=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let i,r,o;switch(t){case"quaternion":i=this._slerp,r=this._slerpAdditive,o=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,o=this._setAdditiveIdentityOther,this.buffer=new Array(n*5);break;default:i=this._lerp,r=this._lerpAdditive,o=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=o,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,i=this.valueSize,r=e*i+i,o=this.cumulativeWeight;if(o===0){for(let a=0;a!==i;++a)n[r+a]=n[a];o=t}else{o+=t;let a=t/o;this._mixBufferRegion(n,r,0,a,i)}this.cumulativeWeight=o}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,i=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,i=e*t+t,r=this.cumulativeWeight,o=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){let c=t*this._origIndex;this._mixBufferRegion(n,i,c,1-r,t)}o>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let c=t,l=t+t;c!==l;++c)if(n[c]!==n[c+t]){a.setValue(n,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let r=n,o=i;r!==o;++r)t[r]=t[i+r%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let 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(){let 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,i,r){if(i>=.5)for(let o=0;o!==r;++o)e[t+o]=e[n+o]}_slerp(e,t,n,i){Rt.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){let o=this._workIndex*r;Rt.multiplyQuaternionsFlat(e,o,e,t,e,n),Rt.slerpFlat(e,t,e,t,e,o,i)}_lerp(e,t,n,i,r){let o=1-i;for(let a=0;a!==r;++a){let c=t+a;e[c]=e[c]*o+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let o=0;o!==r;++o){let a=t+o;e[a]=e[a]+e[n+o]*i}}},sc="\\[\\]\\.:\\/",gd=new RegExp("["+sc+"]","g"),rc="[^"+sc+"]",_d="[^"+sc.replace("\\.","")+"]",xd=/((?:WC+[\/:])*)/.source.replace("WC",rc),yd=/(WCOD+)?/.source.replace("WCOD",_d),vd=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",rc),Md=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",rc),Sd=new RegExp("^"+xd+yd+vd+Md+"$"),bd=["material","materials","bones","map"],Na=class{constructor(e,t,n){let i=n||Qe.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Qe=class s{constructor(e,t,n){this.path=t,this.parsedPath=n||s.parseTrackName(t),this.node=s.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 s.Composite(e,t,n):new s(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(gd,"")}static parseTrackName(e){let t=Sd.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let r=n.nodeName.substring(i+1);bd.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,i),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){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(r){for(let o=0;o<r.length;o++){let a=r[o];if(a.name===t||a.uuid===t)return a;let c=n(a.children);if(c)return c}return null},i=n(e.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)e[t++]=n[i]}_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){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=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,t=this.parsedPath,n=t.objectName,i=t.propertyName,r=t.propertyIndex;if(e||(e=s.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]}}let o=e[i];if(o===void 0){let l=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+l+"."+i+" but it wasn't found.",e);return}let a=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?a=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(a=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(r!==void 0){if(i==="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=o,this.propertyIndex=r}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Qe.Composite=Na;Qe.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};Qe.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};Qe.prototype.GetterByBindingType=[Qe.prototype._getValue_direct,Qe.prototype._getValue_array,Qe.prototype._getValue_arrayElement,Qe.prototype._getValue_toArray];Qe.prototype.SetterByBindingTypeAndVersioning=[[Qe.prototype._setValue_direct,Qe.prototype._setValue_direct_setNeedsUpdate,Qe.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Qe.prototype._setValue_array,Qe.prototype._setValue_array_setNeedsUpdate,Qe.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Qe.prototype._setValue_arrayElement,Qe.prototype._setValue_arrayElement_setNeedsUpdate,Qe.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Qe.prototype._setValue_fromArray,Qe.prototype._setValue_fromArray_setNeedsUpdate,Qe.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var eo=class{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;let r=t.tracks,o=r.length,a=new Array(o),c={endingStart:ri,endingEnd:ri};for(let l=0;l!==o;++l){let h=r[l].createInterpolant(null);a[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=a,this._propertyBindings=new Array(o),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=vh,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){let i=this._clip.duration,r=e._clip.duration,o=r/i,a=i/r;e.warp(1,o,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let 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){let i=this._mixer,r=i.time,o=this.timeScale,a=this._timeScaleInterpolant;a===null&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);let c=a.parameterPositions,l=a.sampleValues;return c[0]=r,c[1]=r+n,l[0]=e/o,l[1]=t/o,this}stopWarping(){let 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,i){if(!this.enabled){this._updateWeight(e);return}let r=this._startTime;if(r!==null){let c=(e-r)*n;c<0||n===0?t=0:(this._startTime=null,t=n*c)}t*=this._updateTimeScale(e);let o=this._updateTime(t),a=this._updateWeight(e);if(a>0){let c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case Sh:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(o),l[h].accumulateAdditive(a);break;case qo:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(o),l[h].accumulate(i,a)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,i=this.time+e,r=this._loopCount,o=n===Mh;if(e===0)return r===-1?i:o&&(r&1)===1?t-i:i;if(n===yh){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,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,o)):this._setEndings(this.repetitions===0,!0,o)),i>=t||i<0){let a=Math.floor(i/t);i-=t*a,r+=Math.abs(a);let c=this.repetitions-r;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(c===1){let l=e<0;this._setEndings(l,!l,o)}else this._setEndings(!1,!1,o);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this.time=i;if(o&&(r&1)===1)return t-i}return i}_setEndings(e,t,n){let i=this._interpolantSettings;n?(i.endingStart=oi,i.endingEnd=oi):(e?i.endingStart=this.zeroSlopeAtStart?oi:ri:i.endingStart=bs,t?i.endingEnd=this.zeroSlopeAtEnd?oi:ri:i.endingEnd=bs)}_scheduleFading(e,t,n){let i=this._mixer,r=i.time,o=this._weightInterpolant;o===null&&(o=i._lendControlInterpolant(),this._weightInterpolant=o);let a=o.parameterPositions,c=o.sampleValues;return a[0]=r,c[0]=t,a[1]=r+e,c[1]=n,this}},Td=new Float32Array(1),$s=class extends pn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let n=e._localRoot||this._root,i=e._clip.tracks,r=i.length,o=e._propertyBindings,a=e._interpolants,c=n.uuid,l=this._bindingsByRootAndName,h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==r;++u){let d=i[u],p=d.name,g=h[p];if(g!==void 0)++g.referenceCount,o[u]=g;else{if(g=o[u],g!==void 0){g._cacheIndex===null&&(++g.referenceCount,this._addInactiveBinding(g,c,p));continue}let _=t&&t._propertyBindings[u].binding.parsedPath;g=new Qr(Qe.create(n,p,_),d.ValueTypeName,d.getValueSize()),++g.referenceCount,this._addInactiveBinding(g,c,p),o[u]=g}a[u].resultBuffer=g.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,i=e._clip.uuid,r=this._actionsByClip[i];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,i,n)}let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];r.useCount++===0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let 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;let 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){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let i=this._actions,r=this._actionsByClip,o=r[t];if(o===void 0)o={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=o;else{let a=o.knownActions;e._byClipCacheIndex=a.length,a.push(e)}e._cacheIndex=i.length,i.push(e),o.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],i=e._cacheIndex;n._cacheIndex=i,t[i]=n,t.pop(),e._cacheIndex=null;let r=e._clip.uuid,o=this._actionsByClip,a=o[r],c=a.knownActions,l=c[c.length-1],h=e._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),e._byClipCacheIndex=null;let u=a.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],c.length===0&&delete o[r],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];--r.referenceCount===0&&this._removeInactiveBinding(r)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,i=this._nActiveActions++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){let i=this._bindingsByRootAndName,r=this._bindings,o=i[t];o===void 0&&(o={},i[t]=o),o[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,i=n.rootNode.uuid,r=n.path,o=this._bindingsByRootAndName,a=o[i],c=t[t.length-1],l=e._cacheIndex;c._cacheIndex=l,t[l]=c,t.pop(),delete a[r],Object.keys(a).length===0&&delete o[i]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new Hs(new Float32Array(2),new Float32Array(2),1,Td),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,r=t[i];e.__cacheIndex=i,t[i]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){let i=t||this._root,r=i.uuid,o=typeof e=="string"?mi.findByName(i,e):e,a=o!==null?o.uuid:e,c=this._actionsByClip[a],l=null;if(n===void 0&&(o!==null?n=o.blendMode:n=qo),c!==void 0){let u=c.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;l=c.knownActions[0],o===null&&(o=l._clip)}if(o===null)return null;let h=new eo(this,o,t,n);return this._bindAction(h,l),this._addInactiveAction(h,a,r),h}existingAction(e,t){let n=t||this._root,i=n.uuid,r=typeof e=="string"?mi.findByName(n,e):e,o=r?r.uuid:e,a=this._actionsByClip[o];return a!==void 0&&a.actionByRoot[i]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,i=this.time+=e,r=Math.sign(e),o=this._accuIndex^=1;for(let l=0;l!==n;++l)t[l]._update(i,e,r,o);let a=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)a[l].apply(o);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){let t=this._actions,n=e.uuid,i=this._actionsByClip,r=i[n];if(r!==void 0){let o=r.knownActions;for(let a=0,c=o.length;a!==c;++a){let l=o[a];this._deactivateAction(l);let 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 i[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let o in n){let a=n[o].actionByRoot,c=a[t];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}let i=this._bindingsByRootAndName,r=i[t];if(r!==void 0)for(let o in r){let a=r[o];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}};function oc(s,e,t,n){let i=Ed(n);switch(t){case qa:return s*e;case go:return s*e/i.components*i.byteLength;case _o:return s*e/i.components*i.byteLength;case Za:return s*e*2/i.components*i.byteLength;case xo:return s*e*2/i.components*i.byteLength;case Ya:return s*e*3/i.components*i.byteLength;case Ht:return s*e*4/i.components*i.byteLength;case yo:return s*e*4/i.components*i.byteLength;case Qs:case er:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case tr:case nr:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case Mo:case bo:return Math.max(s,16)*Math.max(e,8)/4;case vo:case So:return Math.max(s,8)*Math.max(e,8)/2;case To:case Eo:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*8;case Ao:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case wo:return Math.floor((s+3)/4)*Math.floor((e+3)/4)*16;case Ro:return Math.floor((s+4)/5)*Math.floor((e+3)/4)*16;case Co:return Math.floor((s+4)/5)*Math.floor((e+4)/5)*16;case Io:return Math.floor((s+5)/6)*Math.floor((e+4)/5)*16;case Po:return Math.floor((s+5)/6)*Math.floor((e+5)/6)*16;case Lo:return Math.floor((s+7)/8)*Math.floor((e+4)/5)*16;case Do:return Math.floor((s+7)/8)*Math.floor((e+5)/6)*16;case Uo:return Math.floor((s+7)/8)*Math.floor((e+7)/8)*16;case No:return Math.floor((s+9)/10)*Math.floor((e+4)/5)*16;case Fo:return Math.floor((s+9)/10)*Math.floor((e+5)/6)*16;case Oo:return Math.floor((s+9)/10)*Math.floor((e+7)/8)*16;case Bo:return Math.floor((s+9)/10)*Math.floor((e+9)/10)*16;case zo:return Math.floor((s+11)/12)*Math.floor((e+9)/10)*16;case ko:return Math.floor((s+11)/12)*Math.floor((e+11)/12)*16;case ir:case Vo:case Ho:return Math.ceil(s/4)*Math.ceil(e/4)*16;case Ka:case Go:return Math.ceil(s/4)*Math.ceil(e/4)*8;case Wo:case Xo:return Math.ceil(s/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Ed(s){switch(s){case hn:case Ga:return{byteLength:1,components:1};case ns:case Wa:case is:return{byteLength:2,components:1};case po:case mo:return{byteLength:2,components:4};case Jn:case fo:case Zt:return{byteLength:4,components:1};case Xa:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${s}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"176"}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="176");function hu(){let s=null,e=!1,t=null,n=null;function i(r,o){t(r,o),n=s.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=s.requestAnimationFrame(i),e=!0)},stop:function(){s.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){s=r}}}function wd(s){let e=new WeakMap;function t(a,c){let l=a.array,h=a.usage,u=l.byteLength,d=s.createBuffer();s.bindBuffer(c,d),s.bufferData(c,l,h),a.onUploadCallback();let p;if(l instanceof Float32Array)p=s.FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?p=s.HALF_FLOAT:p=s.UNSIGNED_SHORT;else if(l instanceof Int16Array)p=s.SHORT;else if(l instanceof Uint32Array)p=s.UNSIGNED_INT;else if(l instanceof Int32Array)p=s.INT;else if(l instanceof Int8Array)p=s.BYTE;else if(l instanceof Uint8Array)p=s.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)p=s.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:d,type:p,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:u}}function n(a,c,l){let h=c.array,u=c.updateRanges;if(s.bindBuffer(l,a),u.length===0)s.bufferSubData(l,0,h);else{u.sort((p,g)=>p.start-g.start);let d=0;for(let p=1;p<u.length;p++){let g=u[d],_=u[p];_.start<=g.start+g.count+1?g.count=Math.max(g.count,_.start+_.count-g.start):(++d,u[d]=_)}u.length=d+1;for(let p=0,g=u.length;p<g;p++){let _=u[p];s.bufferSubData(l,_.start*h.BYTES_PER_ELEMENT,h,_.start,_.count)}c.clearUpdateRanges()}c.onUploadCallback()}function i(a){return a.isInterleavedBufferAttribute&&(a=a.data),e.get(a)}function r(a){a.isInterleavedBufferAttribute&&(a=a.data);let c=e.get(a);c&&(s.deleteBuffer(c.buffer),e.delete(a))}function o(a,c){if(a.isInterleavedBufferAttribute&&(a=a.data),a.isGLBufferAttribute){let h=e.get(a);(!h||h.version<a.version)&&e.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}let l=e.get(a);if(l===void 0)e.set(a,t(a,c));else if(l.version<a.version){if(l.size!==a.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,a,c),l.version=a.version}}return{get:i,remove:r,update:o}}var Rd=`#ifdef USE_ALPHAHASH+ if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;+#endif`,Cd=`#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 ) ) ) );+ }+ float hash3D( vec3 value ) {+ return hash2D( vec2( hash2D( value.xy ), value.z ) );+ }+ float getAlphaHashThreshold( vec3 position ) {+ float maxDeriv = max(+ length( dFdx( position.xyz ) ),+ length( dFdy( position.xyz ) )+ );+ float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );+ vec2 pixScales = vec2(+ exp2( floor( log2( pixScale ) ) ),+ exp2( ceil( log2( pixScale ) ) )+ );+ vec2 alpha = vec2(+ hash3D( floor( pixScales.x * position.xyz ) ),+ hash3D( floor( pixScales.y * position.xyz ) )+ );+ float lerpFactor = fract( log2( pixScale ) );+ float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;+ float a = min( lerpFactor, 1.0 - lerpFactor );+ vec3 cases = vec3(+ x * x / ( 2.0 * a * ( 1.0 - a ) ),+ ( x - 0.5 * a ) / ( 1.0 - a ),+ 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )+ );+ float threshold = ( x < ( 1.0 - a ) )+ ? ( ( x < a ) ? cases.x : cases.y )+ : cases.z;+ return clamp( threshold , 1.0e-6, 1.0 );+ }+#endif`,Id=`#ifdef USE_ALPHAMAP+ diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;+#endif`,Pd=`#ifdef USE_ALPHAMAP+ uniform sampler2D alphaMap;+#endif`,Ld=`#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`,Dd=`#ifdef USE_ALPHATEST+ uniform float alphaTest;+#endif`,Ud=`#ifdef USE_AOMAP+ float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;+ reflectedLight.indirectDiffuse *= ambientOcclusion;+ #if defined( USE_CLEARCOAT )+ clearcoatSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_SHEEN )+ sheenSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_ENVMAP ) && defined( STANDARD )+ float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );+ reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );+ #endif+#endif`,Nd=`#ifdef USE_AOMAP+ uniform sampler2D aoMap;+ uniform float aoMapIntensity;+#endif`,Fd=`#ifdef USE_BATCHING+ #if ! defined( GL_ANGLE_multi_draw )+ #define gl_DrawID _gl_DrawID+ uniform int _gl_DrawID;+ #endif+ uniform highp sampler2D batchingTexture;+ uniform highp usampler2D batchingIdTexture;+ mat4 getBatchingMatrix( const in float i ) {+ int size = textureSize( batchingTexture, 0 ).x;+ int j = int( i ) * 4;+ int x = j % size;+ int y = j / size;+ vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );+ vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );+ vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );+ vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );+ return mat4( v1, v2, v3, v4 );+ }+ float getIndirectIndex( const in int i ) {+ int size = textureSize( batchingIdTexture, 0 ).x;+ int x = i % size;+ int y = i / size;+ return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );+ }+#endif+#ifdef USE_BATCHING_COLOR+ uniform sampler2D batchingColorTexture;+ vec3 getBatchingColor( const in float i ) {+ int size = textureSize( batchingColorTexture, 0 ).x;+ int j = int( i );+ int x = j % size;+ int y = j / size;+ return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;+ }+#endif`,Od=`#ifdef USE_BATCHING+ mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );+#endif`,Bd=`vec3 transformed = vec3( position );+#ifdef USE_ALPHAHASH+ vPosition = vec3( position );+#endif`,zd=`vec3 objectNormal = vec3( normal );+#ifdef USE_TANGENT+ vec3 objectTangent = vec3( tangent.xyz );+#endif`,kd=`float G_BlinnPhong_Implicit( ) {+ return 0.25;+}+float D_BlinnPhong( const in float shininess, const in float dotNH ) {+ return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );+}+vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( specularColor, 1.0, dotVH );+ float G = G_BlinnPhong_Implicit( );+ float D = D_BlinnPhong( shininess, dotNH );+ return F * ( G * D );+} // validated`,Vd=`#ifdef USE_IRIDESCENCE+ const mat3 XYZ_TO_REC709 = mat3(+ 3.2404542, -0.9692660, 0.0556434,+ -1.5371385, 1.8760108, -0.2040259,+ -0.4985314, 0.0415560, 1.0572252+ );+ vec3 Fresnel0ToIor( vec3 fresnel0 ) {+ vec3 sqrtF0 = sqrt( fresnel0 );+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );+ }+ vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );+ }+ float IorToFresnel0( float transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));+ }+ vec3 evalSensitivity( float OPD, vec3 shift ) {+ float phase = 2.0 * PI * OPD * 1.0e-9;+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );+ xyz /= 1.0685e-7;+ vec3 rgb = XYZ_TO_REC709 * xyz;+ return rgb;+ }+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {+ vec3 I;+ float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );+ float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );+ float cosTheta2Sq = 1.0 - sinTheta2Sq;+ if ( cosTheta2Sq < 0.0 ) {+ return vec3( 1.0 );+ }+ float cosTheta2 = sqrt( cosTheta2Sq );+ float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );+ float R12 = F_Schlick( R0, 1.0, cosTheta1 );+ float T121 = 1.0 - R12;+ float phi12 = 0.0;+ if ( iridescenceIOR < outsideIOR ) phi12 = PI;+ float phi21 = PI - phi12;+ vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );+ vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );+ vec3 phi23 = vec3( 0.0 );+ if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;+ if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;+ if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;+ float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;+ vec3 phi = vec3( phi21 ) + phi23;+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );+ vec3 r123 = sqrt( R123 );+ vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );+ vec3 C0 = R12 + Rs;+ I = C0;+ vec3 Cm = Rs - T121;+ for ( int m = 1; m <= 2; ++ m ) {+ Cm *= r123;+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );+ I += Cm * Sm;+ }+ return max( I, vec3( 0.0 ) );+ }+#endif`,Hd=`#ifdef USE_BUMPMAP+ uniform sampler2D bumpMap;+ uniform float bumpScale;+ vec2 dHdxy_fwd() {+ vec2 dSTdx = dFdx( vBumpMapUv );+ vec2 dSTdy = dFdy( vBumpMapUv );+ float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;+ float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;+ float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;+ return vec2( dBx, dBy );+ }+ vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {+ vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );+ vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );+ vec3 vN = surf_norm;+ vec3 R1 = cross( vSigmaY, vN );+ vec3 R2 = cross( vN, vSigmaX );+ float fDet = dot( vSigmaX, R1 ) * faceDirection;+ vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );+ return normalize( abs( fDet ) * surf_norm - vGrad );+ }+#endif`,Gd=`#if NUM_CLIPPING_PLANES > 0+ vec4 plane;+ #ifdef ALPHA_TO_COVERAGE+ float distanceToPlane, distanceGradient;+ float clipOpacity = 1.0;+ #pragma unroll_loop_start+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;+ distanceGradient = fwidth( distanceToPlane ) / 2.0;+ clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );+ if ( clipOpacity == 0.0 ) discard;+ }+ #pragma unroll_loop_end+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES+ float unionClipOpacity = 1.0;+ #pragma unroll_loop_start+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;+ distanceGradient = fwidth( distanceToPlane ) / 2.0;+ unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );+ }+ #pragma unroll_loop_end+ clipOpacity *= 1.0 - unionClipOpacity;+ #endif+ diffuseColor.a *= clipOpacity;+ if ( diffuseColor.a == 0.0 ) discard;+ #else+ #pragma unroll_loop_start+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;+ }+ #pragma unroll_loop_end+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES+ bool clipped = true;+ #pragma unroll_loop_start+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;+ }+ #pragma unroll_loop_end+ if ( clipped ) discard;+ #endif+ #endif+#endif`,Wd=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+ uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];+#endif`,Xd=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+#endif`,qd=`#if NUM_CLIPPING_PLANES > 0+ vClipPosition = - mvPosition.xyz;+#endif`,Yd=`#if defined( USE_COLOR_ALPHA )+ diffuseColor *= vColor;+#elif defined( USE_COLOR )+ diffuseColor.rgb *= vColor;+#endif`,Zd=`#if defined( USE_COLOR_ALPHA )+ varying vec4 vColor;+#elif defined( USE_COLOR )+ varying vec3 vColor;+#endif`,Kd=`#if defined( USE_COLOR_ALPHA )+ varying vec4 vColor;+#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+ varying vec3 vColor;+#endif`,Jd=`#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 );+#endif+#ifdef USE_COLOR+ vColor *= color;+#endif+#ifdef USE_INSTANCING_COLOR+ vColor.xyz *= instanceColor.xyz;+#endif+#ifdef USE_BATCHING_COLOR+ vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );+ vColor.xyz *= batchingColor.xyz;+#endif`,$d=`#define PI 3.141592653589793+#define PI2 6.283185307179586+#define PI_HALF 1.5707963267948966+#define RECIPROCAL_PI 0.3183098861837907+#define RECIPROCAL_PI2 0.15915494309189535+#define EPSILON 1e-6+#ifndef saturate+#define saturate( a ) clamp( a, 0.0, 1.0 )+#endif+#define whiteComplement( a ) ( 1.0 - saturate( a ) )+float pow2( const in float x ) { return x*x; }+vec3 pow2( const in vec3 x ) { return x*x; }+float pow3( const in float x ) { return x*x*x; }+float pow4( const in float x ) { float x2 = x*x; return x2*x2; }+float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }+float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }+highp float rand( const in vec2 uv ) {+ const highp float a = 12.9898, b = 78.233, c = 43758.5453;+ highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );+ return fract( sin( sn ) * c );+}+#ifdef HIGH_PRECISION+ float precisionSafeLength( vec3 v ) { return length( v ); }+#else+ float precisionSafeLength( vec3 v ) {+ float maxComponent = max3( abs( v ) );+ return length( v / maxComponent ) * maxComponent;+ }+#endif+struct IncidentLight {+ vec3 color;+ vec3 direction;+ bool visible;+};+struct ReflectedLight {+ vec3 directDiffuse;+ vec3 directSpecular;+ vec3 indirectDiffuse;+ vec3 indirectSpecular;+};+#ifdef USE_ALPHAHASH+ varying vec3 vPosition;+#endif+vec3 transformDirection( in vec3 dir, in mat4 matrix ) {+ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );+}+vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {+ return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );+}+mat3 transposeMat3( const in mat3 m ) {+ mat3 tmp;+ tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );+ tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );+ tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );+ return tmp;+}+bool isPerspectiveMatrix( mat4 m ) {+ return m[ 2 ][ 3 ] == - 1.0;+}+vec2 equirectUv( in vec3 dir ) {+ float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;+ float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;+ return vec2( u, v );+}+vec3 BRDF_Lambert( const in vec3 diffuseColor ) {+ return RECIPROCAL_PI * diffuseColor;+}+vec3 F_Schlick( const in vec3 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 );+}+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`,jd=`#ifdef ENVMAP_TYPE_CUBE_UV+ #define cubeUV_minMipLevel 4.0+ #define cubeUV_minTileSize 16.0+ float getFace( vec3 direction ) {+ vec3 absDirection = abs( direction );+ float face = - 1.0;+ if ( absDirection.x > absDirection.z ) {+ if ( absDirection.x > absDirection.y )+ face = direction.x > 0.0 ? 0.0 : 3.0;+ else+ face = direction.y > 0.0 ? 1.0 : 4.0;+ } else {+ if ( absDirection.z > absDirection.y )+ face = direction.z > 0.0 ? 2.0 : 5.0;+ else+ face = direction.y > 0.0 ? 1.0 : 4.0;+ }+ return face;+ }+ vec2 getUV( vec3 direction, float face ) {+ vec2 uv;+ if ( face == 0.0 ) {+ uv = vec2( direction.z, direction.y ) / abs( direction.x );+ } else if ( face == 1.0 ) {+ uv = vec2( - direction.x, - direction.z ) / abs( direction.y );+ } else if ( face == 2.0 ) {+ uv = vec2( - direction.x, direction.y ) / abs( direction.z );+ } else if ( face == 3.0 ) {+ uv = vec2( - direction.z, direction.y ) / abs( direction.x );+ } else if ( face == 4.0 ) {+ uv = vec2( - direction.x, direction.z ) / abs( direction.y );+ } else {+ uv = vec2( direction.x, direction.y ) / abs( direction.z );+ }+ return 0.5 * ( uv + 1.0 );+ }+ vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {+ float face = getFace( direction );+ float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );+ mipInt = max( mipInt, cubeUV_minMipLevel );+ float faceSize = exp2( mipInt );+ highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;+ if ( face > 2.0 ) {+ uv.y += faceSize;+ face -= 3.0;+ }+ uv.x += face * faceSize;+ uv.x += filterInt * 3.0 * cubeUV_minTileSize;+ uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );+ uv.x *= CUBEUV_TEXEL_WIDTH;+ uv.y *= CUBEUV_TEXEL_HEIGHT;+ #ifdef texture2DGradEXT+ return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;+ #else+ return texture2D( envMap, uv ).rgb;+ #endif+ }+ #define cubeUV_r0 1.0+ #define cubeUV_m0 - 2.0+ #define cubeUV_r1 0.8+ #define cubeUV_m1 - 1.0+ #define cubeUV_r4 0.4+ #define cubeUV_m4 2.0+ #define cubeUV_r5 0.305+ #define cubeUV_m5 3.0+ #define cubeUV_r6 0.21+ #define cubeUV_m6 4.0+ float roughnessToMip( float roughness ) {+ float mip = 0.0;+ if ( roughness >= cubeUV_r1 ) {+ mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;+ } else if ( roughness >= cubeUV_r4 ) {+ mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;+ } else if ( roughness >= cubeUV_r5 ) {+ mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;+ } else if ( roughness >= cubeUV_r6 ) {+ mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;+ } else {+ mip = - 2.0 * log2( 1.16 * roughness ); }+ return mip;+ }+ vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {+ float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );+ float mipF = fract( mip );+ float mipInt = floor( mip );+ vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );+ if ( mipF == 0.0 ) {+ return vec4( color0, 1.0 );+ } else {+ vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );+ return vec4( mix( color0, color1, mipF ), 1.0 );+ }+ }+#endif`,Qd=`vec3 transformedNormal = objectNormal;+#ifdef USE_TANGENT+ vec3 transformedTangent = objectTangent;+#endif+#ifdef USE_BATCHING+ mat3 bm = mat3( batchingMatrix );+ transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );+ transformedNormal = bm * transformedNormal;+ #ifdef USE_TANGENT+ transformedTangent = bm * transformedTangent;+ #endif+#endif+#ifdef USE_INSTANCING+ mat3 im = mat3( instanceMatrix );+ transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );+ transformedNormal = im * transformedNormal;+ #ifdef USE_TANGENT+ transformedTangent = im * transformedTangent;+ #endif+#endif+transformedNormal = normalMatrix * transformedNormal;+#ifdef FLIP_SIDED+ transformedNormal = - transformedNormal;+#endif+#ifdef USE_TANGENT+ transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;+ #ifdef FLIP_SIDED+ transformedTangent = - transformedTangent;+ #endif+#endif`,ef=`#ifdef USE_DISPLACEMENTMAP+ uniform sampler2D displacementMap;+ uniform float displacementScale;+ uniform float displacementBias;+#endif`,tf=`#ifdef USE_DISPLACEMENTMAP+ transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );+#endif`,nf=`#ifdef USE_EMISSIVEMAP+ vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE+ emissiveColor = sRGBTransferEOTF( emissiveColor );+ #endif+ totalEmissiveRadiance *= emissiveColor.rgb;+#endif`,sf=`#ifdef USE_EMISSIVEMAP+ uniform sampler2D emissiveMap;+#endif`,rf="gl_FragColor = linearToOutputTexel( gl_FragColor );",of=`vec4 LinearTransferOETF( in vec4 value ) {+ return value;+}+vec4 sRGBTransferEOTF( in vec4 value ) {+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );+}+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 );+}`,af=`#ifdef USE_ENVMAP+ #ifdef ENV_WORLDPOS+ vec3 cameraToFrag;+ if ( isOrthographic ) {+ cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );+ } else {+ cameraToFrag = normalize( vWorldPosition - cameraPosition );+ }+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ #ifdef ENVMAP_MODE_REFLECTION+ vec3 reflectVec = reflect( cameraToFrag, worldNormal );+ #else+ vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );+ #endif+ #else+ vec3 reflectVec = vReflect;+ #endif+ #ifdef ENVMAP_TYPE_CUBE+ vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );+ #else+ vec4 envColor = vec4( 0.0 );+ #endif+ #ifdef ENVMAP_BLENDING_MULTIPLY+ outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );+ #elif defined( ENVMAP_BLENDING_MIX )+ outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );+ #elif defined( ENVMAP_BLENDING_ADD )+ outgoingLight += envColor.xyz * specularStrength * reflectivity;+ #endif+#endif`,cf=`#ifdef USE_ENVMAP+ uniform float envMapIntensity;+ uniform float flipEnvMap;+ uniform mat3 envMapRotation;+ #ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+ #else+ uniform sampler2D envMap;+ #endif++#endif`,lf=`#ifdef USE_ENVMAP+ uniform float reflectivity;+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )+ #define ENV_WORLDPOS+ #endif+ #ifdef ENV_WORLDPOS+ varying vec3 vWorldPosition;+ uniform float refractionRatio;+ #else+ varying vec3 vReflect;+ #endif+#endif`,hf=`#ifdef USE_ENVMAP+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )+ #define ENV_WORLDPOS+ #endif+ #ifdef ENV_WORLDPOS++ varying vec3 vWorldPosition;+ #else+ varying vec3 vReflect;+ uniform float refractionRatio;+ #endif+#endif`,uf=`#ifdef USE_ENVMAP+ #ifdef ENV_WORLDPOS+ vWorldPosition = worldPosition.xyz;+ #else+ vec3 cameraToVertex;+ if ( isOrthographic ) {+ cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );+ } else {+ cameraToVertex = normalize( worldPosition.xyz - cameraPosition );+ }+ vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );+ #ifdef ENVMAP_MODE_REFLECTION+ vReflect = reflect( cameraToVertex, worldNormal );+ #else+ vReflect = refract( cameraToVertex, worldNormal, refractionRatio );+ #endif+ #endif+#endif`,df=`#ifdef USE_FOG+ vFogDepth = - mvPosition.z;+#endif`,ff=`#ifdef USE_FOG+ varying float vFogDepth;+#endif`,pf=`#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`,mf=`#ifdef USE_FOG+ uniform vec3 fogColor;+ varying float vFogDepth;+ #ifdef FOG_EXP2+ uniform float fogDensity;+ #else+ uniform float fogNear;+ uniform float fogFar;+ #endif+#endif`,gf=`#ifdef USE_GRADIENTMAP+ uniform sampler2D gradientMap;+#endif+vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {+ float dotNL = dot( normal, lightDirection );+ vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );+ #ifdef USE_GRADIENTMAP+ return vec3( texture2D( gradientMap, coord ).r );+ #else+ 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+}`,_f=`#ifdef USE_LIGHTMAP+ uniform sampler2D lightMap;+ uniform float lightMapIntensity;+#endif`,xf=`LambertMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularStrength = specularStrength;`,yf=`varying vec3 vViewPosition;+struct LambertMaterial {+ vec3 diffuseColor;+ float specularStrength;+};+void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_Lambert+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,vf=`uniform bool receiveShadow;+uniform vec3 ambientLightColor;+#if defined( USE_LIGHT_PROBES )+ uniform vec3 lightProbe[ 9 ];+#endif+vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {+ float x = normal.x, y = normal.y, z = normal.z;+ vec3 result = shCoefficients[ 0 ] * 0.886227;+ result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;+ result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;+ result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;+ result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;+ result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;+ result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );+ result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;+ result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );+ return result;+}+vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );+ return irradiance;+}+vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {+ vec3 irradiance = ambientLightColor;+ return irradiance;+}+float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );+ if ( cutoffDistance > 0.0 ) {+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );+ }+ return distanceFalloff;+}+float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {+ return smoothstep( coneCosine, penumbraCosine, angleCosine );+}+#if NUM_DIR_LIGHTS > 0+ struct DirectionalLight {+ vec3 direction;+ vec3 color;+ };+ uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];+ void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {+ light.color = directionalLight.color;+ light.direction = directionalLight.direction;+ light.visible = true;+ }+#endif+#if NUM_POINT_LIGHTS > 0+ struct PointLight {+ vec3 position;+ vec3 color;+ float distance;+ float decay;+ };+ uniform PointLight pointLights[ NUM_POINT_LIGHTS ];+ void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {+ vec3 lVector = pointLight.position - geometryPosition;+ light.direction = normalize( lVector );+ float lightDistance = length( lVector );+ light.color = pointLight.color;+ light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );+ light.visible = ( light.color != vec3( 0.0 ) );+ }+#endif+#if NUM_SPOT_LIGHTS > 0+ struct SpotLight {+ vec3 position;+ vec3 direction;+ vec3 color;+ float distance;+ float decay;+ float coneCos;+ float penumbraCos;+ };+ uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];+ void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {+ vec3 lVector = spotLight.position - geometryPosition;+ light.direction = normalize( lVector );+ float angleCos = dot( light.direction, spotLight.direction );+ float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );+ if ( spotAttenuation > 0.0 ) {+ float lightDistance = length( lVector );+ light.color = spotLight.color * spotAttenuation;+ light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );+ light.visible = ( light.color != vec3( 0.0 ) );+ } else {+ light.color = vec3( 0.0 );+ light.visible = false;+ }+ }+#endif+#if NUM_RECT_AREA_LIGHTS > 0+ struct RectAreaLight {+ vec3 color;+ vec3 position;+ vec3 halfWidth;+ vec3 halfHeight;+ };+ uniform sampler2D ltc_1; uniform sampler2D ltc_2;+ uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];+#endif+#if NUM_HEMI_LIGHTS > 0+ struct HemisphereLight {+ vec3 direction;+ vec3 skyColor;+ vec3 groundColor;+ };+ uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];+ vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {+ float dotNL = dot( normal, hemiLight.direction );+ float hemiDiffuseWeight = 0.5 * dotNL + 0.5;+ vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );+ return irradiance;+ }+#endif`,Mf=`#ifdef USE_ENVMAP+ vec3 getIBLIrradiance( const in vec3 normal ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );+ return PI * envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 reflectVec = reflect( - viewDir, normal );+ reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );+ reflectVec = inverseTransformDirection( reflectVec, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );+ return envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ #ifdef USE_ANISOTROPY+ vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 bentNormal = cross( bitangent, viewDir );+ bentNormal = normalize( cross( bentNormal, bitangent ) );+ bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );+ return getIBLRadiance( viewDir, bentNormal, roughness );+ #else+ return vec3( 0.0 );+ #endif+ }+ #endif+#endif`,Sf=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,bf=`varying vec3 vViewPosition;+struct ToonMaterial {+ vec3 diffuseColor;+};+void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {+ vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_Toon+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Tf=`BlinnPhongMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularColor = specular;+material.specularShininess = shininess;+material.specularStrength = specularStrength;`,Ef=`varying vec3 vViewPosition;+struct BlinnPhongMaterial {+ vec3 diffuseColor;+ vec3 specularColor;+ float specularShininess;+ float specularStrength;+};+void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+ reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;+}+void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_BlinnPhong+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Af=`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 );+material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;+material.roughness = min( material.roughness, 1.0 );+#ifdef IOR+ material.ior = ior;+ #ifdef USE_SPECULAR+ float specularIntensityFactor = specularIntensity;+ vec3 specularColorFactor = specularColor;+ #ifdef USE_SPECULAR_COLORMAP+ specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;+ #endif+ #ifdef USE_SPECULAR_INTENSITYMAP+ specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;+ #endif+ material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );+ #else+ float specularIntensityFactor = 1.0;+ vec3 specularColorFactor = vec3( 1.0 );+ material.specularF90 = 1.0;+ #endif+ material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );+#else+ material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );+ material.specularF90 = 1.0;+#endif+#ifdef USE_CLEARCOAT+ material.clearcoat = clearcoat;+ material.clearcoatRoughness = clearcoatRoughness;+ material.clearcoatF0 = vec3( 0.04 );+ material.clearcoatF90 = 1.0;+ #ifdef USE_CLEARCOATMAP+ material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;+ #endif+ #ifdef USE_CLEARCOAT_ROUGHNESSMAP+ material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;+ #endif+ material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );+ material.clearcoatRoughness += geometryRoughness;+ material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );+#endif+#ifdef USE_DISPERSION+ material.dispersion = dispersion;+#endif+#ifdef USE_IRIDESCENCE+ material.iridescence = iridescence;+ material.iridescenceIOR = iridescenceIOR;+ #ifdef USE_IRIDESCENCEMAP+ material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;+ #endif+ #ifdef USE_IRIDESCENCE_THICKNESSMAP+ material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;+ #else+ material.iridescenceThickness = iridescenceThicknessMaximum;+ #endif+#endif+#ifdef USE_SHEEN+ material.sheenColor = sheenColor;+ #ifdef USE_SHEEN_COLORMAP+ material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;+ #endif+ material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );+ #ifdef USE_SHEEN_ROUGHNESSMAP+ material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;+ #endif+#endif+#ifdef USE_ANISOTROPY+ #ifdef USE_ANISOTROPYMAP+ mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );+ vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;+ vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;+ #else+ vec2 anisotropyV = anisotropyVector;+ #endif+ material.anisotropy = length( anisotropyV );+ if( material.anisotropy == 0.0 ) {+ anisotropyV = vec2( 1.0, 0.0 );+ } else {+ anisotropyV /= material.anisotropy;+ material.anisotropy = saturate( material.anisotropy );+ }+ 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`,wf=`struct PhysicalMaterial {+ vec3 diffuseColor;+ float roughness;+ vec3 specularColor;+ float specularF90;+ float dispersion;+ #ifdef USE_CLEARCOAT+ float clearcoat;+ float clearcoatRoughness;+ vec3 clearcoatF0;+ float clearcoatF90;+ #endif+ #ifdef USE_IRIDESCENCE+ float iridescence;+ float iridescenceIOR;+ float iridescenceThickness;+ vec3 iridescenceFresnel;+ vec3 iridescenceF0;+ #endif+ #ifdef USE_SHEEN+ vec3 sheenColor;+ float sheenRoughness;+ #endif+ #ifdef IOR+ float ior;+ #endif+ #ifdef USE_TRANSMISSION+ float transmission;+ float transmissionAlpha;+ float thickness;+ float attenuationDistance;+ vec3 attenuationColor;+ #endif+ #ifdef USE_ANISOTROPY+ float anisotropy;+ float alphaT;+ vec3 anisotropyT;+ vec3 anisotropyB;+ #endif+};+vec3 clearcoatSpecularDirect = vec3( 0.0 );+vec3 clearcoatSpecularIndirect = vec3( 0.0 );+vec3 sheenSpecularDirect = vec3( 0.0 );+vec3 sheenSpecularIndirect = vec3(0.0 );+vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {+ float x = clamp( 1.0 - dotVH, 0.0, 1.0 );+ float x2 = x * x;+ float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );+ return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );+}+float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {+ float a2 = pow2( alpha );+ float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );+ float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );+ return 0.5 / max( gv + gl, EPSILON );+}+float D_GGX( const in float alpha, const in float dotNH ) {+ float a2 = pow2( alpha );+ float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;+ return RECIPROCAL_PI * a2 / pow2( denom );+}+#ifdef USE_ANISOTROPY+ float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {+ float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );+ float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );+ float v = 0.5 / ( gv + gl );+ return saturate(v);+ }+ float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {+ float a2 = alphaT * alphaB;+ highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );+ highp float v2 = dot( v, v );+ float w2 = a2 / v2;+ return RECIPROCAL_PI * a2 * pow2 ( w2 );+ }+#endif+#ifdef USE_CLEARCOAT+ vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {+ vec3 f0 = material.clearcoatF0;+ float f90 = material.clearcoatF90;+ float roughness = material.clearcoatRoughness;+ float alpha = pow2( roughness );+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( f0, f90, dotVH );+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );+ float D = D_GGX( alpha, dotNH );+ return F * ( V * D );+ }+#endif+vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {+ vec3 f0 = material.specularColor;+ float f90 = material.specularF90;+ float roughness = material.roughness;+ float alpha = pow2( roughness );+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( f0, f90, dotVH );+ #ifdef USE_IRIDESCENCE+ F = mix( F, material.iridescenceFresnel, material.iridescence );+ #endif+ #ifdef USE_ANISOTROPY+ float dotTL = dot( material.anisotropyT, lightDir );+ float dotTV = dot( material.anisotropyT, viewDir );+ float dotTH = dot( material.anisotropyT, halfDir );+ float dotBL = dot( material.anisotropyB, lightDir );+ float dotBV = dot( material.anisotropyB, viewDir );+ float dotBH = dot( material.anisotropyB, halfDir );+ float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );+ float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );+ #else+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );+ float D = D_GGX( alpha, dotNH );+ #endif+ return F * ( V * D );+}+vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {+ const float LUT_SIZE = 64.0;+ const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;+ const float LUT_BIAS = 0.5 / LUT_SIZE;+ float dotNV = saturate( dot( N, V ) );+ vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );+ uv = uv * LUT_SCALE + LUT_BIAS;+ return uv;+}+float LTC_ClippedSphereFormFactor( const in vec3 f ) {+ float l = length( f );+ return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );+}+vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {+ float x = dot( v1, v2 );+ float y = abs( x );+ float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;+ float b = 3.4175940 + ( 4.1616724 + y ) * y;+ float v = a / b;+ float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;+ return cross( v1, v2 ) * theta_sintheta;+}+vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {+ vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];+ vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];+ vec3 lightNormal = cross( v1, v2 );+ if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );+ vec3 T1, T2;+ T1 = normalize( V - N * dot( V, N ) );+ T2 = - cross( N, T1 );+ mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );+ vec3 coords[ 4 ];+ coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );+ coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );+ coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );+ coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );+ coords[ 0 ] = normalize( coords[ 0 ] );+ coords[ 1 ] = normalize( coords[ 1 ] );+ coords[ 2 ] = normalize( coords[ 2 ] );+ coords[ 3 ] = normalize( coords[ 3 ] );+ vec3 vectorFormFactor = vec3( 0.0 );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );+ float result = LTC_ClippedSphereFormFactor( vectorFormFactor );+ return vec3( result );+}+#if defined( USE_SHEEN )+float D_Charlie( float roughness, float dotNH ) {+ float alpha = pow2( roughness );+ float invAlpha = 1.0 / alpha;+ float cos2h = dotNH * dotNH;+ float sin2h = max( 1.0 - cos2h, 0.0078125 );+ return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );+}+float V_Neubelt( float dotNV, float dotNL ) {+ return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );+}+vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float D = D_Charlie( sheenRoughness, dotNH );+ float V = V_Neubelt( dotNV, dotNL );+ return sheenColor * ( D * V );+}+#endif+float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {+ float dotNV = saturate( dot( normal, viewDir ) );+ float r2 = roughness * roughness;+ float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;+ float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;+ float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );+ return saturate( DG * RECIPROCAL_PI );+}+vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {+ float dotNV = saturate( dot( normal, viewDir ) );+ const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );+ const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );+ vec4 r = roughness * c0 + c1;+ float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;+ vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;+ return fab;+}+vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {+ vec2 fab = DFGApprox( normal, viewDir, roughness );+ return specularColor * fab.x + specularF90 * fab.y;+}+#ifdef USE_IRIDESCENCE+void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {+#else+void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {+#endif+ vec2 fab = DFGApprox( normal, viewDir, roughness );+ #ifdef USE_IRIDESCENCE+ vec3 Fr = mix( specularColor, iridescenceF0, iridescence );+ #else+ vec3 Fr = specularColor;+ #endif+ vec3 FssEss = Fr * fab.x + specularF90 * fab.y;+ float Ess = fab.x + fab.y;+ float Ems = 1.0 - Ess;+ vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );+ singleScatter += FssEss;+ multiScatter += Fms * Ems;+}+#if NUM_RECT_AREA_LIGHTS > 0+ void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ vec3 normal = geometryNormal;+ vec3 viewDir = geometryViewDir;+ vec3 position = geometryPosition;+ vec3 lightPos = rectAreaLight.position;+ vec3 halfWidth = rectAreaLight.halfWidth;+ vec3 halfHeight = rectAreaLight.halfHeight;+ vec3 lightColor = rectAreaLight.color;+ float roughness = material.roughness;+ vec3 rectCoords[ 4 ];+ rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;+ rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;+ rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;+ vec2 uv = LTC_Uv( normal, viewDir, roughness );+ vec4 t1 = texture2D( ltc_1, uv );+ vec4 t2 = texture2D( ltc_2, uv );+ mat3 mInv = mat3(+ vec3( t1.x, 0, t1.y ),+ vec3( 0, 1, 0 ),+ vec3( t1.z, 0, t1.w )+ );+ vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );+ reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );+ reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );+ }+#endif+void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ #ifdef USE_CLEARCOAT+ float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );+ vec3 ccIrradiance = dotNLcc * directLight.color;+ clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );+ #endif+ #ifdef USE_SHEEN+ sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );+ #endif+ reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {+ #ifdef USE_CLEARCOAT+ clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );+ #endif+ #ifdef USE_SHEEN+ sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );+ #endif+ vec3 singleScattering = vec3( 0.0 );+ vec3 multiScattering = vec3( 0.0 );+ vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;+ #ifdef USE_IRIDESCENCE+ computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );+ #else+ computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );+ #endif+ vec3 totalScattering = singleScattering + multiScattering;+ vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );+ reflectedLight.indirectSpecular += radiance * singleScattering;+ reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;+ reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;+}+#define RE_Direct RE_Direct_Physical+#define RE_Direct_RectArea RE_Direct_RectArea_Physical+#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical+#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 );+}`,Rf=`+vec3 geometryPosition = - vViewPosition;+vec3 geometryNormal = normal;+vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );+vec3 geometryClearcoatNormal = vec3( 0.0 );+#ifdef USE_CLEARCOAT+ geometryClearcoatNormal = clearcoatNormal;+#endif+#ifdef USE_IRIDESCENCE+ float dotNVi = saturate( dot( normal, geometryViewDir ) );+ if ( material.iridescenceThickness == 0.0 ) {+ material.iridescence = 0.0;+ } else {+ material.iridescence = saturate( material.iridescence );+ }+ if ( material.iridescence > 0.0 ) {+ material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );+ material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );+ }+#endif+IncidentLight directLight;+#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )+ PointLight pointLight;+ #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0+ PointLightShadow pointLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {+ pointLight = pointLights[ i ];+ getPointLightInfo( pointLight, geometryPosition, directLight );+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )+ pointLightShadow = pointLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )+ SpotLight spotLight;+ vec4 spotColor;+ vec3 spotLightCoord;+ bool inSpotLightMap;+ #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0+ SpotLightShadow spotLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {+ spotLight = spotLights[ i ];+ getSpotLightInfo( spotLight, geometryPosition, directLight );+ #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )+ #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX+ #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS+ #else+ #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )+ #endif+ #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )+ spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;+ inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );+ spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );+ directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;+ #endif+ #undef SPOT_LIGHT_MAP_INDEX+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ spotLightShadow = spotLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )+ DirectionalLight directionalLight;+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0+ DirectionalLightShadow directionalLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {+ directionalLight = directionalLights[ i ];+ getDirectionalLightInfo( directionalLight, directLight );+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )+ directionalLightShadow = directionalLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )+ RectAreaLight rectAreaLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {+ rectAreaLight = rectAreaLights[ i ];+ RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if defined( RE_IndirectDiffuse )+ vec3 iblIrradiance = vec3( 0.0 );+ vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );+ #if defined( USE_LIGHT_PROBES )+ irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );+ #endif+ #if ( NUM_HEMI_LIGHTS > 0 )+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {+ irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );+ }+ #pragma unroll_loop_end+ #endif+#endif+#if defined( RE_IndirectSpecular )+ vec3 radiance = vec3( 0.0 );+ vec3 clearcoatRadiance = vec3( 0.0 );+#endif`,Cf=`#if defined( RE_IndirectDiffuse )+ #ifdef USE_LIGHTMAP+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );+ vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;+ irradiance += lightMapIrradiance;+ #endif+ #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )+ iblIrradiance += getIBLIrradiance( geometryNormal );+ #endif+#endif+#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )+ #ifdef USE_ANISOTROPY+ radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );+ #else+ radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );+ #endif+ #ifdef USE_CLEARCOAT+ clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );+ #endif+#endif`,If=`#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`,Pf=`#if defined( USE_LOGDEPTHBUF )+ gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;+#endif`,Lf=`#if defined( USE_LOGDEPTHBUF )+ uniform float logDepthBufFC;+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,Df=`#ifdef USE_LOGDEPTHBUF+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,Uf=`#ifdef USE_LOGDEPTHBUF+ vFragDepth = 1.0 + gl_Position.w;+ vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );+#endif`,Nf=`#ifdef USE_MAP+ vec4 sampledDiffuseColor = texture2D( map, vMapUv );+ #ifdef DECODE_VIDEO_TEXTURE+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );+ #endif+ diffuseColor *= sampledDiffuseColor;+#endif`,Ff=`#ifdef USE_MAP+ uniform sampler2D map;+#endif`,Of=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )+ #if defined( USE_POINTS_UV )+ vec2 uv = vUv;+ #else+ vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;+ #endif+#endif+#ifdef USE_MAP+ diffuseColor *= texture2D( map, uv );+#endif+#ifdef USE_ALPHAMAP+ diffuseColor.a *= texture2D( alphaMap, uv ).g;+#endif`,Bf=`#if defined( USE_POINTS_UV )+ varying vec2 vUv;+#else+ #if defined( USE_MAP ) || defined( USE_ALPHAMAP )+ uniform mat3 uvTransform;+ #endif+#endif+#ifdef USE_MAP+ uniform sampler2D map;+#endif+#ifdef USE_ALPHAMAP+ uniform sampler2D alphaMap;+#endif`,zf=`float metalnessFactor = metalness;+#ifdef USE_METALNESSMAP+ vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );+ metalnessFactor *= texelMetalness.b;+#endif`,kf=`#ifdef USE_METALNESSMAP+ uniform sampler2D metalnessMap;+#endif`,Vf=`#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`,Hf=`#if defined( USE_MORPHCOLORS )+ vColor *= morphTargetBaseInfluence;+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {+ #if defined( USE_COLOR_ALPHA )+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];+ #elif defined( USE_COLOR )+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];+ #endif+ }+#endif`,Gf=`#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`,Wf=`#ifdef USE_MORPHTARGETS+ #ifndef USE_INSTANCING_MORPH+ uniform float morphTargetBaseInfluence;+ uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];+ #endif+ uniform sampler2DArray morphTargetsTexture;+ uniform ivec2 morphTargetsTextureSize;+ vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {+ int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;+ int y = texelIndex / morphTargetsTextureSize.x;+ int x = texelIndex - y * morphTargetsTextureSize.x;+ ivec3 morphUV = ivec3( x, y, morphTargetIndex );+ return texelFetch( morphTargetsTexture, morphUV, 0 );+ }+#endif`,Xf=`#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`,qf=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;+#ifdef FLAT_SHADED+ vec3 fdx = dFdx( vViewPosition );+ vec3 fdy = dFdy( vViewPosition );+ vec3 normal = normalize( cross( fdx, fdy ) );+#else+ vec3 normal = normalize( vNormal );+ #ifdef DOUBLE_SIDED+ normal *= faceDirection;+ #endif+#endif+#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )+ #ifdef USE_TANGENT+ mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );+ #else+ mat3 tbn = getTangentFrame( - vViewPosition, normal,+ #if defined( USE_NORMALMAP )+ vNormalMapUv+ #elif defined( USE_CLEARCOAT_NORMALMAP )+ vClearcoatNormalMapUv+ #else+ vUv+ #endif+ );+ #endif+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )+ tbn[0] *= faceDirection;+ tbn[1] *= faceDirection;+ #endif+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ #ifdef USE_TANGENT+ mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );+ #else+ mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );+ #endif+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )+ tbn2[0] *= faceDirection;+ tbn2[1] *= faceDirection;+ #endif+#endif+vec3 nonPerturbedNormal = normal;`,Yf=`#ifdef USE_NORMALMAP_OBJECTSPACE+ normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;+ #ifdef FLIP_SIDED+ normal = - normal;+ #endif+ #ifdef DOUBLE_SIDED+ normal = normal * faceDirection;+ #endif+ normal = normalize( normalMatrix * normal );+#elif defined( USE_NORMALMAP_TANGENTSPACE )+ vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;+ mapN.xy *= normalScale;+ normal = normalize( tbn * mapN );+#elif defined( USE_BUMPMAP )+ normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );+#endif`,Zf=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,Kf=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,Jf=`#ifndef FLAT_SHADED+ vNormal = normalize( transformedNormal );+ #ifdef USE_TANGENT+ vTangent = normalize( transformedTangent );+ vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );+ #endif+#endif`,$f=`#ifdef USE_NORMALMAP+ uniform sampler2D normalMap;+ uniform vec2 normalScale;+#endif+#ifdef USE_NORMALMAP_OBJECTSPACE+ uniform mat3 normalMatrix;+#endif+#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )+ mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {+ vec3 q0 = dFdx( eye_pos.xyz );+ vec3 q1 = dFdy( eye_pos.xyz );+ vec2 st0 = dFdx( uv.st );+ vec2 st1 = dFdy( uv.st );+ vec3 N = surf_norm;+ vec3 q1perp = cross( q1, N );+ vec3 q0perp = cross( N, q0 );+ vec3 T = q1perp * st0.x + q0perp * st1.x;+ vec3 B = q1perp * st0.y + q0perp * st1.y;+ float det = max( dot( T, T ), dot( B, B ) );+ float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );+ return mat3( T * scale, B * scale, N );+ }+#endif`,jf=`#ifdef USE_CLEARCOAT+ vec3 clearcoatNormal = nonPerturbedNormal;+#endif`,Qf=`#ifdef USE_CLEARCOAT_NORMALMAP+ vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;+ clearcoatMapN.xy *= clearcoatNormalScale;+ clearcoatNormal = normalize( tbn2 * clearcoatMapN );+#endif`,ep=`#ifdef USE_CLEARCOATMAP+ uniform sampler2D clearcoatMap;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ uniform sampler2D clearcoatNormalMap;+ uniform vec2 clearcoatNormalScale;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ uniform sampler2D clearcoatRoughnessMap;+#endif`,tp=`#ifdef USE_IRIDESCENCEMAP+ uniform sampler2D iridescenceMap;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ uniform sampler2D iridescenceThicknessMap;+#endif`,np=`#ifdef OPAQUE+diffuseColor.a = 1.0;+#endif+#ifdef USE_TRANSMISSION+diffuseColor.a *= material.transmissionAlpha;+#endif+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,ip=`vec3 packNormalToRGB( const in vec3 normal ) {+ return normalize( normal ) * 0.5 + 0.5;+}+vec3 unpackRGBToNormal( const in vec3 rgb ) {+ return 2.0 * rgb.xyz - 1.0;+}+const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;+const float Inv255 = 1. / 255.;+const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );+const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );+const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );+const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );+vec4 packDepthToRGBA( const in float v ) {+ if( v <= 0.0 )+ return vec4( 0., 0., 0., 0. );+ if( v >= 1.0 )+ return vec4( 1., 1., 1., 1. );+ float vuf;+ float af = modf( v * PackFactors.a, vuf );+ float bf = modf( vuf * ShiftRight8, vuf );+ float gf = modf( vuf * ShiftRight8, vuf );+ return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );+}+vec3 packDepthToRGB( const in float v ) {+ if( v <= 0.0 )+ return vec3( 0., 0., 0. );+ if( v >= 1.0 )+ return vec3( 1., 1., 1. );+ float vuf;+ float bf = modf( v * PackFactors.b, vuf );+ float gf = modf( vuf * ShiftRight8, vuf );+ return vec3( vuf * Inv255, gf * PackUpscale, bf );+}+vec2 packDepthToRG( const in float v ) {+ if( v <= 0.0 )+ return vec2( 0., 0. );+ if( v >= 1.0 )+ return vec2( 1., 1. );+ float vuf;+ float gf = modf( v * 256., vuf );+ return vec2( vuf * Inv255, gf );+}+float unpackRGBAToDepth( const in vec4 v ) {+ return dot( v, UnpackFactors4 );+}+float unpackRGBToDepth( const in vec3 v ) {+ return dot( v, UnpackFactors3 );+}+float unpackRGToDepth( const in vec2 v ) {+ return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;+}+vec4 pack2HalfToRGBA( const in vec2 v ) {+ vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );+ return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );+}+vec2 unpackRGBATo2Half( const in vec4 v ) {+ return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );+}+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {+ return ( viewZ + near ) / ( near - far );+}+float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {+ return depth * ( near - far ) - near;+}+float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {+ return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );+}+float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {+ return ( near * far ) / ( ( far - near ) * depth - far );+}`,sp=`#ifdef PREMULTIPLIED_ALPHA+ gl_FragColor.rgb *= gl_FragColor.a;+#endif`,rp=`vec4 mvPosition = vec4( transformed, 1.0 );+#ifdef USE_BATCHING+ mvPosition = batchingMatrix * mvPosition;+#endif+#ifdef USE_INSTANCING+ mvPosition = instanceMatrix * mvPosition;+#endif+mvPosition = modelViewMatrix * mvPosition;+gl_Position = projectionMatrix * mvPosition;`,op=`#ifdef DITHERING+ gl_FragColor.rgb = dithering( gl_FragColor.rgb );+#endif`,ap=`#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`,cp=`float roughnessFactor = roughness;+#ifdef USE_ROUGHNESSMAP+ vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );+ roughnessFactor *= texelRoughness.g;+#endif`,lp=`#ifdef USE_ROUGHNESSMAP+ uniform sampler2D roughnessMap;+#endif`,hp=`#if NUM_SPOT_LIGHT_COORDS > 0+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];+#endif+#if NUM_SPOT_LIGHT_MAPS > 0+ uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];+#endif+#ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];+ struct DirectionalLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];+ struct SpotLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];+ struct PointLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ float shadowCameraNear;+ float shadowCameraFar;+ };+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];+ #endif+ float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {+ return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );+ }+ vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {+ return unpackRGBATo2Half( texture2D( shadow, uv ) );+ }+ float VSMShadow (sampler2D shadow, vec2 uv, float compare ){+ float occlusion = 1.0;+ vec2 distribution = texture2DDistribution( shadow, uv );+ float hard_shadow = step( compare , distribution.x );+ if (hard_shadow != 1.0 ) {+ float distance = compare - distribution.x ;+ float variance = max( 0.00000, distribution.y * distribution.y );+ float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );+ }+ return occlusion;+ }+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {+ float shadow = 1.0;+ shadowCoord.xyz /= shadowCoord.w;+ shadowCoord.z += shadowBias;+ bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;+ bool frustumTest = inFrustum && shadowCoord.z <= 1.0;+ if ( frustumTest ) {+ #if defined( SHADOWMAP_TYPE_PCF )+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;+ float dx0 = - texelSize.x * shadowRadius;+ float dy0 = - texelSize.y * shadowRadius;+ float dx1 = + texelSize.x * shadowRadius;+ float dy1 = + texelSize.y * shadowRadius;+ float dx2 = dx0 / 2.0;+ float dy2 = dy0 / 2.0;+ float dx3 = dx1 / 2.0;+ float dy3 = dy1 / 2.0;+ shadow = (+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )+ ) * ( 1.0 / 17.0 );+ #elif defined( SHADOWMAP_TYPE_PCF_SOFT )+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;+ float dx = texelSize.x;+ float dy = texelSize.y;+ vec2 uv = shadowCoord.xy;+ vec2 f = fract( uv * shadowMapSize + 0.5 );+ uv -= f * texelSize;+ shadow = (+ texture2DCompare( shadowMap, uv, shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) ++ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),+ f.x ) ++ mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),+ f.x ) ++ mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),+ f.y ) ++ mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),+ f.y ) ++ mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),+ f.x ),+ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),+ f.x ),+ f.y )+ ) * ( 1.0 / 9.0 );+ #elif defined( SHADOWMAP_TYPE_VSM )+ shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );+ #else+ shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );+ #endif+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ vec2 cubeToUV( vec3 v, float texelSizeY ) {+ vec3 absV = abs( v );+ float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );+ absV *= scaleToCube;+ v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );+ vec2 planar = v.xy;+ float almostATexel = 1.5 * texelSizeY;+ float almostOne = 1.0 - almostATexel;+ if ( absV.z >= almostOne ) {+ if ( v.z > 0.0 )+ planar.x = 4.0 - v.x;+ } else if ( absV.x >= almostOne ) {+ float signX = sign( v.x );+ planar.x = v.z * signX + 2.0 * signX;+ } else if ( absV.y >= almostOne ) {+ float signY = sign( v.y );+ planar.x = v.x + 2.0 * signY + 2.0;+ planar.y = v.z * signY - 2.0;+ }+ return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );+ }+ float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {+ float shadow = 1.0;+ vec3 lightToPosition = shadowCoord.xyz;++ float lightToPositionLength = length( lightToPosition );+ if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {+ float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;+ vec3 bd3D = normalize( lightToPosition );+ vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );+ #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )+ vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;+ shadow = (+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )+ ) * ( 1.0 / 9.0 );+ #else+ shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );+ #endif+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+#endif`,up=`#if NUM_SPOT_LIGHT_COORDS > 0+ uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];+#endif+#ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];+ struct DirectionalLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ struct SpotLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];+ struct PointLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ float shadowCameraNear;+ float shadowCameraFar;+ };+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];+ #endif+#endif`,dp=`#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+#if defined( USE_SHADOWMAP )+ #if NUM_DIR_LIGHT_SHADOWS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );+ vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );+ vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+ #endif+#endif+#if NUM_SPOT_LIGHT_COORDS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {+ shadowWorldPosition = worldPosition;+ #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;+ #endif+ vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+#endif`,fp=`float getShadowMask() {+ float shadow = 1.0;+ #ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ DirectionalLightShadow directionalLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {+ directionalLight = directionalLightShadows[ i ];+ shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ SpotLightShadow spotLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {+ spotLight = spotLightShadows[ i ];+ shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ PointLightShadow pointLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {+ pointLight = pointLightShadows[ i ];+ shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #endif+ return shadow;+}`,pp=`#ifdef USE_SKINNING+ mat4 boneMatX = getBoneMatrix( skinIndex.x );+ mat4 boneMatY = getBoneMatrix( skinIndex.y );+ mat4 boneMatZ = getBoneMatrix( skinIndex.z );+ mat4 boneMatW = getBoneMatrix( skinIndex.w );+#endif`,mp=`#ifdef USE_SKINNING+ uniform mat4 bindMatrix;+ uniform mat4 bindMatrixInverse;+ uniform highp sampler2D boneTexture;+ mat4 getBoneMatrix( const in float i ) {+ int size = textureSize( boneTexture, 0 ).x;+ int j = int( i ) * 4;+ int x = j % size;+ int y = j / size;+ vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );+ vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );+ vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );+ vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );+ return mat4( v1, v2, v3, v4 );+ }+#endif`,gp=`#ifdef USE_SKINNING+ vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );+ vec4 skinned = vec4( 0.0 );+ skinned += boneMatX * skinVertex * skinWeight.x;+ skinned += boneMatY * skinVertex * skinWeight.y;+ skinned += boneMatZ * skinVertex * skinWeight.z;+ skinned += boneMatW * skinVertex * skinWeight.w;+ transformed = ( bindMatrixInverse * skinned ).xyz;+#endif`,_p=`#ifdef USE_SKINNING+ mat4 skinMatrix = mat4( 0.0 );+ skinMatrix += skinWeight.x * boneMatX;+ skinMatrix += skinWeight.y * boneMatY;+ skinMatrix += skinWeight.z * boneMatZ;+ skinMatrix += skinWeight.w * boneMatW;+ skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;+ objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;+ #ifdef USE_TANGENT+ objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;+ #endif+#endif`,xp=`float specularStrength;+#ifdef USE_SPECULARMAP+ vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );+ specularStrength = texelSpecular.r;+#else+ specularStrength = 1.0;+#endif`,yp=`#ifdef USE_SPECULARMAP+ uniform sampler2D specularMap;+#endif`,vp=`#if defined( TONE_MAPPING )+ gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );+#endif`,Mp=`#ifndef saturate+#define saturate( a ) clamp( a, 0.0, 1.0 )+#endif+uniform float toneMappingExposure;+vec3 LinearToneMapping( vec3 color ) {+ return saturate( toneMappingExposure * color );+}+vec3 ReinhardToneMapping( vec3 color ) {+ color *= toneMappingExposure;+ return saturate( color / ( vec3( 1.0 ) + color ) );+}+vec3 CineonToneMapping( vec3 color ) {+ color *= toneMappingExposure;+ color = max( vec3( 0.0 ), color - 0.004 );+ return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );+}+vec3 RRTAndODTFit( vec3 v ) {+ vec3 a = v * ( v + 0.0245786 ) - 0.000090537;+ vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;+ return a / b;+}+vec3 ACESFilmicToneMapping( vec3 color ) {+ const mat3 ACESInputMat = mat3(+ vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),+ vec3( 0.04823, 0.01566, 0.83777 )+ );+ const mat3 ACESOutputMat = mat3(+ vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),+ vec3( -0.07367, -0.00605, 1.07602 )+ );+ color *= toneMappingExposure / 0.6;+ color = ACESInputMat * color;+ color = RRTAndODTFit( color );+ color = ACESOutputMat * color;+ return saturate( color );+}+const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(+ vec3( 1.6605, - 0.1246, - 0.0182 ),+ vec3( - 0.5876, 1.1329, - 0.1006 ),+ vec3( - 0.0728, - 0.0083, 1.1187 )+);+const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(+ vec3( 0.6274, 0.0691, 0.0164 ),+ vec3( 0.3293, 0.9195, 0.0880 ),+ vec3( 0.0433, 0.0113, 0.8956 )+);+vec3 agxDefaultContrastApprox( vec3 x ) {+ vec3 x2 = x * x;+ vec3 x4 = x2 * x2;+ return + 15.5 * x4 * x2+ - 40.14 * x4 * x+ + 31.96 * x4+ - 6.868 * x2 * x+ + 0.4298 * x2+ + 0.1191 * x+ - 0.00232;+}+vec3 AgXToneMapping( vec3 color ) {+ const mat3 AgXInsetMatrix = mat3(+ vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),+ vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),+ vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )+ );+ const mat3 AgXOutsetMatrix = mat3(+ vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),+ vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),+ vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )+ );+ const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;+ color *= toneMappingExposure;+ color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;+ color = AgXInsetMatrix * color;+ color = max( color, 1e-10 ); color = log2( color );+ color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );+ color = clamp( color, 0.0, 1.0 );+ color = agxDefaultContrastApprox( color );+ color = AgXOutsetMatrix * color;+ color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );+ color = LINEAR_REC2020_TO_LINEAR_SRGB * color;+ color = clamp( color, 0.0, 1.0 );+ return color;+}+vec3 NeutralToneMapping( vec3 color ) {+ const float StartCompression = 0.8 - 0.04;+ const float Desaturation = 0.15;+ color *= toneMappingExposure;+ float x = min( color.r, min( color.g, color.b ) );+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;+ color -= offset;+ float peak = max( color.r, max( color.g, color.b ) );+ if ( peak < StartCompression ) return color;+ float d = 1. - StartCompression;+ float newPeak = 1. - d * d / ( peak + d - StartCompression );+ color *= newPeak / peak;+ float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );+ return mix( color, vec3( newPeak ), g );+}+vec3 CustomToneMapping( vec3 color ) { return color; }`,Sp=`#ifdef USE_TRANSMISSION+ material.transmission = transmission;+ material.transmissionAlpha = 1.0;+ material.thickness = thickness;+ material.attenuationDistance = attenuationDistance;+ material.attenuationColor = attenuationColor;+ #ifdef USE_TRANSMISSIONMAP+ material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;+ #endif+ #ifdef USE_THICKNESSMAP+ material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;+ #endif+ vec3 pos = vWorldPosition;+ vec3 v = normalize( cameraPosition - pos );+ vec3 n = inverseTransformDirection( normal, viewMatrix );+ vec4 transmitted = getIBLVolumeRefraction(+ n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,+ pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,+ material.attenuationColor, material.attenuationDistance );+ material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );+ totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );+#endif`,bp=`#ifdef USE_TRANSMISSION+ uniform float transmission;+ uniform float thickness;+ uniform float attenuationDistance;+ uniform vec3 attenuationColor;+ #ifdef USE_TRANSMISSIONMAP+ uniform sampler2D transmissionMap;+ #endif+ #ifdef USE_THICKNESSMAP+ uniform sampler2D thicknessMap;+ #endif+ uniform vec2 transmissionSamplerSize;+ uniform sampler2D transmissionSamplerMap;+ uniform mat4 modelMatrix;+ uniform mat4 projectionMatrix;+ varying vec3 vWorldPosition;+ float w0( float a ) {+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );+ }+ float w1( float a ) {+ return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );+ }+ float w2( float a ){+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );+ }+ float w3( float a ) {+ return ( 1.0 / 6.0 ) * ( a * a * a );+ }+ float g0( float a ) {+ return w0( a ) + w1( a );+ }+ float g1( float a ) {+ return w2( a ) + w3( a );+ }+ float h0( float a ) {+ return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );+ }+ float h1( float a ) {+ return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );+ }+ vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {+ uv = uv * texelSize.zw + 0.5;+ vec2 iuv = floor( uv );+ vec2 fuv = fract( uv );+ float g0x = g0( fuv.x );+ float g1x = g1( fuv.x );+ float h0x = h0( fuv.x );+ float h1x = h1( fuv.x );+ float h0y = h0( fuv.y );+ float h1y = h1( fuv.y );+ vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;+ vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;+ vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;+ vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;+ return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) ++ g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );+ }+ vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {+ vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );+ vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );+ vec2 fLodSizeInv = 1.0 / fLodSize;+ vec2 cLodSizeInv = 1.0 / cLodSize;+ vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );+ vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );+ return mix( fSample, cSample, fract( lod ) );+ }+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {+ vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );+ vec3 modelScale;+ modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );+ modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );+ modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );+ return normalize( refractionVector ) * thickness * modelScale;+ }+ float applyIorToRoughness( const in float roughness, const in float ior ) {+ return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );+ }+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {+ float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );+ return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );+ }+ vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {+ if ( isinf( attenuationDistance ) ) {+ return vec3( 1.0 );+ } else {+ vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;+ vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;+ }+ }+ vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,+ const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,+ const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,+ const in vec3 attenuationColor, const in float attenuationDistance ) {+ vec4 transmittedLight;+ vec3 transmittance;+ #ifdef USE_DISPERSION+ float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;+ vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );+ for ( int i = 0; i < 3; i ++ ) {+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );+ vec3 refractedRayExit = position + transmissionRay;+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;+ refractionCoords += 1.0;+ refractionCoords /= 2.0;+ vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );+ transmittedLight[ i ] = transmissionSample[ i ];+ transmittedLight.a += transmissionSample.a;+ transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];+ }+ transmittedLight.a /= 3.0;+ #else+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );+ vec3 refractedRayExit = position + transmissionRay;+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;+ refractionCoords += 1.0;+ refractionCoords /= 2.0;+ transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );+ transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );+ #endif+ vec3 attenuatedColor = transmittance * transmittedLight.rgb;+ vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );+ float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;+ return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );+ }+#endif`,Tp=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ varying vec2 vUv;+#endif+#ifdef USE_MAP+ varying vec2 vMapUv;+#endif+#ifdef USE_ALPHAMAP+ varying vec2 vAlphaMapUv;+#endif+#ifdef USE_LIGHTMAP+ varying vec2 vLightMapUv;+#endif+#ifdef USE_AOMAP+ varying vec2 vAoMapUv;+#endif+#ifdef USE_BUMPMAP+ varying vec2 vBumpMapUv;+#endif+#ifdef USE_NORMALMAP+ varying vec2 vNormalMapUv;+#endif+#ifdef USE_EMISSIVEMAP+ varying vec2 vEmissiveMapUv;+#endif+#ifdef USE_METALNESSMAP+ varying vec2 vMetalnessMapUv;+#endif+#ifdef USE_ROUGHNESSMAP+ varying vec2 vRoughnessMapUv;+#endif+#ifdef USE_ANISOTROPYMAP+ varying vec2 vAnisotropyMapUv;+#endif+#ifdef USE_CLEARCOATMAP+ varying vec2 vClearcoatMapUv;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ varying vec2 vClearcoatNormalMapUv;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ varying vec2 vClearcoatRoughnessMapUv;+#endif+#ifdef USE_IRIDESCENCEMAP+ varying vec2 vIridescenceMapUv;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ varying vec2 vIridescenceThicknessMapUv;+#endif+#ifdef USE_SHEEN_COLORMAP+ varying vec2 vSheenColorMapUv;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ varying vec2 vSheenRoughnessMapUv;+#endif+#ifdef USE_SPECULARMAP+ varying vec2 vSpecularMapUv;+#endif+#ifdef USE_SPECULAR_COLORMAP+ varying vec2 vSpecularColorMapUv;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ varying vec2 vSpecularIntensityMapUv;+#endif+#ifdef USE_TRANSMISSIONMAP+ uniform mat3 transmissionMapTransform;+ varying vec2 vTransmissionMapUv;+#endif+#ifdef USE_THICKNESSMAP+ uniform mat3 thicknessMapTransform;+ varying vec2 vThicknessMapUv;+#endif`,Ep=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ varying vec2 vUv;+#endif+#ifdef USE_MAP+ uniform mat3 mapTransform;+ varying vec2 vMapUv;+#endif+#ifdef USE_ALPHAMAP+ uniform mat3 alphaMapTransform;+ varying vec2 vAlphaMapUv;+#endif+#ifdef USE_LIGHTMAP+ uniform mat3 lightMapTransform;+ varying vec2 vLightMapUv;+#endif+#ifdef USE_AOMAP+ uniform mat3 aoMapTransform;+ varying vec2 vAoMapUv;+#endif+#ifdef USE_BUMPMAP+ uniform mat3 bumpMapTransform;+ varying vec2 vBumpMapUv;+#endif+#ifdef USE_NORMALMAP+ uniform mat3 normalMapTransform;+ varying vec2 vNormalMapUv;+#endif+#ifdef USE_DISPLACEMENTMAP+ uniform mat3 displacementMapTransform;+ varying vec2 vDisplacementMapUv;+#endif+#ifdef USE_EMISSIVEMAP+ uniform mat3 emissiveMapTransform;+ varying vec2 vEmissiveMapUv;+#endif+#ifdef USE_METALNESSMAP+ uniform mat3 metalnessMapTransform;+ varying vec2 vMetalnessMapUv;+#endif+#ifdef USE_ROUGHNESSMAP+ uniform mat3 roughnessMapTransform;+ varying vec2 vRoughnessMapUv;+#endif+#ifdef USE_ANISOTROPYMAP+ uniform mat3 anisotropyMapTransform;+ varying vec2 vAnisotropyMapUv;+#endif+#ifdef USE_CLEARCOATMAP+ uniform mat3 clearcoatMapTransform;+ varying vec2 vClearcoatMapUv;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ uniform mat3 clearcoatNormalMapTransform;+ varying vec2 vClearcoatNormalMapUv;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ uniform mat3 clearcoatRoughnessMapTransform;+ varying vec2 vClearcoatRoughnessMapUv;+#endif+#ifdef USE_SHEEN_COLORMAP+ uniform mat3 sheenColorMapTransform;+ varying vec2 vSheenColorMapUv;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ uniform mat3 sheenRoughnessMapTransform;+ varying vec2 vSheenRoughnessMapUv;+#endif+#ifdef USE_IRIDESCENCEMAP+ uniform mat3 iridescenceMapTransform;+ varying vec2 vIridescenceMapUv;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ uniform mat3 iridescenceThicknessMapTransform;+ varying vec2 vIridescenceThicknessMapUv;+#endif+#ifdef USE_SPECULARMAP+ uniform mat3 specularMapTransform;+ varying vec2 vSpecularMapUv;+#endif+#ifdef USE_SPECULAR_COLORMAP+ uniform mat3 specularColorMapTransform;+ varying vec2 vSpecularColorMapUv;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ uniform mat3 specularIntensityMapTransform;+ varying vec2 vSpecularIntensityMapUv;+#endif+#ifdef USE_TRANSMISSIONMAP+ uniform mat3 transmissionMapTransform;+ varying vec2 vTransmissionMapUv;+#endif+#ifdef USE_THICKNESSMAP+ uniform mat3 thicknessMapTransform;+ varying vec2 vThicknessMapUv;+#endif`,Ap=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ vUv = vec3( uv, 1 ).xy;+#endif+#ifdef USE_MAP+ vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ALPHAMAP+ vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_LIGHTMAP+ vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_AOMAP+ vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_BUMPMAP+ vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_NORMALMAP+ vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_DISPLACEMENTMAP+ vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_EMISSIVEMAP+ vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_METALNESSMAP+ vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ROUGHNESSMAP+ vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ANISOTROPYMAP+ vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOATMAP+ vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_IRIDESCENCEMAP+ vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SHEEN_COLORMAP+ vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULARMAP+ vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULAR_COLORMAP+ vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_TRANSMISSIONMAP+ vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_THICKNESSMAP+ vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;+#endif`,wp=`#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;+ #endif+ #ifdef USE_INSTANCING+ worldPosition = instanceMatrix * worldPosition;+ #endif+ worldPosition = modelMatrix * worldPosition;+#endif`,Rp=`varying vec2 vUv;+uniform mat3 uvTransform;+void main() {+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;+ gl_Position = vec4( position.xy, 1.0, 1.0 );+}`,Cp=`uniform sampler2D t2D;+uniform float backgroundIntensity;+varying vec2 vUv;+void main() {+ vec4 texColor = texture2D( t2D, vUv );+ #ifdef DECODE_VIDEO_TEXTURE+ texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );+ #endif+ texColor.rgb *= backgroundIntensity;+ gl_FragColor = texColor;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Ip=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,Pp=`#ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+#elif defined( ENVMAP_TYPE_CUBE_UV )+ uniform sampler2D envMap;+#endif+uniform float flipEnvMap;+uniform float backgroundBlurriness;+uniform float backgroundIntensity;+uniform mat3 backgroundRotation;+varying vec3 vWorldDirection;+#include <cube_uv_reflection_fragment>+void main() {+ #ifdef ENVMAP_TYPE_CUBE+ vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );+ #elif defined( ENVMAP_TYPE_CUBE_UV )+ vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );+ #else+ vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );+ #endif+ texColor.rgb *= backgroundIntensity;+ gl_FragColor = texColor;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Lp=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,Dp=`uniform samplerCube tCube;+uniform float tFlip;+uniform float opacity;+varying vec3 vWorldDirection;+void main() {+ vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );+ gl_FragColor = texColor;+ gl_FragColor.a *= opacity;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Up=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+varying vec2 vHighPrecisionZW;+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vHighPrecisionZW = gl_Position.zw;+}`,Np=`#if DEPTH_PACKING == 3200+ uniform float opacity;+#endif+#include <common>+#include <packing>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+varying vec2 vHighPrecisionZW;+void main() {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #if DEPTH_PACKING == 3200+ diffuseColor.a = opacity;+ #endif+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <logdepthbuf_fragment>+ float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;+ #if DEPTH_PACKING == 3200+ gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );+ #elif DEPTH_PACKING == 3201+ gl_FragColor = packDepthToRGBA( fragCoordZ );+ #elif DEPTH_PACKING == 3202+ gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );+ #elif DEPTH_PACKING == 3203+ gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );+ #endif+}`,Fp=`#define DISTANCE+varying vec3 vWorldPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <worldpos_vertex>+ #include <clipping_planes_vertex>+ vWorldPosition = worldPosition.xyz;+}`,Op=`#define DISTANCE+uniform vec3 referencePosition;+uniform float nearDistance;+uniform float farDistance;+varying vec3 vWorldPosition;+#include <common>+#include <packing>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <clipping_planes_pars_fragment>+void main () {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ float dist = length( vWorldPosition - referencePosition );+ dist = ( dist - nearDistance ) / ( farDistance - nearDistance );+ dist = saturate( dist );+ gl_FragColor = packDepthToRGBA( dist );+}`,Bp=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+}`,zp=`uniform sampler2D tEquirect;+varying vec3 vWorldDirection;+#include <common>+void main() {+ vec3 direction = normalize( vWorldDirection );+ vec2 sampleUV = equirectUv( direction );+ gl_FragColor = texture2D( tEquirect, sampleUV );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,kp=`uniform float scale;+attribute float lineDistance;+varying float vLineDistance;+#include <common>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ vLineDistance = scale * lineDistance;+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,Vp=`uniform vec3 diffuse;+uniform float opacity;+uniform float dashSize;+uniform float totalSize;+varying float vLineDistance;+#include <common>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ if ( mod( vLineDistance, totalSize ) > dashSize ) {+ discard;+ }+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,Hp=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <fog_vertex>+}`,Gp=`uniform vec3 diffuse;+uniform float opacity;+#ifndef FLAT_SHADED+ varying vec3 vNormal;+#endif+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ #ifdef USE_LIGHTMAP+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );+ reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;+ #else+ reflectedLight.indirectDiffuse += vec3( 1.0 );+ #endif+ #include <aomap_fragment>+ reflectedLight.indirectDiffuse *= diffuseColor.rgb;+ vec3 outgoingLight = reflectedLight.indirectDiffuse;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Wp=`#define LAMBERT+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,Xp=`#define LAMBERT+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_lambert_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_lambert_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,qp=`#define MATCAP+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <displacementmap_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+ vViewPosition = - mvPosition.xyz;+}`,Yp=`#define MATCAP+uniform vec3 diffuse;+uniform float opacity;+uniform sampler2D matcap;+varying vec3 vViewPosition;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ vec3 viewDir = normalize( vViewPosition );+ vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );+ vec3 y = cross( viewDir, x );+ vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;+ #ifdef USE_MATCAP+ vec4 matcapColor = texture2D( matcap, uv );+ #else+ vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );+ #endif+ vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Zp=`#define NORMAL+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ vViewPosition = - mvPosition.xyz;+#endif+}`,Kp=`#define NORMAL+uniform float opacity;+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <packing>+#include <uv_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );+ #ifdef OPAQUE+ gl_FragColor.a = 1.0;+ #endif+}`,Jp=`#define PHONG+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,$p=`#define PHONG+uniform vec3 diffuse;+uniform vec3 emissive;+uniform vec3 specular;+uniform float shininess;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_phong_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_phong_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,jp=`#define STANDARD+varying vec3 vViewPosition;+#ifdef USE_TRANSMISSION+ varying vec3 vWorldPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+#ifdef USE_TRANSMISSION+ vWorldPosition = worldPosition.xyz;+#endif+}`,Qp=`#define STANDARD+#ifdef PHYSICAL+ #define IOR+ #define USE_SPECULAR+#endif+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float roughness;+uniform float metalness;+uniform float opacity;+#ifdef IOR+ uniform float ior;+#endif+#ifdef USE_SPECULAR+ uniform float specularIntensity;+ uniform vec3 specularColor;+ #ifdef USE_SPECULAR_COLORMAP+ uniform sampler2D specularColorMap;+ #endif+ #ifdef USE_SPECULAR_INTENSITYMAP+ uniform sampler2D specularIntensityMap;+ #endif+#endif+#ifdef USE_CLEARCOAT+ uniform float clearcoat;+ uniform float clearcoatRoughness;+#endif+#ifdef USE_DISPERSION+ uniform float dispersion;+#endif+#ifdef USE_IRIDESCENCE+ uniform float iridescence;+ uniform float iridescenceIOR;+ uniform float iridescenceThicknessMinimum;+ uniform float iridescenceThicknessMaximum;+#endif+#ifdef USE_SHEEN+ uniform vec3 sheenColor;+ uniform float sheenRoughness;+ #ifdef USE_SHEEN_COLORMAP+ uniform sampler2D sheenColorMap;+ #endif+ #ifdef USE_SHEEN_ROUGHNESSMAP+ uniform sampler2D sheenRoughnessMap;+ #endif+#endif+#ifdef USE_ANISOTROPY+ uniform vec2 anisotropyVector;+ #ifdef USE_ANISOTROPYMAP+ uniform sampler2D anisotropyMap;+ #endif+#endif+varying vec3 vViewPosition;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <iridescence_fragment>+#include <cube_uv_reflection_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_physical_pars_fragment>+#include <fog_pars_fragment>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_physical_pars_fragment>+#include <transmission_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <clearcoat_pars_fragment>+#include <iridescence_pars_fragment>+#include <roughnessmap_pars_fragment>+#include <metalnessmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <roughnessmap_fragment>+ #include <metalnessmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <clearcoat_normal_fragment_begin>+ #include <clearcoat_normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_physical_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;+ vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;+ #include <transmission_fragment>+ vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;+ #ifdef USE_SHEEN+ float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );+ outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;+ #endif+ #ifdef USE_CLEARCOAT+ float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );+ vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );+ outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;+ #endif+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,em=`#define TOON+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,tm=`#define TOON+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <gradientmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_toon_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_toon_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,nm=`uniform float size;+uniform float scale;+#include <common>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+#ifdef USE_POINTS_UV+ varying vec2 vUv;+ uniform mat3 uvTransform;+#endif+void main() {+ #ifdef USE_POINTS_UV+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;+ #endif+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ gl_PointSize = size;+ #ifdef USE_SIZEATTENUATION+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );+ if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );+ #endif+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <fog_vertex>+}`,im=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <color_pars_fragment>+#include <map_particle_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_particle_fragment>+ #include <color_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,sm=`#include <common>+#include <batching_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <shadowmap_pars_vertex>+void main() {+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,rm=`uniform vec3 color;+uniform float opacity;+#include <common>+#include <packing>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <logdepthbuf_pars_fragment>+#include <shadowmap_pars_fragment>+#include <shadowmask_pars_fragment>+void main() {+ #include <logdepthbuf_fragment>+ gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+}`,om=`uniform float rotation;+uniform vec2 center;+#include <common>+#include <uv_pars_vertex>+#include <fog_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ vec4 mvPosition = modelViewMatrix[ 3 ];+ vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );+ #ifndef USE_SIZEATTENUATION+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );+ if ( isPerspective ) scale *= - mvPosition.z;+ #endif+ vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;+ vec2 rotatedPosition;+ rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;+ rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;+ mvPosition.xy += rotatedPosition;+ gl_Position = projectionMatrix * mvPosition;+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,am=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+}`,Ue={alphahash_fragment:Rd,alphahash_pars_fragment:Cd,alphamap_fragment:Id,alphamap_pars_fragment:Pd,alphatest_fragment:Ld,alphatest_pars_fragment:Dd,aomap_fragment:Ud,aomap_pars_fragment:Nd,batching_pars_vertex:Fd,batching_vertex:Od,begin_vertex:Bd,beginnormal_vertex:zd,bsdfs:kd,iridescence_fragment:Vd,bumpmap_pars_fragment:Hd,clipping_planes_fragment:Gd,clipping_planes_pars_fragment:Wd,clipping_planes_pars_vertex:Xd,clipping_planes_vertex:qd,color_fragment:Yd,color_pars_fragment:Zd,color_pars_vertex:Kd,color_vertex:Jd,common:$d,cube_uv_reflection_fragment:jd,defaultnormal_vertex:Qd,displacementmap_pars_vertex:ef,displacementmap_vertex:tf,emissivemap_fragment:nf,emissivemap_pars_fragment:sf,colorspace_fragment:rf,colorspace_pars_fragment:of,envmap_fragment:af,envmap_common_pars_fragment:cf,envmap_pars_fragment:lf,envmap_pars_vertex:hf,envmap_physical_pars_fragment:Mf,envmap_vertex:uf,fog_vertex:df,fog_pars_vertex:ff,fog_fragment:pf,fog_pars_fragment:mf,gradientmap_pars_fragment:gf,lightmap_pars_fragment:_f,lights_lambert_fragment:xf,lights_lambert_pars_fragment:yf,lights_pars_begin:vf,lights_toon_fragment:Sf,lights_toon_pars_fragment:bf,lights_phong_fragment:Tf,lights_phong_pars_fragment:Ef,lights_physical_fragment:Af,lights_physical_pars_fragment:wf,lights_fragment_begin:Rf,lights_fragment_maps:Cf,lights_fragment_end:If,logdepthbuf_fragment:Pf,logdepthbuf_pars_fragment:Lf,logdepthbuf_pars_vertex:Df,logdepthbuf_vertex:Uf,map_fragment:Nf,map_pars_fragment:Ff,map_particle_fragment:Of,map_particle_pars_fragment:Bf,metalnessmap_fragment:zf,metalnessmap_pars_fragment:kf,morphinstance_vertex:Vf,morphcolor_vertex:Hf,morphnormal_vertex:Gf,morphtarget_pars_vertex:Wf,morphtarget_vertex:Xf,normal_fragment_begin:qf,normal_fragment_maps:Yf,normal_pars_fragment:Zf,normal_pars_vertex:Kf,normal_vertex:Jf,normalmap_pars_fragment:$f,clearcoat_normal_fragment_begin:jf,clearcoat_normal_fragment_maps:Qf,clearcoat_pars_fragment:ep,iridescence_pars_fragment:tp,opaque_fragment:np,packing:ip,premultiplied_alpha_fragment:sp,project_vertex:rp,dithering_fragment:op,dithering_pars_fragment:ap,roughnessmap_fragment:cp,roughnessmap_pars_fragment:lp,shadowmap_pars_fragment:hp,shadowmap_pars_vertex:up,shadowmap_vertex:dp,shadowmask_pars_fragment:fp,skinbase_vertex:pp,skinning_pars_vertex:mp,skinning_vertex:gp,skinnormal_vertex:_p,specularmap_fragment:xp,specularmap_pars_fragment:yp,tonemapping_fragment:vp,tonemapping_pars_fragment:Mp,transmission_fragment:Sp,transmission_pars_fragment:bp,uv_pars_fragment:Tp,uv_pars_vertex:Ep,uv_vertex:Ap,worldpos_vertex:wp,background_vert:Rp,background_frag:Cp,backgroundCube_vert:Ip,backgroundCube_frag:Pp,cube_vert:Lp,cube_frag:Dp,depth_vert:Up,depth_frag:Np,distanceRGBA_vert:Fp,distanceRGBA_frag:Op,equirect_vert:Bp,equirect_frag:zp,linedashed_vert:kp,linedashed_frag:Vp,meshbasic_vert:Hp,meshbasic_frag:Gp,meshlambert_vert:Wp,meshlambert_frag:Xp,meshmatcap_vert:qp,meshmatcap_frag:Yp,meshnormal_vert:Zp,meshnormal_frag:Kp,meshphong_vert:Jp,meshphong_frag:$p,meshphysical_vert:jp,meshphysical_frag:Qp,meshtoon_vert:em,meshtoon_frag:tm,points_vert:nm,points_frag:im,shadow_vert:sm,shadow_frag:rm,sprite_vert:om,sprite_frag:am},te={common:{diffuse:{value:new be(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Pe},alphaMap:{value:null},alphaMapTransform:{value:new Pe},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Pe}},envmap:{envMap:{value:null},envMapRotation:{value:new Pe},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Pe}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Pe}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Pe},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Pe},normalScale:{value:new ze(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Pe},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Pe}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Pe}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Pe}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new be(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 be(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Pe},alphaTest:{value:0},uvTransform:{value:new Pe}},sprite:{diffuse:{value:new be(16777215)},opacity:{value:1},center:{value:new ze(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Pe},alphaMap:{value:null},alphaMapTransform:{value:new Pe},alphaTest:{value:0}}},Mn={basic:{uniforms:Et([te.common,te.specularmap,te.envmap,te.aomap,te.lightmap,te.fog]),vertexShader:Ue.meshbasic_vert,fragmentShader:Ue.meshbasic_frag},lambert:{uniforms:Et([te.common,te.specularmap,te.envmap,te.aomap,te.lightmap,te.emissivemap,te.bumpmap,te.normalmap,te.displacementmap,te.fog,te.lights,{emissive:{value:new be(0)}}]),vertexShader:Ue.meshlambert_vert,fragmentShader:Ue.meshlambert_frag},phong:{uniforms:Et([te.common,te.specularmap,te.envmap,te.aomap,te.lightmap,te.emissivemap,te.bumpmap,te.normalmap,te.displacementmap,te.fog,te.lights,{emissive:{value:new be(0)},specular:{value:new be(1118481)},shininess:{value:30}}]),vertexShader:Ue.meshphong_vert,fragmentShader:Ue.meshphong_frag},standard:{uniforms:Et([te.common,te.envmap,te.aomap,te.lightmap,te.emissivemap,te.bumpmap,te.normalmap,te.displacementmap,te.roughnessmap,te.metalnessmap,te.fog,te.lights,{emissive:{value:new be(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ue.meshphysical_vert,fragmentShader:Ue.meshphysical_frag},toon:{uniforms:Et([te.common,te.aomap,te.lightmap,te.emissivemap,te.bumpmap,te.normalmap,te.displacementmap,te.gradientmap,te.fog,te.lights,{emissive:{value:new be(0)}}]),vertexShader:Ue.meshtoon_vert,fragmentShader:Ue.meshtoon_frag},matcap:{uniforms:Et([te.common,te.bumpmap,te.normalmap,te.displacementmap,te.fog,{matcap:{value:null}}]),vertexShader:Ue.meshmatcap_vert,fragmentShader:Ue.meshmatcap_frag},points:{uniforms:Et([te.points,te.fog]),vertexShader:Ue.points_vert,fragmentShader:Ue.points_frag},dashed:{uniforms:Et([te.common,te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ue.linedashed_vert,fragmentShader:Ue.linedashed_frag},depth:{uniforms:Et([te.common,te.displacementmap]),vertexShader:Ue.depth_vert,fragmentShader:Ue.depth_frag},normal:{uniforms:Et([te.common,te.bumpmap,te.normalmap,te.displacementmap,{opacity:{value:1}}]),vertexShader:Ue.meshnormal_vert,fragmentShader:Ue.meshnormal_frag},sprite:{uniforms:Et([te.sprite,te.fog]),vertexShader:Ue.sprite_vert,fragmentShader:Ue.sprite_frag},background:{uniforms:{uvTransform:{value:new Pe},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ue.background_vert,fragmentShader:Ue.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Pe}},vertexShader:Ue.backgroundCube_vert,fragmentShader:Ue.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ue.cube_vert,fragmentShader:Ue.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ue.equirect_vert,fragmentShader:Ue.equirect_frag},distanceRGBA:{uniforms:Et([te.common,te.displacementmap,{referencePosition:{value:new P},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ue.distanceRGBA_vert,fragmentShader:Ue.distanceRGBA_frag},shadow:{uniforms:Et([te.lights,te.fog,{color:{value:new be(0)},opacity:{value:1}}]),vertexShader:Ue.shadow_vert,fragmentShader:Ue.shadow_frag}};Mn.physical={uniforms:Et([Mn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Pe},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Pe},clearcoatNormalScale:{value:new ze(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Pe},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Pe},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Pe},sheen:{value:0},sheenColor:{value:new be(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Pe},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Pe},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Pe},transmissionSamplerSize:{value:new ze},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Pe},attenuationDistance:{value:0},attenuationColor:{value:new be(0)},specularColor:{value:new be(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Pe},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Pe},anisotropyVector:{value:new ze},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Pe}}]),vertexShader:Ue.meshphysical_vert,fragmentShader:Ue.meshphysical_frag};var Yo={r:0,b:0,g:0},Si=new on,cm=new Ie;function lm(s,e,t,n,i,r,o){let a=new be(0),c=r===!0?0:1,l,h,u=null,d=0,p=null;function g(T){let M=T.isScene===!0?T.background:null;return M&&M.isTexture&&(M=(T.backgroundBlurriness>0?t:e).get(M)),M}function _(T){let M=!1,L=g(T);L===null?f(a,c):L&&L.isColor&&(f(L,1),M=!0);let R=s.xr.getEnvironmentBlendMode();R==="additive"?n.buffers.color.setClear(0,0,0,1,o):R==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(s.autoClear||M)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil))}function m(T,M){let L=g(M);L&&(L.isCubeTexture||L.mapping===js)?(h===void 0&&(h=new Mt(new qi(1,1,1),new cn({name:"BackgroundCubeMaterial",uniforms:Mi(Mn.backgroundCube.uniforms),vertexShader:Mn.backgroundCube.vertexShader,fragmentShader:Mn.backgroundCube.fragmentShader,side:Pt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(R,w,N){this.matrixWorld.copyPosition(N.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(h)),Si.copy(M.backgroundRotation),Si.x*=-1,Si.y*=-1,Si.z*=-1,L.isCubeTexture&&L.isRenderTargetTexture===!1&&(Si.y*=-1,Si.z*=-1),h.material.uniforms.envMap.value=L,h.material.uniforms.flipEnvMap.value=L.isCubeTexture&&L.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=M.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(cm.makeRotationFromEuler(Si)),h.material.toneMapped=Be.getTransfer(L.colorSpace)!==je,(u!==L||d!==L.version||p!==s.toneMapping)&&(h.material.needsUpdate=!0,u=L,d=L.version,p=s.toneMapping),h.layers.enableAll(),T.unshift(h,h.geometry,h.material,0,0,null)):L&&L.isTexture&&(l===void 0&&(l=new Mt(new Vs(2,2),new cn({name:"BackgroundMaterial",uniforms:Mi(Mn.background.uniforms),vertexShader:Mn.background.vertexShader,fragmentShader:Mn.background.fragmentShader,side:rn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=L,l.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,l.material.toneMapped=Be.getTransfer(L.colorSpace)!==je,L.matrixAutoUpdate===!0&&L.updateMatrix(),l.material.uniforms.uvTransform.value.copy(L.matrix),(u!==L||d!==L.version||p!==s.toneMapping)&&(l.material.needsUpdate=!0,u=L,d=L.version,p=s.toneMapping),l.layers.enableAll(),T.unshift(l,l.geometry,l.material,0,0,null))}function f(T,M){T.getRGB(Yo,ic(s)),n.buffers.color.setClear(Yo.r,Yo.g,Yo.b,M,o)}function E(){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 a},setClearColor:function(T,M=1){a.set(T),c=M,f(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(T){c=T,f(a,c)},render:_,addToRenderList:m,dispose:E}}function hm(s,e){let t=s.getParameter(s.MAX_VERTEX_ATTRIBS),n={},i=d(null),r=i,o=!1;function a(v,C,q,z,W){let J=!1,G=u(z,q,C);r!==G&&(r=G,l(r.object)),J=p(v,z,q,W),J&&g(v,z,q,W),W!==null&&e.update(W,s.ELEMENT_ARRAY_BUFFER),(J||o)&&(o=!1,M(v,C,q,z),W!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,e.get(W).buffer))}function c(){return s.createVertexArray()}function l(v){return s.bindVertexArray(v)}function h(v){return s.deleteVertexArray(v)}function u(v,C,q){let z=q.wireframe===!0,W=n[v.id];W===void 0&&(W={},n[v.id]=W);let J=W[C.id];J===void 0&&(J={},W[C.id]=J);let G=J[z];return G===void 0&&(G=d(c()),J[z]=G),G}function d(v){let C=[],q=[],z=[];for(let W=0;W<t;W++)C[W]=0,q[W]=0,z[W]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:C,enabledAttributes:q,attributeDivisors:z,object:v,attributes:{},index:null}}function p(v,C,q,z){let W=r.attributes,J=C.attributes,G=0,Q=q.getAttributes();for(let V in Q)if(Q[V].location>=0){let he=W[V],_e=J[V];if(_e===void 0&&(V==="instanceMatrix"&&v.instanceMatrix&&(_e=v.instanceMatrix),V==="instanceColor"&&v.instanceColor&&(_e=v.instanceColor)),he===void 0||he.attribute!==_e||_e&&he.data!==_e.data)return!0;G++}return r.attributesNum!==G||r.index!==z}function g(v,C,q,z){let W={},J=C.attributes,G=0,Q=q.getAttributes();for(let V in Q)if(Q[V].location>=0){let he=J[V];he===void 0&&(V==="instanceMatrix"&&v.instanceMatrix&&(he=v.instanceMatrix),V==="instanceColor"&&v.instanceColor&&(he=v.instanceColor));let _e={};_e.attribute=he,he&&he.data&&(_e.data=he.data),W[V]=_e,G++}r.attributes=W,r.attributesNum=G,r.index=z}function _(){let v=r.newAttributes;for(let C=0,q=v.length;C<q;C++)v[C]=0}function m(v){f(v,0)}function f(v,C){let q=r.newAttributes,z=r.enabledAttributes,W=r.attributeDivisors;q[v]=1,z[v]===0&&(s.enableVertexAttribArray(v),z[v]=1),W[v]!==C&&(s.vertexAttribDivisor(v,C),W[v]=C)}function E(){let v=r.newAttributes,C=r.enabledAttributes;for(let q=0,z=C.length;q<z;q++)C[q]!==v[q]&&(s.disableVertexAttribArray(q),C[q]=0)}function T(v,C,q,z,W,J,G){G===!0?s.vertexAttribIPointer(v,C,q,W,J):s.vertexAttribPointer(v,C,q,z,W,J)}function M(v,C,q,z){_();let W=z.attributes,J=q.getAttributes(),G=C.defaultAttributeValues;for(let Q in J){let V=J[Q];if(V.location>=0){let ie=W[Q];if(ie===void 0&&(Q==="instanceMatrix"&&v.instanceMatrix&&(ie=v.instanceMatrix),Q==="instanceColor"&&v.instanceColor&&(ie=v.instanceColor)),ie!==void 0){let he=ie.normalized,_e=ie.itemSize,Ne=e.get(ie);if(Ne===void 0)continue;let et=Ne.buffer,X=Ne.type,ee=Ne.bytesPerElement,pe=X===s.INT||X===s.UNSIGNED_INT||ie.gpuType===fo;if(ie.isInterleavedBufferAttribute){let se=ie.data,Me=se.stride,Ye=ie.offset;if(se.isInstancedInterleavedBuffer){for(let Ae=0;Ae<V.locationSize;Ae++)f(V.location+Ae,se.meshPerAttribute);v.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=se.meshPerAttribute*se.count)}else for(let Ae=0;Ae<V.locationSize;Ae++)m(V.location+Ae);s.bindBuffer(s.ARRAY_BUFFER,et);for(let Ae=0;Ae<V.locationSize;Ae++)T(V.location+Ae,_e/V.locationSize,X,he,Me*ee,(Ye+_e/V.locationSize*Ae)*ee,pe)}else{if(ie.isInstancedBufferAttribute){for(let se=0;se<V.locationSize;se++)f(V.location+se,ie.meshPerAttribute);v.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=ie.meshPerAttribute*ie.count)}else for(let se=0;se<V.locationSize;se++)m(V.location+se);s.bindBuffer(s.ARRAY_BUFFER,et);for(let se=0;se<V.locationSize;se++)T(V.location+se,_e/V.locationSize,X,he,_e*ee,_e/V.locationSize*se*ee,pe)}}else if(G!==void 0){let he=G[Q];if(he!==void 0)switch(he.length){case 2:s.vertexAttrib2fv(V.location,he);break;case 3:s.vertexAttrib3fv(V.location,he);break;case 4:s.vertexAttrib4fv(V.location,he);break;default:s.vertexAttrib1fv(V.location,he)}}}}E()}function L(){N();for(let v in n){let C=n[v];for(let q in C){let z=C[q];for(let W in z)h(z[W].object),delete z[W];delete C[q]}delete n[v]}}function R(v){if(n[v.id]===void 0)return;let C=n[v.id];for(let q in C){let z=C[q];for(let W in z)h(z[W].object),delete z[W];delete C[q]}delete n[v.id]}function w(v){for(let C in n){let q=n[C];if(q[v.id]===void 0)continue;let z=q[v.id];for(let W in z)h(z[W].object),delete z[W];delete q[v.id]}}function N(){S(),o=!0,r!==i&&(r=i,l(r.object))}function S(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:a,reset:N,resetDefaultState:S,dispose:L,releaseStatesOfGeometry:R,releaseStatesOfProgram:w,initAttributes:_,enableAttribute:m,disableUnusedAttributes:E}}function um(s,e,t){let n;function i(l){n=l}function r(l,h){s.drawArrays(n,l,h),t.update(h,n,1)}function o(l,h,u){u!==0&&(s.drawArraysInstanced(n,l,h,u),t.update(h,n,u))}function a(l,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,h,0,u);let p=0;for(let g=0;g<u;g++)p+=h[g];t.update(p,n,1)}function c(l,h,u,d){if(u===0)return;let p=e.get("WEBGL_multi_draw");if(p===null)for(let g=0;g<l.length;g++)o(l[g],h[g],d[g]);else{p.multiDrawArraysInstancedWEBGL(n,l,0,h,0,d,0,u);let g=0;for(let _=0;_<u;_++)g+=h[_]*d[_];t.update(g,n,1)}}this.setMode=i,this.render=r,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function dm(s,e,t,n){let i;function r(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){let w=e.get("EXT_texture_filter_anisotropic");i=s.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(w){return!(w!==Ht&&n.convert(w)!==s.getParameter(s.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(w){let N=w===is&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(w!==hn&&n.convert(w)!==s.getParameter(s.IMPLEMENTATION_COLOR_READ_TYPE)&&w!==Zt&&!N)}function c(w){if(w==="highp"){if(s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.HIGH_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp",h=c(l);h!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);let u=t.logarithmicDepthBuffer===!0,d=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),p=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),g=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=s.getParameter(s.MAX_TEXTURE_SIZE),m=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),f=s.getParameter(s.MAX_VERTEX_ATTRIBS),E=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),T=s.getParameter(s.MAX_VARYING_VECTORS),M=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),L=g>0,R=s.getParameter(s.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reverseDepthBuffer:d,maxTextures:p,maxVertexTextures:g,maxTextureSize:_,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:E,maxVaryings:T,maxFragmentUniforms:M,vertexTextures:L,maxSamples:R}}function fm(s){let e=this,t=null,n=0,i=!1,r=!1,o=new un,a=new Pe,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){let p=u.length!==0||d||n!==0||i;return i=d,n=u.length,p},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,p){let g=u.clippingPlanes,_=u.clipIntersection,m=u.clipShadows,f=s.get(u);if(!i||g===null||g.length===0||r&&!m)r?h(null):l();else{let E=r?0:n,T=E*4,M=f.clippingState||null;c.value=M,M=h(g,d,T,p);for(let L=0;L!==T;++L)M[L]=t[L];f.clippingState=M,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=E}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,d,p,g){let _=u!==null?u.length:0,m=null;if(_!==0){if(m=c.value,g!==!0||m===null){let f=p+_*4,E=d.matrixWorldInverse;a.getNormalMatrix(E),(m===null||m.length<f)&&(m=new Float32Array(f));for(let T=0,M=p;T!==_;++T,M+=4)o.copy(u[T]).applyMatrix4(E,a),o.normal.toArray(m,M),m[M+3]=o.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=_,e.numIntersection=0,m}}function pm(s){let e=new WeakMap;function t(o,a){return a===lo?o.mapping=xi:a===ho&&(o.mapping=yi),o}function n(o){if(o&&o.isTexture){let a=o.mapping;if(a===lo||a===ho)if(e.has(o)){let c=e.get(o).texture;return t(c,o.mapping)}else{let c=o.image;if(c&&c.height>0){let l=new Hr(c.height);return l.fromEquirectangularTexture(s,o),e.set(o,l),o.addEventListener("dispose",i),t(l.texture,o.mapping)}else return null}}return o}function i(o){let a=o.target;a.removeEventListener("dispose",i);let c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}var cs=4,Vh=[.125,.215,.35,.446,.526,.582],Ei=20,ac=new _i,Hh=new be,cc=null,lc=0,hc=0,uc=!1,Ti=(1+Math.sqrt(5))/2,as=1/Ti,Gh=[new P(-Ti,as,0),new P(Ti,as,0),new P(-as,0,Ti),new P(as,0,Ti),new P(0,Ti,-as),new P(0,Ti,as),new P(-1,1,-1),new P(1,1,-1),new P(-1,1,1),new P(1,1,1)],mm=new P,Jo=class{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,i=100,r={}){let{size:o=256,position:a=mm}=r;cc=this._renderer.getRenderTarget(),lc=this._renderer.getActiveCubeFace(),hc=this._renderer.getActiveMipmapLevel(),uc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);let c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,i,c,a),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=qh(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Xh(),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(cc,lc,hc),this._renderer.xr.enabled=uc,e.scissorTest=!1,Zo(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===xi||e.mapping===yi?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),cc=this._renderer.getRenderTarget(),lc=this._renderer.getActiveCubeFace(),hc=this._renderer.getActiveMipmapLevel(),uc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Ct,minFilter:Ct,generateMipmaps:!1,type:is,format:Ht,colorSpace:vt,depthBuffer:!1},i=Wh(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Wh(e,t,n);let{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=gm(r)),this._blurMaterial=_m(r,e,t)}return i}_compileMaterial(e){let t=new Mt(this._lodPlanes[0],e);this._renderer.compile(t,ac)}_sceneToCubeUV(e,t,n,i,r){let c=new dt(90,1,t,n),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,p=u.toneMapping;u.getClearColor(Hh),u.toneMapping=Fn,u.autoClear=!1;let g=new an({name:"PMREM.Background",side:Pt,depthWrite:!1,depthTest:!1}),_=new Mt(new qi,g),m=!1,f=e.background;f?f.isColor&&(g.color.copy(f),e.background=null,m=!0):(g.color.copy(Hh),m=!0);for(let E=0;E<6;E++){let T=E%3;T===0?(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+h[E],r.y,r.z)):T===1?(c.up.set(0,0,l[E]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+h[E],r.z)):(c.up.set(0,l[E],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+h[E]));let M=this._cubeSize;Zo(i,T*M,E>2?M:0,M,M),u.setRenderTarget(i),m&&u.render(_,c),u.render(e,c)}_.geometry.dispose(),_.material.dispose(),u.toneMapping=p,u.autoClear=d,e.background=f}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===xi||e.mapping===yi;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=qh()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Xh());let r=i?this._cubemapMaterial:this._equirectMaterial,o=new Mt(this._lodPlanes[0],r),a=r.uniforms;a.envMap.value=e;let c=this._cubeSize;Zo(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,ac)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodPlanes.length;for(let r=1;r<i;r++){let o=Math.sqrt(this._sigmas[r]*this._sigmas[r]-this._sigmas[r-1]*this._sigmas[r-1]),a=Gh[(i-r-1)%Gh.length];this._blur(e,r-1,r,o,a)}t.autoClear=n}_blur(e,t,n,i,r){let o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,i,"latitudinal",r),this._halfBlur(o,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,o,a){let c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");let h=3,u=new Mt(this._lodPlanes[i],l),d=l.uniforms,p=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*p):2*Math.PI/(2*Ei-1),_=r/g,m=isFinite(r)?1+Math.floor(h*_):Ei;m>Ei&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Ei}`);let f=[],E=0;for(let w=0;w<Ei;++w){let N=w/_,S=Math.exp(-N*N/2);f.push(S),w===0?E+=S:w<m&&(E+=2*S)}for(let w=0;w<f.length;w++)f[w]=f[w]/E;d.envMap.value=e.texture,d.samples.value=m,d.weights.value=f,d.latitudinal.value=o==="latitudinal",a&&(d.poleAxis.value=a);let{_lodMax:T}=this;d.dTheta.value=g,d.mipInt.value=T-n;let M=this._sizeLods[i],L=3*M*(i>T-cs?i-T+cs:0),R=4*(this._cubeSize-M);Zo(t,L,R,3*M,2*M),c.setRenderTarget(t),c.render(u,ac)}};function gm(s){let e=[],t=[],n=[],i=s,r=s-cs+1+Vh.length;for(let o=0;o<r;o++){let a=Math.pow(2,i);t.push(a);let c=1/a;o>s-cs?c=Vh[o-s+cs-1]:o===0&&(c=0),n.push(c);let l=1/(a-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,g=6,_=3,m=2,f=1,E=new Float32Array(_*g*p),T=new Float32Array(m*g*p),M=new Float32Array(f*g*p);for(let R=0;R<p;R++){let w=R%3*2/3-1,N=R>2?0:-1,S=[w,N,0,w+2/3,N,0,w+2/3,N+1,0,w,N,0,w+2/3,N+1,0,w,N+1,0];E.set(S,_*g*R),T.set(d,m*g*R);let v=[R,R,R,R,R,R];M.set(v,f*g*R)}let L=new Vt;L.setAttribute("position",new ft(E,_)),L.setAttribute("uv",new ft(T,m)),L.setAttribute("faceIndex",new ft(M,f)),e.push(L),i>cs&&i--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Wh(s,e,t){let n=new mn(s,e,t);return n.texture.mapping=js,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Zo(s,e,t,n,i){s.viewport.set(e,t,n,i),s.scissor.set(e,t,n,i)}function _m(s,e,t){let n=new Float32Array(Ei),i=new P(0,1,0);return new cn({name:"SphericalGaussianBlur",defines:{n:Ei,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Mc(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;+ uniform int samples;+ uniform float weights[ n ];+ uniform bool latitudinal;+ uniform float dTheta;+ uniform float mipInt;+ uniform vec3 poleAxis;++ #define ENVMAP_TYPE_CUBE_UV+ #include <cube_uv_reflection_fragment>++ vec3 getSample( float theta, vec3 axis ) {++ float cosTheta = cos( theta );+ // Rodrigues' axis-angle rotation+ vec3 sampleDirection = vOutputDirection * cosTheta+ + cross( axis, vOutputDirection ) * sin( theta )+ + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );++ return bilinearCubeUV( envMap, sampleDirection, mipInt );++ }++ void main() {++ vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );++ if ( all( equal( axis, vec3( 0.0 ) ) ) ) {++ axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );++ }++ axis = normalize( axis );++ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );+ gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );++ for ( int i = 1; i < n; i++ ) {++ if ( i >= samples ) {++ break;++ }++ float theta = dTheta * float( i );+ gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );+ gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );++ }++ }+ `,blending:Nn,depthTest:!1,depthWrite:!1})}function Xh(){return new cn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Mc(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;++ #include <common>++ void main() {++ vec3 outputDirection = normalize( vOutputDirection );+ vec2 uv = equirectUv( outputDirection );++ gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );++ }+ `,blending:Nn,depthTest:!1,depthWrite:!1})}function qh(){return new cn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Mc(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ uniform float flipEnvMap;++ varying vec3 vOutputDirection;++ uniform samplerCube envMap;++ void main() {++ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );++ }+ `,blending:Nn,depthTest:!1,depthWrite:!1})}function Mc(){return`++ precision mediump float;+ precision mediump int;++ attribute float faceIndex;++ varying vec3 vOutputDirection;++ // RH coordinate system; PMREM face-indexing convention+ vec3 getDirection( vec2 uv, float face ) {++ uv = 2.0 * uv - 1.0;++ vec3 direction = vec3( uv, 1.0 );++ if ( face == 0.0 ) {++ direction = direction.zyx; // ( 1, v, u ) pos x++ } else if ( face == 1.0 ) {++ direction = direction.xzy;+ direction.xz *= -1.0; // ( -u, 1, -v ) pos y++ } else if ( face == 2.0 ) {++ direction.x *= -1.0; // ( -u, v, 1 ) pos z++ } else if ( face == 3.0 ) {++ direction = direction.zyx;+ direction.xz *= -1.0; // ( -1, v, -u ) neg x++ } else if ( face == 4.0 ) {++ direction = direction.xzy;+ direction.xy *= -1.0; // ( -u, -1, v ) neg y++ } else if ( face == 5.0 ) {++ direction.z *= -1.0; // ( u, v, -1 ) neg z++ }++ return direction;++ }++ void main() {++ vOutputDirection = getDirection( uv, faceIndex );+ gl_Position = vec4( position, 1.0 );++ }+ `}function xm(s){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){let c=a.mapping,l=c===lo||c===ho,h=c===xi||c===yi;if(l||h){let u=e.get(a),d=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==d)return t===null&&(t=new Jo(s)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{let p=a.image;return l&&p&&p.height>0||h&&p&&i(p)?(t===null&&(t=new Jo(s)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function i(a){let c=0,l=6;for(let h=0;h<l;h++)a[h]!==void 0&&c++;return c===l}function r(a){let c=a.target;c.removeEventListener("dispose",r);let l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function ym(s){let e={};function t(n){if(e[n]!==void 0)return e[n];let i;switch(n){case"WEBGL_depth_texture":i=s.getExtension("WEBGL_depth_texture")||s.getExtension("MOZ_WEBGL_depth_texture")||s.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=s.getExtension("EXT_texture_filter_anisotropic")||s.getExtension("MOZ_EXT_texture_filter_anisotropic")||s.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=s.getExtension("WEBGL_compressed_texture_s3tc")||s.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=s.getExtension("WEBGL_compressed_texture_pvrtc")||s.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=s.getExtension(n)}return e[n]=i,i}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){let i=t(n);return i===null&&rr("THREE.WebGLRenderer: "+n+" extension not supported."),i}}}function vm(s,e,t,n){let i={},r=new WeakMap;function o(u){let d=u.target;d.index!==null&&e.remove(d.index);for(let g in d.attributes)e.remove(d.attributes[g]);d.removeEventListener("dispose",o),delete i[d.id];let p=r.get(d);p&&(e.remove(p),r.delete(d)),n.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function a(u,d){return i[d.id]===!0||(d.addEventListener("dispose",o),i[d.id]=!0,t.memory.geometries++),d}function c(u){let d=u.attributes;for(let p in d)e.update(d[p],s.ARRAY_BUFFER)}function l(u){let d=[],p=u.index,g=u.attributes.position,_=0;if(p!==null){let E=p.array;_=p.version;for(let T=0,M=E.length;T<M;T+=3){let L=E[T+0],R=E[T+1],w=E[T+2];d.push(L,R,R,w,w,L)}}else if(g!==void 0){let E=g.array;_=g.version;for(let T=0,M=E.length/3-1;T<M;T+=3){let L=T+0,R=T+1,w=T+2;d.push(L,R,R,w,w,L)}}else return;let m=new(nc(d)?Cs:Rs)(d,1);m.version=_;let f=r.get(u);f&&e.remove(f),r.set(u,m)}function h(u){let d=r.get(u);if(d){let p=u.index;p!==null&&d.version<p.version&&l(u)}else l(u);return r.get(u)}return{get:a,update:c,getWireframeAttribute:h}}function Mm(s,e,t){let n;function i(d){n=d}let r,o;function a(d){r=d.type,o=d.bytesPerElement}function c(d,p){s.drawElements(n,p,r,d*o),t.update(p,n,1)}function l(d,p,g){g!==0&&(s.drawElementsInstanced(n,p,r,d*o,g),t.update(p,n,g))}function h(d,p,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,p,0,r,d,0,g);let m=0;for(let f=0;f<g;f++)m+=p[f];t.update(m,n,1)}function u(d,p,g,_){if(g===0)return;let m=e.get("WEBGL_multi_draw");if(m===null)for(let f=0;f<d.length;f++)l(d[f]/o,p[f],_[f]);else{m.multiDrawElementsInstancedWEBGL(n,p,0,r,d,0,_,0,g);let f=0;for(let E=0;E<g;E++)f+=p[E]*_[E];t.update(f,n,1)}}this.setMode=i,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=h,this.renderMultiDrawInstances=u}function Sm(s){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case s.TRIANGLES:t.triangles+=a*(r/3);break;case s.LINES:t.lines+=a*(r/2);break;case s.LINE_STRIP:t.lines+=a*(r-1);break;case s.LINE_LOOP:t.lines+=a*r;break;case s.POINTS:t.points+=a*r;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",o);break}}function i(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:i,update:n}}function bm(s,e,t){let n=new WeakMap,i=new qe;function r(o,a,c){let l=o.morphTargetInfluences,h=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=h!==void 0?h.length:0,d=n.get(a);if(d===void 0||d.count!==u){let S=function(){w.dispose(),n.delete(a),a.removeEventListener("dispose",S)};d!==void 0&&d.texture.dispose();let p=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,_=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],f=a.morphAttributes.normal||[],E=a.morphAttributes.color||[],T=0;p===!0&&(T=1),g===!0&&(T=2),_===!0&&(T=3);let M=a.attributes.position.count*T,L=1;M>e.maxTextureSize&&(L=Math.ceil(M/e.maxTextureSize),M=e.maxTextureSize);let R=new Float32Array(M*L*4*u),w=new As(R,M,L,u);w.type=Zt,w.needsUpdate=!0;let N=T*4;for(let v=0;v<u;v++){let C=m[v],q=f[v],z=E[v],W=M*L*4*v;for(let J=0;J<C.count;J++){let G=J*N;p===!0&&(i.fromBufferAttribute(C,J),R[W+G+0]=i.x,R[W+G+1]=i.y,R[W+G+2]=i.z,R[W+G+3]=0),g===!0&&(i.fromBufferAttribute(q,J),R[W+G+4]=i.x,R[W+G+5]=i.y,R[W+G+6]=i.z,R[W+G+7]=0),_===!0&&(i.fromBufferAttribute(z,J),R[W+G+8]=i.x,R[W+G+9]=i.y,R[W+G+10]=i.z,R[W+G+11]=z.itemSize===4?i.w:1)}}d={count:u,texture:w,size:new ze(M,L)},n.set(a,d),a.addEventListener("dispose",S)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(s,"morphTexture",o.morphTexture,t);else{let p=0;for(let _=0;_<l.length;_++)p+=l[_];let g=a.morphTargetsRelative?1:1-p;c.getUniforms().setValue(s,"morphTargetBaseInfluence",g),c.getUniforms().setValue(s,"morphTargetInfluences",l)}c.getUniforms().setValue(s,"morphTargetsTexture",d.texture,t),c.getUniforms().setValue(s,"morphTargetsTextureSize",d.size)}return{update:r}}function Tm(s,e,t,n){let i=new WeakMap;function r(c){let l=n.render.frame,h=c.geometry,u=e.get(c,h);if(i.get(u)!==l&&(e.update(u),i.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),i.get(c)!==l&&(t.update(c.instanceMatrix,s.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,s.ARRAY_BUFFER),i.set(c,l))),c.isSkinnedMesh){let d=c.skeleton;i.get(d)!==l&&(d.update(),i.set(d,l))}return u}function o(){i=new WeakMap}function a(c){let l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:o}}var uu=new _t,Yh=new ks(1,1),du=new As,fu=new kr,pu=new Ps,Zh=[],Kh=[],Jh=new Float32Array(16),$h=new Float32Array(9),jh=new Float32Array(4);function hs(s,e,t){let n=s[0];if(n<=0||n>0)return s;let i=e*t,r=Zh[i];if(r===void 0&&(r=new Float32Array(i),Zh[i]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,s[o].toArray(r,a)}return r}function pt(s,e){if(s.length!==e.length)return!1;for(let t=0,n=s.length;t<n;t++)if(s[t]!==e[t])return!1;return!0}function mt(s,e){for(let t=0,n=e.length;t<n;t++)s[t]=e[t]}function jo(s,e){let t=Kh[e];t===void 0&&(t=new Int32Array(e),Kh[e]=t);for(let n=0;n!==e;++n)t[n]=s.allocateTextureUnit();return t}function Em(s,e){let t=this.cache;t[0]!==e&&(s.uniform1f(this.addr,e),t[0]=e)}function Am(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(pt(t,e))return;s.uniform2fv(this.addr,e),mt(t,e)}}function wm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.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)&&(s.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(pt(t,e))return;s.uniform3fv(this.addr,e),mt(t,e)}}function Rm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.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(pt(t,e))return;s.uniform4fv(this.addr,e),mt(t,e)}}function Cm(s,e){let t=this.cache,n=e.elements;if(n===void 0){if(pt(t,e))return;s.uniformMatrix2fv(this.addr,!1,e),mt(t,e)}else{if(pt(t,n))return;jh.set(n),s.uniformMatrix2fv(this.addr,!1,jh),mt(t,n)}}function Im(s,e){let t=this.cache,n=e.elements;if(n===void 0){if(pt(t,e))return;s.uniformMatrix3fv(this.addr,!1,e),mt(t,e)}else{if(pt(t,n))return;$h.set(n),s.uniformMatrix3fv(this.addr,!1,$h),mt(t,n)}}function Pm(s,e){let t=this.cache,n=e.elements;if(n===void 0){if(pt(t,e))return;s.uniformMatrix4fv(this.addr,!1,e),mt(t,e)}else{if(pt(t,n))return;Jh.set(n),s.uniformMatrix4fv(this.addr,!1,Jh),mt(t,n)}}function Lm(s,e){let t=this.cache;t[0]!==e&&(s.uniform1i(this.addr,e),t[0]=e)}function Dm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(pt(t,e))return;s.uniform2iv(this.addr,e),mt(t,e)}}function Um(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(pt(t,e))return;s.uniform3iv(this.addr,e),mt(t,e)}}function Nm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.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(pt(t,e))return;s.uniform4iv(this.addr,e),mt(t,e)}}function Fm(s,e){let t=this.cache;t[0]!==e&&(s.uniform1ui(this.addr,e),t[0]=e)}function Om(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(s.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(pt(t,e))return;s.uniform2uiv(this.addr,e),mt(t,e)}}function Bm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(s.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(pt(t,e))return;s.uniform3uiv(this.addr,e),mt(t,e)}}function zm(s,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(s.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(pt(t,e))return;s.uniform4uiv(this.addr,e),mt(t,e)}}function km(s,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(s.uniform1i(this.addr,i),n[0]=i);let r;this.type===s.SAMPLER_2D_SHADOW?(Yh.compareFunction=ja,r=Yh):r=uu,t.setTexture2D(e||r,i)}function Vm(s,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(s.uniform1i(this.addr,i),n[0]=i),t.setTexture3D(e||fu,i)}function Hm(s,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(s.uniform1i(this.addr,i),n[0]=i),t.setTextureCube(e||pu,i)}function Gm(s,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(s.uniform1i(this.addr,i),n[0]=i),t.setTexture2DArray(e||du,i)}function Wm(s){switch(s){case 5126:return Em;case 35664:return Am;case 35665:return wm;case 35666:return Rm;case 35674:return Cm;case 35675:return Im;case 35676:return Pm;case 5124:case 35670:return Lm;case 35667:case 35671:return Dm;case 35668:case 35672:return Um;case 35669:case 35673:return Nm;case 5125:return Fm;case 36294:return Om;case 36295:return Bm;case 36296:return zm;case 35678:case 36198:case 36298:case 36306:case 35682:return km;case 35679:case 36299:case 36307:return Vm;case 35680:case 36300:case 36308:case 36293:return Hm;case 36289:case 36303:case 36311:case 36292:return Gm}}function Xm(s,e){s.uniform1fv(this.addr,e)}function qm(s,e){let t=hs(e,this.size,2);s.uniform2fv(this.addr,t)}function Ym(s,e){let t=hs(e,this.size,3);s.uniform3fv(this.addr,t)}function Zm(s,e){let t=hs(e,this.size,4);s.uniform4fv(this.addr,t)}function Km(s,e){let t=hs(e,this.size,4);s.uniformMatrix2fv(this.addr,!1,t)}function Jm(s,e){let t=hs(e,this.size,9);s.uniformMatrix3fv(this.addr,!1,t)}function $m(s,e){let t=hs(e,this.size,16);s.uniformMatrix4fv(this.addr,!1,t)}function jm(s,e){s.uniform1iv(this.addr,e)}function Qm(s,e){s.uniform2iv(this.addr,e)}function eg(s,e){s.uniform3iv(this.addr,e)}function tg(s,e){s.uniform4iv(this.addr,e)}function ng(s,e){s.uniform1uiv(this.addr,e)}function ig(s,e){s.uniform2uiv(this.addr,e)}function sg(s,e){s.uniform3uiv(this.addr,e)}function rg(s,e){s.uniform4uiv(this.addr,e)}function og(s,e,t){let n=this.cache,i=e.length,r=jo(t,i);pt(n,r)||(s.uniform1iv(this.addr,r),mt(n,r));for(let o=0;o!==i;++o)t.setTexture2D(e[o]||uu,r[o])}function ag(s,e,t){let n=this.cache,i=e.length,r=jo(t,i);pt(n,r)||(s.uniform1iv(this.addr,r),mt(n,r));for(let o=0;o!==i;++o)t.setTexture3D(e[o]||fu,r[o])}function cg(s,e,t){let n=this.cache,i=e.length,r=jo(t,i);pt(n,r)||(s.uniform1iv(this.addr,r),mt(n,r));for(let o=0;o!==i;++o)t.setTextureCube(e[o]||pu,r[o])}function lg(s,e,t){let n=this.cache,i=e.length,r=jo(t,i);pt(n,r)||(s.uniform1iv(this.addr,r),mt(n,r));for(let o=0;o!==i;++o)t.setTexture2DArray(e[o]||du,r[o])}function hg(s){switch(s){case 5126:return Xm;case 35664:return qm;case 35665:return Ym;case 35666:return Zm;case 35674:return Km;case 35675:return Jm;case 35676:return $m;case 5124:case 35670:return jm;case 35667:case 35671:return Qm;case 35668:case 35672:return eg;case 35669:case 35673:return tg;case 5125:return ng;case 36294:return ig;case 36295:return sg;case 36296:return rg;case 35678:case 36198:case 36298:case 36306:case 35682:return og;case 35679:case 36299:case 36307:return ag;case 35680:case 36300:case 36308:case 36293:return cg;case 36289:case 36303:case 36311:case 36292:return lg}}var fc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Wm(t.type)}},pc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=hg(t.type)}},mc=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let i=this.seq;for(let r=0,o=i.length;r!==o;++r){let a=i[r];a.setValue(e,t[a.id],n)}}},dc=/(\w+)(\])?(\[|\.)?/g;function Qh(s,e){s.seq.push(e),s.map[e.id]=e}function ug(s,e,t){let n=s.name,i=n.length;for(dc.lastIndex=0;;){let r=dc.exec(n),o=dc.lastIndex,a=r[1],c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===i){Qh(t,l===void 0?new fc(a,s,e):new pc(a,s,e));break}else{let u=t.map[a];u===void 0&&(u=new mc(a),Qh(t,u)),t=u}}}var ls=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){let r=e.getActiveUniform(t,i),o=e.getUniformLocation(t,r.name);ug(r,o,this)}}setValue(e,t,n,i){let r=this.map[t];r!==void 0&&r.setValue(e,n,i)}setOptional(e,t,n){let i=t[n];i!==void 0&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,o=t.length;r!==o;++r){let a=t[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,i)}}static seqWithValue(e,t){let n=[];for(let i=0,r=e.length;i!==r;++i){let o=e[i];o.id in t&&n.push(o)}return n}};function eu(s,e,t){let n=s.createShader(e);return s.shaderSource(n,t),s.compileShader(n),n}var dg=37297,fg=0;function pg(s,e){let t=s.split(`+`),n=[],i=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let o=i;o<r;o++){let a=o+1;n.push(`${a===e?">":" "} ${a}: ${t[o]}`)}return n.join(`+`)}var tu=new Pe;function mg(s){Be._getMatrix(tu,Be.workingColorSpace,s);let e=`mat3( ${tu.elements.map(t=>t.toFixed(4))} )`;switch(Be.getTransfer(s)){case Ts:return[e,"LinearTransferOETF"];case je:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",s),[e,"LinearTransferOETF"]}}function nu(s,e,t){let n=s.getShaderParameter(e,s.COMPILE_STATUS),i=s.getShaderInfoLog(e).trim();if(n&&i==="")return"";let r=/ERROR: 0:(\d+)/.exec(i);if(r){let o=parseInt(r[1]);return t.toUpperCase()+`++`+i+`++`+pg(s.getShaderSource(e),o)}else return i}function gg(s,e){let t=mg(e);return[`vec4 ${s}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`+`)}function _g(s,e){let t;switch(e){case dh:t="Linear";break;case fh:t="Reinhard";break;case ph:t="Cineon";break;case co:t="ACESFilmic";break;case gh:t="AgX";break;case _h:t="Neutral";break;case mh:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+s+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}var Ko=new P;function xg(){Be.getLuminanceCoefficients(Ko);let s=Ko.x.toFixed(4),e=Ko.y.toFixed(4),t=Ko.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${s}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`+`)}function yg(s){return[s.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",s.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(or).join(`+`)}function vg(s){let e=[];for(let t in s){let n=s[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`+`)}function Mg(s,e){let t={},n=s.getProgramParameter(e,s.ACTIVE_ATTRIBUTES);for(let i=0;i<n;i++){let r=s.getActiveAttrib(e,i),o=r.name,a=1;r.type===s.FLOAT_MAT2&&(a=2),r.type===s.FLOAT_MAT3&&(a=3),r.type===s.FLOAT_MAT4&&(a=4),t[o]={type:r.type,location:s.getAttribLocation(e,o),locationSize:a}}return t}function or(s){return s!==""}function iu(s,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return s.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 su(s,e){return s.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}var Sg=/^[ \t]*#include +<([\w\d./]+)>/gm;function gc(s){return s.replace(Sg,Tg)}var bg=new Map;function Tg(s,e){let t=Ue[e];if(t===void 0){let n=bg.get(e);if(n!==void 0)t=Ue[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 gc(t)}var Eg=/#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 ru(s){return s.replace(Eg,Ag)}function Ag(s,e,t,n){let i="";for(let r=parseInt(e);r<parseInt(t);r++)i+=n.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return i}function ou(s){let e=`precision ${s.precision} float;+ precision ${s.precision} int;+ precision ${s.precision} sampler2D;+ precision ${s.precision} samplerCube;+ precision ${s.precision} sampler3D;+ precision ${s.precision} sampler2DArray;+ precision ${s.precision} sampler2DShadow;+ precision ${s.precision} samplerCubeShadow;+ precision ${s.precision} sampler2DArrayShadow;+ precision ${s.precision} isampler2D;+ precision ${s.precision} isampler3D;+ precision ${s.precision} isamplerCube;+ precision ${s.precision} isampler2DArray;+ precision ${s.precision} usampler2D;+ precision ${s.precision} usampler3D;+ precision ${s.precision} usamplerCube;+ precision ${s.precision} usampler2DArray;+ `;return s.precision==="highp"?e+=`+#define HIGH_PRECISION`:s.precision==="mediump"?e+=`+#define MEDIUM_PRECISION`:s.precision==="lowp"&&(e+=`+#define LOW_PRECISION`),e}function wg(s){let e="SHADOWMAP_TYPE_BASIC";return s.shadowMapType===Oa?e="SHADOWMAP_TYPE_PCF":s.shadowMapType===Xl?e="SHADOWMAP_TYPE_PCF_SOFT":s.shadowMapType===vn&&(e="SHADOWMAP_TYPE_VSM"),e}function Rg(s){let e="ENVMAP_TYPE_CUBE";if(s.envMap)switch(s.envMapMode){case xi:case yi:e="ENVMAP_TYPE_CUBE";break;case js:e="ENVMAP_TYPE_CUBE_UV";break}return e}function Cg(s){let e="ENVMAP_MODE_REFLECTION";return s.envMap&&s.envMapMode===yi&&(e="ENVMAP_MODE_REFRACTION"),e}function Ig(s){let e="ENVMAP_BLENDING_NONE";if(s.envMap)switch(s.combine){case Va:e="ENVMAP_BLENDING_MULTIPLY";break;case hh:e="ENVMAP_BLENDING_MIX";break;case uh:e="ENVMAP_BLENDING_ADD";break}return e}function Pg(s){let e=s.envMapCubeUVHeight;if(e===null)return null;let t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function Lg(s,e,t,n){let i=s.getContext(),r=t.defines,o=t.vertexShader,a=t.fragmentShader,c=wg(t),l=Rg(t),h=Cg(t),u=Ig(t),d=Pg(t),p=yg(t),g=vg(r),_=i.createProgram(),m,f,E=t.glslVersion?"#version "+t.glslVersion+`+`:"";t.isRawShaderMaterial?(m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(or).join(`+`),m.length>0&&(m+=`+`),f=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(or).join(`+`),f.length>0&&(f+=`+`)):(m=[ou(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,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(or).join(`+`),f=[ou(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,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!==Fn?"#define TONE_MAPPING":"",t.toneMapping!==Fn?Ue.tonemapping_pars_fragment:"",t.toneMapping!==Fn?_g("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ue.colorspace_pars_fragment,gg("linearToOutputTexel",t.outputColorSpace),xg(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`+`].filter(or).join(`+`)),o=gc(o),o=iu(o,t),o=su(o,t),a=gc(a),a=iu(a,t),a=su(a,t),o=ru(o),a=ru(a),t.isRawShaderMaterial!==!0&&(E=`#version 300 es+`,m=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`+`)+`+`+m,f=["#define varying in",t.glslVersion===Qa?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Qa?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`+`)+`+`+f);let T=E+m+o,M=E+f+a,L=eu(i,i.VERTEX_SHADER,T),R=eu(i,i.FRAGMENT_SHADER,M);i.attachShader(_,L),i.attachShader(_,R),t.index0AttributeName!==void 0?i.bindAttribLocation(_,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(_,0,"position"),i.linkProgram(_);function w(C){if(s.debug.checkShaderErrors){let q=i.getProgramInfoLog(_).trim(),z=i.getShaderInfoLog(L).trim(),W=i.getShaderInfoLog(R).trim(),J=!0,G=!0;if(i.getProgramParameter(_,i.LINK_STATUS)===!1)if(J=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(i,_,L,R);else{let Q=nu(i,L,"vertex"),V=nu(i,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+`++Material Name: `+C.name+`+Material Type: `+C.type+`++Program Info Log: `+q+`+`+Q+`+`+V)}else q!==""?console.warn("THREE.WebGLProgram: Program Info Log:",q):(z===""||W==="")&&(G=!1);G&&(C.diagnostics={runnable:J,programLog:q,vertexShader:{log:z,prefix:m},fragmentShader:{log:W,prefix:f}})}i.deleteShader(L),i.deleteShader(R),N=new ls(i,_),S=Mg(i,_)}let N;this.getUniforms=function(){return N===void 0&&w(this),N};let S;this.getAttributes=function(){return S===void 0&&w(this),S};let v=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return v===!1&&(v=i.getProgramParameter(_,dg)),v},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(_),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=fg++,this.cacheKey=e,this.usedTimes=1,this.program=_,this.vertexShader=L,this.fragmentShader=R,this}var Dg=0,_c=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let 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){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new xc(e),t.set(e,n)),n}},xc=class{constructor(e){this.id=Dg++,this.code=e,this.usedTimes=0}};function Ug(s,e,t,n,i,r,o){let a=new ws,c=new _c,l=new Set,h=[],u=i.logarithmicDepthBuffer,d=i.vertexTextures,p=i.precision,g={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 _(S){return l.add(S),S===0?"uv":`uv${S}`}function m(S,v,C,q,z){let W=q.fog,J=z.geometry,G=S.isMeshStandardMaterial?q.environment:null,Q=(S.isMeshStandardMaterial?t:e).get(S.envMap||G),V=Q&&Q.mapping===js?Q.image.height:null,ie=g[S.type];S.precision!==null&&(p=i.getMaxPrecision(S.precision),p!==S.precision&&console.warn("THREE.WebGLProgram.getParameters:",S.precision,"not supported, using",p,"instead."));let he=J.morphAttributes.position||J.morphAttributes.normal||J.morphAttributes.color,_e=he!==void 0?he.length:0,Ne=0;J.morphAttributes.position!==void 0&&(Ne=1),J.morphAttributes.normal!==void 0&&(Ne=2),J.morphAttributes.color!==void 0&&(Ne=3);let et,X,ee,pe;if(ie){let Je=Mn[ie];et=Je.vertexShader,X=Je.fragmentShader}else et=S.vertexShader,X=S.fragmentShader,c.update(S),ee=c.getVertexShaderID(S),pe=c.getFragmentShaderID(S);let se=s.getRenderTarget(),Me=s.state.buffers.depth.getReversed(),Ye=z.isInstancedMesh===!0,Ae=z.isBatchedMesh===!0,ct=!!S.map,st=!!S.matcap,ke=!!Q,A=!!S.aoMap,Gt=!!S.lightMap,Ge=!!S.bumpMap,Ve=!!S.normalMap,xe=!!S.displacementMap,nt=!!S.emissiveMap,ge=!!S.metalnessMap,b=!!S.roughnessMap,x=S.anisotropy>0,F=S.clearcoat>0,Y=S.dispersion>0,K=S.iridescence>0,H=S.sheen>0,me=S.transmission>0,re=x&&!!S.anisotropyMap,Se=F&&!!S.clearcoatMap,Te=F&&!!S.clearcoatNormalMap,$=F&&!!S.clearcoatRoughnessMap,ue=K&&!!S.iridescenceMap,Ee=K&&!!S.iridescenceThicknessMap,Re=H&&!!S.sheenColorMap,de=H&&!!S.sheenRoughnessMap,He=!!S.specularMap,De=!!S.specularColorMap,tt=!!S.specularIntensityMap,I=me&&!!S.transmissionMap,oe=me&&!!S.thicknessMap,k=!!S.gradientMap,Z=!!S.alphaMap,ce=S.alphaTest>0,ae=!!S.alphaHash,Le=!!S.extensions,ot=Fn;S.toneMapped&&(se===null||se.isXRRenderTarget===!0)&&(ot=s.toneMapping);let St={shaderID:ie,shaderType:S.type,shaderName:S.name,vertexShader:et,fragmentShader:X,defines:S.defines,customVertexShaderID:ee,customFragmentShaderID:pe,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:p,batching:Ae,batchingColor:Ae&&z._colorsTexture!==null,instancing:Ye,instancingColor:Ye&&z.instanceColor!==null,instancingMorph:Ye&&z.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:se===null?s.outputColorSpace:se.isXRRenderTarget===!0?se.texture.colorSpace:vt,alphaToCoverage:!!S.alphaToCoverage,map:ct,matcap:st,envMap:ke,envMapMode:ke&&Q.mapping,envMapCubeUVHeight:V,aoMap:A,lightMap:Gt,bumpMap:Ge,normalMap:Ve,displacementMap:d&&xe,emissiveMap:nt,normalMapObjectSpace:Ve&&S.normalMapType===Eh,normalMapTangentSpace:Ve&&S.normalMapType===$a,metalnessMap:ge,roughnessMap:b,anisotropy:x,anisotropyMap:re,clearcoat:F,clearcoatMap:Se,clearcoatNormalMap:Te,clearcoatRoughnessMap:$,dispersion:Y,iridescence:K,iridescenceMap:ue,iridescenceThicknessMap:Ee,sheen:H,sheenColorMap:Re,sheenRoughnessMap:de,specularMap:He,specularColorMap:De,specularIntensityMap:tt,transmission:me,transmissionMap:I,thicknessMap:oe,gradientMap:k,opaque:S.transparent===!1&&S.blending===ai&&S.alphaToCoverage===!1,alphaMap:Z,alphaTest:ce,alphaHash:ae,combine:S.combine,mapUv:ct&&_(S.map.channel),aoMapUv:A&&_(S.aoMap.channel),lightMapUv:Gt&&_(S.lightMap.channel),bumpMapUv:Ge&&_(S.bumpMap.channel),normalMapUv:Ve&&_(S.normalMap.channel),displacementMapUv:xe&&_(S.displacementMap.channel),emissiveMapUv:nt&&_(S.emissiveMap.channel),metalnessMapUv:ge&&_(S.metalnessMap.channel),roughnessMapUv:b&&_(S.roughnessMap.channel),anisotropyMapUv:re&&_(S.anisotropyMap.channel),clearcoatMapUv:Se&&_(S.clearcoatMap.channel),clearcoatNormalMapUv:Te&&_(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:$&&_(S.clearcoatRoughnessMap.channel),iridescenceMapUv:ue&&_(S.iridescenceMap.channel),iridescenceThicknessMapUv:Ee&&_(S.iridescenceThicknessMap.channel),sheenColorMapUv:Re&&_(S.sheenColorMap.channel),sheenRoughnessMapUv:de&&_(S.sheenRoughnessMap.channel),specularMapUv:He&&_(S.specularMap.channel),specularColorMapUv:De&&_(S.specularColorMap.channel),specularIntensityMapUv:tt&&_(S.specularIntensityMap.channel),transmissionMapUv:I&&_(S.transmissionMap.channel),thicknessMapUv:oe&&_(S.thicknessMap.channel),alphaMapUv:Z&&_(S.alphaMap.channel),vertexTangents:!!J.attributes.tangent&&(Ve||x),vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!J.attributes.color&&J.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!J.attributes.uv&&(ct||Z),fog:!!W,useFog:S.fog===!0,fogExp2:!!W&&W.isFogExp2,flatShading:S.flatShading===!0,sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:u,reverseDepthBuffer:Me,skinning:z.isSkinnedMesh===!0,morphTargets:J.morphAttributes.position!==void 0,morphNormals:J.morphAttributes.normal!==void 0,morphColors:J.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Ne,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:o.numPlanes,numClipIntersection:o.numIntersection,dithering:S.dithering,shadowMapEnabled:s.shadowMap.enabled&&C.length>0,shadowMapType:s.shadowMap.type,toneMapping:ot,decodeVideoTexture:ct&&S.map.isVideoTexture===!0&&Be.getTransfer(S.map.colorSpace)===je,decodeVideoTextureEmissive:nt&&S.emissiveMap.isVideoTexture===!0&&Be.getTransfer(S.emissiveMap.colorSpace)===je,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===Yt,flipSided:S.side===Pt,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:Le&&S.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Le&&S.extensions.multiDraw===!0||Ae)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function f(S){let v=[];if(S.shaderID?v.push(S.shaderID):(v.push(S.customVertexShaderID),v.push(S.customFragmentShaderID)),S.defines!==void 0)for(let C in S.defines)v.push(C),v.push(S.defines[C]);return S.isRawShaderMaterial===!1&&(E(v,S),T(v,S),v.push(s.outputColorSpace)),v.push(S.customProgramCacheKey),v.join()}function E(S,v){S.push(v.precision),S.push(v.outputColorSpace),S.push(v.envMapMode),S.push(v.envMapCubeUVHeight),S.push(v.mapUv),S.push(v.alphaMapUv),S.push(v.lightMapUv),S.push(v.aoMapUv),S.push(v.bumpMapUv),S.push(v.normalMapUv),S.push(v.displacementMapUv),S.push(v.emissiveMapUv),S.push(v.metalnessMapUv),S.push(v.roughnessMapUv),S.push(v.anisotropyMapUv),S.push(v.clearcoatMapUv),S.push(v.clearcoatNormalMapUv),S.push(v.clearcoatRoughnessMapUv),S.push(v.iridescenceMapUv),S.push(v.iridescenceThicknessMapUv),S.push(v.sheenColorMapUv),S.push(v.sheenRoughnessMapUv),S.push(v.specularMapUv),S.push(v.specularColorMapUv),S.push(v.specularIntensityMapUv),S.push(v.transmissionMapUv),S.push(v.thicknessMapUv),S.push(v.combine),S.push(v.fogExp2),S.push(v.sizeAttenuation),S.push(v.morphTargetsCount),S.push(v.morphAttributeCount),S.push(v.numDirLights),S.push(v.numPointLights),S.push(v.numSpotLights),S.push(v.numSpotLightMaps),S.push(v.numHemiLights),S.push(v.numRectAreaLights),S.push(v.numDirLightShadows),S.push(v.numPointLightShadows),S.push(v.numSpotLightShadows),S.push(v.numSpotLightShadowsWithMaps),S.push(v.numLightProbes),S.push(v.shadowMapType),S.push(v.toneMapping),S.push(v.numClippingPlanes),S.push(v.numClipIntersection),S.push(v.depthPacking)}function T(S,v){a.disableAll(),v.supportsVertexTextures&&a.enable(0),v.instancing&&a.enable(1),v.instancingColor&&a.enable(2),v.instancingMorph&&a.enable(3),v.matcap&&a.enable(4),v.envMap&&a.enable(5),v.normalMapObjectSpace&&a.enable(6),v.normalMapTangentSpace&&a.enable(7),v.clearcoat&&a.enable(8),v.iridescence&&a.enable(9),v.alphaTest&&a.enable(10),v.vertexColors&&a.enable(11),v.vertexAlphas&&a.enable(12),v.vertexUv1s&&a.enable(13),v.vertexUv2s&&a.enable(14),v.vertexUv3s&&a.enable(15),v.vertexTangents&&a.enable(16),v.anisotropy&&a.enable(17),v.alphaHash&&a.enable(18),v.batching&&a.enable(19),v.dispersion&&a.enable(20),v.batchingColor&&a.enable(21),S.push(a.mask),a.disableAll(),v.fog&&a.enable(0),v.useFog&&a.enable(1),v.flatShading&&a.enable(2),v.logarithmicDepthBuffer&&a.enable(3),v.reverseDepthBuffer&&a.enable(4),v.skinning&&a.enable(5),v.morphTargets&&a.enable(6),v.morphNormals&&a.enable(7),v.morphColors&&a.enable(8),v.premultipliedAlpha&&a.enable(9),v.shadowMapEnabled&&a.enable(10),v.doubleSided&&a.enable(11),v.flipSided&&a.enable(12),v.useDepthPacking&&a.enable(13),v.dithering&&a.enable(14),v.transmission&&a.enable(15),v.sheen&&a.enable(16),v.opaque&&a.enable(17),v.pointsUvs&&a.enable(18),v.decodeVideoTexture&&a.enable(19),v.decodeVideoTextureEmissive&&a.enable(20),v.alphaToCoverage&&a.enable(21),S.push(a.mask)}function M(S){let v=g[S.type],C;if(v){let q=Mn[v];C=Bh.clone(q.uniforms)}else C=S.uniforms;return C}function L(S,v){let C;for(let q=0,z=h.length;q<z;q++){let W=h[q];if(W.cacheKey===v){C=W,++C.usedTimes;break}}return C===void 0&&(C=new Lg(s,v,S,r),h.push(C)),C}function R(S){if(--S.usedTimes===0){let v=h.indexOf(S);h[v]=h[h.length-1],h.pop(),S.destroy()}}function w(S){c.remove(S)}function N(){c.dispose()}return{getParameters:m,getProgramCacheKey:f,getUniforms:M,acquireProgram:L,releaseProgram:R,releaseShaderCache:w,programs:h,dispose:N}}function Ng(){let s=new WeakMap;function e(o){return s.has(o)}function t(o){let a=s.get(o);return a===void 0&&(a={},s.set(o,a)),a}function n(o){s.delete(o)}function i(o,a,c){s.get(o)[a]=c}function r(){s=new WeakMap}return{has:e,get:t,remove:n,update:i,dispose:r}}function Fg(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.material.id!==e.material.id?s.material.id-e.material.id:s.z!==e.z?s.z-e.z:s.id-e.id}function au(s,e){return s.groupOrder!==e.groupOrder?s.groupOrder-e.groupOrder:s.renderOrder!==e.renderOrder?s.renderOrder-e.renderOrder:s.z!==e.z?e.z-s.z:s.id-e.id}function cu(){let s=[],e=0,t=[],n=[],i=[];function r(){e=0,t.length=0,n.length=0,i.length=0}function o(u,d,p,g,_,m){let f=s[e];return f===void 0?(f={id:u.id,object:u,geometry:d,material:p,groupOrder:g,renderOrder:u.renderOrder,z:_,group:m},s[e]=f):(f.id=u.id,f.object=u,f.geometry=d,f.material=p,f.groupOrder=g,f.renderOrder=u.renderOrder,f.z=_,f.group=m),e++,f}function a(u,d,p,g,_,m){let f=o(u,d,p,g,_,m);p.transmission>0?n.push(f):p.transparent===!0?i.push(f):t.push(f)}function c(u,d,p,g,_,m){let f=o(u,d,p,g,_,m);p.transmission>0?n.unshift(f):p.transparent===!0?i.unshift(f):t.unshift(f)}function l(u,d){t.length>1&&t.sort(u||Fg),n.length>1&&n.sort(d||au),i.length>1&&i.sort(d||au)}function h(){for(let u=e,d=s.length;u<d;u++){let p=s[u];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:t,transmissive:n,transparent:i,init:r,push:a,unshift:c,finish:h,sort:l}}function Og(){let s=new WeakMap;function e(n,i){let r=s.get(n),o;return r===void 0?(o=new cu,s.set(n,[o])):i>=r.length?(o=new cu,r.push(o)):o=r[i],o}function t(){s=new WeakMap}return{get:e,dispose:t}}function Bg(){let s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new P,color:new be};break;case"SpotLight":t={position:new P,direction:new P,color:new be,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new P,color:new be,distance:0,decay:0};break;case"HemisphereLight":t={direction:new P,skyColor:new be,groundColor:new be};break;case"RectAreaLight":t={color:new be,position:new P,halfWidth:new P,halfHeight:new P};break}return s[e.id]=t,t}}}function zg(){let s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ze};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ze};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ze,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}var kg=0;function Vg(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function Hg(s){let e=new Bg,t=zg(),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 P);let i=new P,r=new Ie,o=new Ie;function a(l){let h=0,u=0,d=0;for(let S=0;S<9;S++)n.probe[S].set(0,0,0);let p=0,g=0,_=0,m=0,f=0,E=0,T=0,M=0,L=0,R=0,w=0;l.sort(Vg);for(let S=0,v=l.length;S<v;S++){let C=l[S],q=C.color,z=C.intensity,W=C.distance,J=C.shadow&&C.shadow.map?C.shadow.map.texture:null;if(C.isAmbientLight)h+=q.r*z,u+=q.g*z,d+=q.b*z;else if(C.isLightProbe){for(let G=0;G<9;G++)n.probe[G].addScaledVector(C.sh.coefficients[G],z);w++}else if(C.isDirectionalLight){let G=e.get(C);if(G.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let Q=C.shadow,V=t.get(C);V.shadowIntensity=Q.intensity,V.shadowBias=Q.bias,V.shadowNormalBias=Q.normalBias,V.shadowRadius=Q.radius,V.shadowMapSize=Q.mapSize,n.directionalShadow[p]=V,n.directionalShadowMap[p]=J,n.directionalShadowMatrix[p]=C.shadow.matrix,E++}n.directional[p]=G,p++}else if(C.isSpotLight){let G=e.get(C);G.position.setFromMatrixPosition(C.matrixWorld),G.color.copy(q).multiplyScalar(z),G.distance=W,G.coneCos=Math.cos(C.angle),G.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),G.decay=C.decay,n.spot[_]=G;let Q=C.shadow;if(C.map&&(n.spotLightMap[L]=C.map,L++,Q.updateMatrices(C),C.castShadow&&R++),n.spotLightMatrix[_]=Q.matrix,C.castShadow){let V=t.get(C);V.shadowIntensity=Q.intensity,V.shadowBias=Q.bias,V.shadowNormalBias=Q.normalBias,V.shadowRadius=Q.radius,V.shadowMapSize=Q.mapSize,n.spotShadow[_]=V,n.spotShadowMap[_]=J,M++}_++}else if(C.isRectAreaLight){let G=e.get(C);G.color.copy(q).multiplyScalar(z),G.halfWidth.set(C.width*.5,0,0),G.halfHeight.set(0,C.height*.5,0),n.rectArea[m]=G,m++}else if(C.isPointLight){let G=e.get(C);if(G.color.copy(C.color).multiplyScalar(C.intensity),G.distance=C.distance,G.decay=C.decay,C.castShadow){let Q=C.shadow,V=t.get(C);V.shadowIntensity=Q.intensity,V.shadowBias=Q.bias,V.shadowNormalBias=Q.normalBias,V.shadowRadius=Q.radius,V.shadowMapSize=Q.mapSize,V.shadowCameraNear=Q.camera.near,V.shadowCameraFar=Q.camera.far,n.pointShadow[g]=V,n.pointShadowMap[g]=J,n.pointShadowMatrix[g]=C.shadow.matrix,T++}n.point[g]=G,g++}else if(C.isHemisphereLight){let G=e.get(C);G.skyColor.copy(C.color).multiplyScalar(z),G.groundColor.copy(C.groundColor).multiplyScalar(z),n.hemi[f]=G,f++}}m>0&&(s.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=te.LTC_FLOAT_1,n.rectAreaLTC2=te.LTC_FLOAT_2):(n.rectAreaLTC1=te.LTC_HALF_1,n.rectAreaLTC2=te.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=d;let N=n.hash;(N.directionalLength!==p||N.pointLength!==g||N.spotLength!==_||N.rectAreaLength!==m||N.hemiLength!==f||N.numDirectionalShadows!==E||N.numPointShadows!==T||N.numSpotShadows!==M||N.numSpotMaps!==L||N.numLightProbes!==w)&&(n.directional.length=p,n.spot.length=_,n.rectArea.length=m,n.point.length=g,n.hemi.length=f,n.directionalShadow.length=E,n.directionalShadowMap.length=E,n.pointShadow.length=T,n.pointShadowMap.length=T,n.spotShadow.length=M,n.spotShadowMap.length=M,n.directionalShadowMatrix.length=E,n.pointShadowMatrix.length=T,n.spotLightMatrix.length=M+L-R,n.spotLightMap.length=L,n.numSpotLightShadowsWithMaps=R,n.numLightProbes=w,N.directionalLength=p,N.pointLength=g,N.spotLength=_,N.rectAreaLength=m,N.hemiLength=f,N.numDirectionalShadows=E,N.numPointShadows=T,N.numSpotShadows=M,N.numSpotMaps=L,N.numLightProbes=w,n.version=kg++)}function c(l,h){let u=0,d=0,p=0,g=0,_=0,m=h.matrixWorldInverse;for(let f=0,E=l.length;f<E;f++){let T=l[f];if(T.isDirectionalLight){let M=n.directional[u];M.direction.setFromMatrixPosition(T.matrixWorld),i.setFromMatrixPosition(T.target.matrixWorld),M.direction.sub(i),M.direction.transformDirection(m),u++}else if(T.isSpotLight){let M=n.spot[p];M.position.setFromMatrixPosition(T.matrixWorld),M.position.applyMatrix4(m),M.direction.setFromMatrixPosition(T.matrixWorld),i.setFromMatrixPosition(T.target.matrixWorld),M.direction.sub(i),M.direction.transformDirection(m),p++}else if(T.isRectAreaLight){let M=n.rectArea[g];M.position.setFromMatrixPosition(T.matrixWorld),M.position.applyMatrix4(m),o.identity(),r.copy(T.matrixWorld),r.premultiply(m),o.extractRotation(r),M.halfWidth.set(T.width*.5,0,0),M.halfHeight.set(0,T.height*.5,0),M.halfWidth.applyMatrix4(o),M.halfHeight.applyMatrix4(o),g++}else if(T.isPointLight){let M=n.point[d];M.position.setFromMatrixPosition(T.matrixWorld),M.position.applyMatrix4(m),d++}else if(T.isHemisphereLight){let M=n.hemi[_];M.direction.setFromMatrixPosition(T.matrixWorld),M.direction.transformDirection(m),_++}}}return{setup:a,setupView:c,state:n}}function lu(s){let e=new Hg(s),t=[],n=[];function i(h){l.camera=h,t.length=0,n.length=0}function r(h){t.push(h)}function o(h){n.push(h)}function a(){e.setup(t)}function c(h){e.setupView(t,h)}let l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:i,state:l,setupLights:a,setupLightsView:c,pushLight:r,pushShadow:o}}function Gg(s){let e=new WeakMap;function t(i,r=0){let o=e.get(i),a;return o===void 0?(a=new lu(s),e.set(i,[a])):r>=o.length?(a=new lu(s),o.push(a)):a=o[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}var Wg=`void main() {+ gl_Position = vec4( position, 1.0 );+}`,Xg=`uniform sampler2D shadow_pass;+uniform vec2 resolution;+uniform float radius;+#include <packing>+void main() {+ const float samples = float( VSM_SAMPLES );+ float mean = 0.0;+ float squared_mean = 0.0;+ float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );+ float uvStart = samples <= 1.0 ? 0.0 : - 1.0;+ for ( float i = 0.0; i < samples; i ++ ) {+ float uvOffset = uvStart + i * uvStride;+ #ifdef HORIZONTAL_PASS+ vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );+ mean += distribution.x;+ squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;+ #else+ float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );+ mean += depth;+ squared_mean += depth * depth;+ #endif+ }+ mean = mean / samples;+ squared_mean = squared_mean / samples;+ float std_dev = sqrt( squared_mean - mean * mean );+ gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );+}`;function qg(s,e,t){let n=new $i,i=new ze,r=new ze,o=new qe,a=new Xr({depthPacking:Th}),c=new qr,l={},h=t.maxTextureSize,u={[rn]:Pt,[Pt]:rn,[Yt]:Yt},d=new cn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ze},radius:{value:4}},vertexShader:Wg,fragmentShader:Xg}),p=d.clone();p.defines.HORIZONTAL_PASS=1;let g=new Vt;g.setAttribute("position",new ft(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new Mt(g,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Oa;let f=this.type;this.render=function(R,w,N){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||R.length===0)return;let S=s.getRenderTarget(),v=s.getActiveCubeFace(),C=s.getActiveMipmapLevel(),q=s.state;q.setBlending(Nn),q.buffers.color.setClear(1,1,1,1),q.buffers.depth.setTest(!0),q.setScissorTest(!1);let z=f!==vn&&this.type===vn,W=f===vn&&this.type!==vn;for(let J=0,G=R.length;J<G;J++){let Q=R[J],V=Q.shadow;if(V===void 0){console.warn("THREE.WebGLShadowMap:",Q,"has no shadow.");continue}if(V.autoUpdate===!1&&V.needsUpdate===!1)continue;i.copy(V.mapSize);let ie=V.getFrameExtents();if(i.multiply(ie),r.copy(V.mapSize),(i.x>h||i.y>h)&&(i.x>h&&(r.x=Math.floor(h/ie.x),i.x=r.x*ie.x,V.mapSize.x=r.x),i.y>h&&(r.y=Math.floor(h/ie.y),i.y=r.y*ie.y,V.mapSize.y=r.y)),V.map===null||z===!0||W===!0){let _e=this.type!==vn?{minFilter:yt,magFilter:yt}:{};V.map!==null&&V.map.dispose(),V.map=new mn(i.x,i.y,_e),V.map.texture.name=Q.name+".shadowMap",V.camera.updateProjectionMatrix()}s.setRenderTarget(V.map),s.clear();let he=V.getViewportCount();for(let _e=0;_e<he;_e++){let Ne=V.getViewport(_e);o.set(r.x*Ne.x,r.y*Ne.y,r.x*Ne.z,r.y*Ne.w),q.viewport(o),V.updateMatrices(Q,_e),n=V.getFrustum(),M(w,N,V.camera,Q,this.type)}V.isPointLightShadow!==!0&&this.type===vn&&E(V,N),V.needsUpdate=!1}f=this.type,m.needsUpdate=!1,s.setRenderTarget(S,v,C)};function E(R,w){let N=e.update(_);d.defines.VSM_SAMPLES!==R.blurSamples&&(d.defines.VSM_SAMPLES=R.blurSamples,p.defines.VSM_SAMPLES=R.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),R.mapPass===null&&(R.mapPass=new mn(i.x,i.y)),d.uniforms.shadow_pass.value=R.map.texture,d.uniforms.resolution.value=R.mapSize,d.uniforms.radius.value=R.radius,s.setRenderTarget(R.mapPass),s.clear(),s.renderBufferDirect(w,null,N,d,_,null),p.uniforms.shadow_pass.value=R.mapPass.texture,p.uniforms.resolution.value=R.mapSize,p.uniforms.radius.value=R.radius,s.setRenderTarget(R.map),s.clear(),s.renderBufferDirect(w,null,N,p,_,null)}function T(R,w,N,S){let v=null,C=N.isPointLight===!0?R.customDistanceMaterial:R.customDepthMaterial;if(C!==void 0)v=C;else if(v=N.isPointLight===!0?c:a,s.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){let q=v.uuid,z=w.uuid,W=l[q];W===void 0&&(W={},l[q]=W);let J=W[z];J===void 0&&(J=v.clone(),W[z]=J,w.addEventListener("dispose",L)),v=J}if(v.visible=w.visible,v.wireframe=w.wireframe,S===vn?v.side=w.shadowSide!==null?w.shadowSide:w.side:v.side=w.shadowSide!==null?w.shadowSide:u[w.side],v.alphaMap=w.alphaMap,v.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,v.map=w.map,v.clipShadows=w.clipShadows,v.clippingPlanes=w.clippingPlanes,v.clipIntersection=w.clipIntersection,v.displacementMap=w.displacementMap,v.displacementScale=w.displacementScale,v.displacementBias=w.displacementBias,v.wireframeLinewidth=w.wireframeLinewidth,v.linewidth=w.linewidth,N.isPointLight===!0&&v.isMeshDistanceMaterial===!0){let q=s.properties.get(v);q.light=N}return v}function M(R,w,N,S,v){if(R.visible===!1)return;if(R.layers.test(w.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&v===vn)&&(!R.frustumCulled||n.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(N.matrixWorldInverse,R.matrixWorld);let z=e.update(R),W=R.material;if(Array.isArray(W)){let J=z.groups;for(let G=0,Q=J.length;G<Q;G++){let V=J[G],ie=W[V.materialIndex];if(ie&&ie.visible){let he=T(R,ie,S,v);R.onBeforeShadow(s,R,w,N,z,he,V),s.renderBufferDirect(N,null,z,he,R,V),R.onAfterShadow(s,R,w,N,z,he,V)}}}else if(W.visible){let J=T(R,W,S,v);R.onBeforeShadow(s,R,w,N,z,J,null),s.renderBufferDirect(N,null,z,J,R,null),R.onAfterShadow(s,R,w,N,z,J,null)}}let q=R.children;for(let z=0,W=q.length;z<W;z++)M(q[z],w,N,S,v)}function L(R){R.target.removeEventListener("dispose",L);for(let N in l){let S=l[N],v=R.target.uuid;v in S&&(S[v].dispose(),delete S[v])}}}var Yg={[to]:no,[io]:oo,[so]:ao,[ci]:ro,[no]:to,[oo]:io,[ao]:so,[ro]:ci};function Zg(s,e){function t(){let I=!1,oe=new qe,k=null,Z=new qe(0,0,0,0);return{setMask:function(ce){k!==ce&&!I&&(s.colorMask(ce,ce,ce,ce),k=ce)},setLocked:function(ce){I=ce},setClear:function(ce,ae,Le,ot,St){St===!0&&(ce*=ot,ae*=ot,Le*=ot),oe.set(ce,ae,Le,ot),Z.equals(oe)===!1&&(s.clearColor(ce,ae,Le,ot),Z.copy(oe))},reset:function(){I=!1,k=null,Z.set(-1,0,0,0)}}}function n(){let I=!1,oe=!1,k=null,Z=null,ce=null;return{setReversed:function(ae){if(oe!==ae){let Le=e.get("EXT_clip_control");ae?Le.clipControlEXT(Le.LOWER_LEFT_EXT,Le.ZERO_TO_ONE_EXT):Le.clipControlEXT(Le.LOWER_LEFT_EXT,Le.NEGATIVE_ONE_TO_ONE_EXT),oe=ae;let ot=ce;ce=null,this.setClear(ot)}},getReversed:function(){return oe},setTest:function(ae){ae?se(s.DEPTH_TEST):Me(s.DEPTH_TEST)},setMask:function(ae){k!==ae&&!I&&(s.depthMask(ae),k=ae)},setFunc:function(ae){if(oe&&(ae=Yg[ae]),Z!==ae){switch(ae){case to:s.depthFunc(s.NEVER);break;case no:s.depthFunc(s.ALWAYS);break;case io:s.depthFunc(s.LESS);break;case ci:s.depthFunc(s.LEQUAL);break;case so:s.depthFunc(s.EQUAL);break;case ro:s.depthFunc(s.GEQUAL);break;case oo:s.depthFunc(s.GREATER);break;case ao:s.depthFunc(s.NOTEQUAL);break;default:s.depthFunc(s.LEQUAL)}Z=ae}},setLocked:function(ae){I=ae},setClear:function(ae){ce!==ae&&(oe&&(ae=1-ae),s.clearDepth(ae),ce=ae)},reset:function(){I=!1,k=null,Z=null,ce=null,oe=!1}}}function i(){let I=!1,oe=null,k=null,Z=null,ce=null,ae=null,Le=null,ot=null,St=null;return{setTest:function(Je){I||(Je?se(s.STENCIL_TEST):Me(s.STENCIL_TEST))},setMask:function(Je){oe!==Je&&!I&&(s.stencilMask(Je),oe=Je)},setFunc:function(Je,Jt,Sn){(k!==Je||Z!==Jt||ce!==Sn)&&(s.stencilFunc(Je,Jt,Sn),k=Je,Z=Jt,ce=Sn)},setOp:function(Je,Jt,Sn){(ae!==Je||Le!==Jt||ot!==Sn)&&(s.stencilOp(Je,Jt,Sn),ae=Je,Le=Jt,ot=Sn)},setLocked:function(Je){I=Je},setClear:function(Je){St!==Je&&(s.clearStencil(Je),St=Je)},reset:function(){I=!1,oe=null,k=null,Z=null,ce=null,ae=null,Le=null,ot=null,St=null}}}let r=new t,o=new n,a=new i,c=new WeakMap,l=new WeakMap,h={},u={},d=new WeakMap,p=[],g=null,_=!1,m=null,f=null,E=null,T=null,M=null,L=null,R=null,w=new be(0,0,0),N=0,S=!1,v=null,C=null,q=null,z=null,W=null,J=s.getParameter(s.MAX_COMBINED_TEXTURE_IMAGE_UNITS),G=!1,Q=0,V=s.getParameter(s.VERSION);V.indexOf("WebGL")!==-1?(Q=parseFloat(/^WebGL (\d)/.exec(V)[1]),G=Q>=1):V.indexOf("OpenGL ES")!==-1&&(Q=parseFloat(/^OpenGL ES (\d)/.exec(V)[1]),G=Q>=2);let ie=null,he={},_e=s.getParameter(s.SCISSOR_BOX),Ne=s.getParameter(s.VIEWPORT),et=new qe().fromArray(_e),X=new qe().fromArray(Ne);function ee(I,oe,k,Z){let ce=new Uint8Array(4),ae=s.createTexture();s.bindTexture(I,ae),s.texParameteri(I,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(I,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let Le=0;Le<k;Le++)I===s.TEXTURE_3D||I===s.TEXTURE_2D_ARRAY?s.texImage3D(oe,0,s.RGBA,1,1,Z,0,s.RGBA,s.UNSIGNED_BYTE,ce):s.texImage2D(oe+Le,0,s.RGBA,1,1,0,s.RGBA,s.UNSIGNED_BYTE,ce);return ae}let pe={};pe[s.TEXTURE_2D]=ee(s.TEXTURE_2D,s.TEXTURE_2D,1),pe[s.TEXTURE_CUBE_MAP]=ee(s.TEXTURE_CUBE_MAP,s.TEXTURE_CUBE_MAP_POSITIVE_X,6),pe[s.TEXTURE_2D_ARRAY]=ee(s.TEXTURE_2D_ARRAY,s.TEXTURE_2D_ARRAY,1,1),pe[s.TEXTURE_3D]=ee(s.TEXTURE_3D,s.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),se(s.DEPTH_TEST),o.setFunc(ci),Ge(!1),Ve(Fa),se(s.CULL_FACE),A(Nn);function se(I){h[I]!==!0&&(s.enable(I),h[I]=!0)}function Me(I){h[I]!==!1&&(s.disable(I),h[I]=!1)}function Ye(I,oe){return u[I]!==oe?(s.bindFramebuffer(I,oe),u[I]=oe,I===s.DRAW_FRAMEBUFFER&&(u[s.FRAMEBUFFER]=oe),I===s.FRAMEBUFFER&&(u[s.DRAW_FRAMEBUFFER]=oe),!0):!1}function Ae(I,oe){let k=p,Z=!1;if(I){k=d.get(oe),k===void 0&&(k=[],d.set(oe,k));let ce=I.textures;if(k.length!==ce.length||k[0]!==s.COLOR_ATTACHMENT0){for(let ae=0,Le=ce.length;ae<Le;ae++)k[ae]=s.COLOR_ATTACHMENT0+ae;k.length=ce.length,Z=!0}}else k[0]!==s.BACK&&(k[0]=s.BACK,Z=!0);Z&&s.drawBuffers(k)}function ct(I){return g!==I?(s.useProgram(I),g=I,!0):!1}let st={[qn]:s.FUNC_ADD,[Yl]:s.FUNC_SUBTRACT,[Zl]:s.FUNC_REVERSE_SUBTRACT};st[Kl]=s.MIN,st[Jl]=s.MAX;let ke={[$l]:s.ZERO,[jl]:s.ONE,[Ql]:s.SRC_COLOR,[Nr]:s.SRC_ALPHA,[rh]:s.SRC_ALPHA_SATURATE,[ih]:s.DST_COLOR,[th]:s.DST_ALPHA,[eh]:s.ONE_MINUS_SRC_COLOR,[Fr]:s.ONE_MINUS_SRC_ALPHA,[sh]:s.ONE_MINUS_DST_COLOR,[nh]:s.ONE_MINUS_DST_ALPHA,[oh]:s.CONSTANT_COLOR,[ah]:s.ONE_MINUS_CONSTANT_COLOR,[ch]:s.CONSTANT_ALPHA,[lh]:s.ONE_MINUS_CONSTANT_ALPHA};function A(I,oe,k,Z,ce,ae,Le,ot,St,Je){if(I===Nn){_===!0&&(Me(s.BLEND),_=!1);return}if(_===!1&&(se(s.BLEND),_=!0),I!==ql){if(I!==m||Je!==S){if((f!==qn||M!==qn)&&(s.blendEquation(s.FUNC_ADD),f=qn,M=qn),Je)switch(I){case ai:s.blendFuncSeparate(s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case Ba:s.blendFunc(s.ONE,s.ONE);break;case za:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case ka:s.blendFuncSeparate(s.ZERO,s.SRC_COLOR,s.ZERO,s.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",I);break}else switch(I){case ai:s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case Ba:s.blendFunc(s.SRC_ALPHA,s.ONE);break;case za:s.blendFuncSeparate(s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case ka:s.blendFunc(s.ZERO,s.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",I);break}E=null,T=null,L=null,R=null,w.set(0,0,0),N=0,m=I,S=Je}return}ce=ce||oe,ae=ae||k,Le=Le||Z,(oe!==f||ce!==M)&&(s.blendEquationSeparate(st[oe],st[ce]),f=oe,M=ce),(k!==E||Z!==T||ae!==L||Le!==R)&&(s.blendFuncSeparate(ke[k],ke[Z],ke[ae],ke[Le]),E=k,T=Z,L=ae,R=Le),(ot.equals(w)===!1||St!==N)&&(s.blendColor(ot.r,ot.g,ot.b,St),w.copy(ot),N=St),m=I,S=!1}function Gt(I,oe){I.side===Yt?Me(s.CULL_FACE):se(s.CULL_FACE);let k=I.side===Pt;oe&&(k=!k),Ge(k),I.blending===ai&&I.transparent===!1?A(Nn):A(I.blending,I.blendEquation,I.blendSrc,I.blendDst,I.blendEquationAlpha,I.blendSrcAlpha,I.blendDstAlpha,I.blendColor,I.blendAlpha,I.premultipliedAlpha),o.setFunc(I.depthFunc),o.setTest(I.depthTest),o.setMask(I.depthWrite),r.setMask(I.colorWrite);let Z=I.stencilWrite;a.setTest(Z),Z&&(a.setMask(I.stencilWriteMask),a.setFunc(I.stencilFunc,I.stencilRef,I.stencilFuncMask),a.setOp(I.stencilFail,I.stencilZFail,I.stencilZPass)),nt(I.polygonOffset,I.polygonOffsetFactor,I.polygonOffsetUnits),I.alphaToCoverage===!0?se(s.SAMPLE_ALPHA_TO_COVERAGE):Me(s.SAMPLE_ALPHA_TO_COVERAGE)}function Ge(I){v!==I&&(I?s.frontFace(s.CW):s.frontFace(s.CCW),v=I)}function Ve(I){I!==Gl?(se(s.CULL_FACE),I!==C&&(I===Fa?s.cullFace(s.BACK):I===Wl?s.cullFace(s.FRONT):s.cullFace(s.FRONT_AND_BACK))):Me(s.CULL_FACE),C=I}function xe(I){I!==q&&(G&&s.lineWidth(I),q=I)}function nt(I,oe,k){I?(se(s.POLYGON_OFFSET_FILL),(z!==oe||W!==k)&&(s.polygonOffset(oe,k),z=oe,W=k)):Me(s.POLYGON_OFFSET_FILL)}function ge(I){I?se(s.SCISSOR_TEST):Me(s.SCISSOR_TEST)}function b(I){I===void 0&&(I=s.TEXTURE0+J-1),ie!==I&&(s.activeTexture(I),ie=I)}function x(I,oe,k){k===void 0&&(ie===null?k=s.TEXTURE0+J-1:k=ie);let Z=he[k];Z===void 0&&(Z={type:void 0,texture:void 0},he[k]=Z),(Z.type!==I||Z.texture!==oe)&&(ie!==k&&(s.activeTexture(k),ie=k),s.bindTexture(I,oe||pe[I]),Z.type=I,Z.texture=oe)}function F(){let I=he[ie];I!==void 0&&I.type!==void 0&&(s.bindTexture(I.type,null),I.type=void 0,I.texture=void 0)}function Y(){try{s.compressedTexImage2D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function K(){try{s.compressedTexImage3D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function H(){try{s.texSubImage2D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function me(){try{s.texSubImage3D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function re(){try{s.compressedTexSubImage2D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Se(){try{s.compressedTexSubImage3D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Te(){try{s.texStorage2D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function $(){try{s.texStorage3D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function ue(){try{s.texImage2D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Ee(){try{s.texImage3D(...arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Re(I){et.equals(I)===!1&&(s.scissor(I.x,I.y,I.z,I.w),et.copy(I))}function de(I){X.equals(I)===!1&&(s.viewport(I.x,I.y,I.z,I.w),X.copy(I))}function He(I,oe){let k=l.get(oe);k===void 0&&(k=new WeakMap,l.set(oe,k));let Z=k.get(I);Z===void 0&&(Z=s.getUniformBlockIndex(oe,I.name),k.set(I,Z))}function De(I,oe){let Z=l.get(oe).get(I);c.get(oe)!==Z&&(s.uniformBlockBinding(oe,Z,I.__bindingPointIndex),c.set(oe,Z))}function tt(){s.disable(s.BLEND),s.disable(s.CULL_FACE),s.disable(s.DEPTH_TEST),s.disable(s.POLYGON_OFFSET_FILL),s.disable(s.SCISSOR_TEST),s.disable(s.STENCIL_TEST),s.disable(s.SAMPLE_ALPHA_TO_COVERAGE),s.blendEquation(s.FUNC_ADD),s.blendFunc(s.ONE,s.ZERO),s.blendFuncSeparate(s.ONE,s.ZERO,s.ONE,s.ZERO),s.blendColor(0,0,0,0),s.colorMask(!0,!0,!0,!0),s.clearColor(0,0,0,0),s.depthMask(!0),s.depthFunc(s.LESS),o.setReversed(!1),s.clearDepth(1),s.stencilMask(4294967295),s.stencilFunc(s.ALWAYS,0,4294967295),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),s.clearStencil(0),s.cullFace(s.BACK),s.frontFace(s.CCW),s.polygonOffset(0,0),s.activeTexture(s.TEXTURE0),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),s.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.useProgram(null),s.lineWidth(1),s.scissor(0,0,s.canvas.width,s.canvas.height),s.viewport(0,0,s.canvas.width,s.canvas.height),h={},ie=null,he={},u={},d=new WeakMap,p=[],g=null,_=!1,m=null,f=null,E=null,T=null,M=null,L=null,R=null,w=new be(0,0,0),N=0,S=!1,v=null,C=null,q=null,z=null,W=null,et.set(0,0,s.canvas.width,s.canvas.height),X.set(0,0,s.canvas.width,s.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:se,disable:Me,bindFramebuffer:Ye,drawBuffers:Ae,useProgram:ct,setBlending:A,setMaterial:Gt,setFlipSided:Ge,setCullFace:Ve,setLineWidth:xe,setPolygonOffset:nt,setScissorTest:ge,activeTexture:b,bindTexture:x,unbindTexture:F,compressedTexImage2D:Y,compressedTexImage3D:K,texImage2D:ue,texImage3D:Ee,updateUBOMapping:He,uniformBlockBinding:De,texStorage2D:Te,texStorage3D:$,texSubImage2D:H,texSubImage3D:me,compressedTexSubImage2D:re,compressedTexSubImage3D:Se,scissor:Re,viewport:de,reset:tt}}function Kg(s,e,t,n,i,r,o){let a=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=new WeakMap,u,d=new WeakMap,p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(b,x){return p?new OffscreenCanvas(b,x):Wi("canvas")}function _(b,x,F){let Y=1,K=ge(b);if((K.width>F||K.height>F)&&(Y=F/Math.max(K.width,K.height)),Y<1)if(typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&b instanceof ImageBitmap||typeof VideoFrame<"u"&&b instanceof VideoFrame){let H=Math.floor(Y*K.width),me=Math.floor(Y*K.height);u===void 0&&(u=g(H,me));let re=x?g(H,me):u;return re.width=H,re.height=me,re.getContext("2d").drawImage(b,0,0,H,me),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+K.width+"x"+K.height+") to ("+H+"x"+me+")."),re}else return"data"in b&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+K.width+"x"+K.height+")."),b;return b}function m(b){return b.generateMipmaps}function f(b){s.generateMipmap(b)}function E(b){return b.isWebGLCubeRenderTarget?s.TEXTURE_CUBE_MAP:b.isWebGL3DRenderTarget?s.TEXTURE_3D:b.isWebGLArrayRenderTarget||b.isCompressedArrayTexture?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D}function T(b,x,F,Y,K=!1){if(b!==null){if(s[b]!==void 0)return s[b];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+b+"'")}let H=x;if(x===s.RED&&(F===s.FLOAT&&(H=s.R32F),F===s.HALF_FLOAT&&(H=s.R16F),F===s.UNSIGNED_BYTE&&(H=s.R8)),x===s.RED_INTEGER&&(F===s.UNSIGNED_BYTE&&(H=s.R8UI),F===s.UNSIGNED_SHORT&&(H=s.R16UI),F===s.UNSIGNED_INT&&(H=s.R32UI),F===s.BYTE&&(H=s.R8I),F===s.SHORT&&(H=s.R16I),F===s.INT&&(H=s.R32I)),x===s.RG&&(F===s.FLOAT&&(H=s.RG32F),F===s.HALF_FLOAT&&(H=s.RG16F),F===s.UNSIGNED_BYTE&&(H=s.RG8)),x===s.RG_INTEGER&&(F===s.UNSIGNED_BYTE&&(H=s.RG8UI),F===s.UNSIGNED_SHORT&&(H=s.RG16UI),F===s.UNSIGNED_INT&&(H=s.RG32UI),F===s.BYTE&&(H=s.RG8I),F===s.SHORT&&(H=s.RG16I),F===s.INT&&(H=s.RG32I)),x===s.RGB_INTEGER&&(F===s.UNSIGNED_BYTE&&(H=s.RGB8UI),F===s.UNSIGNED_SHORT&&(H=s.RGB16UI),F===s.UNSIGNED_INT&&(H=s.RGB32UI),F===s.BYTE&&(H=s.RGB8I),F===s.SHORT&&(H=s.RGB16I),F===s.INT&&(H=s.RGB32I)),x===s.RGBA_INTEGER&&(F===s.UNSIGNED_BYTE&&(H=s.RGBA8UI),F===s.UNSIGNED_SHORT&&(H=s.RGBA16UI),F===s.UNSIGNED_INT&&(H=s.RGBA32UI),F===s.BYTE&&(H=s.RGBA8I),F===s.SHORT&&(H=s.RGBA16I),F===s.INT&&(H=s.RGBA32I)),x===s.RGB&&F===s.UNSIGNED_INT_5_9_9_9_REV&&(H=s.RGB9_E5),x===s.RGBA){let me=K?Ts:Be.getTransfer(Y);F===s.FLOAT&&(H=s.RGBA32F),F===s.HALF_FLOAT&&(H=s.RGBA16F),F===s.UNSIGNED_BYTE&&(H=me===je?s.SRGB8_ALPHA8:s.RGBA8),F===s.UNSIGNED_SHORT_4_4_4_4&&(H=s.RGBA4),F===s.UNSIGNED_SHORT_5_5_5_1&&(H=s.RGB5_A1)}return(H===s.R16F||H===s.R32F||H===s.RG16F||H===s.RG32F||H===s.RGBA16F||H===s.RGBA32F)&&e.get("EXT_color_buffer_float"),H}function M(b,x){let F;return b?x===null||x===Jn||x===ss?F=s.DEPTH24_STENCIL8:x===Zt?F=s.DEPTH32F_STENCIL8:x===ns&&(F=s.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):x===null||x===Jn||x===ss?F=s.DEPTH_COMPONENT24:x===Zt?F=s.DEPTH_COMPONENT32F:x===ns&&(F=s.DEPTH_COMPONENT16),F}function L(b,x){return m(b)===!0||b.isFramebufferTexture&&b.minFilter!==yt&&b.minFilter!==Ct?Math.log2(Math.max(x.width,x.height))+1:b.mipmaps!==void 0&&b.mipmaps.length>0?b.mipmaps.length:b.isCompressedTexture&&Array.isArray(b.image)?x.mipmaps.length:1}function R(b){let x=b.target;x.removeEventListener("dispose",R),N(x),x.isVideoTexture&&h.delete(x)}function w(b){let x=b.target;x.removeEventListener("dispose",w),v(x)}function N(b){let x=n.get(b);if(x.__webglInit===void 0)return;let F=b.source,Y=d.get(F);if(Y){let K=Y[x.__cacheKey];K.usedTimes--,K.usedTimes===0&&S(b),Object.keys(Y).length===0&&d.delete(F)}n.remove(b)}function S(b){let x=n.get(b);s.deleteTexture(x.__webglTexture);let F=b.source,Y=d.get(F);delete Y[x.__cacheKey],o.memory.textures--}function v(b){let x=n.get(b);if(b.depthTexture&&(b.depthTexture.dispose(),n.remove(b.depthTexture)),b.isWebGLCubeRenderTarget)for(let Y=0;Y<6;Y++){if(Array.isArray(x.__webglFramebuffer[Y]))for(let K=0;K<x.__webglFramebuffer[Y].length;K++)s.deleteFramebuffer(x.__webglFramebuffer[Y][K]);else s.deleteFramebuffer(x.__webglFramebuffer[Y]);x.__webglDepthbuffer&&s.deleteRenderbuffer(x.__webglDepthbuffer[Y])}else{if(Array.isArray(x.__webglFramebuffer))for(let Y=0;Y<x.__webglFramebuffer.length;Y++)s.deleteFramebuffer(x.__webglFramebuffer[Y]);else s.deleteFramebuffer(x.__webglFramebuffer);if(x.__webglDepthbuffer&&s.deleteRenderbuffer(x.__webglDepthbuffer),x.__webglMultisampledFramebuffer&&s.deleteFramebuffer(x.__webglMultisampledFramebuffer),x.__webglColorRenderbuffer)for(let Y=0;Y<x.__webglColorRenderbuffer.length;Y++)x.__webglColorRenderbuffer[Y]&&s.deleteRenderbuffer(x.__webglColorRenderbuffer[Y]);x.__webglDepthRenderbuffer&&s.deleteRenderbuffer(x.__webglDepthRenderbuffer)}let F=b.textures;for(let Y=0,K=F.length;Y<K;Y++){let H=n.get(F[Y]);H.__webglTexture&&(s.deleteTexture(H.__webglTexture),o.memory.textures--),n.remove(F[Y])}n.remove(b)}let C=0;function q(){C=0}function z(){let b=C;return b>=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+b+" texture units while this GPU supports only "+i.maxTextures),C+=1,b}function W(b){let x=[];return x.push(b.wrapS),x.push(b.wrapT),x.push(b.wrapR||0),x.push(b.magFilter),x.push(b.minFilter),x.push(b.anisotropy),x.push(b.internalFormat),x.push(b.format),x.push(b.type),x.push(b.generateMipmaps),x.push(b.premultiplyAlpha),x.push(b.flipY),x.push(b.unpackAlignment),x.push(b.colorSpace),x.join()}function J(b,x){let F=n.get(b);if(b.isVideoTexture&&xe(b),b.isRenderTargetTexture===!1&&b.version>0&&F.__version!==b.version){let Y=b.image;if(Y===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(Y.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{X(F,b,x);return}}t.bindTexture(s.TEXTURE_2D,F.__webglTexture,s.TEXTURE0+x)}function G(b,x){let F=n.get(b);if(b.version>0&&F.__version!==b.version){X(F,b,x);return}t.bindTexture(s.TEXTURE_2D_ARRAY,F.__webglTexture,s.TEXTURE0+x)}function Q(b,x){let F=n.get(b);if(b.version>0&&F.__version!==b.version){X(F,b,x);return}t.bindTexture(s.TEXTURE_3D,F.__webglTexture,s.TEXTURE0+x)}function V(b,x){let F=n.get(b);if(b.version>0&&F.__version!==b.version){ee(F,b,x);return}t.bindTexture(s.TEXTURE_CUBE_MAP,F.__webglTexture,s.TEXTURE0+x)}let ie={[Yn]:s.REPEAT,[dn]:s.CLAMP_TO_EDGE,[Hi]:s.MIRRORED_REPEAT},he={[yt]:s.NEAREST,[uo]:s.NEAREST_MIPMAP_NEAREST,[vi]:s.NEAREST_MIPMAP_LINEAR,[Ct]:s.LINEAR,[ts]:s.LINEAR_MIPMAP_NEAREST,[ln]:s.LINEAR_MIPMAP_LINEAR},_e={[Ah]:s.NEVER,[Lh]:s.ALWAYS,[wh]:s.LESS,[ja]:s.LEQUAL,[Rh]:s.EQUAL,[Ph]:s.GEQUAL,[Ch]:s.GREATER,[Ih]:s.NOTEQUAL};function Ne(b,x){if(x.type===Zt&&e.has("OES_texture_float_linear")===!1&&(x.magFilter===Ct||x.magFilter===ts||x.magFilter===vi||x.magFilter===ln||x.minFilter===Ct||x.minFilter===ts||x.minFilter===vi||x.minFilter===ln)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),s.texParameteri(b,s.TEXTURE_WRAP_S,ie[x.wrapS]),s.texParameteri(b,s.TEXTURE_WRAP_T,ie[x.wrapT]),(b===s.TEXTURE_3D||b===s.TEXTURE_2D_ARRAY)&&s.texParameteri(b,s.TEXTURE_WRAP_R,ie[x.wrapR]),s.texParameteri(b,s.TEXTURE_MAG_FILTER,he[x.magFilter]),s.texParameteri(b,s.TEXTURE_MIN_FILTER,he[x.minFilter]),x.compareFunction&&(s.texParameteri(b,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(b,s.TEXTURE_COMPARE_FUNC,_e[x.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(x.magFilter===yt||x.minFilter!==vi&&x.minFilter!==ln||x.type===Zt&&e.has("OES_texture_float_linear")===!1)return;if(x.anisotropy>1||n.get(x).__currentAnisotropy){let F=e.get("EXT_texture_filter_anisotropic");s.texParameterf(b,F.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(x.anisotropy,i.getMaxAnisotropy())),n.get(x).__currentAnisotropy=x.anisotropy}}}function et(b,x){let F=!1;b.__webglInit===void 0&&(b.__webglInit=!0,x.addEventListener("dispose",R));let Y=x.source,K=d.get(Y);K===void 0&&(K={},d.set(Y,K));let H=W(x);if(H!==b.__cacheKey){K[H]===void 0&&(K[H]={texture:s.createTexture(),usedTimes:0},o.memory.textures++,F=!0),K[H].usedTimes++;let me=K[b.__cacheKey];me!==void 0&&(K[b.__cacheKey].usedTimes--,me.usedTimes===0&&S(x)),b.__cacheKey=H,b.__webglTexture=K[H].texture}return F}function X(b,x,F){let Y=s.TEXTURE_2D;(x.isDataArrayTexture||x.isCompressedArrayTexture)&&(Y=s.TEXTURE_2D_ARRAY),x.isData3DTexture&&(Y=s.TEXTURE_3D);let K=et(b,x),H=x.source;t.bindTexture(Y,b.__webglTexture,s.TEXTURE0+F);let me=n.get(H);if(H.version!==me.__version||K===!0){t.activeTexture(s.TEXTURE0+F);let re=Be.getPrimaries(Be.workingColorSpace),Se=x.colorSpace===On?null:Be.getPrimaries(x.colorSpace),Te=x.colorSpace===On||re===Se?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,x.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,x.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,Te);let $=_(x.image,!1,i.maxTextureSize);$=nt(x,$);let ue=r.convert(x.format,x.colorSpace),Ee=r.convert(x.type),Re=T(x.internalFormat,ue,Ee,x.colorSpace,x.isVideoTexture);Ne(Y,x);let de,He=x.mipmaps,De=x.isVideoTexture!==!0,tt=me.__version===void 0||K===!0,I=H.dataReady,oe=L(x,$);if(x.isDepthTexture)Re=M(x.format===rs,x.type),tt&&(De?t.texStorage2D(s.TEXTURE_2D,1,Re,$.width,$.height):t.texImage2D(s.TEXTURE_2D,0,Re,$.width,$.height,0,ue,Ee,null));else if(x.isDataTexture)if(He.length>0){De&&tt&&t.texStorage2D(s.TEXTURE_2D,oe,Re,He[0].width,He[0].height);for(let k=0,Z=He.length;k<Z;k++)de=He[k],De?I&&t.texSubImage2D(s.TEXTURE_2D,k,0,0,de.width,de.height,ue,Ee,de.data):t.texImage2D(s.TEXTURE_2D,k,Re,de.width,de.height,0,ue,Ee,de.data);x.generateMipmaps=!1}else De?(tt&&t.texStorage2D(s.TEXTURE_2D,oe,Re,$.width,$.height),I&&t.texSubImage2D(s.TEXTURE_2D,0,0,0,$.width,$.height,ue,Ee,$.data)):t.texImage2D(s.TEXTURE_2D,0,Re,$.width,$.height,0,ue,Ee,$.data);else if(x.isCompressedTexture)if(x.isCompressedArrayTexture){De&&tt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,oe,Re,He[0].width,He[0].height,$.depth);for(let k=0,Z=He.length;k<Z;k++)if(de=He[k],x.format!==Ht)if(ue!==null)if(De){if(I)if(x.layerUpdates.size>0){let ce=oc(de.width,de.height,x.format,x.type);for(let ae of x.layerUpdates){let Le=de.data.subarray(ae*ce/de.data.BYTES_PER_ELEMENT,(ae+1)*ce/de.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,k,0,0,ae,de.width,de.height,1,ue,Le)}x.clearLayerUpdates()}else t.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,k,0,0,0,de.width,de.height,$.depth,ue,de.data)}else t.compressedTexImage3D(s.TEXTURE_2D_ARRAY,k,Re,de.width,de.height,$.depth,0,de.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else De?I&&t.texSubImage3D(s.TEXTURE_2D_ARRAY,k,0,0,0,de.width,de.height,$.depth,ue,Ee,de.data):t.texImage3D(s.TEXTURE_2D_ARRAY,k,Re,de.width,de.height,$.depth,0,ue,Ee,de.data)}else{De&&tt&&t.texStorage2D(s.TEXTURE_2D,oe,Re,He[0].width,He[0].height);for(let k=0,Z=He.length;k<Z;k++)de=He[k],x.format!==Ht?ue!==null?De?I&&t.compressedTexSubImage2D(s.TEXTURE_2D,k,0,0,de.width,de.height,ue,de.data):t.compressedTexImage2D(s.TEXTURE_2D,k,Re,de.width,de.height,0,de.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):De?I&&t.texSubImage2D(s.TEXTURE_2D,k,0,0,de.width,de.height,ue,Ee,de.data):t.texImage2D(s.TEXTURE_2D,k,Re,de.width,de.height,0,ue,Ee,de.data)}else if(x.isDataArrayTexture)if(De){if(tt&&t.texStorage3D(s.TEXTURE_2D_ARRAY,oe,Re,$.width,$.height,$.depth),I)if(x.layerUpdates.size>0){let k=oc($.width,$.height,x.format,x.type);for(let Z of x.layerUpdates){let ce=$.data.subarray(Z*k/$.data.BYTES_PER_ELEMENT,(Z+1)*k/$.data.BYTES_PER_ELEMENT);t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,Z,$.width,$.height,1,ue,Ee,ce)}x.clearLayerUpdates()}else t.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,$.width,$.height,$.depth,ue,Ee,$.data)}else t.texImage3D(s.TEXTURE_2D_ARRAY,0,Re,$.width,$.height,$.depth,0,ue,Ee,$.data);else if(x.isData3DTexture)De?(tt&&t.texStorage3D(s.TEXTURE_3D,oe,Re,$.width,$.height,$.depth),I&&t.texSubImage3D(s.TEXTURE_3D,0,0,0,0,$.width,$.height,$.depth,ue,Ee,$.data)):t.texImage3D(s.TEXTURE_3D,0,Re,$.width,$.height,$.depth,0,ue,Ee,$.data);else if(x.isFramebufferTexture){if(tt)if(De)t.texStorage2D(s.TEXTURE_2D,oe,Re,$.width,$.height);else{let k=$.width,Z=$.height;for(let ce=0;ce<oe;ce++)t.texImage2D(s.TEXTURE_2D,ce,Re,k,Z,0,ue,Ee,null),k>>=1,Z>>=1}}else if(He.length>0){if(De&&tt){let k=ge(He[0]);t.texStorage2D(s.TEXTURE_2D,oe,Re,k.width,k.height)}for(let k=0,Z=He.length;k<Z;k++)de=He[k],De?I&&t.texSubImage2D(s.TEXTURE_2D,k,0,0,ue,Ee,de):t.texImage2D(s.TEXTURE_2D,k,Re,ue,Ee,de);x.generateMipmaps=!1}else if(De){if(tt){let k=ge($);t.texStorage2D(s.TEXTURE_2D,oe,Re,k.width,k.height)}I&&t.texSubImage2D(s.TEXTURE_2D,0,0,0,ue,Ee,$)}else t.texImage2D(s.TEXTURE_2D,0,Re,ue,Ee,$);m(x)&&f(Y),me.__version=H.version,x.onUpdate&&x.onUpdate(x)}b.__version=x.version}function ee(b,x,F){if(x.image.length!==6)return;let Y=et(b,x),K=x.source;t.bindTexture(s.TEXTURE_CUBE_MAP,b.__webglTexture,s.TEXTURE0+F);let H=n.get(K);if(K.version!==H.__version||Y===!0){t.activeTexture(s.TEXTURE0+F);let me=Be.getPrimaries(Be.workingColorSpace),re=x.colorSpace===On?null:Be.getPrimaries(x.colorSpace),Se=x.colorSpace===On||me===re?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,x.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,x.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,Se);let Te=x.isCompressedTexture||x.image[0].isCompressedTexture,$=x.image[0]&&x.image[0].isDataTexture,ue=[];for(let Z=0;Z<6;Z++)!Te&&!$?ue[Z]=_(x.image[Z],!0,i.maxCubemapSize):ue[Z]=$?x.image[Z].image:x.image[Z],ue[Z]=nt(x,ue[Z]);let Ee=ue[0],Re=r.convert(x.format,x.colorSpace),de=r.convert(x.type),He=T(x.internalFormat,Re,de,x.colorSpace),De=x.isVideoTexture!==!0,tt=H.__version===void 0||Y===!0,I=K.dataReady,oe=L(x,Ee);Ne(s.TEXTURE_CUBE_MAP,x);let k;if(Te){De&&tt&&t.texStorage2D(s.TEXTURE_CUBE_MAP,oe,He,Ee.width,Ee.height);for(let Z=0;Z<6;Z++){k=ue[Z].mipmaps;for(let ce=0;ce<k.length;ce++){let ae=k[ce];x.format!==Ht?Re!==null?De?I&&t.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce,0,0,ae.width,ae.height,Re,ae.data):t.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce,He,ae.width,ae.height,0,ae.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):De?I&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce,0,0,ae.width,ae.height,Re,de,ae.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce,He,ae.width,ae.height,0,Re,de,ae.data)}}}else{if(k=x.mipmaps,De&&tt){k.length>0&&oe++;let Z=ge(ue[0]);t.texStorage2D(s.TEXTURE_CUBE_MAP,oe,He,Z.width,Z.height)}for(let Z=0;Z<6;Z++)if($){De?I&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,ue[Z].width,ue[Z].height,Re,de,ue[Z].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,He,ue[Z].width,ue[Z].height,0,Re,de,ue[Z].data);for(let ce=0;ce<k.length;ce++){let Le=k[ce].image[Z].image;De?I&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce+1,0,0,Le.width,Le.height,Re,de,Le.data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce+1,He,Le.width,Le.height,0,Re,de,Le.data)}}else{De?I&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,0,0,Re,de,ue[Z]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,0,He,Re,de,ue[Z]);for(let ce=0;ce<k.length;ce++){let ae=k[ce];De?I&&t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce+1,0,0,Re,de,ae.image[Z]):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+Z,ce+1,He,Re,de,ae.image[Z])}}}m(x)&&f(s.TEXTURE_CUBE_MAP),H.__version=K.version,x.onUpdate&&x.onUpdate(x)}b.__version=x.version}function pe(b,x,F,Y,K,H){let me=r.convert(F.format,F.colorSpace),re=r.convert(F.type),Se=T(F.internalFormat,me,re,F.colorSpace),Te=n.get(x),$=n.get(F);if($.__renderTarget=x,!Te.__hasExternalTextures){let ue=Math.max(1,x.width>>H),Ee=Math.max(1,x.height>>H);K===s.TEXTURE_3D||K===s.TEXTURE_2D_ARRAY?t.texImage3D(K,H,Se,ue,Ee,x.depth,0,me,re,null):t.texImage2D(K,H,Se,ue,Ee,0,me,re,null)}t.bindFramebuffer(s.FRAMEBUFFER,b),Ve(x)?a.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,Y,K,$.__webglTexture,0,Ge(x)):(K===s.TEXTURE_2D||K>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&K<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,Y,K,$.__webglTexture,H),t.bindFramebuffer(s.FRAMEBUFFER,null)}function se(b,x,F){if(s.bindRenderbuffer(s.RENDERBUFFER,b),x.depthBuffer){let Y=x.depthTexture,K=Y&&Y.isDepthTexture?Y.type:null,H=M(x.stencilBuffer,K),me=x.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,re=Ge(x);Ve(x)?a.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,re,H,x.width,x.height):F?s.renderbufferStorageMultisample(s.RENDERBUFFER,re,H,x.width,x.height):s.renderbufferStorage(s.RENDERBUFFER,H,x.width,x.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,me,s.RENDERBUFFER,b)}else{let Y=x.textures;for(let K=0;K<Y.length;K++){let H=Y[K],me=r.convert(H.format,H.colorSpace),re=r.convert(H.type),Se=T(H.internalFormat,me,re,H.colorSpace),Te=Ge(x);F&&Ve(x)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,Te,Se,x.width,x.height):Ve(x)?a.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,Te,Se,x.width,x.height):s.renderbufferStorage(s.RENDERBUFFER,Se,x.width,x.height)}}s.bindRenderbuffer(s.RENDERBUFFER,null)}function Me(b,x){if(x&&x.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(s.FRAMEBUFFER,b),!(x.depthTexture&&x.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let Y=n.get(x.depthTexture);Y.__renderTarget=x,(!Y.__webglTexture||x.depthTexture.image.width!==x.width||x.depthTexture.image.height!==x.height)&&(x.depthTexture.image.width=x.width,x.depthTexture.image.height=x.height,x.depthTexture.needsUpdate=!0),J(x.depthTexture,0);let K=Y.__webglTexture,H=Ge(x);if(x.depthTexture.format===Gi)Ve(x)?a.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,K,0,H):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,K,0);else if(x.depthTexture.format===rs)Ve(x)?a.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,K,0,H):s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,K,0);else throw new Error("Unknown depthTexture format")}function Ye(b){let x=n.get(b),F=b.isWebGLCubeRenderTarget===!0;if(x.__boundDepthTexture!==b.depthTexture){let Y=b.depthTexture;if(x.__depthDisposeCallback&&x.__depthDisposeCallback(),Y){let K=()=>{delete x.__boundDepthTexture,delete x.__depthDisposeCallback,Y.removeEventListener("dispose",K)};Y.addEventListener("dispose",K),x.__depthDisposeCallback=K}x.__boundDepthTexture=Y}if(b.depthTexture&&!x.__autoAllocateDepthBuffer){if(F)throw new Error("target.depthTexture not supported in Cube render targets");let Y=b.texture.mipmaps;Y&&Y.length>0?Me(x.__webglFramebuffer[0],b):Me(x.__webglFramebuffer,b)}else if(F){x.__webglDepthbuffer=[];for(let Y=0;Y<6;Y++)if(t.bindFramebuffer(s.FRAMEBUFFER,x.__webglFramebuffer[Y]),x.__webglDepthbuffer[Y]===void 0)x.__webglDepthbuffer[Y]=s.createRenderbuffer(),se(x.__webglDepthbuffer[Y],b,!1);else{let K=b.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,H=x.__webglDepthbuffer[Y];s.bindRenderbuffer(s.RENDERBUFFER,H),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,H)}}else{let Y=b.texture.mipmaps;if(Y&&Y.length>0?t.bindFramebuffer(s.FRAMEBUFFER,x.__webglFramebuffer[0]):t.bindFramebuffer(s.FRAMEBUFFER,x.__webglFramebuffer),x.__webglDepthbuffer===void 0)x.__webglDepthbuffer=s.createRenderbuffer(),se(x.__webglDepthbuffer,b,!1);else{let K=b.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,H=x.__webglDepthbuffer;s.bindRenderbuffer(s.RENDERBUFFER,H),s.framebufferRenderbuffer(s.FRAMEBUFFER,K,s.RENDERBUFFER,H)}}t.bindFramebuffer(s.FRAMEBUFFER,null)}function Ae(b,x,F){let Y=n.get(b);x!==void 0&&pe(Y.__webglFramebuffer,b,b.texture,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,0),F!==void 0&&Ye(b)}function ct(b){let x=b.texture,F=n.get(b),Y=n.get(x);b.addEventListener("dispose",w);let K=b.textures,H=b.isWebGLCubeRenderTarget===!0,me=K.length>1;if(me||(Y.__webglTexture===void 0&&(Y.__webglTexture=s.createTexture()),Y.__version=x.version,o.memory.textures++),H){F.__webglFramebuffer=[];for(let re=0;re<6;re++)if(x.mipmaps&&x.mipmaps.length>0){F.__webglFramebuffer[re]=[];for(let Se=0;Se<x.mipmaps.length;Se++)F.__webglFramebuffer[re][Se]=s.createFramebuffer()}else F.__webglFramebuffer[re]=s.createFramebuffer()}else{if(x.mipmaps&&x.mipmaps.length>0){F.__webglFramebuffer=[];for(let re=0;re<x.mipmaps.length;re++)F.__webglFramebuffer[re]=s.createFramebuffer()}else F.__webglFramebuffer=s.createFramebuffer();if(me)for(let re=0,Se=K.length;re<Se;re++){let Te=n.get(K[re]);Te.__webglTexture===void 0&&(Te.__webglTexture=s.createTexture(),o.memory.textures++)}if(b.samples>0&&Ve(b)===!1){F.__webglMultisampledFramebuffer=s.createFramebuffer(),F.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,F.__webglMultisampledFramebuffer);for(let re=0;re<K.length;re++){let Se=K[re];F.__webglColorRenderbuffer[re]=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,F.__webglColorRenderbuffer[re]);let Te=r.convert(Se.format,Se.colorSpace),$=r.convert(Se.type),ue=T(Se.internalFormat,Te,$,Se.colorSpace,b.isXRRenderTarget===!0),Ee=Ge(b);s.renderbufferStorageMultisample(s.RENDERBUFFER,Ee,ue,b.width,b.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+re,s.RENDERBUFFER,F.__webglColorRenderbuffer[re])}s.bindRenderbuffer(s.RENDERBUFFER,null),b.depthBuffer&&(F.__webglDepthRenderbuffer=s.createRenderbuffer(),se(F.__webglDepthRenderbuffer,b,!0)),t.bindFramebuffer(s.FRAMEBUFFER,null)}}if(H){t.bindTexture(s.TEXTURE_CUBE_MAP,Y.__webglTexture),Ne(s.TEXTURE_CUBE_MAP,x);for(let re=0;re<6;re++)if(x.mipmaps&&x.mipmaps.length>0)for(let Se=0;Se<x.mipmaps.length;Se++)pe(F.__webglFramebuffer[re][Se],b,x,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+re,Se);else pe(F.__webglFramebuffer[re],b,x,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+re,0);m(x)&&f(s.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(me){for(let re=0,Se=K.length;re<Se;re++){let Te=K[re],$=n.get(Te);t.bindTexture(s.TEXTURE_2D,$.__webglTexture),Ne(s.TEXTURE_2D,Te),pe(F.__webglFramebuffer,b,Te,s.COLOR_ATTACHMENT0+re,s.TEXTURE_2D,0),m(Te)&&f(s.TEXTURE_2D)}t.unbindTexture()}else{let re=s.TEXTURE_2D;if((b.isWebGL3DRenderTarget||b.isWebGLArrayRenderTarget)&&(re=b.isWebGL3DRenderTarget?s.TEXTURE_3D:s.TEXTURE_2D_ARRAY),t.bindTexture(re,Y.__webglTexture),Ne(re,x),x.mipmaps&&x.mipmaps.length>0)for(let Se=0;Se<x.mipmaps.length;Se++)pe(F.__webglFramebuffer[Se],b,x,s.COLOR_ATTACHMENT0,re,Se);else pe(F.__webglFramebuffer,b,x,s.COLOR_ATTACHMENT0,re,0);m(x)&&f(re),t.unbindTexture()}b.depthBuffer&&Ye(b)}function st(b){let x=b.textures;for(let F=0,Y=x.length;F<Y;F++){let K=x[F];if(m(K)){let H=E(b),me=n.get(K).__webglTexture;t.bindTexture(H,me),f(H),t.unbindTexture()}}}let ke=[],A=[];function Gt(b){if(b.samples>0){if(Ve(b)===!1){let x=b.textures,F=b.width,Y=b.height,K=s.COLOR_BUFFER_BIT,H=b.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,me=n.get(b),re=x.length>1;if(re)for(let Te=0;Te<x.length;Te++)t.bindFramebuffer(s.FRAMEBUFFER,me.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Te,s.RENDERBUFFER,null),t.bindFramebuffer(s.FRAMEBUFFER,me.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Te,s.TEXTURE_2D,null,0);t.bindFramebuffer(s.READ_FRAMEBUFFER,me.__webglMultisampledFramebuffer);let Se=b.texture.mipmaps;Se&&Se.length>0?t.bindFramebuffer(s.DRAW_FRAMEBUFFER,me.__webglFramebuffer[0]):t.bindFramebuffer(s.DRAW_FRAMEBUFFER,me.__webglFramebuffer);for(let Te=0;Te<x.length;Te++){if(b.resolveDepthBuffer&&(b.depthBuffer&&(K|=s.DEPTH_BUFFER_BIT),b.stencilBuffer&&b.resolveStencilBuffer&&(K|=s.STENCIL_BUFFER_BIT)),re){s.framebufferRenderbuffer(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,me.__webglColorRenderbuffer[Te]);let $=n.get(x[Te]).__webglTexture;s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,$,0)}s.blitFramebuffer(0,0,F,Y,0,0,F,Y,K,s.NEAREST),c===!0&&(ke.length=0,A.length=0,ke.push(s.COLOR_ATTACHMENT0+Te),b.depthBuffer&&b.resolveDepthBuffer===!1&&(ke.push(H),A.push(H),s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,A)),s.invalidateFramebuffer(s.READ_FRAMEBUFFER,ke))}if(t.bindFramebuffer(s.READ_FRAMEBUFFER,null),t.bindFramebuffer(s.DRAW_FRAMEBUFFER,null),re)for(let Te=0;Te<x.length;Te++){t.bindFramebuffer(s.FRAMEBUFFER,me.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+Te,s.RENDERBUFFER,me.__webglColorRenderbuffer[Te]);let $=n.get(x[Te]).__webglTexture;t.bindFramebuffer(s.FRAMEBUFFER,me.__webglFramebuffer),s.framebufferTexture2D(s.DRAW_FRAMEBUFFER,s.COLOR_ATTACHMENT0+Te,s.TEXTURE_2D,$,0)}t.bindFramebuffer(s.DRAW_FRAMEBUFFER,me.__webglMultisampledFramebuffer)}else if(b.depthBuffer&&b.resolveDepthBuffer===!1&&c){let x=b.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,[x])}}}function Ge(b){return Math.min(i.maxSamples,b.samples)}function Ve(b){let x=n.get(b);return b.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&x.__useRenderToTexture!==!1}function xe(b){let x=o.render.frame;h.get(b)!==x&&(h.set(b,x),b.update())}function nt(b,x){let F=b.colorSpace,Y=b.format,K=b.type;return b.isCompressedTexture===!0||b.isVideoTexture===!0||F!==vt&&F!==On&&(Be.getTransfer(F)===je?(Y!==Ht||K!==hn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",F)),x}function ge(b){return typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement?(l.width=b.naturalWidth||b.width,l.height=b.naturalHeight||b.height):typeof VideoFrame<"u"&&b instanceof VideoFrame?(l.width=b.displayWidth,l.height=b.displayHeight):(l.width=b.width,l.height=b.height),l}this.allocateTextureUnit=z,this.resetTextureUnits=q,this.setTexture2D=J,this.setTexture2DArray=G,this.setTexture3D=Q,this.setTextureCube=V,this.rebindTextures=Ae,this.setupRenderTarget=ct,this.updateRenderTargetMipmap=st,this.updateMultisampleRenderTarget=Gt,this.setupDepthRenderbuffer=Ye,this.setupFrameBufferTexture=pe,this.useMultisampledRTT=Ve}function Jg(s,e){function t(n,i=On){let r,o=Be.getTransfer(i);if(n===hn)return s.UNSIGNED_BYTE;if(n===po)return s.UNSIGNED_SHORT_4_4_4_4;if(n===mo)return s.UNSIGNED_SHORT_5_5_5_1;if(n===Xa)return s.UNSIGNED_INT_5_9_9_9_REV;if(n===Ga)return s.BYTE;if(n===Wa)return s.SHORT;if(n===ns)return s.UNSIGNED_SHORT;if(n===fo)return s.INT;if(n===Jn)return s.UNSIGNED_INT;if(n===Zt)return s.FLOAT;if(n===is)return s.HALF_FLOAT;if(n===qa)return s.ALPHA;if(n===Ya)return s.RGB;if(n===Ht)return s.RGBA;if(n===Gi)return s.DEPTH_COMPONENT;if(n===rs)return s.DEPTH_STENCIL;if(n===go)return s.RED;if(n===_o)return s.RED_INTEGER;if(n===Za)return s.RG;if(n===xo)return s.RG_INTEGER;if(n===yo)return s.RGBA_INTEGER;if(n===Qs||n===er||n===tr||n===nr)if(o===je)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Qs)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===er)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===tr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===nr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Qs)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===er)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===tr)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===nr)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===vo||n===Mo||n===So||n===bo)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===vo)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Mo)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===So)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===bo)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===To||n===Eo||n===Ao)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===To||n===Eo)return o===je?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Ao)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===wo||n===Ro||n===Co||n===Io||n===Po||n===Lo||n===Do||n===Uo||n===No||n===Fo||n===Oo||n===Bo||n===zo||n===ko)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===wo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Ro)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Co)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Io)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Po)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Lo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Do)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Uo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===No)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Fo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Oo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Bo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===zo)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ko)return o===je?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===ir||n===Vo||n===Ho)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===ir)return o===je?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Vo)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Ho)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Ka||n===Go||n===Wo||n===Xo)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===ir)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Go)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Wo)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Xo)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===ss?s.UNSIGNED_INT_24_8:s[n]!==void 0?s[n]:null}return{convert:t}}var $g=`+void main() {++ gl_Position = vec4( position, 1.0 );++}`,jg=`+uniform sampler2DArray depthColor;+uniform float depthWidth;+uniform float depthHeight;++void main() {++ vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );++ if ( coord.x >= 1.0 ) {++ gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;++ } else {++ gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;++ }++}`,yc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){let i=new _t,r=e.properties.get(i);r.__webglTexture=t.texture,(t.depthNear!==n.depthNear||t.depthFar!==n.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new cn({vertexShader:$g,fragmentShader:jg,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Mt(new Vs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},vc=class extends pn{constructor(e,t){super();let n=this,i=null,r=1,o=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,p=null,g=null,_=new yc,m=t.getContextAttributes(),f=null,E=null,T=[],M=[],L=new ze,R=null,w=new dt;w.viewport=new qe;let N=new dt;N.viewport=new qe;let S=[w,N],v=new jr,C=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(X){let ee=T[X];return ee===void 0&&(ee=new Yi,T[X]=ee),ee.getTargetRaySpace()},this.getControllerGrip=function(X){let ee=T[X];return ee===void 0&&(ee=new Yi,T[X]=ee),ee.getGripSpace()},this.getHand=function(X){let ee=T[X];return ee===void 0&&(ee=new Yi,T[X]=ee),ee.getHandSpace()};function z(X){let ee=M.indexOf(X.inputSource);if(ee===-1)return;let pe=T[ee];pe!==void 0&&(pe.update(X.inputSource,X.frame,l||o),pe.dispatchEvent({type:X.type,data:X.inputSource}))}function W(){i.removeEventListener("select",z),i.removeEventListener("selectstart",z),i.removeEventListener("selectend",z),i.removeEventListener("squeeze",z),i.removeEventListener("squeezestart",z),i.removeEventListener("squeezeend",z),i.removeEventListener("end",W),i.removeEventListener("inputsourceschange",J);for(let X=0;X<T.length;X++){let ee=M[X];ee!==null&&(M[X]=null,T[X].disconnect(ee))}C=null,q=null,_.reset(),e.setRenderTarget(f),p=null,d=null,u=null,i=null,E=null,et.stop(),n.isPresenting=!1,e.setPixelRatio(R),e.setSize(L.width,L.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(X){r=X,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(X){a=X,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(X){l=X},this.getBaseLayer=function(){return d!==null?d:p},this.getBinding=function(){return u},this.getFrame=function(){return g},this.getSession=function(){return i},this.setSession=async function(X){if(i=X,i!==null){if(f=e.getRenderTarget(),i.addEventListener("select",z),i.addEventListener("selectstart",z),i.addEventListener("selectend",z),i.addEventListener("squeeze",z),i.addEventListener("squeezestart",z),i.addEventListener("squeezeend",z),i.addEventListener("end",W),i.addEventListener("inputsourceschange",J),m.xrCompatible!==!0&&await t.makeXRCompatible(),R=e.getPixelRatio(),e.getSize(L),typeof XRWebGLBinding<"u"&&"createProjectionLayer"in XRWebGLBinding.prototype){let pe=null,se=null,Me=null;m.depth&&(Me=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,pe=m.stencil?rs:Gi,se=m.stencil?ss:Jn);let Ye={colorFormat:t.RGBA8,depthFormat:Me,scaleFactor:r};u=new XRWebGLBinding(i,t),d=u.createProjectionLayer(Ye),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),E=new mn(d.textureWidth,d.textureHeight,{format:Ht,type:hn,depthTexture:new ks(d.textureWidth,d.textureHeight,se,void 0,void 0,void 0,void 0,void 0,void 0,pe),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let pe={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};p=new XRWebGLLayer(i,t,pe),i.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),E=new mn(p.framebufferWidth,p.framebufferHeight,{format:Ht,type:hn,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}E.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await i.requestReferenceSpace(a),et.setContext(i),et.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return _.getDepthTexture()};function J(X){for(let ee=0;ee<X.removed.length;ee++){let pe=X.removed[ee],se=M.indexOf(pe);se>=0&&(M[se]=null,T[se].disconnect(pe))}for(let ee=0;ee<X.added.length;ee++){let pe=X.added[ee],se=M.indexOf(pe);if(se===-1){for(let Ye=0;Ye<T.length;Ye++)if(Ye>=M.length){M.push(pe),se=Ye;break}else if(M[Ye]===null){M[Ye]=pe,se=Ye;break}if(se===-1)break}let Me=T[se];Me&&Me.connect(pe)}}let G=new P,Q=new P;function V(X,ee,pe){G.setFromMatrixPosition(ee.matrixWorld),Q.setFromMatrixPosition(pe.matrixWorld);let se=G.distanceTo(Q),Me=ee.projectionMatrix.elements,Ye=pe.projectionMatrix.elements,Ae=Me[14]/(Me[10]-1),ct=Me[14]/(Me[10]+1),st=(Me[9]+1)/Me[5],ke=(Me[9]-1)/Me[5],A=(Me[8]-1)/Me[0],Gt=(Ye[8]+1)/Ye[0],Ge=Ae*A,Ve=Ae*Gt,xe=se/(-A+Gt),nt=xe*-A;if(ee.matrixWorld.decompose(X.position,X.quaternion,X.scale),X.translateX(nt),X.translateZ(xe),X.matrixWorld.compose(X.position,X.quaternion,X.scale),X.matrixWorldInverse.copy(X.matrixWorld).invert(),Me[10]===-1)X.projectionMatrix.copy(ee.projectionMatrix),X.projectionMatrixInverse.copy(ee.projectionMatrixInverse);else{let ge=Ae+xe,b=ct+xe,x=Ge-nt,F=Ve+(se-nt),Y=st*ct/b*ge,K=ke*ct/b*ge;X.projectionMatrix.makePerspective(x,F,Y,K,ge,b),X.projectionMatrixInverse.copy(X.projectionMatrix).invert()}}function ie(X,ee){ee===null?X.matrixWorld.copy(X.matrix):X.matrixWorld.multiplyMatrices(ee.matrixWorld,X.matrix),X.matrixWorldInverse.copy(X.matrixWorld).invert()}this.updateCamera=function(X){if(i===null)return;let ee=X.near,pe=X.far;_.texture!==null&&(_.depthNear>0&&(ee=_.depthNear),_.depthFar>0&&(pe=_.depthFar)),v.near=N.near=w.near=ee,v.far=N.far=w.far=pe,(C!==v.near||q!==v.far)&&(i.updateRenderState({depthNear:v.near,depthFar:v.far}),C=v.near,q=v.far),w.layers.mask=X.layers.mask|2,N.layers.mask=X.layers.mask|4,v.layers.mask=w.layers.mask|N.layers.mask;let se=X.parent,Me=v.cameras;ie(v,se);for(let Ye=0;Ye<Me.length;Ye++)ie(Me[Ye],se);Me.length===2?V(v,w,N):v.projectionMatrix.copy(w.projectionMatrix),he(X,v,se)};function he(X,ee,pe){pe===null?X.matrix.copy(ee.matrixWorld):(X.matrix.copy(pe.matrixWorld),X.matrix.invert(),X.matrix.multiply(ee.matrixWorld)),X.matrix.decompose(X.position,X.quaternion,X.scale),X.updateMatrixWorld(!0),X.projectionMatrix.copy(ee.projectionMatrix),X.projectionMatrixInverse.copy(ee.projectionMatrixInverse),X.isPerspectiveCamera&&(X.fov=ui*2*Math.atan(1/X.projectionMatrix.elements[5]),X.zoom=1)}this.getCamera=function(){return v},this.getFoveation=function(){if(!(d===null&&p===null))return c},this.setFoveation=function(X){c=X,d!==null&&(d.fixedFoveation=X),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=X)},this.hasDepthSensing=function(){return _.texture!==null},this.getDepthSensingMesh=function(){return _.getMesh(v)};let _e=null;function Ne(X,ee){if(h=ee.getViewerPose(l||o),g=ee,h!==null){let pe=h.views;p!==null&&(e.setRenderTargetFramebuffer(E,p.framebuffer),e.setRenderTarget(E));let se=!1;pe.length!==v.cameras.length&&(v.cameras.length=0,se=!0);for(let Ae=0;Ae<pe.length;Ae++){let ct=pe[Ae],st=null;if(p!==null)st=p.getViewport(ct);else{let A=u.getViewSubImage(d,ct);st=A.viewport,Ae===0&&(e.setRenderTargetTextures(E,A.colorTexture,A.depthStencilTexture),e.setRenderTarget(E))}let ke=S[Ae];ke===void 0&&(ke=new dt,ke.layers.enable(Ae),ke.viewport=new qe,S[Ae]=ke),ke.matrix.fromArray(ct.transform.matrix),ke.matrix.decompose(ke.position,ke.quaternion,ke.scale),ke.projectionMatrix.fromArray(ct.projectionMatrix),ke.projectionMatrixInverse.copy(ke.projectionMatrix).invert(),ke.viewport.set(st.x,st.y,st.width,st.height),Ae===0&&(v.matrix.copy(ke.matrix),v.matrix.decompose(v.position,v.quaternion,v.scale)),se===!0&&v.cameras.push(ke)}let Me=i.enabledFeatures;if(Me&&Me.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&u){let Ae=u.getDepthInformation(pe[0]);Ae&&Ae.isValid&&Ae.texture&&_.init(e,Ae,i.renderState)}}for(let pe=0;pe<T.length;pe++){let se=M[pe],Me=T[pe];se!==null&&Me!==void 0&&Me.update(se,ee,l||o)}_e&&_e(X,ee),ee.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ee}),g=null}let et=new hu;et.setAnimationLoop(Ne),this.setAnimationLoop=function(X){_e=X},this.dispose=function(){}}},bi=new on,Qg=new Ie;function e_(s,e){function t(m,f){m.matrixAutoUpdate===!0&&m.updateMatrix(),f.value.copy(m.matrix)}function n(m,f){f.color.getRGB(m.fogColor.value,ic(s)),f.isFog?(m.fogNear.value=f.near,m.fogFar.value=f.far):f.isFogExp2&&(m.fogDensity.value=f.density)}function i(m,f,E,T,M){f.isMeshBasicMaterial||f.isMeshLambertMaterial?r(m,f):f.isMeshToonMaterial?(r(m,f),u(m,f)):f.isMeshPhongMaterial?(r(m,f),h(m,f)):f.isMeshStandardMaterial?(r(m,f),d(m,f),f.isMeshPhysicalMaterial&&p(m,f,M)):f.isMeshMatcapMaterial?(r(m,f),g(m,f)):f.isMeshDepthMaterial?r(m,f):f.isMeshDistanceMaterial?(r(m,f),_(m,f)):f.isMeshNormalMaterial?r(m,f):f.isLineBasicMaterial?(o(m,f),f.isLineDashedMaterial&&a(m,f)):f.isPointsMaterial?c(m,f,E,T):f.isSpriteMaterial?l(m,f):f.isShadowMaterial?(m.color.value.copy(f.color),m.opacity.value=f.opacity):f.isShaderMaterial&&(f.uniformsNeedUpdate=!1)}function r(m,f){m.opacity.value=f.opacity,f.color&&m.diffuse.value.copy(f.color),f.emissive&&m.emissive.value.copy(f.emissive).multiplyScalar(f.emissiveIntensity),f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.bumpMap&&(m.bumpMap.value=f.bumpMap,t(f.bumpMap,m.bumpMapTransform),m.bumpScale.value=f.bumpScale,f.side===Pt&&(m.bumpScale.value*=-1)),f.normalMap&&(m.normalMap.value=f.normalMap,t(f.normalMap,m.normalMapTransform),m.normalScale.value.copy(f.normalScale),f.side===Pt&&m.normalScale.value.negate()),f.displacementMap&&(m.displacementMap.value=f.displacementMap,t(f.displacementMap,m.displacementMapTransform),m.displacementScale.value=f.displacementScale,m.displacementBias.value=f.displacementBias),f.emissiveMap&&(m.emissiveMap.value=f.emissiveMap,t(f.emissiveMap,m.emissiveMapTransform)),f.specularMap&&(m.specularMap.value=f.specularMap,t(f.specularMap,m.specularMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest);let E=e.get(f),T=E.envMap,M=E.envMapRotation;T&&(m.envMap.value=T,bi.copy(M),bi.x*=-1,bi.y*=-1,bi.z*=-1,T.isCubeTexture&&T.isRenderTargetTexture===!1&&(bi.y*=-1,bi.z*=-1),m.envMapRotation.value.setFromMatrix4(Qg.makeRotationFromEuler(bi)),m.flipEnvMap.value=T.isCubeTexture&&T.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,t(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,t(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function c(m,f,E,T){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*E,m.scale.value=T*.5,f.map&&(m.map.value=f.map,t(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function l(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function u(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function d(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,t(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,t(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,E){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,t(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,t(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,t(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,t(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,t(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===Pt&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,t(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,t(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=E.texture,m.transmissionSamplerSize.value.set(E.width,E.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,t(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,t(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,t(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,t(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,t(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function _(m,f){let E=e.get(f).light;m.referencePosition.value.setFromMatrixPosition(E.matrixWorld),m.nearDistance.value=E.shadow.camera.near,m.farDistance.value=E.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function t_(s,e,t,n){let i={},r={},o=[],a=s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS);function c(E,T){let M=T.program;n.uniformBlockBinding(E,M)}function l(E,T){let M=i[E.id];M===void 0&&(g(E),M=h(E),i[E.id]=M,E.addEventListener("dispose",m));let L=T.program;n.updateUBOMapping(E,L);let R=e.render.frame;r[E.id]!==R&&(d(E),r[E.id]=R)}function h(E){let T=u();E.__bindingPointIndex=T;let M=s.createBuffer(),L=E.__size,R=E.usage;return s.bindBuffer(s.UNIFORM_BUFFER,M),s.bufferData(s.UNIFORM_BUFFER,L,R),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,T,M),M}function u(){for(let E=0;E<a;E++)if(o.indexOf(E)===-1)return o.push(E),E;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(E){let T=i[E.id],M=E.uniforms,L=E.__cache;s.bindBuffer(s.UNIFORM_BUFFER,T);for(let R=0,w=M.length;R<w;R++){let N=Array.isArray(M[R])?M[R]:[M[R]];for(let S=0,v=N.length;S<v;S++){let C=N[S];if(p(C,R,S,L)===!0){let q=C.__offset,z=Array.isArray(C.value)?C.value:[C.value],W=0;for(let J=0;J<z.length;J++){let G=z[J],Q=_(G);typeof G=="number"||typeof G=="boolean"?(C.__data[0]=G,s.bufferSubData(s.UNIFORM_BUFFER,q+W,C.__data)):G.isMatrix3?(C.__data[0]=G.elements[0],C.__data[1]=G.elements[1],C.__data[2]=G.elements[2],C.__data[3]=0,C.__data[4]=G.elements[3],C.__data[5]=G.elements[4],C.__data[6]=G.elements[5],C.__data[7]=0,C.__data[8]=G.elements[6],C.__data[9]=G.elements[7],C.__data[10]=G.elements[8],C.__data[11]=0):(G.toArray(C.__data,W),W+=Q.storage/Float32Array.BYTES_PER_ELEMENT)}s.bufferSubData(s.UNIFORM_BUFFER,q,C.__data)}}}s.bindBuffer(s.UNIFORM_BUFFER,null)}function p(E,T,M,L){let R=E.value,w=T+"_"+M;if(L[w]===void 0)return typeof R=="number"||typeof R=="boolean"?L[w]=R:L[w]=R.clone(),!0;{let N=L[w];if(typeof R=="number"||typeof R=="boolean"){if(N!==R)return L[w]=R,!0}else if(N.equals(R)===!1)return N.copy(R),!0}return!1}function g(E){let T=E.uniforms,M=0,L=16;for(let w=0,N=T.length;w<N;w++){let S=Array.isArray(T[w])?T[w]:[T[w]];for(let v=0,C=S.length;v<C;v++){let q=S[v],z=Array.isArray(q.value)?q.value:[q.value];for(let W=0,J=z.length;W<J;W++){let G=z[W],Q=_(G),V=M%L,ie=V%Q.boundary,he=V+ie;M+=ie,he!==0&&L-he<Q.storage&&(M+=L-he),q.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),q.__offset=M,M+=Q.storage}}}let R=M%L;return R>0&&(M+=L-R),E.__size=M,E.__cache={},this}function _(E){let T={boundary:0,storage:0};return typeof E=="number"||typeof E=="boolean"?(T.boundary=4,T.storage=4):E.isVector2?(T.boundary=8,T.storage=8):E.isVector3||E.isColor?(T.boundary=16,T.storage=12):E.isVector4?(T.boundary=16,T.storage=16):E.isMatrix3?(T.boundary=48,T.storage=48):E.isMatrix4?(T.boundary=64,T.storage=64):E.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",E),T}function m(E){let T=E.target;T.removeEventListener("dispose",m);let M=o.indexOf(T.__bindingPointIndex);o.splice(M,1),s.deleteBuffer(i[T.id]),delete i[T.id],delete r[T.id]}function f(){for(let E in i)s.deleteBuffer(i[E]);o=[],i={},r={}}return{bind:c,update:l,dispose:f}}var $o=class{constructor(e={}){let{canvas:t=Dh(),context:n=null,depth:i=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=o;let g=new Uint32Array(4),_=new Int32Array(4),m=null,f=null,E=[],T=[];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=Fn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let M=this,L=!1;this._outputColorSpace=lt;let R=0,w=0,N=null,S=-1,v=null,C=new qe,q=new qe,z=null,W=new be(0),J=0,G=t.width,Q=t.height,V=1,ie=null,he=null,_e=new qe(0,0,G,Q),Ne=new qe(0,0,G,Q),et=!1,X=new $i,ee=!1,pe=!1,se=new Ie,Me=new Ie,Ye=new P,Ae=new qe,ct={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},st=!1;function ke(){return N===null?V:1}let A=n;function Gt(y,D){return t.getContext(y,D)}try{let y={alpha:!0,depth:i,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"176"}`),t.addEventListener("webglcontextlost",Z,!1),t.addEventListener("webglcontextrestored",ce,!1),t.addEventListener("webglcontextcreationerror",ae,!1),A===null){let D="webgl2";if(A=Gt(D,y),A===null)throw Gt(D)?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 Ge,Ve,xe,nt,ge,b,x,F,Y,K,H,me,re,Se,Te,$,ue,Ee,Re,de,He,De,tt,I;function oe(){Ge=new ym(A),Ge.init(),De=new Jg(A,Ge),Ve=new dm(A,Ge,e,De),xe=new Zg(A,Ge),Ve.reverseDepthBuffer&&d&&xe.buffers.depth.setReversed(!0),nt=new Sm(A),ge=new Ng,b=new Kg(A,Ge,xe,ge,Ve,De,nt),x=new pm(M),F=new xm(M),Y=new wd(A),tt=new hm(A,Y),K=new vm(A,Y,nt,tt),H=new Tm(A,K,Y,nt),Re=new bm(A,Ve,b),$=new fm(ge),me=new Ug(M,x,F,Ge,Ve,tt,$),re=new e_(M,ge),Se=new Og,Te=new Gg(Ge),Ee=new lm(M,x,F,xe,H,p,c),ue=new qg(M,H,Ve),I=new t_(A,nt,Ve,xe),de=new um(A,Ge,nt),He=new Mm(A,Ge,nt),nt.programs=me.programs,M.capabilities=Ve,M.extensions=Ge,M.properties=ge,M.renderLists=Se,M.shadowMap=ue,M.state=xe,M.info=nt}oe();let k=new vc(M,A);this.xr=k,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){let y=Ge.get("WEBGL_lose_context");y&&y.loseContext()},this.forceContextRestore=function(){let y=Ge.get("WEBGL_lose_context");y&&y.restoreContext()},this.getPixelRatio=function(){return V},this.setPixelRatio=function(y){y!==void 0&&(V=y,this.setSize(G,Q,!1))},this.getSize=function(y){return y.set(G,Q)},this.setSize=function(y,D,O=!0){if(k.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}G=y,Q=D,t.width=Math.floor(y*V),t.height=Math.floor(D*V),O===!0&&(t.style.width=y+"px",t.style.height=D+"px"),this.setViewport(0,0,y,D)},this.getDrawingBufferSize=function(y){return y.set(G*V,Q*V).floor()},this.setDrawingBufferSize=function(y,D,O){G=y,Q=D,V=O,t.width=Math.floor(y*O),t.height=Math.floor(D*O),this.setViewport(0,0,y,D)},this.getCurrentViewport=function(y){return y.copy(C)},this.getViewport=function(y){return y.copy(_e)},this.setViewport=function(y,D,O,B){y.isVector4?_e.set(y.x,y.y,y.z,y.w):_e.set(y,D,O,B),xe.viewport(C.copy(_e).multiplyScalar(V).round())},this.getScissor=function(y){return y.copy(Ne)},this.setScissor=function(y,D,O,B){y.isVector4?Ne.set(y.x,y.y,y.z,y.w):Ne.set(y,D,O,B),xe.scissor(q.copy(Ne).multiplyScalar(V).round())},this.getScissorTest=function(){return et},this.setScissorTest=function(y){xe.setScissorTest(et=y)},this.setOpaqueSort=function(y){ie=y},this.setTransparentSort=function(y){he=y},this.getClearColor=function(y){return y.copy(Ee.getClearColor())},this.setClearColor=function(){Ee.setClearColor(...arguments)},this.getClearAlpha=function(){return Ee.getClearAlpha()},this.setClearAlpha=function(){Ee.setClearAlpha(...arguments)},this.clear=function(y=!0,D=!0,O=!0){let B=0;if(y){let U=!1;if(N!==null){let j=N.texture.format;U=j===yo||j===xo||j===_o}if(U){let j=N.texture.type,ne=j===hn||j===Jn||j===ns||j===ss||j===po||j===mo,le=Ee.getClearColor(),fe=Ee.getClearAlpha(),Ce=le.r,we=le.g,ye=le.b;ne?(g[0]=Ce,g[1]=we,g[2]=ye,g[3]=fe,A.clearBufferuiv(A.COLOR,0,g)):(_[0]=Ce,_[1]=we,_[2]=ye,_[3]=fe,A.clearBufferiv(A.COLOR,0,_))}else B|=A.COLOR_BUFFER_BIT}D&&(B|=A.DEPTH_BUFFER_BIT),O&&(B|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),A.clear(B)},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",Z,!1),t.removeEventListener("webglcontextrestored",ce,!1),t.removeEventListener("webglcontextcreationerror",ae,!1),Ee.dispose(),Se.dispose(),Te.dispose(),ge.dispose(),x.dispose(),F.dispose(),H.dispose(),tt.dispose(),I.dispose(),me.dispose(),k.dispose(),k.removeEventListener("sessionstart",Qc),k.removeEventListener("sessionend",el),jn.stop()};function Z(y){y.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),L=!0}function ce(){console.log("THREE.WebGLRenderer: Context Restored."),L=!1;let y=nt.autoReset,D=ue.enabled,O=ue.autoUpdate,B=ue.needsUpdate,U=ue.type;oe(),nt.autoReset=y,ue.enabled=D,ue.autoUpdate=O,ue.needsUpdate=B,ue.type=U}function ae(y){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",y.statusMessage)}function Le(y){let D=y.target;D.removeEventListener("dispose",Le),ot(D)}function ot(y){St(y),ge.remove(y)}function St(y){let D=ge.get(y).programs;D!==void 0&&(D.forEach(function(O){me.releaseProgram(O)}),y.isShaderMaterial&&me.releaseShaderCache(y))}this.renderBufferDirect=function(y,D,O,B,U,j){D===null&&(D=ct);let ne=U.isMesh&&U.matrixWorld.determinant()<0,le=Mu(y,D,O,B,U);xe.setMaterial(B,ne);let fe=O.index,Ce=1;if(B.wireframe===!0){if(fe=K.getWireframeAttribute(O),fe===void 0)return;Ce=2}let we=O.drawRange,ye=O.attributes.position,We=we.start*Ce,Ze=(we.start+we.count)*Ce;j!==null&&(We=Math.max(We,j.start*Ce),Ze=Math.min(Ze,(j.start+j.count)*Ce)),fe!==null?(We=Math.max(We,0),Ze=Math.min(Ze,fe.count)):ye!=null&&(We=Math.max(We,0),Ze=Math.min(Ze,ye.count));let ht=Ze-We;if(ht<0||ht===1/0)return;tt.setup(U,B,le,O,fe);let at,Xe=de;if(fe!==null&&(at=Y.get(fe),Xe=He,Xe.setIndex(at)),U.isMesh)B.wireframe===!0?(xe.setLineWidth(B.wireframeLinewidth*ke()),Xe.setMode(A.LINES)):Xe.setMode(A.TRIANGLES);else if(U.isLine){let ve=B.linewidth;ve===void 0&&(ve=1),xe.setLineWidth(ve*ke()),U.isLineSegments?Xe.setMode(A.LINES):U.isLineLoop?Xe.setMode(A.LINE_LOOP):Xe.setMode(A.LINE_STRIP)}else U.isPoints?Xe.setMode(A.POINTS):U.isSprite&&Xe.setMode(A.TRIANGLES);if(U.isBatchedMesh)if(U._multiDrawInstances!==null)rr("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Xe.renderMultiDrawInstances(U._multiDrawStarts,U._multiDrawCounts,U._multiDrawCount,U._multiDrawInstances);else if(Ge.get("WEBGL_multi_draw"))Xe.renderMultiDraw(U._multiDrawStarts,U._multiDrawCounts,U._multiDrawCount);else{let ve=U._multiDrawStarts,xt=U._multiDrawCounts,Ke=U._multiDrawCount,$t=fe?Y.get(fe).bytesPerElement:1,wi=ge.get(B).currentProgram.getUniforms();for(let Ot=0;Ot<Ke;Ot++)wi.setValue(A,"_gl_DrawID",Ot),Xe.render(ve[Ot]/$t,xt[Ot])}else if(U.isInstancedMesh)Xe.renderInstances(We,ht,U.count);else if(O.isInstancedBufferGeometry){let ve=O._maxInstanceCount!==void 0?O._maxInstanceCount:1/0,xt=Math.min(O.instanceCount,ve);Xe.renderInstances(We,ht,xt)}else Xe.render(We,ht)};function Je(y,D,O){y.transparent===!0&&y.side===Yt&&y.forceSinglePass===!1?(y.side=Pt,y.needsUpdate=!0,lr(y,D,O),y.side=rn,y.needsUpdate=!0,lr(y,D,O),y.side=Yt):lr(y,D,O)}this.compile=function(y,D,O=null){O===null&&(O=y),f=Te.get(O),f.init(D),T.push(f),O.traverseVisible(function(U){U.isLight&&U.layers.test(D.layers)&&(f.pushLight(U),U.castShadow&&f.pushShadow(U))}),y!==O&&y.traverseVisible(function(U){U.isLight&&U.layers.test(D.layers)&&(f.pushLight(U),U.castShadow&&f.pushShadow(U))}),f.setupLights();let B=new Set;return y.traverse(function(U){if(!(U.isMesh||U.isPoints||U.isLine||U.isSprite))return;let j=U.material;if(j)if(Array.isArray(j))for(let ne=0;ne<j.length;ne++){let le=j[ne];Je(le,O,U),B.add(le)}else Je(j,O,U),B.add(j)}),f=T.pop(),B},this.compileAsync=function(y,D,O=null){let B=this.compile(y,D,O);return new Promise(U=>{function j(){if(B.forEach(function(ne){ge.get(ne).currentProgram.isReady()&&B.delete(ne)}),B.size===0){U(y);return}setTimeout(j,10)}Ge.get("KHR_parallel_shader_compile")!==null?j():setTimeout(j,10)})};let Jt=null;function Sn(y){Jt&&Jt(y)}function Qc(){jn.stop()}function el(){jn.start()}let jn=new hu;jn.setAnimationLoop(Sn),typeof self<"u"&&jn.setContext(self),this.setAnimationLoop=function(y){Jt=y,k.setAnimationLoop(y),y===null?jn.stop():jn.start()},k.addEventListener("sessionstart",Qc),k.addEventListener("sessionend",el),this.render=function(y,D){if(D!==void 0&&D.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;if(y.matrixWorldAutoUpdate===!0&&y.updateMatrixWorld(),D.parent===null&&D.matrixWorldAutoUpdate===!0&&D.updateMatrixWorld(),k.enabled===!0&&k.isPresenting===!0&&(k.cameraAutoUpdate===!0&&k.updateCamera(D),D=k.getCamera()),y.isScene===!0&&y.onBeforeRender(M,y,D,N),f=Te.get(y,T.length),f.init(D),T.push(f),Me.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),X.setFromProjectionMatrix(Me),pe=this.localClippingEnabled,ee=$.init(this.clippingPlanes,pe),m=Se.get(y,E.length),m.init(),E.push(m),k.enabled===!0&&k.isPresenting===!0){let j=M.xr.getDepthSensingMesh();j!==null&&ta(j,D,-1/0,M.sortObjects)}ta(y,D,0,M.sortObjects),m.finish(),M.sortObjects===!0&&m.sort(ie,he),st=k.enabled===!1||k.isPresenting===!1||k.hasDepthSensing()===!1,st&&Ee.addToRenderList(m,y),this.info.render.frame++,ee===!0&&$.beginShadows();let O=f.state.shadowsArray;ue.render(O,y,D),ee===!0&&$.endShadows(),this.info.autoReset===!0&&this.info.reset();let B=m.opaque,U=m.transmissive;if(f.setupLights(),D.isArrayCamera){let j=D.cameras;if(U.length>0)for(let ne=0,le=j.length;ne<le;ne++){let fe=j[ne];nl(B,U,y,fe)}st&&Ee.render(y);for(let ne=0,le=j.length;ne<le;ne++){let fe=j[ne];tl(m,y,fe,fe.viewport)}}else U.length>0&&nl(B,U,y,D),st&&Ee.render(y),tl(m,y,D);N!==null&&w===0&&(b.updateMultisampleRenderTarget(N),b.updateRenderTargetMipmap(N)),y.isScene===!0&&y.onAfterRender(M,y,D),tt.resetDefaultState(),S=-1,v=null,T.pop(),T.length>0?(f=T[T.length-1],ee===!0&&$.setGlobalState(M.clippingPlanes,f.state.camera)):f=null,E.pop(),E.length>0?m=E[E.length-1]:m=null};function ta(y,D,O,B){if(y.visible===!1)return;if(y.layers.test(D.layers)){if(y.isGroup)O=y.renderOrder;else if(y.isLOD)y.autoUpdate===!0&&y.update(D);else if(y.isLight)f.pushLight(y),y.castShadow&&f.pushShadow(y);else if(y.isSprite){if(!y.frustumCulled||X.intersectsSprite(y)){B&&Ae.setFromMatrixPosition(y.matrixWorld).applyMatrix4(Me);let ne=H.update(y),le=y.material;le.visible&&m.push(y,ne,le,O,Ae.z,null)}}else if((y.isMesh||y.isLine||y.isPoints)&&(!y.frustumCulled||X.intersectsObject(y))){let ne=H.update(y),le=y.material;if(B&&(y.boundingSphere!==void 0?(y.boundingSphere===null&&y.computeBoundingSphere(),Ae.copy(y.boundingSphere.center)):(ne.boundingSphere===null&&ne.computeBoundingSphere(),Ae.copy(ne.boundingSphere.center)),Ae.applyMatrix4(y.matrixWorld).applyMatrix4(Me)),Array.isArray(le)){let fe=ne.groups;for(let Ce=0,we=fe.length;Ce<we;Ce++){let ye=fe[Ce],We=le[ye.materialIndex];We&&We.visible&&m.push(y,ne,We,O,Ae.z,ye)}}else le.visible&&m.push(y,ne,le,O,Ae.z,null)}}let j=y.children;for(let ne=0,le=j.length;ne<le;ne++)ta(j[ne],D,O,B)}function tl(y,D,O,B){let U=y.opaque,j=y.transmissive,ne=y.transparent;f.setupLightsView(O),ee===!0&&$.setGlobalState(M.clippingPlanes,O),B&&xe.viewport(C.copy(B)),U.length>0&&cr(U,D,O),j.length>0&&cr(j,D,O),ne.length>0&&cr(ne,D,O),xe.buffers.depth.setTest(!0),xe.buffers.depth.setMask(!0),xe.buffers.color.setMask(!0),xe.setPolygonOffset(!1)}function nl(y,D,O,B){if((O.isScene===!0?O.overrideMaterial:null)!==null)return;f.state.transmissionRenderTarget[B.id]===void 0&&(f.state.transmissionRenderTarget[B.id]=new mn(1,1,{generateMipmaps:!0,type:Ge.has("EXT_color_buffer_half_float")||Ge.has("EXT_color_buffer_float")?is:hn,minFilter:ln,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Be.workingColorSpace}));let j=f.state.transmissionRenderTarget[B.id],ne=B.viewport||C;j.setSize(ne.z*M.transmissionResolutionScale,ne.w*M.transmissionResolutionScale);let le=M.getRenderTarget();M.setRenderTarget(j),M.getClearColor(W),J=M.getClearAlpha(),J<1&&M.setClearColor(16777215,.5),M.clear(),st&&Ee.render(O);let fe=M.toneMapping;M.toneMapping=Fn;let Ce=B.viewport;if(B.viewport!==void 0&&(B.viewport=void 0),f.setupLightsView(B),ee===!0&&$.setGlobalState(M.clippingPlanes,B),cr(y,O,B),b.updateMultisampleRenderTarget(j),b.updateRenderTargetMipmap(j),Ge.has("WEBGL_multisampled_render_to_texture")===!1){let we=!1;for(let ye=0,We=D.length;ye<We;ye++){let Ze=D[ye],ht=Ze.object,at=Ze.geometry,Xe=Ze.material,ve=Ze.group;if(Xe.side===Yt&&ht.layers.test(B.layers)){let xt=Xe.side;Xe.side=Pt,Xe.needsUpdate=!0,il(ht,O,B,at,Xe,ve),Xe.side=xt,Xe.needsUpdate=!0,we=!0}}we===!0&&(b.updateMultisampleRenderTarget(j),b.updateRenderTargetMipmap(j))}M.setRenderTarget(le),M.setClearColor(W,J),Ce!==void 0&&(B.viewport=Ce),M.toneMapping=fe}function cr(y,D,O){let B=D.isScene===!0?D.overrideMaterial:null;for(let U=0,j=y.length;U<j;U++){let ne=y[U],le=ne.object,fe=ne.geometry,Ce=ne.group,we=ne.material;we.allowOverride===!0&&B!==null&&(we=B),le.layers.test(O.layers)&&il(le,D,O,fe,we,Ce)}}function il(y,D,O,B,U,j){y.onBeforeRender(M,D,O,B,U,j),y.modelViewMatrix.multiplyMatrices(O.matrixWorldInverse,y.matrixWorld),y.normalMatrix.getNormalMatrix(y.modelViewMatrix),U.onBeforeRender(M,D,O,B,y,j),U.transparent===!0&&U.side===Yt&&U.forceSinglePass===!1?(U.side=Pt,U.needsUpdate=!0,M.renderBufferDirect(O,D,B,U,y,j),U.side=rn,U.needsUpdate=!0,M.renderBufferDirect(O,D,B,U,y,j),U.side=Yt):M.renderBufferDirect(O,D,B,U,y,j),y.onAfterRender(M,D,O,B,U,j)}function lr(y,D,O){D.isScene!==!0&&(D=ct);let B=ge.get(y),U=f.state.lights,j=f.state.shadowsArray,ne=U.state.version,le=me.getParameters(y,U.state,j,D,O),fe=me.getProgramCacheKey(le),Ce=B.programs;B.environment=y.isMeshStandardMaterial?D.environment:null,B.fog=D.fog,B.envMap=(y.isMeshStandardMaterial?F:x).get(y.envMap||B.environment),B.envMapRotation=B.environment!==null&&y.envMap===null?D.environmentRotation:y.envMapRotation,Ce===void 0&&(y.addEventListener("dispose",Le),Ce=new Map,B.programs=Ce);let we=Ce.get(fe);if(we!==void 0){if(B.currentProgram===we&&B.lightsStateVersion===ne)return rl(y,le),we}else le.uniforms=me.getUniforms(y),y.onBeforeCompile(le,M),we=me.acquireProgram(le,fe),Ce.set(fe,we),B.uniforms=le.uniforms;let ye=B.uniforms;return(!y.isShaderMaterial&&!y.isRawShaderMaterial||y.clipping===!0)&&(ye.clippingPlanes=$.uniform),rl(y,le),B.needsLights=bu(y),B.lightsStateVersion=ne,B.needsLights&&(ye.ambientLightColor.value=U.state.ambient,ye.lightProbe.value=U.state.probe,ye.directionalLights.value=U.state.directional,ye.directionalLightShadows.value=U.state.directionalShadow,ye.spotLights.value=U.state.spot,ye.spotLightShadows.value=U.state.spotShadow,ye.rectAreaLights.value=U.state.rectArea,ye.ltc_1.value=U.state.rectAreaLTC1,ye.ltc_2.value=U.state.rectAreaLTC2,ye.pointLights.value=U.state.point,ye.pointLightShadows.value=U.state.pointShadow,ye.hemisphereLights.value=U.state.hemi,ye.directionalShadowMap.value=U.state.directionalShadowMap,ye.directionalShadowMatrix.value=U.state.directionalShadowMatrix,ye.spotShadowMap.value=U.state.spotShadowMap,ye.spotLightMatrix.value=U.state.spotLightMatrix,ye.spotLightMap.value=U.state.spotLightMap,ye.pointShadowMap.value=U.state.pointShadowMap,ye.pointShadowMatrix.value=U.state.pointShadowMatrix),B.currentProgram=we,B.uniformsList=null,we}function sl(y){if(y.uniformsList===null){let D=y.currentProgram.getUniforms();y.uniformsList=ls.seqWithValue(D.seq,y.uniforms)}return y.uniformsList}function rl(y,D){let O=ge.get(y);O.outputColorSpace=D.outputColorSpace,O.batching=D.batching,O.batchingColor=D.batchingColor,O.instancing=D.instancing,O.instancingColor=D.instancingColor,O.instancingMorph=D.instancingMorph,O.skinning=D.skinning,O.morphTargets=D.morphTargets,O.morphNormals=D.morphNormals,O.morphColors=D.morphColors,O.morphTargetsCount=D.morphTargetsCount,O.numClippingPlanes=D.numClippingPlanes,O.numIntersection=D.numClipIntersection,O.vertexAlphas=D.vertexAlphas,O.vertexTangents=D.vertexTangents,O.toneMapping=D.toneMapping}function Mu(y,D,O,B,U){D.isScene!==!0&&(D=ct),b.resetTextureUnits();let j=D.fog,ne=B.isMeshStandardMaterial?D.environment:null,le=N===null?M.outputColorSpace:N.isXRRenderTarget===!0?N.texture.colorSpace:vt,fe=(B.isMeshStandardMaterial?F:x).get(B.envMap||ne),Ce=B.vertexColors===!0&&!!O.attributes.color&&O.attributes.color.itemSize===4,we=!!O.attributes.tangent&&(!!B.normalMap||B.anisotropy>0),ye=!!O.morphAttributes.position,We=!!O.morphAttributes.normal,Ze=!!O.morphAttributes.color,ht=Fn;B.toneMapped&&(N===null||N.isXRRenderTarget===!0)&&(ht=M.toneMapping);let at=O.morphAttributes.position||O.morphAttributes.normal||O.morphAttributes.color,Xe=at!==void 0?at.length:0,ve=ge.get(B),xt=f.state.lights;if(ee===!0&&(pe===!0||y!==v)){let At=y===v&&B.id===S;$.setState(B,y,At)}let Ke=!1;B.version===ve.__version?(ve.needsLights&&ve.lightsStateVersion!==xt.state.version||ve.outputColorSpace!==le||U.isBatchedMesh&&ve.batching===!1||!U.isBatchedMesh&&ve.batching===!0||U.isBatchedMesh&&ve.batchingColor===!0&&U.colorTexture===null||U.isBatchedMesh&&ve.batchingColor===!1&&U.colorTexture!==null||U.isInstancedMesh&&ve.instancing===!1||!U.isInstancedMesh&&ve.instancing===!0||U.isSkinnedMesh&&ve.skinning===!1||!U.isSkinnedMesh&&ve.skinning===!0||U.isInstancedMesh&&ve.instancingColor===!0&&U.instanceColor===null||U.isInstancedMesh&&ve.instancingColor===!1&&U.instanceColor!==null||U.isInstancedMesh&&ve.instancingMorph===!0&&U.morphTexture===null||U.isInstancedMesh&&ve.instancingMorph===!1&&U.morphTexture!==null||ve.envMap!==fe||B.fog===!0&&ve.fog!==j||ve.numClippingPlanes!==void 0&&(ve.numClippingPlanes!==$.numPlanes||ve.numIntersection!==$.numIntersection)||ve.vertexAlphas!==Ce||ve.vertexTangents!==we||ve.morphTargets!==ye||ve.morphNormals!==We||ve.morphColors!==Ze||ve.toneMapping!==ht||ve.morphTargetsCount!==Xe)&&(Ke=!0):(Ke=!0,ve.__version=B.version);let $t=ve.currentProgram;Ke===!0&&($t=lr(B,D,U));let wi=!1,Ot=!1,ds=!1,it=$t.getUniforms(),Wt=ve.uniforms;if(xe.useProgram($t.program)&&(wi=!0,Ot=!0,ds=!0),B.id!==S&&(S=B.id,Ot=!0),wi||v!==y){xe.buffers.depth.getReversed()?(se.copy(y.projectionMatrix),Nh(se),Fh(se),it.setValue(A,"projectionMatrix",se)):it.setValue(A,"projectionMatrix",y.projectionMatrix),it.setValue(A,"viewMatrix",y.matrixWorldInverse);let Lt=it.map.cameraPosition;Lt!==void 0&&Lt.setValue(A,Ye.setFromMatrixPosition(y.matrixWorld)),Ve.logarithmicDepthBuffer&&it.setValue(A,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2)),(B.isMeshPhongMaterial||B.isMeshToonMaterial||B.isMeshLambertMaterial||B.isMeshBasicMaterial||B.isMeshStandardMaterial||B.isShaderMaterial)&&it.setValue(A,"isOrthographic",y.isOrthographicCamera===!0),v!==y&&(v=y,Ot=!0,ds=!0)}if(U.isSkinnedMesh){it.setOptional(A,U,"bindMatrix"),it.setOptional(A,U,"bindMatrixInverse");let At=U.skeleton;At&&(At.boneTexture===null&&At.computeBoneTexture(),it.setValue(A,"boneTexture",At.boneTexture,b))}U.isBatchedMesh&&(it.setOptional(A,U,"batchingTexture"),it.setValue(A,"batchingTexture",U._matricesTexture,b),it.setOptional(A,U,"batchingIdTexture"),it.setValue(A,"batchingIdTexture",U._indirectTexture,b),it.setOptional(A,U,"batchingColorTexture"),U._colorsTexture!==null&&it.setValue(A,"batchingColorTexture",U._colorsTexture,b));let Xt=O.morphAttributes;if((Xt.position!==void 0||Xt.normal!==void 0||Xt.color!==void 0)&&Re.update(U,O,$t),(Ot||ve.receiveShadow!==U.receiveShadow)&&(ve.receiveShadow=U.receiveShadow,it.setValue(A,"receiveShadow",U.receiveShadow)),B.isMeshGouraudMaterial&&B.envMap!==null&&(Wt.envMap.value=fe,Wt.flipEnvMap.value=fe.isCubeTexture&&fe.isRenderTargetTexture===!1?-1:1),B.isMeshStandardMaterial&&B.envMap===null&&D.environment!==null&&(Wt.envMapIntensity.value=D.environmentIntensity),Ot&&(it.setValue(A,"toneMappingExposure",M.toneMappingExposure),ve.needsLights&&Su(Wt,ds),j&&B.fog===!0&&re.refreshFogUniforms(Wt,j),re.refreshMaterialUniforms(Wt,B,V,Q,f.state.transmissionRenderTarget[y.id]),ls.upload(A,sl(ve),Wt,b)),B.isShaderMaterial&&B.uniformsNeedUpdate===!0&&(ls.upload(A,sl(ve),Wt,b),B.uniformsNeedUpdate=!1),B.isSpriteMaterial&&it.setValue(A,"center",U.center),it.setValue(A,"modelViewMatrix",U.modelViewMatrix),it.setValue(A,"normalMatrix",U.normalMatrix),it.setValue(A,"modelMatrix",U.matrixWorld),B.isShaderMaterial||B.isRawShaderMaterial){let At=B.uniformsGroups;for(let Lt=0,na=At.length;Lt<na;Lt++){let Qn=At[Lt];I.update(Qn,$t),I.bind(Qn,$t)}}return $t}function Su(y,D){y.ambientLightColor.needsUpdate=D,y.lightProbe.needsUpdate=D,y.directionalLights.needsUpdate=D,y.directionalLightShadows.needsUpdate=D,y.pointLights.needsUpdate=D,y.pointLightShadows.needsUpdate=D,y.spotLights.needsUpdate=D,y.spotLightShadows.needsUpdate=D,y.rectAreaLights.needsUpdate=D,y.hemisphereLights.needsUpdate=D}function bu(y){return y.isMeshLambertMaterial||y.isMeshToonMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isShadowMaterial||y.isShaderMaterial&&y.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return w},this.getRenderTarget=function(){return N},this.setRenderTargetTextures=function(y,D,O){let B=ge.get(y);B.__autoAllocateDepthBuffer=y.resolveDepthBuffer===!1,B.__autoAllocateDepthBuffer===!1&&(B.__useRenderToTexture=!1),ge.get(y.texture).__webglTexture=D,ge.get(y.depthTexture).__webglTexture=B.__autoAllocateDepthBuffer?void 0:O,B.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(y,D){let O=ge.get(y);O.__webglFramebuffer=D,O.__useDefaultFramebuffer=D===void 0};let Tu=A.createFramebuffer();this.setRenderTarget=function(y,D=0,O=0){N=y,R=D,w=O;let B=!0,U=null,j=!1,ne=!1;if(y){let fe=ge.get(y);if(fe.__useDefaultFramebuffer!==void 0)xe.bindFramebuffer(A.FRAMEBUFFER,null),B=!1;else if(fe.__webglFramebuffer===void 0)b.setupRenderTarget(y);else if(fe.__hasExternalTextures)b.rebindTextures(y,ge.get(y.texture).__webglTexture,ge.get(y.depthTexture).__webglTexture);else if(y.depthBuffer){let ye=y.depthTexture;if(fe.__boundDepthTexture!==ye){if(ye!==null&&ge.has(ye)&&(y.width!==ye.image.width||y.height!==ye.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");b.setupDepthRenderbuffer(y)}}let Ce=y.texture;(Ce.isData3DTexture||Ce.isDataArrayTexture||Ce.isCompressedArrayTexture)&&(ne=!0);let we=ge.get(y).__webglFramebuffer;y.isWebGLCubeRenderTarget?(Array.isArray(we[D])?U=we[D][O]:U=we[D],j=!0):y.samples>0&&b.useMultisampledRTT(y)===!1?U=ge.get(y).__webglMultisampledFramebuffer:Array.isArray(we)?U=we[O]:U=we,C.copy(y.viewport),q.copy(y.scissor),z=y.scissorTest}else C.copy(_e).multiplyScalar(V).floor(),q.copy(Ne).multiplyScalar(V).floor(),z=et;if(O!==0&&(U=Tu),xe.bindFramebuffer(A.FRAMEBUFFER,U)&&B&&xe.drawBuffers(y,U),xe.viewport(C),xe.scissor(q),xe.setScissorTest(z),j){let fe=ge.get(y.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+D,fe.__webglTexture,O)}else if(ne){let fe=ge.get(y.texture),Ce=D;A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,fe.__webglTexture,O,Ce)}else if(y!==null&&O!==0){let fe=ge.get(y.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,fe.__webglTexture,O)}S=-1},this.readRenderTargetPixels=function(y,D,O,B,U,j,ne){if(!(y&&y.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let le=ge.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&ne!==void 0&&(le=le[ne]),le){xe.bindFramebuffer(A.FRAMEBUFFER,le);try{let fe=y.texture,Ce=fe.format,we=fe.type;if(!Ve.textureFormatReadable(Ce)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Ve.textureTypeReadable(we)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}D>=0&&D<=y.width-B&&O>=0&&O<=y.height-U&&A.readPixels(D,O,B,U,De.convert(Ce),De.convert(we),j)}finally{let fe=N!==null?ge.get(N).__webglFramebuffer:null;xe.bindFramebuffer(A.FRAMEBUFFER,fe)}}},this.readRenderTargetPixelsAsync=async function(y,D,O,B,U,j,ne){if(!(y&&y.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let le=ge.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&ne!==void 0&&(le=le[ne]),le)if(D>=0&&D<=y.width-B&&O>=0&&O<=y.height-U){xe.bindFramebuffer(A.FRAMEBUFFER,le);let fe=y.texture,Ce=fe.format,we=fe.type;if(!Ve.textureFormatReadable(Ce))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ve.textureTypeReadable(we))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let ye=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,ye),A.bufferData(A.PIXEL_PACK_BUFFER,j.byteLength,A.STREAM_READ),A.readPixels(D,O,B,U,De.convert(Ce),De.convert(we),0);let We=N!==null?ge.get(N).__webglFramebuffer:null;xe.bindFramebuffer(A.FRAMEBUFFER,We);let Ze=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await Uh(A,Ze,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,ye),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,j),A.deleteBuffer(ye),A.deleteSync(Ze),j}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(y,D=null,O=0){let B=Math.pow(2,-O),U=Math.floor(y.image.width*B),j=Math.floor(y.image.height*B),ne=D!==null?D.x:0,le=D!==null?D.y:0;b.setTexture2D(y,0),A.copyTexSubImage2D(A.TEXTURE_2D,O,0,0,ne,le,U,j),xe.unbindTexture()};let Eu=A.createFramebuffer(),Au=A.createFramebuffer();this.copyTextureToTexture=function(y,D,O=null,B=null,U=0,j=null){j===null&&(U!==0?(rr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),j=U,U=0):j=0);let ne,le,fe,Ce,we,ye,We,Ze,ht,at=y.isCompressedTexture?y.mipmaps[j]:y.image;if(O!==null)ne=O.max.x-O.min.x,le=O.max.y-O.min.y,fe=O.isBox3?O.max.z-O.min.z:1,Ce=O.min.x,we=O.min.y,ye=O.isBox3?O.min.z:0;else{let Xt=Math.pow(2,-U);ne=Math.floor(at.width*Xt),le=Math.floor(at.height*Xt),y.isDataArrayTexture?fe=at.depth:y.isData3DTexture?fe=Math.floor(at.depth*Xt):fe=1,Ce=0,we=0,ye=0}B!==null?(We=B.x,Ze=B.y,ht=B.z):(We=0,Ze=0,ht=0);let Xe=De.convert(D.format),ve=De.convert(D.type),xt;D.isData3DTexture?(b.setTexture3D(D,0),xt=A.TEXTURE_3D):D.isDataArrayTexture||D.isCompressedArrayTexture?(b.setTexture2DArray(D,0),xt=A.TEXTURE_2D_ARRAY):(b.setTexture2D(D,0),xt=A.TEXTURE_2D),A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,D.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,D.unpackAlignment);let Ke=A.getParameter(A.UNPACK_ROW_LENGTH),$t=A.getParameter(A.UNPACK_IMAGE_HEIGHT),wi=A.getParameter(A.UNPACK_SKIP_PIXELS),Ot=A.getParameter(A.UNPACK_SKIP_ROWS),ds=A.getParameter(A.UNPACK_SKIP_IMAGES);A.pixelStorei(A.UNPACK_ROW_LENGTH,at.width),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,at.height),A.pixelStorei(A.UNPACK_SKIP_PIXELS,Ce),A.pixelStorei(A.UNPACK_SKIP_ROWS,we),A.pixelStorei(A.UNPACK_SKIP_IMAGES,ye);let it=y.isDataArrayTexture||y.isData3DTexture,Wt=D.isDataArrayTexture||D.isData3DTexture;if(y.isDepthTexture){let Xt=ge.get(y),At=ge.get(D),Lt=ge.get(Xt.__renderTarget),na=ge.get(At.__renderTarget);xe.bindFramebuffer(A.READ_FRAMEBUFFER,Lt.__webglFramebuffer),xe.bindFramebuffer(A.DRAW_FRAMEBUFFER,na.__webglFramebuffer);for(let Qn=0;Qn<fe;Qn++)it&&(A.framebufferTextureLayer(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,ge.get(y).__webglTexture,U,ye+Qn),A.framebufferTextureLayer(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,ge.get(D).__webglTexture,j,ht+Qn)),A.blitFramebuffer(Ce,we,ne,le,We,Ze,ne,le,A.DEPTH_BUFFER_BIT,A.NEAREST);xe.bindFramebuffer(A.READ_FRAMEBUFFER,null),xe.bindFramebuffer(A.DRAW_FRAMEBUFFER,null)}else if(U!==0||y.isRenderTargetTexture||ge.has(y)){let Xt=ge.get(y),At=ge.get(D);xe.bindFramebuffer(A.READ_FRAMEBUFFER,Eu),xe.bindFramebuffer(A.DRAW_FRAMEBUFFER,Au);for(let Lt=0;Lt<fe;Lt++)it?A.framebufferTextureLayer(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,Xt.__webglTexture,U,ye+Lt):A.framebufferTexture2D(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,Xt.__webglTexture,U),Wt?A.framebufferTextureLayer(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,At.__webglTexture,j,ht+Lt):A.framebufferTexture2D(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,At.__webglTexture,j),U!==0?A.blitFramebuffer(Ce,we,ne,le,We,Ze,ne,le,A.COLOR_BUFFER_BIT,A.NEAREST):Wt?A.copyTexSubImage3D(xt,j,We,Ze,ht+Lt,Ce,we,ne,le):A.copyTexSubImage2D(xt,j,We,Ze,Ce,we,ne,le);xe.bindFramebuffer(A.READ_FRAMEBUFFER,null),xe.bindFramebuffer(A.DRAW_FRAMEBUFFER,null)}else Wt?y.isDataTexture||y.isData3DTexture?A.texSubImage3D(xt,j,We,Ze,ht,ne,le,fe,Xe,ve,at.data):D.isCompressedArrayTexture?A.compressedTexSubImage3D(xt,j,We,Ze,ht,ne,le,fe,Xe,at.data):A.texSubImage3D(xt,j,We,Ze,ht,ne,le,fe,Xe,ve,at):y.isDataTexture?A.texSubImage2D(A.TEXTURE_2D,j,We,Ze,ne,le,Xe,ve,at.data):y.isCompressedTexture?A.compressedTexSubImage2D(A.TEXTURE_2D,j,We,Ze,at.width,at.height,Xe,at.data):A.texSubImage2D(A.TEXTURE_2D,j,We,Ze,ne,le,Xe,ve,at);A.pixelStorei(A.UNPACK_ROW_LENGTH,Ke),A.pixelStorei(A.UNPACK_IMAGE_HEIGHT,$t),A.pixelStorei(A.UNPACK_SKIP_PIXELS,wi),A.pixelStorei(A.UNPACK_SKIP_ROWS,Ot),A.pixelStorei(A.UNPACK_SKIP_IMAGES,ds),j===0&&D.generateMipmaps&&A.generateMipmap(xt),xe.unbindTexture()},this.copyTextureToTexture3D=function(y,D,O=null,B=null,U=0){return rr('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(y,D,O,B,U)},this.initRenderTarget=function(y){ge.get(y).__webglFramebuffer===void 0&&b.setupRenderTarget(y)},this.initTexture=function(y){y.isCubeTexture?b.setTextureCube(y,0):y.isData3DTexture?b.setTexture3D(y,0):y.isDataArrayTexture||y.isCompressedArrayTexture?b.setTexture2DArray(y,0):b.setTexture2D(y,0),xe.unbindTexture()},this.resetState=function(){R=0,w=0,N=null,xe.reset(),tt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return fn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Be._getDrawingBufferColorSpace(e),t.unpackColorSpace=Be._getUnpackColorSpace()}};function Sc(s,e){if(e===Ja)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===os||e===sr){let t=s.getIndex();if(t===null){let o=[],a=s.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);s.setIndex(o),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}let n=t.count-2,i=[];if(e===os)for(let o=1;o<=n;o++)i.push(t.getX(0)),i.push(t.getX(o)),i.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(i.push(t.getX(o)),i.push(t.getX(o+1)),i.push(t.getX(o+2))):(i.push(t.getX(o+2)),i.push(t.getX(o+1)),i.push(t.getX(o)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let r=s.clone();return r.setIndex(i),r.clearGroups(),r}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}var Qo=class extends yn{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Cc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new zc(t)}),this.register(function(t){return new kc(t)}),this.register(function(t){return new Vc(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new Dc(t)}),this.register(function(t){return new Uc(t)}),this.register(function(t){return new Nc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new Fc(t)}),this.register(function(t){return new Pc(t)}),this.register(function(t){return new Bc(t)}),this.register(function(t){return new Oc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new Hc(t)}),this.register(function(t){return new Gc(t)})}load(e,t,n,i){let r=this,o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){let l=Un.extractUrlBase(e);o=Un.resolveURL(l,this.path)}else o=Un.extractUrlBase(e);this.manager.itemStart(e);let a=function(l){i?i(l):console.error(l),r.manager.itemError(e),r.manager.itemEnd(e)},c=new es(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,o,function(h){t(h),r.manager.itemEnd(e)},a)}catch(h){a(h)}},n,a)}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,i){let r,o={},a={},c=new TextDecoder;if(typeof e=="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===yu){try{o[Oe.KHR_BINARY_GLTF]=new Wc(e)}catch(u){i&&i(u);return}r=JSON.parse(o[Oe.KHR_BINARY_GLTF].content)}else r=JSON.parse(c.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let l=new $c(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++){let u=this.pluginCallbacks[h](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,o[u.name]=!0}if(r.extensionsUsed)for(let h=0;h<r.extensionsUsed.length;++h){let u=r.extensionsUsed[h],d=r.extensionsRequired||[];switch(u){case Oe.KHR_MATERIALS_UNLIT:o[u]=new wc;break;case Oe.KHR_DRACO_MESH_COMPRESSION:o[u]=new Xc(r,this.dracoLoader);break;case Oe.KHR_TEXTURE_TRANSFORM:o[u]=new qc;break;case Oe.KHR_MESH_QUANTIZATION:o[u]=new Yc;break;default:d.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(o),l.setPlugins(a),l.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}};function i_(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}var Oe={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"},Ac=class{constructor(e){this.parser=e,this.name=Oe.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){let 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){let t=this.parser,n="light:"+e,i=t.cache.get(n);if(i)return i;let r=t.json,c=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e],l,h=new be(16777215);c.color!==void 0&&h.setRGB(c.color[0],c.color[1],c.color[2],vt);let u=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new Kn(h),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new Ys(h),l.distance=u;break;case"spot":l=new qs(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),Bn(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),i=Promise.resolve(l),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],a=(r.extensions&&r.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}},wc=class{constructor(){this.name=Oe.KHR_MATERIALS_UNLIT}getMaterialType(){return an}extendParams(e,t,n){let i=[];e.color=new be(1,1,1),e.opacity=1;let r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){let o=r.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],vt),e.opacity=o[3]}r.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",r.baseColorTexture,lt))}return Promise.all(i)}},Rc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=i.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}},Cc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(r.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){let a=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new ze(a,a)}return Promise.all(r)}},Ic=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_DISPERSION}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=i.extensions[this.name];return t.dispersion=r.dispersion!==void 0?r.dispersion:0,Promise.resolve()}},Pc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&r.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(r)}},Lc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_SHEEN}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[];t.sheenColor=new be(0,0,0),t.sheenRoughness=0,t.sheen=1;let o=i.extensions[this.name];if(o.sheenColorFactor!==void 0){let a=o.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],vt)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&r.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,lt)),o.sheenRoughnessTexture!==void 0&&r.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(r)}},Dc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&r.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(r)}},Uc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_VOLUME}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&r.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;let a=o.attenuationColor||[1,1,1];return t.attenuationColor=new be().setRGB(a[0],a[1],a[2],vt),Promise.all(r)}},Nc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_IOR}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=i.extensions[this.name];return t.ior=r.ior!==void 0?r.ior:1.5,Promise.resolve()}},Fc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_SPECULAR}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&r.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));let a=o.specularColorFactor||[1,1,1];return t.specularColor=new be().setRGB(a[0],a[1],a[2],vt),o.specularColorTexture!==void 0&&r.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,lt)),Promise.all(r)}},Oc=class{constructor(e){this.parser=e,this.name=Oe.EXT_MATERIALS_BUMP}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&r.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(r)}},Bc=class{constructor(e){this.parser=e,this.name=Oe.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Nt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let r=[],o=i.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&r.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(r)}},zc=class{constructor(e){this.parser=e,this.name=Oe.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let r=i.extensions[this.name],o=t.options.ktx2Loader;if(!o){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,o)}},kc=class{constructor(e){this.parser=e,this.name=Oe.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return n.loadTextureImage(e,o.source,c)}},Vc=class{constructor(e){this.parser=e,this.name=Oe.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return n.loadTextureImage(e,o.source,c)}},Hc=class{constructor(e){this.name=Oe.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.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(a){let c=i.byteOffset||0,l=i.byteLength||0,h=i.count,u=i.byteStride,d=new Uint8Array(a,c,l);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,u,d,i.mode,i.filter).then(function(p){return p.buffer}):o.ready.then(function(){let p=new ArrayBuffer(h*u);return o.decodeGltfBuffer(new Uint8Array(p),h,u,d,i.mode,i.filter),p})})}else return null}},Gc=class{constructor(e){this.name=Oe.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let i=t.meshes[n.mesh];for(let l of i.primitives)if(l.mode!==Kt.TRIANGLES&&l.mode!==Kt.TRIANGLE_STRIP&&l.mode!==Kt.TRIANGLE_FAN&&l.mode!==void 0)return null;let o=n.extensions[this.name].attributes,a=[],c={};for(let l in o)a.push(this.parser.getDependency("accessor",o[l]).then(h=>(c[l]=h,c[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{let h=l.pop(),u=h.isGroup?h.children:[h],d=l[0].count,p=[];for(let g of u){let _=new Ie,m=new P,f=new Rt,E=new P(1,1,1),T=new Fs(g.geometry,g.material,d);for(let M=0;M<d;M++)c.TRANSLATION&&m.fromBufferAttribute(c.TRANSLATION,M),c.ROTATION&&f.fromBufferAttribute(c.ROTATION,M),c.SCALE&&E.fromBufferAttribute(c.SCALE,M),T.setMatrixAt(M,_.compose(m,f,E));for(let M in c)if(M==="_COLOR_0"){let L=c[M];T.instanceColor=new Zn(L.array,L.itemSize,L.normalized)}else M!=="TRANSLATION"&&M!=="ROTATION"&&M!=="SCALE"&&g.geometry.setAttribute(M,c[M]);rt.prototype.copy.call(T,g),this.parser.assignFinalMaterial(T),p.push(T)}return h.isGroup?(h.clear(),h.add(...p),h):p[0]}))}},yu="glTF",ar=12,mu={JSON:1313821514,BIN:5130562},Wc=class{constructor(e){this.name=Oe.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,ar),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!==yu)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-ar,r=new DataView(e,ar),o=0;for(;o<i;){let a=r.getUint32(o,!0);o+=4;let c=r.getUint32(o,!0);if(o+=4,c===mu.JSON){let l=new Uint8Array(e,ar+o,a);this.content=n.decode(l)}else if(c===mu.BIN){let l=ar+o;this.body=e.slice(l,l+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},Xc=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Oe.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,i=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},l={};for(let h in o){let u=Kc[h]||h.toLowerCase();a[u]=o[h]}for(let h in e.attributes){let u=Kc[h]||h.toLowerCase();if(o[h]!==void 0){let d=n.accessors[e.attributes[h]],p=us[d.componentType];l[u]=p.name,c[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(h){return new Promise(function(u,d){i.decodeDracoFile(h,function(p){for(let g in p.attributes){let _=p.attributes[g],m=c[g];m!==void 0&&(_.normalized=m)}u(p)},a,l,vt,d)})})}},qc=class{constructor(){this.name=Oe.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}},Yc=class{constructor(){this.name=Oe.KHR_MESH_QUANTIZATION}},ea=class extends Pn{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i*3+i;for(let o=0;o!==i;o++)t[o]=n[r+o];return t}interpolate_(e,t,n,i){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,l=a*3,h=i-t,u=(n-t)/h,d=u*u,p=d*u,g=e*l,_=g-l,m=-2*p+3*d,f=p-d,E=1-m,T=f-d+u;for(let M=0;M!==a;M++){let L=o[_+M+a],R=o[_+M+c]*h,w=o[g+M+a],N=o[g+M]*h;r[M]=E*L+T*R+m*w+f*N}return r}},s_=new Rt,Zc=class extends ea{interpolate_(e,t,n,i){let r=super.interpolate_(e,t,n,i);return s_.fromArray(r).normalize().toArray(r),r}},Kt={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},us={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},gu={9728:yt,9729:Ct,9984:uo,9985:ts,9986:vi,9987:ln},_u={33071:dn,33648:Hi,10497:Yn},bc={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Kc={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"},$n={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},r_={CUBICSPLINE:void 0,LINEAR:hi,STEP:li},Tc={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function o_(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new pi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:rn})),s.DefaultMaterial}function Ai(s,e,t){for(let n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Bn(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function a_(s,e,t){let n=!1,i=!1,r=!1;for(let l=0,h=e.length;l<h;l++){let u=e[l];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(i=!0),u.COLOR_0!==void 0&&(r=!0),n&&i&&r)break}if(!n&&!i&&!r)return Promise.resolve(s);let o=[],a=[],c=[];for(let l=0,h=e.length;l<h;l++){let u=e[l];if(n){let d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):s.attributes.position;o.push(d)}if(i){let d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):s.attributes.normal;a.push(d)}if(r){let d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):s.attributes.color;c.push(d)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(l){let h=l[0],u=l[1],d=l[2];return n&&(s.morphAttributes.position=h),i&&(s.morphAttributes.normal=u),r&&(s.morphAttributes.color=d),s.morphTargetsRelative=!0,s})}function c_(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function l_(s){let e,t=s.extensions&&s.extensions[Oe.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Ec(t.attributes):e=s.indices+":"+Ec(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+Ec(s.targets[n]);return e}function Ec(s){let e="",t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function Jc(s){switch(s){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 h_(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var u_=new Ie,$c=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new i_,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,i=-1,r=!1,o=-1;if(typeof navigator<"u"){let a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;let c=a.match(/Version\/(\d+)/);i=n&&c?parseInt(c[1],10):-1,r=a.indexOf("Firefox")>-1,o=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||r&&o<98?this.textureLoader=new Ws(this.options.manager):this.textureLoader=new Ks(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new es(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){let n=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){let a={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:n,userData:{}};return Ai(r,a,i),Bn(a,i),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(let c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i<r;i++){let o=t[i].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let i=0,r=e.length;i<r;i++){let o=e[i];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.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;let i=n.clone(),r=(o,a)=>{let c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(let[l,h]of o.children.entries())r(h,a.children[l])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let i=e(t[n]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let i=0;i<t.length;i++){let r=e(t[i]);r&&n.push(r)}return n}getDependency(e,t){let n=e+":"+t,i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":i=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(r,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){let 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[Oe.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(r,o){n.load(Un.resolveURL(t.uri,i.path),r,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){let i=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+i)})}loadAccessor(e){let t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let o=bc[i.type],a=us[i.componentType],c=i.normalized===!0,l=new a(i.count*o);return Promise.resolve(new ft(l,o,c))}let r=[];return i.bufferView!==void 0?r.push(this.getDependency("bufferView",i.bufferView)):r.push(null),i.sparse!==void 0&&(r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(r).then(function(o){let a=o[0],c=bc[i.type],l=us[i.componentType],h=l.BYTES_PER_ELEMENT,u=h*c,d=i.byteOffset||0,p=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,g=i.normalized===!0,_,m;if(p&&p!==u){let f=Math.floor(d/p),E="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+f+":"+i.count,T=t.cache.get(E);T||(_=new l(a,f*p,i.count*p/h),T=new Zi(_,p/h),t.cache.add(E,T)),m=new Ki(T,c,d%p/h,g)}else a===null?_=new l(i.count*c):_=new l(a,d,i.count*c),m=new ft(_,c,g);if(i.sparse!==void 0){let f=bc.SCALAR,E=us[i.sparse.indices.componentType],T=i.sparse.indices.byteOffset||0,M=i.sparse.values.byteOffset||0,L=new E(o[1],T,i.sparse.count*f),R=new l(o[2],M,i.sparse.count*c);a!==null&&(m=new ft(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let w=0,N=L.length;w<N;w++){let S=L[w];if(m.setX(S,R[w*c]),c>=2&&m.setY(S,R[w*c+1]),c>=3&&m.setZ(S,R[w*c+2]),c>=4&&m.setW(S,R[w*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=g}return m})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r],a=this.textureLoader;if(o.uri){let c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let i=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];let l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);let d=(r.samplers||{})[o.sampler]||{};return h.magFilter=gu[d.magFilter]||Ct,h.minFilter=gu[d.minFilter]||ln,h.wrapS=_u[d.wrapS]||Yn,h.wrapT=_u[d.wrapT]||Yn,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==yt&&h.minFilter!==Ct,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){let n=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let o=i.images[e],a=self.URL||self.webkitURL,c=o.uri||"",l=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(u){l=!0;let d=new Blob([u],{type:o.mimeType});return c=a.createObjectURL(d),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(c).then(function(u){return new Promise(function(d,p){let g=d;t.isImageBitmapLoader===!0&&(g=function(_){let m=new _t(_);m.needsUpdate=!0,d(m)}),t.load(Un.resolveURL(u,r.path),g,void 0,p)})}).then(function(u){return l===!0&&a.revokeObjectURL(c),Bn(u,o),u.userData.mimeType=o.mimeType||h_(o.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,i){let r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[Oe.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[Oe.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let c=r.associations.get(o);o=r.extensions[Oe.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return i!==void 0&&(o.colorSpace=i),e[t]=o,o})}assignFinalMaterial(e){let t=e.geometry,n=e.material,i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new Qi,Ut.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new ji,Ut.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(i||r||o){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),i&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return pi}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],o,a={},c=r.extensions||{},l=[];if(c[Oe.KHR_MATERIALS_UNLIT]){let u=i[Oe.KHR_MATERIALS_UNLIT];o=u.getMaterialType(),l.push(u.extendParams(a,r,t))}else{let u=r.pbrMetallicRoughness||{};if(a.color=new be(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],vt),a.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",u.baseColorTexture,lt)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),o=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=Yt);let h=r.alphaMode||Tc.OPAQUE;if(h===Tc.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===Tc.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==an&&(l.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new ze(1,1),r.normalTexture.scale!==void 0)){let u=r.normalTexture.scale;a.normalScale.set(u,u)}if(r.occlusionTexture!==void 0&&o!==an&&(l.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==an){let u=r.emissiveFactor;a.emissive=new be().setRGB(u[0],u[1],u[2],vt)}return r.emissiveTexture!==void 0&&o!==an&&l.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,lt)),Promise.all(l).then(function(){let u=new o(a);return r.name&&(u.name=r.name),Bn(u,r),t.associations.set(u,{materials:e}),r.extensions&&Ai(i,u,r),u})}createUniqueName(e){let t=Qe.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function r(a){return n[Oe.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return xu(c,a,t)})}let o=[];for(let a=0,c=e.length;a<c;a++){let l=e[a],h=l_(l),u=i[h];if(u)o.push(u.promise);else{let d;l.extensions&&l.extensions[Oe.KHR_DRACO_MESH_COMPRESSION]?d=r(l):d=xu(new Vt,l,t),i[h]={primitive:l,promise:d},o.push(d)}}return Promise.all(o)}loadMesh(e){let t=this,n=this.json,i=this.extensions,r=n.meshes[e],o=r.primitives,a=[];for(let c=0,l=o.length;c<l;c++){let h=o[c].material===void 0?o_(this.cache):this.getDependency("material",o[c].material);a.push(h)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){let l=c.slice(0,c.length-1),h=c[c.length-1],u=[];for(let p=0,g=h.length;p<g;p++){let _=h[p],m=o[p],f,E=l[p];if(m.mode===Kt.TRIANGLES||m.mode===Kt.TRIANGLE_STRIP||m.mode===Kt.TRIANGLE_FAN||m.mode===void 0)f=r.isSkinnedMesh===!0?new Ds(_,E):new Mt(_,E),f.isSkinnedMesh===!0&&f.normalizeSkinWeights(),m.mode===Kt.TRIANGLE_STRIP?f.geometry=Sc(f.geometry,sr):m.mode===Kt.TRIANGLE_FAN&&(f.geometry=Sc(f.geometry,os));else if(m.mode===Kt.LINES)f=new Os(_,E);else if(m.mode===Kt.LINE_STRIP)f=new fi(_,E);else if(m.mode===Kt.LINE_LOOP)f=new Bs(_,E);else if(m.mode===Kt.POINTS)f=new zs(_,E);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);Object.keys(f.geometry.morphAttributes).length>0&&c_(f,r),f.name=t.createUniqueName(r.name||"mesh_"+e),Bn(f,r),m.extensions&&Ai(i,f,m),t.assignFinalMaterial(f),u.push(f)}for(let p=0,g=u.length;p<g;p++)t.associations.set(u[p],{meshes:e,primitives:p});if(u.length===1)return r.extensions&&Ai(i,u[0],r),u[0];let d=new nn;r.extensions&&Ai(i,d,r),t.associations.set(d,{meshes:e});for(let p=0,g=u.length;p<g;p++)d.add(u[p]);return d})}loadCamera(e){let t,n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new dt(tc.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new _i(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Bn(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let i=0,r=t.joints.length;i<r;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){let r=i.pop(),o=i,a=[],c=[];for(let l=0,h=o.length;l<h;l++){let u=o[l];if(u){a.push(u);let d=new Ie;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 Ns(a,c)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,o=[],a=[],c=[],l=[],h=[];for(let u=0,d=i.channels.length;u<d;u++){let p=i.channels[u],g=i.samplers[p.sampler],_=p.target,m=_.node,f=i.parameters!==void 0?i.parameters[g.input]:g.input,E=i.parameters!==void 0?i.parameters[g.output]:g.output;_.node!==void 0&&(o.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",f)),c.push(this.getDependency("accessor",E)),l.push(g),h.push(_))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(l),Promise.all(h)]).then(function(u){let d=u[0],p=u[1],g=u[2],_=u[3],m=u[4],f=[];for(let E=0,T=d.length;E<T;E++){let M=d[E],L=p[E],R=g[E],w=_[E],N=m[E];if(M===void 0)continue;M.updateMatrix&&M.updateMatrix();let S=n._createAnimationTracks(M,L,R,w,N);if(S)for(let v=0;v<S.length;v++)f.push(S[v])}return new mi(r,void 0,f)})}createNodeMesh(e){let t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(r){let o=n._getNodeRef(n.meshCache,i.mesh,r);return i.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,l=i.weights.length;c<l;c++)a.morphTargetInfluences[c]=i.weights[c]}),o})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],r=n._loadNodeShallow(e),o=[],a=i.children||[];for(let l=0,h=a.length;l<h;l++)o.push(n.getDependency("node",a[l]));let c=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(o),c]).then(function(l){let h=l[0],u=l[1],d=l[2];d!==null&&h.traverse(function(p){p.isSkinnedMesh&&p.bind(d,u_)});for(let p=0,g=u.length;p<g;p++)h.add(u[p]);return h})}_loadNodeShallow(e){let t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let r=t.nodes[e],o=r.name?i.createUniqueName(r.name):"",a=[],c=i._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&a.push(c),r.camera!==void 0&&a.push(i.getDependency("camera",r.camera).then(function(l){return i._getNodeRef(i.cameraCache,r.camera,l)})),i._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){a.push(l)}),this.nodeCache[e]=Promise.all(a).then(function(l){let h;if(r.isBone===!0?h=new Ji:l.length>1?h=new nn:l.length===1?h=l[0]:h=new rt,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=o),Bn(h,r),r.extensions&&Ai(n,h,r),r.matrix!==void 0){let u=new Ie;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 i.associations.has(h)||i.associations.set(h,{}),i.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],i=this,r=new nn;n.name&&(r.name=i.createUniqueName(n.name)),Bn(r,n),n.extensions&&Ai(t,r,n);let o=n.nodes||[],a=[];for(let c=0,l=o.length;c<l;c++)a.push(i.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let h=0,u=c.length;h<u;h++)r.add(c[h]);let l=h=>{let u=new Map;for(let[d,p]of i.associations)(d instanceof Ut||d instanceof _t)&&u.set(d,p);return h.traverse(d=>{let p=i.associations.get(d);p!=null&&u.set(d,p)}),u};return i.associations=l(r),r})}_createAnimationTracks(e,t,n,i,r){let o=[],a=e.name?e.name:e.uuid,c=[];$n[r.path]===$n.weights?e.traverse(function(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}):c.push(a);let l;switch($n[r.path]){case $n.weights:l=gn;break;case $n.rotation:l=_n;break;case $n.translation:case $n.scale:l=xn;break;default:n.itemSize===1?l=gn:l=xn;break}let h=i.interpolation!==void 0?r_[i.interpolation]:hi,u=this._getArrayFromAccessor(n);for(let d=0,p=c.length;d<p;d++){let g=new l(c[d]+"."+$n[r.path],t.array,u,h);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(g),o.push(g)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=Jc(t.constructor),i=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r++)i[r]=t[r]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){let i=this instanceof _n?Zc:ea;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function d_(s,e,t){let n=e.attributes,i=new It;if(n.POSITION!==void 0){let a=t.json.accessors[n.POSITION],c=a.min,l=a.max;if(c!==void 0&&l!==void 0){if(i.set(new P(c[0],c[1],c[2]),new P(l[0],l[1],l[2])),a.normalized){let h=Jc(us[a.componentType]);i.min.multiplyScalar(h),i.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let r=e.targets;if(r!==void 0){let a=new P,c=new P;for(let l=0,h=r.length;l<h;l++){let u=r[l];if(u.POSITION!==void 0){let d=t.json.accessors[u.POSITION],p=d.min,g=d.max;if(p!==void 0&&g!==void 0){if(c.setX(Math.max(Math.abs(p[0]),Math.abs(g[0]))),c.setY(Math.max(Math.abs(p[1]),Math.abs(g[1]))),c.setZ(Math.max(Math.abs(p[2]),Math.abs(g[2]))),d.normalized){let _=Jc(us[d.componentType]);c.multiplyScalar(_)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}s.boundingBox=i;let o=new Dt;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=o}function xu(s,e,t){let n=e.attributes,i=[];function r(o,a){return t.getDependency("accessor",o).then(function(c){s.setAttribute(a,c)})}for(let o in n){let a=Kc[o]||o.toLowerCase();a in s.attributes||i.push(r(n[o],a))}if(e.indices!==void 0&&!s.index){let o=t.getDependency("accessor",e.indices).then(function(a){s.setIndex(a)});i.push(o)}return Be.workingColorSpace!==vt&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Be.workingColorSpace}" not supported.`),Bn(s,e),d_(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?a_(s,e.targets,t):s})}var f_={dark:{bg:"#0a0e27",amb:16777215,key:16777215,fill:10075135},light:{bg:"#f5f5f7",amb:16777215,key:16777215,fill:16771272}},p_=window.matchMedia("(prefers-reduced-motion: reduce)").matches;function m_(){let s=document.getElementById("artifact-config");if(!s)throw new Error("artifact-config script tag not found");let e=JSON.parse(s.textContent);if(!e.glb)throw new Error("artifact-config.glb missing");return e}function g_(s){let e=atob(s),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return n.buffer}function __(s){let e=f_[s.theme==="light"?"light":"dark"],t=s.bg&&/^#?[0-9a-f]{6}$/i.test(s.bg)?`#${s.bg.replace(/^#/,"")}`:e.bg;return{...e,bg:t}}function x_(s,e){let t=s.clientWidth||600,n=s.clientHeight||600,i=new $o({antialias:!0,alpha:!0});i.setPixelRatio(Math.min(window.devicePixelRatio||1,2)),i.setSize(t,n,!1),i.outputColorSpace=lt,i.toneMapping=co,i.toneMappingExposure=1.05,i.domElement.style.display="block",i.domElement.style.width="100%",i.domElement.style.height="100%",s.appendChild(i.domElement);let r=new Ls;r.background=new be(e.bg);let o=new dt(38,t/n,.05,50);o.position.set(0,1.4,2.7),o.lookAt(0,1.05,0),r.add(new Zs(e.amb,.85));let a=new Kn(e.key,1.25);a.position.set(2.5,5,3),r.add(a);let c=new Kn(e.fill,.45);return c.position.set(-3,1.5,-2),r.add(c),new ResizeObserver(()=>{let h=s.clientWidth,u=s.clientHeight;!h||!u||(o.aspect=h/u,o.updateProjectionMatrix(),i.setSize(h,u,!1))}).observe(s),{renderer:i,scene:r,camera:o}}function y_(s){let e=new It().setFromObject(s),t=e.getSize(new P),n=e.getCenter(new P),r=1.8/Math.max(t.y,.001);s.scale.setScalar(r),s.position.copy(n.multiplyScalar(-r)),s.position.y+=t.y*r/2}function v_(s,e){if(!s?.length)return null;if(e){let t=s.find(n=>n.name===e);if(t)return t}return s.find(t=>/idle|breathing|stand/i.test(t.name))||s[0]}function jc(s,e){s.querySelector(".artifact-error")?.remove();let t=document.createElement("div");t.className="artifact-error",t.textContent=e,Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.65)",color:"#f87171",font:"14px/1.4 system-ui, sans-serif",padding:"24px",textAlign:"center"}),s.appendChild(t)}function M_(s,e,t){if(!e.name)return;let n=document.createElement("div");n.className="artifact-name-plate",n.textContent=e.name;let i=t.bg&&/^#[ef]/i.test(t.bg);Object.assign(n.style,{position:"absolute",left:"16px",bottom:"16px",padding:"6px 12px",borderRadius:"999px",font:"500 13px/1 system-ui, -apple-system, sans-serif",letterSpacing:"0.01em",color:i?"#111":"#fff",background:i?"rgba(255,255,255,0.85)":"rgba(0,0,0,0.55)",backdropFilter:"blur(8px)",pointerEvents:"none",userSelect:"none"}),s.appendChild(n)}async function vu(){let s=document.getElementById("artifact-stage");if(!s)throw new Error("artifact-stage element not found");s.style.position="relative";let e=m_(),t=__(e);s.style.background=t.bg;let{renderer:n,scene:i,camera:r}=x_(s,t),o;try{o=g_(e.glb)}catch(c){jc(s,"Failed to decode embedded model: "+c.message);return}new Qo().parse(o,"",c=>{let l=c.scene||c.scenes?.[0];if(!l){jc(s,"Embedded GLB has no scene");return}y_(l),i.add(l);let h=null,u=v_(c.animations,e.idle);u&&(h=new $s(l),h.clipAction(u).play()),M_(s,e,t);let d=new Js,p=0,g=l.scale.clone();function _(){requestAnimationFrame(_);let m=d.getDelta();p+=m,h&&h.update(m),p_||(l.rotation.y+=m*.32,l.scale.y=g.y*(1+Math.sin(p*1.1)*.006)),n.render(i,r)}_()},c=>{jc(s,"Model parse failed: "+(c?.message||c))})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{vu().catch(s=>console.error("[artifact-viewer]",s))}):vu().catch(s=>console.error("[artifact-viewer]",s));})();diff --git a/public/artifact/index.html b/public/artifact/index.htmlindex f07079a9f..80b046498 100644--- a/public/artifact/index.html+++ b/public/artifact/index.html@@ -3,173 +3,736 @@<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>three.ws Artifact Demo</title>+ <title>three.ws — Claude.ai artifact</title>+ <meta+ name="description"+ content="Embed an interactive three.ws agent inside a Claude.ai artifact. Self-contained HTML, zero external dependencies."+ />+ <link rel="stylesheet" href="/style.css" /><style>- * {- margin: 0;- padding: 0;- box-sizing: border-box;+ body {+ overflow: auto;+ background: radial-gradient(circle at 50% 0%, #1a0d3a 0%, #0a0e27 50%, #06081a 100%);}- body {- font-family:- system-ui,- -apple-system,- sans-serif;- background: #0a0e27;- color: #fff;+ .artifact-page {+ max-width: 1180px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg) var(--space-2xl);display: flex;flex-direction: column;+ gap: var(--space-2xl);+ }++ .hero {+ text-align: center;+ display: flex;+ flex-direction: column;+ gap: var(--space-md);align-items: center;- justify-content: center;- min-height: 100vh;- padding: 20px;}- .container {- max-width: 800px;- width: 100%;+ .eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 4px 12px;+ border-radius: 999px;+ font-size: var(--text-sm);+ font-weight: 500;+ color: var(--accent);+ background: var(--accent-soft);+ border: 1px solid var(--accent-soft);+ letter-spacing: 0.04em;+ text-transform: uppercase;}- h1 {- text-align: center;- margin-bottom: 20px;- font-size: 28px;+ .eyebrow::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow: 0 0 12px var(--accent);+ }++ h1.headline {+ font-family: var(--font-display);+ font-size: clamp(2rem, 5vw, 3.4rem);+ font-weight: 700;+ line-height: 1.05;+ margin: 0;+ letter-spacing: -0.02em;+ background: linear-gradient(180deg, #fff 0%, #b9b3ff 100%);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }++ .lede {+ max-width: 580px;+ color: rgba(255, 255, 255, 0.7);+ font-size: var(--text-lg);+ line-height: var(--leading-tight);+ margin: 0;+ }++ .builder {+ display: grid;+ grid-template-columns: minmax(320px, 1fr) minmax(0, 1.382fr);+ gap: var(--space-lg);+ align-items: stretch;+ }++ @media (max-width: 880px) {+ .builder {+ grid-template-columns: 1fr;+ }+ }++ .panel {+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-lg);+ padding: var(--space-lg);+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ min-width: 0;+ }++ .panel h2 {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: rgba(255, 255, 255, 0.85);+ letter-spacing: 0.02em;+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }++ .field label {+ font-size: var(--text-sm);+ color: rgba(255, 255, 255, 0.6);+ font-weight: 500;+ }++ .field input,+ .field select {+ background: rgba(0, 0, 0, 0.3);+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: #fff;+ padding: 10px 12px;+ border-radius: var(--radius-md);+ font: inherit;+ font-size: var(--text-base);+ transition:+ border-color 120ms,+ background 120ms;+ }++ .field input:focus,+ .field select:focus {+ outline: none;+ border-color: var(--accent);+ background: rgba(0, 0, 0, 0.4);+ }++ .field-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-sm);+ }++ .btn-row {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ }++ button.btn {+ flex: 1;+ min-width: 120px;+ background: var(--accent);+ color: #fff;+ border: none;+ padding: 11px 16px;+ border-radius: var(--radius-md);+ font: inherit;+ font-weight: 600;+ font-size: var(--text-base);+ cursor: pointer;+ transition:+ transform 80ms,+ filter 120ms;}- .info {- background: rgba(255, 255, 255, 0.05);+ button.btn:hover {+ filter: brightness(1.1);+ }++ button.btn:active {+ transform: scale(0.98);+ }++ button.btn.ghost {+ background: rgba(255, 255, 255, 0.06);+ color: rgba(255, 255, 255, 0.9);border: 1px solid rgba(255, 255, 255, 0.1);- border-radius: 8px;- padding: 16px;- margin-bottom: 20px;- font-size: 14px;- line-height: 1.6;}- .viewer-frame {+ button.btn.ghost:hover {+ background: rgba(255, 255, 255, 0.12);+ filter: none;+ }++ button.btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ filter: none;+ }++ .preview {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ }++ .preview-frame {+ flex: 1;+ min-height: 380px;background: #000;+ border-radius: var(--radius-md);border: 1px solid rgba(255, 255, 255, 0.1);- border-radius: 8px;overflow: hidden;- aspect-ratio: 16 / 9;- margin-bottom: 20px;+ position: relative;}- #agent3d {+ .preview-frame iframe {width: 100%;height: 100%;+ min-height: 380px;+ border: 0;+ display: block;}- .controls {+ .preview-overlay {+ position: absolute;+ inset: 0;display: flex;- gap: 10px;- flex-wrap: wrap;+ align-items: center;justify-content: center;+ flex-direction: column;+ gap: 12px;+ background: rgba(8, 8, 20, 0.92);+ color: rgba(255, 255, 255, 0.85);+ font-size: var(--text-sm);+ transition: opacity 200ms;+ text-align: center;+ padding: 24px;}- button {- background: rgba(59, 130, 246, 0.8);- border: none;+ .preview-overlay[hidden] {+ display: none;+ }++ .preview-overlay.error {+ color: #fca5a5;+ }++ .spinner {+ width: 28px;+ height: 28px;+ border: 2px solid rgba(255, 255, 255, 0.15);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 700ms linear infinite;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ .stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: var(--space-sm);+ }++ .stat {+ background: rgba(0, 0, 0, 0.25);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: var(--radius-md);+ padding: 10px 12px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .stat .label {+ font-size: var(--text-xs);+ color: rgba(255, 255, 255, 0.5);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ }++ .stat .value {+ font-family: var(--font-mono);+ font-size: var(--text-base);color: #fff;- padding: 10px 20px;- border-radius: 6px;- cursor: pointer;- font-size: 14px;- transition: background 0.2s;+ font-weight: 500;}- button:hover {- background: rgba(59, 130, 246, 1);+ .stat .value.ok {+ color: #6ee7b7;}- button:active {- transform: scale(0.98);+ .stat .value.warn {+ color: #fcd34d;+ }++ .stat .value.bad {+ color: #fca5a5;+ }++ details.snippet {+ background: rgba(0, 0, 0, 0.3);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-md);+ padding: var(--space-sm) var(--space-md);}- .input-group {+ details.snippet > summary {+ cursor: pointer;+ font-size: var(--text-sm);+ font-weight: 500;+ color: rgba(255, 255, 255, 0.75);+ list-style: none;display: flex;- gap: 10px;align-items: center;- margin-bottom: 10px;+ gap: 8px;+ }++ details.snippet > summary::-webkit-details-marker {+ display: none;+ }++ details.snippet > summary::before {+ content: '›';+ transition: transform 150ms;+ color: var(--accent);+ font-size: 1.2em;+ }++ details.snippet[open] > summary::before {+ transform: rotate(90deg);+ }++ details.snippet pre {+ margin: var(--space-sm) 0 0;+ padding: var(--space-md);+ background: #06081a;+ border-radius: var(--radius-md);+ color: #d8d4ff;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ line-height: 1.6;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-all;}- input {- background: rgba(255, 255, 255, 0.1);- border: 1px solid rgba(255, 255, 255, 0.2);+ .facts {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: var(--space-md);+ }++ .fact {+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: var(--radius-md);+ padding: var(--space-md);+ }++ .fact h3 {+ margin: 0 0 6px;+ font-size: var(--text-base);+ font-weight: 600;+ color: rgba(255, 255, 255, 0.92);+ }++ .fact p {+ margin: 0;+ font-size: var(--text-sm);+ color: rgba(255, 255, 255, 0.65);+ line-height: var(--leading-tight);+ }++ .toast {+ position: fixed;+ left: 50%;+ bottom: 32px;+ transform: translate(-50%, 24px);+ background: #14141c;color: #fff;- padding: 8px 12px;- border-radius: 4px;- flex: 1;+ padding: 10px 18px;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ font-size: var(--text-sm);+ font-weight: 500;+ opacity: 0;+ transition:+ opacity 180ms,+ transform 180ms;+ pointer-events: none;+ z-index: 50;+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);}- input::placeholder {- color: rgba(255, 255, 255, 0.5);+ .toast.show {+ opacity: 1;+ transform: translate(-50%, 0);+ }++ .csp-line {+ font-family: var(--font-mono);+ font-size: 11px;+ color: rgba(255, 255, 255, 0.4);+ word-break: break-all;+ padding: var(--space-sm) var(--space-md);+ background: rgba(0, 0, 0, 0.3);+ border-radius: var(--radius-sm);+ border: 1px solid rgba(255, 255, 255, 0.05);+ line-height: 1.5;}</style></head><body>- <div class="container">- <h1>three.ws Artifact Viewer</h1>-- <div class="info">- <p>- This demo shows how a three.ws renders inside a Claude Artifact. The bundle is- self-contained — no external dependencies or iframes.+ <main class="artifact-page">+ <header class="hero">+ <span class="eyebrow">Claude.ai artifact</span>+ <h1 class="headline">Embed your agent in Claude.ai</h1>+ <p class="lede">+ Paste a single URL into a Claude conversation. The response is one self-contained+ HTML document — three.js, GLTFLoader, and your agent's GLB are all inlined. No+ script blocked by Claude's sandbox CSP, no fetch that ever leaves the page.</p>- </div>-- <div class="input-group">- <input- type="text"- id="agentIdInput"- placeholder="Enter agent ID (e.g., from URL ?agentId=123)"- value=""- onkeydown="if(event.key==='Enter') loadAgent()"- />- <button onclick="loadAgent()">Load</button>- </div>-- <div class="viewer-frame">- <div id="agent3d" data-origin="https://three.ws/"></div>- </div>-- <div class="controls">- <button onclick="reloadAgent()">Reload</button>- </div>- </div>-- <!-- The artifact bundle -->- <script src="/artifact.js"></script>-- <script>- function getAgentIdFromUrl() {- return new URLSearchParams(window.location.search).get('agentId');- }-- function loadAgent() {- const input = document.getElementById('agentIdInput');- const agentId = input.value.trim();- if (!agentId) return;- history.pushState({}, '', '?agentId=' + encodeURIComponent(agentId));- document.getElementById('agent3d').setAttribute('data-agent-id', agentId);- }-- function reloadAgent() {- const el = document.getElementById('agent3d');- const agentId = el.getAttribute('data-agent-id');- if (!agentId) return;- el.removeAttribute('data-agent-id');- setTimeout(() => el.setAttribute('data-agent-id', agentId), 0);- }-- window.addEventListener('DOMContentLoaded', () => {- const agentId = getAgentIdFromUrl();- if (agentId) {- document.getElementById('agent3d').setAttribute('data-agent-id', agentId);- document.getElementById('agentIdInput').value = agentId;+ </header>++ <section class="builder">+ <div class="panel" aria-labelledby="config-h">+ <h2 id="config-h">Configure</h2>++ <div class="field">+ <label for="agentIdInput">Agent ID</label>+ <input+ type="text"+ id="agentIdInput"+ placeholder="e.g. 3f2a4c… (UUID or handle)"+ autocomplete="off"+ spellcheck="false"+ />+ </div>++ <div class="field-row">+ <div class="field">+ <label for="themeInput">Theme</label>+ <select id="themeInput">+ <option value="dark">dark</option>+ <option value="light">light</option>+ </select>+ </div>+ <div class="field">+ <label for="idleInput">Idle clip</label>+ <input+ type="text"+ id="idleInput"+ placeholder="(default)"+ autocomplete="off"+ spellcheck="false"+ />+ </div>+ </div>++ <div class="field">+ <label for="bgInput">Background hex (optional)</label>+ <input+ type="text"+ id="bgInput"+ placeholder="1a0533"+ maxlength="7"+ autocomplete="off"+ spellcheck="false"+ />+ </div>++ <div class="btn-row">+ <button class="btn" id="btnGenerate" type="button">Generate</button>+ <button class="btn ghost" id="btnReload" type="button" disabled>Reload</button>+ </div>++ <div class="stats" id="stats" hidden>+ <div class="stat">+ <span class="label">Artifact</span>+ <span class="value" id="statSize">—</span>+ </div>+ <div class="stat">+ <span class="label">First paint</span>+ <span class="value" id="statTtfp">—</span>+ </div>+ <div class="stat">+ <span class="label">Sandbox</span>+ <span class="value" id="statSandbox">—</span>+ </div>+ </div>++ <details class="snippet">+ <summary>Claude artifact sandbox CSP</summary>+ <div class="csp-line" id="cspText">Loading actual CSP from Claude.ai mirror…</div>+ </details>+ </div>++ <div class="panel preview" aria-labelledby="preview-h">+ <h2 id="preview-h">Live preview</h2>++ <div class="preview-frame">+ <iframe+ id="previewFrame"+ title="Claude.ai artifact preview"+ sandbox="allow-scripts"+ referrerpolicy="no-referrer"+ ></iframe>+ <div class="preview-overlay" id="previewOverlay">+ <div>Enter an agent ID and press <strong>Generate</strong></div>+ </div>+ </div>++ <div class="btn-row">+ <button class="btn" id="btnCopyUrl" type="button" disabled>Copy URL</button>+ <button class="btn ghost" id="btnCopyHtml" type="button" disabled>+ Copy raw HTML+ </button>+ <button class="btn ghost" id="btnOpen" type="button" disabled>Open in tab</button>+ </div>++ <details class="snippet">+ <summary>Paste-into-Claude snippet</summary>+ <pre id="claudeSnippet">Generate to see the snippet…</pre>+ </details>+ </div>+ </section>++ <section class="facts">+ <div class="fact">+ <h3>Self-contained</h3>+ <p>+ three.js, GLTFLoader, and the GLB are all inlined. The page renders with zero+ network calls — fully compatible with Claude's sandbox CSP that forbids fetch+ and external scripts.+ </p>+ </div>+ <div class="fact">+ <h3>Sandbox-locked CSP</h3>+ <p>+ The response sets a CSP mirroring Claude's own. Behavior in the live preview+ matches behavior inside Claude.ai — no surprises between staging and prod.+ </p>+ </div>+ <div class="fact">+ <h3>Size budget</h3>+ <p>+ GLBs over 6 MB are rejected — Claude's artifact panel can hang on huge inlined+ payloads. The viewer adds a flat 565 KB on top of the model.+ </p>+ </div>+ </section>+ </main>++ <div class="toast" id="toast" role="status" aria-live="polite"></div>++ <script type="module">+ const $ = (id) => document.getElementById(id);+ const els = {+ agentInput: $('agentIdInput'),+ themeInput: $('themeInput'),+ idleInput: $('idleInput'),+ bgInput: $('bgInput'),+ btnGenerate: $('btnGenerate'),+ btnReload: $('btnReload'),+ btnCopyUrl: $('btnCopyUrl'),+ btnCopyHtml: $('btnCopyHtml'),+ btnOpen: $('btnOpen'),+ frame: $('previewFrame'),+ overlay: $('previewOverlay'),+ stats: $('stats'),+ statSize: $('statSize'),+ statTtfp: $('statTtfp'),+ statSandbox: $('statSandbox'),+ snippet: $('claudeSnippet'),+ toast: $('toast'),+ cspText: $('cspText'),+ };++ const state = { url: null, html: null };++ function showOverlay(message, isError = false) {+ els.overlay.hidden = false;+ els.overlay.classList.toggle('error', isError);+ els.overlay.innerHTML = isError+ ? `<div>${escapeHtml(message)}</div>`+ : `<div class="spinner"></div><div>${escapeHtml(message)}</div>`;+ }++ function hideOverlay() {+ els.overlay.hidden = true;+ }++ function escapeHtml(s) {+ return String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]);+ }++ function toast(msg) {+ els.toast.textContent = msg;+ els.toast.classList.add('show');+ clearTimeout(toast._t);+ toast._t = setTimeout(() => els.toast.classList.remove('show'), 1600);+ }++ function buildUrl() {+ const agentId = els.agentInput.value.trim();+ if (!agentId) return null;+ const url = new URL('/api/artifact', window.location.origin);+ url.searchParams.set('agent', agentId);+ if (els.themeInput.value === 'light') url.searchParams.set('theme', 'light');+ const idle = els.idleInput.value.trim();+ if (idle) url.searchParams.set('idle', idle);+ const bg = els.bgInput.value.trim().replace(/^#/, '');+ if (/^[0-9a-f]{6}$/i.test(bg)) url.searchParams.set('bg', bg);+ return url.toString();+ }++ function fmtBytes(n) {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(2)} MB`;+ }++ async function generate() {+ const url = buildUrl();+ if (!url) {+ showOverlay('Enter an agent ID first.', true);+ return;}+ state.url = url;+ history.replaceState({}, '', '?agentId=' + encodeURIComponent(els.agentInput.value.trim()));++ showOverlay('Fetching artifact…');+ els.btnReload.disabled = true;+ els.btnCopyUrl.disabled = true;+ els.btnCopyHtml.disabled = true;+ els.btnOpen.disabled = true;+ els.stats.hidden = true;++ const t0 = performance.now();+ let res, html;+ try {+ res = await fetch(url, { credentials: 'omit' });+ } catch (err) {+ showOverlay(`Network error: ${err.message}`, true);+ return;+ }+ if (!res.ok) {+ let body;+ try {+ body = await res.json();+ } catch {+ body = null;+ }+ const msg = body?.error_description || body?.error || `HTTP ${res.status}`;+ showOverlay(`${msg}`, true);+ return;+ }+ html = await res.text();+ const t1 = performance.now();++ state.html = html;+ const cspHeader = res.headers.get('content-security-policy') || '';+ const sandboxOk = /frame-ancestors\s+\*/.test(cspHeader);+ const sizeBytes = new Blob([html]).size;++ els.statSize.textContent = fmtBytes(sizeBytes);+ els.statSize.className =+ 'value ' + (sizeBytes > 8 * 1024 * 1024 ? 'bad' : sizeBytes > 5 * 1024 * 1024 ? 'warn' : 'ok');+ els.statTtfp.textContent = `${(t1 - t0).toFixed(0)} ms`;+ els.statTtfp.className =+ 'value ' + (t1 - t0 > 2000 ? 'warn' : t1 - t0 > 5000 ? 'bad' : 'ok');+ els.statSandbox.textContent = sandboxOk ? 'compliant' : 'mismatch';+ els.statSandbox.className = 'value ' + (sandboxOk ? 'ok' : 'bad');+ els.stats.hidden = false;++ els.frame.srcdoc = html;+ hideOverlay();++ els.btnReload.disabled = false;+ els.btnCopyUrl.disabled = false;+ els.btnCopyHtml.disabled = false;+ els.btnOpen.disabled = false;++ els.snippet.textContent =+ "Here's my agent for this conversation:\n" + state.url;+ }++ els.btnGenerate.addEventListener('click', generate);+ els.btnReload.addEventListener('click', generate);++ els.agentInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') generate();+ });++ els.btnCopyUrl.addEventListener('click', async () => {+ if (!state.url) return;+ await navigator.clipboard.writeText(state.url);+ toast('URL copied');+ });++ els.btnCopyHtml.addEventListener('click', async () => {+ if (!state.html) return;+ await navigator.clipboard.writeText(state.html);+ toast(`Raw HTML copied (${fmtBytes(new Blob([state.html]).size)})`);});++ els.btnOpen.addEventListener('click', () => {+ if (state.url) window.open(state.url, '_blank', 'noopener');+ });++ (function loadCsp() {+ const cspUrl =+ 'https://raw.githubusercontent.com/simonw/scrape-claude-artifacts/main/content-security-policy.txt';+ fetch(cspUrl)+ .then((r) => (r.ok ? r.text() : Promise.reject()))+ .then((txt) => {+ els.cspText.textContent = txt.trim();+ })+ .catch(() => {+ els.cspText.textContent =+ 'Could not reach simonw/scrape-claude-artifacts — see specs/CLAUDE_ARTIFACT.md for the locked-in copy.';+ });+ })();++ (function init() {+ const initialId = new URLSearchParams(window.location.search).get('agentId');+ if (initialId) {+ els.agentInput.value = initialId;+ generate();+ }+ })();</script></body></html>diff --git a/public/eth-vanity.html b/public/eth-vanity.htmlindex c3473becd..b6f448e60 100644--- a/public/eth-vanity.html+++ b/public/eth-vanity.html@@ -129,12 +129,15 @@<div class="card"><h2>2. Pattern</h2>- <p class="desc">Hex characters only (0–9, a–f). Each extra character is 16× harder.</p>+ <p class="desc">+ Hex characters only (0–9, a–f). Each extra character is 16× harder.+ <strong>Mixed case</strong> (e.g. <code>Beef</code>) matches the EIP-55 checksum — visually distinctive, ~2× harder per letter.+ </p><div class="row2"><div><label for="prefix">Prefix (after 0x)</label>- <input id="prefix" type="text" maxlength="10" placeholder="e.g. beef" autocomplete="off" spellcheck="false" />+ <input id="prefix" type="text" maxlength="10" placeholder="e.g. beef or Beef" autocomplete="off" spellcheck="false" /></div><div><label for="suffix">Suffix</label>@@ -142,11 +145,13 @@</div></div>+ <div class="preset-row" id="word-chips" aria-label="Quick-pick patterns" style="margin-top:.6rem"></div>+<div class="preview" id="preview" aria-live="polite"></div><div class="row"><span id="est">type a pattern to see estimated time</span>- <span id="cores-row">cores: <span id="cores">?</span></span>+ <span id="cores-row">cores: <span id="cores">?</span> <span id="case-tag" style="margin-left:.5rem"></span></span></div><div class="actions">@@ -178,8 +183,10 @@import { grindCreate2Vanity } from '/src/eth/vanity/grinder.js';import {validatePattern, validateAddress, validateInitCodeHash,- estimateAttempts, formatTimeEstimate, MAX_PATTERN_LENGTH,+ estimateAttempts, formatTimeEstimate, letterCount, eip55Checksum,+ MAX_PATTERN_LENGTH,} from '/src/eth/vanity/validation.js';+ import { PRESET_CHIPS } from '/src/eth/vanity/wordlist.js';const $ = (id) => document.getElementById(id);const HEX_ALPHA = '0123456789abcdef';@@ -205,9 +212,14 @@if (seconds < 31536000) return `~${Math.round(seconds/86400)}d`;return '>1y';}- function estSeconds(prefixLen, suffixLen) {+ function estSeconds(prefixLen, suffixLen, letters = 0, caseSensitive = false) {const total = prefixLen + suffixLen;- return total <= 0 ? 0 : Math.pow(16, total) / (RATE_PER_CORE * cores);+ if (total <= 0) return 0;+ const base = Math.pow(16, total);+ const tax = caseSensitive ? Math.pow(2, letters) : 1;+ // case-sensitive mode pays an extra keccak per attempt → ~30% slower hot loop.+ const ratePerCore = caseSensitive ? RATE_PER_CORE * 0.7 : RATE_PER_CORE;+ return (base * tax) / (ratePerCore * cores);}function bytesToHex(bytes) {let s = '';@@ -233,6 +245,21 @@});});+ // ── Wordlist chips ────────────────────────────────────────────────+ const chipsEl = $('word-chips');+ PRESET_CHIPS.forEach((w) => {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'preset';+ b.textContent = w;+ b.addEventListener('click', () => {+ $('prefix').value = w;+ $('prefix').dispatchEvent(new Event('input'));+ $('prefix').focus();+ });+ chipsEl.appendChild(b);+ });+// ── Auto-hash raw initCode → fill initcode-hash ────────────────────$('initcode-raw').addEventListener('input', () => {const raw = $('initcode-raw').value.trim();@@ -247,9 +274,11 @@// ── Live preview / validation ──────────────────────────────────────function readPattern() {- const p = $('prefix').value.trim().replace(/^0x/i, '').toLowerCase();- const s = $('suffix').value.trim().toLowerCase();- return { p, s };+ // Preserve casing — the grinder switches into EIP-55 mode if any char is uppercase.+ const p = $('prefix').value.trim().replace(/^0x/i, '');+ const s = $('suffix').value.trim();+ const caseSensitive = /[A-F]/.test(p) || /[A-F]/.test(s);+ return { p, s, caseSensitive };}let previewLoop = null;function startPreviewLoop() {@@ -264,9 +293,9 @@function stopPreviewLoop() { if (previewLoop) clearInterval(previewLoop); previewLoop = null; }function update() {- const { p, s } = readPattern();- const pv = p ? validatePattern(p) : { valid: true, errors: [] };- const sv = s ? validatePattern(s) : { valid: true, errors: [] };+ const { p, s, caseSensitive } = readPattern();+ const pv = p ? validatePattern(p) : { valid: true, errors: [], caseSensitive: false };+ const sv = s ? validatePattern(s) : { valid: true, errors: [], caseSensitive: false };$('prefix').classList.toggle('invalid', !!p && !pv.valid);$('suffix').classList.toggle('invalid', !!s && !sv.valid);@@ -276,9 +305,11 @@$('initcode-hash').classList.toggle('invalid', !!$('initcode-hash').value && !ich.valid);const total = (pv.valid ? p.length : 0) + (sv.valid ? s.length : 0);+ const letters = letterCount(p) + letterCount(s);if (total === 0) {$('preview').innerHTML = `<span class="rest">0x${esc(sample())}</span>`;$('est').textContent = 'type a pattern to see estimated time';+ $('case-tag').innerHTML = '';} else {const mid = sample('', '').slice(0, 40 - p.length - s.length);$('preview').innerHTML =@@ -286,7 +317,10 @@(p ? `<span class="pfx">${esc(p)}</span>` : '') +`<span class="rest">${esc(mid)}</span>` +(s ? `<span class="sfx">${esc(s)}</span>` : '');- $('est').textContent = `est. ${fmtTime(estSeconds(p.length, s.length))} on ${cores} cores`;+ $('est').textContent = `est. ${fmtTime(estSeconds(p.length, s.length, letters, caseSensitive))} on ${cores} cores`;+ $('case-tag').innerHTML = caseSensitive+ ? `<span style="background:linear-gradient(90deg,rgba(167,139,250,0.2),rgba(99,102,241,0.2));color:#c4b5fd;border:1px solid rgba(167,139,250,0.25);padding:.05rem .4rem;border-radius:999px;font-size:.7rem">EIP-55 case-sensitive</span>`+ : '';}$('grind').disabled =@@ -307,7 +341,7 @@let abort = null;$('grind').addEventListener('click', async () => {- const { p, s } = readPattern();+ const { p, s, caseSensitive } = readPattern();const dv = validateAddress($('deployer').value);const ich = validateInitCodeHash($('initcode-hash').value);if (!dv.valid) { showError(dv.error); return; }@@ -320,7 +354,7 @@$('error').hidden = true;$('attempts').textContent = '0';$('rate').textContent = '0/s';- $('eta').textContent = fmtTime(estSeconds(p.length, s.length));+ $('eta').textContent = fmtTime(estSeconds(p.length, s.length, letterCount(p) + letterCount(s), caseSensitive));$('scan').textContent = `0x${sample(p, s)}`;stopPreviewLoop();@@ -371,7 +405,10 @@$('grind').textContent = 'Grind another';$('progress').hidden = true;- const addrNoPrefix = result.address.slice(2); // 40 hex chars+ // Use the checksummed (EIP-55) form for display when the user+ // asked for a case-sensitive match; otherwise show lowercase.+ const display = result.caseSensitive ? result.addressChecksum : result.address;+ const addrNoPrefix = display.slice(2);const mid = addrNoPrefix.slice(p.length, addrNoPrefix.length - s.length);const html = `<div class="result">@@ -383,13 +420,14 @@(s ? `<span class="sfx">${esc(s)}</span>` : '')}</div>+ ${result.caseSensitive ? `<div class="out-row"><span class="k">lowercase</span> ${esc(result.address)}</div>` : ''}<div class="out-row"><span class="k">salt</span> ${esc(result.salt)}</div><div class="out-row"><span class="k">deployer</span> ${esc(result.deployer)}</div><div class="out-row"><span class="k">initCodeHash</span> ${esc(result.initCodeHash)}</div><div class="meta">${result.attempts.toLocaleString()} attempts in ${(result.durationMs/1000).toFixed(1)}sacross ${result.workers} cores- (${Math.round(result.attempts / (result.durationMs/1000)).toLocaleString()}/s)+ (${Math.round(result.attempts / (result.durationMs/1000)).toLocaleString()}/s)${result.caseSensitive ? ' · EIP-55 case-sensitive' : ''}</div><div class="actions"><button id="copy-salt" class="btn primary" type="button">Copy salt</button>@@ -408,17 +446,18 @@renderAssignBlock(result, p, s);$('copy-salt').addEventListener('click', () => copy(result.salt, 'copy-salt', 'Copy salt'));- $('copy-addr').addEventListener('click', () => copy(result.address, 'copy-addr', 'Copy address'));+ $('copy-addr').addEventListener('click', () => copy(result.caseSensitive ? result.addressChecksum : result.address, 'copy-addr', 'Copy address'));$('download').addEventListener('click', () => {const payload = {- address: result.address,- salt: result.salt,- deployer: result.deployer,- initCodeHash: result.initCodeHash,- pattern: { prefix: p || null, suffix: s || null },- attempts: result.attempts,- durationMs: result.durationMs,- generatedAt: new Date().toISOString(),+ address: result.address,+ addressChecksum: result.addressChecksum,+ salt: result.salt,+ deployer: result.deployer,+ initCodeHash: result.initCodeHash,+ pattern: { prefix: p || null, suffix: s || null, caseSensitive: !!result.caseSensitive },+ attempts: result.attempts,+ durationMs: result.durationMs,+ generatedAt: new Date().toISOString(),};const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });const url = URL.createObjectURL(blob);@@ -521,6 +560,7 @@predicted_address: result.address,prefix: p || null,suffix: s || null,+ case_sensitive: !!result.caseSensitive,deployer_label: presetLabel,};try {diff --git a/public/pay/calls/index.html b/public/pay/calls/index.htmlnew file mode 100644index 000000000..e09988cc6--- /dev/null+++ b/public/pay/calls/index.html@@ -0,0 +1,324 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width,initial-scale=1" />+<title>three.ws · paid call · x402</title>+<meta name="description" content="An x402 paid call to three.ws/api/mcp — settled on Solana, $0.001 USDC." />+<meta property="og:type" content="article" />+<meta property="og:title" content="three.ws · paid call (x402)" />+<meta property="og:image" content="" id="ogImage" />+<meta property="og:image:width" content="1200" />+<meta property="og:image:height" content="630" />+<meta name="twitter:card" content="summary_large_image" />+<meta name="twitter:image" content="" id="twImage" />+<meta name="theme-color" content="#0a0b10" />+<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+<style>+ :root {+ --bg: #0a0b10; --bg-2: #0f1119;+ --panel: #14161f; --panel-2: #1a1d29;+ --border: #232636; --border-strong: #2e3447;+ --text: #e6e8f0; --muted: #8a90a8;+ --accent: #8b5cf6; --accent-2: #22d3ee;+ --green: #22c55e; --orange: #f59e0b; --red: #ef4444;+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }+ body {+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ a { color: var(--accent-2); text-decoration: none; }+ a:hover { text-decoration: underline; }++ header {+ padding: 16px 28px;+ display: flex; align-items: center; justify-content: space-between;+ gap: 16px; border-bottom: 1px solid var(--border);+ background: linear-gradient(180deg, rgba(139,92,246,0.04), transparent);+ }+ .brand { display: flex; align-items: center; gap: 12px; }+ .brand .logo {+ width: 32px; height: 32px;+ background: conic-gradient(from 230deg, var(--accent), var(--accent-2), var(--accent));+ border-radius: 9px; box-shadow: 0 0 24px rgba(139, 92, 246, 0.5);+ }+ .brand a { color: var(--text); }+ .brand .title { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }+ .brand .sub { font-size: 12px; color: var(--muted); }++ main { max-width: 980px; margin: 32px auto; padding: 0 24px 64px; }++ .hero {+ padding: 24px 28px;+ border: 1px solid var(--border-strong);+ border-radius: 16px;+ background: linear-gradient(180deg, rgba(34, 211, 238, 0.06), rgba(139, 92, 246, 0.04), var(--panel));+ margin-bottom: 24px;+ }+ .hero .top { display: flex; gap: 14px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }+ .hero .badge {+ background: rgba(34, 197, 94, 0.12); color: var(--green);+ border: 1px solid rgba(34, 197, 94, 0.4);+ padding: 4px 10px; border-radius: 99px;+ font-size: 11px; font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.06em;+ }+ .hero h1 {+ margin: 0 0 4px; font-size: 22px; font-weight: 600; letter-spacing: -0.01em;+ }+ .hero .ts { color: var(--muted); font-size: 12px; font-family: var(--mono); }++ .grid {+ display: grid; gap: 18px;+ grid-template-columns: 1fr 1fr;+ }+ @media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }+ .card {+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 12px; padding: 18px 20px;+ }+ .card h2 {+ font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;+ color: var(--muted); margin: 0 0 12px;+ display: flex; align-items: center; gap: 8px;+ }+ .card h2::before {+ content: ''; width: 4px; height: 12px;+ background: var(--accent); border-radius: 2px;+ }+ .row {+ display: flex; justify-content: space-between; gap: 12px;+ font-size: 13px; padding: 6px 0;+ border-bottom: 1px dashed rgba(255,255,255,0.04);+ font-family: var(--mono);+ }+ .row:last-child { border-bottom: none; }+ .row .k { color: var(--muted); }+ .row .v { color: var(--text); word-break: break-all; text-align: right; }++ .result-block { margin-top: 24px; }+ .meta-grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));+ gap: 8px; margin-top: 12px;+ }+ .chip {+ background: var(--bg); border: 1px solid var(--border);+ border-radius: 8px; padding: 10px 12px;+ }+ .chip .k { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }+ .chip .v { font-size: 16px; font-family: var(--mono); margin-top: 2px; }++ .mv-block { margin-top: 16px; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; background: linear-gradient(180deg, #1a1d29, #0a0b10); }+ .mv-block model-viewer { width: 100%; height: 420px; display: block; --progress-bar-color: var(--accent); }+ .mv-block .caption { padding: 8px 14px; font-size: 11px; color: var(--muted); border-top: 1px solid var(--border); font-family: var(--mono); }++ .cta {+ margin-top: 32px; padding: 18px 22px;+ border: 1px solid var(--border);+ border-radius: 12px;+ background: linear-gradient(180deg, rgba(139,92,246,0.08), transparent);+ display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;+ }+ .cta .text { font-size: 14px; }+ .cta .btn {+ display: inline-block;+ background: var(--accent); color: #fff !important;+ padding: 10px 18px; border-radius: 10px;+ font-weight: 600; font-size: 14px; text-decoration: none;+ }+ .cta .btn:hover { background: #7c3aed; text-decoration: none; }++ .skeleton { color: var(--muted); padding: 32px; text-align: center; font-family: var(--mono); font-size: 13px; }+ .err { color: var(--red); padding: 32px; text-align: center; font-family: var(--mono); font-size: 13px; }++ pre.json {+ margin: 12px 0 0; padding: 12px; background: var(--bg);+ border: 1px solid var(--border); border-radius: 8px;+ font-family: var(--mono); font-size: 11px; line-height: 1.5;+ overflow-x: auto; max-height: 320px;+ }++ .opt-list { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }+ .opt-row { display: flex; gap: 10px; padding: 10px 12px; background: var(--bg); border-left: 3px solid var(--border); border-radius: 4px; }+ .opt-row.high { border-left-color: var(--red); background: rgba(239,68,68,0.05); }+ .opt-row.medium { border-left-color: var(--orange); background: rgba(245,158,11,0.05); }+ .opt-row.low { border-left-color: var(--green); background: rgba(34,197,94,0.05); }+ .opt-row .opt-icon { flex: 0 0 auto; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; }+ .opt-row.high .opt-icon { background: rgba(239,68,68,0.15); color: var(--red); }+ .opt-row.medium .opt-icon { background: rgba(245,158,11,0.15); color: var(--orange); }+ .opt-row.low .opt-icon { background: rgba(34,197,94,0.15); color: var(--green); }+ .opt-row .opt-body { flex: 1; min-width: 0; font-size: 13px; line-height: 1.5; }+ .opt-row .opt-title { font-weight: 600; }+ .opt-row .opt-detail { color: var(--muted); margin-top: 2px; font-size: 12px; }+</style>+</head>+<body>++<header>+ <div class="brand">+ <a href="/pay"><div class="logo"></div></a>+ <div>+ <div class="title">three.ws · pay-per-call</div>+ <div class="sub">paid x402 call · permalink</div>+ </div>+ </div>+ <a href="/pay" style="font-size: 13px;">← back to demo</a>+</header>++<main id="main">+ <div class="skeleton">loading paid call…</div>+</main>++<script type="module">+const main = document.getElementById('main');++function escape(s) { return String(s).replace(/[<>&]/g, c => ({'<':'<','>':'>','&':'&'}[c])); }+function formatBytes(n) {+ if (!Number.isFinite(n)) return '—';+ if (n < 1024) return `${n} B`;+ if (n < 1024*1024) return `${(n/1024).toFixed(1)} KB`;+ return `${(n/1024/1024).toFixed(1)} MB`;+}+function chip(k, v) { return `<div class="chip"><div class="k">${k}</div><div class="v">${v}</div></div>`; }+function modelViewer(url) {+ return `<div class="mv-block">+ <model-viewer src="${escape(url)}" autoplay auto-rotate camera-controls ar shadow-intensity="0.6" exposure="1.0" interaction-prompt="none" loading="eager" reveal="auto"></model-viewer>+ <div class="caption">rendered from <code>${escape(url)}</code></div>+ </div>`;+}+function parseTextResult(result) {+ const c = result?.content?.[0];+ if (c?.type === 'text' && typeof c.text === 'string') {+ try { return JSON.parse(c.text); } catch { return c.text; }+ }+ return null;+}++function renderResultBlock(record) {+ const { tool, args, result } = record;+ const url = args?.url || '';+ if (tool === 'tools/list') {+ const tools = result?.tools || [];+ return `<div class="card"><h2>${tools.length} MCP tools returned</h2>+ <pre class="json">${escape(tools.map(t => t.name + (t.title ? ' · ' + t.title : '')).join('\n'))}</pre>+ </div>`;+ }+ if (tool === 'validate_model') {+ const t = parseTextResult(result);+ if (!t) return `<div class="card"><h2>validate_model</h2><pre class="json">${escape(JSON.stringify(result, null, 2))}</pre></div>`;+ const issues = t.issues || {};+ const errs = Number(issues.numErrors ?? 0);+ const meta = t.meta || {};+ return `<div class="card"><h2>validate_model</h2>+ <div style="font-size:15px">${errs === 0 ? '✅ glTF spec-compliant' : '❌ ' + errs + ' errors'}</div>+ <div class="meta-grid">+ ${meta.vertices != null ? chip('vertices', Number(meta.vertices).toLocaleString()) : ''}+ ${meta.triangles != null ? chip('triangles', Number(meta.triangles).toLocaleString()) : ''}+ ${meta.meshes != null ? chip('meshes', meta.meshes) : ''}+ ${meta.materials != null ? chip('materials', meta.materials) : ''}+ ${meta.textures != null ? chip('textures', meta.textures) : ''}+ ${meta.bytes != null ? chip('size', formatBytes(meta.bytes)) : ''}+ </div>+ ${url ? modelViewer(url) : ''}+ </div>`;+ }+ if (tool === 'inspect_model') {+ const t = parseTextResult(result);+ if (!t) return `<div class="card"><h2>inspect_model</h2><pre class="json">${escape(JSON.stringify(result, null, 2))}</pre></div>`;+ const meta = t.meta || t;+ return `<div class="card"><h2>inspect_model</h2>+ <div class="meta-grid">+ ${meta.vertices != null ? chip('vertices', Number(meta.vertices).toLocaleString()) : ''}+ ${meta.triangles != null ? chip('triangles', Number(meta.triangles).toLocaleString()) : ''}+ ${meta.meshes != null ? chip('meshes', meta.meshes) : ''}+ ${meta.materials != null ? chip('materials', meta.materials) : ''}+ ${meta.textures != null ? chip('textures', meta.textures) : ''}+ ${meta.bytes != null ? chip('size', formatBytes(meta.bytes)) : ''}+ </div>+ ${url ? modelViewer(url) : ''}+ </div>`;+ }+ if (tool === 'optimize_model') {+ const t = parseTextResult(result);+ const sugs = t?.suggestions || t?.recommendations || [];+ return `<div class="card"><h2>optimize_model · ${sugs.length} suggestion${sugs.length===1?'':'s'}</h2>+ <div class="opt-list">+ ${sugs.map(s => {+ const sev = (s.severity || s.priority || 'low').toLowerCase();+ const title = s.title || s.kind || s.id || 'suggestion';+ const detail = s.detail || s.description || s.message || '';+ return `<div class="opt-row ${sev}"><div class="opt-icon">${sev === 'high' ? '!' : sev === 'medium' ? '~' : '·'}</div><div class="opt-body"><div class="opt-title">${escape(title)}</div>${detail ? `<div class="opt-detail">${escape(detail)}</div>` : ''}</div></div>`;+ }).join('')}+ </div>+ ${url ? modelViewer(url) : ''}+ </div>`;+ }+ return `<div class="card"><h2>${escape(tool)}</h2>+ <pre class="json">${escape(JSON.stringify(result, null, 2)).slice(0, 4000)}</pre>+ </div>`;+}++function render(record) {+ const tx = record.tx;+ const explorer = `https://solscan.io/tx/${tx}`;+ const amount = (Number(record.amount || 1000) / 1e6).toFixed(6);+ const ts = new Date(record.ts || Date.now()).toUTCString();+ const url = record.args?.url;++ document.title = `${record.tool} · paid call · three.ws`;+ // Update OG meta+ document.querySelector('meta[property="og:title"]').content =+ `three.ws · ${record.tool} (${amount} USDC) · x402 paid call`;+ document.querySelector('meta[name="description"]').content =+ `${record.tool}${record.argsSummary ? ' · ' + record.argsSummary : ''} — paid ${amount} USDC on Solana, settled on-chain. View the receipt + result.`;++ main.innerHTML = `+ <div class="hero">+ <div class="top">+ <span class="badge">✓ settled on-chain</span>+ <span class="ts">${escape(ts)}</span>+ </div>+ <h1><code style="background: rgba(255,255,255,0.06); padding: 4px 10px; border-radius: 6px; font-family: var(--mono); font-size: 18px;">${escape(record.tool)}</code>${record.argsSummary ? ' · ' + escape(record.argsSummary) : ''}</h1>+ <div class="meta-grid" style="margin-top:14px">+ ${chip('amount', amount + ' USDC')}+ ${chip('network', 'Solana mainnet')}+ ${chip('payer', `${(record.payer||'').slice(0,4)}…${(record.payer||'').slice(-4)}`)}+ ${chip('payTo', `${(record.payTo||'').slice(0,4)}…${(record.payTo||'').slice(-4)}`)}+ </div>+ <div style="margin-top:14px;font-family:var(--mono);font-size:12px;color:var(--muted)">+ tx: <a href="${explorer}" target="_blank" rel="noopener">${escape(tx)} ↗</a>+ </div>+ </div>++ <div class="result-block">+ ${renderResultBlock(record)}+ </div>++ <div class="cta">+ <div class="text"><strong>Try it yourself.</strong> Pay $0.001 USDC for any MCP tool, settled per call on Solana — no API keys, no signup.</div>+ <a class="btn" href="/pay${url ? `?validate=${encodeURIComponent(url)}` : ''}">Open the demo →</a>+ </div>+ `;+}++const m = location.pathname.match(/^\/pay\/calls\/([1-9A-HJ-NP-Za-km-z]+)/);+const tx = m ? m[1] : null;++if (!tx) {+ main.innerHTML = `<div class="err">Missing transaction signature in URL.</div>`;+} else {+ fetch(`/api/x402-pay?call=${tx}`)+ .then(r => r.ok ? r.json() : r.json().then(e => Promise.reject(e.error || 'load_failed')))+ .then(render)+ .catch((err) => {+ main.innerHTML = `<div class="err">Couldn't load this paid call.<br/><br/>+ <a href="/pay">← back to demo</a> · + <a href="https://solscan.io/tx/${tx}" target="_blank" rel="noopener">view on Solscan</a></div>`;+ });+}+</script>++</body>+</html>diff --git a/public/pay/index.html b/public/pay/index.htmlindex e036891df..2558da068 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -3,15 +3,24 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />-<title>three.ws · pay-per-call demo (x402)</title>-<meta name="description" content="Live demo of x402 paid API calls on Solana. The on-page agent pays $0.001 USDC per request to the three.ws MCP server and renders the response in real time." />+<title>three.ws · pay-per-call (x402)</title>+<meta name="description" content="Live x402 demo — agent pays $0.001 USDC on Solana per request to call MCP tools, render glTF/GLB models, and inspect 3D assets. No keys, no signup, on-chain settlement per call." />+<meta property="og:title" content="three.ws · pay-per-call (x402)" />+<meta property="og:description" content="Live x402 demo — agent pays $0.001 USDC on Solana per MCP tool call. Settled on-chain, rendered live." />+<meta property="og:type" content="website" />+<meta property="og:url" content="https://three.ws/pay" />+<meta name="twitter:card" content="summary_large_image" />+<meta name="theme-color" content="#0a0b10" /><link rel="preconnect" href="https://api.mainnet-beta.solana.com" />+<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script><style>:root {--bg: #0a0b10;+ --bg-2: #0f1119;--panel: #14161f;--panel-2: #1a1d29;--border: #232636;+ --border-strong: #2e3447;--text: #e6e8f0;--muted: #8a90a8;--accent: #8b5cf6;@@ -28,56 +37,78 @@min-height: 100vh;display: flex;flex-direction: column;+ -webkit-font-smoothing: antialiased;}+ a { color: var(--accent-2); }+ a:hover { color: #67e8f9; }++ /* Header */header {- padding: 22px 32px 14px;+ padding: 16px 28px;display: flex;align-items: center;justify-content: space-between;- gap: 24px;+ gap: 16px;border-bottom: 1px solid var(--border);+ background: linear-gradient(180deg, rgba(139,92,246,0.04), transparent);}- .brand { display: flex; align-items: center; gap: 12px; }+ .brand { display: flex; align-items: center; gap: 12px; min-width: 0; }.brand .logo {width: 32px; height: 32px;background: conic-gradient(from 230deg, var(--accent), var(--accent-2), var(--accent));border-radius: 9px;- box-shadow: 0 0 20px rgba(139, 92, 246, 0.4);+ box-shadow: 0 0 24px rgba(139, 92, 246, 0.5);+ flex: 0 0 auto;}- .brand .title { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }- .brand .sub { font-size: 12px; color: var(--muted); }+ .brand .title { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; white-space: nowrap; }+ .brand .sub { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .header-right { display: flex; gap: 8px; align-items: center; }.pill {- display: inline-flex; align-items: center; gap: 6px;+ display: inline-flex; align-items: center; gap: 8px;background: var(--panel); border: 1px solid var(--border);padding: 6px 12px; border-radius: 99px;font-family: var(--mono); font-size: 12px;- color: var(--muted);+ color: var(--text);+ transition: border-color 0.2s;}.pill .dot {width: 6px; height: 6px; border-radius: 50%;background: var(--green); box-shadow: 0 0 8px var(--green);+ animation: pulse 2s ease-in-out infinite;+ }+ .pill.ticker .dot { background: var(--accent-2); box-shadow: 0 0 8px var(--accent-2); }+ .pill .label { color: var(--muted); }+ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }+ .pill.flash {+ border-color: var(--accent-2);+ animation: flash 0.6s ease-out;}+ @keyframes flash {+ 0% { background: var(--accent-2); color: #0a0b10; }+ 100% { background: var(--panel); }+ }++ /* Main */main {flex: 1; display: grid;- grid-template-columns: 1.4fr 1fr;+ grid-template-columns: 1.55fr 1fr;gap: 0; min-height: 0;}- @media (max-width: 900px) {+ @media (max-width: 980px) {main { grid-template-columns: 1fr; }- aside { border-left: none !important; border-top: 1px solid var(--border); }- }- section.chat {- display: flex; flex-direction: column; min-height: 0;+ aside.status { border-left: none !important; border-top: 1px solid var(--border); }}+ section.chat { display: flex; flex-direction: column; min-height: 0; }.conv {flex: 1; overflow-y: auto;- padding: 24px 32px;- display: flex; flex-direction: column; gap: 16px;- }- .msg {- display: flex; gap: 12px; align-items: flex-start;- animation: fade 0.18s ease-out;+ padding: 22px 28px;+ display: flex; flex-direction: column; gap: 14px;+ scroll-behavior: smooth;}+ .msg { display: flex; gap: 12px; align-items: flex-start; animation: fade 0.18s ease-out; }@keyframes fade {from { opacity: 0; transform: translateY(4px); }to { opacity: 1; transform: translateY(0); }@@ -94,12 +125,12 @@color: #0a0b10;}.msg .body {- flex: 1;+ flex: 1; min-width: 0;background: var(--panel);border: 1px solid var(--border);border-radius: 12px;padding: 12px 14px;- font-size: 14px; line-height: 1.5;+ font-size: 14px; line-height: 1.55;}.msg.user .body { background: var(--panel-2); }.msg .body code {@@ -111,10 +142,13 @@background: var(--bg); border: 1px solid var(--border);border-radius: 8px; overflow-x: auto;font-family: var(--mono); font-size: 12px; line-height: 1.5;+ max-height: 320px;}++ /* Composer */.composer {border-top: 1px solid var(--border);- padding: 16px 32px;+ padding: 14px 28px;background: linear-gradient(to bottom, transparent, rgba(0,0,0,0.2));}.quick {@@ -125,16 +159,12 @@color: var(--text);padding: 6px 12px; border-radius: 99px;font-size: 12px; cursor: pointer;- transition: border-color 0.15s, background 0.15s;- }- .quick button:hover {- border-color: var(--accent);- background: rgba(139, 92, 246, 0.08);+ transition: border-color 0.15s, background 0.15s, transform 0.05s;}+ .quick button:hover { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }+ .quick button:active { transform: translateY(1px); }.quick button:disabled { opacity: 0.4; cursor: not-allowed; }- .input-row {- display: flex; gap: 10px; align-items: stretch;- }+ .input-row { display: flex; gap: 10px; align-items: stretch; }.input-row input {flex: 1;background: var(--panel);@@ -146,33 +176,41 @@transition: border-color 0.15s;}.input-row input:focus { border-color: var(--accent); }- .input-row button {+ .input-row .send {background: var(--accent); color: #fff;- border: none; padding: 0 20px; border-radius: 10px;+ border: none; padding: 0 22px; border-radius: 10px;font-weight: 600; font-size: 14px; cursor: pointer;transition: background 0.15s, transform 0.05s;}- .input-row button:hover { background: #7c3aed; }- .input-row button:active { transform: translateY(1px); }- .input-row button:disabled { opacity: 0.5; cursor: not-allowed; }- aside {+ .input-row .send:hover { background: #7c3aed; }+ .input-row .send:active { transform: translateY(1px); }+ .input-row .send:disabled { opacity: 0.5; cursor: not-allowed; }++ /* Status sidebar */+ aside.status {border-left: 1px solid var(--border);- padding: 24px;+ padding: 22px 24px;background: var(--panel);overflow-y: auto;}- aside h2 {+ aside.status h2 {font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em;- color: var(--muted); margin: 0 0 14px;+ color: var(--muted); margin: 0 0 12px;+ display: flex; align-items: center; gap: 8px;+ }+ aside.status h2::before {+ content: '';+ width: 4px; height: 12px; background: var(--accent); border-radius: 2px;}.step {display: flex; align-items: flex-start; gap: 12px;padding: 10px 12px;border: 1px solid var(--border);border-radius: 10px;- margin-bottom: 8px;+ margin-bottom: 6px;background: var(--panel-2);font-size: 13px;+ transition: border-color 0.2s, background 0.2s;}.step .icon {width: 22px; height: 22px; flex: 0 0 auto;@@ -180,20 +218,39 @@display: flex; align-items: center; justify-content: center;font-size: 12px; background: var(--bg);border: 1px solid var(--border);+ transition: all 0.2s;+ }+ .step.active {+ border-color: var(--accent);+ background: linear-gradient(180deg, rgba(139,92,246,0.06), var(--panel-2));+ }+ .step.active .icon {+ background: var(--accent); color: #fff; border-color: var(--accent);+ animation: spin 1.2s linear infinite;}- .step.active { border-color: var(--accent); }- .step.active .icon { background: var(--accent); color: #fff; border-color: var(--accent); }- .step.done .icon { background: var(--green); color: #0a0b10; border-color: var(--green); }+ @keyframes spin { to { transform: rotate(360deg); } }+ .step.done .icon { background: var(--green); color: #0a0b10; border-color: var(--green); animation: none; }.step.error { border-color: var(--red); }- .step.error .icon { background: var(--red); color: #fff; border-color: var(--red); }+ .step.error .icon { background: var(--red); color: #fff; border-color: var(--red); animation: none; }.step .label { font-weight: 500; }- .step .meta { color: var(--muted); font-family: var(--mono); font-size: 11px; }+ .step .meta { color: var(--muted); font-family: var(--mono); font-size: 11px; margin-top: 2px; }++ /* Receipt */.receipt {- margin-top: 18px;+ margin-top: 14px;padding: 14px;border-radius: 10px;background: linear-gradient(180deg, rgba(34, 211, 238, 0.06), transparent);border: 1px solid rgba(34, 211, 238, 0.3);+ animation: receiptIn 0.4s ease-out;+ }+ @keyframes receiptIn {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+ }+ .receipt h3 {+ margin: 0 0 8px; font-size: 11px; text-transform: uppercase;+ letter-spacing: 0.08em; color: var(--accent-2);}.receipt .row {display: flex; justify-content: space-between; gap: 12px;@@ -204,6 +261,42 @@.receipt .row .v { color: var(--text); word-break: break-all; text-align: right; }.receipt a { color: var(--accent-2); text-decoration: none; }.receipt a:hover { text-decoration: underline; }+ .receipt .actions {+ display: flex; gap: 6px; margin-top: 10px; flex-wrap: wrap;+ }+ .receipt .actions a, .receipt .actions button {+ flex: 1;+ background: var(--panel-2); border: 1px solid var(--border);+ color: var(--text); padding: 6px 10px; border-radius: 6px;+ font-size: 11px; text-decoration: none; text-align: center;+ cursor: pointer; transition: border-color 0.15s, background 0.15s;+ font-family: inherit;+ }+ .receipt .actions a:hover, .receipt .actions button:hover {+ border-color: var(--accent-2);+ }+ .copied { background: rgba(34, 197, 94, 0.15) !important; color: var(--green) !important; }++ /* Curl drawer */+ details.curl { margin-top: 14px; }+ details.curl summary {+ cursor: pointer; font-size: 11px; color: var(--muted);+ text-transform: uppercase; letter-spacing: 0.08em;+ padding: 6px 0;+ list-style: none;+ }+ details.curl summary::-webkit-details-marker { display: none; }+ details.curl summary::before { content: '▸ '; }+ details.curl[open] summary::before { content: '▾ '; }+ details.curl pre {+ margin: 6px 0 0; padding: 10px 12px;+ background: var(--bg); border: 1px solid var(--border);+ border-radius: 8px; overflow-x: auto;+ font-family: var(--mono); font-size: 11px; line-height: 1.5;+ color: var(--accent-2);+ }++ /* Errors */.err {color: var(--red); font-family: var(--mono); font-size: 12px;padding: 10px 12px;@@ -211,34 +304,179 @@border: 1px solid rgba(239, 68, 68, 0.3);border-radius: 8px;}- .avatars-grid {- display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));- gap: 8px; margin-top: 8px;++ /* Result chips */+ .meta-grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ gap: 8px; margin-top: 10px;}- .avatars-grid .card {+ .chip {background: var(--bg); border: 1px solid var(--border);- border-radius: 8px; padding: 8px;- font-size: 12px; line-height: 1.3;+ border-radius: 8px; padding: 8px 10px;}- .avatars-grid .card .name { font-weight: 600; word-break: break-word; }- .avatars-grid .card .slug { color: var(--muted); font-family: var(--mono); font-size: 11px; }- .meta-grid {- display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));- gap: 8px; margin-top: 8px;+ .chip .k { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }+ .chip .v { font-size: 14px; font-family: var(--mono); margin-top: 2px; word-break: break-word; }++ /* Tools list */+ .tools-list { display: flex; flex-direction: column; gap: 6px; margin-top: 10px; }+ .tool-row {+ display: flex; justify-content: space-between; gap: 12px;+ padding: 8px 10px; background: var(--bg);+ border: 1px solid var(--border); border-radius: 8px;+ font-size: 12px;+ }+ .tool-row .name { font-family: var(--mono); color: var(--accent-2); }+ .tool-row .desc { color: var(--muted); }+ .tool-row .price {+ font-family: var(--mono); font-size: 11px; color: var(--orange);+ background: rgba(245, 158, 11, 0.1);+ border: 1px solid rgba(245, 158, 11, 0.3);+ padding: 2px 6px; border-radius: 4px; flex: 0 0 auto;+ }++ /* Avatars */+ .avatars-grid {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));+ gap: 10px; margin-top: 10px;}- .meta-grid .chip {+ .avatar-card {background: var(--bg); border: 1px solid var(--border);- border-radius: 8px; padding: 8px 10px;+ border-radius: 10px; overflow: hidden;+ transition: border-color 0.2s, transform 0.15s;+ }+ .avatar-card:hover { border-color: var(--accent); transform: translateY(-1px); }+ .avatar-card model-viewer {+ width: 100%; height: 140px;+ background: linear-gradient(180deg, #1a1d29, #0a0b10);+ --poster-color: transparent;+ }+ .avatar-card .body { padding: 8px 10px; }+ .avatar-card .name { font-weight: 600; font-size: 12px; }+ .avatar-card .slug { color: var(--muted); font-family: var(--mono); font-size: 10px; }++ /* Model viewer block */+ .mv-block {+ margin-top: 10px;+ border: 1px solid var(--border);+ border-radius: 10px; overflow: hidden;+ background: linear-gradient(180deg, #1a1d29, #0a0b10);}- .meta-grid .chip .k { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }- .meta-grid .chip .v { font-size: 14px; font-family: var(--mono); margin-top: 2px; }- .footer-note {- padding: 10px 32px 18px;- font-size: 11px; color: var(--muted);- text-align: center;+ .mv-block model-viewer {+ width: 100%; height: 320px; display: block;+ --progress-bar-color: var(--accent);+ }+ .mv-block .caption {+ padding: 6px 10px; font-size: 11px; color: var(--muted);+ border-top: 1px solid var(--border);+ font-family: var(--mono);+ display: flex; justify-content: space-between; gap: 12px;+ }++ /* Optimize / inspect cards */+ .opt-list { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }+ .opt-row {+ display: flex; gap: 10px;+ padding: 10px 12px; background: var(--bg);+ border-left: 3px solid var(--border);+ border-radius: 4px;+ }+ .opt-row.high { border-left-color: var(--red); background: rgba(239,68,68,0.05); }+ .opt-row.medium { border-left-color: var(--orange); background: rgba(245,158,11,0.05); }+ .opt-row.low { border-left-color: var(--green); background: rgba(34,197,94,0.05); }+ .opt-row .opt-icon {+ flex: 0 0 auto; width: 24px; height: 24px;+ border-radius: 50%; display: flex; align-items: center; justify-content: center;+ font-size: 14px;+ }+ .opt-row.high .opt-icon { background: rgba(239,68,68,0.15); color: var(--red); }+ .opt-row.medium .opt-icon { background: rgba(245,158,11,0.15); color: var(--orange); }+ .opt-row.low .opt-icon { background: rgba(34,197,94,0.15); color: var(--green); }+ .opt-row .opt-body { flex: 1; min-width: 0; font-size: 13px; line-height: 1.5; }+ .opt-row .opt-title { font-weight: 600; }+ .opt-row .opt-detail { color: var(--muted); margin-top: 2px; font-size: 12px; }++ /* Tree (inspect) */+ .tree { margin-top: 8px; font-family: var(--mono); font-size: 12px; line-height: 1.6; }+ .tree-node { padding-left: 14px; border-left: 1px dashed var(--border); margin-left: 4px; }+ .tree-node .tag { color: var(--accent-2); }+ .tree-node .stat { color: var(--muted); }++ /* Footer & activity feed */+ footer.feed {border-top: 1px solid var(--border);+ padding: 8px 28px;+ background: var(--bg-2);+ display: flex; align-items: center; gap: 12px;+ font-size: 11px; font-family: var(--mono);+ overflow: hidden;+ }+ .feed-label {+ color: var(--muted); flex: 0 0 auto;+ text-transform: uppercase; letter-spacing: 0.06em;+ }+ .feed-track {+ flex: 1; overflow: hidden; position: relative;+ height: 18px;+ }+ .feed-strip {+ display: flex; gap: 28px;+ white-space: nowrap;+ animation: marquee 60s linear infinite;+ }+ .feed-strip:hover { animation-play-state: paused; }+ @keyframes marquee {+ from { transform: translateX(0); }+ to { transform: translateX(-50%); }+ }+ .feed-item { color: var(--text); }+ .feed-item .tool { color: var(--accent-2); }+ .feed-item .ago { color: var(--muted); }++ /* Walkthrough overlay */+ .overlay {+ position: fixed; inset: 0; background: rgba(0,0,0,0.7);+ backdrop-filter: blur(8px);+ display: none; align-items: center; justify-content: center;+ z-index: 100;+ }+ .overlay.show { display: flex; }+ .walkthrough {+ background: var(--panel);+ border: 1px solid var(--border-strong);+ border-radius: 16px;+ padding: 28px 32px;+ max-width: 480px; width: calc(100% - 32px);+ animation: walkIn 0.25s ease-out;+ }+ @keyframes walkIn {+ from { opacity: 0; transform: scale(0.96); }+ to { opacity: 1; transform: scale(1); }+ }+ .walkthrough h1 { margin: 0 0 4px; font-size: 22px; letter-spacing: -0.01em; }+ .walkthrough p { color: var(--muted); margin: 0 0 18px; font-size: 14px; }+ .walkthrough .steps { display: flex; flex-direction: column; gap: 10px; margin-bottom: 18px; }+ .walkthrough .step-item {+ display: flex; gap: 12px; align-items: flex-start;+ padding: 10px 12px;+ border: 1px solid var(--border); border-radius: 10px;+ background: var(--panel-2);+ }+ .walkthrough .step-item .num {+ width: 24px; height: 24px; flex: 0 0 auto;+ border-radius: 50%;+ background: conic-gradient(from 200deg, var(--accent), var(--accent-2));+ color: #0a0b10; font-weight: 700;+ display: flex; align-items: center; justify-content: center;+ font-size: 13px;+ }+ .walkthrough .step-item .text { font-size: 13px; line-height: 1.5; }+ .walkthrough .step-item .text b { color: var(--accent-2); }+ .walkthrough button {+ background: var(--accent); color: #fff; border: none;+ width: 100%; padding: 12px; border-radius: 10px;+ font-weight: 600; font-size: 14px; cursor: pointer;}- .footer-note code { font-family: var(--mono); }+ .walkthrough button:hover { background: #7c3aed; }</style></head><body>@@ -251,9 +489,16 @@<div class="sub">Live x402 demo — agent pays USDC on Solana per request</div></div></div>- <div class="pill" id="walletPill" title="Agent wallet on Solana mainnet">- <span class="dot"></span>- <span id="walletText">loading…</span>+ <div class="header-right">+ <div class="pill ticker" id="tickerPill" title="USDC settled this session">+ <span class="dot"></span>+ <span class="label">session</span>+ <span id="tickerText">0.000 USDC</span>+ </div>+ <div class="pill" id="walletPill" title="Agent wallet on Solana mainnet">+ <span class="dot"></span>+ <span id="walletText">loading…</span>+ </div></div></header>@@ -263,9 +508,9 @@<div class="msg agent"><div class="av">3</div><div class="body">- Hi. I'm the three.ws agent. Every request you send below triggers a real <strong>x402</strong> paid API call to <code>https://three.ws/api/mcp</code>: I pay <strong>$0.001 USDC on Solana mainnet</strong>, the facilitator settles on-chain, then the MCP tool runs and I render the response.+ Hi. I'm the three.ws agent. Every request below triggers a real <strong>x402</strong> paid API call to <code>three.ws/api/mcp</code>: I sign a Solana SPL transfer for <strong>$0.001 USDC</strong>, the facilitator settles on-chain, the MCP tool runs, and I render the result — including <em>actual 3D models</em> when the tool processes one.<br/><br/>- Try one of the chips below, or type your own model URL.+ Try one of the chips below, or paste a glTF/GLB URL.</div></div></div>@@ -279,31 +524,68 @@</div><div class="input-row"><input id="prompt" placeholder='Try: validate https://example.com/model.glb' autocomplete="off" />- <button id="send">Pay & Run</button>+ <button id="send" class="send">Pay & Run</button></div></div></section>- <aside id="status">+ <aside class="status"><h2>x402 settlement timeline</h2><div id="steps"></div><div id="receipt"></div></aside></main>-<div class="footer-note">- Source: <code>POST /api/x402-pay</code> → <code>POST /api/mcp</code> with <code>X-PAYMENT</code>. Settlement via <code>facilitator.payai.network</code>.+<footer class="feed">+ <span class="feed-label">recent paid calls</span>+ <div class="feed-track">+ <div class="feed-strip" id="feedStrip">+ <span class="feed-item"><span class="ago">…</span></span>+ </div>+ </div>+</footer>++<div class="overlay" id="walkthrough">+ <div class="walkthrough">+ <h1>How this works</h1>+ <p>Every action on this page costs the agent $0.001 USDC. Settled per call. No keys, no signup.</p>+ <div class="steps">+ <div class="step-item"><div class="num">1</div><div class="text">You click. The page POSTs to <b>/api/mcp</b>. The server replies <b>402 Payment Required</b> with the price.</div></div>+ <div class="step-item"><div class="num">2</div><div class="text">The agent wallet builds an <b>SPL transferChecked</b> on Solana, signs it, and re-sends the request with an <b>X-PAYMENT</b> header.</div></div>+ <div class="step-item"><div class="num">3</div><div class="text">The facilitator <b>verifies + settles</b> on-chain. The MCP tool runs. You see the result + a Solscan tx link in <2s.</div></div>+ </div>+ <button id="closeWalk">Got it — let's go</button>+ </div></div><script type="module">-const conv = document.getElementById('conv');-const stepsEl = document.getElementById('steps');-const receiptEl = document.getElementById('receipt');-const promptEl = document.getElementById('prompt');-const sendBtn = document.getElementById('send');-const quickEl = document.getElementById('quick');+const $ = (id) => document.getElementById(id);+const conv = $('conv'), stepsEl = $('steps'), receiptEl = $('receipt');+const promptEl = $('prompt'), sendBtn = $('send'), quickEl = $('quick');+const walletText = $('walletText'), walletPill = $('walletPill');+const tickerText = $('tickerText'), tickerPill = $('tickerPill');+const feedStrip = $('feedStrip'), walkthrough = $('walkthrough'), closeWalk = $('closeWalk');const DEMO_MODEL = 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';+const TOOL_PRICE_USDC = 0.001;++let sessionTotal = Number(sessionStorage.getItem('x402:total') || 0);+const renderTicker = () => { tickerText.textContent = `${sessionTotal.toFixed(3)} USDC`; };+renderTicker();++function escape(s) { return String(s).replace(/[<>&]/g, c => ({'<':'<','>':'>','&':'&'}[c])); }+function formatBytes(n) {+ if (!Number.isFinite(n)) return '—';+ if (n < 1024) return `${n} B`;+ if (n < 1024*1024) return `${(n/1024).toFixed(1)} KB`;+ return `${(n/1024/1024).toFixed(1)} MB`;+}+function ago(ts) {+ const d = Math.max(0, Date.now() - ts);+ if (d < 60_000) return `${Math.floor(d/1000)}s ago`;+ if (d < 3600_000) return `${Math.floor(d/60_000)}m ago`;+ return `${Math.floor(d/3600_000)}h ago`;+}function addMsg(role, html) {const el = document.createElement('div');@@ -322,7 +604,6 @@ const STEP_DEFS = [{ id: 'dispatched', label: 'Run MCP tool in-process' },{ id: 'settled', label: 'Facilitator settle (on-chain)' },];-function resetSteps() {stepsEl.innerHTML = '';receiptEl.innerHTML = '';@@ -334,72 +615,104 @@ function resetSteps() {stepsEl.appendChild(el);}}-function setStep(id, state, meta) {- const el = document.getElementById(`step-${id}`);+ const el = $(`step-${id}`);if (!el) return;el.className = `step ${state}`;const ic = el.querySelector('.icon');if (state === 'active') ic.textContent = '…';else if (state === 'done') ic.textContent = '✓';else if (state === 'error') ic.textContent = '!';- if (meta) el.querySelector('[data-meta]').textContent = meta;+ if (meta != null) el.querySelector('[data-meta]').textContent = meta;+}++function curlSnippet(call) {+ const body = JSON.stringify({+ jsonrpc: '2.0', id: 1,+ method: call.tool === 'tools/list' ? 'tools/list' : 'tools/call',+ params: call.tool === 'tools/list' ? undefined : { name: call.tool, arguments: call.args || {} },+ });+ return [+ `# 1) Get the 402 challenge`,+ `curl -i -X POST https://three.ws/api/mcp \\`,+ ` -H 'content-type: application/json' \\`,+ ` -d '${body}'`,+ ``,+ `# 2) Build & sign a Solana transferChecked, base64-encode the v2 paymentPayload,`,+ `# then re-POST with X-PAYMENT: <base64>. See scripts/x402-pay-three-ws-sol.mjs.`,+ ].join('\n');}-function renderReceipt(payment, durations) {+function renderReceipt(call, payment, durations) {const explorer = payment.tx ? `https://solscan.io/tx/${payment.tx}` : null;+ const permalink = payment.tx ? `${location.origin}/pay/calls/${payment.tx}` : null;receiptEl.innerHTML = `<div class="receipt">+ <h3>settlement receipt</h3><div class="row"><span class="k">amount</span><span class="v">${(Number(payment.amount) / 1e6).toFixed(6)} USDC</span></div><div class="row"><span class="k">network</span><span class="v">Solana mainnet</span></div><div class="row"><span class="k">payer</span><span class="v">${payment.payer.slice(0,8)}…${payment.payer.slice(-4)}</span></div><div class="row"><span class="k">payTo</span><span class="v">${payment.payTo.slice(0,8)}…${payment.payTo.slice(-4)}</span></div><div class="row"><span class="k">total</span><span class="v">${durations.total_ms} ms</span></div>${explorer ? `<div class="row"><span class="k">tx</span><span class="v"><a href="${explorer}" target="_blank" rel="noopener">${payment.tx.slice(0,10)}…${payment.tx.slice(-6)} ↗</a></span></div>` : ''}+ <div class="actions">+ ${explorer ? `<a href="${explorer}" target="_blank" rel="noopener">view on Solscan</a>` : ''}+ ${permalink ? `<button data-copy="${permalink}">copy permalink</button>` : ''}+ <button data-replay>↻ replay</button>+ </div>+ <details class="curl">+ <summary>show equivalent curl</summary>+ <pre>${escape(curlSnippet(call))}</pre>+ </details></div>`;+ receiptEl.querySelector('[data-replay]')?.addEventListener('click', () => run(call, displayLabelFor(call)));+ for (const btn of receiptEl.querySelectorAll('[data-copy]')) {+ btn.addEventListener('click', async () => {+ try { await navigator.clipboard.writeText(btn.dataset.copy); btn.classList.add('copied'); btn.textContent = '✓ copied'; }+ catch { btn.textContent = 'copy failed'; }+ });+ }}-function renderResultBubble(tool, result) {- if (tool === 'tools/list') {- const tools = result?.tools || [];- return `<div><strong>${tools.length} tools available</strong> on the MCP server:</div>- <pre>${tools.map(t => `${t.name.padEnd(28)} ${t.title || ''}`).join('\n')}</pre>`;- }- if (tool === 'search_public_avatars') {- const text = parseTextResult(result);- if (text?.items) {- return `<div><strong>${text.items.length} public avatars</strong></div>- <div class="avatars-grid">${- text.items.map(a => `<div class="card"><div class="name">${escape(a.name || a.slug || '—')}</div><div class="slug">${escape(a.slug || '')}</div></div>`).join('')- }</div>`;- }- return defaultRender(result);- }- if (tool === 'validate_model') {- const text = parseTextResult(result);- if (text) {- const ok = text.ok ? '✅ valid' : '⚠️ warnings';- const meta = text.meta || {};- return `<div><strong>${ok}</strong> — ${(text.warnings || []).length} warnings</div>- <div class="meta-grid">- ${meta.vertices != null ? chip('vertices', meta.vertices.toLocaleString()) : ''}- ${meta.triangles != null ? chip('triangles', meta.triangles.toLocaleString()) : ''}- ${meta.materials != null ? chip('materials', meta.materials) : ''}- ${meta.meshes != null ? chip('meshes', meta.meshes) : ''}- ${meta.textures != null ? chip('textures', meta.textures) : ''}- ${meta.bytes != null ? chip('size', formatBytes(meta.bytes)) : ''}- </div>- ${(text.warnings || []).length ? `<pre>${text.warnings.join('\n')}</pre>` : ''}`;- }- }- if (tool === 'inspect_model') {- const text = parseTextResult(result);- if (text) return `<pre>${escape(JSON.stringify(text, null, 2)).slice(0, 1500)}</pre>`;- }- return defaultRender(result);+function displayLabelFor(call) {+ if (call.tool === 'tools/list') return '/list_tools';+ if (call.tool === 'search_public_avatars') return call.args?.q ? `/search ${call.args.q}` : '/search_avatars';+ const url = call.args?.url || '';+ const short = url.split('/').pop() || url;+ return `/${call.tool.replace('_model','')} ${short}`;+}++// ---- Result rendering ---------------------------------------------------++function modelViewerBlock(url, captionExtra) {+ return `+ <div class="mv-block">+ <model-viewer src="${escape(url)}" autoplay auto-rotate camera-controls+ ar shadow-intensity="0.6" exposure="1.0" interaction-prompt="none"+ loading="eager" reveal="auto"></model-viewer>+ <div class="caption">+ <span>rendered from <code>${escape(url.split('/').pop())}</code></span>+ <span>drag to rotate · scroll to zoom</span>+ </div>+ </div>`;}+function chip(k, v) { return `<div class="chip"><div class="k">${k}</div><div class="v">${v}</div></div>`; }-function defaultRender(result) { return `<pre>${escape(JSON.stringify(result, null, 2)).slice(0, 1500)}</pre>`; }++function renderToolsList(result) {+ const tools = result?.tools || [];+ const rows = tools.map(t => {+ const price = t.pricing?.amount_usdc;+ const priceTag = price ? `<span class="price">${price} USDC</span>` : '';+ return `<div class="tool-row">+ <div><div class="name">${escape(t.name)}</div><div class="desc">${escape((t.description || '').slice(0, 90))}</div></div>+ ${priceTag}+ </div>`;+ }).join('');+ return `<div><strong>${tools.length} MCP tools</strong> exposed by three.ws:</div>+ <div class="tools-list">${rows}</div>`;+}+function parseTextResult(result) {const c = result?.content?.[0];if (c?.type === 'text' && typeof c.text === 'string') {@@ -407,29 +720,138 @@ function parseTextResult(result) {}return null;}-function escape(s) { return String(s).replace(/[<>&]/g, c => ({'<':'<','>':'>','&':'&'}[c])); }-function formatBytes(n) {- if (n < 1024) return `${n} B`;- if (n < 1024*1024) return `${(n/1024).toFixed(1)} KB`;- return `${(n/1024/1024).toFixed(1)} MB`;++function renderValidate(args, result) {+ const text = parseTextResult(result);+ const url = args?.url || '';+ if (!text || typeof text !== 'object') {+ return `<div>Validation result:</div><pre>${escape(JSON.stringify(result, null, 2)).slice(0, 1500)}</pre>`;+ }+ const issues = text.issues || {};+ const errs = Number(issues.numErrors ?? 0);+ const warns = Number(issues.numWarnings ?? 0);+ const infos = Number(issues.numInfos ?? 0);+ const ok = errs === 0;+ const meta = text.meta || {};+ return `+ <div><strong>${ok ? '✅ glTF spec-compliant' : '❌ has errors'}</strong> — ${errs} errors, ${warns} warnings, ${infos} infos</div>+ <div class="meta-grid">+ ${meta.vertices != null ? chip('vertices', Number(meta.vertices).toLocaleString()) : ''}+ ${meta.triangles != null ? chip('triangles', Number(meta.triangles).toLocaleString()) : ''}+ ${meta.meshes != null ? chip('meshes', meta.meshes) : ''}+ ${meta.materials != null ? chip('materials', meta.materials) : ''}+ ${meta.textures != null ? chip('textures', meta.textures) : ''}+ ${meta.animations != null ? chip('animations', meta.animations) : ''}+ ${meta.bytes != null ? chip('size', formatBytes(meta.bytes)) : ''}+ ${meta.version ? chip('glTF', `v${meta.version}`) : ''}+ </div>+ ${url.startsWith('http') ? modelViewerBlock(url) : ''}`;+}++function renderInspect(args, result) {+ const text = parseTextResult(result);+ const url = args?.url || '';+ if (!text || typeof text !== 'object') return defaultRender(result);+ const meta = text.meta || text;+ const exts = (text.extensions || meta.extensionsUsed || []);+ const animations = text.animations || meta.animations || [];+ const meshes = text.meshes || [];+ return `+ <div><strong>Inspection complete</strong> · ${meta.scenes || 1} scene${(meta.scenes||1)>1?'s':''}, ${meta.nodes || '?'} nodes, ${meta.meshes || '?'} meshes</div>+ <div class="meta-grid">+ ${meta.vertices != null ? chip('vertices', Number(meta.vertices).toLocaleString()) : ''}+ ${meta.triangles != null ? chip('triangles', Number(meta.triangles).toLocaleString()) : ''}+ ${meta.materials != null ? chip('materials', meta.materials) : ''}+ ${meta.textures != null ? chip('textures', meta.textures) : ''}+ ${(animations.length || meta.animations) != null ? chip('animations', Array.isArray(animations) ? animations.length : meta.animations) : ''}+ ${meta.bytes != null ? chip('size', formatBytes(meta.bytes)) : ''}+ </div>+ ${exts.length ? `<div style="margin-top:10px;font-size:12px;color:var(--muted)">extensions: ${exts.map(e => `<code>${escape(e)}</code>`).join(' ')}</div>` : ''}+ ${Array.isArray(meshes) && meshes.length ? `+ <div class="tree" style="margin-top:10px;">+ ${meshes.slice(0, 8).map(m => `<div class="tree-node"><span class="tag">${escape(m.name || 'mesh')}</span> <span class="stat">· ${Number(m.vertices||0).toLocaleString()} verts · ${Number(m.triangles||0).toLocaleString()} tris</span></div>`).join('')}+ ${meshes.length > 8 ? `<div class="tree-node"><span class="stat">… ${meshes.length - 8} more</span></div>` : ''}+ </div>` : ''}+ ${url.startsWith('http') ? modelViewerBlock(url) : ''}`;+}++function renderOptimize(args, result) {+ const text = parseTextResult(result);+ const url = args?.url || '';+ if (!text || typeof text !== 'object') return defaultRender(result);+ const sugs = text.suggestions || text.recommendations || [];+ const sevIcon = (s) => s === 'high' ? '!' : s === 'medium' ? '~' : '·';+ const summary = text.summary || `${sugs.length} optimization suggestion${sugs.length===1?'':'s'}`;+ return `+ <div><strong>${escape(summary)}</strong></div>+ <div class="opt-list">+ ${sugs.slice(0, 12).map(s => {+ const sev = (s.severity || s.priority || 'low').toLowerCase();+ const title = s.title || s.name || s.kind || s.id || 'suggestion';+ const detail = s.detail || s.description || s.message || s.recommendation || '';+ const est = s.estimatedSavings || s.savings;+ return `<div class="opt-row ${sev}">+ <div class="opt-icon">${sevIcon(sev)}</div>+ <div class="opt-body">+ <div class="opt-title">${escape(title)}</div>+ ${detail ? `<div class="opt-detail">${escape(detail)}${est ? ` · est. <strong>${escape(String(est))}</strong> saved` : ''}</div>` : ''}+ </div>+ </div>`;+ }).join('')}+ </div>+ ${url.startsWith('http') ? modelViewerBlock(url) : ''}`;+}++function renderSearch(args, result) {+ const text = parseTextResult(result);+ const items = text?.items || text?.avatars || (Array.isArray(text) ? text : []);+ if (!items?.length) return `<div>No avatars matched.</div>${defaultRender(result)}`;+ const cards = items.map(a => {+ const url = a.model_url || a.url;+ return `<div class="avatar-card">+ ${url ? `<model-viewer src="${escape(url)}" auto-rotate disable-zoom interaction-prompt="none" loading="lazy" camera-orbit="0deg 80deg 2.5m" reveal="auto"></model-viewer>` : ''}+ <div class="body">+ <div class="name">${escape(a.name || a.slug || 'avatar')}</div>+ <div class="slug">${escape(a.slug || a.id || '')}</div>+ </div>+ </div>`;+ }).join('');+ return `<div><strong>${items.length} public avatar${items.length===1?'':'s'}</strong>${args?.q ? ` matching "${escape(args.q)}"` : ''}:</div>+ <div class="avatars-grid">${cards}</div>`;+}++function defaultRender(result) {+ return `<pre>${escape(JSON.stringify(result, null, 2)).slice(0, 1500)}</pre>`;+}++function renderResult(call, result) {+ if (call.tool === 'tools/list') return renderToolsList(result);+ if (call.tool === 'validate_model') return renderValidate(call.args, result);+ if (call.tool === 'inspect_model') return renderInspect(call.args, result);+ if (call.tool === 'optimize_model') return renderOptimize(call.args, result);+ if (call.tool === 'search_public_avatars') return renderSearch(call.args, result);+ return defaultRender(result);}+// ---- Prompt parsing -----------------------------------------------------+function parsePrompt(text) {const t = text.trim();if (!t) return null;- if (t === '/list_tools' || t === 'list tools' || t === 'tools/list') return { tool: 'tools/list', args: {} };+ if (/^(\/?list_tools|tools\/list|list tools)$/i.test(t)) return { tool: 'tools/list', args: {} };let m;if ((m = t.match(/^\/?validate(?:_model)?\s+(\S+)/i))) return { tool: 'validate_model', args: { url: m[1] } };if ((m = t.match(/^\/?inspect(?:_model)?\s+(\S+)/i))) return { tool: 'inspect_model', args: { url: m[1] } };- if ((m = t.match(/^\/?optimize(?:_model)?\s+(\S+)/i))) return { tool: 'optimize_model', args: { url: m[1] } };+ if ((m = t.match(/^\/?(?:optimize|fix|improve)(?:_model)?\s+(\S+)/i))) return { tool: 'optimize_model', args: { url: m[1] } };if ((m = t.match(/^\/?search(?:_avatars|_public_avatars)?(?:\s+(.+))?/i))) {return { tool: 'search_public_avatars', args: m[1] ? { q: m[1].trim(), limit: 12 } : { limit: 12 } };}if (t.startsWith('http')) return { tool: 'validate_model', args: { url: t } };- return { tool: 'validate_model', args: { url: t } };+ return { tool: 'search_public_avatars', args: { q: t, limit: 12 } };}-// Parse a Server-Sent Events stream from a fetch ReadableStream.+// ---- SSE consumer -------------------------------------------------------+async function* sseEvents(response) {const reader = response.body.getReader();const decoder = new TextDecoder();@@ -462,12 +884,11 @@ async function run(call, displayLabel) {for (const b of quickEl.querySelectorAll('button')) b.disabled = true;promptEl.disabled = true;- addMsg('user', escape(displayLabel));+ addMsg('user', escape(displayLabel || displayLabelFor(call)));resetSteps();setStep('challenge', 'active', 'requesting paymentRequirements…');const t0 = performance.now();- let final = null;- let errored = false;+ let final = null, errored = false;let activeId = 'challenge';try {@@ -483,47 +904,40 @@ async function run(call, displayLabel) {addMsg('agent', `<div class="err">x402 call failed: ${escape(parsed.error || res.statusText)}</div>`);return;}-for await (const { event, data } of sseEvents(res)) {if (event === 'challenge') {setStep('challenge', 'done', `${(Number(data.amount)/1e6).toFixed(6)} USDC`);- activeId = 'built';- setStep('built', 'active', 'signing partial Solana tx…');+ activeId = 'built'; setStep('built', 'active', 'signing partial Solana tx…');} else if (event === 'built') {setStep('built', 'done', `${data.build_ms} ms`);- activeId = 'verified';- setStep('verified', 'active', 'facilitator /verify…');+ activeId = 'verified'; setStep('verified', 'active', 'facilitator /verify…');} else if (event === 'verified') {setStep('verified', 'done', `${data.verify_ms} ms`);- activeId = 'dispatched';- setStep('dispatched', 'active', 'running MCP tool…');+ activeId = 'dispatched'; setStep('dispatched', 'active', 'running MCP tool…');} else if (event === 'dispatched') {setStep('dispatched', 'done', `${data.dispatch_ms} ms`);- activeId = 'settled';- setStep('settled', 'active', 'facilitator /settle (on-chain)…');+ activeId = 'settled'; setStep('settled', 'active', 'facilitator /settle (on-chain)…');} else if (event === 'settled') {setStep('settled', 'done', `${data.settle_ms} ms · ${data.tx ? data.tx.slice(0,8)+'…' : ''}`);} else if (event === 'result') {final = data;} else if (event === 'error') {setStep(activeId, 'error', data.error || 'failed');- addMsg('agent', `<div class="err">x402 call failed: ${escape(data.error || 'unknown')}${- data.mcpError ? ` · MCP: ${escape(data.mcpError.message || '')}` : ''- }</div>`);+ addMsg('agent', `<div class="err">x402 call failed: ${escape(data.error || 'unknown')}${data.mcpError ? ` · MCP: ${escape(data.mcpError.message || '')}` : ''}</div>`);errored = true;}}-if (errored) return;if (!final) {setStep(activeId, 'error', 'stream ended without result');addMsg('agent', `<div class="err">Stream ended without a result event.</div>`);return;}-- renderReceipt(final.payment, final.durations);- addMsg('agent', renderResultBubble(call.tool, final.result));+ renderReceipt(call, final.payment, final.durations);+ addMsg('agent', renderResult(call, final.result));+ bumpTicker();refreshBalance();+ refreshFeed();} catch (err) {setStep(activeId, 'error', String(err.message || err));addMsg('agent', `<div class="err">Network error: ${escape(String(err.message || err))}</div>`);@@ -537,7 +951,17 @@ async function run(call, displayLabel) {}}-const walletText = document.getElementById('walletText');+function bumpTicker() {+ sessionTotal += TOOL_PRICE_USDC;+ sessionStorage.setItem('x402:total', String(sessionTotal));+ renderTicker();+ tickerPill.classList.remove('flash');+ void tickerPill.offsetWidth;+ tickerPill.classList.add('flash');+}++// ---- Wallet balance + activity feed ------------------------------------+async function refreshBalance() {try {const r = await fetch('/api/x402-pay?balance=1');@@ -548,11 +972,27 @@ async function refreshBalance() {} else {walletText.textContent = 'agent wallet (no env)';}- } catch {- walletText.textContent = 'agent wallet';- }+ } catch { walletText.textContent = 'agent wallet'; }}+async function refreshFeed() {+ try {+ const r = await fetch('/api/x402-pay?feed=1');+ if (!r.ok) return;+ const f = await r.json();+ const items = (f.items || []).slice(0, 25);+ if (!items.length) { feedStrip.innerHTML = `<span class="feed-item"><span class="ago">no calls yet</span></span>`; return; }+ const make = () => items.map(it => `<span class="feed-item">+ <span class="tool">${escape(it.tool)}</span>+ <span class="ago">${ago(it.ts)}</span>+ ${it.tx ? `· <a href="https://solscan.io/tx/${it.tx}" target="_blank" rel="noopener">${it.tx.slice(0,6)}…</a>` : ''}+ </span>`).join('');+ feedStrip.innerHTML = make() + make();+ } catch {}+}++// ---- Wire up ------------------------------------------------------------+quickEl.addEventListener('click', (e) => {const btn = e.target.closest('button');if (!btn) return;@@ -576,9 +1016,21 @@ promptEl.addEventListener('keydown', (e) => {if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendBtn.click(); }});+closeWalk.addEventListener('click', () => {+ walkthrough.classList.remove('show');+ localStorage.setItem('x402:seen-walk', '1');+});+if (!localStorage.getItem('x402:seen-walk') && !location.search.includes('skipwalk=1')) {+ walkthrough.classList.add('show');+}++// ---- Init ---------------------------------------------------------------+resetSteps();refreshBalance();+refreshFeed();setInterval(refreshBalance, 30_000);+setInterval(refreshFeed, 20_000);// Deep-link prefill: /pay?validate=https://...glb auto-fires the call.const params = new URLSearchParams(location.search);@@ -589,13 +1041,11 @@ for (const [tool, alias] of []) {const url = params.get(alias);if (url) {- setTimeout(() => run({ tool, args: { url } }, `${alias} ${url.split('/').pop()}`), 200);+ setTimeout(() => run({ tool, args: { url } }), 250);break;}}-if (params.get('list') === '1') {- setTimeout(() => run({ tool: 'tools/list', args: {} }, '/list_tools'), 200);-}+if (params.get('list') === '1') setTimeout(() => run({ tool: 'tools/list', args: {} }), 250);promptEl.focus();</script>diff --git a/public/studio/launch-panel.js b/public/studio/launch-panel.jsindex f8a1df867..abb4cd81c 100644--- a/public/studio/launch-panel.js+++ b/public/studio/launch-panel.js@@ -1,20 +1,16 @@-// Launch panel for the character studio right column.-// Adds a "launch a token for this agent" form with bonding-curve progress visual.+// Launch panel for the studio right column.+// Self-contained: handles wallet detection, SOL balance, metadata upload,+// on-chain signing, confirmation, and success display — no separate modal.//-// Public API (pure, testable without DOM):+// Exported pure functions (keep for tests):// validateLaunchForm(fields) → { ok, errors }// handleLaunchSubmit(fields, onSubmit) → { ok, errors? }//-// DOM:-// mountLaunchPanel(container, opts) → teardown()+// DOM entry point:+// mountLaunchPanel(container, { getAvatar, getUser }) → { avatarChanged, teardown }-const FEE_TIERS = [- ['standard', 'Standard (0.25%)'],- ['boosted', 'Boosted (0.5%)'],- ['premium', 'Premium (1%)'],-];+// ── Pure validation (tested) ────────────────────────────────────────────────-/** Validate launch form fields. Returns { ok, errors } — no DOM side-effects. */export function validateLaunchForm({ name, symbol, description, initialBuy } = {}) {const errors = {};if (!name?.trim()) errors.name = 'Token name is required';@@ -27,7 +23,6 @@ export function validateLaunchForm({ name, symbol, description, initialBuy } = {return { ok: Object.keys(errors).length === 0, errors };}-/** Validate then call onSubmit(fields) if valid. Returns { ok, errors? }. */export function handleLaunchSubmit(fields, onSubmit) {const result = validateLaunchForm(fields);if (!result.ok) return result;@@ -35,164 +30,711 @@ export function handleLaunchSubmit(fields, onSubmit) {return { ok: true };}-function escHtml(s) {- return String(s ?? '').replace(- /[&<>"']/g,- (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+// ── Utilities ───────────────────────────────────────────────────────────────++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],);}-/**- * Mount the launch panel into `container`.- * opts.onSubmit(fields) — called when form passes validation.- * If omitted, dispatches pump-launch-open CustomEvent (consumed by mountPumpModals- * when loaded on the same page).- * Returns a teardown() function.- */-export function mountLaunchPanel(container, { onSubmit } = {}) {- const tierOpts = FEE_TIERS.map(- ([v, l]) => `<option value="${escHtml(v)}">${escHtml(l)}</option>`,- ).join('');-- container.innerHTML = `-<div class="launch-panel">- <p class="muted launch-panel-desc">- Launch a pump.fun bonding-curve token for this agent.- Fill in the details and submit — you'll sign one transaction with your Solana wallet.- </p>-- <label class="field">- <span>Token name <span class="launch-req">*</span></span>- <input type="text" name="lp-name" maxlength="32" placeholder="My Agent Token" />- <span class="launch-field-err" id="lp-err-name" hidden></span>- </label>-- <label class="field">- <span>Symbol <span class="launch-req">*</span></span>- <input type="text" name="lp-symbol" maxlength="10" placeholder="AGENT" />- <span class="launch-field-err" id="lp-err-symbol" hidden></span>- </label>-- <label class="field">- <span>Token image</span>- <input type="file" name="lp-image" accept="image/*" class="launch-file-input" />- <span class="muted" style="font-size:0.72rem">PNG or JPG — square recommended.</span>- </label>-- <label class="field">- <span>Description <span class="launch-req">*</span></span>- <textarea name="lp-description" rows="3" maxlength="500" placeholder="What does this agent do?"></textarea>- <span class="launch-field-err" id="lp-err-description" hidden></span>- </label>-- <label class="field">- <span>Initial buy (SOL)</span>- <input type="number" name="lp-initial-buy" min="0" max="50" step="0.01" value="0" />- <span class="muted" style="font-size:0.72rem">Optional creator buy-in on launch. 0 = no buy.</span>- <span class="launch-field-err" id="lp-err-initialbuy" hidden></span>- </label>-- <label class="field">- <span>Fee tier</span>- <select name="lp-fee-tier">${tierOpts}</select>- </label>-- <div class="bonding-curve-preview">- <div class="bonding-curve-header">- <span class="muted" style="font-size:0.72rem;text-transform:uppercase;letter-spacing:0.06em">Bonding curve</span>- <span id="lp-curve-pct" class="bonding-curve-pct">0%</span>- </div>- <div class="bonding-curve-track">- <div class="bonding-curve-fill" id="lp-curve-fill" style="width:0%"></div>- </div>- <div class="bonding-curve-labels">- <span>Genesis</span>- <span>Graduation ($69k)</span>- </div>- </div>-- <div class="launch-field-err" id="lp-err-global" style="margin-bottom:0.5rem" hidden></div>-- <button type="button" class="btn-primary" id="lp-submit" style="width:100%">- Launch token- </button>-</div>`;-- const q = (sel) => container.querySelector(sel);-- function getFields() {- return {- name: q('[name="lp-name"]').value,- symbol: q('[name="lp-symbol"]').value.toUpperCase().trim(),- description: q('[name="lp-description"]').value,- initialBuy: q('[name="lp-initial-buy"]').value,- feeTier: q('[name="lp-fee-tier"]').value,- image: q('[name="lp-image"]').files?.[0] ?? null,- };+function toSymbol(name) {+ return (name || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8) || 'AGENT';+}++function shortenAddr(addr) {+ if (!addr || addr.length < 10) return addr || '';+ return addr.slice(0, 4) + '…' + addr.slice(-4);+}++function detectWallet() {+ if (typeof window === 'undefined') return null;+ return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;+}++function fileToDataUrl(file) {+ return new Promise((res, rej) => {+ const reader = new FileReader();+ reader.onload = (e) => res(e.target.result);+ reader.onerror = rej;+ reader.readAsDataURL(file);+ });+}++function friendlyError(msg) {+ const m = String(msg || '');+ if (/user rejected|rejected the request/i.test(m)) return 'Wallet signing cancelled.';+ if (/0x1\b/.test(m) || /insufficient.*sol/i.test(m) || /insufficient lamports/i.test(m))+ return 'Transaction failed — not enough SOL for fees and rent. Fund your wallet and try again.';+ if (/wallet.*not.*found|no.*wallet.*detected/i.test(m))+ return 'No Solana wallet detected. Install Phantom or Backpack.';+ return m;+}++// pump.fun create fee + mint account rent (estimate; actual may vary slightly)+const PUMP_BASE_COST_SOL = 0.022;++// ── CSS ─────────────────────────────────────────────────────────────────────++const LP_STYLES = `+.lp { display: flex; flex-direction: column; gap: 0.9rem; }+.lp-empty { text-align: center; padding: 2.5rem 1rem; color: rgba(255,255,255,0.3);+ font-size: 0.85rem; line-height: 1.7; }+.lp-empty a { color: rgba(164,240,188,0.7); text-decoration: none; }+.lp-empty a:hover { color: #a4f0bc; }++/* Token card — image + name/symbol */+.lp-card {+ display: flex; gap: 0.8rem; align-items: flex-start;+ padding: 0.85rem; border-radius: 12px;+ background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07);+ transition: border-color 0.2s;+}+.lp-card:focus-within { border-color: rgba(255,255,255,0.14); }++/* Image drop zone */+.lp-img-zone {+ flex-shrink: 0; width: 78px; height: 78px; border-radius: 11px;+ border: 2px dashed rgba(255,255,255,0.14); cursor: pointer;+ overflow: hidden; display: flex; align-items: center; justify-content: center;+ background: rgba(255,255,255,0.03); position: relative; transition: all 0.2s;+}+.lp-img-zone:hover, .lp-img-zone.dragover { border-color: rgba(164,240,188,0.5); background: rgba(164,240,188,0.05); }+.lp-img-zone img { width: 100%; height: 100%; object-fit: cover; border-radius: 9px; }+.lp-img-ph { font-size: 0.62rem; color: rgba(255,255,255,0.28); text-align: center; line-height: 1.5; padding: 0.25rem; pointer-events: none; }+.lp-img-file { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }++/* Name + symbol inline in card */+.lp-card-fields { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 0.35rem; padding-top: 0.1rem; }+.lp-iname {+ width: 100%; font-size: 0.97rem; font-weight: 600;+ background: transparent; border: none; border-bottom: 1px solid rgba(255,255,255,0.09);+ color: #fff; padding: 0 0 0.28rem; outline: none; transition: border-color 0.15s;+}+.lp-iname:focus { border-bottom-color: rgba(255,255,255,0.28); }+.lp-iname::placeholder { color: rgba(255,255,255,0.2); font-weight: 400; }+.lp-isymbol {+ width: 100%; font-size: 0.8rem; background: transparent; border: none;+ color: #a4f0bc; padding: 0; outline: none;+ font-family: ui-monospace, monospace; letter-spacing: 0.05em;+}+.lp-isymbol::placeholder { color: rgba(164,240,188,0.28); }+.lp-img-hint { font-size: 0.6rem; color: rgba(255,255,255,0.2); margin-top: 0.3rem; }++/* Standard fields */+.lp label { font-size: 0.72rem; color: rgba(255,255,255,0.4); display: block; margin-bottom: 0.22rem; }+.lp textarea, .lp-number {+ width: 100%; padding: 0.5rem 0.7rem; border-radius: 8px; outline: none;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);+ color: #fff; font-size: 0.85rem; font-family: inherit; box-sizing: border-box;+ transition: border-color 0.15s;+}+.lp textarea { resize: vertical; }+.lp textarea:focus, .lp-number:focus { border-color: rgba(255,255,255,0.2); }+.lp-number::-webkit-inner-spin-button { opacity: 0.4; }++/* Two-column row */+.lp-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }++/* Buyback slider */+.lp-slider-head { display: flex; justify-content: space-between; align-items: baseline; }+.lp-bps-val { font-size: 0.78rem; color: #a4f0bc; font-weight: 500; }+.lp-slider { width: 100%; accent-color: #a4f0bc; margin-top: 0.4rem; cursor: pointer; }+.lp-slider-hint { font-size: 0.62rem; color: rgba(255,255,255,0.22); margin-top: 0.18rem; }++/* Wallet bar */+.lp-wallet {+ display: flex; align-items: center; gap: 0.55rem; padding: 0.58rem 0.8rem;+ background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07);+ border-radius: 10px; font-size: 0.78rem;+}+.lp-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; transition: background 0.3s; }+.lp-dot.on { background: #a4f0bc; box-shadow: 0 0 6px rgba(164,240,188,0.45); }+.lp-dot.off { background: rgba(255,255,255,0.18); }+.lp-wallet-info { flex: 1; min-width: 0; }+.lp-wallet-addr { color: rgba(255,255,255,0.75); }+.lp-wallet-bal { color: rgba(255,255,255,0.42); margin-left: 0.4rem; font-size: 0.73rem; }+.lp-wallet-cost { display: block; font-size: 0.69rem; margin-top: 0.1rem; }+.lp-wallet-cost.ok { color: #a4f0bc; }+.lp-wallet-cost.warn { color: #f6b3b3; }+.lp-wallet-cost.dim { color: rgba(255,255,255,0.3); }+.lp-wallet-none { flex: 1; color: rgba(255,255,255,0.32); }+.lp-wbtn {+ padding: 0.28rem 0.65rem; border-radius: 6px; cursor: pointer; flex-shrink: 0;+ background: rgba(255,255,255,0.07); border: 1px solid rgba(255,255,255,0.1);+ color: rgba(255,255,255,0.78); font-size: 0.72rem; white-space: nowrap;+ transition: background 0.15s;+}+.lp-wbtn:hover { background: rgba(255,255,255,0.13); }+.lp-wbtn.ghost { opacity: 0.4; font-size: 0.65rem; }++/* Launch button */+.lp-launch {+ width: 100%; padding: 0.8rem 1rem; border-radius: 10px; cursor: pointer;+ background: linear-gradient(135deg, rgba(120,200,140,0.22), rgba(60,140,100,0.14));+ border: 1px solid rgba(120,200,140,0.42); color: #c6f0d6;+ font-size: 0.94rem; font-weight: 600; letter-spacing: -0.01em;+ transition: all 0.15s; line-height: 1;+}+.lp-launch:hover:not([disabled]) {+ background: linear-gradient(135deg, rgba(120,200,140,0.33), rgba(60,140,100,0.22));+ border-color: rgba(120,200,140,0.65); color: #d8f5e2;+}+.lp-launch[disabled] { opacity: 0.38; cursor: not-allowed; }+.lp-launch.busy { opacity: 0.72; cursor: wait; }+.lp-phase { font-size: 0.7rem; color: rgba(255,255,255,0.35); text-align: center; min-height: 1.1em; margin-top: 0.15rem; }+.lp-err {+ font-size: 0.78rem; color: #f6b3b3; padding: 0.55rem 0.75rem; line-height: 1.5;+ border-radius: 8px; background: rgba(246,179,179,0.07); border: 1px solid rgba(246,179,179,0.18);+}+.lp-err-retry { margin-top: 0.35rem; font-size: 0.72rem; color: rgba(255,255,255,0.35); }++/* ── Success state ─────────────────────────────────── */+.lp-ok { display: flex; flex-direction: column; align-items: center; gap: 0.85rem; text-align: center; }+.lp-ok-thumb { width: 82px; height: 82px; border-radius: 50%; object-fit: cover;+ border: 2px solid rgba(164,240,188,0.4); }+.lp-ok-thumb-ph { width: 82px; height: 82px; border-radius: 50%;+ background: rgba(164,240,188,0.08); border: 2px solid rgba(164,240,188,0.2);+ display: flex; align-items: center; justify-content: center; font-size: 2.2rem; }+.lp-ok-title { font-size: 1.3rem; font-weight: 700; color: #a4f0bc; letter-spacing: -0.02em; margin: 0; }+.lp-ok-sub { font-size: 0.78rem; color: rgba(255,255,255,0.38); margin: -0.45rem 0 0; }+.lp-ok-mint {+ display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0.75rem;+ background: rgba(255,255,255,0.04); border-radius: 8px; width: 100%;+ font-family: ui-monospace, monospace; font-size: 0.75rem; color: rgba(255,255,255,0.6);+}+.lp-ok-mint span { flex: 1; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.lp-copy { padding: 0.2rem 0.5rem; border-radius: 5px; cursor: pointer; flex-shrink: 0;+ background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12);+ color: rgba(255,255,255,0.65); font-size: 0.7rem; white-space: nowrap; }+.lp-copy:hover { background: rgba(255,255,255,0.15); }+.lp-ok-links { display: flex; gap: 0.45rem; justify-content: center; flex-wrap: wrap; width: 100%; }+.lp-ext { padding: 0.38rem 0.7rem; border-radius: 7px; font-size: 0.78rem; text-decoration: none;+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);+ color: rgba(255,255,255,0.78); transition: all 0.15s; }+.lp-ext:hover { background: rgba(255,255,255,0.11); color: #fff; }+.lp-share { width: 100%; padding: 0.55rem 0.9rem; border-radius: 8px; cursor: pointer;+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);+ color: rgba(255,255,255,0.65); font-size: 0.8rem; }+.lp-share:hover { background: rgba(255,255,255,0.09); color: rgba(255,255,255,0.92); }+.lp-again { width: 100%; padding: 0.42rem; border-radius: 7px; cursor: pointer;+ background: transparent; border: 1px solid rgba(255,255,255,0.07);+ color: rgba(255,255,255,0.32); font-size: 0.77rem; }+.lp-again:hover { color: rgba(255,255,255,0.62); border-color: rgba(255,255,255,0.16); }+`;++let _stylesInjected = false;+function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const el = document.createElement('style');+ el.textContent = LP_STYLES;+ document.head.appendChild(el);+}++// ── Mount ────────────────────────────────────────────────────────────────────++const DEMO_ID = '__demo__';++export function mountLaunchPanel(container, { getAvatar, getUser } = {}) {+ injectStyles();++ let av = null; // current avatar object++ // All mutable UI + launch state in one flat object+ let s = {+ // form (seeded from avatar on mount / avatar change)+ name: '',+ symbol: '',+ description: '',+ initialBuy: '0',+ buybackBps: 500,+ imageFile: null,+ imagePreviewUrl: null, // data URL of custom image; falls back to av.thumbnail_url+ _symbolEdited: false, // user manually typed a symbol++ // wallet+ walletAddr: null,+ solBalance: null,++ // launch state machine+ phase: 'idle', // idle | building | signing | confirming | success | error+ phaseLabel: '',+ errorMsg: '',++ // results+ mint: null,+ resolvedAgentId: null,++ // metadata cache+ _metaUrl: null,+ _metaKey: null, // `name|symbol|description` the cached URL was built for+ };++ // ── Helpers ────────────────────────────────────────────────────────────++ function estimatedCost() {+ return PUMP_BASE_COST_SOL + Math.max(0, parseFloat(s.initialBuy) || 0);+ }++ function formValid() {+ return s.name.trim() && s.symbol.trim() && s.description.trim();}- function clearErrors() {- for (const el of container.querySelectorAll('.launch-field-err')) {- el.hidden = true;- el.textContent = '';+ // ── Wallet ─────────────────────────────────────────────────────────────++ async function tryAutoConnect() {+ const w = detectWallet();+ if (!w?.isConnected || !w.publicKey) return;+ const addr = w.publicKey.toBase58?.() || w.publicKey.toString?.();+ if (addr && addr !== s.walletAddr) {+ s.walletAddr = addr;+ render();+ fetchBalance(addr);}}- function showErr(id, msg) {- const el = q(`#${id}`);- if (!el) return;- el.textContent = msg;- el.hidden = false;+ async function connectWallet() {+ let w = detectWallet();+ if (!w) { window.open('https://phantom.app/', '_blank', 'noopener'); return; }+ try {+ if (!w.isConnected) await w.connect?.();+ const addr = w.publicKey?.toBase58?.() || w.publicKey?.toString?.();+ if (!addr) return;+ s.walletAddr = addr;+ render();+ fetchBalance(addr);+ } catch { /* user dismissed */ }}- function updateCurve() {- const f = getFields();- const filled = [f.name.trim(), f.symbol.trim(), f.description.trim()].filter(Boolean).length;- // Visual only: max 72% at form-complete — graduation is on-chain- const pct = Math.round((filled / 3) * 72);- q('#lp-curve-fill').style.width = `${pct}%`;- q('#lp-curve-pct').textContent = `${pct}%`;+ async function fetchBalance(addr) {+ try {+ const { Connection, PublicKey } = await import('https://esm.sh/@solana/[email protected]');+ const conn = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');+ s.solBalance = (await conn.getBalance(new PublicKey(addr))) / 1e9;+ } catch {+ s.solBalance = null;+ }+ render();}- q('[name="lp-name"]').addEventListener('input', updateCurve);- q('[name="lp-symbol"]').addEventListener('input', updateCurve);- q('[name="lp-description"]').addEventListener('input', updateCurve);+ function disconnectWallet() {+ s.walletAddr = null;+ s.solBalance = null;+ render();+ }- q('#lp-submit').addEventListener('click', () => {- clearErrors();- const fields = getFields();+ // ── Image ──────────────────────────────────────────────────────────────- if (typeof onSubmit === 'function') {- const result = handleLaunchSubmit(fields, onSubmit);- if (!result.ok) {- const e = result.errors;- if (e.name) showErr('lp-err-name', e.name);- if (e.symbol) showErr('lp-err-symbol', e.symbol);- if (e.description) showErr('lp-err-description', e.description);- if (e.initialBuy) showErr('lp-err-initialbuy', e.initialBuy);+ function handleImageFile(file) {+ if (!file?.type.startsWith('image/')) return;+ if (file.size > 4 * 1024 * 1024) { alert('Image must be under 4 MB'); return; }+ s.imageFile = file;+ const reader = new FileReader();+ reader.onload = (e) => {+ s.imagePreviewUrl = e.target.result;+ // Update img zone in-place without full re-render+ const zone = container.querySelector('.lp-img-zone');+ if (zone) {+ const old = zone.querySelector('img, .lp-img-ph');+ if (old) old.remove();+ const img = document.createElement('img');+ img.src = s.imagePreviewUrl;+ img.alt = '';+ zone.insertBefore(img, zone.firstChild);}- return;- }+ };+ reader.readAsDataURL(file);+ }- const { ok, errors } = validateLaunchForm(fields);- if (!ok) {- if (errors.name) showErr('lp-err-name', errors.name);- if (errors.symbol) showErr('lp-err-symbol', errors.symbol);- if (errors.description) showErr('lp-err-description', errors.description);- if (errors.initialBuy) showErr('lp-err-initialbuy', errors.initialBuy);- return;- }+ // ── Launch ─────────────────────────────────────────────────────────────++ async function launch() {+ if (!formValid() || !s.walletAddr || s.phase !== 'idle') return;+ if (!av || av.id === DEMO_ID) return;++ s.errorMsg = '';++ try {+ // 1. Build / reuse metadata+ s.phase = 'building';+ s.phaseLabel = 'Uploading metadata…';+ render();++ const nameTrim = s.name.trim();+ const symTrim = s.symbol.trim();+ const descTrim = s.description.trim();+ const metaKey = `${nameTrim}|${symTrim}|${descTrim}|${!!s.imageFile}`;++ if (s._metaKey !== metaKey || !s._metaUrl) {+ let imageDataUrl = null;+ if (s.imageFile) imageDataUrl = await fileToDataUrl(s.imageFile);- if (typeof window !== 'undefined') {- window.dispatchEvent(- new CustomEvent('pump-launch-open', {- detail: { identity: { name: fields.name }, formData: fields },+ const mr = await fetch('/api/pump/build-metadata', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ name: nameTrim, symbol: symTrim, description: descTrim,+ ...(av.id ? { avatar_id: av.id } : {}),+ ...(av.agent_id ? { agent_id: av.agent_id } : {}),+ ...(imageDataUrl ? { image_data_url: imageDataUrl } : {}),+ }),+ });+ if (!mr.ok) throw new Error(`Metadata build failed (${mr.status})`);+ const md = await mr.json();+ s._metaUrl = md.metadata_url;+ s._metaKey = metaKey;+ }++ // 2. Prep transaction (wallet must sign)+ s.phase = 'signing';+ s.phaseLabel = 'Sign in your wallet…';+ render();++ const w = detectWallet();+ if (!w) throw new Error('No Solana wallet detected. Install Phantom or Backpack.');+ if (!w.isConnected) await w.connect?.();+ const payer = w.publicKey?.toBase58?.() || w.publicKey?.toString?.();+ if (!payer) throw new Error('Could not read wallet public key.');++ const pr = await fetch('/api/pump/launch-prep', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ ...(av.agent_id ? { agent_id: av.agent_id } : { avatar_id: av.id }),+ wallet_address: payer,+ name: nameTrim, symbol: symTrim, uri: s._metaUrl,+ buyback_bps: s.buybackBps,+ sol_buy_in: Math.max(0, parseFloat(s.initialBuy) || 0),+ network: 'mainnet',}),+ });+ const prep = await pr.json();+ if (prep.error) throw new Error(prep.error_description || prep.error);+ s.resolvedAgentId = prep.agent_id;++ // 3. Deserialize, co-sign mint keypair, send to wallet+ const { VersionedTransaction, Keypair, Connection } =+ await import('https://esm.sh/@solana/[email protected]');++ const tx = VersionedTransaction.deserialize(+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),);+ if (prep.mint_secret_key_b64) {+ const mintKp = Keypair.fromSecretKey(+ Uint8Array.from(atob(prep.mint_secret_key_b64), (c) => c.charCodeAt(0)),+ );+ tx.sign([mintKp]);+ }+ const signed = await w.signTransaction(tx);++ // 4. Send + confirm+ s.phase = 'confirming';+ s.phaseLabel = 'Confirming on-chain…';+ render();++ const conn = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });+ await conn.confirmTransaction(sig, 'confirmed');++ const cr = await fetch('/api/pump/launch-confirm', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ prep_id: prep.prep_id, tx_signature: sig }),+ });+ const confirmed = await cr.json();+ if (confirmed.error) throw new Error(confirmed.error_description || confirmed.error);++ s.mint = prep.mint;+ s.phase = 'success';+ render();++ } catch (e) {+ s.errorMsg = friendlyError(e.message || String(e));+ s.phase = 'error';+ render();}- });+ }- return function teardown() {- container.innerHTML = '';- };+ // ── Render ─────────────────────────────────────────────────────────────++ function render() {+ if (!av || av.id === DEMO_ID) { renderEmpty(); return; }+ if (s.phase === 'success') { renderSuccess(); return; }+ renderForm();+ }++ function renderEmpty() {+ container.innerHTML = `+ <div class="lp">+ <div class="lp-empty">+ Select one of your own avatars from the left panel<br>to launch a token.+ <br><br>+ <a href="/dashboard/avatars" target="_blank" rel="noopener">Upload an avatar →</a>+ </div>+ </div>`;+ }++ function renderForm() {+ const busy = s.phase !== 'idle' && s.phase !== 'error';+ const dis = busy ? 'disabled' : '';++ // Wallet bar+ const w = detectWallet();+ const cost = estimatedCost();+ let walletHtml;+ if (!w) {+ walletHtml = `+ <div class="lp-wallet">+ <div class="lp-dot off"></div>+ <span class="lp-wallet-none">No Solana wallet found</span>+ <button class="lp-wbtn" id="lp-install">Install Phantom ↗</button>+ </div>`;+ } else if (!s.walletAddr) {+ walletHtml = `+ <div class="lp-wallet">+ <div class="lp-dot off"></div>+ <span class="lp-wallet-none">Wallet not connected</span>+ <button class="lp-wbtn" id="lp-connect">Connect</button>+ </div>`;+ } else {+ const hasEnough = s.solBalance !== null && s.solBalance >= cost;+ const costCls = s.solBalance === null ? 'dim' : hasEnough ? 'ok' : 'warn';+ const costTxt = s.solBalance === null+ ? `Est. cost ~${cost.toFixed(3)} SOL`+ : hasEnough+ ? `~${cost.toFixed(3)} SOL required · ${s.solBalance.toFixed(3)} available ✓`+ : `Need ~${cost.toFixed(3)} SOL · ${s.solBalance.toFixed(3)} in wallet`;+ walletHtml = `+ <div class="lp-wallet">+ <div class="lp-dot on"></div>+ <div class="lp-wallet-info">+ <span class="lp-wallet-addr">${shortenAddr(s.walletAddr)}</span>+ ${s.solBalance !== null ? `<span class="lp-wallet-bal">${s.solBalance.toFixed(3)} SOL</span>` : ''}+ <span class="lp-wallet-cost ${costCls}">${costTxt}</span>+ </div>+ <button class="lp-wbtn ghost" id="lp-disc" title="Disconnect">✕</button>+ </div>`;+ }++ // Launch button+ let btnText, btnDis;+ if (busy) {+ btnText = s.phaseLabel || 'Working…'; btnDis = true;+ } else if (!formValid()) {+ btnText = 'Fill in name, symbol & description'; btnDis = true;+ } else if (!s.walletAddr) {+ btnText = 'Connect wallet to launch'; btnDis = true;+ } else {+ btnText = `Launch $${esc(s.symbol.trim() || 'TOKEN')}`; btnDis = false;+ }++ // Image preview+ const imgSrc = s.imagePreviewUrl || av?.thumbnail_url;++ container.innerHTML = `+ <div class="lp">+ <div class="lp-card">+ <div class="lp-img-zone" id="lp-zone">+ ${imgSrc ? `<img src="${esc(imgSrc)}" alt="" />` : `<div class="lp-img-ph">Drop image<br>or click</div>`}+ <input type="file" class="lp-img-file" id="lp-img" accept="image/*" ${dis} />+ </div>+ <div class="lp-card-fields">+ <input class="lp-iname" id="lp-name" type="text" maxlength="32"+ placeholder="Token name" value="${esc(s.name)}" ${dis} />+ <input class="lp-isymbol" id="lp-sym" type="text" maxlength="10"+ placeholder="SYMBOL" value="${esc(s.symbol)}" ${dis} />+ <div class="lp-img-hint">Click image to replace · drag & drop</div>+ </div>+ </div>++ <div>+ <label for="lp-desc">Description</label>+ <textarea id="lp-desc" rows="3" maxlength="500"+ placeholder="What does this agent do?" ${dis}>${esc(s.description)}</textarea>+ </div>++ <div class="lp-2col">+ <div>+ <label for="lp-buy">Initial buy (SOL)</label>+ <input class="lp-number" id="lp-buy" type="number"+ min="0" max="50" step="0.001" value="${esc(s.initialBuy)}" ${dis} />+ </div>+ <div>+ <div class="lp-slider-head">+ <label>Buyback share</label>+ <span class="lp-bps-val" id="lp-bps-val">${(s.buybackBps / 100).toFixed(1)}%</span>+ </div>+ <input type="range" class="lp-slider" id="lp-bps"+ min="0" max="5000" step="50" value="${s.buybackBps}" ${dis} />+ <div class="lp-slider-hint">Of agent revenue burned back</div>+ </div>+ </div>++ ${walletHtml}++ ${s.phase === 'error' ? `+ <div class="lp-err">${esc(s.errorMsg)}+ <div class="lp-err-retry">Fix the issue above and try again.</div>+ </div>` : ''}++ <button class="lp-launch${busy ? ' busy' : ''}" id="lp-go" ${btnDis ? 'disabled' : ''}>+ ${btnText}+ </button>+ ${busy ? `<div class="lp-phase">${esc(s.phaseLabel)}</div>` : ''}+ </div>`;++ wireForm();+ }++ function renderSuccess() {+ const imgSrc = s.imagePreviewUrl || av?.thumbnail_url;+ const mint = s.mint || '';+ const mintShort = mint ? mint.slice(0, 6) + '…' + mint.slice(-6) : '';+ const sym = s.symbol.trim() || 'TOKEN';+ const pumpUrl = `https://pump.fun/coin/${mint}`;+ const scanUrl = `https://solscan.io/token/${mint}`;+ const agentUrl = s.resolvedAgentId ? `/agent/${s.resolvedAgentId}` : null;+ const shareText = `Just launched $${sym} on pump.fun 🎉 Built with three.ws\n${pumpUrl}`;++ container.innerHTML = `+ <div class="lp">+ <div class="lp-ok">+ ${imgSrc+ ? `<img class="lp-ok-thumb" src="${esc(imgSrc)}" alt="" />`+ : `<div class="lp-ok-thumb-ph">🪙</div>`}+ <p class="lp-ok-title">$${esc(sym)} is live!</p>+ <p class="lp-ok-sub">Your token is live on pump.fun</p>++ <div class="lp-ok-mint">+ <span title="${esc(mint)}">${mintShort}</span>+ <button class="lp-copy" id="lp-copy-mint">Copy</button>+ </div>++ <div class="lp-ok-links">+ <a class="lp-ext" href="${esc(pumpUrl)}" target="_blank" rel="noopener">pump.fun ↗</a>+ <a class="lp-ext" href="${esc(scanUrl)}" target="_blank" rel="noopener">Solscan ↗</a>+ ${agentUrl ? `<a class="lp-ext" href="${esc(agentUrl)}">Agent page ↗</a>` : ''}+ </div>++ <button class="lp-share" id="lp-share">📋 Copy launch announcement</button>+ <button class="lp-again" id="lp-again">Launch another token</button>+ </div>+ </div>`;++ function copyBtn(id, text, resetText) {+ container.querySelector(id)?.addEventListener('click', (e) => {+ navigator.clipboard?.writeText(text).catch(() => {});+ const btn = e.currentTarget;+ const orig = btn.textContent;+ btn.textContent = resetText;+ setTimeout(() => { btn.textContent = orig; }, 1800);+ });+ }+ copyBtn('#lp-copy-mint', mint, 'Copied!');+ copyBtn('#lp-share', shareText, '✓ Copied to clipboard');++ container.querySelector('#lp-again')?.addEventListener('click', () => {+ s.phase = 'idle'; s.mint = null; s.errorMsg = '';+ s.imageFile = null; s.imagePreviewUrl = null;+ s._metaUrl = null; s._metaKey = null;+ render();+ });+ }++ function wireForm() {+ const q = (sel) => container.querySelector(sel);++ // Image+ q('#lp-zone')?.addEventListener('dragover', (e) => {+ e.preventDefault(); q('#lp-zone')?.classList.add('dragover');+ });+ q('#lp-zone')?.addEventListener('dragleave', () => q('#lp-zone')?.classList.remove('dragover'));+ q('#lp-zone')?.addEventListener('drop', (e) => {+ e.preventDefault(); q('#lp-zone')?.classList.remove('dragover');+ handleImageFile(e.dataTransfer?.files?.[0]);+ });+ q('#lp-img')?.addEventListener('change', (e) => handleImageFile(e.target.files?.[0]));++ // Name → auto-derive symbol+ q('#lp-name')?.addEventListener('input', (e) => {+ s.name = e.target.value;+ if (!s._symbolEdited) {+ s.symbol = toSymbol(s.name);+ const symEl = q('#lp-sym');+ if (symEl) symEl.value = s.symbol;+ }+ });++ // Symbol (force uppercase/alphanumeric)+ q('#lp-sym')?.addEventListener('input', (e) => {+ const raw = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 10);+ e.target.value = raw;+ s.symbol = raw;+ s._symbolEdited = true;+ });++ q('#lp-desc')?.addEventListener('input', (e) => { s.description = e.target.value; });++ // Initial buy — update cost display inline without full re-render+ q('#lp-buy')?.addEventListener('input', (e) => {+ s.initialBuy = e.target.value;+ const costEl = container.querySelector('.lp-wallet-cost');+ if (!costEl || !s.walletAddr) return;+ const cost = estimatedCost();+ const ok = s.solBalance !== null && s.solBalance >= cost;+ costEl.className = `lp-wallet-cost ${s.solBalance === null ? 'dim' : ok ? 'ok' : 'warn'}`;+ costEl.textContent = s.solBalance === null+ ? `Est. cost ~${cost.toFixed(3)} SOL`+ : ok+ ? `~${cost.toFixed(3)} SOL required · ${s.solBalance.toFixed(3)} available ✓`+ : `Need ~${cost.toFixed(3)} SOL · ${s.solBalance.toFixed(3)} in wallet`;+ });++ // Buyback slider — update value label inline+ q('#lp-bps')?.addEventListener('input', (e) => {+ s.buybackBps = parseInt(e.target.value, 10);+ const v = q('#lp-bps-val');+ if (v) v.textContent = `${(s.buybackBps / 100).toFixed(1)}%`;+ });++ // Wallet+ q('#lp-install')?.addEventListener('click', () => window.open('https://phantom.app/', '_blank', 'noopener'));+ q('#lp-connect')?.addEventListener('click', connectWallet);+ q('#lp-disc')?.addEventListener('click', disconnectWallet);++ // Launch+ q('#lp-go')?.addEventListener('click', launch);+ }++ // ── Public API ──────────────────────────────────────────────────────────++ function avatarChanged() {+ av = getAvatar?.() || null;+ if (av && av.id !== DEMO_ID) {+ if (!s.name) s.name = av.name || '';+ if (!s._symbolEdited) s.symbol = toSymbol(s.name);+ if (!s.description) s.description = av.description || '';+ }+ // Invalidate metadata cache on avatar change+ s._metaUrl = null; s._metaKey = null;+ render();+ }++ // ── Boot ────────────────────────────────────────────────────────────────++ av = getAvatar?.() || null;+ if (av && av.id !== DEMO_ID) {+ s.name = av.name || '';+ s.symbol = toSymbol(s.name);+ s.description = av.description || '';+ }++ render();+ setTimeout(tryAutoConnect, 250); // check for already-connected wallet++ return { avatarChanged, teardown() { container.innerHTML = ''; } };}diff --git a/public/studio/studio.js b/public/studio/studio.jsindex f93ae2aed..fdde82c6d 100644--- a/public/studio/studio.js+++ b/public/studio/studio.js@@ -6,7 +6,6 @@// Keep this list in sync with src/widget-types.js as new types light up.import { mountLaunchPanel } from './launch-panel.js';-import { openPumpLaunchWizard } from '/src/pump/pump-modals.js';const WIDGET_TYPES = {turntable: {@@ -127,6 +126,8 @@ const saveBtn = $('#save-draft-btn');const generateBtn = $('#generate-btn');const toastEl = $('#toast');+let launchPanel = null; // set in wireButtons, used in selectAvatar+const state = {user: null,avatars: [],diff --git a/public/validation/index.html b/public/validation/index.htmlindex ca28fd5ad..d9fe178e7 100644--- a/public/validation/index.html+++ b/public/validation/index.html@@ -3,7 +3,11 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" />- <title>Validation Records · three.ws</title>+ <title>glTF Validator · three.ws</title>+ <meta+ name="description"+ content="Run the official Khronos glTF 2.0 validator and glTF-Transform performance inspector in your browser. Optionally sign & pin reports on-chain."+ /><link rel="icon" href="/favicon.ico" /><style>:root {@@ -13,6 +17,13 @@--border: #22222e;--bg: #0b0b10;--panel: #14141c;+ --panel2: #1a1a24;+ --muted: #888;+ --text: #eee;+ --text-soft: #bbb;+ --ok: #76d776;+ --warn: #ffc107;+ --err: #ff5252;}* {box-sizing: border-box;@@ -24,7 +35,7 @@Segoe UI,Roboto,sans-serif;- color: #eee;+ color: var(--text);margin: 0;background: var(--bg);min-height: 100vh;@@ -67,40 +78,44 @@letter-spacing: -0.01em;}.sub {- color: #888;+ color: var(--muted);margin: 0 0 22px;font-size: 14px;}- .toolbar {- display: flex;- gap: 12px;- margin-bottom: 24px;- flex-wrap: wrap;- align-items: center;+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ transition: filter 0.12s;}- .toolbar input {- padding: 9px 11px;- background: #0f0f17;- border: 1px solid var(--border);- color: #eee;- border-radius: 8px;- font-size: 14px;+ .btn:hover {+ filter: brightness(1.1);}- .toolbar input:focus {- outline: none;- border-color: var(--accent);+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ filter: none;}- .form-group {- margin-bottom: 18px;+ .btn.sec {+ background: #222230;+ color: #ddd;}- label {- display: block;- font-size: 13px;- font-weight: 500;- color: #bbb;- margin-bottom: 6px;+ .btn.ghost {+ background: transparent;+ border: 1px solid var(--border);+ color: var(--text-soft);+ }+ .btn.ghost:hover {+ background: var(--panel);+ color: var(--text);}input[type='text'],+ input[type='url'],textarea,select {width: 100%;@@ -112,7 +127,7 @@font-size: 14px;font-family: inherit;}- input[type='text']:focus,+ input:focus,textarea:focus,select:focus {outline: none;@@ -120,34 +135,380 @@}textarea {resize: vertical;- font-family:- ui-monospace,- SF Mono,- Menlo,- monospace;+ font-family: ui-monospace, SF Mono, Menlo, monospace;font-size: 13px;}- .btn {- padding: 9px 14px;- border-radius: 9px;++ /* ── Tabs ────────────────────────────────────────────────────── */+ .tabs {+ display: flex;+ gap: 4px;+ border-bottom: 1px solid var(--border);+ margin: 18px 0 24px;+ }+ .tab {+ padding: 10px 18px;+ background: transparent;border: 0;- font-size: 13px;+ border-bottom: 2px solid transparent;+ color: var(--muted);+ font: inherit;+ font-weight: 500;+ cursor: pointer;+ margin-bottom: -1px;+ }+ .tab:hover {+ color: var(--text-soft);+ }+ .tab.active {+ color: var(--text);+ border-bottom-color: var(--accent);+ }+ .tab-panel {+ display: none;+ }+ .tab-panel.active {+ display: block;+ }++ /* ── Drop zone + URL input ───────────────────────────────────── */+ .input-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 14px;+ margin-bottom: 14px;+ }+ @media (max-width: 720px) {+ .input-row {+ grid-template-columns: 1fr;+ }+ }+ .drop-zone {+ border: 2px dashed var(--border);+ border-radius: 12px;+ padding: 26px 18px;+ text-align: center;+ background: var(--panel);+ cursor: pointer;+ transition: border-color 0.15s, background 0.15s;+ }+ .drop-zone:hover,+ .drop-zone.drag {+ border-color: var(--accent);+ background: rgba(106, 92, 255, 0.05);+ }+ .drop-zone input[type='file'] {+ display: none;+ }+ .drop-zone .dz-title {font-weight: 600;+ color: var(--text);+ margin-bottom: 4px;+ }+ .drop-zone .dz-sub {+ font-size: 12px;+ color: var(--muted);+ }+ .url-box {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 18px;+ }+ .url-box label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: var(--text-soft);+ margin-bottom: 6px;+ }+ .url-row {+ display: flex;+ gap: 8px;+ }+ .url-row input {+ flex: 1;+ }+ .url-box .url-hint {+ font-size: 12px;+ color: var(--muted);+ margin-top: 8px;+ }++ .samples {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+ margin-bottom: 16px;+ }+ .samples-label {+ font-size: 12px;+ color: var(--muted);+ margin-right: 4px;+ }+ .sample-chip {+ background: var(--panel);+ border: 1px solid var(--border);+ color: var(--text-soft);+ padding: 6px 12px;+ border-radius: 99px;+ font-size: 12px;cursor: pointer;- background: var(--accent);+ transition: all 0.12s;+ }+ .sample-chip:hover {+ border-color: var(--accent);+ color: var(--text);+ }++ .status {+ font-size: 13px;+ color: var(--text-soft);+ padding: 10px 14px;+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 8px;+ margin-bottom: 16px;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ }+ .status.ok {+ border-color: rgba(118, 215, 118, 0.3);+ color: var(--ok);+ }+ .status.err {+ border-color: rgba(255, 92, 92, 0.4);+ color: #ffb3b3;+ background: rgba(255, 92, 92, 0.08);+ }+ .status:empty {+ display: none;+ }++ .action-bar {+ display: flex;+ gap: 8px;+ margin-bottom: 16px;+ align-items: center;+ justify-content: flex-end;+ }++ /* ── Validator report (shared by /app and /validation) ─────── */+ .report {+ padding: 0;+ color: var(--text);+ }+ .report h1 {+ margin: 0 0 8px;+ font-size: 20px;+ }+ .report-sub {+ color: var(--muted);+ font-size: 13px;+ margin: 0 0 16px;+ }+ .report-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 14px;+ flex-wrap: wrap;+ margin-bottom: 12px;+ }+ .report-download {+ font-size: 12px;+ background: var(--panel);+ border: 1px solid var(--border);+ padding: 6px 12px;+ border-radius: 7px;+ color: var(--text-soft);+ }+ .report-download:hover {+ background: var(--panel2);+ color: var(--text);+ }+ .report ul {+ line-height: 1.65;+ padding-left: 22px;+ }+ .report ul li {+ margin: 4px 0;+ }+ .report-banner {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 14px 16px;+ border-radius: 8px;+ margin-bottom: 16px;+ font-size: 14px;+ }+ .report-banner-clean {+ background: rgba(118, 215, 118, 0.1);+ border: 1px solid rgba(118, 215, 118, 0.3);+ color: var(--ok);+ }+ .report-banner-issues {+ background: rgba(244, 67, 54, 0.08);+ border: 1px solid rgba(244, 67, 54, 0.25);+ color: var(--text);+ }+ .report-banner-icon {+ font-size: 18px;+ font-weight: bold;+ }+ .report-section-heading {+ font-size: 15px;+ margin: 22px 0 10px;+ padding-left: 12px;+ border-left: 4px solid #888;+ font-weight: 600;+ }+ .report-count {+ font-weight: normal;+ opacity: 0.7;+ font-size: 0.9em;+ }+ .report-table-wrap {+ overflow-x: auto;+ border: 1px solid var(--border);+ border-radius: 8px;+ margin-bottom: 14px;+ }+ .report-table {+ border-collapse: collapse;+ width: 100%;+ font-size: 13px;+ }+ .report-table thead tr {+ background: var(--panel);+ }+ .report-table th,+ .report-table td {+ padding: 8px 12px;+ text-align: left;+ color: var(--text-soft);+ border-bottom: 1px solid var(--border);+ }+ .report-table tr:last-child td {+ border-bottom: 0;+ }+ .report-table tr:nth-child(2n) td {+ background: rgba(255, 255, 255, 0.015);+ }+ .report-table code {+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ font-size: 12px;+ color: var(--text);+ }++ /* ── Inspect report ──────────────────────────────────────────── */+ .inspect-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 10px;+ margin-bottom: 22px;+ }+ .inspect-card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 14px 16px;+ }+ .inspect-card-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ color: var(--muted);+ margin-bottom: 6px;+ }+ .inspect-card-value {+ font-size: 22px;+ font-weight: 600;+ color: var(--text);+ font-variant-numeric: tabular-nums;+ }+ .inspect-card-foot {+ font-size: 11px;+ color: var(--muted);+ margin-top: 4px;+ }+ .inspect-suggestions {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-bottom: 22px;+ }+ .inspect-suggestion {+ background: var(--panel);+ border: 1px solid var(--border);+ border-left: 3px solid #888;+ border-radius: 8px;+ padding: 12px 14px;+ }+ .inspect-suggestion-head {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-bottom: 6px;+ flex-wrap: wrap;+ }+ .inspect-suggestion-badge {+ font-size: 10px;+ font-weight: 700;color: #fff;+ padding: 2px 8px;+ border-radius: 4px;+ text-transform: uppercase;+ letter-spacing: 0.5px;}- .btn:hover {- filter: brightness(1.1);+ .inspect-suggestion-id {+ font-size: 11px;+ color: var(--muted);+ font-family: ui-monospace, SF Mono, Menlo, monospace;}- .btn:disabled {- opacity: 0.5;- cursor: not-allowed;- filter: none;+ .inspect-suggestion-estimate {+ font-size: 11px;+ color: var(--ok);+ margin-left: auto;}- .btn.sec {- background: #222230;- color: #ddd;+ .inspect-suggestion-msg {+ font-size: 13px;+ color: var(--text-soft);+ line-height: 1.5;+ }+ .inspect-ext-list {+ list-style: none;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-bottom: 22px;+ }+ .inspect-ext-list li {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 4px 10px;+ font-size: 12px;+ }+ .inspect-ext-list code {+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ color: var(--text);+ }+ .inspect-ext-required {+ margin-left: 8px;+ font-size: 10px;+ color: var(--accent2);+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }++ .loading {+ padding: 40px 20px;+ text-align: center;+ color: var(--muted);+ font-size: 13px;}.err {padding: 12px;@@ -155,16 +516,37 @@border: 1px solid rgba(255, 92, 92, 0.3);border-radius: 8px;color: #ffb3b3;- margin-bottom: 14px;}- .info {- padding: 12px;- background: rgba(106, 92, 255, 0.1);- border: 1px solid rgba(106, 92, 255, 0.3);+ .empty-result {+ padding: 60px 20px;+ text-align: center;+ color: var(--muted);+ border: 1px dashed var(--border);+ border-radius: 12px;+ }+ .empty-result-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-soft);+ margin-bottom: 6px;+ }++ /* ── Records tab (kept compatible with ValidationDashboard) ── */+ .records-toolbar {+ display: flex;+ gap: 12px;+ margin-bottom: 18px;+ flex-wrap: wrap;+ align-items: center;+ }+ .records-toolbar input {+ padding: 9px 11px;+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;border-radius: 8px;- color: #c9bfff;- margin-bottom: 14px;- font-size: 13px;+ font-size: 14px;+ width: 190px;}.records {display: flex;@@ -204,22 +586,23 @@}.badge.pass {background: rgba(76, 175, 80, 0.15);- color: #76d776;+ color: var(--ok);}.badge.warn {background: rgba(255, 193, 7, 0.15);- color: #ffc107;+ color: var(--warn);}.badge.fail {background: rgba(244, 67, 54, 0.15);- color: #ff5252;+ color: var(--err);}.record-meta {display: flex;gap: 16px;font-size: 12px;- color: #888;+ color: var(--muted);margin: 8px 0;+ flex-wrap: wrap;}.record-meta-item {display: flex;@@ -234,11 +617,7 @@}.record-meta-value {color: #ccc;- font-family:- ui-monospace,- SF Mono,- Menlo,- monospace;+ font-family: ui-monospace, SF Mono, Menlo, monospace;font-size: 13px;word-break: break-all;}@@ -253,7 +632,7 @@font-size: 12px;border-radius: 7px;border: 1px solid var(--border);- background: #1a1a24;+ background: var(--panel2);color: #ddd;cursor: pointer;text-decoration: none;@@ -262,12 +641,21 @@.record-actions a:hover {background: #22222e;}+ .record-notes {+ font-size: 13px;+ color: #aaa;+ margin: 8px 0 4px;+ padding: 8px 10px;+ background: rgba(106, 92, 255, 0.06);+ border-left: 2px solid var(--accent);+ border-radius: 0 6px 6px 0;+ }.empty {text-align: center;padding: 60px 20px;border: 1px dashed var(--border);border-radius: 14px;- color: #888;+ color: var(--muted);}.empty-title {font-size: 15px;@@ -279,42 +667,25 @@font-size: 13px;margin-bottom: 18px;}- .how-grid {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));- gap: 12px;- margin-bottom: 28px;- }- .how-card {- background: var(--panel);- border: 1px solid var(--border);- border-radius: 10px;- padding: 14px 16px;- }- .how-card-icon {- font-size: 18px;- margin-bottom: 8px;+ .err-box {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;}- .how-card-title {+ .info-box {+ padding: 12px;+ background: rgba(106, 92, 255, 0.1);+ border: 1px solid rgba(106, 92, 255, 0.3);+ border-radius: 8px;+ color: #c9bfff;+ margin-bottom: 14px;font-size: 13px;- font-weight: 600;- color: #ddd;- margin-bottom: 4px;- }- .how-card-desc {- font-size: 12px;- color: #888;- line-height: 1.5;- }- .record-notes {- font-size: 13px;- color: #aaa;- margin: 8px 0 4px;- padding: 8px 10px;- background: rgba(106, 92, 255, 0.06);- border-left: 2px solid var(--accent);- border-radius: 0 6px 6px 0;}++ /* ── Submit modal (unchanged element IDs/classes for dashboard) */.modal-overlay {position: fixed;inset: 0;@@ -335,7 +706,7 @@border: 1px solid var(--border);border-radius: 14px;padding: 22px;- width: min(600px, calc(100vw - 32px));+ width: min(640px, calc(100vw - 32px));max-height: calc(100vh - 32px);overflow-y: auto;}@@ -352,43 +723,21 @@margin-top: 20px;justify-content: flex-end;}- .toast {- position: fixed;- bottom: 24px;- left: 50%;- transform: translateX(-50%);- background: #1a1a24;- border: 1px solid var(--border);- padding: 10px 18px;- border-radius: 99px;- font-size: 13px;- color: #ddd;- z-index: 70;- box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);- animation: toast-in 0.2s;- }- @keyframes toast-in {- from {- opacity: 0;- transform: translate(-50%, 8px);- }- to {- opacity: 1;- transform: translateX(-50%);- }- }- .toast.err {- border-color: #cc4040;- background: #1e1010;+ .form-group {+ margin-bottom: 18px;}- .section {- margin-top: 34px;+ .form-group label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: var(--text-soft);+ margin-bottom: 6px;}.section-title {- font-size: 15px;+ font-size: 13px;font-weight: 600;- margin: 0 0 12px;- color: #eee;+ margin: 14px 0 8px;+ color: var(--text-soft);}.file-input-wrapper {position: relative;@@ -409,16 +758,11 @@border-radius: 8px;text-align: center;cursor: pointer;- transition: border-color 0.15s;- color: #888;- }- .file-input-wrapper input[type='file']:focus + .file-input-label {- border-color: var(--accent);- color: #ccc;+ color: var(--muted);}.file-input-wrapper:hover .file-input-label {- border-color: #444;- color: #aaa;+ border-color: var(--accent);+ color: var(--text-soft);}pre {background: #0f0f17;@@ -430,11 +774,25 @@max-height: 200px;}code {- font-family:- ui-monospace,- SF Mono,- Menlo,- monospace;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ }+ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: var(--panel2);+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ }+ .toast.err {+ border-color: #cc4040;+ background: #1e1010;}.header-logo {width: 14px;@@ -442,11 +800,42 @@vertical-align: -2px;margin-right: 6px;}+ .how-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 12px;+ margin-bottom: 22px;+ }+ .how-card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 14px 16px;+ }+ .how-card-icon {+ font-size: 18px;+ margin-bottom: 8px;+ }+ .how-card-title {+ font-size: 13px;+ font-weight: 600;+ color: #ddd;+ margin-bottom: 4px;+ }+ .how-card-desc {+ font-size: 12px;+ color: var(--muted);+ line-height: 1.5;+ }</style></head><body><header>- <div class="brand"><a href="/"><img src="/three.svg" alt="" class="header-logo" aria-hidden="true" />three.ws</a></div>+ <div class="brand">+ <a href="/"+ ><img src="/three.svg" alt="" class="header-logo" aria-hidden="true" />three.ws</a+ >+ </div><nav><a href="/marketplace.html?tab=mine">Home</a><a href="/dashboard">Dashboard</a>@@ -454,62 +843,150 @@</nav></header>- <main id="main">- <h1>Validation Records</h1>+ <main>+ <h1>glTF Validator</h1><p class="sub">- On-chain proof that an agent's GLB model, metadata, and skills have been audited. Each record is signed by a validator's wallet and stored immutably.+ Run the official+ <a href="https://github.com/KhronosGroup/glTF-Validator" target="_blank" rel="noreferrer"+ >Khronos glTF 2.0 validator</a+ >+ and a+ <a href="https://gltf-transform.dev" target="_blank" rel="noreferrer"+ >glTF-Transform</a+ >+ performance inspector — fully client-side. Optionally sign & pin reports+ on-chain.</p><div class="how-grid"><div class="how-card"><div class="how-card-icon">◈</div>- <div class="how-card-title">GLB Schema</div>- <div class="how-card-desc">Validates glTF 2.0 file structure — required chunks, mesh data, extensions.</div>+ <div class="how-card-title">Khronos spec check</div>+ <div class="how-card-desc">+ Validates glTF 2.0 file structure, accessors, materials and extensions against+ the official Khronos suite.+ </div></div><div class="how-card"><div class="how-card-icon">◆</div>- <div class="how-card-title">Manifest Integrity</div>- <div class="how-card-desc">Checks on-chain metadata — agent ID, chain ID, registry address consistency.</div>+ <div class="how-card-title">Performance inspector</div>+ <div class="how-card-desc">+ Surfaces what the spec check does not — texture weights, draw-call shape, and+ compression opportunities (Draco, Meshopt, KTX2).+ </div></div><div class="how-card"><div class="how-card-icon">◇</div>- <div class="how-card-title">Skill Handlers</div>- <div class="how-card-desc">Verifies declared skills initialize without errors or missing dependencies.</div>+ <div class="how-card-title">On-chain attestations</div>+ <div class="how-card-desc">+ Sign reports with a wallet, pin to IPFS, and record on the Validation Registry+ so anyone can verify the audit.+ </div></div></div>- <div class="toolbar">- <input- type="text"- id="agent-input"- placeholder="Agent ID (e.g., 1)"- style="width: 180px"- />- <input- type="text"- id="chain-input"- placeholder="Chain ID (e.g., 84532)"- style="width: 190px"- />- <button class="btn" id="load-btn">Load Records</button>- <button class="btn sec" id="submit-btn">Submit Validation</button>+ <div class="tabs" role="tablist">+ <button class="tab active" role="tab" data-tab="validate" aria-selected="true">+ Validate+ </button>+ <button class="tab" role="tab" data-tab="inspect" aria-selected="false">+ Inspect+ </button>+ <button class="tab" role="tab" data-tab="records" aria-selected="false">+ Records+ </button></div>- <div id="error" class="err" style="display: none"></div>- <div id="info" class="info" style="display: none"></div>- <div id="records" class="records"></div>- <div id="empty" class="empty" style="display: none">- <div class="empty-title">No validation records found</div>- <div class="empty-sub">This agent hasn't been validated yet, or the agent ID / chain ID is incorrect.</div>- <button class="btn" id="empty-submit-btn">Submit a Validation</button>- </div>+ <!-- ── Validate panel ─────────────────────────────────────────── -->+ <section class="tab-panel active" data-tab="validate" role="tabpanel">+ <div class="input-row">+ <label class="drop-zone" id="drop-zone">+ <input type="file" id="file-input" accept=".glb,.gltf,model/gltf-binary,model/gltf+json" />+ <div class="dz-title">Drop a .glb or .gltf file</div>+ <div class="dz-sub">or click to choose · runs entirely in your browser</div>+ </label>+ <div class="url-box">+ <label for="url-input">…or fetch from a URL</label>+ <div class="url-row">+ <input+ type="url"+ id="url-input"+ placeholder="https://example.com/model.glb"+ />+ <button class="btn" id="url-btn">Fetch</button>+ </div>+ <div class="url-hint">CORS must be allowed by the host server.</div>+ </div>+ </div>++ <div class="samples">+ <span class="samples-label">Try a sample:</span>+ <span id="samples"></span>+ </div>++ <div id="status" class="status"></div>++ <div class="action-bar">+ <button class="btn ghost" id="sign-btn" disabled>+ Sign & pin on-chain →+ </button>+ </div>++ <div id="validate-output">+ <div class="empty-result">+ <div class="empty-result-title">No model loaded</div>+ <div>Drop a file, paste a URL, or pick a sample to run the validator.</div>+ </div>+ </div>+ </section>++ <!-- ── Inspect panel ──────────────────────────────────────────── -->+ <section class="tab-panel" data-tab="inspect" role="tabpanel">+ <div id="inspect-output">+ <div class="empty-result">+ <div class="empty-result-title">No model loaded</div>+ <div>+ Load a model in the <b>Validate</b> tab — both checks run in parallel and+ results appear here.+ </div>+ </div>+ </div>+ </section>++ <!-- ── Records panel ──────────────────────────────────────────── -->+ <section class="tab-panel" data-tab="records" role="tabpanel">+ <p class="sub">+ On-chain proof that an agent's GLB model has been audited. Each record is signed by+ a validator's wallet and stored immutably.+ </p>++ <div class="records-toolbar">+ <input type="text" id="agent-input" placeholder="Agent ID (e.g., 1)" />+ <input type="text" id="chain-input" placeholder="Chain ID (e.g., 84532)" />+ <button class="btn" id="load-btn">Load Records</button>+ <button class="btn sec" id="submit-btn">Submit JSON Report</button>+ </div>++ <div id="error" class="err-box" style="display: none"></div>+ <div id="info" class="info-box" style="display: none"></div>+ <div id="records" class="records"></div>+ <div id="empty" class="empty" style="display: none">+ <div class="empty-title">No validation records found</div>+ <div class="empty-sub">+ This agent hasn't been validated yet, or the agent ID / chain ID is incorrect.+ </div>+ <button class="btn" id="empty-submit-btn">Submit a Validation</button>+ </div>+ </section></main>- <!-- Submit Modal -->+ <!-- Submit Modal — IDs preserved so ValidationDashboard wiring still works --><div class="modal-overlay" id="submit-modal"><div class="modal"><h2>Submit Validation Report</h2>- <p class="sub">Upload a JSON validation report signed by your wallet.</p>+ <p class="sub">+ Upload a JSON validation report — signed by your wallet and stored on-chain.+ </p><div class="form-group"><label>Report File (JSON)</label>@@ -519,19 +996,13 @@📄 Click to select or drag a JSON report file</label></div>- <div- id="file-status"- style="font-size: 12px; color: #888; margin-top: 8px"- ></div>+ <div id="file-status" style="font-size: 12px; color: var(--muted); margin-top: 8px"></div></div>- <div id="preview-section" style="display: none" class="section">+ <div id="preview-section" style="display: none"><div class="section-title">Preview</div><pre id="preview-json"></pre>- <div- id="preview-error"- style="color: #ffb3b3; font-size: 12px; margin-top: 8px"- ></div>+ <div id="preview-error" style="color: #ffb3b3; font-size: 12px; margin-top: 8px"></div></div><div id="hash-section" style="display: none" class="form-group">@@ -540,16 +1011,9 @@type="text"id="report-hash"readonly- style="- font-family:- ui-monospace,- SF Mono,- Menlo,- monospace;- font-size: 12px;- "+ style="font-family: ui-monospace, SF Mono, Menlo, monospace; font-size: 12px"/>- <div style="font-size: 12px; color: #888; margin-top: 6px">+ <div style="font-size: 12px; color: var(--muted); margin-top: 6px">Computed via keccak256(JSON.stringify(report))</div></div>@@ -563,8 +1027,9 @@<script type="module">import { ValidationDashboard } from '/src/validation-ui.js';+ import { ValidationPage } from '/src/validation-page.js';- const dashboard = new ValidationDashboard(document.getElementById('main'), {+ const dashboard = new ValidationDashboard(document.querySelector('main'), {agentInput: document.getElementById('agent-input'),chainInput: document.getElementById('chain-input'),loadBtn: document.getElementById('load-btn'),@@ -584,11 +1049,30 @@submitReportBtn: document.getElementById('submit-report-btn'),});+ const page = new ValidationPage(+ {+ tabs: document.querySelectorAll('.tab'),+ panels: document.querySelectorAll('.tab-panel'),+ dropZone: document.getElementById('drop-zone'),+ fileInput: document.getElementById('file-input'),+ urlInput: document.getElementById('url-input'),+ urlBtn: document.getElementById('url-btn'),+ samples: document.getElementById('samples'),+ statusEl: document.getElementById('status'),+ validateOut: document.getElementById('validate-output'),+ inspectOut: document.getElementById('inspect-output'),+ signBtn: document.getElementById('sign-btn'),+ },+ dashboard,+ );+window.valDash = dashboard;+ window.valPage = page;window.closeSubmitModal = () => dashboard.closeModal();- window.submitModal = () => dashboard.submitReport();- document.getElementById('empty-submit-btn').addEventListener('click', () => dashboard.openModal());+ document+ .getElementById('empty-submit-btn')+ .addEventListener('click', () => dashboard.openModal());</script></body></html>diff --git a/scripts/artifact-viewer/src.js b/scripts/artifact-viewer/src.jsnew file mode 100644index 000000000..83aee525a--- /dev/null+++ b/scripts/artifact-viewer/src.js@@ -0,0 +1,223 @@+// Source for the inlined artifact viewer bundle.+//+// Bundled to a single self-contained IIFE by scripts/build-artifact-viewer.mjs.+// The bundle is then inlined verbatim into the HTML returned by /api/artifact.+//+// Why a separate viewer (vs. agent-3d)?+// Claude.ai's artifact sandbox CSP forbids fetch() to any host except+// cdn.jsdelivr.net/pyodide/. The agent-3d bundle calls back to three.ws/api+// to resolve agents and pulls GLBs from R2 — both blocked. This viewer takes+// every byte from inline data: GLB ArrayBuffer parsed directly via+// GLTFLoader.parse(), persona embedded in <script type=application/json>.+// Scene, lights, camera, animation loop are minimal but production-quality.++import * as THREE from 'three';+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';++const PALETTES = {+ dark: { bg: '#0a0e27', amb: 0xffffff, key: 0xffffff, fill: 0x99bbff },+ light: { bg: '#f5f5f7', amb: 0xffffff, key: 0xffffff, fill: 0xffe8c8 },+};++const REDUCED = window.matchMedia('(prefers-reduced-motion: reduce)').matches;++function readConfig() {+ const node = document.getElementById('artifact-config');+ if (!node) throw new Error('artifact-config script tag not found');+ const cfg = JSON.parse(node.textContent);+ if (!cfg.glb) throw new Error('artifact-config.glb missing');+ return cfg;+}++function base64ToArrayBuffer(b64) {+ const bin = atob(b64);+ const len = bin.length;+ const bytes = new Uint8Array(len);+ for (let i = 0; i < len; i++) bytes[i] = bin.charCodeAt(i);+ return bytes.buffer;+}++function pickPalette(cfg) {+ const base = PALETTES[cfg.theme === 'light' ? 'light' : 'dark'];+ const bg = cfg.bg && /^#?[0-9a-f]{6}$/i.test(cfg.bg) ? `#${cfg.bg.replace(/^#/, '')}` : base.bg;+ return { ...base, bg };+}++function buildScene(host, palette) {+ const w = host.clientWidth || 600;+ const h = host.clientHeight || 600;++ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.setSize(w, h, false);+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.domElement.style.display = 'block';+ renderer.domElement.style.width = '100%';+ renderer.domElement.style.height = '100%';+ host.appendChild(renderer.domElement);++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(palette.bg);++ const camera = new THREE.PerspectiveCamera(38, w / h, 0.05, 50);+ camera.position.set(0, 1.4, 2.7);+ camera.lookAt(0, 1.05, 0);++ scene.add(new THREE.AmbientLight(palette.amb, 0.85));+ const key = new THREE.DirectionalLight(palette.key, 1.25);+ key.position.set(2.5, 5, 3);+ scene.add(key);+ const fill = new THREE.DirectionalLight(palette.fill, 0.45);+ fill.position.set(-3, 1.5, -2);+ scene.add(fill);++ const ro = new ResizeObserver(() => {+ const nw = host.clientWidth;+ const nh = host.clientHeight;+ if (!nw || !nh) return;+ camera.aspect = nw / nh;+ camera.updateProjectionMatrix();+ renderer.setSize(nw, nh, false);+ });+ ro.observe(host);++ return { renderer, scene, camera };+}++function fitAvatar(root) {+ const box = new THREE.Box3().setFromObject(root);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ const targetHeight = 1.8;+ const scale = targetHeight / Math.max(size.y, 0.001);+ root.scale.setScalar(scale);+ root.position.copy(center.multiplyScalar(-scale));+ root.position.y += (size.y * scale) / 2;+}++function pickIdleClip(animations, requested) {+ if (!animations?.length) return null;+ if (requested) {+ const named = animations.find((a) => a.name === requested);+ if (named) return named;+ }+ return (+ animations.find((a) => /idle|breathing|stand/i.test(a.name)) || animations[0]+ );+}++function showError(host, msg) {+ host.querySelector('.artifact-error')?.remove();+ const div = document.createElement('div');+ div.className = 'artifact-error';+ div.textContent = msg;+ Object.assign(div.style, {+ position: 'absolute',+ inset: '0',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ background: 'rgba(0,0,0,0.65)',+ color: '#f87171',+ font: '14px/1.4 system-ui, sans-serif',+ padding: '24px',+ textAlign: 'center',+ });+ host.appendChild(div);+}++function renderNamePlate(host, cfg, palette) {+ if (!cfg.name) return;+ const plate = document.createElement('div');+ plate.className = 'artifact-name-plate';+ plate.textContent = cfg.name;+ const isLight = palette.bg && /^#[ef]/i.test(palette.bg);+ Object.assign(plate.style, {+ position: 'absolute',+ left: '16px',+ bottom: '16px',+ padding: '6px 12px',+ borderRadius: '999px',+ font: '500 13px/1 system-ui, -apple-system, sans-serif',+ letterSpacing: '0.01em',+ color: isLight ? '#111' : '#fff',+ background: isLight ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.55)',+ backdropFilter: 'blur(8px)',+ pointerEvents: 'none',+ userSelect: 'none',+ });+ host.appendChild(plate);+}++async function start() {+ const host = document.getElementById('artifact-stage');+ if (!host) throw new Error('artifact-stage element not found');+ host.style.position = 'relative';++ const cfg = readConfig();+ const palette = pickPalette(cfg);+ host.style.background = palette.bg;++ const { renderer, scene, camera } = buildScene(host, palette);++ let glbBuffer;+ try {+ glbBuffer = base64ToArrayBuffer(cfg.glb);+ } catch (err) {+ showError(host, 'Failed to decode embedded model: ' + err.message);+ return;+ }++ const loader = new GLTFLoader();+ loader.parse(+ glbBuffer,+ '',+ (gltf) => {+ const root = gltf.scene || gltf.scenes?.[0];+ if (!root) {+ showError(host, 'Embedded GLB has no scene');+ return;+ }+ fitAvatar(root);+ scene.add(root);++ let mixer = null;+ const clip = pickIdleClip(gltf.animations, cfg.idle);+ if (clip) {+ mixer = new THREE.AnimationMixer(root);+ mixer.clipAction(clip).play();+ }++ renderNamePlate(host, cfg, palette);++ const clock = new THREE.Clock();+ let t = 0;+ const baseScale = root.scale.clone();+ function tick() {+ requestAnimationFrame(tick);+ const dt = clock.getDelta();+ t += dt;+ if (mixer) mixer.update(dt);+ if (!REDUCED) {+ root.rotation.y += dt * 0.32;+ root.scale.y = baseScale.y * (1 + Math.sin(t * 1.1) * 0.006);+ }+ renderer.render(scene, camera);+ }+ tick();+ },+ (err) => {+ showError(host, 'Model parse failed: ' + (err?.message || err));+ },+ );+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => {+ start().catch((err) => console.error('[artifact-viewer]', err));+ });+} else {+ start().catch((err) => console.error('[artifact-viewer]', err));+}diff --git a/scripts/build-artifact-viewer.mjs b/scripts/build-artifact-viewer.mjsnew file mode 100644index 000000000..3d281adf7--- /dev/null+++ b/scripts/build-artifact-viewer.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+// Build the artifact-viewer bundle that gets inlined into /api/artifact.+//+// Output: public/artifact-viewer.bundle.js — an IIFE containing three.js ++// GLTFLoader + viewer code. Inlined verbatim into the artifact HTML so the+// document needs no external script (Claude.ai's sandbox CSP forbids that).+//+// Run via: node scripts/build-artifact-viewer.mjs+// (or `npm run build:artifact-viewer`)++import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import { writeFileSync, mkdirSync, statSync } from 'node:fs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');+const ENTRY = resolve(ROOT, 'scripts/artifact-viewer/src.js');+const OUT = resolve(ROOT, 'public/artifact-viewer.bundle.js');++mkdirSync(dirname(OUT), { recursive: true });++const result = await build({+ entryPoints: [ENTRY],+ bundle: true,+ format: 'iife',+ platform: 'browser',+ target: ['es2020'],+ minify: true,+ legalComments: 'none',+ write: false,+ logLevel: 'info',+ define: { 'process.env.NODE_ENV': '"production"' },+});++const [bundle] = result.outputFiles;+const banner =+ '/* artifact-viewer bundle — three.js + GLTFLoader + viewer.\n' ++ ' * Built from scripts/artifact-viewer/src.js. Do not edit by hand.\n' ++ ' * Generated: ' ++ new Date().toISOString() ++ ' */\n';+writeFileSync(OUT, banner + bundle.text);++const { size } = statSync(OUT);+console.log(`✓ ${OUT}`);+console.log(` ${(size / 1024).toFixed(1)} KB`);diff --git a/scripts/refresh-claude-csp.mjs b/scripts/refresh-claude-csp.mjsnew file mode 100644index 000000000..4b9faf74b--- /dev/null+++ b/scripts/refresh-claude-csp.mjs@@ -0,0 +1,40 @@+#!/usr/bin/env node+// Refresh tests/_fixtures/claude-artifact-csp.txt from simonw's scraper.+//+// Run periodically (or via a cron). The contract test reads the vendored+// copy so it doesn't depend on network at run time; this script keeps it+// honest. If the upstream CSP changes shape, the test will start failing+// until /api/artifact is updated to match.++import { writeFileSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const SOURCE =+ 'https://raw.githubusercontent.com/simonw/scrape-claude-artifacts/main/content-security-policy.txt';++const __dirname = dirname(fileURLToPath(import.meta.url));+const TARGET = resolve(__dirname, '../tests/_fixtures/claude-artifact-csp.txt');++const res = await fetch(SOURCE);+if (!res.ok) {+ console.error(`fetch failed: ${res.status}`);+ process.exit(1);+}+const fresh = (await res.text()).trim() + '\n';++let prev = '';+try {+ prev = readFileSync(TARGET, 'utf8');+} catch {}++if (prev.trim() === fresh.trim()) {+ console.log('CSP unchanged');+ process.exit(0);+}++writeFileSync(TARGET, fresh);+console.log(`updated ${TARGET}`);+console.log('--- diff snippet ---');+console.log('was:', prev.slice(0, 300).replace(/\n/g, ' '));+console.log('now:', fresh.slice(0, 300).replace(/\n/g, ' '));diff --git a/src/agent-eth-vanity-card.js b/src/agent-eth-vanity-card.jsindex 1ddd98242..10604be5a 100644--- a/src/agent-eth-vanity-card.js+++ b/src/agent-eth-vanity-card.js@@ -1,39 +1,43 @@/*** Agent ETH-CREATE2 vanity card — sibling of agent-vanity-grinder.js.*- * Surfaces the CREATE2 vanity record stored under- * /api/agents/:id/eth-vanity. Lifecycle states:+ * Lifecycle states:+ * none → form (deployer + raw initCode + prefix/suffix)+ * with leet-suggestions and word-chip presets+ * saved → predicted address + per-chain Deploy buttons+ * deployed → list of {chain, tx, verified} entries*- * none → form to pick deployer + raw initCode + prefix/suffix,- * grind locally (Web Workers), POST to save- * saved → show predicted address + Deploy button (Arachnid only)- * + Replace and Remove- * deployed → show address + chain id + tx link, no Deploy button+ * Same factory + same initCode + same salt = same address on every EVM+ * chain that has the factory deployed. The card surfaces this directly:+ * once you've ground a salt, you can deploy on Ethereum, Base, Arbitrum,+ * Optimism, Polygon, BNB, Avalanche, and the testnets in one click each.*- * Deploy uses the connected EVM signer via ethers BrowserProvider and- * targets the **Arachnid deterministic-deployment-proxy** at- * 0x4e59b44847b379578588920cA78FbF26c0B4956C. That proxy's interface is- * a raw fallback: send tx with `data = salt(32) ‖ initCode` and the- * contract is created at the predicted address.+ * One-click deploy uses the Arachnid deterministic-deployment-proxy+ * (data = salt ‖ initCode → CREATE2). Other factories need their ABI+ * to deploy, but the saved record still carries everything they need.*- * Other factory presets (Safe / CreateX / Coinbase Smart Wallet) save- * fine but show "Use your factory tooling to deploy" — those need- * factory-specific ABIs we don't bundle here.+ * Defenses:+ * - pre-deploy `eth_getCode` collision check on the predicted address+ * - server-side bytecode verification on the deployed callback*/import { keccak_256 } from '@noble/hashes/sha3';import { grindCreate2Vanity } from './eth/vanity/grinder.js';import {- validatePattern, validateAddress, validateInitCodeHash, MAX_PATTERN_LENGTH,+ validatePattern, validateAddress, validateInitCodeHash,+ letterCount, eip55Checksum, MAX_PATTERN_LENGTH,} from './eth/vanity/validation.js';--const ARACHNID_PROXY = '0x4e59b44847b379578588920ca78fbf26c0b4956c';+import { PRESET_CHIPS, suggestPrefixFromName } from './eth/vanity/wordlist.js';+import {+ CHAINS, ARACHNID_PROXY, CREATEX, SAFE_FACTORY, COINBASE_SW,+ chainsWithFactory, getChain, txUrl, addrUrl,+} from './eth/vanity/chains.js';const PRESETS = [- { addr: ARACHNID_PROXY, label: 'Arachnid proxy', deployable: true },- { addr: '0xba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed', label: 'CreateX', deployable: false },- { addr: '0x4e1dcf7ad4e460cfd30791ccc4f9c8a4f820ec67', label: 'Safe v1.4.1', deployable: false },- { addr: '0x0ba5ed0c6aa8c49038f819e587e2633c4a9f428a', label: 'Coinbase SW', deployable: false },+ { addr: ARACHNID_PROXY, label: 'Arachnid proxy', deployable: true },+ { addr: CREATEX, label: 'CreateX', deployable: false },+ { addr: SAFE_FACTORY, label: 'Safe v1.4.1', deployable: false },+ { addr: COINBASE_SW, label: 'Coinbase SW', deployable: false },];const STYLE = `@@ -45,12 +49,13 @@ const STYLE = `.agent-eth-vanity { border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; padding: .85rem 1rem; margin: .4rem 0 0; font: 13px/1.4 system-ui, sans-serif; background: rgba(255,255,255,0.03); color: #e6e6ea; }.agent-eth-vanity h3 { margin: 0 0 .2rem; font-size: .85rem; font-weight: 600; color: #f2f2f5; display:flex; align-items:center; gap:.4rem; }.agent-eth-vanity h3 .badge { font-size: .65rem; font-weight: 600; padding: .1rem .45rem; border-radius: 999px; background: linear-gradient(90deg, rgba(167,139,250,0.2), rgba(99,102,241,0.2)); color: #c4b5fd; border: 1px solid rgba(167,139,250,0.25); letter-spacing: .03em; }+.agent-eth-vanity h3 .badge.case { background: linear-gradient(90deg, rgba(251,191,36,0.18), rgba(239,68,68,0.18)); color: #fbbf24; border-color: rgba(251,191,36,0.25); }.agent-eth-vanity .sub { color: rgba(230,230,234,0.6); font-size: .78rem; margin: 0 0 .55rem; }.agent-eth-vanity .row { display: flex; gap: .5rem; align-items: center; margin-top: .35rem; flex-wrap: wrap; }.agent-eth-vanity .grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: .5rem; }@media (max-width: 480px) { .agent-eth-vanity .grid2 { grid-template-columns: 1fr; } }.agent-eth-vanity input, .agent-eth-vanity textarea, .agent-eth-vanity select { font: inherit; font-family: ui-monospace, monospace; padding: .35rem .55rem; border-radius: 5px; border: 1px solid rgba(255,255,255,0.12); background: #1a1a1a; color: #e6e6ea; width: 100%; }-.agent-eth-vanity input:focus, .agent-eth-vanity textarea:focus { outline: none; border-color: rgba(255,255,255,0.3); }+.agent-eth-vanity input:focus, .agent-eth-vanity textarea:focus, .agent-eth-vanity select:focus { outline: none; border-color: rgba(255,255,255,0.3); }.agent-eth-vanity input.invalid, .agent-eth-vanity textarea.invalid { border-color: #ff8a80; }.agent-eth-vanity textarea { resize: vertical; min-height: 3em; }.agent-eth-vanity label { display: block; font-size: .7rem; color: rgba(230,230,234,0.55); margin: .55rem 0 .15rem; }@@ -71,6 +76,16 @@ const STYLE = `.agent-eth-vanity .meta-line { font-size: .68rem; color: rgba(230,230,234,0.5); margin-top: .4rem; font-family: ui-monospace, monospace; }.agent-eth-vanity a { color: #a78bfa; text-decoration: none; }.agent-eth-vanity a:hover { text-decoration: underline; }+.agent-eth-vanity .chain-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(160px,1fr)); gap: .35rem; margin-top: .5rem; }+.agent-eth-vanity .chain-cell { display:flex; flex-direction:column; gap:.15rem; padding:.4rem .55rem; border:1px solid rgba(255,255,255,0.08); border-radius:6px; background:rgba(255,255,255,0.02); }+.agent-eth-vanity .chain-cell .ch-name { font-size:.72rem; color:rgba(230,230,234,0.85); font-weight:600; }+.agent-eth-vanity .chain-cell .ch-status { font-size:.65rem; color:rgba(230,230,234,0.55); font-family: ui-monospace, monospace; }+.agent-eth-vanity .chain-cell.deployed { border-color: rgba(74,222,128,0.25); background: rgba(74,222,128,0.05); }+.agent-eth-vanity .chain-cell.deployed .ch-status { color: #4ade80; }+.agent-eth-vanity .chain-cell.unverified { border-color: rgba(251,191,36,0.25); background: rgba(251,191,36,0.05); }+.agent-eth-vanity .chain-cell.unverified .ch-status { color: #fbbf24; }+.agent-eth-vanity .chain-cell button { padding: .2rem .5rem; font-size: .7rem; }+.agent-eth-vanity .chain-cell.testnet .ch-name::after { content: ' · testnet'; font-weight: 400; opacity: .6; }`;let _styleInjected = false;@@ -95,16 +110,6 @@ function _hexToBytes(hex) {function _bytesToHex(b) { let s=''; for (let i=0;i<b.length;i++) s += b[i].toString(16).padStart(2,'0'); return s; }function _isHex(s) { return typeof s === 'string' && /^0x[0-9a-f]*$/i.test(s) && s.length % 2 === 0; }-const EXPLORERS = {- 1: 'https://etherscan.io',- 8453: 'https://basescan.org',- 10: 'https://optimistic.etherscan.io',- 42161: 'https://arbiscan.io',- 137: 'https://polygonscan.com',- 11155111: 'https://sepolia.etherscan.io',- 84532: 'https://sepolia.basescan.org',-};-/*** @param {object} opts* @param {HTMLElement} opts.panel@@ -129,19 +134,22 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {root.className = 'agent-eth-vanity';wrapper.appendChild(root);+ const suggestedFromName = suggestPrefixFromName(identity.name || '');+const state = {loaded: false,- record: null, // null when no record exists- mode: 'view', // view | form+ record: null,+ mode: 'view',busy: false,progress: null,err: null,ok: null,+ deployStatusByChain: {}, // { [chainId]: 'pending' | 'submitted' }form: {deployer: ARACHNID_PROXY,deployerLabel: 'Arachnid proxy',rawInitCode: '',- prefix: '',+ prefix: suggestedFromName || '',suffix: '',},};@@ -173,7 +181,6 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {root.innerHTML = `<div class="sub">Loading…</div>`;return;}-if (state.mode === 'form' || (!state.record && state.busy)) return renderForm();if (state.record) return renderSaved();return renderEmpty();@@ -183,9 +190,11 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {root.innerHTML = `<h3>Vanity address <span class="badge">CREATE2</span></h3><p class="sub">- Predict and assign a smart-contract address whose hex digits start (or end) with characters you choose.- No keys involved — you grind a salt and deploy from a factory with your own EVM signer.+ Predict a smart-contract address whose hex starts (or ends) with characters you choose, then deploy it+ to <strong>every EVM chain</strong> that has your factory — same address everywhere.+ No keys. Mixed-case patterns enable EIP-55 checksum matching.</p>+ ${suggestedFromName ? `<p class="sub" style="color:#c4b5fd">Suggested prefix from agent name: <code style="font-family:ui-monospace,monospace">${_esc(suggestedFromName)}</code></p>` : ''}<div class="row"><button class="primary" data-act="new">Set up CREATE2 vanity</button><a href="/eth-vanity" target="_blank" rel="noopener" style="font-size:.72rem">open full grinder ↗</a>@@ -196,35 +205,39 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {}function renderForm() {- const canDeploy = PRESETS.find((p) => p.addr === state.form.deployer.toLowerCase())?.deployable;+ const presetMatch = PRESETS.find((p) => p.addr === state.form.deployer.toLowerCase());+ const canDeploy = !!presetMatch?.deployable;const presets = PRESETS.map((p) =>`<button class="preset ${state.form.deployer.toLowerCase() === p.addr ? 'active' : ''}" data-preset="${p.addr}" data-label="${_esc(p.label)}" type="button">${_esc(p.label)}</button>`).join('');+ const wordChips = PRESET_CHIPS.map((w) => `<button class="preset" data-word="${_esc(w)}" type="button">${_esc(w)}</button>`).join('');+ const caseSensitive = /[A-F]/.test(state.form.prefix) || /[A-F]/.test(state.form.suffix);root.innerHTML = `- <h3>Set up CREATE2 vanity <span class="badge">CREATE2</span></h3>+ <h3>Set up CREATE2 vanity <span class="badge">CREATE2</span>${caseSensitive ? '<span class="badge case">EIP-55</span>' : ''}</h3><p class="sub">Pick the factory you'll deploy through, paste its init code, choose a pattern, and grind.</p><label>Deployer / factory</label><input data-field="deployer" type="text" value="${_esc(state.form.deployer)}" spellcheck="false" /><div class="preset-row">${presets}</div>${canDeploy- ? `<div class="meta-line">✓ Arachnid proxy supports one-click deploy from this card.</div>`- : `<div class="meta-line">Note: this factory requires its own deploy ABI — saving works, but you'll deploy from your own tooling.</div>`}+ ? `<div class="meta-line">✓ Arachnid proxy supports one-click deploy from this card on every chain it's deployed to.</div>`+ : `<div class="meta-line">Note: this factory needs its own deploy ABI — saving works, but you'll deploy from your own tooling.</div>`}<label>Init code (raw deploy bytecode + ABI-encoded args)</label><textarea data-field="initcode" rows="3" placeholder="0x…" spellcheck="false">${_esc(state.form.rawInitCode)}</textarea><div class="grid2"><div>- <label>Prefix (hex, after 0x)</label>- <input data-field="prefix" type="text" maxlength="${MAX_PATTERN_LENGTH}" value="${_esc(state.form.prefix)}" placeholder="beef" />+ <label>Prefix (hex; mixed case → EIP-55)</label>+ <input data-field="prefix" type="text" maxlength="${MAX_PATTERN_LENGTH}" value="${_esc(state.form.prefix)}" placeholder="${_esc(suggestedFromName || 'beef')}" /></div><div><label>Suffix (hex)</label><input data-field="suffix" type="text" maxlength="${MAX_PATTERN_LENGTH}" value="${_esc(state.form.suffix)}" placeholder="cafe" /></div></div>+ <div class="preset-row">${wordChips}</div><div class="row"><button class="primary" data-act="grind" ${state.busy ? 'disabled' : ''}>${state.busy ? 'Grinding…' : 'Grind & assign'}</button>@@ -240,8 +253,8 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {state.form.deployerLabel = p ? p.label : null;});root.querySelector('[data-field="initcode"]').addEventListener('input', (e) => { state.form.rawInitCode = e.target.value.trim(); });- root.querySelector('[data-field="prefix"]').addEventListener('input', (e) => { state.form.prefix = e.target.value.trim().replace(/^0x/i, '').toLowerCase(); });- root.querySelector('[data-field="suffix"]').addEventListener('input', (e) => { state.form.suffix = e.target.value.trim().toLowerCase(); });+ root.querySelector('[data-field="prefix"]').addEventListener('input', (e) => { state.form.prefix = e.target.value.trim().replace(/^0x/i, ''); });+ root.querySelector('[data-field="suffix"]').addEventListener('input', (e) => { state.form.suffix = e.target.value.trim(); });root.querySelectorAll('[data-preset]').forEach((b) => {b.addEventListener('click', () => {state.form.deployer = b.dataset.preset;@@ -249,6 +262,12 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {render();});});+ root.querySelectorAll('[data-word]').forEach((b) => {+ b.addEventListener('click', () => {+ state.form.prefix = b.dataset.word;+ render();+ });+ });root.querySelector('[data-act="back"]')?.addEventListener('click', () => { state.mode = 'view'; state.err = null; render(); });root.querySelector('[data-act="cancel"]')?.addEventListener('click', () => abort?.abort());root.querySelector('[data-act="grind"]')?.addEventListener('click', onGrindAndAssign);@@ -256,34 +275,60 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {function renderSaved() {const r = state.record;- const addr = r.predicted_address;- const noPrefix = addr.slice(2);+ const isCase = !!r.case_sensitive;+ const displayAddr = isCase ? ('0x' + eip55Checksum(r.predicted_address.slice(2))) : r.predicted_address;+ const noPrefix = displayAddr.slice(2);const pLen = (r.prefix || '').length;const sLen = (r.suffix || '').length;const mid = noPrefix.slice(pLen, noPrefix.length - sLen);const isArachnid = r.deployer.toLowerCase() === ARACHNID_PROXY;- const canDeploy = isArachnid && !!r.init_code && !r.deployed;- const explorer = r.deployed ? EXPLORERS[r.deployed.chain_id] : null;+ const canDeployHere = isArachnid && !!r.init_code;++ const deployments = Array.isArray(r.deployments) ? r.deployments : [];+ const deployedById = Object.fromEntries(deployments.map((d) => [d.chain_id, d]));+ const supported = chainsWithFactory(r.deployer);+ const status = state.deployStatusByChain;++ const cells = supported.map((c) => {+ const d = deployedById[c.id];+ const isPending = status[c.id] === 'pending' || status[c.id] === 'submitted';+ let cls = 'chain-cell';+ if (c.testnet) cls += ' testnet';+ if (d) cls += d.verified ? ' deployed' : ' unverified';+ let statusLine;+ if (d) {+ const tx = d.tx_hash;+ const url = txUrl(c.id, tx);+ statusLine = d.verified+ ? `<a href="${_esc(url)}" target="_blank" rel="noopener">verified · ${_esc(tx.slice(0,10))}…</a>`+ : `<a href="${_esc(url)}" target="_blank" rel="noopener">unverified · ${_esc(tx.slice(0,10))}…</a>`;+ } else if (canDeployHere) {+ statusLine = `<button data-deploy="${c.id}" ${isPending ? 'disabled' : ''}>${isPending ? 'deploying…' : 'Deploy'}</button>`;+ } else {+ statusLine = `<span style="opacity:.5">deploy from your tooling</span>`;+ }+ return `<div class="${cls}"><div class="ch-name">${_esc(c.name)}</div><div class="ch-status">${statusLine}</div></div>`;+ }).join('');++ const verifiedCount = deployments.filter((d) => d.verified).length;+ const unverifiedCount = deployments.length - verifiedCount;root.innerHTML = `- <h3>Vanity address <span class="badge">CREATE2</span></h3>+ <h3>Vanity address <span class="badge">CREATE2</span>${isCase ? '<span class="badge case">EIP-55</span>' : ''}</h3><p class="sub">Deterministic contract address — same on every chain that has the factory at <code style="font-family:ui-monospace,monospace">${_esc(r.deployer.slice(0,8))}…${_esc(r.deployer.slice(-4))}</code>${r.deployer_label ? ` (${_esc(r.deployer_label)})` : ''}.</p><div class="addr">0x${r.prefix ? `<span class="pfx">${_esc(r.prefix)}</span>` : ''}${_esc(mid)}${r.suffix ? `<span class="sfx">${_esc(r.suffix)}</span>` : ''}</div>- ${r.deployed ? `- <div class="ok">- ✓ Deployed on chain ${r.deployed.chain_id}- ${explorer ? `· <a href="${explorer}/tx/${_esc(r.deployed.tx_hash)}" target="_blank" rel="noopener">view tx</a>` : `· tx ${_esc(r.deployed.tx_hash.slice(0,12))}…`}- </div>- ` : ''}+ ${isCase ? `<div class="meta-line">lowercase: ${_esc(r.predicted_address)}</div>` : ''}<div class="meta-line">salt ${_esc(r.salt.slice(0, 14))}…${_esc(r.salt.slice(-4))}${r.init_code ? ' · init code stored' : ' · init code hash only'}+ ${verifiedCount ? ` · <span style="color:#4ade80">${verifiedCount} verified</span>` : ''}+ ${unverifiedCount ? ` · <span style="color:#fbbf24">${unverifiedCount} unverified</span>` : ''}</div>- <div class="row">- ${canDeploy ? `<button class="primary" data-act="deploy" ${state.busy ? 'disabled' : ''}>${state.busy ? 'Deploying…' : 'Deploy via Arachnid'}</button>` : ''}+ <div class="chain-grid">${cells}</div>+ <div class="row" style="margin-top:.7rem"><button data-act="copy">Copy address</button><button data-act="json">Download JSON</button><button data-act="replace">Replace</button>@@ -293,7 +338,7 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {${state.err ? `<div class="err">${_esc(state.err)}</div>` : ''}`;root.querySelector('[data-act="copy"]').addEventListener('click', async () => {- try { await navigator.clipboard.writeText(r.predicted_address); state.ok = 'address copied'; render(); setTimeout(() => { state.ok = null; render(); }, 1500); } catch {}+ try { await navigator.clipboard.writeText(displayAddr); state.ok = 'address copied'; render(); setTimeout(() => { state.ok = null; render(); }, 1500); } catch {}});root.querySelector('[data-act="json"]').addEventListener('click', () => {const blob = new Blob([JSON.stringify(r, null, 2)], { type: 'application/json' });@@ -304,20 +349,22 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {URL.revokeObjectURL(url);});root.querySelector('[data-act="replace"]').addEventListener('click', async () => {- if (!confirm('Replace the saved CREATE2 vanity record? The address above will no longer be associated with this agent.')) return;+ if (!confirm('Replace the saved CREATE2 vanity record? The address above and any deploy history will no longer be associated with this agent.')) return;try {await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });- state.record = null; state.mode = 'form'; state.err = null; render();+ state.record = null; state.mode = 'form'; state.err = null; state.deployStatusByChain = {}; render();} catch (e) { state.err = e.message; render(); }});root.querySelector('[data-act="remove"]').addEventListener('click', async () => {if (!confirm('Remove the saved CREATE2 vanity record?')) return;try {await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });- state.record = null; state.err = null; render();+ state.record = null; state.err = null; state.deployStatusByChain = {}; render();} catch (e) { state.err = e.message; render(); }});- root.querySelector('[data-act="deploy"]')?.addEventListener('click', onDeploy);+ root.querySelectorAll('[data-deploy]').forEach((b) => {+ b.addEventListener('click', () => onDeploy(Number(b.dataset.deploy)));+ });}async function onGrindAndAssign() {@@ -327,13 +374,16 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {if (!dv.valid) { state.err = `deployer: ${dv.error}`; render(); return; }if (!_isHex(f.rawInitCode)) { state.err = 'init code must be 0x-prefixed even-length hex'; render(); return; }if (!f.prefix && !f.suffix) { state.err = 'pick a prefix or suffix'; render(); return; }+ let caseSensitive = false;if (f.prefix) {const v = validatePattern(f.prefix);if (!v.valid) { state.err = `prefix: ${v.errors.join('; ')}`; render(); return; }+ if (v.caseSensitive) caseSensitive = true;}if (f.suffix) {const v = validatePattern(f.suffix);if (!v.valid) { state.err = `suffix: ${v.errors.join('; ')}`; render(); return; }+ if (v.caseSensitive) caseSensitive = true;}const initCode = f.rawInitCode.toLowerCase();@@ -353,7 +403,6 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {onProgress: (p) => { state.progress = p; render(); },});- // Save to server.const res = await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, {method: 'POST',credentials: 'include',@@ -366,13 +415,13 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {predicted_address: result.address,prefix: f.prefix || null,suffix: f.suffix || null,+ case_sensitive: caseSensitive,deployer_label: f.deployerLabel || null,}),});const data = await res.json().catch(() => ({}));if (!res.ok) {if (res.status === 409) {- // Already has a record; delete and retry once.await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });return onGrindAndAssign();}@@ -390,48 +439,84 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {}}- async function onDeploy() {+ /**+ * Deploy on a specific chain. Switches the wallet to the target chain,+ * checks for prior deployment (collision), submits the raw CREATE2 tx,+ * and POSTs to the /deployed endpoint which verifies bytecode server-side.+ */+ async function onDeploy(chainId) {const r = state.record;if (!r || !r.init_code) { state.err = 'no init code stored — cannot deploy from this card'; render(); return; }if (r.deployer.toLowerCase() !== ARACHNID_PROXY) { state.err = 'one-click deploy only supported for the Arachnid proxy'; render(); return; }+ const target = getChain(chainId);+ if (!target) { state.err = `unknown chain ${chainId}`; render(); return; }++ state.deployStatusByChain = { ...state.deployStatusByChain, [chainId]: 'pending' };+ state.err = null; state.ok = null; render();- state.busy = true; state.err = null; state.ok = null; render();try {const { BrowserProvider } = await import('ethers');if (!window.ethereum) throw new Error('no EVM wallet detected — install MetaMask or another EIP-1193 wallet');const provider = new BrowserProvider(window.ethereum);await provider.send('eth_requestAccounts', []);++ // Switch network to the target chain (request → user approves).+ const hexChain = '0x' + chainId.toString(16);+ try {+ await provider.send('wallet_switchEthereumChain', [{ chainId: hexChain }]);+ } catch (switchErr) {+ if (switchErr?.code === 4902) {+ // Unknown to the wallet — try to add it from our registry.+ await provider.send('wallet_addEthereumChain', [{+ chainId: hexChain,+ chainName: target.name,+ rpcUrls: [target.rpc],+ blockExplorerUrls: [target.explorer],+ nativeCurrency: { name: target.currency, symbol: target.currency, decimals: 18 },+ }]);+ } else {+ throw switchErr;+ }+ }const signer = await provider.getSigner();- const network = await provider.getNetwork();- const chainId = Number(network.chainId);- // Arachnid proxy: send tx with data = salt(32) ‖ initCode → CREATE2.- const data = r.salt + r.init_code.slice(2);+ // Pre-deploy collision check: if the predicted address already has+ // bytecode on this chain, bail rather than wasting gas / overwriting state.+ const code = await provider.send('eth_getCode', [r.predicted_address, 'latest']);+ if (code && code !== '0x' && code !== '0x0') {+ throw new Error('contract already deployed at this address on this chain — refusing to overwrite');+ }+ const data = r.salt + r.init_code.slice(2);const tx = await signer.sendTransaction({ to: r.deployer, data });- state.ok = `submitted ${tx.hash.slice(0, 10)}… waiting for inclusion`;+ state.deployStatusByChain = { ...state.deployStatusByChain, [chainId]: 'submitted' };+ state.ok = `${target.name}: submitted ${tx.hash.slice(0, 10)}… waiting for inclusion`;render();+const receipt = await tx.wait();if (receipt?.status !== 1) throw new Error('deploy reverted');- // Persist deployment metadata.const mark = await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity/deployed`, {method: 'POST',credentials: 'include',headers: { 'content-type': 'application/json' },body: JSON.stringify({ chain_id: chainId, tx_hash: tx.hash }),});- if (mark.ok) {- const md = await mark.json().catch(() => ({}));- state.record = md.data || { ...r, deployed: { chain_id: chainId, tx_hash: tx.hash, at: new Date().toISOString() } };+ const md = await mark.json().catch(() => ({}));+ if (md?.data?.record) {+ state.record = md.data.record;+ state.ok = md.data.verified+ ? `${target.name}: deployed and verified ✓`+ : `${target.name}: deployed but server couldn't verify bytecode (${md.data.reason || 'unknown'})`;} else {- state.record = { ...r, deployed: { chain_id: chainId, tx_hash: tx.hash, at: new Date().toISOString() } };+ state.ok = `${target.name}: deploy submitted`;}- state.ok = `deployed on chain ${chainId}`;+ delete state.deployStatusByChain[chainId];} catch (e) {- state.err = e.shortMessage || e.message || 'deploy failed';+ state.err = `${target.name}: ${e.shortMessage || e.message || 'deploy failed'}`;+ delete state.deployStatusByChain[chainId];} finally {- state.busy = false; render();+ render();}}diff --git a/src/components/inspect-report.jsx b/src/components/inspect-report.jsxnew file mode 100644index 000000000..c6bfd8758--- /dev/null+++ b/src/components/inspect-report.jsx@@ -0,0 +1,165 @@+import vhtml from 'vhtml';++/** @jsx vhtml */++function fmtBytes(n) {+ if (n == null) return '—';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(2)} MB`;+}++function fmtNumber(n) {+ if (n == null) return '—';+ return Number(n).toLocaleString();+}++const SEVERITY_COLOR = {+ critical: '#f44336',+ warn: '#f9a825',+ info: '#2196f3',+};++const SEVERITY_LABEL = {+ critical: 'Critical',+ warn: 'Warning',+ info: 'Info',+};++export function InspectReport({ inspect, suggestions, reportJSON }) {+ const c = inspect.counts;+ const totalTextureBytes = inspect.textures.reduce((a, t) => a + (t.byteSize || 0), 0);+ return (+ <div class="report">+ <div class="report-head">+ <h1>Performance inspector</h1>+ {reportJSON && (+ <a class="report-download" href={reportJSON} download="gltf-inspect-report.json">+ Download JSON+ </a>+ )}+ </div>+ <p class="report-sub">+ Structural analysis from{' '}+ <a href="https://gltf-transform.dev" target="_blank" rel="noreferrer">+ glTF-Transform+ </a>+ . Surfaces what the Khronos validator does not — texture weights, draw-call shape,+ and compression opportunities.+ </p>++ <div class="inspect-grid">+ <div class="inspect-card">+ <div class="inspect-card-label">File</div>+ <div class="inspect-card-value">{fmtBytes(inspect.fileSize)}</div>+ <div class="inspect-card-foot">{inspect.container.toUpperCase()}</div>+ </div>+ <div class="inspect-card">+ <div class="inspect-card-label">Triangles</div>+ <div class="inspect-card-value">{fmtNumber(c.totalTriangles)}</div>+ <div class="inspect-card-foot">{fmtNumber(c.totalVertices)} verts</div>+ </div>+ <div class="inspect-card">+ <div class="inspect-card-label">Draw calls</div>+ <div class="inspect-card-value">{fmtNumber(c.meshes)}</div>+ <div class="inspect-card-foot">{fmtNumber(c.materials)} materials</div>+ </div>+ <div class="inspect-card">+ <div class="inspect-card-label">Textures</div>+ <div class="inspect-card-value">{fmtNumber(c.textures)}</div>+ <div class="inspect-card-foot">{fmtBytes(totalTextureBytes)}</div>+ </div>+ <div class="inspect-card">+ <div class="inspect-card-label">Animations</div>+ <div class="inspect-card-value">{fmtNumber(c.animations)}</div>+ <div class="inspect-card-foot">{fmtNumber(c.skins)} skins</div>+ </div>+ <div class="inspect-card">+ <div class="inspect-card-label">Scene graph</div>+ <div class="inspect-card-value">{fmtNumber(c.nodes)}</div>+ <div class="inspect-card-foot">{fmtNumber(c.scenes)} scene(s)</div>+ </div>+ </div>++ <h2 class="report-section-heading" style="border-left-color:#6a5cff">+ Optimization suggestions{' '}+ <span class="report-count">({suggestions.length})</span>+ </h2>+ <div class="inspect-suggestions">+ {suggestions.map((s) => (+ <div+ class={`inspect-suggestion sev-${s.severity}`}+ style={`border-left-color:${SEVERITY_COLOR[s.severity] || '#888'}`}+ >+ <div class="inspect-suggestion-head">+ <span+ class="inspect-suggestion-badge"+ style={`background:${SEVERITY_COLOR[s.severity] || '#888'}`}+ >+ {SEVERITY_LABEL[s.severity] || s.severity}+ </span>+ <code class="inspect-suggestion-id">{s.id}</code>+ {s.estimate && (+ <span class="inspect-suggestion-estimate">{s.estimate}</span>+ )}+ </div>+ <div class="inspect-suggestion-msg">{s.message}</div>+ </div>+ ))}+ </div>++ {inspect.extensionsUsed.length > 0 && (+ <>+ <h2 class="report-section-heading" style="border-left-color:#888">+ Extensions used{' '}+ <span class="report-count">({inspect.extensionsUsed.length})</span>+ </h2>+ <ul class="inspect-ext-list">+ {inspect.extensionsUsed.map((ext) => (+ <li>+ <code>{ext}</code>+ {inspect.extensionsRequired.includes(ext) && (+ <span class="inspect-ext-required">required</span>+ )}+ </li>+ ))}+ </ul>+ </>+ )}++ {inspect.textures.length > 0 && (+ <>+ <h2 class="report-section-heading" style="border-left-color:#888">+ Textures <span class="report-count">({inspect.textures.length})</span>+ </h2>+ <div class="report-table-wrap">+ <table class="report-table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Type</th>+ <th>Dimensions</th>+ <th>Bytes</th>+ </tr>+ </thead>+ <tbody>+ {inspect.textures.map((t) => (+ <tr>+ <td>{t.name || <em>unnamed</em>}</td>+ <td>+ <code>{t.mimeType || '—'}</code>+ </td>+ <td>+ {t.width}×{t.height}+ </td>+ <td>{fmtBytes(t.byteSize)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/src/eth/vanity/chains.js b/src/eth/vanity/chains.jsnew file mode 100644index 000000000..161660f41--- /dev/null+++ b/src/eth/vanity/chains.js@@ -0,0 +1,117 @@+/**+ * EVM chain registry for the CREATE2 vanity flow.+ *+ * The killer feature of CREATE2 is "deploy at the same address on every+ * chain that has the factory deployed." For factories like the Arachnid+ * deterministic-deployment-proxy this is most major chains.+ *+ * Each entry has:+ * id EIP-155 chain ID+ * name human label+ * shortName chain shortName (matches eip155 chain registry)+ * rpc public RPC endpoint+ * explorer base URL (no trailing slash)+ * currency native token symbol+ * factories set of factory address presence flags (lowercase keys)+ */++export const ARACHNID_PROXY = '0x4e59b44847b379578588920ca78fbf26c0b4956c';+export const CREATEX = '0xba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed';+export const SAFE_FACTORY = '0x4e1dcf7ad4e460cfd30791ccc4f9c8a4f820ec67';+export const COINBASE_SW = '0x0ba5ed0c6aa8c49038f819e587e2633c4a9f428a';++/** @typedef {{ id: number, name: string, shortName: string, rpc: string, explorer: string, currency: string, testnet?: boolean, factories: Record<string, boolean> }} ChainMeta */++/** @type {ChainMeta[]} */+export const CHAINS = [+ {+ id: 1, name: 'Ethereum', shortName: 'eth',+ rpc: 'https://cloudflare-eth.com',+ explorer: 'https://etherscan.io',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true, [COINBASE_SW]: true },+ },+ {+ id: 8453, name: 'Base', shortName: 'base',+ rpc: 'https://mainnet.base.org',+ explorer: 'https://basescan.org',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true, [COINBASE_SW]: true },+ },+ {+ id: 10, name: 'Optimism', shortName: 'oeth',+ rpc: 'https://mainnet.optimism.io',+ explorer: 'https://optimistic.etherscan.io',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+ {+ id: 42161, name: 'Arbitrum', shortName: 'arb1',+ rpc: 'https://arb1.arbitrum.io/rpc',+ explorer: 'https://arbiscan.io',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+ {+ id: 137, name: 'Polygon', shortName: 'matic',+ rpc: 'https://polygon-rpc.com',+ explorer: 'https://polygonscan.com',+ currency: 'POL',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+ {+ id: 56, name: 'BNB Chain', shortName: 'bnb',+ rpc: 'https://bsc-dataseed.bnbchain.org',+ explorer: 'https://bscscan.com',+ currency: 'BNB',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+ {+ id: 43114, name: 'Avalanche', shortName: 'avax',+ rpc: 'https://api.avax.network/ext/bc/C/rpc',+ explorer: 'https://snowtrace.io',+ currency: 'AVAX',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true },+ },+ {+ id: 11155111, name: 'Sepolia', shortName: 'sep', testnet: true,+ rpc: 'https://ethereum-sepolia-rpc.publicnode.com',+ explorer: 'https://sepolia.etherscan.io',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+ {+ id: 84532, name: 'Base Sepolia', shortName: 'basesep', testnet: true,+ rpc: 'https://sepolia.base.org',+ explorer: 'https://sepolia.basescan.org',+ currency: 'ETH',+ factories: { [ARACHNID_PROXY]: true, [CREATEX]: true, [SAFE_FACTORY]: true },+ },+];++/** @returns {ChainMeta | undefined} */+export function getChain(chainId) {+ return CHAINS.find((c) => c.id === Number(chainId));+}++/**+ * Chains where a given factory address is deployed (lowercase deployer).+ * @param {string} deployer+ * @returns {ChainMeta[]}+ */+export function chainsWithFactory(deployer) {+ const key = String(deployer).toLowerCase();+ return CHAINS.filter((c) => c.factories[key]);+}++/** Build a tx URL for an explorer. */+export function txUrl(chainId, txHash) {+ const c = getChain(chainId);+ return c ? `${c.explorer}/tx/${txHash}` : null;+}++/** Build an address URL for an explorer. */+export function addrUrl(chainId, address) {+ const c = getChain(chainId);+ return c ? `${c.explorer}/address/${address}` : null;+}diff --git a/src/eth/vanity/grinder-worker.js b/src/eth/vanity/grinder-worker.jsindex e425e3151..7f8acce7e 100644--- a/src/eth/vanity/grinder-worker.js+++ b/src/eth/vanity/grinder-worker.js@@ -1,17 +1,19 @@/*** CREATE2 vanity grinder Web Worker.*- * Hot loop: sample 32 random salt bytes, compute the EIP-1014 CREATE2- * address, check prefix/suffix against the lowercased hex address.+ * Hot loop:+ * 1. bump the salt counter (last 8 bytes of salt)+ * 2. keccak_256 over `0xff ‖ deployer ‖ salt ‖ initCodeHash` (85 bytes)+ * 3. take the lower 20 bytes as the candidate address+ * 4. if pattern matching is case-INsensitive → compare lowercase hex+ * directly; else compute the EIP-55 checksum (one extra keccak over+ * the 40-char lowercase ASCII hex) and compare case-sensitively.*- * address = keccak256(0xff ‖ deployer ‖ salt ‖ initCodeHash)[12:]- *- * `deployer` (20 bytes) and `initCodeHash` (32 bytes) are fixed for the- * session — we pre-build an 85-byte input buffer with those segments- * already in place and only rewrite bytes 21..52 (the salt) per attempt.- *- * Uses `@noble/hashes/sha3` keccak_256. Vite bundles workers, so the- * import resolves at build time.+ * The 0xff‖deployer prefix is constant per session, but Keccak-f[1600]'s+ * permutation is the dominant cost and can't be cached for partial inputs+ * shorter than the rate (136 bytes) — our preimage is 85 bytes, fits in+ * one block. So per-attempt cost is ~1 permutation (case-insensitive) or+ * ~2 permutations (case-sensitive).*/import { keccak_256 } from '@noble/hashes/sha3';@@ -31,7 +33,6 @@ self.onmessage = (e) => {}};-/** Decode a 0x-prefixed hex string to a Uint8Array. */function hexToBytes(hex) {let h = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;if (h.length % 2) h = '0' + h;@@ -42,7 +43,6 @@ function hexToBytes(hex) {return out;}-/** Encode bytes as a lowercase hex string (no 0x). */function bytesToHex(bytes) {let s = '';for (let i = 0; i < bytes.length; i++) {@@ -53,7 +53,26 @@ function bytesToHex(bytes) {}/**- * @param {{ deployer: string, initCodeHash: string, prefix: string, suffix: string }} cfg+ * EIP-55 checksum of a 40-char lowercase hex address. Inlined so the hot+ * loop avoids any function-call overhead beyond the keccak itself.+ */+function eip55(lowerHex) {+ const ascii = new Uint8Array(40);+ for (let i = 0; i < 40; i++) ascii[i] = lowerHex.charCodeAt(i);+ const h = keccak_256(ascii);+ let out = '';+ for (let i = 0; i < 40; i++) {+ const c = lowerHex.charCodeAt(i);+ if (c < 0x61) { out += lowerHex[i]; continue; } // not a letter+ const nibble = (i & 1) === 0 ? (h[i >> 1] >> 4) : (h[i >> 1] & 0xf);+ out += nibble >= 8 ? lowerHex[i].toUpperCase() : lowerHex[i];+ }+ return out;+}++/**+ * @param {{ deployer: string, initCodeHash: string,+ * prefix: string, suffix: string, caseSensitive: boolean }} cfg*/async function grind(cfg) {const deployer = hexToBytes(cfg.deployer);@@ -61,25 +80,23 @@ async function grind(cfg) {if (deployer.length !== 20) return self.postMessage({ type: 'error', message: 'deployer must be 20 bytes' });if (initCodeHash.length !== 32) return self.postMessage({ type: 'error', message: 'initCodeHash must be 32 bytes' });- // Pre-build the 85-byte CREATE2 preimage: 0xff ‖ deployer(20) ‖ salt(32) ‖ initCodeHash(32).- // Only bytes 21..52 (salt) change per attempt.+ // Pre-build the 85-byte CREATE2 preimage. Only bytes 21..52 (salt) change.const buf = new Uint8Array(1 + 20 + 32 + 32);buf[0] = 0xff;buf.set(deployer, 1);buf.set(initCodeHash, 1 + 20 + 32);const saltView = buf.subarray(1 + 20, 1 + 20 + 32);- const wantPrefix = (cfg.prefix || '').toLowerCase();- const wantSuffix = (cfg.suffix || '').toLowerCase();+ const caseSensitive = !!cfg.caseSensitive;+ const wantPrefix = caseSensitive ? (cfg.prefix || '') : (cfg.prefix || '').toLowerCase();+ const wantSuffix = caseSensitive ? (cfg.suffix || '') : (cfg.suffix || '').toLowerCase();const pLen = wantPrefix.length;const sLen = wantSuffix.length;- // Seed the salt with a fresh random base; we then increment a counter- // at the tail to avoid re-deriving entropy on every iteration. The- // remaining 24 bytes of randomness still give 2^192 distinct salts- // per worker, which is more than enough.+ // Seed salt with crypto-random bytes; per-iteration we increment a+ // 64-bit counter at salt[24..32], leaving 24 bytes of fresh entropy.crypto.getRandomValues(saltView);- const counter = new DataView(buf.buffer, buf.byteOffset + 1 + 20 + 24, 8); // last 8 bytes of salt+ const counter = new DataView(buf.buffer, buf.byteOffset + 1 + 20 + 24, 8);let lo = counter.getUint32(4, false);let hi = counter.getUint32(0, false);@@ -88,30 +105,29 @@ async function grind(cfg) {let intervalStart = performance.now();while (running) {- // Bump the salt counter (big-endian 64-bit increment at salt[24..32]).+ // Bump 64-bit counter (big-endian) at salt[24..32].lo = (lo + 1) >>> 0;if (lo === 0) hi = (hi + 1) >>> 0;counter.setUint32(0, hi, false);counter.setUint32(4, lo, false);const digest = keccak_256(buf);- // Address is digest[12..32] — 20 bytes, lowercase hex.- const addr = bytesToHex(digest.subarray(12));+ const lowerHex = bytesToHex(digest.subarray(12));attempts++;intervalAttempts++;- const headOk = !pLen || addr.startsWith(wantPrefix);- const tailOk = !sLen || addr.endsWith(wantSuffix);+ const candidate = caseSensitive ? eip55(lowerHex) : lowerHex;+ const headOk = !pLen || candidate.startsWith(wantPrefix);+ const tailOk = !sLen || candidate.endsWith(wantSuffix);if (headOk && tailOk) {- // Copy salt out before transferring buf — saltView is a subarray of buf,- // and we want to keep buf inside the worker for any subsequent runs.const saltOut = new Uint8Array(32);saltOut.set(saltView);self.postMessage({type: 'match',- address: '0x' + addr,+ address: '0x' + lowerHex, // canonical lowercase+ addressChecksum: '0x' + (caseSensitive ? candidate : eip55(lowerHex)),salt: '0x' + bytesToHex(saltOut),attempts,}, [saltOut.buffer]);@@ -123,10 +139,14 @@ async function grind(cfg) {const now = performance.now();const elapsed = (now - intervalStart) / 1000;const rate = elapsed > 0 ? intervalAttempts / elapsed : 0;- self.postMessage({ type: 'progress', attempts, rate, sample: '0x' + addr });+ self.postMessage({+ type: 'progress',+ attempts,+ rate,+ sample: '0x' + (caseSensitive ? candidate : lowerHex),+ });intervalStart = now;intervalAttempts = 0;- // Yield so 'stop' messages get processed.await new Promise((r) => setTimeout(r, 0));}}diff --git a/src/eth/vanity/grinder.js b/src/eth/vanity/grinder.jsindex 888428f6f..a9b5583bf 100644--- a/src/eth/vanity/grinder.js+++ b/src/eth/vanity/grinder.js@@ -25,6 +25,8 @@ import {validateInitCodeHash,estimateAttempts,formatTimeEstimate,+ letterCount,+ eip55Checksum,} from './validation.js';const DEFAULT_MAX_WORKERS = 8;@@ -67,22 +69,26 @@ export function grindCreate2Vanity(opts = {}) {return Promise.reject(new Error('prefix or suffix is required'));}let normPrefix = '', normSuffix = '';+ let caseSensitive = false;if (prefix) {const v = validatePattern(prefix);if (!v.valid) return Promise.reject(new Error(`invalid prefix: ${v.errors.join('; ')}`));normPrefix = v.normalized;+ if (v.caseSensitive) caseSensitive = true;}if (suffix) {const v = validatePattern(suffix);if (!v.valid) return Promise.reject(new Error(`invalid suffix: ${v.errors.join('; ')}`));normSuffix = v.normalized;+ if (v.caseSensitive) caseSensitive = true;}const cores = Math.max(1, Math.min(opts.maxWorkers || (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4,DEFAULT_MAX_WORKERS,));- const expected = estimateAttempts(normPrefix.length + normSuffix.length);+ const totalLetters = letterCount(normPrefix) + letterCount(normSuffix);+ const expected = estimateAttempts(normPrefix.length + normSuffix.length, totalLetters, caseSensitive);const startedAt = performance.now();/** @type {Worker[]} */@@ -119,13 +125,15 @@ export function grindCreate2Vanity(opts = {}) {if (signal) signal.removeEventListener('abort', onAbort);const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0) + msg.attempts;resolve({- address: msg.address,- salt: msg.salt,- deployer: dep.normalized,- initCodeHash: ich.normalized,- attempts: totalAttempts,- durationMs: performance.now() - startedAt,- workers: cores,+ address: msg.address,+ addressChecksum: msg.addressChecksum || ('0x' + eip55Checksum(msg.address.slice(2))),+ salt: msg.salt,+ deployer: dep.normalized,+ initCodeHash: ich.normalized,+ caseSensitive,+ attempts: totalAttempts,+ durationMs: performance.now() - startedAt,+ workers: cores,});} else if (msg.type === 'progress') {attemptsByWorker[i] = msg.attempts;@@ -154,14 +162,15 @@ export function grindCreate2Vanity(opts = {}) {};w.postMessage({- type: 'start',- deployer: dep.normalized,- initCodeHash: ich.normalized,- prefix: normPrefix,- suffix: normSuffix,+ type: 'start',+ deployer: dep.normalized,+ initCodeHash: ich.normalized,+ prefix: normPrefix,+ suffix: normSuffix,+ caseSensitive,});}});}-export { validatePattern, validateAddress, validateInitCodeHash, estimateAttempts, formatTimeEstimate };+export { validatePattern, validateAddress, validateInitCodeHash, estimateAttempts, formatTimeEstimate, letterCount, eip55Checksum };diff --git a/src/eth/vanity/validation.js b/src/eth/vanity/validation.jsindex 5f6339499..d97901d7e 100644--- a/src/eth/vanity/validation.js+++ b/src/eth/vanity/validation.js@@ -1,20 +1,29 @@/*** Validation for Ethereum CREATE2 vanity grinding.*- * Pattern grammar: hex chars [0-9a-f], case-insensitive (we always compare- * lowercased — Ethereum addresses are 20 raw bytes; the EIP-55 mixed-case- * checksum is purely a presentation layer and isn't matched against here).+ * Pattern grammar+ * ───────────────+ * Hex chars [0-9a-fA-F]. The casing of the user's pattern selects the+ * matching mode:*- * CREATE2 address derivation (EIP-1014):+ * • all lowercase → case-INsensitive match against the lowercase address.+ * Fastest — no extra hashing per attempt.+ * • any uppercase → case-SENSITIVE match against the EIP-55 checksummed+ * address. ~16× rarer per char; +1 keccak per attempt.+ *+ * CREATE2 derivation (EIP-1014):* address = keccak256(0xff ‖ deployer ‖ salt ‖ keccak256(initCode))[12:]** The grinder samples random `salt` values; `deployer` and `initCodeHash`* are fixed per session. Result is a deterministic smart-contract address —- * this is the standard pattern used by modern smart-account factories- * (Safe, ERC-4337 SimpleAccount, Coinbase Smart Wallet, CreateX, etc.).+ * the standard pattern used by Safe, ERC-4337 SimpleAccount, Coinbase Smart+ * Wallet, CreateX, the Arachnid deterministic-deployment-proxy, etc.*/-const HEX = /^[0-9a-f]+$/i;+import { keccak_256 } from '@noble/hashes/sha3';++const HEX_ANY = /^[0-9a-fA-F]+$/;+const HEX_LOW = /^[0-9a-f]+$/;/** 20 hex chars (40 nibbles) is the entire address — anything past that is impossible. */export const MAX_PATTERN_LENGTH = 10;@@ -23,28 +32,36 @@ export const MAX_PATTERN_LENGTH = 10;export const FREE_THRESHOLD = 6;/**- * Validate a hex pattern (prefix or suffix), case-insensitive.- * Strips a leading "0x" if present.+ * Validate a hex pattern (prefix or suffix). Preserves casing so the caller+ * can decide whether to grind in case-sensitive mode.+ ** @param {string} pattern- * @returns {{ valid: boolean, errors: string[], normalized: string }}+ * @returns {{ valid: boolean, errors: string[], normalized: string, caseSensitive: boolean }}*/export function validatePattern(pattern) {const errors = [];if (typeof pattern !== 'string') {- return { valid: false, errors: ['pattern must be a string'], normalized: '' };+ return { valid: false, errors: ['pattern must be a string'], normalized: '', caseSensitive: false };}let p = pattern.trim();if (p.startsWith('0x') || p.startsWith('0X')) p = p.slice(2);if (p.length === 0) {- return { valid: false, errors: ['pattern is empty'], normalized: '' };+ return { valid: false, errors: ['pattern is empty'], normalized: '', caseSensitive: false };}if (p.length > MAX_PATTERN_LENGTH) {errors.push(`length ${p.length} exceeds maximum of ${MAX_PATTERN_LENGTH}`);}- if (!HEX.test(p)) {- errors.push('pattern must be hexadecimal (0-9, a-f)');+ if (!HEX_ANY.test(p)) {+ errors.push('pattern must be hexadecimal (0-9, a-f, A-F)');}- return { valid: errors.length === 0, errors, normalized: p.toLowerCase() };+ // Mixed/upper case → case-sensitive (EIP-55 checksum match).+ const caseSensitive = !HEX_LOW.test(p);+ return {+ valid: errors.length === 0,+ errors,+ normalized: caseSensitive ? p : p.toLowerCase(),+ caseSensitive,+ };}/** Validate a 20-byte EVM address: optional 0x, 40 hex chars. */@@ -53,7 +70,7 @@ export function validateAddress(addr) {let a = addr.trim();if (a.startsWith('0x') || a.startsWith('0X')) a = a.slice(2);if (a.length !== 40) return { valid: false, error: `address must be 20 bytes (40 hex chars), got ${a.length}` };- if (!HEX.test(a)) return { valid: false, error: 'address contains non-hex characters' };+ if (!HEX_ANY.test(a)) return { valid: false, error: 'address contains non-hex characters' };return { valid: true, normalized: '0x' + a.toLowerCase() };}@@ -63,16 +80,25 @@ export function validateInitCodeHash(hash) {let h = hash.trim();if (h.startsWith('0x') || h.startsWith('0X')) h = h.slice(2);if (h.length !== 64) return { valid: false, error: `init code hash must be 32 bytes (64 hex chars), got ${h.length}` };- if (!HEX.test(h)) return { valid: false, error: 'init code hash contains non-hex characters' };+ if (!HEX_ANY.test(h)) return { valid: false, error: 'init code hash contains non-hex characters' };return { valid: true, normalized: '0x' + h.toLowerCase() };}/**- * Expected attempts to find a hex pattern of `length` nibbles.- * 16^length, since each nibble is uniformly random from a 16-char alphabet.+ * Expected attempts to find a pattern of `length` chars.+ * - case-insensitive: 16^length (uniform random nibble)+ * - case-sensitive (EIP-55): each letter has an extra ½ probability of+ * being the right case → 16^length × 2^(letterCount). Digits are never+ * upper/lowercased so they don't pay the casing tax.+ *+ * @param {number} length+ * @param {number} [letterCount] – number of A-F characters in the pattern+ * @param {boolean} [caseSensitive=false]*/-export function estimateAttempts(length) {- return Math.pow(16, length);+export function estimateAttempts(length, letterCount = 0, caseSensitive = false) {+ const base = Math.pow(16, length);+ if (!caseSensitive) return base;+ return base * Math.pow(2, letterCount);}/** Format a duration estimate as a human-readable string. */@@ -86,3 +112,40 @@ export function formatTimeEstimate(attempts, ratePerSecond) {if (seconds < 31536000) return `~${Math.round(seconds / 86400)} days`;return `~${Math.round(seconds / 31536000)} years`;}++/** Count A-F (case-insensitive) characters in a hex string — for difficulty estimation. */+export function letterCount(pattern) {+ let n = 0;+ for (const c of pattern) {+ if (/[a-fA-F]/.test(c)) n++;+ }+ return n;+}++const _ASCII_HEX = '0123456789abcdef';++/**+ * Apply EIP-55 mixed-case checksum to a 40-char lowercase hex address.+ * Returns the checksummed address string (no 0x prefix).+ *+ * For each nibble of keccak256(asciiLowerAddress):+ * • if the corresponding char is a-f AND the hash nibble >= 8 → uppercase it+ * • else leave it+ *+ * @param {string} lowerHex - 40 lowercase hex chars+ * @returns {string} 40-char checksummed hex+ */+export function eip55Checksum(lowerHex) {+ const asciiBytes = new Uint8Array(40);+ for (let i = 0; i < 40; i++) asciiBytes[i] = lowerHex.charCodeAt(i);+ const hash = keccak_256(asciiBytes);+ let out = '';+ for (let i = 0; i < 40; i++) {+ const c = lowerHex[i];+ if (c < 'a') { out += c; continue; }+ // Each byte of the hash is two nibbles; the i-th nibble is at byte i>>1, high if i even.+ const nibble = (i & 1) === 0 ? (hash[i >> 1] >> 4) : (hash[i >> 1] & 0xf);+ out += nibble >= 8 ? c.toUpperCase() : c;+ }+ return out;+}diff --git a/src/eth/vanity/wordlist.js b/src/eth/vanity/wordlist.jsnew file mode 100644index 000000000..b41b5942b--- /dev/null+++ b/src/eth/vanity/wordlist.js@@ -0,0 +1,94 @@+/**+ * Pronounceable hex wordlist + leet-speak conversion.+ *+ * Hex chars only contain `0-9 a-f`, but enough English maps to that set+ * that you can spell things in raw hex. Useful for vanity prefixes and+ * suffixes that are immediately readable.+ *+ * Curated for: real words, no profanity, ≤5 chars (so they fit+ * comfortably under our MAX_PATTERN_LENGTH of 10).+ */++/** @type {Array<{ word: string, length: number }>} */+export const HEX_WORDS = [+ // Classic 4-char+ { word: 'beef', length: 4 }, { word: 'cafe', length: 4 }, { word: 'dead', length: 4 },+ { word: 'face', length: 4 }, { word: 'fade', length: 4 }, { word: 'feed', length: 4 },+ { word: 'fade', length: 4 }, { word: 'babe', length: 4 }, { word: 'b00b', length: 4 },+ { word: 'bead', length: 4 }, { word: 'cab', length: 3 }, { word: 'bed', length: 3 },+ { word: 'fed', length: 3 }, { word: 'ace', length: 3 }, { word: 'add', length: 3 },+ { word: 'aid', length: 3 }, { word: 'bad', length: 3 }, { word: 'fee', length: 3 },+ { word: 'dad', length: 3 }, { word: 'eed', length: 3 },++ // 5-char+ { word: 'decaf', length: 5 }, { word: 'faced', length: 5 }, { word: 'faded', length: 5 },+ { word: 'fded', length: 4 }, { word: 'beefd', length: 5 },+ // Crypto-cultural+ { word: 'b00ba', length: 5 }, { word: 'bafff', length: 5 }, { word: '0xdeed', length: 6 },+];++/**+ * Curated short presets — used as quick-pick chips in the UI.+ * Sorted by difficulty (length then letterCount).+ */+export const PRESET_CHIPS = [+ 'ace', 'bad', 'bed', 'cab', 'dad', 'fed',+ 'beef', 'cafe', 'dead', 'face', 'fade', 'feed', 'babe', 'bead',+ 'decaf', 'faced',+ // Pure leading-zeros — gas-saving classic.+ '0000', '00000',+];++/**+ * Convert ASCII text into hex by leet-speak substitution. Uppercase letters+ * preserve case in the output (so EIP-55 case-sensitive grinding kicks in).+ *+ * l/L → 1 (digit; safe to keep lowercase)+ * i/I → 1+ * o → 0 (digit)+ * o → 0+ * s → 5+ * t/T → 7+ * z/Z → 2+ * g/G → 9+ * q/Q → 9+ * y → 1+ *+ * Letters already in hex (a-f / A-F) and digits 0-9 pass through unchanged.+ * Returns null if any char can't be mapped.+ *+ * @param {string} text+ * @returns {string | null}+ */+export function leetToHex(text) {+ if (!text) return null;+ const map = {+ l: '1', L: '1', i: '1', I: '1', o: '0', O: '0',+ s: '5', S: '5', t: '7', T: '7', z: '2', Z: '2',+ g: '9', G: '9', q: '9', Q: '9', y: '1', Y: '1',+ };+ let out = '';+ for (const ch of text.replace(/[^a-zA-Z0-9]/g, '')) {+ if (/[0-9]/.test(ch)) out += ch;+ else if (/[a-fA-F]/.test(ch)) out += ch;+ else if (map[ch]) out += map[ch];+ else return null;+ }+ return out || null;+}++/**+ * Suggest a vanity prefix derived from an agent's display name. Returns+ * the leet-converted name truncated to 5 chars, or null if nothing useful+ * can be derived.+ *+ * @param {string} name+ * @returns {string | null}+ */+export function suggestPrefixFromName(name) {+ if (!name || typeof name !== 'string') return null;+ const candidate = leetToHex(name);+ if (!candidate) return null;+ const trimmed = candidate.slice(0, 5);+ return trimmed.length >= 3 ? trimmed : null;+}diff --git a/src/gltf-inspect.js b/src/gltf-inspect.jsnew file mode 100644index 000000000..589f52aed--- /dev/null+++ b/src/gltf-inspect.js@@ -0,0 +1,232 @@+// Model inspection + optimization suggestions using glTF-Transform.+//+// Isomorphic: works in the browser (Vite-bundled, used by /validation page) and+// in Node (re-exported by api/_lib/model-inspect.js for Vercel functions and the+// MCP tool). Input is raw bytes (Uint8Array) of either a binary GLB or a JSON+// glTF; output is a structured summary.++import { WebIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';++const GLB_MAGIC = 0x46546c67; // "glTF"++function isGLB(bytes) {+ if (!bytes || bytes.byteLength < 4) return false;+ const view = new DataView(bytes.buffer, bytes.byteOffset, Math.min(4, bytes.byteLength));+ return view.getUint32(0, true) === GLB_MAGIC;+}++async function readDocument(bytes) {+ const io = new WebIO().registerExtensions(ALL_EXTENSIONS);+ if (isGLB(bytes)) return io.readBinary(bytes);+ // Fall back to JSON glTF (rare, usually requires external buffers we don't have).+ const text = new TextDecoder().decode(bytes);+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ throw new Error('input is not a valid GLB or JSON glTF');+ }+ return io.readJSON({ json, resources: {} });+}++/**+ * Inspect a model's structure. Pure stats — no optimization advice.+ * @param {Uint8Array} bytes+ * @param {{ fileSize?: number }} opts+ */+export async function inspectModel(bytes, opts = {}) {+ const doc = await readDocument(bytes);+ const root = doc.getRoot();+ const asset = root.getAsset();++ const meshes = root.listMeshes();+ const materials = root.listMaterials();+ const textures = root.listTextures();+ const animations = root.listAnimations();+ const nodes = root.listNodes();+ const scenes = root.listScenes();+ const skins = root.listSkins();++ let totalVertices = 0;+ let totalTriangles = 0;+ let indexedPrimitives = 0;+ let nonIndexedPrimitives = 0;+ const primitiveModes = new Set();++ for (const mesh of meshes) {+ for (const prim of mesh.listPrimitives()) {+ const pos = prim.getAttribute('POSITION');+ const verts = pos ? pos.getCount() : 0;+ totalVertices += verts;+ const idx = prim.getIndices();+ if (idx) {+ indexedPrimitives++;+ totalTriangles += Math.floor(idx.getCount() / 3);+ } else {+ nonIndexedPrimitives++;+ totalTriangles += Math.floor(verts / 3);+ }+ primitiveModes.add(prim.getMode());+ }+ }++ const textureDetails = textures.map((tex) => {+ const img = tex.getImage();+ const size = tex.getSize();+ const [w, h] = size || [0, 0];+ return {+ name: tex.getName() || null,+ mimeType: tex.getMimeType(),+ width: w,+ height: h,+ byteSize: img ? img.byteLength : 0,+ };+ });++ const materialSummary = materials.map((m) => ({+ name: m.getName() || null,+ alphaMode: m.getAlphaMode(),+ doubleSided: m.getDoubleSided(),+ hasBaseColorTexture: !!m.getBaseColorTexture(),+ hasNormalTexture: !!m.getNormalTexture(),+ hasMetallicRoughnessTexture: !!m.getMetallicRoughnessTexture(),+ hasEmissiveTexture: !!m.getEmissiveTexture(),+ hasOcclusionTexture: !!m.getOcclusionTexture(),+ }));++ return {+ fileSize: opts.fileSize ?? bytes.byteLength,+ container: isGLB(bytes) ? 'glb' : 'gltf',+ generator: asset.generator || null,+ version: asset.version || null,+ copyright: asset.copyright || null,+ extensionsUsed: root.listExtensionsUsed().map((x) => x.extensionName),+ extensionsRequired: root.listExtensionsRequired().map((x) => x.extensionName),+ counts: {+ scenes: scenes.length,+ nodes: nodes.length,+ meshes: meshes.length,+ materials: materials.length,+ textures: textures.length,+ animations: animations.length,+ skins: skins.length,+ totalVertices,+ totalTriangles,+ indexedPrimitives,+ nonIndexedPrimitives,+ },+ primitiveModes: [...primitiveModes],+ textures: textureDetails,+ materials: materialSummary,+ };+}++/**+ * Offer optimization suggestions based on structural analysis.+ * Each suggestion has a severity (info|warn|critical), id, message, and+ * optional estimate of impact.+ *+ * @param {Awaited<ReturnType<typeof inspectModel>>} info+ * @returns {Array<{ id: string, severity: 'info'|'warn'|'critical', message: string, estimate?: string }>}+ */+export function suggestOptimizations(info) {+ const out = [];+ const c = info.counts;++ if (c.totalTriangles > 500_000) {+ out.push({+ id: 'tri_budget',+ severity: 'warn',+ message: `Model has ${c.totalTriangles.toLocaleString()} triangles — consider mesh decimation or LODs for web delivery.`,+ });+ }++ if (!info.extensionsUsed.includes('KHR_draco_mesh_compression') && c.totalVertices > 50_000) {+ out.push({+ id: 'draco',+ severity: 'info',+ message: 'Apply Draco compression to geometry for ~60-80% smaller vertex buffers.',+ estimate: `~${Math.round((c.totalVertices * 12) / 1024)} KB potential savings`,+ });+ }++ if (!info.extensionsUsed.includes('EXT_meshopt_compression') && c.totalVertices > 50_000) {+ out.push({+ id: 'meshopt',+ severity: 'info',+ message:+ 'Meshopt compression can reduce vertex+index size with faster decode than Draco.',+ });+ }++ const bigTextures = info.textures.filter((t) => Math.max(t.width, t.height) >= 4096);+ if (bigTextures.length > 0) {+ out.push({+ id: 'texture_oversized',+ severity: 'warn',+ message: `${bigTextures.length} texture(s) at ≥4K. Resize to 2048px for web unless hero detail is required.`,+ });+ }++ const pngTextures = info.textures.filter((t) => t.mimeType === 'image/png');+ if (pngTextures.length > 0 && !info.extensionsUsed.includes('KHR_texture_basisu')) {+ out.push({+ id: 'texture_basisu',+ severity: 'info',+ message:+ 'Transcode PNG textures to KTX2 (Basis Universal) for GPU-direct upload and smaller download.',+ });+ }++ if (c.nonIndexedPrimitives > 0) {+ out.push({+ id: 'non_indexed',+ severity: 'info',+ message: `${c.nonIndexedPrimitives} primitive(s) are non-indexed — re-indexing typically reduces vertex count by 2-3×.`,+ });+ }++ if (info.materials.length > c.meshes * 2 && c.meshes > 0) {+ out.push({+ id: 'too_many_materials',+ severity: 'info',+ message: `${info.materials.length} materials for ${c.meshes} meshes. Merging identical materials can reduce draw calls.`,+ });+ }++ const totalTextureBytes = info.textures.reduce((a, t) => a + t.byteSize, 0);+ if (totalTextureBytes > 20 * 1024 * 1024) {+ out.push({+ id: 'texture_weight',+ severity: 'warn',+ message: `Textures alone weigh ${(totalTextureBytes / 1024 / 1024).toFixed(1)} MB — combine with KTX2 compression and resize for web.`,+ });+ }++ if (info.fileSize > 25 * 1024 * 1024) {+ out.push({+ id: 'file_size',+ severity: 'warn',+ message: `Overall file size ${(info.fileSize / 1024 / 1024).toFixed(1)} MB is heavy for web delivery; target <10 MB.`,+ });+ }++ if (c.animations > 0 && c.skins === 0) {+ out.push({+ id: 'anim_without_skin',+ severity: 'info',+ message: `${c.animations} animation(s) without skins — confirm these are node-level and not orphan data.`,+ });+ }++ if (out.length === 0) {+ out.push({+ id: 'ok',+ severity: 'info',+ message: 'Model looks well-optimized for web delivery — no suggestions flagged.',+ });+ }++ return out;+}diff --git a/src/marketplace.js b/src/marketplace.jsindex 1ba1dfc7a..e6a494394 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -46,13 +46,20 @@ const state = {category: null, // null = Discover (all)q: '',sort: 'recommended',+ filter: 'all', // all | agents | avatarscursor: null,items: [],loading: false,publicAvatars: [],publicAvatarsLoaded: false,+ featured: [],+ heroIndex: 0,+ heroTimer: null,+ stats: null,};+const WIP_DISMISS_KEY = 'marketplace_wip_dismissed_v1';+const $ = (id) => document.getElementById(id);const els = {discovery: $('market-discovery'),@@ -73,6 +80,9 @@ function readRoute() {if (m) return { view: 'detail', id: m[1] };const tab = new URLSearchParams(location.search).get('tab');if (tab === 'tools') return { view: 'tools' };+ if (tab === 'skills') return { view: 'skills' };+ if (tab === 'mine') return { view: 'mine' };+ if (tab === 'avatars') return { view: 'list', filter: 'avatars' };return { view: 'list' };}@@ -162,8 +172,11 @@ async function loadList(reset = false) {if (state.cursor) url.searchParams.set('cursor', state.cursor);const r = await fetch(url);const j = await r.json();- const items = j || [];+ // Real endpoint wraps as { data: { items, next_cursor } }; legacy mock returns a bare array.+ const items = Array.isArray(j) ? j : (j?.data?.items ?? []);+ const nextCursor = Array.isArray(j) ? null : (j?.data?.next_cursor ?? null);state.items = reset ? items : [...state.items, ...items];+ state.cursor = nextCursor;renderGrid();} catch (err) {console.error('[marketplace] list', err);@@ -172,7 +185,10 @@ async function loadList(reset = false) {state.loading = false;}- if (reset) loadPublicAvatars();+ if (reset) {+ loadPublicAvatars();+ loadFeatured();+ }}async function loadPublicAvatars() {@@ -180,6 +196,7 @@ async function loadPublicAvatars() {const url = new URL(`${API}/explore`, location.origin);url.searchParams.set('source', 'avatar');url.searchParams.set('limit', '60');+ url.searchParams.set('quality', 'high');if (state.q) url.searchParams.set('q', state.q);const r = await fetch(url);if (!r.ok) return;@@ -187,31 +204,257 @@ async function loadPublicAvatars() {const avatars = (j?.items || []).filter((it) => it.kind === 'avatar' && it.glbUrl);state.publicAvatars = avatars;state.publicAvatarsLoaded = true;+ state.stats = j?.totals || state.stats;renderGrid();+ renderHeroStats();} catch (err) {console.error('[marketplace] public avatars', err);}}+// ── Featured hero (rotating 3D showcase) ─────────────────────────────────++async function loadFeatured() {+ if (state.featured.length || state.q || state.category) return;+ try {+ const url = new URL(`${API}/explore`, location.origin);+ url.searchParams.set('source', 'avatar');+ url.searchParams.set('quality', 'high');+ url.searchParams.set('limit', '12');+ const r = await fetch(url);+ if (!r.ok) return;+ const j = await r.json();+ const named = (j?.items || []).filter(+ (it) =>+ it.kind === 'avatar' &&+ it.glbUrl &&+ it.name &&+ !/^Avatar #|^TEST$|^test$/i.test(it.name.trim()) &&+ it.name.trim().length > 1,+ );+ state.featured = named.slice(0, 3);+ if (!state.featured.length) {+ // Fall back to any 3 named avatars to keep hero populated.+ state.featured = (j?.items || [])+ .filter((it) => it.kind === 'avatar' && it.glbUrl)+ .slice(0, 3);+ }+ state.heroIndex = 0;+ renderHero();+ startHeroAutoplay();+ } catch (err) {+ console.error('[marketplace] featured', err);+ }+}++function renderHero() {+ const hero = $('market-hero');+ if (!hero) return;+ if (!state.featured.length) {+ hero.hidden = true;+ return;+ }+ hero.hidden = false;+ const stage = $('market-hero-stage');+ const dots = $('market-hero-dots');+ stage.innerHTML = state.featured+ .map(+ (a, i) => `+ <div class="market-hero-slide${i === state.heroIndex ? ' active' : ''}" data-slot="${i}">+ <model-viewer+ src="${escapeHtml(a.glbUrl)}"+ alt="${escapeHtml(a.name || 'Avatar')}"+ auto-rotate+ rotation-per-second="20deg"+ camera-controls+ interaction-prompt="none"+ exposure="1.05"+ shadow-intensity="0.8"+ tone-mapping="aces"+ loading="${i === state.heroIndex ? 'eager' : 'lazy'}"+ reveal="auto"+ ></model-viewer>+ </div>`,+ )+ .join('');+ dots.innerHTML = state.featured+ .map(+ (_, i) =>+ `<button class="market-hero-dot${i === state.heroIndex ? ' active' : ''}" data-dot="${i}" aria-label="Slide ${i + 1}"></button>`,+ )+ .join('');+ dots.querySelectorAll('[data-dot]').forEach((btn) => {+ btn.addEventListener('click', () => {+ state.heroIndex = Number(btn.dataset.dot);+ renderHero();+ startHeroAutoplay();+ });+ });+ updateHeroMeta();+}++function updateHeroMeta() {+ const a = state.featured[state.heroIndex];+ if (!a) return;+ $('market-hero-title').textContent = a.name || 'Untitled avatar';+ $('market-hero-desc').textContent =+ a.description ||+ (a.author?.handle+ ? `A 3D avatar by ${a.author.handle}.`+ : 'A 3D avatar published to the community.');+ const view = $('market-hero-view');+ if (view) {+ view.onclick = () => {+ location.href = a.avatarId ? `/avatars/${a.avatarId}` : a.viewerUrl || '/';+ };+ }+ renderHeroStats();+}++function renderHeroStats() {+ const el = $('market-hero-stats');+ if (!el) return;+ const totals = state.stats;+ if (!totals) return;+ const items = [];+ if (totals.avatars != null) items.push(`<span><strong>${fmtNumber(totals.avatars)}</strong> avatars</span>`);+ if (totals.onchain != null) items.push(`<span><strong>${fmtNumber(totals.onchain)}</strong> onchain agents</span>`);+ if (totals.threeD != null) items.push(`<span><strong>${fmtNumber(totals.threeD)}</strong> in 3D</span>`);+ el.innerHTML = items.join('<span class="dot">·</span>');+ updateNavCounts();+}++// Update sidebar count badges from current state. Called after the explore+// feed settles so the nav reflects what's actually browsable.+function updateNavCounts() {+ const agentEl = $('nav-count-agent');+ const avatarEl = $('nav-count-avatar');+ const totals = state.stats || {};+ if (agentEl) {+ const n = Number(totals.onchain ?? state.items.length);+ if (Number.isFinite(n) && n > 0) {+ agentEl.textContent = fmtNumber(n);+ agentEl.hidden = false;+ } else {+ agentEl.hidden = true;+ }+ }+ if (avatarEl) {+ const n = Number(totals.avatars ?? state.publicAvatars.length);+ if (Number.isFinite(n) && n > 0) {+ avatarEl.textContent = fmtNumber(n);+ avatarEl.hidden = false;+ } else {+ avatarEl.hidden = true;+ }+ }+}++function startHeroAutoplay() {+ if (state.heroTimer) clearInterval(state.heroTimer);+ if (state.featured.length < 2) return;+ state.heroTimer = setInterval(() => {+ state.heroIndex = (state.heroIndex + 1) % state.featured.length;+ // Cheap update — just toggle active classes + meta, don't re-render model-viewers.+ document.querySelectorAll('.market-hero-slide').forEach((el) => {+ el.classList.toggle('active', Number(el.dataset.slot) === state.heroIndex);+ });+ document.querySelectorAll('.market-hero-dot').forEach((el) => {+ el.classList.toggle('active', Number(el.dataset.dot) === state.heroIndex);+ });+ updateHeroMeta();+ }, 6500);+}++function stopHeroAutoplay() {+ if (state.heroTimer) clearInterval(state.heroTimer);+ state.heroTimer = null;+}++// ── WIP banner dismiss ───────────────────────────────────────────────────++function initWipBanner() {+ const banner = $('market-wip-banner');+ const dismiss = $('market-wip-dismiss');+ if (!banner) return;+ const dismissed = (() => {+ try {+ return localStorage.getItem(WIP_DISMISS_KEY) === '1';+ } catch {+ return false;+ }+ })();+ banner.hidden = dismissed;+ if (dismiss) {+ dismiss.addEventListener('click', () => {+ banner.hidden = true;+ try {+ localStorage.setItem(WIP_DISMISS_KEY, '1');+ } catch {+ // localStorage unavailable — banner stays dismissed only for the session+ }+ });+ }+}++// ── Filter chips (All / Agents / Avatars) ────────────────────────────────++function bindFilterChips() {+ const chips = document.querySelectorAll('#market-filter-chips .market-chip');+ chips.forEach((chip) => {+ chip.addEventListener('click', () => {+ chips.forEach((c) => c.classList.remove('active'));+ chip.classList.add('active');+ state.filter = chip.dataset.filter || 'all';+ // Hero showcases community avatars; hide it when filter is agents-only.+ const hero = $('market-hero');+ if (hero) {+ if (state.filter === 'agents') {+ hero.hidden = true;+ stopHeroAutoplay();+ } else if (state.featured.length) {+ hero.hidden = false;+ startHeroAutoplay();+ }+ }+ renderGrid();+ });+ });+}+function renderGrid() {- const showAvatars = !state.category;+ const showAgents = state.filter !== 'avatars';+ const showAvatars = state.filter !== 'agents' && !state.category;+ const agentItems = showAgents ? state.items : [];const avatars = showAvatars ? state.publicAvatars : [];- if (!state.items.length && !avatars.length) {- const msg = state.publicAvatarsLoaded- ? 'No agents yet. Be the first to publish!'- : 'Loading…';- els.grid.innerHTML = `<div class="market-empty">${msg}</div>`;+ if (!agentItems.length && !avatars.length) {+ let msg;+ if (!state.publicAvatarsLoaded && !state.items.length) {+ msg = renderSkeletons(8);+ } else if (state.filter === 'agents') {+ msg = '<div class="market-empty">No agents published yet. Be the first.</div>';+ } else if (state.filter === 'avatars') {+ msg = '<div class="market-empty">No public avatars match your search.</div>';+ } else {+ msg = '<div class="market-empty">Nothing here yet — try a different search.</div>';+ }+ els.grid.innerHTML = msg;els.loadMore.hidden = true;return;}let html = '';- if (state.items.length) {- html += state.items.map(renderCard).join('');+ if (agentItems.length) {+ if (state.filter === 'all' && avatars.length) {+ html += `<div class="market-grid-section-title">Agents <span class="count">${agentItems.length}</span></div>`;+ }+ html += agentItems.map(renderCard).join('');}if (avatars.length) {- html += `<div class="market-grid-section-title">Community Avatars <span class="count">${avatars.length} public</span></div>`;+ if (state.filter === 'all' && agentItems.length) {+ html += `<div class="market-grid-section-title">Community Avatars <span class="count">${avatars.length} public</span></div>`;+ }html += avatars.map(renderAvatarCard).join('');}els.grid.innerHTML = html;@@ -219,53 +462,340 @@ function renderGrid() {els.grid.querySelectorAll('[data-id]').forEach((card) => {card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));});- els.grid.querySelectorAll('[data-avatar-glb]').forEach((card) => {- card.addEventListener('click', () => {- const glb = card.dataset.avatarGlb;- if (glb) location.href = `/#model=${encodeURIComponent(glb)}`;+ els.grid.querySelectorAll('[data-avatar-id]').forEach((card) => {+ card.addEventListener('click', (e) => {+ // Don't trigger card nav when clicking the embedded author link.+ if (e.target.closest('a')) return;+ const id = card.dataset.avatarId;+ const avatar = state.publicAvatars.find((a) => a.avatarId === id);+ if (avatar) openAvatarModal(avatar);});});els.loadMore.hidden = !state.cursor;}+// ── Avatar detail modal ──────────────────────────────────────────────────++let activeAvatar = null;++function openAvatarModal(avatar) {+ activeAvatar = avatar;+ const overlay = $('avatar-modal-overlay');+ const stage = $('avatar-modal-stage');+ if (!overlay || !stage) return;++ const closeBtn = stage.querySelector('.avatar-modal-close');+ stage.innerHTML = '';+ if (closeBtn) stage.appendChild(closeBtn);+ const mv = document.createElement('model-viewer');+ mv.setAttribute('src', avatar.glbUrl || '');+ mv.setAttribute('alt', avatar.name || 'Avatar');+ mv.setAttribute('auto-rotate', '');+ mv.setAttribute('rotation-per-second', '18deg');+ mv.setAttribute('camera-controls', '');+ mv.setAttribute('interaction-prompt', 'none');+ mv.setAttribute('exposure', '1.05');+ mv.setAttribute('shadow-intensity', '0.7');+ mv.setAttribute('tone-mapping', 'aces');+ stage.appendChild(mv);++ $('avatar-modal-title').textContent = avatar.name || 'Untitled avatar';+ $('avatar-modal-desc').textContent =+ avatar.description ||+ 'A 3D avatar published to the community. You can use it as the visual identity for a new agent.';++ const meta = $('avatar-modal-meta');+ const pills = [];+ if (avatar.createdAt) pills.push(`<span class="stat-pill">${escapeHtml(liveTime(avatar.createdAt))}</span>`);+ if (avatar.has3d !== false) pills.push('<span class="stat-pill">3D · GLB</span>');+ (avatar.tags || []).slice(0, 4).forEach((t) => {+ pills.push(`<span class="stat-pill">#${escapeHtml(t)}</span>`);+ });+ meta.innerHTML = pills.join('');++ const view = $('avatar-modal-view');+ if (view) {+ view.href = avatar.viewerUrl || (avatar.glbUrl ? `/#model=${encodeURIComponent(avatar.glbUrl)}` : '#');+ }+ const dl = $('avatar-modal-download');+ if (dl) {+ dl.href = avatar.glbUrl || '#';+ dl.download = (avatar.slug || avatar.avatarId || 'avatar') + '.glb';+ }++ overlay.hidden = false;+ requestAnimationFrame(() => overlay.classList.add('show'));+}++function closeAvatarModal() {+ const overlay = $('avatar-modal-overlay');+ if (!overlay) return;+ overlay.classList.remove('show');+ setTimeout(() => {+ overlay.hidden = true;+ const stage = $('avatar-modal-stage');+ const closeBtn = stage?.querySelector('.avatar-modal-close');+ if (stage) {+ stage.innerHTML = '';+ if (closeBtn) stage.appendChild(closeBtn);+ }+ activeAvatar = null;+ }, 200);+}++async function startAgentFromAvatar() {+ if (!activeAvatar) return;+ const params = new URLSearchParams({ avatar_id: activeAvatar.avatarId || '' });+ if (activeAvatar.name) params.set('avatar_name', activeAvatar.name);+ if (activeAvatar.glbUrl) params.set('avatar_glb', activeAvatar.glbUrl);+ location.href = `/agent-edit.html?${params.toString()}`;+}++// ── Skills marketplace tab ───────────────────────────────────────────────++const skillsState = {+ loaded: false,+ loading: false,+ skills: [],+ q: '',+ filter: 'all',+};++async function loadSkillsTab(force = false) {+ if (skillsState.loading) return;+ if (skillsState.loaded && !force) {+ renderSkillsGrid();+ return;+ }+ skillsState.loading = true;+ const grid = $('skills-grid');+ if (grid) grid.innerHTML = renderSkeletons(8);++ try {+ const url = new URL(`${API}/marketplace/agents`, location.origin);+ url.searchParams.set('limit', '48');+ const r = await fetch(url);+ const j = await r.json();+ const items = Array.isArray(j) ? j : (j?.data?.items ?? []);++ const flat = [];+ for (const a of items) {+ const skills = Array.isArray(a.skills) ? a.skills : [];+ for (const s of skills) {+ const name = typeof s === 'string' ? s : s?.name;+ if (!name) continue;+ flat.push({+ name: String(name),+ agentId: a.id,+ agentName: a.name || 'Untitled',+ agentAuthor: a.author_name || 'Anonymous',+ agentAvatar: a.thumbnail_url || null,+ paid: !!a.has_paid_skills,+ category: a.category,+ });+ }+ }+ flat.sort((a, b) => Number(b.paid) - Number(a.paid) || a.name.localeCompare(b.name));+ skillsState.skills = flat;+ skillsState.loaded = true;+ } catch (err) {+ console.error('[marketplace] skills load', err);+ } finally {+ skillsState.loading = false;+ }+ renderSkillsGrid();+}++function renderSkillsGrid() {+ const grid = $('skills-grid');+ if (!grid) return;+ const q = skillsState.q.toLowerCase();+ const filtered = skillsState.skills.filter((s) => {+ if (skillsState.filter === 'paid' && !s.paid) return false;+ if (skillsState.filter === 'free' && s.paid) return false;+ if (q && !(s.name.toLowerCase().includes(q) || s.agentName.toLowerCase().includes(q))) return false;+ return true;+ });+ const sub = $('skills-subtitle');+ if (sub) sub.textContent = `${filtered.length} ${filtered.length === 1 ? 'skill' : 'skills'} across the marketplace`;++ if (!filtered.length) {+ const msg = !skillsState.skills.length+ ? `<div class="market-empty-cta">+ <h3>No skills published yet</h3>+ <p>Skills appear here once agents are published with capabilities. Be the first to publish.</p>+ <button id="skills-empty-publish">Submit an Agent</button>+ </div>`+ : '<div class="market-empty">No skills match your filter.</div>';+ grid.innerHTML = msg;+ const btn = $('skills-empty-publish');+ if (btn) btn.addEventListener('click', openSubmitModal);+ return;+ }+ grid.innerHTML = filtered.map(renderSkillCard).join('');+ grid.querySelectorAll('[data-agent-id]').forEach((card) => {+ card.addEventListener('click', () => {+ const id = card.dataset.agentId;+ if (id) navTo(`/marketplace/agents/${id}`);+ });+ });+}++function renderSkillCard(s) {+ const av = s.agentAvatar+ ? `<span class="av" style="background:url('${escapeHtml(s.agentAvatar)}') center/cover"></span>`+ : `<span class="av">${escapeHtml(initial(s.agentName))}</span>`;+ return `<div class="market-skill-card" data-agent-id="${escapeHtml(s.agentId)}">+ <div class="skill-head">+ <div class="skill-name">${escapeHtml(s.name)}</div>+ <div class="skill-price ${s.paid ? 'paid' : 'free'}">${s.paid ? 'Paid' : 'Free'}</div>+ </div>+ <div class="skill-agent">${av}<span>${escapeHtml(s.agentName)}</span></div>+ <div class="skill-cta ${s.paid ? 'purchase' : ''}">${s.paid ? 'View & purchase →' : 'Open agent →'}</div>+ </div>`;+}++// ── My Agents tab ────────────────────────────────────────────────────────++const mineState = { loaded: false, loading: false, items: [] };++async function loadMine(force = false) {+ if (mineState.loading) return;+ if (mineState.loaded && !force) return renderMineGrid();+ mineState.loading = true;+ const grid = $('mine-grid');+ if (grid) grid.innerHTML = renderSkeletons(4);+ try {+ const r = await fetch(`${API}/marketplace/agents/mine`, { credentials: 'include' });+ if (r.status === 401) {+ grid.innerHTML = `<div class="market-empty-cta">+ <h3>Sign in to see your agents</h3>+ <p>Your published and draft agents will appear here.</p>+ <button id="mine-signin">Sign in</button>+ </div>`;+ $('mine-signin')?.addEventListener('click', () => {+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ });+ mineState.loading = false;+ return;+ }+ const j = await r.json().catch(() => ({}));+ mineState.items = Array.isArray(j) ? j : (j?.data?.items ?? []);+ mineState.loaded = true;+ } catch (err) {+ console.error('[marketplace] mine', err);+ } finally {+ mineState.loading = false;+ }+ renderMineGrid();+}++function renderMineGrid() {+ const grid = $('mine-grid');+ const sub = $('mine-subtitle');+ if (!grid) return;+ if (sub) {+ sub.textContent = mineState.items.length+ ? `${mineState.items.length} ${mineState.items.length === 1 ? 'agent' : 'agents'}`+ : '';+ }+ if (!mineState.items.length) {+ grid.innerHTML = `<div class="market-empty-cta">+ <h3>No agents yet</h3>+ <p>Create your first agent — it'll appear here as draft, then publish when you're ready.</p>+ <button id="mine-empty-new">+ New Agent</button>+ </div>`;+ $('mine-empty-new')?.addEventListener('click', () => {+ location.href = '/agent-edit.html';+ });+ return;+ }+ grid.innerHTML = mineState.items.map(renderCard).join('');+ grid.querySelectorAll('[data-id]').forEach((card) => {+ card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));+ });+}++function renderSkeletons(n) {+ const cards = Array.from({ length: n }, () =>+ `<div class="market-card-skeleton"><div class="sk-thumb"></div><div class="sk-line"></div><div class="sk-line short"></div></div>`,+ ).join('');+ return cards;+}+function renderAvatarCard(a) {- const name = escapeHtml(a.name || 'Untitled Avatar');+ const name = escapeHtml(a.name || 'Untitled avatar');const desc = escapeHtml(a.description || '');- const date = a.createdAt ? formatDate(a.createdAt) : '';- const thumbStyle = a.image- ? `style="background-image:url('${escapeHtml(a.image)}')"`+ const when = a.createdAt ? liveTime(a.createdAt) : '';+ const author = a.author;+ const authorLine = author?.profileUrl+ ? `<a class="card-author" href="${escapeHtml(author.profileUrl)}" rel="author">${escapeHtml(author.displayName || author.handle)}</a>`+ : author?.handle+ ? `<span class="card-author">${escapeHtml(author.displayName || author.handle)}</span>`+ : `<span class="card-author muted">Anonymous</span>`;+ const tags = (a.tags || []).slice(0, 3);+ const tagPills = tags.length+ ? `<div class="card-tags">${tags.map((t) => `<span class="tag-pill">${escapeHtml(t)}</span>`).join('')}</div>`: '';- const fallback = a.image ? '' : '◉';- return `<div class="market-card-avatar" data-avatar-glb="${escapeHtml(a.glbUrl || '')}">- <div class="thumb" ${thumbStyle}>${fallback}</div>+ const preview = a.image+ ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" />`+ : a.glbUrl+ ? `<model-viewer+ src="${escapeHtml(a.glbUrl)}"+ alt="${name}"+ auto-rotate+ rotation-per-second="14deg"+ interaction-prompt="none"+ disable-zoom+ disable-pan+ disable-tap+ exposure="1"+ shadow-intensity="0.4"+ tone-mapping="aces"+ loading="lazy"+ reveal="auto"+ ></model-viewer>`+ : `<div class="thumb-fallback">◉</div>`;+ return `<div class="market-card-avatar" data-avatar-id="${escapeHtml(a.avatarId || '')}">+ <div class="thumb">${preview}</div><div class="body"><div class="title">${name}</div>- <div class="desc">${desc}</div>+ <div class="byline">${authorLine}${when ? `<span class="dot">·</span><span class="when">${escapeHtml(when)}</span>` : ''}</div>+ ${desc ? `<div class="desc">${desc}</div>` : ''}+ ${tagPills}<div class="footer">- <span>${date}</span><span class="avatar-pill">3D Avatar</span>+ <span class="open-cta">Open →</span></div></div></div>`;}function renderCard(a) {- const date = a.published ? formatDate(a.published) : '';- const skills = (a.skills || []).length;+ const published = a.published_at || a.published || a.created_at;+ const date = published ? formatDate(published) : '';+ const skillsCount = (a.skills || []).length;+ const author = a.author_name || a.author || 'Anonymous';+ const views = a.views_count ?? a.views ?? 0;+ const forks = a.forks_count ?? a.forks ?? 0;+ const paid = a.has_paid_skills || Object.keys(a.skill_prices || {}).length > 0;+ const avatarBlock = a.thumbnail_url+ ? `<div class="avatar avatar-img" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`+ : `<div class="avatar">${escapeHtml(initial(a.name))}</div>`;return `<div class="market-card-agent" data-id="${a.id}"><div class="head">- <div class="avatar">${a.avatar}</div>+ ${avatarBlock}<div style="min-width:0;flex:1"><div class="title">${escapeHtml(a.name || 'Untitled')}</div>- <div class="author">${escapeHtml(a.author || 'Anonymous')}</div>+ <div class="author">${escapeHtml(author)}</div></div></div><div class="desc">${escapeHtml(a.description || '')}</div><div class="stats">- <span class="stat-pill">⊙ ${a.views || 0}</span>- <span class="stat-pill">⑂ ${a.forks || 0}</span>- ${skills ? `<span class="stat-pill">▤ ${skills}</span>` : ''}- ${Object.keys(a.skill_prices || {}).length > 0 ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}+ <span class="stat-pill">⊙ ${fmtNumber(views)}</span>+ <span class="stat-pill">⑂ ${fmtNumber(forks)}</span>+ ${skillsCount ? `<span class="stat-pill">▤ ${skillsCount}</span>` : ''}+ ${paid ? `<span class="stat-pill paid-badge">$ Paid</span>` : ''}</div><div class="footer"><span>${date}</span>@@ -316,22 +846,56 @@ async function loadDetail(id) {els.detail.hidden = false;els.detail.scrollIntoView({ behavior: 'instant', block: 'start' });- const agent = state.items.find(item => item.id === id);- if (agent) {- detailState = { agent: agent, bookmarked: false };- renderDetail(agent, false);+ // Optimistically render from cached list item if available, then refresh from API.+ const cached = state.items.find((item) => item.id === id);+ if (cached) {+ detailState = { agent: cached, bookmarked: false };+ renderDetail(cached, false);+ } else {+ renderDetailError('Loading…');+ }++ try {+ const r = await fetch(`${API}/marketplace/agents/${id}`, { credentials: 'include' });+ if (!r.ok) {+ if (!cached) renderDetailError('Agent not found');+ return;+ }+ const j = await r.json();+ const agent = j?.data?.agent;+ if (!agent) {+ if (!cached) renderDetailError('Agent not found');+ return;+ }+ detailState = { agent, bookmarked: !!agent.bookmarked };+ renderDetail(agent, !!agent.bookmarked);try {- const res = await fetch(`/api/users/me/agent-skills/${id}`);- const { skills: agentSkills } = await res.json();- unlockedSkills = new Set(agentSkills || []);+ const res = await fetch(`/api/users/me/agent-skills/${id}`, { credentials: 'include' });+ if (res.ok) {+ const { skills: agentSkills } = await res.json();+ unlockedSkills = new Set(agentSkills || []);+ } else {+ unlockedSkills = new Set();+ }} catch {unlockedSkills = new Set();}renderSkillList(agent);- } else {- renderDetailError('Agent not found');+ // Versions + similar (best-effort).+ Promise.all([+ fetch(`${API}/marketplace/agents/${id}/versions`).then((r) => (r.ok ? r.json() : null)).catch(() => null),+ fetch(`${API}/marketplace/agents/${id}/similar`).then((r) => (r.ok ? r.json() : null)).catch(() => null),+ ]).then(([versionsRes, similarRes]) => {+ const versions = versionsRes?.data?.items || versionsRes?.data?.versions || [];+ renderVersions(versions);+ const similar = similarRes?.data?.items || similarRes?.data?.similar || [];+ renderSimilar(similar);+ });+ } catch (err) {+ console.error('[marketplace] detail load', err);+ if (!cached) renderDetailError('Failed to load agent.');}}@@ -345,22 +909,35 @@ function renderDetailError(msg) {}function renderDetail(a, bookmarked) {+ const author = a.author_name || a.author || 'Anonymous';+ const published = a.published_at || a.published || a.created_at;+ const views = a.views_count ?? a.views ?? 0;+ const forks = a.forks_count ?? a.forks ?? 0;$('d-name').textContent = a.name || 'Untitled';- $('d-avatar').textContent = a.avatar;- $('d-author').textContent = a.author || 'Anonymous';- $('d-published').textContent = a.published ? formatDate(a.published) : '';+ const avEl = $('d-avatar');+ if (a.thumbnail_url) {+ avEl.style.backgroundImage = `url('${a.thumbnail_url}')`;+ avEl.style.backgroundSize = 'cover';+ avEl.style.backgroundPosition = 'center';+ avEl.textContent = '';+ } else {+ avEl.style.backgroundImage = '';+ avEl.textContent = initial(a.name);+ }+ $('d-author').textContent = author;+ $('d-published').textContent = published ? formatDate(published) : '';$('d-category').textContent = CATEGORY_LABELS[a.category] || a.category || 'General';- $('d-views').textContent = `⊙ ${a.views || 0}`;+ $('d-views').textContent = `⊙ ${fmtNumber(views)}`;$('d-overview').textContent = a.description || '';$('d-overview-side').textContent = a.description || '';$('d-greeting').textContent = a.greeting || `Hello! I am ${a.name}. How can I help you today?`;- $('d-profile').textContent = a.prompt || '(No profile yet.)';+ $('d-profile').textContent = a.system_prompt || a.prompt || '(No profile yet.)';$('d-bookmark').classList.toggle('on', bookmarked);$('d-bookmark').textContent = bookmarked ? '★' : '☆';const forksEl = $('d-forks-pill');- if (a.forks > 0) {- forksEl.textContent = `⑂ ${a.forks} forks`;+ if (forks > 0) {+ forksEl.textContent = `⑂ ${fmtNumber(forks)} forks`;forksEl.hidden = false;} else {forksEl.hidden = true;@@ -542,8 +1119,16 @@ function bindEvents() {els.back.addEventListener('click', () => navTo('/marketplace'));$('d-fork').addEventListener('click', fork);$('d-bookmark').addEventListener('click', toggleBookmark);- bindTabs();+ bindTabs();bindSubmit();+ bindFilterChips();+ initWipBanner();+ // Pause the hero rotation when the page is hidden, resume when it returns —+ // avoids burning GPU on a tab the user isn't even looking at.+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) stopHeroAutoplay();+ else if (state.featured.length) startHeroAutoplay();+ });document.body.addEventListener('click', async (e) => {if (e.target.matches('.purchase-btn')) {@@ -558,6 +1143,63 @@ function bindEvents() {$('payment-modal-overlay')?.addEventListener('click', (e) => {if (e.target.id === 'payment-modal-overlay') closePaymentModal();});++ // Avatar detail modal+ $('avatar-modal-close')?.addEventListener('click', closeAvatarModal);+ $('avatar-modal-overlay')?.addEventListener('click', (e) => {+ if (e.target.id === 'avatar-modal-overlay') closeAvatarModal();+ });+ $('avatar-modal-use')?.addEventListener('click', startAgentFromAvatar);+ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && !$('avatar-modal-overlay')?.hidden) closeAvatarModal();+ });++ // Hero CTA — open most recent featured avatar in 3D modal+ $('market-hero-view')?.addEventListener('click', () => {+ const a = state.featured[state.heroIndex];+ if (a) openAvatarModal(a);+ });+ $('market-hero-fork')?.addEventListener('click', () => {+ const a = state.featured[state.heroIndex];+ if (a) {+ activeAvatar = a;+ startAgentFromAvatar();+ }+ });++ // Skills tab controls+ let skillsSearchTimer;+ $('skills-search')?.addEventListener('input', (e) => {+ clearTimeout(skillsSearchTimer);+ skillsSearchTimer = setTimeout(() => {+ skillsState.q = e.target.value.trim();+ renderSkillsGrid();+ }, 150);+ });+ document.querySelectorAll('[data-skill-filter]').forEach((chip) => {+ chip.addEventListener('click', () => {+ document.querySelectorAll('[data-skill-filter]').forEach((c) => c.classList.remove('active'));+ chip.classList.add('active');+ skillsState.filter = chip.dataset.skillFilter;+ renderSkillsGrid();+ });+ });++ // New Agent CTA on Mine tab+ $('market-new-agent-btn')?.addEventListener('click', () => {+ location.href = '/agent-edit.html';+ });++ // Sidebar nav: intercept marketplace links so we route via SPA+ document.querySelectorAll('.market-nav a[data-nav]').forEach((a) => {+ a.addEventListener('click', (e) => {+ const href = a.getAttribute('href') || '';+ if (href.startsWith('/marketplace')) {+ e.preventDefault();+ navTo(href);+ }+ });+ });}// ── Submit Modal ──────────────────────────────────────────────────────────@@ -634,6 +1276,27 @@ function formatDate(iso) {return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });}+function liveTime(iso) {+ if (!iso) return '';+ const d = new Date(iso);+ if (isNaN(d)) return '';+ const sec = (Date.now() - d.getTime()) / 1000;+ if (sec < 60) return 'just now';+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ if (sec < 604800) return `${Math.floor(sec / 86400)}d ago`;+ if (sec < 2592000) return `${Math.floor(sec / 604800)}w ago`;+ return formatDate(iso);+}++function fmtNumber(n) {+ const num = Number(n);+ if (!Number.isFinite(num)) return String(n ?? '');+ if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(num >= 10_000_000 ? 0 : 1)}M`;+ if (num >= 1_000) return `${(num / 1_000).toFixed(num >= 10_000 ? 0 : 1)}k`;+ return String(num);+}+// ── Purchase Flow ─────────────────────────────────────────────────────────//// One-shot Solana Pay purchase: server mints a unique reference Pubkey, the@@ -855,24 +1518,67 @@ function render() {document.querySelectorAll('.market-nav a[data-nav]').forEach((a) => {const nav = a.dataset.nav;const active =- (nav === 'agent' && (r.view === 'list' || r.view === 'detail')) ||- (nav === 'tools' && r.view === 'tools');+ (nav === 'agent' && r.view === 'list' && r.filter !== 'avatars') ||+ (nav === 'agent' && r.view === 'detail') ||+ (nav === 'avatars' && r.view === 'list' && r.filter === 'avatars') ||+ (nav === 'tools' && r.view === 'tools') ||+ (nav === 'skills' && r.view === 'skills') ||+ (nav === 'mine' && r.view === 'mine');a.classList.toggle('active', active);});+ // Apply route-driven filter (e.g. ?tab=avatars selects the avatars chip).+ if (r.view === 'list' && r.filter && r.filter !== state.filter) {+ state.filter = r.filter;+ document.querySelectorAll('#market-filter-chips .market-chip').forEach((c) => {+ c.classList.toggle('active', c.dataset.filter === r.filter);+ });+ // Re-render so the grid reflects the new filter without a refetch.+ if (state.publicAvatarsLoaded) renderGrid();+ }++ const skillsSec = $('market-skills-section');+ const mineSec = $('market-mine');+ const discovery = els.discovery;+ const tools = els.tools;+ const detail = els.detail;++ const setHidden = (el, hidden) => { if (el) el.hidden = hidden; };+if (r.view === 'detail') {loadDetail(r.id);- els.discovery.hidden = true;- els.tools.hidden = true;+ setHidden(discovery, true);+ setHidden(tools, true);+ setHidden(skillsSec, true);+ setHidden(mineSec, true);+ setHidden(detail, false);} else if (r.view === 'tools') {- els.detail.hidden = true;- els.discovery.hidden = true;- els.tools.hidden = false;+ setHidden(detail, true);+ setHidden(discovery, true);+ setHidden(skillsSec, true);+ setHidden(mineSec, true);+ setHidden(tools, false);if (!pluginState.loaded) loadPlugins(true);+ } else if (r.view === 'skills') {+ setHidden(detail, true);+ setHidden(discovery, true);+ setHidden(tools, true);+ setHidden(mineSec, true);+ setHidden(skillsSec, false);+ loadSkillsTab();+ } else if (r.view === 'mine') {+ setHidden(detail, true);+ setHidden(discovery, true);+ setHidden(tools, true);+ setHidden(skillsSec, true);+ setHidden(mineSec, false);+ loadMine();} else {- els.detail.hidden = true;- els.discovery.hidden = false;- els.tools.hidden = true;+ setHidden(detail, true);+ setHidden(tools, true);+ setHidden(skillsSec, true);+ setHidden(mineSec, true);+ setHidden(discovery, false);}}diff --git a/src/validation-page.js b/src/validation-page.jsnew file mode 100644index 000000000..e93ff8914--- /dev/null+++ b/src/validation-page.js@@ -0,0 +1,262 @@+/**+ * ValidationPage — orchestrator for /validation.+ *+ * Three tabs share one input source (file/URL/sample):+ * 1. Validate → official Khronos glTF-Validator (gltf-validator npm)+ * 2. Inspect → glTF-Transform stats + optimization suggestions+ * 3. Records → existing on-chain attestation browser/submitter+ *+ * The Validate tab can hand its report straight to the Records submit flow+ * via "Pin & sign on-chain" — no copy/paste round-trip.+ */++import { Validator } from './validator.js';+import { ValidatorReport } from './components/validator-report.jsx';+import { InspectReport } from './components/inspect-report.jsx';+import { inspectModel, suggestOptimizations } from './gltf-inspect.js';+import { hashReport } from './erc8004/validation-recorder.js';++// Khronos-curated sample assets, served from jsdelivr (CORS-friendly CDN over+// the official KhronosGroup/glTF-Sample-Assets repo). All are GLB-Binary so+// textures and buffers are self-contained — no external resource resolution.+const SAMPLE_BASE =+ 'https://cdn.jsdelivr.net/gh/KhronosGroup/glTF-Sample-Assets@main/Models';+const SAMPLES = [+ { name: 'Box', file: `${SAMPLE_BASE}/Box/glTF-Binary/Box.glb` },+ { name: 'Duck', file: `${SAMPLE_BASE}/Duck/glTF-Binary/Duck.glb` },+ { name: 'BoomBox', file: `${SAMPLE_BASE}/BoomBox/glTF-Binary/BoomBox.glb` },+ { name: 'DamagedHelmet', file: `${SAMPLE_BASE}/DamagedHelmet/glTF-Binary/DamagedHelmet.glb` },+ { name: 'Avocado', file: `${SAMPLE_BASE}/Avocado/glTF-Binary/Avocado.glb` },+];++export class ValidationPage {+ constructor(els, dashboard) {+ this.els = els;+ this.dashboard = dashboard;+ this.activeTab = 'validate';+ this.currentBytes = null;+ this.currentName = null;+ this.currentReport = null;+ this.currentInspect = null;+ this.currentSuggestions = null;++ this._renderSamples();+ this._bindEvents();+ this._restoreFromHash();+ }++ // ── Tabs ────────────────────────────────────────────────────────────────++ switchTab(name) {+ this.activeTab = name;+ this.els.tabs.forEach((btn) => {+ btn.classList.toggle('active', btn.dataset.tab === name);+ btn.setAttribute('aria-selected', btn.dataset.tab === name ? 'true' : 'false');+ });+ this.els.panels.forEach((p) => {+ p.classList.toggle('active', p.dataset.tab === name);+ });+ const url = new URL(location.href);+ url.hash = name;+ history.replaceState(null, '', url);+ }++ _restoreFromHash() {+ const h = (location.hash || '').replace(/^#/, '');+ if (h === 'validate' || h === 'inspect' || h === 'records') {+ this.switchTab(h);+ }+ }++ // ── Input wiring ────────────────────────────────────────────────────────++ _bindEvents() {+ this.els.tabs.forEach((btn) => {+ btn.addEventListener('click', () => this.switchTab(btn.dataset.tab));+ });++ this.els.fileInput.addEventListener('change', (e) => {+ const f = e.target.files?.[0];+ if (f) this.loadFile(f);+ });++ this.els.dropZone.addEventListener('dragover', (e) => {+ e.preventDefault();+ this.els.dropZone.classList.add('drag');+ });+ this.els.dropZone.addEventListener('dragleave', () => {+ this.els.dropZone.classList.remove('drag');+ });+ this.els.dropZone.addEventListener('drop', (e) => {+ e.preventDefault();+ this.els.dropZone.classList.remove('drag');+ const f = e.dataTransfer?.files?.[0];+ if (f) this.loadFile(f);+ });++ this.els.urlBtn.addEventListener('click', () => {+ const url = this.els.urlInput.value.trim();+ if (url) this.loadUrl(url);+ });+ this.els.urlInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') this.els.urlBtn.click();+ });++ this.els.signBtn.addEventListener('click', () => this._handOffToDashboard());+ }++ _renderSamples() {+ this.els.samples.innerHTML = SAMPLES.map(+ (s) =>+ `<button class="sample-chip" data-url="${s.file}" data-name="${s.name}">${s.name}</button>`,+ ).join('');+ this.els.samples.querySelectorAll('.sample-chip').forEach((btn) => {+ btn.addEventListener('click', () => {+ this.loadUrl(btn.dataset.url, btn.dataset.name);+ });+ });+ }++ // ── Load + run ──────────────────────────────────────────────────────────++ async loadFile(file) {+ this._setStatus(`Reading ${file.name} (${(file.size / 1024).toFixed(1)} KB)…`);+ try {+ const buffer = await file.arrayBuffer();+ await this._run(new Uint8Array(buffer), file.name);+ } catch (e) {+ this._setError(`Could not read file: ${e.message}`);+ }+ }++ async loadUrl(url, displayName) {+ const name = displayName || url.split('/').pop() || 'remote';+ this._setStatus(`Fetching ${name}…`);+ try {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const buffer = await res.arrayBuffer();+ await this._run(new Uint8Array(buffer), name);+ } catch (e) {+ this._setError(`Could not fetch ${name}: ${e.message}`);+ }+ }++ async _run(bytes, name) {+ this.currentBytes = bytes;+ this.currentName = name;+ this.currentReport = null;+ this.currentInspect = null;+ this.currentSuggestions = null;+ this.els.signBtn.disabled = true;++ this._setStatus(`Running validator + inspector on ${name}…`);+ this.els.validateOut.innerHTML = '<div class="loading">Validating…</div>';+ this.els.inspectOut.innerHTML = '<div class="loading">Inspecting…</div>';++ const validator = new Validator(null);+ const validatePromise = validator+ .validateBuffer(bytes)+ .then((report) => {+ this.currentReport = report;+ this._renderValidate(report);+ })+ .catch((e) => {+ this.els.validateOut.innerHTML = `<div class="err">Validator failed: ${escapeHtml(+ e.message,+ )}</div>`;+ });++ const inspectPromise = inspectModel(bytes, { fileSize: bytes.byteLength })+ .then((inspect) => {+ const suggestions = suggestOptimizations(inspect);+ this.currentInspect = inspect;+ this.currentSuggestions = suggestions;+ this._renderInspect(inspect, suggestions);+ })+ .catch((e) => {+ this.els.inspectOut.innerHTML = `<div class="err">Inspector failed: ${escapeHtml(+ e.message,+ )}</div>`;+ });++ await Promise.allSettled([validatePromise, inspectPromise]);+ this._setStatus(+ `Loaded ${name} · ${(bytes.byteLength / 1024).toFixed(1)} KB · validated`,+ true,+ );+ if (this.currentReport) this.els.signBtn.disabled = false;+ }++ _renderValidate(report) {+ const reportJSON = buildDownloadHref(report);+ this.els.validateOut.innerHTML = ValidatorReport({+ ...report,+ location,+ reportJSON,+ });+ }++ _renderInspect(inspect, suggestions) {+ const reportJSON = buildDownloadHref({ inspect, suggestions });+ this.els.inspectOut.innerHTML = InspectReport({ inspect, suggestions, reportJSON });+ }++ // ── Status display ──────────────────────────────────────────────────────++ _setStatus(msg, ok = false) {+ this.els.statusEl.textContent = msg;+ this.els.statusEl.className = `status${ok ? ' ok' : ''}`;+ }++ _setError(msg) {+ this.els.statusEl.textContent = msg;+ this.els.statusEl.className = 'status err';+ this.els.validateOut.innerHTML = '';+ this.els.inspectOut.innerHTML = '';+ }++ // ── Bridge to on-chain submit ───────────────────────────────────────────++ _handOffToDashboard() {+ if (!this.currentReport) {+ this.dashboard.showToast('Run a validation first', true);+ return;+ }+ // Switch to the Records tab and pre-load the modal with the in-memory+ // report, skipping the JSON file picker entirely.+ this.switchTab('records');+ this.dashboard.openModal();+ const report = this.currentReport;+ const hash = hashReport(report);+ this.dashboard.currentReport = report;+ this.dashboard.currentReportHash = hash;+ this.dashboard.els.fileStatus.textContent = `✓ In-memory report from ${this.currentName}`;+ this.dashboard.els.fileStatus.style.color = '#76d776';+ this.dashboard.els.previewJson.textContent = JSON.stringify(report, null, 2);+ this.dashboard.els.previewSection.style.display = 'block';+ this.dashboard.els.previewError.style.display = 'none';+ this.dashboard.els.reportHash.value = hash;+ this.dashboard.els.hashSection.style.display = 'block';+ this.dashboard.els.submitReportBtn.disabled = false;+ }+}++function buildDownloadHref(payload) {+ try {+ const json = JSON.stringify(payload, null, 2);+ return 'data:application/json;charset=utf-8,' + encodeURIComponent(json);+ } catch {+ return '';+ }+}++function escapeHtml(str) {+ return String(str).replace(/[&<>"']/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ })[c]);+}diff --git a/src/validator.js b/src/validator.jsindex 102577f78..7a2154bae 100644--- a/src/validator.js+++ b/src/validator.js@@ -44,6 +44,27 @@ export class Validator {.catch((e) => this.setReportException(e));}+ /**+ * Validate a raw byte buffer (no Three.js viewer dependency). Used by the+ * standalone /validation page where there's no GLTFLoader response to enrich+ * the report with `asset.extras` metadata.+ *+ * @param {ArrayBuffer | Uint8Array} buffer+ * @param {Object} [opts]+ * @param {Function} [opts.externalResourceFunction] resolves URIs in .gltf+ * @return {Promise<Object>} the processed report+ */+ async validateBuffer(buffer, opts = {}) {+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);+ const externalResourceFunction =+ opts.externalResourceFunction ||+ ((uri) => Promise.reject(new Error(`external resource not available: ${uri}`)));+ const report = await validateBytes(bytes, { externalResourceFunction });+ this._processReport(report);+ this.report = report;+ return this.report;+ }+/*** Loads a resource (either locally or from the network) and returns it.* @param {string} uri@@ -76,10 +97,13 @@ export class Validator {}/**+ * Decorate a raw glTF-Validator report with the derived shape consumed by+ * ValidatorReport / ValidatorToggle / ValidatorTable: maxSeverity, severity-+ * bucketed message arrays, and aggregation of repeated error codes.+ ** @param {GLTFValidator.Report} report- * @param {Object} response*/- setReport(report, response) {+ _processReport(report) {report.generator = (report && report.info && report.info.generator) || '';report.issues.maxSeverity = -1;SEVERITY_MAP.forEach((severity, index) => {@@ -91,48 +115,51 @@ export class Validator {report.warnings = report.issues.messages.filter((msg) => msg.severity === 1);report.infos = report.issues.messages.filter((msg) => msg.severity === 2);report.hints = report.issues.messages.filter((msg) => msg.severity === 3);- groupMessages(report);- this.report = report;-- this.setResponse(response);- function groupMessages(report) {- const CODES = {- ACCESSOR_NON_UNIT: {- message: '{count} accessor elements not of unit length: 0. [AGGREGATED]',- pointerCounts: {},- },- ACCESSOR_ANIMATION_INPUT_NON_INCREASING: {- message:- '{count} animation input accessor elements not in ascending order. [AGGREGATED]',- pointerCounts: {},- },- };-- report.errors.forEach((message) => {- if (!CODES[message.code]) return;- if (!CODES[message.code].pointerCounts[message.pointer]) {- CODES[message.code].pointerCounts[message.pointer] = 0;- }- CODES[message.code].pointerCounts[message.pointer]++;- });- report.errors = report.errors.filter((message) => {- if (!CODES[message.code]) return true;- if (!CODES[message.code].pointerCounts[message.pointer]) return true;- return CODES[message.code].pointerCounts[message.pointer] < 2;- });- Object.keys(CODES).forEach((code) => {- Object.keys(CODES[code].pointerCounts).forEach((pointer) => {- const count = CODES[code].pointerCounts[pointer];- if (count < 2) return;- report.errors.push({- code: code,- pointer: pointer,- message: CODES[code].message.replace('{count}', count),- });+ const CODES = {+ ACCESSOR_NON_UNIT: {+ message: '{count} accessor elements not of unit length: 0. [AGGREGATED]',+ pointerCounts: {},+ },+ ACCESSOR_ANIMATION_INPUT_NON_INCREASING: {+ message: '{count} animation input accessor elements not in ascending order. [AGGREGATED]',+ pointerCounts: {},+ },+ };++ report.errors.forEach((message) => {+ if (!CODES[message.code]) return;+ if (!CODES[message.code].pointerCounts[message.pointer]) {+ CODES[message.code].pointerCounts[message.pointer] = 0;+ }+ CODES[message.code].pointerCounts[message.pointer]++;+ });+ report.errors = report.errors.filter((message) => {+ if (!CODES[message.code]) return true;+ if (!CODES[message.code].pointerCounts[message.pointer]) return true;+ return CODES[message.code].pointerCounts[message.pointer] < 2;+ });+ Object.keys(CODES).forEach((code) => {+ Object.keys(CODES[code].pointerCounts).forEach((pointer) => {+ const count = CODES[code].pointerCounts[pointer];+ if (count < 2) return;+ report.errors.push({+ code: code,+ pointer: pointer,+ message: CODES[code].message.replace('{count}', count),});});- }+ });+ }++ /**+ * @param {GLTFValidator.Report} report+ * @param {Object} response+ */+ setReport(report, response) {+ this._processReport(report);+ this.report = report;+ this.setResponse(response);}/**diff --git a/tests/_fixtures/claude-artifact-csp.txt b/tests/_fixtures/claude-artifact-csp.txtnew file mode 100644index 000000000..91001de59--- /dev/null+++ b/tests/_fixtures/claude-artifact-csp.txt@@ -0,0 +1,13 @@+content-security-policy: default-src https://www.claudeusercontent.com;+ script-src 'unsafe-eval' 'unsafe-inline' https://www.claudeusercontent.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net/pyodide/;+ connect-src https://cdn.jsdelivr.net/pyodide/;+ worker-src https://www.claudeusercontent.com blob:;+ style-src 'unsafe-inline' https://www.claudeusercontent.com https://cdnjs.cloudflare.com https://fonts.googleapis.com;+ img-src blob: data: https://www.claudeusercontent.com;+ font-src data: https://www.claudeusercontent.com;+ object-src 'none';+ base-uri https://www.claudeusercontent.com;+ form-action https://www.claudeusercontent.com;+ frame-ancestors https://www.claudeusercontent.com https://claude.ai https://preview.claude.ai https://claude.site https://feedback.anthropic.com;+ upgrade-insecure-requests;+ block-all-mixed-contentdiff --git a/tests/api/all-modules-load.test.js b/tests/api/all-modules-load.test.jsnew file mode 100644index 000000000..e21eac7db--- /dev/null+++ b/tests/api/all-modules-load.test.js@@ -0,0 +1,54 @@+// Smoke test: every api routed-handler module must import cleanly.+//+// Catches broken import paths, wrong-stack imports, and placeholder code that+// throws on module init. If this fails on a file that is intentionally a stub,+// fix the stub or add it to SKIP_MODULES below with a clear reason.+import { describe, it, expect } from 'vitest';+import { readdirSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import { pathToFileURL } from 'node:url';++const API_DIR = join(process.cwd(), 'api');++// Files we know fail because they load env-gated infrastructure not present in the+// test sandbox (DB, RPC, keypair files). Add only with a clear reason; never to+// hide a real bug.+const SKIP_MODULES = new Set([+ // @nirholas/pump-sdk has an ESM exports map that vite's import-analysis+ // stage cannot resolve (works fine in plain node + vercel runtime).+ // Verified: `node -e "import('./api/pump/curve.js')"` succeeds.+ 'api/pump/curve.js',+ 'api/pump/quote-sdk.js',+]);++function* walk(dir) {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ const st = statSync(path);+ if (st.isDirectory()) {+ // Skip _lib, _id (helpers), and node_modules — those are imported by routed handlers,+ // so they get exercised transitively. We only enumerate routed surfaces here.+ if (name === '_lib' || name === '_id' || name === 'node_modules') continue;+ yield* walk(path);+ } else if (st.isFile() && name.endsWith('.js')) {+ yield path;+ }+ }+}++const files = [...walk(API_DIR)]+ .map((p) => relative(process.cwd(), p))+ .filter((rel) => !SKIP_MODULES.has(rel))+ .sort();++describe('every api/**/*.js handler loads', () => {+ for (const rel of files) {+ it(rel, async () => {+ const url = pathToFileURL(join(process.cwd(), rel)).href;+ const mod = await import(url);+ expect(mod).toBeTruthy();+ // Most Vercel handlers export `default`; some export named handlers (e.g. cron jobs).+ // We don't enforce shape — only that the module evaluates without throwing.+ });+ }+});diff --git a/tests/api/artifact.test.js b/tests/api/artifact.test.jsnew file mode 100644index 000000000..338990ef9--- /dev/null+++ b/tests/api/artifact.test.js@@ -0,0 +1,332 @@+// Contract test for /api/artifact. The artifact endpoint must produce HTML+// that survives Claude.ai's actual sandbox CSP — otherwise the artifact+// silently breaks when pasted into a Claude conversation. We pin against the+// real CSP scraped at github.com/simonw/scrape-claude-artifacts (vendored at+// tests/_fixtures/claude-artifact-csp.txt; refresh via+// `node scripts/refresh-claude-csp.mjs`).+//+// What "survive" means here: for every directive that controls fetchable+// resources (script-src, style-src, connect-src, img-src, font-src), every+// reference in our HTML must use a scheme/origin that the directive allows.+// Inline scripts/styles need 'unsafe-inline' (Claude's CSP grants both).++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const FIXTURE = resolve(__dirname, '../_fixtures/claude-artifact-csp.txt');+const BUNDLE = resolve(__dirname, '../../public/artifact-viewer.bundle.js');++vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { widgetRead: async () => ({ success: true }) },+ clientIp: () => '127.0.0.1',+}));++const sqlMock = vi.fn();+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++const getObjectBufferMock = vi.fn();+vi.mock('../../api/_lib/r2.js', () => ({+ getObjectBuffer: (...a) => getObjectBufferMock(...a),+}));++// A tiny but valid GLB. The test parses no actual geometry — we only need+// the byte stream to round-trip through base64 and into the HTML.+const FAKE_GLB = Buffer.from('glTF\x02\x00\x00\x00' + 'A'.repeat(1024));++function makeReq(qs) {+ return {+ url: '/api/artifact?' + qs,+ method: 'GET',+ headers: { 'x-forwarded-host': 'three.ws', 'x-forwarded-proto': 'https' },+ };+}+function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ writableEnded: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ this.writableEnded = true;+ },+ };+}++function parseCsp(raw) {+ const text = raw.replace(/^content-security-policy:\s*/i, '').replace(/\s+/g, ' ').trim();+ const out = {};+ for (const part of text.split(';')) {+ const trimmed = part.trim();+ if (!trimmed) continue;+ const [name, ...sources] = trimmed.split(/\s+/);+ out[name.toLowerCase()] = sources;+ }+ return out;+}++function loadClaudeCsp() {+ if (!existsSync(FIXTURE)) {+ throw new Error(`Missing CSP fixture at ${FIXTURE}`);+ }+ return parseCsp(readFileSync(FIXTURE, 'utf8'));+}++// Effective directive lookup: fall back to default-src per CSP spec.+function effective(csp, directive) {+ if (csp[directive]) return csp[directive];+ if (csp['default-src']) return csp['default-src'];+ return ['*'];+}++function urlAllowedBy(rawUrl, sources) {+ if (sources.includes('*')) return true;++ for (const src of sources) {+ // Scheme sources: data:, blob:, https:+ if (src.endsWith(':')) {+ if (rawUrl.startsWith(src)) return true;+ continue;+ }+ if (src === "'self'") continue; // 'self' is the document origin — claudeusercontent.com — so external URLs aren't 'self'+ if (src.startsWith("'")) continue; // 'unsafe-inline', 'unsafe-eval', 'none' don't gate URLs+ // Origin/path sources: e.g. https://cdnjs.cloudflare.com or https://cdn.jsdelivr.net/pyodide/+ try {+ const allowed = new URL(src);+ const target = new URL(rawUrl, 'https://www.claudeusercontent.com/');+ const originMatch = target.protocol === allowed.protocol && target.host === allowed.host;+ if (!originMatch) continue;+ if (allowed.pathname && allowed.pathname !== '/') {+ if (target.pathname.startsWith(allowed.pathname)) return true;+ } else {+ return true;+ }+ } catch {+ // not a URL; ignore+ }+ }+ return false;+}++// Pull every URL-shaped string out of HTML attributes and inline JS we care about.+function extractExternalUrls(html) {+ const urls = [];+ const hits = html.matchAll(/(?:src|href)=["']([^"']+)["']/gi);+ for (const m of hits) {+ const u = m[1];+ if (!/^https?:\/\//i.test(u)) continue;+ urls.push({ url: u, kind: 'attr' });+ }+ return urls;+}++let handler;++beforeEach(async () => {+ vi.resetModules();+ sqlMock.mockReset();+ getObjectBufferMock.mockReset();+ const mod = await import('../../api/artifact.js');+ handler = mod.default;+});++describe('/api/artifact contract', () => {+ it('viewer bundle exists (run `npm run build:artifact-viewer` if this fails)', () => {+ expect(existsSync(BUNDLE)).toBe(true);+ });++ it('vendored Claude CSP fixture parses with the directives we depend on', () => {+ const csp = loadClaudeCsp();+ expect(csp['script-src']).toContain("'unsafe-inline'");+ expect(csp['style-src']).toContain("'unsafe-inline'");+ expect(csp['img-src']).toContain('data:');+ expect(csp['img-src']).toContain('blob:');+ expect(csp['object-src']).toContain("'none'");+ });++ describe('?agent=<id>', () => {+ it('returns 404 when agent missing', async () => {+ sqlMock.mockResolvedValueOnce([]);+ const res = makeRes();+ await handler(makeReq('agent=missing-agent-id-1234'), res);+ expect(res.statusCode).toBe(404);+ });++ it('returns 422 when agent has no avatar', async () => {+ sqlMock.mockResolvedValueOnce([{ id: 'a1', name: 'Test', storage_key: null }]);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ expect(res.statusCode).toBe(422);+ });++ it('returns 400 for malformed agent id', async () => {+ const res = makeRes();+ await handler(makeReq('agent=' + encodeURIComponent('not legal!')), res);+ expect(res.statusCode).toBe(400);+ });++ it('returns 200 self-contained HTML for a valid agent', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Aurora', storage_key: 'u/123/aurora.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toMatch(/text\/html/);+ expect(res._body).toContain('<html');+ expect(res._body).toContain('artifact-config');+ expect(res._body).toContain('artifact-stage');+ });++ it('embeds the GLB as base64 in the config script tag', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Aurora', storage_key: 'u/123/aurora.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ const m = res._body.match(/id="artifact-config">([^<]+)</);+ expect(m).not.toBeNull();+ const cfg = JSON.parse(m[1]);+ expect(cfg.glb).toBe(FAKE_GLB.toString('base64'));+ expect(cfg.name).toBe('Aurora');+ });++ it('rejects oversized GLB (>6 MB)', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Big', storage_key: 'u/big.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(Buffer.alloc(7 * 1024 * 1024));+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ expect(res.statusCode).toBe(413);+ });++ it('escapes name to prevent HTML injection', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: '<script>alert(1)</script>', storage_key: 'u/x.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ expect(res._body).not.toMatch(/<script>alert\(1\)<\/script>/);+ expect(res._body).toContain('<script>');+ });+ });++ describe('input validation', () => {+ it('400s when neither agent nor model is provided', async () => {+ const res = makeRes();+ await handler(makeReq(''), res);+ expect(res.statusCode).toBe(400);+ });++ it('400s when both agent and model are provided', async () => {+ const res = makeRes();+ await handler(+ makeReq('agent=a1234&model=https://three.ws/x.glb'),+ res,+ );+ expect(res.statusCode).toBe(400);+ });++ it('400s for non-whitelisted model origin', async () => {+ const res = makeRes();+ await handler(makeReq('model=' + encodeURIComponent('https://evil.com/x.glb')), res);+ expect(res.statusCode).toBe(400);+ });++ it('rejects non-GET/HEAD', async () => {+ const res = makeRes();+ await handler({ ...makeReq('agent=a1234'), method: 'POST' }, res);+ expect(res.statusCode).toBe(405);+ });+ });++ describe('CSP compliance vs Claude.ai sandbox', () => {+ // Generate one valid response to inspect.+ async function generate() {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Aurora', storage_key: 'u/123/aurora.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ return res;+ }++ it("contains no <script src=> — only inline scripts (Claude allows 'unsafe-inline')", async () => {+ const res = await generate();+ const externalScripts = res._body.match(/<script[^>]*\bsrc=/gi);+ expect(externalScripts).toBeNull();+ });++ it('contains no <link rel="stylesheet"> — only inline styles', async () => {+ const res = await generate();+ expect(res._body).not.toMatch(/<link[^>]+rel=["']stylesheet["']/i);+ });++ it('contains no external https:// URLs in src/href attributes', async () => {+ const res = await generate();+ const externals = extractExternalUrls(res._body);+ expect(externals).toEqual([]);+ });++ it('every script-src reference is allowed by Claude\'s real script-src', async () => {+ const res = await generate();+ const csp = loadClaudeCsp();+ const allowed = effective(csp, 'script-src');+ const scriptSrcs = [...res._body.matchAll(/<script[^>]*\bsrc=["']([^"']+)["']/gi)].map(+ (m) => m[1],+ );+ for (const src of scriptSrcs) {+ expect(urlAllowedBy(src, allowed), `script src ${src} blocked by ${allowed}`).toBe(true);+ }+ });++ it('our response CSP allows itself (we serve a CSP that mirrors Claude\'s)', async () => {+ const res = await generate();+ const ourCsp = parseCsp(res.getHeader('content-security-policy'));+ expect(effective(ourCsp, 'script-src')).toContain("'unsafe-inline'");+ expect(effective(ourCsp, 'style-src')).toContain("'unsafe-inline'");+ expect(effective(ourCsp, 'img-src')).toEqual(expect.arrayContaining(['data:', 'blob:']));+ expect(effective(ourCsp, 'object-src')).toContain("'none'");+ expect(ourCsp['frame-ancestors']).toContain('*');+ });+ });++ describe('headers', () => {+ it('sets cache-control with stale-while-revalidate', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Aurora', storage_key: 'u/123/aurora.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler(makeReq('agent=a1234'), res);+ expect(res.getHeader('cache-control')).toMatch(/stale-while-revalidate/);+ });++ it('HEAD returns no body', async () => {+ sqlMock.mockResolvedValueOnce([+ { id: 'a1', name: 'Aurora', storage_key: 'u/123/aurora.glb' },+ ]);+ getObjectBufferMock.mockResolvedValueOnce(FAKE_GLB);+ const res = makeRes();+ await handler({ ...makeReq('agent=a1234'), method: 'HEAD' }, res);+ expect(res.statusCode).toBe(200);+ expect(res._body).toBeUndefined();+ expect(res.getHeader('content-length')).toBeDefined();+ });+ });+});diff --git a/tests/src/eth-vanity-validation.test.js b/tests/src/eth-vanity-validation.test.jsnew file mode 100644index 000000000..56ef15e08--- /dev/null+++ b/tests/src/eth-vanity-validation.test.js@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest';+import {+ validatePattern,+ validateAddress,+ validateInitCodeHash,+ estimateAttempts,+ letterCount,+ eip55Checksum,+ MAX_PATTERN_LENGTH,+} from '../../src/eth/vanity/validation.js';++describe('eth vanity · validatePattern', () => {+ it('accepts plain hex', () => {+ const v = validatePattern('beef');+ expect(v.valid).toBe(true);+ expect(v.normalized).toBe('beef');+ expect(v.caseSensitive).toBe(false);+ });++ it('strips a leading 0x', () => {+ expect(validatePattern('0xdead').normalized).toBe('dead');+ expect(validatePattern('0XDeAd').normalized).toBe('DeAd');+ });++ it('detects mixed-case as case-sensitive (EIP-55 mode)', () => {+ const v = validatePattern('Beef');+ expect(v.valid).toBe(true);+ expect(v.caseSensitive).toBe(true);+ expect(v.normalized).toBe('Beef'); // preserved+ });++ it('rejects non-hex characters', () => {+ expect(validatePattern('beeg').valid).toBe(false);+ expect(validatePattern('xyz').valid).toBe(false);+ });++ it('rejects empty', () => {+ expect(validatePattern('').valid).toBe(false);+ });++ it('rejects patterns over the maximum length', () => {+ const v = validatePattern('f'.repeat(MAX_PATTERN_LENGTH + 1));+ expect(v.valid).toBe(false);+ });+});++describe('eth vanity · validateAddress', () => {+ it('accepts a 40-char hex with or without 0x', () => {+ expect(validateAddress('0x' + 'a'.repeat(40)).valid).toBe(true);+ expect(validateAddress('a'.repeat(40)).valid).toBe(true);+ });+ it('rejects wrong length', () => {+ expect(validateAddress('0x' + 'a'.repeat(39)).valid).toBe(false);+ expect(validateAddress('0x' + 'a'.repeat(41)).valid).toBe(false);+ });+ it('lowercases on normalize', () => {+ const v = validateAddress('0x' + 'ABCDEF'.padEnd(40, '0'));+ expect(v.normalized).toBe('0x' + 'abcdef'.padEnd(40, '0'));+ });+});++describe('eth vanity · validateInitCodeHash', () => {+ it('accepts 64 hex chars', () => {+ expect(validateInitCodeHash('0x' + '1'.repeat(64)).valid).toBe(true);+ });+ it('rejects wrong length', () => {+ expect(validateInitCodeHash('0x' + '1'.repeat(63)).valid).toBe(false);+ });+});++describe('eth vanity · estimateAttempts', () => {+ it('is 16^length when case-insensitive', () => {+ expect(estimateAttempts(4)).toBe(65536);+ });+ it('multiplies by 2^letterCount when case-sensitive', () => {+ // "Beef" — 3 letters → 16^4 * 2^3 = 524288+ expect(estimateAttempts(4, 3, true)).toBe(65536 * 8);+ });+ it('digits don\'t pay the casing tax', () => {+ // "B0ef" — 3 letters → 16^4 * 2^3+ expect(estimateAttempts(4, 3, true)).toBe(65536 * 8);+ });+});++describe('eth vanity · letterCount', () => {+ it('counts a-f and A-F', () => {+ expect(letterCount('beef')).toBe(4);+ expect(letterCount('Beef')).toBe(4);+ expect(letterCount('1337')).toBe(0);+ expect(letterCount('B0ef')).toBe(3);+ });+});++describe('eth vanity · eip55Checksum', () => {+ // Reference vectors from EIP-55 (https://eips.ethereum.org/EIPS/eip-55).+ // All lowercase input → expected mixed-case output.+ const VECTORS = [+ // Ethereum Foundation+ ['52908400098527886e0f7030069857d2e4169ee7', '52908400098527886E0F7030069857D2E4169EE7'],+ ['8617e340b3d01fa5f11f306f4090fd50e238070d', '8617E340B3D01FA5F11F306F4090FD50E238070D'],+ // Mixed+ ['de709f2102306220921060314715629080e2fb77', 'de709f2102306220921060314715629080e2fb77'],+ ['fb6916095ca1df60bb79ce92ce3ea74c37c5d359', 'fB6916095ca1df60bB79Ce92cE3Ea74c37c5d359'],+ ['dbf03b407c01e7cd3cbea99509d93f8dddc8c6fb', 'DBF03B407c01E7cD3CBea99509d93f8DDDC8C6FB'],+ ['d1220a0cf47c7b9be7a2e6ba89f429762e7b9adb', 'D1220A0cf47C7B9Be7A2E6BA89F429762e7b9aDb'],+ ];++ for (const [lower, expected] of VECTORS) {+ it(`matches reference vector for ${lower.slice(0, 8)}…`, () => {+ expect(eip55Checksum(lower)).toBe(expected);+ });+ }+});diff --git a/tests/validation-smoke.mjs b/tests/validation-smoke.mjsnew file mode 100644index 000000000..5ea4e243c--- /dev/null+++ b/tests/validation-smoke.mjs@@ -0,0 +1,113 @@+// Smoke test for /validation. Loads the page in a headless browser, clicks+// the Box sample chip, waits for the Khronos validator + glTF-Transform+// inspector to finish, and asserts that both reports rendered.++import { chromium } from 'playwright';++const URL = process.env.URL || 'http://localhost:3003/validation/';+const browser = await chromium.launch();+const ctx = await browser.newContext();+const page = await ctx.newPage();++const consoleErrors = [];+page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(msg.text());+});+page.on('pageerror', (err) => consoleErrors.push('pageerror: ' + err.message));++await page.goto(URL, { waitUntil: 'networkidle' });++// Tabs visible?+await page.waitForSelector('.tab[data-tab="validate"]');+await page.waitForSelector('.sample-chip');++// Click the first sample (Box).+await page.click('.sample-chip[data-name="Box"]');++// Wait for the Validate panel to render the report banner OR an error.+await page.waitForFunction(+ () => {+ const out = document.getElementById('validate-output');+ return out && (out.querySelector('.report-banner') || out.querySelector('.err'));+ },+ { timeout: 30000 },+);++const validateText = await page.locator('#validate-output').innerText();+const inspectText = await page.locator('#inspect-output').innerText();++// Switch to inspect tab and check it rendered too.+await page.click('.tab[data-tab="inspect"]');+await page.waitForFunction(+ () => {+ const out = document.getElementById('inspect-output');+ return out && (out.querySelector('.inspect-grid') || out.querySelector('.err'));+ },+ { timeout: 15000 },+);+const inspectVisibleText = await page.locator('#inspect-output').innerText();+const inspectCardCount = await page.locator('.inspect-card').count();++// On-chain bridge — Sign button should now be enabled. Clicking it must+// switch to Records tab AND open the submit modal pre-filled.+await page.click('.tab[data-tab="validate"]');+const signEnabled = !(await page.locator('#sign-btn').isDisabled());+await page.click('#sign-btn');+const modalOpen = await page.locator('#submit-modal.open').count() > 0;+const modalReportHash = await page.locator('#report-hash').inputValue();+await page.locator('button.sec', { hasText: 'Cancel' }).click();++// Records tab → ensure the existing dashboard still mounts.+await page.click('.tab[data-tab="records"]');+const recordsToolbar = await page.locator('.records-toolbar').isVisible();++const status = await page.locator('#status').innerText();++console.log('— Status:', status.trim());+console.log('— Validate panel preview:', validateText.slice(0, 200).replace(/\s+/g, ' '));+console.log('— Inspect panel preview:', inspectVisibleText.slice(0, 200).replace(/\s+/g, ' '));+console.log('— Inspect card count:', inspectCardCount);+console.log('— Sign button enabled after run:', signEnabled);+console.log('— Modal opened on bridge click:', modalOpen);+console.log('— Modal report hash:', modalReportHash.slice(0, 18) + (modalReportHash ? '…' : ''));+console.log('— Records toolbar visible:', recordsToolbar);+console.log('— Console errors:', consoleErrors.length);+if (consoleErrors.length) {+ console.log(consoleErrors.map((e) => ' · ' + e).join('\n'));+}++const failures = [];+if (!validateText.includes('Validation report') && !validateText.includes('All clear') && !validateText.includes('Found')) {+ failures.push('Validate output does not contain expected report banner');+}+if (!inspectVisibleText.includes('Performance inspector')) {+ failures.push('Inspect output does not contain "Performance inspector"');+}+if (inspectCardCount < 6) {+ failures.push(`Expected ≥6 inspect cards, got ${inspectCardCount}`);+}+if (!signEnabled) {+ failures.push('Sign & pin button did not enable after a successful validation');+}+if (!modalOpen) {+ failures.push('On-chain bridge did not open the submit modal');+}+if (!/^0x[0-9a-f]{64}$/i.test(modalReportHash)) {+ failures.push(`Bridge did not pre-fill a valid keccak256 hash (got "${modalReportHash}")`);+}+if (!recordsToolbar) {+ failures.push('Records tab toolbar is not visible');+}+// Filter out network-noise console errors that are unrelated (devtools-ws, etc.)+const realErrors = consoleErrors.filter(+ (e) => !/Failed to load resource: net::ERR_FAILED/i.test(e) && !/favicon/i.test(e),+);+if (realErrors.length) failures.push(`Page console errors: ${realErrors.length}`);++await browser.close();++if (failures.length) {+ console.error('\nFAIL:\n' + failures.map((f) => ' ✗ ' + f).join('\n'));+ process.exit(1);+}+console.log('\nOK — validate + inspect + records tabs all functional.');diff --git a/vercel.json b/vercel.jsonindex befd57412..d56a14fbe 100644--- a/vercel.json+++ b/vercel.json@@ -846,6 +846,10 @@"src": "/pay/","dest": "/pay/index.html"},+ {+ "src": "/pay/calls/[1-9A-HJ-NP-Za-km-z]+",+ "dest": "/pay/calls/index.html"+ },{"src": "/pay/(.*)","dest": "/pay/$1"diff --git a/vite.config.js b/vite.config.jsindex c6587ce6e..544025bf3 100644--- a/vite.config.js+++ b/vite.config.js@@ -111,6 +111,7 @@ const appConfig = {'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),pay: resolve(__dirname, 'public/pay/index.html'),+ 'pay-calls': resolve(__dirname, 'public/pay/calls/index.html'),},},},@@ -150,6 +151,8 @@ const appConfig = {'/marketplace/': resolve(root, 'marketplace.html'),'/pay': resolve(root, 'public/pay/index.html'),'/pay/': resolve(root, 'public/pay/index.html'),+ '/pay/calls': resolve(root, 'public/pay/calls/index.html'),+ '/pay/calls/': resolve(root, 'public/pay/calls/index.html'),'/explore': resolve(root, 'public/discover/index.html'),'/explore/': resolve(root, 'public/discover/index.html'),// END:DISCOVER_ROUTE@@ -224,6 +227,9 @@ const appConfig = {// /a/<chainId>/<agentId> or /a/<chainId>/<registry>/<agentId>else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/?$/.test(path))filePath = resolve(root, 'app.html');+ // /pay/calls/<base58 tx sig> → permalink for a paid x402 call+ else if (!filePath && /^\/pay\/calls\/[1-9A-HJ-NP-Za-km-z]+\/?$/.test(path))+ filePath = resolve(root, 'public/pay/calls/index.html');// Serve the rider webpack app as static files.if (path === '/rider' || path === '/rider/') {const html = readFileSync(resolve(root, 'rider/index.html'), 'utf8');