From 3f3200634123e7e9974c133d516f2bafb94f64ae Mon Sep 17 00:00:00 2001 From: JianFeeeee Date: Sun, 16 Aug 2026 08:17:34 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20=E4=BF=AE=E5=A4=8D=E6=80=BB=E7=BD=91?= =?UTF-8?q?=E5=85=B3=E8=AE=A4=E8=AF=81(host=E5=9F=9Fcookie=E6=B3=A8?= =?UTF-8?q?=E5=85=A5+session.fetch=E7=99=BB=E5=BD=95+sl-session=E5=90=88?= =?UTF-8?q?=E5=B9=B6)=20&=20=E8=BF=9E=E6=8E=A5=E6=8C=81=E4=B9=85=E5=8C=96?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=E5=AD=97=E6=AE=B5+=E7=BD=91=E5=85=B3?= =?UTF-8?q?=E5=BE=BD=E6=A0=87;=20vendor=20=E6=9C=AC=E5=9C=B0=20three.js=20?= =?UTF-8?q?=E5=A4=87=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/gui/main.js | 698 ++-- cmd/gui/package.json | 4 +- cmd/gui/renderer/app.js | 4536 +++++++++++++++++++------- cmd/gui/renderer/index.html | 1 + cmd/gui/renderer/style.css | 1884 +++++++++-- cmd/gui/renderer/vendor/three.min.js | 6 + 6 files changed, 5371 insertions(+), 1758 deletions(-) create mode 100644 cmd/gui/renderer/vendor/three.min.js diff --git a/cmd/gui/main.js b/cmd/gui/main.js index 19ea320..022ec9b 100644 --- a/cmd/gui/main.js +++ b/cmd/gui/main.js @@ -1,98 +1,226 @@ -const { app, BrowserWindow, ipcMain, dialog, Menu } = require('electron'); -const path = require('path'); -const fs = require('fs'); -const { spawn } = require('child_process'); -const http = require('http'); -const crypto = require('crypto'); -const { pathToFileURL } = require('url'); +const { app, BrowserWindow, ipcMain, dialog, Menu } = require("electron"); +const path = require("path"); +const fs = require("fs"); +const { spawn } = require("child_process"); +const http = require("http"); +const crypto = require("crypto"); +const { pathToFileURL } = require("url"); -const CONNECTIONS_FILE = path.join(app.getPath('userData'), 'connections.json'); -const LOG_FILE = path.join(app.getPath('userData'), 'gui.log'); +const CONNECTIONS_FILE = path.join(app.getPath("userData"), "connections.json"); +const LOG_FILE = path.join(app.getPath("userData"), "gui.log"); function log(msg) { - try { fs.appendFileSync(LOG_FILE, new Date().toISOString() + ' ' + msg + '\n'); } catch (e) {} + try { + fs.appendFileSync(LOG_FILE, new Date().toISOString() + " " + msg + "\n"); + } catch (e) {} } -const _consoleLog = console.log, _consoleErr = console.error; -console.log = function () { log(Array.prototype.slice.call(arguments).join(' ')); _consoleLog.apply(null, arguments); }; -console.error = function () { log('ERR ' + Array.prototype.slice.call(arguments).join(' ')); _consoleErr.apply(null, arguments); }; +const _consoleLog = console.log, + _consoleErr = console.error; +console.log = function () { + log(Array.prototype.slice.call(arguments).join(" ")); + _consoleLog.apply(null, arguments); +}; +console.error = function () { + log("ERR " + Array.prototype.slice.call(arguments).join(" ")); + _consoleErr.apply(null, arguments); +}; let homedProcess = null; let mainWindow; let authRule = null; function installAuthRule() { - const { session } = require('electron'); + const { session } = require("electron"); session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => { const h = Object.assign({}, details.requestHeaders); - if (authRule && details.url.indexOf(authRule.url) === 0) { + // 按目标 host 校验作用域:网关会把请求 302 到 login.* 域,若按 url 前缀匹配, + // 登录域自身请求会被错误附加本站 cookie。 + const hu = (() => { + try { + return new URL(details.url); + } catch (e) { + return null; + } + })(); + if (authRule && hu && authRule.hosts && authRule.hosts.has(hu.hostname)) { if (authRule.headers) { Object.keys(authRule.headers).forEach((k) => { h[k] = authRule.headers[k]; }); } - if (authRule.cookie) { - h['Cookie'] = (h['Cookie'] ? h['Cookie'] + '; ' : '') + authRule.cookie; + // Electron 会自动附带 jar 中 Cookie(含外部网关 Set-Cookie 的 sl-session)。 + // 这里再显式合并持久化 cookie 与 sl-session 兜底,避免网关再 302。 + const extra = [authRule.cookie, authRule.slSession].filter(Boolean); + if (extra.length) { + const existing = h["Cookie"] || ""; + h["Cookie"] = [existing].concat(extra).filter(Boolean).join("; "); } } callback({ requestHeaders: h }); }); session.defaultSession.webRequest.onHeadersReceived((details, callback) => { const h = Object.assign({}, details.responseHeaders || {}); - if (details.method === 'OPTIONS' || (authRule && details.url.indexOf(authRule.url) === 0)) { - h['Access-Control-Allow-Origin'] = ['*']; - h['Access-Control-Allow-Methods'] = ['GET,POST,PUT,DELETE,OPTIONS']; - h['Access-Control-Allow-Headers'] = ['Content-Type, X-API-Key, Authorization, Cookie']; - h['Access-Control-Max-Age'] = ['86400']; + const inScope = (() => { + if (details.method === "OPTIONS") return true; + if (!authRule || !authRule.urlHost) return false; + try { + return new URL(details.url).hostname === authRule.urlHost; + } catch (e) { + return false; + } + })(); + if (inScope) { + h["Access-Control-Allow-Origin"] = ["*"]; + h["Access-Control-Allow-Methods"] = ["GET,POST,PUT,DELETE,OPTIONS"]; + h["Access-Control-Allow-Headers"] = [ + "Content-Type, X-API-Key, Authorization, Cookie", + ]; + h["Access-Control-Max-Age"] = ["86400"]; } - if (details.method === 'OPTIONS') { - callback({ responseHeaders: h, statusLine: 'HTTP/1.1 200 OK' }); + if (details.method === "OPTIONS") { + callback({ responseHeaders: h, statusLine: "HTTP/1.1 200 OK" }); return; } callback({ responseHeaders: h }); }); session.defaultSession.webRequest.onCompleted((details) => { - if (authRule && details.url.indexOf(authRule.url) === 0 && details.url.indexOf('/api/') !== -1) { - log('[req] ' + details.method + ' ' + details.statusCode + ' ' + details.url.slice(0, 120)); + if (!authRule || !authRule.urlHost) return; + try { + if (new URL(details.url).hostname !== authRule.urlHost) return; + } catch (e) { + return; + } + if (details.url.indexOf("/api/") !== -1) { + log( + "[req] " + + details.method + + " " + + details.statusCode + + " " + + details.url.slice(0, 120), + ); } }); session.defaultSession.webRequest.onErrorOccurred((details) => { - if (authRule && details.url.indexOf(authRule.url) === 0) { - log('[req-err] ' + details.method + ' ' + details.error + ' ' + details.url.slice(0, 120)); + if (!authRule || !authRule.urlHost) return; + try { + if (new URL(details.url).hostname !== authRule.urlHost) return; + } catch (e) { + return; } + log( + "[req-err] " + + details.method + + " " + + details.error + + " " + + details.url.slice(0, 120), + ); }); } +// 组装 authRule(url + 持久化 cookie + 显式 sl-session),并缓存 hosts 集合。 +// 供 installAuthRule 按目标 host 做作用域匹配:jsdom 前缀匹配有误伤,host 级最稳。 +async function applyAuthRule(url, cookie, headers) { + if (!url) { + authRule = null; + return; + } + let hosts; + let urlHost = ""; + try { + const h = new URL(url).hostname; + urlHost = h; + hosts = new Set([h]); + } catch (e) { + hosts = new Set(); + } + authRule = { + url, + urlHost, + hosts, + cookie: cookie || "", + headers: headers || {}, + }; + // 显式的 sl-session 从 cookie jar 里取(网关 Set-Cookie 且 HttpOnly) + authRule.slSession = await adoptSlSession(url); +} + +// 从 Electron cookie jar 中取出目标 host 的 sl-session(若存在)。 +async function adoptSlSession(url) { + try { + const { session } = require("electron"); + const hostname = new URL(url).hostname; + const all = await session.defaultSession.cookies.get({}); + const hit = (all || []).find( + (c) => + c.name === "sl-session" && + (c.domain || "").replace(/^\./, "") === hostname, + ); + return hit ? "sl-session=" + hit.value : ""; + } catch (e) { + return ""; + } +} + +// 带 Electron cookie jar 的 fetch(跟随外部网关 302 → login 域 → 回跳,最多 6 跳), +// 使 POST /api/v1/login 真正触达内层 HomeAgent 并取回 homeagent_session。 +async function sessionFetch(initUrl, opts) { + const { session } = require("electron"); + let url = initUrl; + let resp; + for (let i = 0; i < 6; i++) { + resp = await session.defaultSession.fetch(url, opts); + if ( + resp.status >= 300 && + resp.status < 400 && + resp.headers.get("location") + ) { + url = new URL(resp.headers.get("location"), url).toString(); + continue; + } + return resp; + } + return resp; +} + function loadConnections() { try { if (fs.existsSync(CONNECTIONS_FILE)) { - const raw = fs.readFileSync(CONNECTIONS_FILE, 'utf-8').replace(/^\uFEFF/, ''); + const raw = fs + .readFileSync(CONNECTIONS_FILE, "utf-8") + .replace(/^\uFEFF/, ""); const data = JSON.parse(raw); normalizeConnections(data); return data; } } catch (e) { - console.error('Failed to load connections:', e); + console.error("Failed to load connections:", e); // 配置损坏:备份后重建,避免应用一直处于"无连接"状态 try { - const backup = CONNECTIONS_FILE + '.bak'; + const backup = CONNECTIONS_FILE + ".bak"; fs.copyFileSync(CONNECTIONS_FILE, backup); - fs.writeFileSync(CONNECTIONS_FILE, '{"connections":[],"currentId":null}', 'utf-8'); - console.error('Backed up corrupt connections to', backup); + fs.writeFileSync( + CONNECTIONS_FILE, + '{"connections":[],"currentId":null}', + "utf-8", + ); + console.error("Backed up corrupt connections to", backup); } catch (e2) { - console.error('Failed to recover connections file:', e2); + console.error("Failed to recover connections file:", e2); } } // Fallback: check app resource dir (installer writes fallback copy there) try { - const fallback = path.join(__dirname, 'connections.json'); + const fallback = path.join(__dirname, "connections.json"); if (fs.existsSync(fallback)) { - const data = JSON.parse(fs.readFileSync(fallback, 'utf-8')); + const data = JSON.parse(fs.readFileSync(fallback, "utf-8")); normalizeConnections(data); saveConnections(data); - console.log('Imported connections from app resource dir'); + console.log("Imported connections from app resource dir"); return data; } } catch (e) { - console.error('Fallback connections load failed:', e); + console.error("Fallback connections load failed:", e); } return { connections: [], currentId: null }; } @@ -101,31 +229,34 @@ function loadConnections() { function normalizeConnections(data) { if (!data || !Array.isArray(data.connections)) return; data.connections.forEach((c) => { - if (!c.type) c.type = 'webui'; - if (c.type !== 'cli' && c.type !== 'webui') c.type = 'webui'; + if (!c.type) c.type = "webui"; + if (c.type !== "cli" && c.type !== "webui") c.type = "webui"; }); } function saveConnections(data) { try { - fs.writeFileSync(CONNECTIONS_FILE, JSON.stringify(data, null, 2), 'utf-8'); + fs.writeFileSync(CONNECTIONS_FILE, JSON.stringify(data, null, 2), "utf-8"); } catch (e) { - console.error('Failed to save connections:', e); + console.error("Failed to save connections:", e); } } function findHomed() { - if (process.platform !== 'win32') return null; - const exeDir = path.dirname(app.getPath('exe')); - const p = path.resolve(exeDir, '..', 'homed.exe'); + if (process.platform !== "win32") return null; + const exeDir = path.dirname(app.getPath("exe")); + const p = path.resolve(exeDir, "..", "homed.exe"); return fs.existsSync(p) ? p : null; } function isServerRunning() { return new Promise((resolve) => { - const req = http.get('http://localhost:8080/', () => resolve(true)); - req.on('error', () => resolve(false)); - req.setTimeout(2000, () => { req.destroy(); resolve(false); }); + const req = http.get("http://localhost:8080/", () => resolve(true)); + req.on("error", () => resolve(false)); + req.setTimeout(2000, () => { + req.destroy(); + resolve(false); + }); }); } @@ -146,22 +277,22 @@ function waitForServer(maxWait = 8000) { function startHomed() { const homedBin = findHomed(); if (!homedBin) { - console.log('homed.exe not found near GUI, skipping auto-launch'); + console.log("homed.exe not found near GUI, skipping auto-launch"); return; } - const dataDir = path.resolve(path.dirname(homedBin), 'data'); - console.log('Starting homed:', homedBin, '-data', dataDir); - homedProcess = spawn(homedBin, ['-data', dataDir], { - stdio: 'ignore', + const dataDir = path.resolve(path.dirname(homedBin), "data"); + console.log("Starting homed:", homedBin, "-data", dataDir); + homedProcess = spawn(homedBin, ["-data", dataDir], { + stdio: "ignore", detached: false, windowsHide: true, }); - homedProcess.on('error', (err) => { - console.error('homed start failed:', err.message); + homedProcess.on("error", (err) => { + console.error("homed start failed:", err.message); homedProcess = null; }); - homedProcess.on('exit', (code) => { - console.log('homed exited with code', code); + homedProcess.on("exit", (code) => { + console.log("homed exited with code", code); homedProcess = null; }); } @@ -182,62 +313,69 @@ function createWindow() { height: 860, minWidth: 900, minHeight: 600, - title: 'HomeAgent', + title: "HomeAgent", frame: false, - icon: path.join(__dirname, 'icon.ico'), + icon: path.join(__dirname, "icon.ico"), webPreferences: { - preload: path.join(__dirname, 'preload.js'), + preload: path.join(__dirname, "preload.js"), contextIsolation: true, nodeIntegration: false, }, }); - mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html')); + mainWindow.loadFile(path.join(__dirname, "renderer", "index.html")); - if (process.argv.includes('--dev')) { + if (process.argv.includes("--dev")) { mainWindow.webContents.openDevTools(); } - mainWindow.on('closed', () => { + mainWindow.on("closed", () => { mainWindow = null; }); } -ipcMain.handle('window:minimize', (e) => { +ipcMain.handle("window:minimize", (e) => { BrowserWindow.fromWebContents(e.sender)?.minimize(); }); -ipcMain.handle('window:toggleMaximize', (e) => { +ipcMain.handle("window:toggleMaximize", (e) => { const win = BrowserWindow.fromWebContents(e.sender); if (!win) return; - if (win.isMaximized()) win.unmaximize(); else win.maximize(); + if (win.isMaximized()) win.unmaximize(); + else win.maximize(); }); -ipcMain.handle('window:close', (e) => { +ipcMain.handle("window:close", (e) => { BrowserWindow.fromWebContents(e.sender)?.close(); }); -ipcMain.handle('connections:list', () => { +ipcMain.handle("connections:list", () => { return loadConnections(); }); -ipcMain.handle('connections:add', (_, conn) => { +ipcMain.handle("connections:add", (_, conn) => { const data = loadConnections(); const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6); data.connections.push({ id, - name: conn.name, - url: conn.url || '', - apiKey: conn.apiKey || '', - type: conn.type === 'cli' ? 'cli' : 'webui', - socketPath: conn.socketPath || '', + name: conn.name || "", + url: conn.url || "", + apiKey: conn.apiKey || "", + type: conn.type === "cli" ? "cli" : "webui", + socketPath: conn.socketPath || "", + // 网关认证字段在 add 时必须一并持久化,否则新增连接后 cookie/网关标记丢失 + username: conn.username || "", + password: conn.password || "", + cookie: conn.cookie || "", + headers: conn.headers || "", + gateway: !!conn.gateway, }); if (!data.currentId) data.currentId = id; saveConnections(data); return data; }); -ipcMain.handle('connections:update', (_, { id, updates }) => { +ipcMain.handle("connections:update", (_, { id, updates }) => { const data = loadConnections(); - const idx = data.connections.findIndex(c => c.id === id); + const idx = data.connections.findIndex((c) => c.id === id); if (idx !== -1) { data.connections[idx] = { ...data.connections[idx], ...updates }; saveConnections(data); @@ -245,11 +383,12 @@ ipcMain.handle('connections:update', (_, { id, updates }) => { return data; }); -ipcMain.handle('connections:delete', (_, id) => { +ipcMain.handle("connections:delete", (_, id) => { const data = loadConnections(); - data.connections = data.connections.filter(c => c.id !== id); + data.connections = data.connections.filter((c) => c.id !== id); if (data.currentId === id) { - data.currentId = data.connections.length > 0 ? data.connections[0].id : null; + data.currentId = + data.connections.length > 0 ? data.connections[0].id : null; } saveConnections(data); return data; @@ -257,51 +396,82 @@ ipcMain.handle('connections:delete', (_, id) => { function downloadTo(src, dest) { return new Promise((resolve, reject) => { - const mod = src.startsWith('https:') ? require('https') : http; - const req = mod.get(src, { - headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }, - rejectUnauthorized: false, - }, (res) => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); - downloadTo(new URL(res.headers.location, src).toString(), dest).then(resolve, reject); - return; - } - if (res.statusCode !== 200) { res.resume(); reject(new Error('HTTP ' + res.statusCode)); return; } - const out = fs.createWriteStream(dest); - res.pipe(out); - out.on('finish', () => out.close(resolve)); - out.on('error', reject); - res.on('error', reject); - }); - req.on('error', reject); - req.setTimeout(60000, () => req.destroy(new Error('timeout'))); + const mod = src.startsWith("https:") ? require("https") : http; + const req = mod.get( + src, + { + headers: { + "User-Agent": + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + }, + rejectUnauthorized: false, + }, + (res) => { + if ( + res.statusCode >= 300 && + res.statusCode < 400 && + res.headers.location + ) { + res.resume(); + downloadTo(new URL(res.headers.location, src).toString(), dest).then( + resolve, + reject, + ); + return; + } + if (res.statusCode !== 200) { + res.resume(); + reject(new Error("HTTP " + res.statusCode)); + return; + } + const out = fs.createWriteStream(dest); + res.pipe(out); + out.on("finish", () => out.close(resolve)); + out.on("error", reject); + res.on("error", reject); + }, + ); + req.on("error", reject); + req.setTimeout(60000, () => req.destroy(new Error("timeout"))); }); } -ipcMain.handle('bg:cache', async (_, { src }) => { - if (!src || typeof src !== 'string') return { ok: false, error: 'no src' }; - const dir = path.join(app.getPath('userData'), 'bg-cache'); +ipcMain.handle("bg:cache", async (_, { src }) => { + if (!src || typeof src !== "string") return { ok: false, error: "no src" }; + const dir = path.join(app.getPath("userData"), "bg-cache"); try { fs.mkdirSync(dir, { recursive: true }); - const hash = crypto.createHash('sha1').update(src).digest('hex').slice(0, 24); + const hash = crypto + .createHash("sha1") + .update(src) + .digest("hex") + .slice(0, 24); let dest = null; if (/^https?:\/\//i.test(src)) { dest = path.join(dir, hash); if (!fs.existsSync(dest)) { - try { await downloadTo(src, dest); } - catch (e) { return { ok: false, error: '下载失败: ' + e.message, useOriginal: true }; } + try { + await downloadTo(src, dest); + } catch (e) { + return { + ok: false, + error: "下载失败: " + e.message, + useOriginal: true, + }; + } } } else if (/^file:\/\//i.test(src)) { - dest = new URL(src).pathname.replace(/^\/([A-Za-z]:)/, '$1'); - if (!fs.existsSync(dest)) return { ok: false, error: '文件不存在: ' + src }; + dest = new URL(src).pathname.replace(/^\/([A-Za-z]:)/, "$1"); + if (!fs.existsSync(dest)) + return { ok: false, error: "文件不存在: " + src }; } else if (/^data:image\//i.test(src)) { - dest = path.join(dir, hash + '.png'); - if (!fs.existsSync(dest)) fs.writeFileSync(dest, Buffer.from(src.split(',')[1] || '', 'base64')); + dest = path.join(dir, hash + ".png"); + if (!fs.existsSync(dest)) + fs.writeFileSync(dest, Buffer.from(src.split(",")[1] || "", "base64")); } else { const p = path.resolve(src); - if (!fs.existsSync(p)) return { ok: false, error: '路径不存在: ' + src }; - dest = path.join(dir, hash + (path.extname(p) || '')); + if (!fs.existsSync(p)) return { ok: false, error: "路径不存在: " + src }; + dest = path.join(dir, hash + (path.extname(p) || "")); if (!fs.existsSync(dest)) fs.copyFileSync(p, dest); } return { ok: true, file: pathToFileURL(dest).href }; @@ -310,106 +480,127 @@ ipcMain.handle('bg:cache', async (_, { src }) => { } }); -ipcMain.handle('connections:setCurrent', (_, id) => { +ipcMain.handle("connections:setCurrent", (_, id) => { const data = loadConnections(); - if (data.connections.some(c => c.id === id)) { + if (data.connections.some((c) => c.id === id)) { data.currentId = id; saveConnections(data); } return data; }); -function doWebuiLogin(baseUrl, username, password, extraCookie) { - return new Promise((resolve, reject) => { - const u = new URL(baseUrl + '/api/v1/login'); - const body = JSON.stringify({ username, password }); - const mod = u.protocol === 'https:' ? require('https') : http; - const headers = { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(body), - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36', - 'Accept': 'application/json', - }; - if (extraCookie) headers['Cookie'] = extraCookie; - const req = mod.request(u, { - method: 'POST', - headers, - }, (res) => { - let data = ''; - res.on('data', (c) => (data += c)); - res.on('end', () => { - const sc = res.headers['set-cookie']; - if (!sc) { - reject(new Error('login failed HTTP ' + res.statusCode + ' ' + data.slice(0, 150))); - return; - } - const cookies = Array.isArray(sc) ? sc : [sc]; - let tok = null; - cookies.some((c) => { - const m = /homeagent_session=([^;]+)/.exec(c); - if (m) { tok = m[1]; return true; } - return false; - }); - if (!tok) { - reject(new Error('login ok but no homeagent_session cookie')); - return; - } - resolve(tok); - }); - }); - req.on('error', reject); - req.write(body); - req.end(); +async function doWebuiLogin(baseUrl, username, password, extraCookie) { + const u = baseUrl + "/api/v1/login"; + const headers = { + "Content-Type": "application/json", + Accept: "application/json", + }; + if (extraCookie) headers["Cookie"] = extraCookie; + const resp = await sessionFetch(u, { + method: "POST", + headers, + body: JSON.stringify({ username, password }), }); + // 1) Set-Cookie 直读(重定向未被 session.fetch 自动吞掉时) + const sc = resp.headers.get("set-cookie") || ""; + let m = /homeagent_session=([^;]+)/.exec(sc); + // 2) 重定向被自动跟随时 Set-Cookie 可能在中间 302 上:从 cookie jar 兜底 + if (!m) { + try { + const { session } = require("electron"); + const hostname = new URL(u).hostname; + const all = await session.defaultSession.cookies.get({}); + const hit = (all || []).find( + (c) => + c.name === "homeagent_session" && + (c.domain || "").replace(/^\./, "").toLowerCase() === + hostname.toLowerCase(), + ); + if (hit) m = [null, hit.value]; + } catch (e) {} + } + if (!m) { + const bodyTxt = await resp.text(); + throw new Error( + "login ok but no homeagent_session cookie (HTTP " + + resp.status + + " " + + bodyTxt.slice(0, 150) + + ")", + ); + } + return m[1]; } -ipcMain.on('log:r', (_e, m) => { log('[r] ' + m); }); -ipcMain.handle('log:r', (_e, m) => { log('[r] ' + m); return true; }); - -ipcMain.handle('webui:setAuth', async (_, { url, cookie, headers, username, password }) => { - const resp = { ok: true, error: '' }; - let extra = cookie || ''; - try { - if (username && url) { - try { - const tok = await doWebuiLogin(url, username, password, extra); - extra = extra ? extra + '; homeagent_session=' + tok : 'homeagent_session=' + tok; - } catch (e) { - if (extra) { - log('[setAuth] auto-login skipped (gateway cookie mode): ' + e.message.slice(0, 120)); - } else { - throw e; - } - } - } else if (!cookie) { - authRule = { url: '', cookie: '', headers: {} }; - return resp; - } - } catch (e) { - authRule = { url: url || '', cookie: extra || '', headers: headers || {} }; - resp.ok = false; - resp.error = e.message; - log('[setAuth] fail url=' + (url || '') + ' err=' + e.message.slice(0, 150)); - return resp; - } - authRule = { url: url || '', cookie: extra, headers: headers || {} }; - log('[setAuth] ok url=' + (url || '') + ' cookieLen=' + extra.length + ' hasTok=' + (extra.indexOf('homeagent_session') !== -1)); - return resp; +ipcMain.on("log:r", (_e, m) => { + log("[r] " + m); +}); +ipcMain.handle("log:r", (_e, m) => { + log("[r] " + m); + return true; }); -ipcMain.handle('webui:openLogin', (_, { url, username, password }) => { - if (!url) return { ok: false, error: 'no url' }; +ipcMain.handle( + "webui:setAuth", + async (_, { url, cookie, headers, username, password }) => { + const resp = { ok: true, error: "" }; + let extra = cookie || ""; + try { + if (username && url) { + try { + const tok = await doWebuiLogin(url, username, password, extra); + extra = extra + ? extra + "; homeagent_session=" + tok + : "homeagent_session=" + tok; + } catch (e) { + if (extra) { + log( + "[setAuth] auto-login skipped (gateway cookie mode): " + + e.message.slice(0, 120), + ); + } else { + throw e; + } + } + } else if (!cookie) { + await applyAuthRule("", "", {}); + return resp; + } + } catch (e) { + await applyAuthRule(url, extra || "", headers || {}); + resp.ok = false; + resp.error = e.message; + log( + "[setAuth] fail url=" + (url || "") + " err=" + e.message.slice(0, 150), + ); + return resp; + } + await applyAuthRule(url, extra, headers || {}); + log( + "[setAuth] ok url=" + + (url || "") + + " cookieLen=" + + extra.length + + " hasTok=" + + (extra.indexOf("homeagent_session") !== -1), + ); + return resp; + }, +); + +ipcMain.handle("webui:openLogin", (_, { url, username, password }) => { + if (!url) return { ok: false, error: "no url" }; const loginWin = new BrowserWindow({ width: 980, height: 740, parent: mainWindow, modal: true, autoHideMenuBar: true, - title: 'HomeAgent - 网关联机登录', + title: "HomeAgent - 网关联机登录", webPreferences: { contextIsolation: true, nodeIntegration: false }, }); - const u = encodeURIComponent(username || ''); - const p = encodeURIComponent(password || ''); + const u = encodeURIComponent(username || ""); + const p = encodeURIComponent(password || ""); let autoFills = 0; const tryAutofill = () => { if (autoFills > 8) return; @@ -420,55 +611,80 @@ ipcMain.handle('webui:openLogin', (_, { url, username, password }) => { 'if(!pw)return false;var f=pw.closest("form")||pw.form;if(!f)return false;' + 'var ins=f.querySelectorAll("input");var filled=false;' + 'for(var i=0;i { - if (r) log('[openLogin] autofilled gateway login form'); + if (r) log("[openLogin] autofilled gateway login form"); }) - .catch((e) => log('[openLogin] autofill error: ' + e.message)); + .catch((e) => log("[openLogin] autofill error: " + e.message)); }; - loginWin.webContents.on('did-finish-load', () => { + loginWin.webContents.on("did-finish-load", () => { if (autoFills < 3) tryAutofill(); }); - loginWin.webContents.on('did-navigate', (_e, u) => { - log('[openLogin] nav: ' + u); + loginWin.webContents.on("did-navigate", (_e, u) => { + log("[openLogin] nav: " + u); if (autoFills < 6) setTimeout(tryAutofill, 600); }); - loginWin.webContents.on('did-fail-load', (_e, code, desc, isMain, failedUrl) => { - if (isMain) log('[openLogin] fail-load ' + code + ' ' + desc + ' @ ' + failedUrl); - }); - loginWin.loadURL(url).catch((e) => console.error('login window load error:', e.message)); + loginWin.webContents.on( + "did-fail-load", + (_e, code, desc, isMain, failedUrl) => { + if (isMain) + log("[openLogin] fail-load " + code + " " + desc + " @ " + failedUrl); + }, + ); + loginWin + .loadURL(url) + .catch((e) => console.error("login window load error:", e.message)); let grabbed = null; - loginWin.on('close', async () => { + loginWin.on("close", async () => { if (grabbed) return; try { - const all = await require('electron').session.defaultSession.cookies.get({}); + const all = await require("electron").session.defaultSession.cookies.get( + {}, + ); const host = new URL(url).hostname; const keep = (all || []).filter((c) => { - const d = (c.domain || '').replace(/^\./, ''); - const onHost = host === d || host.endsWith('.' + d); + const d = (c.domain || "").replace(/^\./, ""); + const onHost = host === d || host.endsWith("." + d); const onSibling = /(^|\.)jianfgit\.xyz$/i.test(d); - return onHost || onSibling || /^sl-/.test(c.name || ''); + return onHost || onSibling || /^sl-/.test(c.name || ""); }); - const list = keep.map((c) => c.name + '=' + c.value); - log('[openLogin] close-grab: host=' + host + ' kept=' + keep.length + - ' names=' + keep.map((c) => c.name + '@' + (c.domain || '')).join(',')); - grabbed = { ok: true, cookie: list.join('; '), count: keep.length }; + const list = keep.map((c) => c.name + "=" + c.value); + // 目标 host 的 sl-session 一并带上(网关会话是 host 级,登录域抓取未必覆盖) + const sl = await adoptSlSession(url); + if (sl && list.indexOf(sl) === -1) list.push(sl); + log( + "[openLogin] close-grab: host=" + + host + + " kept=" + + keep.length + + " names=" + + keep.map((c) => c.name + "@" + (c.domain || "")).join(","), + ); + grabbed = { + ok: true, + cookie: list.join("; "), + count: keep.length + (sl ? 1 : 0), + }; } catch (e) { - log('[openLogin] close-grab error: ' + e.message); + log("[openLogin] close-grab error: " + e.message); grabbed = { ok: false, error: e.message }; } }); - loginWin.on('closed', () => { + loginWin.on("closed", () => { if (mainWindow && !mainWindow.isDestroyed() && grabbed) { - mainWindow.webContents.send('webui:login-result', { ...grabbed, url }); + mainWindow.webContents.send("webui:login-result", { ...grabbed, url }); } }); return { ok: true }; @@ -476,46 +692,52 @@ ipcMain.handle('webui:openLogin', (_, { url, username, password }) => { // CLI 传输:通过 homed 的 unix socket(逐行 JSON 协议)发起请求。 // 认证行:/auth (若配置了密钥)。返回 JSON 响应行。 -ipcMain.handle('cli:request', (_, { socketPath, apiKey, line }) => { +ipcMain.handle("cli:request", (_, { socketPath, apiKey, line }) => { return new Promise((resolve) => { - const net = require('net'); + const net = require("net"); let client; try { client = net.createConnection({ path: socketPath }); } catch (e) { - return resolve({ error: 'create connection: ' + e.message }); + return resolve({ error: "create connection: " + e.message }); } const timeout = setTimeout(() => { - try { client.destroy(); } catch (_) {} - resolve({ error: 'timeout waiting for cli response' }); + try { + client.destroy(); + } catch (_) {} + resolve({ error: "timeout waiting for cli response" }); }, 30000); - let buf = ''; + let buf = ""; const onData = (chunk) => { - buf += chunk.toString('utf8'); - const idx = buf.indexOf('\n'); + buf += chunk.toString("utf8"); + const idx = buf.indexOf("\n"); if (idx === -1) return; const lineOut = buf.slice(0, idx); clearTimeout(timeout); - try { client.destroy(); } catch (_) {} + try { + client.destroy(); + } catch (_) {} try { resolve(JSON.parse(lineOut)); } catch (e) { - resolve({ error: 'bad response: ' + lineOut }); + resolve({ error: "bad response: " + lineOut }); } }; const onError = (err) => { clearTimeout(timeout); - try { client.destroy(); } catch (_) {} + try { + client.destroy(); + } catch (_) {} resolve({ error: err.message }); }; - client.on('error', onError); - client.on('data', onData); - client.on('connect', () => { + client.on("error", onError); + client.on("data", onData); + client.on("connect", () => { let next = line; - if (apiKey) next = '/auth ' + apiKey + '\n' + next; - client.write(next + '\n'); + if (apiKey) next = "/auth " + apiKey + "\n" + next; + client.write(next + "\n"); }); }); }); @@ -527,21 +749,21 @@ app.whenReady().then(async () => { startHomed(); const started = await waitForServer(); if (started) { - console.log('homed started successfully'); + console.log("homed started successfully"); } else { - console.error('homed failed to start within timeout'); + console.error("homed failed to start within timeout"); } } createWindow(); }); -app.on('before-quit', stopHomed); +app.on("before-quit", stopHomed); -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') app.quit(); +app.on("window-all-closed", () => { + if (process.platform !== "darwin") app.quit(); }); -app.on('activate', () => { +app.on("activate", () => { if (mainWindow === null) { createWindow(); } diff --git a/cmd/gui/package.json b/cmd/gui/package.json index ab53e97..3534be0 100644 --- a/cmd/gui/package.json +++ b/cmd/gui/package.json @@ -1,6 +1,8 @@ { "name": "homeagent-gui", "version": "1.0.0", + "author": "JianFeeeee ", + "homepage": "https://gitcode.com/JianFeeeee/HomeAgent", "description": "HomeAgent Desktop GUI - Multi-connection management dashboard", "main": "main.js", "scripts": { @@ -8,10 +10,10 @@ "dev": "electron . --no-sandbox --dev" }, "dependencies": { - "electron": "^33.0.0" }, "devDependencies": { "asar": "^3.2.0", + "electron": "^33.0.0", "electron-builder": "^26.15.3", "electron-packager": "^17.1.2", "icojs": "^0.23.0", diff --git a/cmd/gui/renderer/app.js b/cmd/gui/renderer/app.js index bf14d1b..2591365 100644 --- a/cmd/gui/renderer/app.js +++ b/cmd/gui/renderer/app.js @@ -1,17 +1,17 @@ // ===== State ===== -let state = { +const state = { status: {}, kernel: null, settings: {}, meta: {}, pluginMeta: {}, - settingsPlugins: ['core'], + settingsPlugins: ["core"], disabledPlugins: [], - currentView: 'chat', - selectedSection: 'core', + currentView: "chat", + selectedSection: "core", messages: [], chatLoading: false, - chatStage: '', + chatStage: "", healthResult: null, starmapInit: false, starmapLoading: false, @@ -24,91 +24,95 @@ let state = { pendingTools: [], eventSource: null, chatFinalIdx: -1, - lang: localStorage.getItem('ha-lang') || 'zh', - connections: [], currentConn: null, - + lang: localStorage.getItem("ha-lang") || "zh", + connections: [], + currentConn: null, }; // ===== I18n ===== window._i18n = { - navOverview: ['概览','Overview'], - navChat: ['对话','Chat'], - navPlugins: ['插件','Plugins'], - navSettings: ['设置','Settings'], - navAdapters: ['适配器','Adapters'], - navKernel: ['内核','Kernel'], - navLogout: ['退出登录','Logout'], - themeToggle: ['切换亮色/暗色模式','Toggle theme'], - clickManage: ['点击管理连接','Click to manage connections'], - secondsAgo: ['秒前','s ago'], - minutesAgo: ['分钟前','min ago'], - hoursAgo: ['小时前','h ago'], - noConnection: ['未连接','Not connected'], - agentAvatar: ['小宅','Agent'], - waitingAI: ['等待AI回复...','Waiting for AI...'], - noResponse: ['(无响应)','(no response)'], - error: ['错误: ','Error: '], - requestFailed: ['请求失败: ','Request failed: '], - send: ['发送','Send'], - queryFailed: ['查询失败: ','Query failed: '], - searchFailed: ['搜索失败: ','Search failed: '], - getFailed: ['获取失败: ','Get failed: '], - createFailed: ['创建失败','Create failed'], - createFailedWith: ['创建失败: ','Create failed: '], - nameContentEmpty: ['名称和内容不能为空','Name and content cannot be empty'], - knowledgeCreated: ['知识「','Knowledge "'], - knowledgeCreatedEnd: ['」已创建','" created'], - noContext: ['无上下文','No context'], - noSessions: ['暂无终端会话','No terminal sessions'], - noHistory: ['暂无命令记录','No command history'], - running: ['运行中','Running'], - closed: ['已关闭','Closed'], - command: ['命令','Command'], - status: ['状态','Status'], - created: ['创建时间','Created'], - uptime: ['运行时长','Uptime'], - output: ['输出预览','Output'], - time: ['时间','Time'], - actions: ['操作','Actions'], - name: ['名称','Name'], - description: ['描述','Description'], - version: ['版本','Version'], - details: ['详情','Details'], - close: ['关闭','Close'], - install: ['安装','Install'], - installPlugin: ['安装插件','Install Plugin'], - packageUrl: ['.hmap 包下载 URL','Package URL'], - uploadHmap: ['选择 .hmap 文件上传','Upload .hmap file'], - loadedPlugins: ['已加载插件','Loaded Plugins'], - noLoadedPlugins: ['暂无已加载插件','No loaded plugins'], - loaded: ['已加载','Loaded'], - builtin: ['内置','Built-in'], - unload: ['卸载','Unload'], - installedExternal: ['已安装外部插件','Installed Plugins'], - pluginDetails: ['插件详情','Plugin Details'], - registeredTools: ['已注册工具','Registered Tools'], - systemOps: ['系统操作','System Operations'], - reloadPlugins: ['重载插件','Reload Plugins'], + navOverview: ["概览", "Overview"], + navChat: ["对话", "Chat"], + navPlugins: ["插件", "Plugins"], + navSettings: ["设置", "Settings"], + navAdapters: ["适配器", "Adapters"], + navKernel: ["内核", "Kernel"], + navLogout: ["退出登录", "Logout"], + themeToggle: ["切换亮色/暗色模式", "Toggle theme"], + clickManage: ["点击管理连接", "Click to manage connections"], + secondsAgo: ["秒前", "s ago"], + minutesAgo: ["分钟前", "min ago"], + hoursAgo: ["小时前", "h ago"], + noConnection: ["未连接", "Not connected"], + agentAvatar: ["小宅", "Agent"], + waitingAI: ["等待AI回复...", "Waiting for AI..."], + noResponse: ["(无响应)", "(no response)"], + error: ["错误: ", "Error: "], + requestFailed: ["请求失败: ", "Request failed: "], + send: ["发送", "Send"], + queryFailed: ["查询失败: ", "Query failed: "], + searchFailed: ["搜索失败: ", "Search failed: "], + getFailed: ["获取失败: ", "Get failed: "], + createFailed: ["创建失败", "Create failed"], + createFailedWith: ["创建失败: ", "Create failed: "], + nameContentEmpty: ["名称和内容不能为空", "Name and content cannot be empty"], + knowledgeCreated: ["知识「", 'Knowledge "'], + knowledgeCreatedEnd: ["」已创建", '" created'], + noContext: ["无上下文", "No context"], + noSessions: ["暂无终端会话", "No terminal sessions"], + noHistory: ["暂无命令记录", "No command history"], + running: ["运行中", "Running"], + closed: ["已关闭", "Closed"], + command: ["命令", "Command"], + status: ["状态", "Status"], + created: ["创建时间", "Created"], + uptime: ["运行时长", "Uptime"], + output: ["输出预览", "Output"], + time: ["时间", "Time"], + actions: ["操作", "Actions"], + name: ["名称", "Name"], + description: ["描述", "Description"], + version: ["版本", "Version"], + details: ["详情", "Details"], + close: ["关闭", "Close"], + install: ["安装", "Install"], + installPlugin: ["安装插件", "Install Plugin"], + packageUrl: [".hmap 包下载 URL", "Package URL"], + uploadHmap: ["选择 .hmap 文件上传", "Upload .hmap file"], + loadedPlugins: ["已加载插件", "Loaded Plugins"], + noLoadedPlugins: ["暂无已加载插件", "No loaded plugins"], + loaded: ["已加载", "Loaded"], + builtin: ["内置", "Built-in"], + unload: ["卸载", "Unload"], + installedExternal: ["已安装外部插件", "Installed Plugins"], + pluginDetails: ["插件详情", "Plugin Details"], + registeredTools: ["已注册工具", "Registered Tools"], + systemOps: ["系统操作", "System Operations"], + reloadPlugins: ["重载插件", "Reload Plugins"], }; -function __(zh, en) { return state.lang === 'en' ? en : zh } -function L() { return state.lang } +function __(zh, en) { + return state.lang === "en" ? en : zh; +} +function L() { + return state.lang; +} function toggleLang() { - state.lang = state.lang === 'zh' ? 'en' : 'zh'; - localStorage.setItem('ha-lang', state.lang); + state.lang = state.lang === "zh" ? "en" : "zh"; + localStorage.setItem("ha-lang", state.lang); applyI18n(); renderAll(); } function applyI18n() { var lang = state.lang; - var btn = document.getElementById('lang-btn'); - if (btn) btn.textContent = lang === 'zh' ? 'EN' : '中'; - document.querySelectorAll('[data-i18n]').forEach(function(el) { - var k = el.getAttribute('data-i18n'); + var btn = document.getElementById("lang-btn"); + if (btn) btn.textContent = lang === "zh" ? "EN" : "中"; + document.querySelectorAll("[data-i18n]").forEach((el) => { + var k = el.getAttribute("data-i18n"); var m = window._i18n && window._i18n[k]; - if (m) el.textContent = lang === 'en' ? m[1] : m[0]; + if (m) el.textContent = lang === "en" ? m[1] : m[0]; }); } @@ -119,44 +123,45 @@ var ICON_MOON_GUI = ''; function setTheme(name) { - document.documentElement.setAttribute('data-theme', name); - localStorage.setItem('ha-theme', name); - var btn = document.getElementById('theme-btn'); - if (btn) btn.innerHTML = name === 'light' ? ICON_SUN_GUI : ICON_MOON_GUI; + document.documentElement.setAttribute("data-theme", name); + localStorage.setItem("ha-theme", name); + var btn = document.getElementById("theme-btn"); + if (btn) btn.innerHTML = name === "light" ? ICON_SUN_GUI : ICON_MOON_GUI; } function toggleTheme() { - var cur = document.documentElement.getAttribute('data-theme'); - setTheme(cur === 'light' ? 'dark' : 'light'); + var cur = document.documentElement.getAttribute("data-theme"); + setTheme(cur === "light" ? "dark" : "light"); } // ===== Appearance: 主题色 / 背景图 ===== var PALETTES_GUI = { - sakura: '#ff7fac', - cyan: '#2dd4bf', - violet: '#a78bfa', - emerald: '#34d399', - amber: '#fbbf24', - blue: '#60a5fa' + sakura: "#ff7fac", + cyan: "#2dd4bf", + violet: "#a78bfa", + emerald: "#34d399", + amber: "#fbbf24", + blue: "#60a5fa", }; function setColor(name) { - document.documentElement.setAttribute('data-color', name); - localStorage.setItem('ha-color', name); - var pop = document.getElementById('palette-pop'); + document.documentElement.setAttribute("data-color", name); + localStorage.setItem("ha-color", name); + var pop = document.getElementById("palette-pop"); if (!pop) return; - var btns = pop.querySelectorAll('button.cdot'); + var btns = pop.querySelectorAll("button.cdot"); for (var i = 0; i < btns.length; i++) { - btns[i].className = btns[i].getAttribute('data-c') === name ? 'cdot on' : 'cdot'; + btns[i].className = + btns[i].getAttribute("data-c") === name ? "cdot on" : "cdot"; } } async function applyBgImg(input) { - var src = (input || '').trim(); + var src = (input || "").trim(); if (!src) { - document.documentElement.style.setProperty('--bg-img', 'none'); - localStorage.removeItem('ha-bg-img'); - localStorage.removeItem('ha-bg-final'); + document.documentElement.style.setProperty("--bg-img", "none"); + localStorage.removeItem("ha-bg-img"); + localStorage.removeItem("ha-bg-final"); return; } var finalSrc = src; @@ -164,37 +169,48 @@ async function applyBgImg(input) { try { var r = await window.homeagent.cacheBg(src); if (r && r.ok && r.file) finalSrc = r.file; - else if (r && r.error && !r.useOriginal) toast(__('背景图加载失败: ','Bg load failed: ') + r.error, true); - } catch (e) { toast(__('背景图加载失败: ','Bg load failed: ') + e.message, true); } + else if (r && r.error && !r.useOriginal) + toast(__("背景图加载失败: ", "Bg load failed: ") + r.error, true); + } catch (e) { + toast(__("背景图加载失败: ", "Bg load failed: ") + e.message, true); + } } - document.documentElement.style.setProperty('--bg-img', 'url("' + finalSrc.replace(/"/g, '\\"') + '")'); + document.documentElement.style.setProperty( + "--bg-img", + 'url("' + finalSrc.replace(/"/g, '\\"') + '")', + ); if (/^data:/.test(src)) { - localStorage.setItem('ha-bg-img', finalSrc); + localStorage.setItem("ha-bg-img", finalSrc); } else { - localStorage.setItem('ha-bg-img', src); + localStorage.setItem("ha-bg-img", src); } - localStorage.setItem('ha-bg-final', finalSrc); + localStorage.setItem("ha-bg-final", finalSrc); } function setBgImgVar(finalSrc) { - document.documentElement.style.setProperty('--bg-img', 'url("' + (finalSrc || '').replace(/"/g, '\\"') + '")'); + document.documentElement.style.setProperty( + "--bg-img", + 'url("' + (finalSrc || "").replace(/"/g, '\\"') + '")', + ); } function pickBgFile() { - var fi = document.getElementById('bg-file-input'); + var fi = document.getElementById("bg-file-input"); if (!fi) { - fi = document.createElement('input'); - fi.type = 'file'; - fi.id = 'bg-file-input'; - fi.accept = 'image/*'; - fi.style.display = 'none'; - fi.onchange = function () { + fi = document.createElement("input"); + fi.type = "file"; + fi.id = "bg-file-input"; + fi.accept = "image/*"; + fi.style.display = "none"; + fi.onchange = () => { var f = fi.files && fi.files[0]; if (!f) return; var rd = new FileReader(); - rd.onload = function () { applyBgImg(rd.result); }; + rd.onload = () => { + applyBgImg(rd.result); + }; rd.readAsDataURL(f); - fi.value = ''; + fi.value = ""; }; document.body.appendChild(fi); } @@ -203,52 +219,79 @@ function pickBgFile() { function applyBgBlur(n) { n = Math.max(0, Math.min(30, Number(n) || 0)); - document.documentElement.style.setProperty('--bg-blur', String(n)); - localStorage.setItem('ha-bg-blur', String(n)); - var v = document.getElementById('bg-blur-val'); - if (v) v.textContent = n + 'px'; - var r = document.getElementById('bg-blur-range'); + document.documentElement.style.setProperty("--bg-blur", String(n)); + localStorage.setItem("ha-bg-blur", String(n)); + var v = document.getElementById("bg-blur-val"); + if (v) v.textContent = n + "px"; + var r = document.getElementById("bg-blur-range"); if (r) r.value = String(n); } function toggleAppearance() { - var pop = document.getElementById('palette-pop'); + var pop = document.getElementById("palette-pop"); if (!pop) return; - var on = pop.classList.contains('on'); - if (!pop.querySelector('button.cdot')) { - var cur = localStorage.getItem('ha-color') || 'sakura'; - var img = localStorage.getItem('ha-bg-img') || ''; - var blur = localStorage.getItem('ha-bg-blur') || '0'; - var dots = ''; - Object.keys(PALETTES_GUI).forEach(function (k) { - dots += ''; + var on = pop.classList.contains("on"); + if (!pop.querySelector("button.cdot")) { + var cur = localStorage.getItem("ha-color") || "sakura"; + var img = localStorage.getItem("ha-bg-img") || ""; + var blur = localStorage.getItem("ha-bg-blur") || "0"; + var dots = ""; + Object.keys(PALETTES_GUI).forEach((k) => { + dots += + '"; }); pop.innerHTML = - '

' + __('主题色','Theme color') + '

' + dots + '
' + - '

' + __('背景图片 URL','Background image URL') + '

' + - '' + - '
' + - '' + - '' + - '' + __('模糊','Blur') + ' ' + - '' + blur + 'px
'; + "

" + + __("主题色", "Theme color") + + "

" + + dots + + "
" + + '

' + + __("背景图片 URL", "Background image URL") + + "

" + + '' + + '
" + + '" + + '" + + '' + + __("模糊", "Blur") + + ' ' + + '' + + blur + + "px
"; setColor(cur); - var rr = document.getElementById('bg-blur-range'); + var rr = document.getElementById("bg-blur-range"); if (rr) rr.value = blur; - var vv = document.getElementById('bg-blur-val'); - if (vv) vv.textContent = blur + 'px'; + var vv = document.getElementById("bg-blur-val"); + if (vv) vv.textContent = blur + "px"; } - pop.classList.toggle('on', !on); + pop.classList.toggle("on", !on); } -(function() { - var saved = localStorage.getItem('ha-theme'); - setTheme(saved || 'light'); - var finalSrc = localStorage.getItem('ha-bg-final'); - var img = localStorage.getItem('ha-bg-img'); - var blur = localStorage.getItem('ha-bg-blur'); +(() => { + var saved = localStorage.getItem("ha-theme"); + setTheme(saved || "light"); + var finalSrc = localStorage.getItem("ha-bg-final"); + var img = localStorage.getItem("ha-bg-img"); + var blur = localStorage.getItem("ha-bg-blur"); if (img) { if (finalSrc) setBgImgVar(finalSrc); else applyBgImg(img); @@ -258,31 +301,103 @@ function toggleAppearance() { // ===== Utility ===== function escHtml(s) { - return String(s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); + return String(s) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); } function timeAgo(t) { var s = Math.floor((Date.now() - new Date(t).getTime()) / 1000); - if (s < 60) return s + __('秒前','s ago'); + if (s < 60) return s + __("秒前", "s ago"); var m = Math.floor(s / 60); - if (m < 60) return m + __('分钟前','min ago'); - return Math.floor(m / 60) + __('小时前','h ago'); + if (m < 60) return m + __("分钟前", "min ago"); + return Math.floor(m / 60) + __("小时前", "h ago"); } -function toast(m, isError) { - var t = document.getElementById('toast'); +function toast(m, isError, warn) { + var t = document.getElementById("toast"); t.textContent = m; - t.className = 'toast' + (isError ? ' error' : ''); - t.style.display = 'block'; - setTimeout(function() { t.style.display = 'none' }, 3000); + var cls = "toast"; + if (isError) cls += " error"; + else if (warn) cls += " warn"; + else cls += " success"; + t.className = cls; + t.style.display = "block"; + t.style.animation = "none"; + void t.offsetWidth; + t.style.animation = ""; + clearTimeout(t._hideTimer); + t._hideTimer = setTimeout(() => { + t.style.display = "none"; + }, 3000); +} + +// confirmDialog 替换原生 confirm():玻璃态弹窗 + Esc/Enter/遮罩关闭,返回 Promise +function confirmDialog(action, isDanger) { + var o = document.getElementById("confirm-overlay"); + if (!o) return Promise.resolve(false); + o.innerHTML = + '
' + + '

' + + __("确认操作", "Confirm action") + + "

" + + "

" + + escHtml(action) + + "

" + + '
' + + '" + + '" + + "
"; + o.style.display = "flex"; + o.querySelector('[data-confirm="no"]').focus(); + // 复用持久遮罩层的单一委托监听(首次挂载),避免每次调用累积监听器 + if (!o._bound) { + o._bound = true; + o.addEventListener("click", (e) => { + if (o.style.display !== "flex") return; + var btn = e.target.closest("[data-confirm]"); + if (btn) { + var ok = btn.getAttribute("data-confirm") === "yes"; + o._close(ok); + } else if (e.target === o) { + o._close(false); + } + }); + document.addEventListener("keydown", (ev) => { + if (o.style.display !== "flex") return; + if (ev.key === "Escape") o._close(false); + else if (ev.key === "Enter") o._close(true); + }); + } + return new Promise((resolve) => { + o._close = (ok) => { + o.innerHTML = ""; + o.style.display = "none"; + o._close = null; + resolve(ok); + }; + }); } // ===== API ===== async function cliRequest(line) { var conn = state.currentConn; - if (!conn) throw new Error(__('未选择连接','No connection selected')); - if (!window.homeagent || !window.homeagent.cli) throw new Error('cli bridge unavailable'); - var resp = await window.homeagent.cli.request(conn.socketPath || conn.url, conn.apiKey, line); + if (!conn) throw new Error(__("未选择连接", "No connection selected")); + if (!window.homeagent || !window.homeagent.cli) + throw new Error("cli bridge unavailable"); + var resp = await window.homeagent.cli.request( + conn.socketPath || conn.url, + conn.apiKey, + line, + ); if (resp && resp.error) throw new Error(resp.error); return resp; } @@ -290,58 +405,79 @@ async function cliRequest(line) { // CLI 传输映射:将 REST 路径转换为 cli 内置命令或直接对话 function cliMap(path, o) { o = o || {}; - var m = o.method || 'GET'; - if (m === 'POST' && path.indexOf('/chat') !== -1) { + var m = o.method || "GET"; + if (m === "POST" && path.indexOf("/chat") !== -1) { var body = {}; - try { body = JSON.parse(o.body || '{}'); } catch (e) {} - return cliRequest(body.message || ''); + try { + body = JSON.parse(o.body || "{}"); + } catch (e) {} + return cliRequest(body.message || ""); } - if (path === '/status') return cliRequest('/status'); - if (path === '/kernel') return cliRequest('/kernel'); - if (path === '/settings') return cliRequest('/settings'); - if (path === '/chat/history') return Promise.resolve({ messages: [] }); - return Promise.reject(new Error(__('CLI 连接不支持此功能','Not supported on CLI connection'))); + if (path === "/status") return cliRequest("/status"); + if (path === "/kernel") return cliRequest("/kernel"); + if (path === "/settings") return cliRequest("/settings"); + if (path === "/chat/history") return Promise.resolve({ messages: [] }); + return Promise.reject( + new Error(__("CLI 连接不支持此功能", "Not supported on CLI connection")), + ); } async function api(p, o) { - if (!state.currentConn) throw new Error(__('未选择连接','No connection selected')); - if (state.currentConn.type === 'cli') { + if (!state.currentConn) + throw new Error(__("未选择连接", "No connection selected")); + if (state.currentConn.type === "cli") { return cliMap(p, o); } var opts = o || {}; var to = opts.timeout || 8000; - var headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) }; - if (state.currentConn.apiKey) headers['X-API-Key'] = state.currentConn.apiKey; + var headers = { "Content-Type": "application/json", ...(opts.headers || {}) }; + if (state.currentConn.apiKey) headers["X-API-Key"] = state.currentConn.apiKey; var ctl = new AbortController(); - var timer = setTimeout(function(){ ctl.abort() }, to); + var timer = setTimeout(() => { + ctl.abort(); + }, to); var r; try { - r = await fetch(state.currentConn.url + '/api/v1' + p, { ...opts, headers: headers, signal: ctl.signal }); + r = await fetch(state.currentConn.url + "/api/v1" + p, { + ...opts, + headers: headers, + signal: ctl.signal, + }); } catch (e) { clearTimeout(timer); - throw new Error(__('连接超时或失败','Timeout or connection failed')); + throw new Error(__("连接超时或失败", "Timeout or connection failed")); } clearTimeout(timer); - if (r.status === 401) throw new Error(__('认证失败','unauthorized')); + if (r.status === 401) throw new Error(__("认证失败", "unauthorized")); if (opts.raw) return r; - var ct = r.headers.get('content-type') || ''; - if (ct.includes('json')) return r.json(); + var ct = r.headers.get("content-type") || ""; + if (ct.includes("json")) return r.json(); return r.text(); } // ===== Navigation ===== function switchView(n) { - document.querySelectorAll('.view').forEach(function(e) { e.classList.remove('active') }); - var el = document.getElementById('view-' + n); - if (el) el.classList.add('active'); - document.querySelectorAll('.rail-btn').forEach(function(e) { e.classList.remove('active') }); - var rb = document.getElementById('rail-' + n); - if (rb) rb.classList.add('active'); + document.querySelectorAll(".view").forEach((e) => { + e.classList.remove("active"); + }); + var el = document.getElementById("view-" + n); + if (el) el.classList.add("active"); + document.querySelectorAll(".rail-btn").forEach((e) => { + e.classList.remove("active"); + }); + var rb = document.getElementById("rail-" + n); + if (rb) rb.classList.add("active"); state.currentView = n; - if (n === 'chat') { + if (n === "chat") { state.chatStick = true; - var msgsEl = document.getElementById('chat-msgs'); - if (msgsEl) { try { msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: 'smooth' }) } catch(e) { msgsEl.scrollTop = msgsEl.scrollHeight } } + var msgsEl = document.getElementById("chat-msgs"); + if (msgsEl) { + try { + msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: "smooth" }); + } catch (e) { + msgsEl.scrollTop = msgsEl.scrollHeight; + } + } } renderAll(); } @@ -352,177 +488,467 @@ async function doRenderAll() { } function renderAll() { - try { renderOverview() } catch(e) { console.error('renderOverview', e) } - try { renderChat() } catch(e) { console.error('renderChat', e) } - try { renderChatStarmap() } catch(e) { console.error('renderChatStarmap', e) } - try { renderPlugins() } catch(e) { console.error('renderPlugins', e) } - try { renderKernel() } catch(e) { console.error('renderKernel', e) } - try { renderOneSettings() } catch(e) { console.error('renderOneSettings', e) } - try { renderAdapters() } catch(e) { console.error('renderAdapters', e) } + try { + renderOverview(); + } catch (e) { + console.error("renderOverview", e); + } + try { + renderChat(); + } catch (e) { + console.error("renderChat", e); + } + try { + renderChatStarmap(); + } catch (e) { + console.error("renderChatStarmap", e); + } + try { + renderPlugins(); + } catch (e) { + console.error("renderPlugins", e); + } + try { + renderKernel(); + } catch (e) { + console.error("renderKernel", e); + } + try { + renderOneSettings(); + } catch (e) { + console.error("renderOneSettings", e); + } + try { + renderAdapters(); + } catch (e) { + console.error("renderAdapters", e); + } applyI18n(); + applyCardTilt(); refreshAll(); } async function refreshAll() { - try { var s = await api('/status'); state.status = s; state.startedAt = s.startedAt ? new Date(s.startedAt).getTime() : null; updateConnIndicator() } catch(e) {} - try { state.kernel = await api('/kernel') } catch(e) {} try { - var s = await api('/settings'); + var s = await api("/status"); + state.status = s; + state.startedAt = s.startedAt ? new Date(s.startedAt).getTime() : null; + updateConnIndicator(); + } catch (e) {} + try { + state.kernel = await api("/kernel"); + } catch (e) {} + try { + var s = await api("/settings"); state.settings = s.settings || {}; state.meta = s.meta || {}; - state.settingsPlugins = s.plugins || ['core']; + state.settingsPlugins = s.plugins || ["core"]; state.pluginMeta = s.plugin_meta || {}; state.disabledPlugins = s.disabled_plugins || []; - } catch(e) {} - try { state.installedPlugins = await api('/plugins') } catch(e) {} - try { await loadTerminals() } catch(e) {} - try { await loadCmdHistory() } catch(e) {} - try { renderOverview() } catch(e) { console.error('renderOverview', e) } - try { renderChat() } catch(e) { console.error('renderChat', e) } - try { renderChatStarmap() } catch(e) { console.error('renderChatStarmap', e) } - try { renderPlugins() } catch(e) { console.error('renderPlugins', e) } - try { renderKernel() } catch(e) { console.error('renderKernel', e) } - try { renderOneSettings() } catch(e) { console.error('renderOneSettings', e) } - try { renderAdapters() } catch(e) { console.error('renderAdapters', e) } + } catch (e) {} + try { + state.installedPlugins = await api("/plugins"); + } catch (e) {} + try { + await loadTerminals(); + } catch (e) {} + try { + await loadCmdHistory(); + } catch (e) {} + try { + renderOverview(); + } catch (e) { + console.error("renderOverview", e); + } + try { + renderChat(); + } catch (e) { + console.error("renderChat", e); + } + try { + renderChatStarmap(); + } catch (e) { + console.error("renderChatStarmap", e); + } + try { + renderPlugins(); + } catch (e) { + console.error("renderPlugins", e); + } + try { + renderKernel(); + } catch (e) { + console.error("renderKernel", e); + } + try { + renderOneSettings(); + } catch (e) { + console.error("renderOneSettings", e); + } + try { + renderAdapters(); + } catch (e) { + console.error("renderAdapters", e); + } applyI18n(); + applyCardTilt(); +} + +// ===== 动效补齐:卡片 3D tilt + 光标光斑(事件委托,动态渲染后自动生效) ===== +function applyCardTilt() { + if (!window.matchMedia || window.matchMedia("(hover: none)").matches) return; + if (!document.body._tiltApplied) { + document.body._tiltApplied = true; + document.addEventListener("mousemove", onCardTiltMove); + document.addEventListener("mouseleave", (e) => { + var card = e.target.closest && e.target.closest(".card.tilt"); + if (card) card.style.transform = ""; + }); + } + // 给概览/插件/内核三类页面的卡片补上 tilt-glow 子元素并启用 tilt + var holders = ["#view-overview", "#view-plugins", "#view-kernel"]; + holders.forEach((sel) => { + var root = document.querySelector(sel); + if (!root) return; + root.querySelectorAll(".card").forEach((c) => { + if (c.classList.contains("tilt")) return; + if (!c.querySelector(".tilt-glow")) { + var g = document.createElement("span"); + g.className = "tilt-glow"; + c.appendChild(g); + } + c.classList.add("tilt"); + }); + }); +} + +function onCardTiltMove(e) { + var card = e.target.closest ? e.target.closest(".card.tilt") : null; + if (!card) return; + var r = card.getBoundingClientRect(); + if (r.width === 0 || r.height === 0) return; + card.style.setProperty("--mx", e.clientX - r.left + "px"); + card.style.setProperty("--my", e.clientY - r.top + "px"); + var rx = ((e.clientY - r.top) / r.height - 0.5) * -4; + var ry = ((e.clientX - r.left) / r.width - 0.5) * 4; + card.style.transform = + "perspective(1000px) rotateX(" + + rx.toFixed(2) + + "deg) rotateY(" + + ry.toFixed(2) + + "deg) translateY(-1px)"; } function fmtUptime(ms) { var s = Math.floor(ms / 1000); - if (s < 60) return s + 's'; - var m = Math.floor(s / 60); s = s % 60; - if (m < 60) return m + 'm ' + s + 's'; - var h = Math.floor(m / 60); m = m % 60; - return h + 'h ' + m + 'm ' + s + 's'; + if (s < 60) return s + "s"; + var m = Math.floor(s / 60); + s = s % 60; + if (m < 60) return m + "m " + s + "s"; + var h = Math.floor(m / 60); + m = m % 60; + return h + "h " + m + "m " + s + "s"; } var uptimeTick = null; function startUptimeTicker() { if (uptimeTick) clearInterval(uptimeTick); - uptimeTick = setInterval(function() { - var el = document.querySelector('#uptime-val'); + uptimeTick = setInterval(() => { + var el = document.querySelector("#uptime-val"); if (el && state.startedAt) { var now = Date.now(); el.textContent = fmtUptime(now - state.startedAt); } else if (!state.startedAt) { - var el2 = document.querySelector('#uptime-val'); - if (el2) el2.textContent = '-'; + var el2 = document.querySelector("#uptime-val"); + if (el2) el2.textContent = "-"; } }, 1000); } // ===== Overview ===== function statCard(l, v) { - return '
' + v + '
' + l + '
'; + return ( + '
' + + v + + '
' + + l + + "
" + ); } function renderOverview() { var s = state.status || {}; var k = state.kernel; - var html = '
' - + statCard(__('运行状态','Status'), s.status || 'unknown', 'running') - + statCard(__('运行时间','Uptime'), '' + (state.startedAt ? fmtUptime(Date.now() - state.startedAt) : '-') + '', 'uptime') - + statCard(__('插件','Plugins'), (k?.plugins || []).length || 0, 'plugin') - + statCard(__('版本','Version'), s.version || '0.1.0', 'version') - + '
'; + var html = + '
' + + statCard(__("运行状态", "Status"), s.status || "unknown", "running") + + statCard( + __("运行时间", "Uptime"), + '' + + (state.startedAt ? fmtUptime(Date.now() - state.startedAt) : "-") + + "", + "uptime", + ) + + statCard(__("插件", "Plugins"), (k?.plugins || []).length || 0, "plugin") + + statCard(__("版本", "Version"), s.version || "0.1.0", "version") + + "
"; if (k) { - html += '
' - + '

' + __('LLM 状态','LLM Status') + '

' - + '
Provider' + (k.llm?.provider || __('未配置','Not configured')) + '
' - + '
' + __('可用源','Sources') + '' + (k.llm?.sources || 0) + '
' - + '
' + __('状态','Status') + '' + (k.llm?.available ? __('运行中','Running') : __('不可用','Unavailable')) + '
' - + '
' - + '

' + __('记忆状态','Memory Status') + '

' - + '
' + __('图记忆','Graph Memory') + '' + (k.memory?.available ? k.memory.entity_count + __(' 实体, ',' entities, ') + k.memory.relation_count + __(' 关系',' relations') : __('未初始化','Uninitialized')) + '
' - + '
' + __('文档记忆','Document Memory') + '' + (k.documents?.available ? k.documents.doc_count + __(' 文档',' docs') : __('未初始化','Uninitialized')) + '
' - + '
' + __('文本记忆','Text Memory') + '' + (k.text_memory?.available ? k.text_memory.file_count + __(' 文件',' files') : __('未初始化','Uninitialized')) + '
' - + '
' + __('知识库','Knowledge') + '' + (k.knowledge?.available ? k.knowledge.item_count + __(' 项',' items') : __('未初始化','Uninitialized')) + '
' - + '
'; + html += + '
' + + '

' + + __("LLM 状态", "LLM Status") + + "

" + + '
Provider' + + (k.llm?.provider || __("未配置", "Not configured")) + + "
" + + '
' + + __("可用源", "Sources") + + '' + + (k.llm?.sources || 0) + + "
" + + '
' + + __("状态", "Status") + + '' + + (k.llm?.available + ? __("运行中", "Running") + : __("不可用", "Unavailable")) + + "
" + + "
" + + '

' + + __("记忆状态", "Memory Status") + + "

" + + '
' + + __("图记忆", "Graph Memory") + + '' + + (k.memory?.available + ? k.memory.entity_count + + __(" 实体, ", " entities, ") + + k.memory.relation_count + + __(" 关系", " relations") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("文档记忆", "Document Memory") + + '' + + (k.documents?.available + ? k.documents.doc_count + __(" 文档", " docs") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("文本记忆", "Text Memory") + + '' + + (k.text_memory?.available + ? k.text_memory.file_count + __(" 文件", " files") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("知识库", "Knowledge") + + '' + + (k.knowledge?.available + ? k.knowledge.item_count + __(" 项", " items") + : __("未初始化", "Uninitialized")) + + "
" + + "
"; } - html += '

' + __('运行时','Runtime') + '

' - + statCard('Goroutines', k?.runtime?.goroutines || '-', '') - + statCard(__('内存','Memory'), k?.runtime?.memory_mb ? k.runtime.memory_mb + ' MB' : '-', '') - + statCard('Go ' + __('版本','Version'), k?.runtime?.go_version || '-', '') - + '
'; - document.getElementById('view-overview').innerHTML = html; + html += + '

' + + __("运行时", "Runtime") + + '

' + + statCard("Goroutines", k?.runtime?.goroutines || "-", "") + + statCard( + __("内存", "Memory"), + k?.runtime?.memory_mb ? k.runtime.memory_mb + " MB" : "-", + "", + ) + + statCard("Go " + __("版本", "Version"), k?.runtime?.go_version || "-", "") + + "
"; + document.getElementById("view-overview").innerHTML = html; } // ===== Chat ===== var _chatLayoutBuilt = false; function buildChatLayout() { - var cont = document.getElementById('view-chat'); + var cont = document.getElementById("view-chat"); var k = state.kernel || {}; var html = '
'; - html += '
' - + '' + __('对话','Chat') + '' - + '' + __('星图','Star Map') + '' - + '' + __('终端','Terminal') + '' - + '' + __('运行中命令','Running Commands') + '' - + '' + __('记忆','Memory') + '' - + '' + __('上下文','Context') + '' - + '' + __('知识','Knowledge') + '' - + '
'; + html += + '
' + + '' + + __("对话", "Chat") + + "" + + "" + + __("星图", "Star Map") + + "" + + "" + + __("终端", "Terminal") + + "" + + "" + + __("运行中命令", "Running Commands") + + "" + + "" + + __("记忆", "Memory") + + "" + + "" + + __("上下文", "Context") + + "" + + "" + + __("知识", "Knowledge") + + "" + + "
"; if (!state.currentConn) { - html += '
' - + '' - + '

' + __('未配置后端','No backend configured') + '

' - + '

' + __('连接 HomeAgent 服务端后即可开始对话。请在设置中添加后端连接。','Connect to a HomeAgent server to start chatting. Add a backend connection in Settings.') + '

' - + '' - + '
'; + html += + '
' + + '' + + "

" + + __("未配置后端", "No backend configured") + + "

" + + "

" + + __( + "连接 HomeAgent 服务端后即可开始对话。请在设置中添加后端连接。", + "Connect to a HomeAgent server to start chatting. Add a backend connection in Settings.", + ) + + "

" + + '" + + "
"; for (var p2 = 0; p2 < 6; p2++) { - html += '

' + __('请先在设置中添加后端连接','Add a backend connection in Settings first') + '

'; + html += + '

' + + __( + "请先在设置中添加后端连接", + "Add a backend connection in Settings first", + ) + + "

"; } cont.innerHTML = html; _chatLayoutBuilt = true; return; } - html += '
'; - html += '

' + __('对话','Chat') + '

'; + html += + '
'; + html += + '

' + + __("对话", "Chat") + + '

'; if (state.messages.length === 0) { - html += '

' + __('开始与您的 HomeAgent 聊天吧','Start chatting with your HomeAgent') + '

'; + html += + '

' + + __("开始与您的 HomeAgent 聊天吧", "Start chatting with your HomeAgent") + + "

"; } - html += '
' - + '
' - + '' - + '' - + '
'; - html += '

' + __('星图','Star Map') + '

' - + '
'; - html += '

' + __('终端','Terminal') + ' 0

' - + '
'; - html += '

' + __('运行中命令','Running Commands') + ' 0

' - + '
'; - html += '

' + __('记忆','Memory') + '

' - + '
' + __('实体','Entities') + '' + (k?.memory?.entity_count || '-') + '
' - + '
' + __('关系','Relations') + '' + (k?.memory?.relation_count || '-') + '
' - + '
' - + '' - + '' - + '
' - + '
'; - html += '

' + __('上下文','Context') + '

' - + '
' - + '' - + '' - + '
' - + '
'; - html += '

' + __('知识','Knowledge') + '

' - + '
' + __('项目','Items') + '' + (k?.knowledge?.item_count || '-') + '
' - + '
' - + '' - + '' - + '
' - + '
' - + '' - + '' - + '' - + '
'; + html += + "
" + + '
' + + '' + + '" + + "
"; + html += + '

' + + __("星图", "Star Map") + + "

" + + '
'; + html += + '

' + + __("终端", "Terminal") + + ' 0

' + + '
'; + html += + '

' + + __("运行中命令", "Running Commands") + + ' 0

' + + '
'; + html += + '

' + + __("记忆", "Memory") + + "

" + + '
' + + __("实体", "Entities") + + '' + + (k?.memory?.entity_count || "-") + + "
" + + '
' + + __("关系", "Relations") + + '' + + (k?.memory?.relation_count || "-") + + "
" + + '
' + + '' + + '" + + '
' + + "
"; + html += + '

' + + __("上下文", "Context") + + "

" + + '
' + + '' + + '" + + '
' + + "
"; + html += + '

' + + __("知识", "Knowledge") + + "

" + + '
' + + __("项目", "Items") + + '' + + (k?.knowledge?.item_count || "-") + + "
" + + '
' + + '' + + '" + + '
' + + '
' + + '' + + '' + + '" + + "
"; cont.innerHTML = html; _chatLayoutBuilt = true; } -var CHAN_COLORS = ['#e08a5f', '#5f9fe0', '#6bbf8f', '#c06bbf', '#d9a13b', '#5fb3bf', '#b06b6b', '#7f8ce0']; +var CHAN_COLORS = [ + "#e08a5f", + "#5f9fe0", + "#6bbf8f", + "#c06bbf", + "#d9a13b", + "#5fb3bf", + "#b06b6b", + "#7f8ce0", +]; function chanColor(src) { var h = 0; @@ -531,196 +957,389 @@ function chanColor(src) { } function chanLetter(src) { - var s = (src || '').trim(); - if (!s) return 'C'; + var s = (src || "").trim(); + if (!s) return "C"; var ch = s.charAt(0).toUpperCase(); - return /[A-Za-z0-9]/.test(ch) ? ch : 'C'; + return /[A-Za-z0-9]/.test(ch) ? ch : "C"; } function renderChat() { - if (!_chatLayoutBuilt) { buildChatLayout(); renderChatStarmap(); renderTerminals(); renderCmdHistory() } - var msgsEl = document.getElementById('chat-msgs'); + if (!_chatLayoutBuilt) { + buildChatLayout(); + renderChatStarmap(); + renderTerminals(); + renderCmdHistory(); + } + var msgsEl = document.getElementById("chat-msgs"); if (!msgsEl) return; if (!msgsEl._stickBound) { msgsEl._stickBound = true; - msgsEl.addEventListener('scroll', function() { - state.chatStick = msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight < 80; - }, { passive: true }); + msgsEl.addEventListener( + "scroll", + () => { + state.chatStick = + msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight < 80; + }, + { passive: true }, + ); } var msgs = state.messages; - var sig = msgs.map(function(m) { - var c = m.content || ''; - return (m.role || '') + ':' + c.length + ':' + c.slice(-40) + ':' + (m.tool_calls || []).map(function(t) { return (t.tool || t.name || '') + '/' + (t.status || '') }).join(','); - }).join('|') + '|L' + (state.chatLoading ? '1' : '0') + '|P' + (state.pendingTools || []).join(','); - if (msgsEl._chatSig === sig && msgsEl.childElementCount > 0) { return; } + var sig = + msgs + .map((m) => { + var c = m.content || ""; + return ( + (m.role || "") + + ":" + + c.length + + ":" + + c.slice(-40) + + ":" + + (m.tool_calls || []) + .map((t) => (t.tool || t.name || "") + "/" + (t.status || "")) + .join(",") + ); + }) + .join("|") + + "|L" + + (state.chatLoading ? "1" : "0") + + "|P" + + (state.pendingTools || []).join(","); + if (msgsEl._chatSig === sig && msgsEl.childElementCount > 0) { + return; + } msgsEl._chatSig = sig; var prevPending = msgsEl._lastPending || []; var newPending = (state.pendingTools || []).slice(); var lastM = msgs.length ? msgs[msgs.length - 1] : null; - if (state.chatLoading && lastM && lastM.role === 'assistant') { - (lastM.tool_calls || []).forEach(function(tc) { - if (!tc.result && tc.status !== 'denied') { - var nm = tc.tool || tc.name || ''; + if (state.chatLoading && lastM && lastM.role === "assistant") { + (lastM.tool_calls || []).forEach((tc) => { + if (!tc.result && tc.status !== "denied") { + var nm = tc.tool || tc.name || ""; if (newPending.indexOf(nm) === -1) newPending.push(nm); } }); } - var newlyDone = prevPending.filter(function(n) { return newPending.indexOf(n) === -1; }); + var newlyDone = prevPending.filter((n) => newPending.indexOf(n) === -1); msgsEl._lastPending = newPending; - var streamingLast = !!(state.chatLoading && lastM && lastM.role === 'assistant' && !lastM._final); + var streamingLast = !!( + state.chatLoading && + lastM && + lastM.role === "assistant" && + !lastM._final + ); function pillHtml() { - var s = ''; - newPending.forEach(function(nm) { - var anim = prevPending.indexOf(nm) !== -1 ? '' : ' pill-in'; - s += '' - + '' - + escHtml(nm) + ''; + var s = ""; + newPending.forEach((nm) => { + var anim = prevPending.indexOf(nm) === -1 ? " pill-in" : ""; + s += + '' + + '' + + escHtml(nm) + + ""; }); return s; } - var html = ''; + var html = ""; if (msgs.length === 0) { - html = '

' + __('开始与您的 HomeAgent 聊天吧','Start chatting with your HomeAgent') + '

'; + html = + '

' + + __("开始与您的 HomeAgent 聊天吧", "Start chatting with your HomeAgent") + + "

"; } else { - msgs.forEach(function(m, i) { - var role = m.role || 'user'; - var c = m.content || ''; - if (role === 'assistant') { - if (typeof marked !== 'undefined') { c = marked.parse(c) } else { c = '
' + escHtml(c) + '
' } - } else if (role === 'system') { + msgs.forEach((m, i) => { + var role = m.role || "user"; + var c = m.content || ""; + if (role === "assistant") { + if (typeof marked === "undefined") { + c = "
" + escHtml(c) + "
"; + } else { + c = marked.parse(c); + } + } else if (role === "system") { c = escHtml(c); } else { c = escHtml(c); } - var isChan = !!(m.source && m.source !== 'webui'); - var rc = ''; + var isChan = !!(m.source && m.source !== "webui"); + var rc = ""; if (m.reasoning_content) { - var rcBody = (typeof marked !== 'undefined' ? marked.parse(m.reasoning_content) : escHtml(m.reasoning_content)); - rc = '
' - + '
' + __('展开思考','Expand') + '
' - + '
'; + var rcBody = + typeof marked === "undefined" + ? escHtml(m.reasoning_content) + : marked.parse(m.reasoning_content); + rc = + '
' + + "
" + + __("展开思考", "Expand") + + "
" + + '
"; } - var tcs = ''; + var tcs = ""; if (m.tool_calls && m.tool_calls.length > 0) { - m.tool_calls.forEach(function(tc) { - var argsStr = typeof tc.args === 'object' ? JSON.stringify(tc.args, null, 1) : (tc.args || ''); - var resultStr = tc.result ? (typeof tc.result === 'object' ? JSON.stringify(tc.result, null, 1) : String(tc.result)) : ''; - var statusIcon = tc.status === 'denied' - ? '' - : ''; - tcs += '
' - + '
' + statusIcon + '' + escHtml(tc.tool || tc.name || '') + '' - + (tc.status === 'denied' - ? '' + __('已拒绝','Denied') + '' - : (resultStr - ? '' + __('完成','Done') + '' - : '' + __('调用中','Running') + '')) - + '
' - + '
'; + m.tool_calls.forEach((tc) => { + var argsStr = + typeof tc.args === "object" + ? JSON.stringify(tc.args, null, 1) + : tc.args || ""; + var resultStr = tc.result + ? typeof tc.result === "object" + ? JSON.stringify(tc.result, null, 1) + : String(tc.result) + : ""; + var statusIcon = + tc.status === "denied" + ? '' + : ''; + tcs += + '
' + + '
' + + statusIcon + + '' + + escHtml(tc.tool || tc.name || "") + + "" + + (tc.status === "denied" + ? '' + + __("已拒绝", "Denied") + + "" + : resultStr + ? '' + + __("完成", "Done") + + "" + : '' + + __("调用中", "Running") + + "") + + '
' + + '
"; }); } var body = rc + tcs; - var growCls = m._grow ? ' grow-in' : ''; + var growCls = m._grow ? " grow-in" : ""; if (m._grow) m._grow = false; var isStreamingLast = i === msgs.length - 1 && streamingLast; if (isStreamingLast) { - var liveRow = '' + (newPending.length ? '' + pillHtml() + '' : ''); + var liveRow = + '' + + (newPending.length + ? '' + pillHtml() + "" + : ""); if (c) { - body += '
' + liveRow + '
' + c + '
'; - c = ''; + body += + '
' + + liveRow + + '
' + + c + + "
"; + c = ""; } else { - body += '
' + liveRow + '
'; + body += '
' + liveRow + "
"; } } else if (c) { - body += '
' + c + '
'; + body += + '
' + + c + + "
"; } - if (role === 'system') { - html += '
' + (c || '') + '
'; + if (role === "system") { + html += + '
' + + (c || "") + + "
"; } else if (isChan) { - html += '
' - + '
' + chanLetter(m.source) + '
' - + '
' + escHtml(m.source) + '
' + body + '
' - + '
'; + html += + '
' + + '
' + + chanLetter(m.source) + + "
" + + '
' + + escHtml(m.source) + + "
" + + body + + "
" + + "
"; } else { - var userAvatar = ''; - var aiAvatar = '' + __('小宅','Agent') + ''; - html += '
' - + '
' + (role === 'user' ? userAvatar : aiAvatar) + '
' - + '
' + body + '
' - + '
'; + var userAvatar = + ''; + var aiAvatar = + '' +
+          __('; + html += + '
' + + '
' + + (role === "user" ? userAvatar : aiAvatar) + + "
" + + '
' + + body + + "
" + + "
"; } }); } if (state.chatLoading && !streamingLast) { - var aiAvatar2 = '' + __('小宅','Agent') + ''; - html += '
' + aiAvatar2 + '
' - + '' - + (newPending.length ? '' + pillHtml() + '' : '') - + '
'; + var aiAvatar2 = + '' +
+      __('; + html += + '
' + + aiAvatar2 + + '
' + + '' + + (newPending.length + ? '' + pillHtml() + "" + : "") + + "
"; } msgsEl.innerHTML = html; - if (state.chatStick !== false) { try { msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: 'smooth' }) } catch(e) { msgsEl.scrollTop = msgsEl.scrollHeight } } + if (state.chatStick !== false) { + try { + msgsEl.scrollTo({ top: msgsEl.scrollHeight, behavior: "smooth" }); + } catch (e) { + msgsEl.scrollTop = msgsEl.scrollHeight; + } + } updateChatBadge(); if (window.homeagent && window.homeagent.log) { - window.homeagent.log('render: msgs=' + msgs.length + ' sig=' + sig.slice(0, 60) - + ' last=' + (lastM ? lastM.role + '/C=' + String(lastM.content || '').length + '/T=' + ((lastM.tool_calls || []).length) : 'none') - + ' roles=' + msgs.map(function(m){ return m.role + (m.content ? '#' + String(m.content).length : '') + (m.source ? '@' + m.source : '') + (m.tool_calls && m.tool_calls.length ? 'T' + m.tool_calls.length : '') }).join(',')); + window.homeagent.log( + "render: msgs=" + + msgs.length + + " sig=" + + sig.slice(0, 60) + + " last=" + + (lastM + ? lastM.role + + "/C=" + + String(lastM.content || "").length + + "/T=" + + (lastM.tool_calls || []).length + : "none") + + " roles=" + + msgs + .map( + (m) => + m.role + + (m.content ? "#" + String(m.content).length : "") + + (m.source ? "@" + m.source : "") + + (m.tool_calls && m.tool_calls.length + ? "T" + m.tool_calls.length + : ""), + ) + .join(","), + ); } } function guardedRenderChat() { - try { renderChat() } catch (e) { - if (window.homeagent && window.homeagent.log) window.homeagent.log('renderChat ERROR: ' + e.message + ' stack=' + (e.stack || '').split('\n').slice(0, 2).join(';')); - console.error('renderChat error', e); + try { + renderChat(); + } catch (e) { + if (window.homeagent && window.homeagent.log) + window.homeagent.log( + "renderChat ERROR: " + + e.message + + " stack=" + + (e.stack || "").split("\n").slice(0, 2).join(";"), + ); + console.error("renderChat error", e); } } function updateChatBadge() { - var badge = document.getElementById('chat-stage'); + var badge = document.getElementById("chat-stage"); if (!badge) return; - badge.textContent = state.chatStage || ''; - badge.style.display = 'none'; + badge.textContent = state.chatStage || ""; + badge.style.display = "none"; } -function rerenderChat() { guardedRenderChat(); renderChatStarmap(); renderTerminals(); renderCmdHistory() } +function rerenderChat() { + guardedRenderChat(); + renderChatStarmap(); + renderTerminals(); + renderCmdHistory(); +} function toggleToolCall(el) { - var d = el.querySelector('.tc-detail'); + var d = el.querySelector(".tc-detail"); if (!d) return; - var open = d.style.display !== 'none'; - d.style.display = open ? 'none' : 'block'; - if (open) { el.classList.remove('open'); } else { el.classList.add('open'); } + var open = d.style.display !== "none"; + d.style.display = open ? "none" : "block"; + if (open) { + el.classList.remove("open"); + } else { + el.classList.add("open"); + } } function renderChatStarmap() { - var cont = document.getElementById('sm-container-chat'); + var cont = document.getElementById("sm-container-chat"); if (!cont) return; - if (window._THREE_FAILED || (!window.THREE && window._THREE_FAILED !== undefined)) { - cont.innerHTML = '

' + __('3D 星图不可用(CDN 加载失败)','Star map unavailable (CDN load failed)') + '

'; + if ( + window._THREE_FAILED || + (!window.THREE && window._THREE_FAILED !== undefined) + ) { + cont.innerHTML = + '

' + + __( + "3D 星图不可用(CDN 加载失败)", + "Star map unavailable (CDN load failed)", + ) + + "

"; state.starmapInit = true; state.starmapLoading = false; return; } if (!window.THREE) { - cont.innerHTML = '
'; + cont.innerHTML = + '
'; state.starmapInit = false; state.starmapLoading = false; return; } - if (cont.querySelector('canvas')) { + if (cont.querySelector("canvas")) { var rect = cont.getBoundingClientRect(); - if (starmapRen && rect.width > 0) starmapRen.setSize(rect.width, Math.max(rect.height, 250)); + if (starmapRen && rect.width > 0) + starmapRen.setSize(rect.width, Math.max(rect.height, 250)); return; } if (state.starmapInit) { if (starmapRen) { var rect = cont.getBoundingClientRect(); - if (rect.width > 0) starmapRen.setSize(rect.width, Math.max(rect.height, 250)); + if (rect.width > 0) + starmapRen.setSize(rect.width, Math.max(rect.height, 250)); cont.appendChild(starmapRen.domElement); - starmapRen.domElement.style.display = 'block'; + starmapRen.domElement.style.display = "block"; } else { // starmapRen was destroyed (e.g. re-render cycle), restart state.starmapInit = false; @@ -735,11 +1354,18 @@ function renderChatStarmap() { async function loadChatStarmapData() { try { - var resp = await api('/memory/graph'); - if (!resp || !resp.success || !resp.data || !resp.data.nodes || resp.data.nodes.length === 0) { - document.getElementById('sm-container-chat').innerHTML - = '

' - + __('暂无记忆数据','No memory data') + '

'; + var resp = await api("/memory/graph"); + if ( + !resp || + !resp.success || + !resp.data || + !resp.data.nodes || + resp.data.nodes.length === 0 + ) { + document.getElementById("sm-container-chat").innerHTML = + '

' + + __("暂无记忆数据", "No memory data") + + "

"; state.starmapInit = true; state.starmapLoading = false; return; @@ -750,10 +1376,11 @@ async function loadChatStarmapData() { state.starmapInit = true; state.starmapLoading = false; initChatStarmap(); - } catch(e) { - document.getElementById('sm-container-chat').innerHTML - = '

' - + __('加载失败','Load failed') + '

'; + } catch (e) { + document.getElementById("sm-container-chat").innerHTML = + '

' + + __("加载失败", "Load failed") + + "

"; state.starmapInit = true; state.starmapLoading = false; } @@ -764,7 +1391,7 @@ function getStarmapBg() { } function initChatStarmap() { - var cont = document.getElementById('sm-container-chat'); + var cont = document.getElementById("sm-container-chat"); if (!cont) return; var rect = cont.getBoundingClientRect(); var w = Math.max(rect.width || 300, 100); @@ -772,7 +1399,7 @@ function initChatStarmap() { if (starmapRen) { starmapRen.setSize(w, h); cont.appendChild(starmapRen.domElement); - starmapRen.domElement.style.display = 'block'; + starmapRen.domElement.style.display = "block"; return; } starmapScene = new THREE.Scene(); @@ -783,7 +1410,7 @@ function initChatStarmap() { starmapRen.setSize(w, h); starmapRen.setPixelRatio(Math.min(window.devicePixelRatio, 2)); starmapRen.setClearColor(0x0a0a1a, 1); - cont.innerHTML = ''; + cont.innerHTML = ""; cont.appendChild(starmapRen.domElement); starmapCtrl = new THREE.OrbitControls(starmapCam, starmapRen.domElement); starmapCtrl.enableDamping = true; @@ -798,40 +1425,52 @@ function initChatStarmap() { createStarField(); createNebula(); buildChatStarmapGraph(); - starmapRen.domElement.addEventListener('mousemove', onStarmapMove); - starmapRen.domElement.addEventListener('click', onStarmapClick); - window.addEventListener('resize', onStarmapResize); + starmapRen.domElement.addEventListener("mousemove", onStarmapMove); + starmapRen.domElement.addEventListener("click", onStarmapClick); + window.addEventListener("resize", onStarmapResize); if (starmapRaf) cancelAnimationFrame(starmapRaf); starmapAnimate(); } function buildChatStarmapGraph() { - starmapNodeMeshes.forEach(function(m) { starmapScene.remove(m) }); - starmapEdgeLines.forEach(function(l) { starmapScene.remove(l) }); + starmapNodeMeshes.forEach((m) => { + starmapScene.remove(m); + }); + starmapEdgeLines.forEach((l) => { + starmapScene.remove(l); + }); starmapNodeMeshes = []; starmapEdgeLines = []; if (starmapNodes.length === 0) return; // Calculate node degrees for leaf node detection var nodeDegs = {}; - starmapNodes.forEach(function(n) { nodeDegs[n.id] = 0 }); - starmapEdges.forEach(function(e) { + starmapNodes.forEach((n) => { + nodeDegs[n.id] = 0; + }); + starmapEdges.forEach((e) => { nodeDegs[e.source_id] = (nodeDegs[e.source_id] || 0) + 1; nodeDegs[e.target_id] = (nodeDegs[e.target_id] || 0) + 1; }); var nodeMap = {}; - starmapNodes.forEach(function(n) { nodeMap[n.id] = n }); - var sorted = starmapNodes.slice().sort(function(a, b) { - return (b.mention_count || 0) - (a.mention_count || 0); + starmapNodes.forEach((n) => { + nodeMap[n.id] = n; }); - var mc = sorted.map(function(n) { return n.mention_count || 0 }); - var maxMc = Math.max(...mc, 1), minMc = Math.min(...mc, 0), rng = maxMc - minMc || 1; + var sorted = starmapNodes + .slice() + .sort((a, b) => (b.mention_count || 0) - (a.mention_count || 0)); + var mc = sorted.map((n) => n.mention_count || 0); + var maxMc = Math.max(...mc, 1), + minMc = Math.min(...mc, 0), + rng = maxMc - minMc || 1; // Layout positions var pos = {}; - var baseR = 15, maxR = 80; + var baseR = 15, + maxR = 80; var total = sorted.length; var acc = 0; - sorted.forEach(function(n, i) { - var m = n.mention_count || 0, mn = rng > 0 ? (m - minMc) / rng : 0; + sorted.forEach((n, i) => { + var m = n.mention_count || 0, + mn = rng > 0 ? (m - minMc) / rng : 0; var radius = baseR + mn * (maxR - baseR); var baseStep = (Math.PI * 2) / total; var extra = mn * baseStep * 2; @@ -842,19 +1481,22 @@ function buildChatStarmapGraph() { y: (Math.random() - 0.5) * (10 + mn * 20), z: radius * Math.sin(angle), mn: mn, - rad: radius + rad: radius, }; }); // Leaf nodes (degree 1) reposition near parent - sorted.forEach(function(n) { + sorted.forEach((n) => { var deg = nodeDegs[n.id] || 0; if (deg !== 1) return; - var edge = starmapEdges.find(function(e) { return e.source_id === n.id || e.target_id === n.id }); + var edge = starmapEdges.find( + (e) => e.source_id === n.id || e.target_id === n.id, + ); if (!edge) return; var parentId = edge.source_id === n.id ? edge.target_id : edge.source_id; if (!pos[parentId]) return; var pp = pos[parentId]; - var m = n.mention_count || 0, mn = rng > 0 ? (m - minMc) / rng : 0; + var m = n.mention_count || 0, + mn = rng > 0 ? (m - minMc) / rng : 0; var off = 6 + mn * 8 + Math.random() * 4; var a2 = Math.random() * Math.PI * 2; pos[n.id] = { @@ -862,7 +1504,7 @@ function buildChatStarmapGraph() { y: pp.y + (Math.random() - 0.5) * (4 + mn * 6), z: pp.z + off * Math.sin(a2), mn: mn, - rad: off + rad: off, }; }); // Force-directed simulation @@ -871,46 +1513,73 @@ function buildChatStarmapGraph() { // Repulsion for (var i = 0; i < ids.length; i++) { for (var j = i + 1; j < ids.length; j++) { - var a = pos[ids[i]], b = pos[ids[j]]; - var dx = a.x - b.x, dy = a.y - b.y, dz = a.z - b.z, d = Math.sqrt(dx*dx + dy*dy + dz*dz) + 0.1; + var a = pos[ids[i]], + b = pos[ids[j]]; + var dx = a.x - b.x, + dy = a.y - b.y, + dz = a.z - b.z, + d = Math.sqrt(dx * dx + dy * dy + dz * dz) + 0.1; var rf = 0.5 + (a.mn + b.mn) * 0.5; if (d < 25) { var force = (0.06 * rf) / Math.max(d, 0.5); - a.x += dx / d * force; a.y += dy / d * force; a.z += dz / d * force; - b.x -= dx / d * force; b.y -= dy / d * force; b.z -= dz / d * force; + a.x += (dx / d) * force; + a.y += (dy / d) * force; + a.z += (dz / d) * force; + b.x -= (dx / d) * force; + b.y -= (dy / d) * force; + b.z -= (dz / d) * force; } } } // Attraction along edges - starmapEdges.forEach(function(e) { - var a = pos[e.source_id], b = pos[e.target_id]; + starmapEdges.forEach((e) => { + var a = pos[e.source_id], + b = pos[e.target_id]; if (!a || !b) return; - var dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z, d = Math.sqrt(dx*dx + dy*dy + dz*dz) + 0.1; + var dx = b.x - a.x, + dy = b.y - a.y, + dz = b.z - a.z, + d = Math.sqrt(dx * dx + dy * dy + dz * dz) + 0.1; var af = Math.max(0.3, 1.0 - (a.mn + b.mn) * 0.3); if (d > 20) { var force = 0.04 * af; - a.x += dx / d * force; a.y += dy / d * force; a.z += dz / d * force; - b.x -= dx / d * force; b.y -= dy / d * force; b.z -= dz / d * force; + a.x += (dx / d) * force; + a.y += (dy / d) * force; + a.z += (dz / d) * force; + b.x -= (dx / d) * force; + b.y -= (dy / d) * force; + b.z -= (dz / d) * force; } }); // Centering constraint - ids.forEach(function(id) { + ids.forEach((id) => { var p = pos[id]; var dist = Math.sqrt(p.x * p.x + p.y * p.y + p.z * p.z); var maxA = maxR * 1.5; - if (dist > maxA) { var s = maxA / dist; p.x *= s; p.y *= s; p.z *= s } + if (dist > maxA) { + var s = maxA / dist; + p.x *= s; + p.y *= s; + p.z *= s; + } }); } // Create nodes - starmapNodes.forEach(function(n) { + starmapNodes.forEach((n) => { var p = pos[n.id]; if (!p) return; - var mn = n.mention_count || 0, mnr = rng > 0 ? (mn - minMc) / rng : 0; + var mn = n.mention_count || 0, + mnr = rng > 0 ? (mn - minMc) / rng : 0; var rad = 0.5 + mnr * 2.0; var col = smTypeColors[n.type] || 0xcccccc; var ei = 0.3 + mnr * 0.7; var g = new THREE.SphereGeometry(rad, 16, 12); - var mat = new THREE.MeshPhongMaterial({ color: col, emissive: col, emissiveIntensity: ei, shininess: 30 }); + var mat = new THREE.MeshPhongMaterial({ + color: col, + emissive: col, + emissiveIntensity: ei, + shininess: 30, + }); var mesh = new THREE.Mesh(g, mat); mesh.position.set(p.x, p.y, p.z); mesh.userData.nodeData = n; @@ -919,26 +1588,39 @@ function buildChatStarmapGraph() { // Glow sphere var gr = rad * 1.2 + mnr * 0.5; var gg = new THREE.SphereGeometry(gr, 16, 12); - var gm = new THREE.MeshBasicMaterial({ color: col, transparent: true, opacity: 0.12 + mnr * 0.08, side: THREE.BackSide, blending: THREE.AdditiveBlending }); + var gm = new THREE.MeshBasicMaterial({ + color: col, + transparent: true, + opacity: 0.12 + mnr * 0.08, + side: THREE.BackSide, + blending: THREE.AdditiveBlending, + }); var gs = new THREE.Mesh(gg, gm); mesh.add(gs); mesh.userData.glowSphere = gs; // Label sprite - var canvas = document.createElement('canvas'); + var canvas = document.createElement("canvas"); canvas.width = 256; canvas.height = 64; - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, 256, 64); - ctx.font = 'Bold 24px Courier New'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - ctx.shadowColor = '#aaccff'; + ctx.font = "Bold 24px Courier New"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.shadowColor = "#aaccff"; ctx.shadowBlur = 8; - ctx.fillStyle = '#ffffff'; + ctx.fillStyle = "#ffffff"; ctx.fillText((n.name || n.id).substring(0, 12), 128, 32); var tex = new THREE.CanvasTexture(canvas); tex.needsUpdate = true; - var spMat = new THREE.SpriteMaterial({ map: tex, transparent: true, opacity: 0.9, depthTest: false, depthWrite: false, blending: THREE.AdditiveBlending }); + var spMat = new THREE.SpriteMaterial({ + map: tex, + transparent: true, + opacity: 0.9, + depthTest: false, + depthWrite: false, + blending: THREE.AdditiveBlending, + }); var sprite = new THREE.Sprite(spMat); sprite.scale.set(8, 2, 1); sprite.position.y = rad + 2; @@ -947,16 +1629,21 @@ function buildChatStarmapGraph() { starmapNodeMeshes.push(mesh); }); // Create edges - starmapEdges.forEach(function(e) { - var a = pos[e.source_id], b = pos[e.target_id]; + starmapEdges.forEach((e) => { + var a = pos[e.source_id], + b = pos[e.target_id]; if (!a || !b) return; var col = smEdgeColors[e.relation_type] || smEdgeColors[e.type] || 0x444466; var pts = [ new THREE.Vector3(a.x, a.y, a.z), - new THREE.Vector3(b.x, b.y, b.z) + new THREE.Vector3(b.x, b.y, b.z), ]; var geo = new THREE.BufferGeometry().setFromPoints(pts); - var mat = new THREE.LineBasicMaterial({ color: col, transparent: true, opacity: 0.4 }); + var mat = new THREE.LineBasicMaterial({ + color: col, + transparent: true, + opacity: 0.4, + }); var line = new THREE.Line(geo, mat); line.userData = { edgeId: e.id, edgeData: e }; starmapScene.add(line); @@ -965,166 +1652,256 @@ function buildChatStarmapGraph() { } async function sendChat() { - var inp = document.getElementById('chat-input'); - var btn = document.getElementById('chat-send-btn'); + var inp = document.getElementById("chat-input"); + var btn = document.getElementById("chat-send-btn"); var text = inp.value.trim(); if (!text || state.chatLoading) return; state.chatStick = true; state.chatFinalIdx = -1; - state.messages.push({ role: 'user', content: text }); - inp.value = ''; + state.messages.push({ role: "user", content: text }); + inp.value = ""; rerenderChat(); state.chatLoading = true; - state.chatStage = __('等待AI回复...','Waiting for AI...'); + state.chatStage = __("等待AI回复...", "Waiting for AI..."); btn.disabled = true; - btn.textContent = ''; + btn.textContent = ""; rerenderChat(); try { - var r = await api('/chat', { method: 'POST', body: JSON.stringify({ message: text }), timeout: 120000 }); - state.chatStage = ''; + var r = await api("/chat", { + method: "POST", + body: JSON.stringify({ message: text }), + timeout: 120000, + }); + state.chatStage = ""; var last = state.messages[state.messages.length - 1]; - console.log('[sendChat] POST returned, last msg:', last ? {role:last.role, _streaming:last._streaming, _final:last._final, tool_calls:last.tool_calls?.length, content_len:last.content?.length} : null); - if (last && last.role === 'assistant' && last._streaming) { - console.log('[sendChat] updating existing streaming msg, tool_calls before:', last.tool_calls?.length); - last.content = r.response || __('(无响应)','(no response)'); + console.log( + "[sendChat] POST returned, last msg:", + last + ? { + role: last.role, + _streaming: last._streaming, + _final: last._final, + tool_calls: last.tool_calls?.length, + content_len: last.content?.length, + } + : null, + ); + if (last && last.role === "assistant" && last._streaming) { + console.log( + "[sendChat] updating existing streaming msg, tool_calls before:", + last.tool_calls?.length, + ); + last.content = r.response || __("(无响应)", "(no response)"); last._grow = true; - if (!last.reasoning_content) last.reasoning_content = r.reasoning_content || ''; + if (!last.reasoning_content) + last.reasoning_content = r.reasoning_content || ""; last._final = true; delete last._streaming; } else { state.messages.push({ - role: 'assistant', - content: r.response || __('(无响应)','(no response)'), + role: "assistant", + content: r.response || __("(无响应)", "(no response)"), reasoning_content: r.reasoning_content, - tool_calls: last && last.role === 'assistant' && last.tool_calls ? last.tool_calls : [], + tool_calls: + last && last.role === "assistant" && last.tool_calls + ? last.tool_calls + : [], _final: true, - _grow: true + _grow: true, }); } state.chatFinalIdx = state.messages.length - 1; rerenderChat(); - } catch(e) { - state.messages.push({ role: 'assistant', content: __('错误: ','Error: ') + e.message, _final: true }); + } catch (e) { + state.messages.push({ + role: "assistant", + content: __("错误: ", "Error: ") + e.message, + _final: true, + }); rerenderChat(); - toast(__('请求失败: ','Request failed: ') + e.message, true); + toast(__("请求失败: ", "Request failed: ") + e.message, true); } finally { state.chatLoading = false; - state.chatStage = ''; + state.chatStage = ""; btn.disabled = false; - btn.textContent = __('发送','Send'); + btn.textContent = __("发送", "Send"); rerenderChat(); } } async function queryMemoryChat() { - var q = document.getElementById('mem-query')?.value; - var r = document.getElementById('mem-result-chat'); + var q = document.getElementById("mem-query")?.value; + var r = document.getElementById("mem-result-chat"); if (!r || !q) return; r.innerHTML = '
'; try { - var data = await api('/memory?q=' + encodeURIComponent(q) + '&depth=2'); - r.innerHTML = '
' + escHtml(JSON.stringify(data, null, 2)) + '
'; - } catch(e) { - r.innerHTML = '

' + __('查询失败: ','Query failed: ') + escHtml(e.message) + '

'; + var data = await api("/memory?q=" + encodeURIComponent(q) + "&depth=2"); + r.innerHTML = + '
' +
+      escHtml(JSON.stringify(data, null, 2)) +
+      "
"; + } catch (e) { + r.innerHTML = + '

' + + __("查询失败: ", "Query failed: ") + + escHtml(e.message) + + "

"; } } async function queryMemoryContext() { - var q = document.getElementById('ctx-query')?.value; - var r = document.getElementById('ctx-result'); + var q = document.getElementById("ctx-query")?.value; + var r = document.getElementById("ctx-result"); if (!r) return; r.innerHTML = '
'; try { - var data = await api('/memory/context?q=' + encodeURIComponent(q || '')); - var ctx = data?.context || __('无上下文','No context'); - var summary = data?.summary || ''; + var data = await api("/memory/context?q=" + encodeURIComponent(q || "")); + var ctx = data?.context || __("无上下文", "No context"); + var summary = data?.summary || ""; var entities = data?.entities || []; var tk = data?.token_estimate || 0; var html = '
'; - if (summary) html += '
' + __('摘要','Summary') + '' + escHtml(summary) + '
'; - html += '
Token ' + __('预估','Estimate') + '' + tk + '
'; + if (summary) + html += + '
' + + __("摘要", "Summary") + + '' + + escHtml(summary) + + "
"; + html += + '
Token ' + + __("预估", "Estimate") + + '' + + tk + + "
"; if (entities.length) { - html += '
' + __('实体','Entities') + '' - + entities.map(function(e) { return escHtml(e.name || e.id || '') }).join(', ') - + '
'; + html += + '
' + + __("实体", "Entities") + + '' + + entities.map((e) => escHtml(e.name || e.id || "")).join(", ") + + "
"; } - html += '
' + escHtml(ctx) + '
'; + html += + '
' +
+      escHtml(ctx) +
+      "
"; r.innerHTML = html; - } catch(e) { - r.innerHTML = '

' + __('获取失败: ','Get failed: ') + escHtml(e.message) + '

'; + } catch (e) { + r.innerHTML = + '

' + + __("获取失败: ", "Get failed: ") + + escHtml(e.message) + + "

"; } } async function searchKnowledgeChat() { - var q = document.getElementById('know-query')?.value; - var r = document.getElementById('know-result-chat'); + var q = document.getElementById("know-query")?.value; + var r = document.getElementById("know-result-chat"); if (!r || !q) return; r.innerHTML = '
'; try { - var data = await api('/knowledge?q=' + encodeURIComponent(q)); - r.innerHTML = '
' + escHtml(JSON.stringify(data, null, 2)) + '
'; - } catch(e) { - r.innerHTML = '

' + __('搜索失败: ','Search failed: ') + escHtml(e.message) + '

'; + var data = await api("/knowledge?q=" + encodeURIComponent(q)); + r.innerHTML = + '
' +
+      escHtml(JSON.stringify(data, null, 2)) +
+      "
"; + } catch (e) { + r.innerHTML = + '

' + + __("搜索失败: ", "Search failed: ") + + escHtml(e.message) + + "

"; } } async function createKnowledgeChat() { - var name = document.getElementById('know-name')?.value; - var content = document.getElementById('know-content')?.value; - if (!name || !content) { toast(__('名称和内容不能为空','Name and content cannot be empty'), true); return } + var name = document.getElementById("know-name")?.value; + var content = document.getElementById("know-content")?.value; + if (!name || !content) { + toast(__("名称和内容不能为空", "Name and content cannot be empty"), true); + return; + } try { - var r = await api('/knowledge', { method: 'POST', body: JSON.stringify({ name: name, content: content }) }); + var r = await api("/knowledge", { + method: "POST", + body: JSON.stringify({ name: name, content: content }), + }); if (r.status || r.id) { - toast(__('知识「','Knowledge "') + name + __('」已创建','" created')); - document.getElementById('know-name').value = ''; - document.getElementById('know-content').value = ''; + toast(__("知识「", 'Knowledge "') + name + __("」已创建", '" created')); + document.getElementById("know-name").value = ""; + document.getElementById("know-content").value = ""; } else { - toast(__('创建失败','Create failed'), true); + toast(__("创建失败", "Create failed"), true); } - } catch(e) { - toast(__('创建失败: ','Create failed: ') + e.message, true); + } catch (e) { + toast(__("创建失败: ", "Create failed: ") + e.message, true); } } function switchChatPanel(tab, el) { var panels = { - 'chat': document.getElementById('chat-panel-chat'), - 'starmap': document.getElementById('chat-panel-starmap'), - 'terminal': document.getElementById('chat-panel-terminal'), - 'cmd': document.getElementById('chat-panel-cmd'), - 'memory': document.getElementById('chat-panel-memory'), - 'context': document.getElementById('chat-panel-context'), - 'knowledge': document.getElementById('chat-panel-knowledge') + chat: document.getElementById("chat-panel-chat"), + starmap: document.getElementById("chat-panel-starmap"), + terminal: document.getElementById("chat-panel-terminal"), + cmd: document.getElementById("chat-panel-cmd"), + memory: document.getElementById("chat-panel-memory"), + context: document.getElementById("chat-panel-context"), + knowledge: document.getElementById("chat-panel-knowledge"), }; - Object.keys(panels).forEach(function(k) { + Object.keys(panels).forEach((k) => { var p = panels[k]; - if (p) p.classList.toggle('active', k === tab); + if (p) p.classList.toggle("active", k === tab); }); if (el) { var parent = el.parentElement; if (parent) { - Array.from(parent.children).forEach(function(ch) { ch.classList.remove('active') }); - el.classList.add('active'); + Array.from(parent.children).forEach((ch) => { + ch.classList.remove("active"); + }); + el.classList.add("active"); } } - if (tab === 'starmap') { renderChatStarmap(); onStarmapResize(); } - if (tab === 'terminal') renderTerminals(); - if (tab === 'cmd') renderCmdHistory(); - if (tab === 'memory') queryMemoryChat(); - if (tab === 'context') queryMemoryContext(); - if (tab === 'knowledge') searchKnowledgeChat(); + if (tab === "starmap") { + renderChatStarmap(); + onStarmapResize(); + } + if (tab === "terminal") renderTerminals(); + if (tab === "cmd") renderCmdHistory(); + if (tab === "memory") queryMemoryChat(); + if (tab === "context") queryMemoryContext(); + if (tab === "knowledge") searchKnowledgeChat(); } async function loadChatHistory() { - try { var data = await api('/chat/history'); if (data && data.messages) { state.messages = data.messages; if (window.homeagent && window.homeagent.log) window.homeagent.log('history: loaded ' + data.messages.length); } else if (window.homeagent && window.homeagent.log) { window.homeagent.log('history: no messages field'); } } catch(e) { if (window.homeagent && window.homeagent.log) window.homeagent.log('history: error ' + e.message) } + try { + var data = await api("/chat/history"); + if (data && data.messages) { + state.messages = data.messages; + if (window.homeagent && window.homeagent.log) + window.homeagent.log("history: loaded " + data.messages.length); + } else if (window.homeagent && window.homeagent.log) { + window.homeagent.log("history: no messages field"); + } + } catch (e) { + if (window.homeagent && window.homeagent.log) + window.homeagent.log("history: error " + e.message); + } } async function loadTerminals() { - try { var data = await api('/terminals'); if (data && data.terminals) state.terminals = data.terminals } catch(e) {} + try { + var data = await api("/terminals"); + if (data && data.terminals) state.terminals = data.terminals; + } catch (e) {} } async function loadCmdHistory() { - try { var data = await api('/cmd/history'); if (data && data.history) state.cmdHistory = data.history } catch(e) {} + try { + var data = await api("/cmd/history"); + if (data && data.history) state.cmdHistory = data.history; + } catch (e) {} } function appendTermBuf(el, text) { @@ -1137,66 +1914,129 @@ function appendTermBuf(el, text) { } function renderTerminals() { - var r = document.getElementById('term-list'); - var cnt = document.getElementById('term-count-badge'); + var r = document.getElementById("term-list"); + var cnt = document.getElementById("term-count-badge"); if (!r) return; var list = state.terminals || []; if (cnt) cnt.textContent = list.length; if (list.length === 0) { - r.innerHTML = '

' + __('暂无终端会话','No terminal sessions') + '

'; + r.innerHTML = + '

' + + __("暂无终端会话", "No terminal sessions") + + "

"; return; } - var html = ''; - list.forEach(function(t, i) { - var detailId = 'term-detail-' + i; + var html = ""; + list.forEach((t, i) => { + var detailId = "term-detail-" + i; var scr = (state.termScreens && state.termScreens[t.id]) || null; var running = scr ? scr.running : !!t.running; - var fullOut = scr ? scr.output : t.output || ''; - if (!fullOut) { - fullOut = '' + __('[终端暂无输出]','[No terminal output]') + ''; - } else { + var fullOut = scr ? scr.output : t.output || ""; + if (fullOut) { fullOut = escHtml(fullOut); + } else { + fullOut = + '' + + __("[终端暂无输出]", "[No terminal output]") + + ""; } - html += '
'; - html += '
'; - html += '' + escHtml(t.id || '-') + ''; - html += '' + escHtml(t.command || '') + ''; - html += '' + (running ? __('运行中','Running') : __('已关闭','Closed')) + ''; - html += '' + escHtml(t.created_at || '') + ''; - html += '
'; - html += '
"; }); r.innerHTML = html; } function renderCmdHistory() { - var r = document.getElementById('cmd-list'); - var cnt = document.getElementById('cmd-count-badge'); + var r = document.getElementById("cmd-list"); + var cnt = document.getElementById("cmd-count-badge"); if (!r) return; - var running = (state.terminals || []).filter(function(t) { return t.running; }); + var running = (state.terminals || []).filter((t) => t.running); if (cnt) cnt.textContent = running.length; if (running.length === 0) { - r.innerHTML = '

' + __('暂无运行中的命令','No running commands') + '

'; + r.innerHTML = + '

' + + __("暂无运行中的命令", "No running commands") + + "

"; return; } - var html = ''; - running.forEach(function(t) { + var html = + '
' + __('命令','Command') + '' + __('状态','Status') + '' + __('运行时长','Uptime') + '
"; + running.forEach((t) => { var scr = (state.termScreens && state.termScreens[t.id]) || null; - var out = scr ? scr.output : t.output || ''; - html += '' - + '' - + '' - + '' - + ''; + var out = scr ? scr.output : t.output || ""; + html += + "" + + '" + + '" + + '" + + ""; if (out) { - html += ''; + html += + '"; } }); - html += '
' + + __("命令", "Command") + + "" + + __("状态", "Status") + + "" + + __("运行时长", "Uptime") + + "
' + escHtml(t.command || t.id || '') + '' + __('运行中','Running') + '' + escHtml(t.uptime || '-') + '
' + + escHtml(t.command || t.id || "") + + "' + + __("运行中", "Running") + + "' + + escHtml(t.uptime || "-") + + "
' + escHtml(out.substring(0, 2000)) + '
' +
+        escHtml(out.substring(0, 2000)) +
+        "
'; + html += ""; r.innerHTML = html; } @@ -1206,200 +2046,467 @@ function renderPlugins() { var plugins = k?.plugins || []; var tools = k?.tools || []; var installed = state.installedPlugins || []; - var html = '

' + __('安装插件','Install Plugin') + '

' - + '
' - + '' - + '
' - + '
' - + '
'; - var installedNames = (state.installedPlugins || []).map(function(p) { return p.name }); + var html = + '

' + + __("安装插件", "Install Plugin") + + "

" + + '
' + + '' + + '
" + + '
' + + '
"; + var installedNames = (state.installedPlugins || []).map((p) => p.name); var disabledNames = {}; - (state.disabledPlugins || []).forEach(function(d) { disabledNames[d.name] = d; }); - html += '

' + __('已加载插件','Loaded Plugins') + ' (' + plugins.length + ')

'; + (state.disabledPlugins || []).forEach((d) => { + disabledNames[d.name] = d; + }); + html += + '

' + + __("已加载插件", "Loaded Plugins") + + " (" + + plugins.length + + ")

"; if (plugins.length === 0 && (state.disabledPlugins || []).length === 0) { - html += '

' + __('暂无已加载插件','No loaded plugins') + '

'; + html += + '

' + + __("暂无已加载插件", "No loaded plugins") + + "

"; } else { - html += ''; + html += + "
' + __('名称','Name') + '' + __('状态','Status') + '' + __('操作','Actions') + '
"; var allNames = {}; - plugins.forEach(function(p) { allNames[p.name] = true; }); - (state.disabledPlugins || []).forEach(function(d) { allNames[d.name] = true; }); - Object.keys(allNames).sort().forEach(function(name) { - var loaded = plugins.some(function(p) { return p.name === name }); - var isDisabled = !!disabledNames[name]; - var isExternal = installedNames.indexOf(name) >= 0; - var statusHtml = loaded && !isDisabled - ? '' + __('已加载','Loaded') + '' - : loaded && isDisabled - ? '' + __('运行中(禁用待生效)','Running (disable pending)') + '' - : isDisabled - ? '' + __('已禁用','Disabled') + '' - : '' + __('未加载','Not Loaded') + ''; - var actionsHtml = ''; - if (loaded && !isDisabled) { - actionsHtml += ''; - } - if (isDisabled) { - actionsHtml += ''; - } - if (loaded && isExternal) { - actionsHtml += ''; - } else if (loaded) { - actionsHtml += '' + __('内置','Built-in') + ''; - } - html += '' - + '' - + ''; + plugins.forEach((p) => { + allNames[p.name] = true; }); - html += '
" + + __("名称", "Name") + + "" + + __("状态", "Status") + + "" + + __("操作", "Actions") + + "
' + escHtml(name) + '' + statusHtml + '' + actionsHtml + '
'; + (state.disabledPlugins || []).forEach((d) => { + allNames[d.name] = true; + }); + Object.keys(allNames) + .sort() + .forEach((name) => { + var loaded = plugins.some((p) => p.name === name); + var isDisabled = !!disabledNames[name]; + var isExternal = installedNames.indexOf(name) >= 0; + var statusHtml = + loaded && !isDisabled + ? '' + + __("已加载", "Loaded") + + "" + : loaded && isDisabled + ? '' + + __("运行中(禁用待生效)", "Running (disable pending)") + + "" + : isDisabled + ? '' + + __("已禁用", "Disabled") + + "" + : '' + + __("未加载", "Not Loaded") + + ""; + var actionsHtml = ""; + if (loaded && !isDisabled) { + actionsHtml += + '"; + } + if (isDisabled) { + actionsHtml += + '"; + } + if (loaded && isExternal) { + actionsHtml += + '"; + } else if (loaded) { + actionsHtml += + '' + + __("内置", "Built-in") + + ""; + } + html += + "" + + escHtml(name) + + "" + + "" + + statusHtml + + "" + + "" + + actionsHtml + + ""; + }); + html += ""; } - html += '
'; + html += "
"; if (installed.length > 0) { - html += '

' + __('已安装外部插件','Installed Plugins') + ' (' + installed.length + ')

' - + ''; - installed.forEach(function(p) { - html += '' - + '' - + '' - + ''; + html += + '

' + + __("已安装外部插件", "Installed Plugins") + + " (" + + installed.length + + ")

" + + "
' + __('名称','Name') + '' + __('版本','Version') + '' + __('描述','Description') + '' + __('操作','Actions') + '
' + escHtml(p.name) + '' + escHtml(p.version || '-') + '' + escHtml((p.description || '').substring(0, 50)) + ' ' - + '
"; + installed.forEach((p) => { + html += + "" + + "" + + "" + + '"; }); - html += '
" + + __("名称", "Name") + + "" + + __("版本", "Version") + + "" + + __("描述", "Description") + + "" + + __("操作", "Actions") + + "
" + + escHtml(p.name) + + "" + + escHtml(p.version || "-") + + "" + + escHtml((p.description || "").substring(0, 50)) + + " " + + '
'; + html += ""; } if (state.pluginInfo) { - html += '

' + __('插件详情','Plugin Details') + ': ' + escHtml(state.pluginInfo.name) + '

' - + '
' + escHtml(JSON.stringify(state.pluginInfo, null, 2)) + '
' - + '
'; + html += + '

' + + __("插件详情", "Plugin Details") + + ": " + + escHtml(state.pluginInfo.name) + + "

" + + "
" +
+      escHtml(JSON.stringify(state.pluginInfo, null, 2)) +
+      "
" + + '
"; } if (tools.length > 0) { - html += '

' + __('已注册工具','Registered Tools') + ' (' + tools.length + ')

' - + '
'; - tools.forEach(function(t) { - html += '' + escHtml(t.name) + ''; + html += + '

' + + __("已注册工具", "Registered Tools") + + " (" + + tools.length + + ")

" + + '
'; + tools.forEach((t) => { + html += + '' + + escHtml(t.name) + + ""; }); - html += '
'; + html += "
"; } - html += '

' + __('系统操作','System Operations') + '

' - + '' - + '
'; - html += '

' + __('健康检查','Health Check') + '

'; + html += + '

' + + __("系统操作", "System Operations") + + "

" + + '" + + '
"; + html += + '

' + + __("健康检查", "Health Check") + + '

'; if (state.healthResult) { html += renderHealthResult(state.healthResult); } else { - html += '

' + __('点击上方按钮运行','Click the button above to run') + '

'; + html += + '

' + + __("点击上方按钮运行", "Click the button above to run") + + "

"; } - html += '
'; - document.getElementById('view-plugins').innerHTML = html; + html += "
"; + document.getElementById("view-plugins").innerHTML = html; } async function loadInstalledPlugins() { - try { state.installedPlugins = await api('/plugins') } catch(e) { state.installedPlugins = [] } + try { + state.installedPlugins = await api("/plugins"); + } catch (e) { + state.installedPlugins = []; + } } async function installPlugin() { - var inp = document.getElementById('plugin-url'); + var inp = document.getElementById("plugin-url"); var url = inp?.value.trim(); - if (!url) { toast(__('请输入插件包 URL','Please enter plugin URL'), true); return } + if (!url) { + toast(__("请输入插件包 URL", "Please enter plugin URL"), true); + return; + } try { - var r = await api('/plugins', { method: 'POST', body: JSON.stringify({ url: url }) }); - toast(__('安装结果: ','Install result: ') + (r.status || JSON.stringify(r))); - if (r.action === 'reload_required') toast(__('已安装,请点击「重载插件」加载','Installed, click "Reload Plugins" to load'), false); - loadInstalledPlugins(); renderPlugins(); - } catch(e) { toast(__('安装失败: ','Install failed: ') + e.message, true) } + var r = await api("/plugins", { + method: "POST", + body: JSON.stringify({ url: url }), + }); + toast( + __("安装结果: ", "Install result: ") + (r.status || JSON.stringify(r)), + ); + if (r.action === "reload_required") + toast( + __( + "已安装,请点击「重载插件」加载", + 'Installed, click "Reload Plugins" to load', + ), + false, + ); + loadInstalledPlugins(); + renderPlugins(); + } catch (e) { + toast(__("安装失败: ", "Install failed: ") + e.message, true); + } } async function installPluginFile(file) { if (!file) return; try { - var r = await fetch('/api/v1/plugins', { method: 'POST', body: file, headers: { 'Content-Type': 'application/octet-stream' } }); + var r = await fetch("/api/v1/plugins", { + method: "POST", + body: file, + headers: { "Content-Type": "application/octet-stream" }, + }); var data = await r.json(); - toast(__('上传安装: ','Upload install: ') + (data.status || JSON.stringify(data))); - if (data.action === 'reload_required') toast(__('已安装,请点击「重载插件」加载','Installed, click "Reload Plugins" to load'), false); - loadInstalledPlugins(); renderPlugins(); - } catch(e) { toast(__('上传失败: ','Upload failed: ') + e.message, true) } + toast( + __("上传安装: ", "Upload install: ") + + (data.status || JSON.stringify(data)), + ); + if (data.action === "reload_required") + toast( + __( + "已安装,请点击「重载插件」加载", + 'Installed, click "Reload Plugins" to load', + ), + false, + ); + loadInstalledPlugins(); + renderPlugins(); + } catch (e) { + toast(__("上传失败: ", "Upload failed: ") + e.message, true); + } } async function showPluginInfo(name) { - try { state.pluginInfo = await api('/plugins/' + encodeURIComponent(name)); renderPlugins() } catch(e) { toast(__('获取详情失败: ','Get details failed: ') + e.message, true) } + try { + state.pluginInfo = await api("/plugins/" + encodeURIComponent(name)); + renderPlugins(); + } catch (e) { + toast(__("获取详情失败: ", "Get details failed: ") + e.message, true); + } } -function closePluginInfo() { state.pluginInfo = null; renderPlugins() } +function closePluginInfo() { + state.pluginInfo = null; + renderPlugins(); +} async function removePlugin(name) { - if (!confirm(__('确定卸载插件','Are you sure to unload plugin') + '「' + name + '」?')) return; + if ( + !(await confirmDialog( + __("确定卸载插件", "Are you sure to unload plugin") + + "「" + + name + + "」?", + true, + )) + ) + return; try { - var r = await api('/plugins/' + encodeURIComponent(name), { method: 'DELETE' }); - toast(__('已卸载: ','Unloaded: ') + (r.status || r.name)); - if (r.action === 'reload_required') toast(__('已卸载,请点击「重载插件」生效','Unloaded, click "Reload Plugins" to apply'), false); - loadInstalledPlugins(); renderPlugins(); - } catch(e) { toast(__('卸载失败: ','Unload failed: ') + e.message, true) } + var r = await api("/plugins/" + encodeURIComponent(name), { + method: "DELETE", + }); + toast(__("已卸载: ", "Unloaded: ") + (r.status || r.name)); + if (r.action === "reload_required") + toast( + __( + "已卸载,请点击「重载插件」生效", + 'Unloaded, click "Reload Plugins" to apply', + ), + false, + ); + loadInstalledPlugins(); + renderPlugins(); + } catch (e) { + toast(__("卸载失败: ", "Unload failed: ") + e.message, true); + } } async function disablePlugin(name) { - if (name === 'webui') { - var r = confirm(__('禁用 WebUI 后将无法通过 URL:端口访问此管理面板,若要重新启用需要通过 CLI 命令 /plugin enable webui 恢复。\n\n确定要禁用吗?','Disabling WebUI will make this management panel inaccessible via URL:port. To re-enable, use CLI command /plugin enable webui.\n\nAre you sure?')); + if (name === "webui") { + var r = await confirmDialog( + __( + "禁用 WebUI 后将无法通过 URL:端口访问此管理面板,若要重新启用需要通过 CLI 命令 /plugin enable webui 恢复。\n\n确定要禁用吗?", + "Disabling WebUI will make this management panel inaccessible via URL:port. To re-enable, use CLI command /plugin enable webui.\n\nAre you sure?", + ), + true, + ); if (!r) return; } try { - await api('/plugins/' + encodeURIComponent(name) + '/disable', { method: 'POST' }); - toast(__('已禁用: ','Disabled: ') + name); - state.kernel = await api('/kernel'); - var s = await api('/settings'); + await api("/plugins/" + encodeURIComponent(name) + "/disable", { + method: "POST", + }); + toast(__("已禁用: ", "Disabled: ") + name); + state.kernel = await api("/kernel"); + var s = await api("/settings"); state.disabledPlugins = s.disabled_plugins || []; renderPlugins(); - } catch(e) { toast(__('禁用失败: ','Disable failed: ') + e.message, true) } + } catch (e) { + toast(__("禁用失败: ", "Disable failed: ") + e.message, true); + } } async function enablePlugin(name) { try { - await api('/plugins/' + encodeURIComponent(name) + '/enable', { method: 'POST' }); - toast(__('已启用: ','Enabled: ') + name); - state.kernel = await api('/kernel'); - var s = await api('/settings'); + await api("/plugins/" + encodeURIComponent(name) + "/enable", { + method: "POST", + }); + toast(__("已启用: ", "Enabled: ") + name); + state.kernel = await api("/kernel"); + var s = await api("/settings"); state.disabledPlugins = s.disabled_plugins || []; renderPlugins(); - } catch(e) { toast(__('启用失败: ','Enable failed: ') + e.message, true) } + } catch (e) { + toast(__("启用失败: ", "Enable failed: ") + e.message, true); + } } async function reloadPlugins() { try { - var r = await api('/plugins/reload', { method: 'POST' }); - toast(__('插件已重载','Plugins reloaded')); - state.kernel = await api('/kernel'); + var r = await api("/plugins/reload", { method: "POST" }); + toast(__("插件已重载", "Plugins reloaded")); + state.kernel = await api("/kernel"); renderPlugins(); - } catch(e) { toast(__('重载失败: ','Reload failed: ') + e.message, true) } + } catch (e) { + toast(__("重载失败: ", "Reload failed: ") + e.message, true); + } } async function runHealthcheck() { - var panel = document.getElementById('health-panel'); + var panel = document.getElementById("health-panel"); if (!panel) return; - panel.innerHTML = '

' + __('运行中...','Running...') + '

'; + panel.innerHTML = + '

' + + __("运行中...", "Running...") + + "

"; try { - var r = await api('/kernel'); + var r = await api("/kernel"); var tools = r?.tools || []; - var healthTool = tools.find(function(t) { return t.name === 'healthcheck' }); - if (!healthTool) { panel.innerHTML = '

' + __('healthcheck 工具未注册','healthcheck tool not registered') + '

'; return } - panel.innerHTML = '

' + __('通过 Agent 对话触发 healthcheck...','Triggering healthcheck via Agent...') + '

'; - var chatR = await api('/chat', { method: 'POST', body: JSON.stringify({ message: __('请运行 healthcheck 工具进行全面健康检查并报告结果','Please run the healthcheck tool for a full system check and report the results') }) }); - panel.innerHTML = '
' + escHtml(JSON.stringify(chatR, null, 2)) + '
'; - } catch(e) { panel.innerHTML = '

' + __('错误: ','Error: ') + escHtml(e.message) + '

'; toast(__('健康检查失败: ','Health check failed: ') + e.message, true) } + var healthTool = tools.find((t) => t.name === "healthcheck"); + if (!healthTool) { + panel.innerHTML = + '

' + + __("healthcheck 工具未注册", "healthcheck tool not registered") + + "

"; + return; + } + panel.innerHTML = + '

' + + __( + "通过 Agent 对话触发 healthcheck...", + "Triggering healthcheck via Agent...", + ) + + "

"; + var chatR = await api("/chat", { + method: "POST", + body: JSON.stringify({ + message: __( + "请运行 healthcheck 工具进行全面健康检查并报告结果", + "Please run the healthcheck tool for a full system check and report the results", + ), + }), + }); + panel.innerHTML = + "
" + escHtml(JSON.stringify(chatR, null, 2)) + "
"; + } catch (e) { + panel.innerHTML = + '

' + + __("错误: ", "Error: ") + + escHtml(e.message) + + "

"; + toast(__("健康检查失败: ", "Health check failed: ") + e.message, true); + } } function renderHealthResult(r) { - if (!r || !r.checks) return '

' + __('暂无健康检查数据','No health check data') + '

'; + if (!r || !r.checks) + return ( + '

' + + __("暂无健康检查数据", "No health check data") + + "

" + ); var checks = r.checks || []; - var passed = checks.filter(function(c) { return c.pass }).length; - var failed = checks.filter(function(c) { return !c.pass }).length; - var html = '
' - + '' + __('通过: ','Pass: ') + passed + '' - + '' + __('失败: ','Fail: ') + failed + '' - + '' + __('总计: ','Total: ') + checks.length + '
'; - checks.forEach(function(c) { - var passClass = c.pass ? 'check-pass' : 'check-fail'; - if (c.status === 'skip') passClass = 'check-skip'; - html += '
' - + '' + escHtml(c.name) + '' - + '' + (c.status || 'unknown') + '' - + '' + escHtml(c.detail || '') + '
'; + var passed = checks.filter((c) => c.pass).length; + var failed = checks.filter((c) => !c.pass).length; + var html = + '
' + + '' + + __("通过: ", "Pass: ") + + passed + + "" + + '' + + __("失败: ", "Fail: ") + + failed + + "" + + '' + + __("总计: ", "Total: ") + + checks.length + + "
"; + checks.forEach((c) => { + var passClass = c.pass ? "check-pass" : "check-fail"; + if (c.status === "skip") passClass = "check-skip"; + html += + '
' + + '' + + escHtml(c.name) + + "" + + '' + + (c.status || "unknown") + + "" + + '' + + escHtml(c.detail || "") + + "
"; }); return html; } @@ -1407,63 +2514,161 @@ function renderHealthResult(r) { // ===== Kernel ===== function renderKernel() { var k = state.kernel; - if (!k) { document.getElementById('view-kernel').innerHTML = '

' + __('内核未响应','Kernel not responding') + '

'; return } - var html = '

' + __('运行时','Runtime') + '

' - + statCard('Goroutines', k?.runtime?.goroutines || '-', '') - + statCard(__('内存','Memory'), k?.runtime?.memory_mb ? k.runtime.memory_mb + ' MB' : '-', '') - + statCard('Go ' + __('版本','Version'), k?.runtime?.go_version || '-', '') - + '
'; - html += '

LLM

' - + '
Provider' + (k.llm?.provider || __('未配置','Not configured')) + '
' - + '
' + __('可用源','Sources') + '' + (k.llm?.sources || 0) + '
' - + '
' + __('状态','Status') + '' + (k.llm?.available ? __('运行中','Running') : __('不可用','Unavailable')) + '
'; - html += '

' + __('记忆','Memory') + '

' - + '
' + __('图记忆','Graph Memory') + '' + (k.memory?.available ? k.memory.entity_count + __(' 实体, ',' entities, ') + k.memory.relation_count + __(' 关系',' relations') : __('未初始化','Uninitialized')) + '
' - + '
' + __('文档记忆','Document Memory') + '' + (k.documents?.available ? k.documents.doc_count + __(' 文档',' docs') : __('未初始化','Uninitialized')) + '
' - + '
' + __('文本记忆','Text Memory') + '' + (k.text_memory?.available ? k.text_memory.file_count + __(' 文件',' files') : __('未初始化','Uninitialized')) + '
' - + '
' + __('知识库','Knowledge') + '' + (k.knowledge?.available ? k.knowledge.item_count + __(' 项',' items') : __('未初始化','Uninitialized')) + '
'; - html += '

' + __('插件','Plugins') + ' (' + (k.plugins?.length || 0) + ')

'; + if (!k) { + document.getElementById("view-kernel").innerHTML = + '

' + + __("内核未响应", "Kernel not responding") + + "

"; + return; + } + var html = + '

' + + __("运行时", "Runtime") + + '

' + + statCard("Goroutines", k?.runtime?.goroutines || "-", "") + + statCard( + __("内存", "Memory"), + k?.runtime?.memory_mb ? k.runtime.memory_mb + " MB" : "-", + "", + ) + + statCard("Go " + __("版本", "Version"), k?.runtime?.go_version || "-", "") + + "
"; + html += + '

LLM

' + + '
Provider' + + (k.llm?.provider || __("未配置", "Not configured")) + + "
" + + '
' + + __("可用源", "Sources") + + '' + + (k.llm?.sources || 0) + + "
" + + '
' + + __("状态", "Status") + + '' + + (k.llm?.available ? __("运行中", "Running") : __("不可用", "Unavailable")) + + "
"; + html += + '

' + + __("记忆", "Memory") + + "

" + + '
' + + __("图记忆", "Graph Memory") + + '' + + (k.memory?.available + ? k.memory.entity_count + + __(" 实体, ", " entities, ") + + k.memory.relation_count + + __(" 关系", " relations") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("文档记忆", "Document Memory") + + '' + + (k.documents?.available + ? k.documents.doc_count + __(" 文档", " docs") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("文本记忆", "Text Memory") + + '' + + (k.text_memory?.available + ? k.text_memory.file_count + __(" 文件", " files") + : __("未初始化", "Uninitialized")) + + "
" + + '
' + + __("知识库", "Knowledge") + + '' + + (k.knowledge?.available + ? k.knowledge.item_count + __(" 项", " items") + : __("未初始化", "Uninitialized")) + + "
"; + html += + '

' + + __("插件", "Plugins") + + " (" + + (k.plugins?.length || 0) + + ")

"; if (k.plugins?.length) { html += '
'; - k.plugins.forEach(function(p) { html += '' + escHtml(p.name) + '' }); - html += '
'; + k.plugins.forEach((p) => { + html += '' + escHtml(p.name) + ""; + }); + html += "
"; } else { - html += '

' + __('无','None') + '

'; + html += '

' + __("无", "None") + "

"; } - html += '
'; - document.getElementById('view-kernel').innerHTML = html; + html += ""; + document.getElementById("view-kernel").innerHTML = html; } // ===== Star Map ===== -var starmapScene = null, starmapCam = null, starmapRen = null, starmapCtrl = null; -var starmapNodes = [], starmapEdges = []; -var starmapNodeMeshes = [], starmapEdgeLines = [], starmapStarField = null; -var starmapHovered = null, starmapSelected = null, starmapAutoView = true; +var starmapScene = null, + starmapCam = null, + starmapRen = null, + starmapCtrl = null; +var starmapNodes = [], + starmapEdges = []; +var starmapNodeMeshes = [], + starmapEdgeLines = [], + starmapStarField = null; +var starmapHovered = null, + starmapSelected = null, + starmapAutoView = true; var starmapRaf = null; -var smTypeColors = { person: 0x4488ff, task: 0xff8844, ai: 0xaa44ff, concept: 0x44ff88, object: 0xff4444 }; -var smEdgeColors = { '喜欢': 0xff6b6b, '学习': 0x4ecdc4, '属于': 0x45b7d1, '相关': 0x96ceb4, '使用': 0xfeca57, '创建': 0xff9ff3 }; +var smTypeColors = { + person: 0x4488ff, + task: 0xff8844, + ai: 0xaa44ff, + concept: 0x44ff88, + object: 0xff4444, +}; +var smEdgeColors = { + 喜欢: 0xff6b6b, + 学习: 0x4ecdc4, + 属于: 0x45b7d1, + 相关: 0x96ceb4, + 使用: 0xfeca57, + 创建: 0xff9ff3, +}; function createStarField() { var c = 3000; - var p = new Float32Array(c * 3), cl = new Float32Array(c * 3), s = new Float32Array(c); + var p = new Float32Array(c * 3), + cl = new Float32Array(c * 3), + s = new Float32Array(c); for (var i = 0; i < c; i++) { var i3 = i * 3; - var r = 400 + Math.random() * 600, th = Math.random() * Math.PI * 2, ph = Math.acos(2 * Math.random() - 1); + var r = 400 + Math.random() * 600, + th = Math.random() * Math.PI * 2, + ph = Math.acos(2 * Math.random() - 1); p[i3] = r * Math.sin(ph) * Math.cos(th); p[i3 + 1] = r * Math.sin(ph) * Math.sin(th); p[i3 + 2] = r * Math.cos(ph); if (Math.random() < 0.7) { - cl[i3] = 0.8 + Math.random() * 0.2; cl[i3 + 1] = 0.8 + Math.random() * 0.2; cl[i3 + 2] = 1; + cl[i3] = 0.8 + Math.random() * 0.2; + cl[i3 + 1] = 0.8 + Math.random() * 0.2; + cl[i3 + 2] = 1; } else { - cl[i3] = 1; cl[i3 + 1] = 0.9 + Math.random() * 0.1; cl[i3 + 2] = 0.8 + Math.random() * 0.2; + cl[i3] = 1; + cl[i3 + 1] = 0.9 + Math.random() * 0.1; + cl[i3 + 2] = 0.8 + Math.random() * 0.2; } s[i] = 0.5 + Math.random() * 2; } var g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.BufferAttribute(p, 3)); - g.setAttribute('color', new THREE.BufferAttribute(cl, 3)); - g.setAttribute('size', new THREE.BufferAttribute(s, 1)); - var m = new THREE.PointsMaterial({ size: 1.5, vertexColors: true, transparent: true, opacity: 0.8, sizeAttenuation: true }); + g.setAttribute("position", new THREE.BufferAttribute(p, 3)); + g.setAttribute("color", new THREE.BufferAttribute(cl, 3)); + g.setAttribute("size", new THREE.BufferAttribute(s, 1)); + var m = new THREE.PointsMaterial({ + size: 1.5, + vertexColors: true, + transparent: true, + opacity: 0.8, + sizeAttenuation: true, + }); starmapStarField = new THREE.Points(g, m); starmapScene.add(starmapStarField); } @@ -1471,11 +2676,14 @@ function createStarField() { function onStarmapMove(e) { if (!starmapRen || !starmapCam) return; var rect = starmapRen.domElement.getBoundingClientRect(); - var mouse = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1); + var mouse = new THREE.Vector2( + ((e.clientX - rect.left) / rect.width) * 2 - 1, + -((e.clientY - rect.top) / rect.height) * 2 + 1, + ); var rc = new THREE.Raycaster(); rc.setFromCamera(mouse, starmapCam); var hits = rc.intersectObjects(starmapNodeMeshes); - var infoEl = document.getElementById('starmap-info'); + var infoEl = document.getElementById("starmap-info"); if (hits.length > 0) { var n = hits[0].object; if (starmapHovered !== n) { @@ -1484,31 +2692,44 @@ function onStarmapMove(e) { n.scale.set(1.2, 1.2, 1.2); var nd = n.userData.nodeData; if (infoEl) { - var e1 = document.getElementById('sm-info-name'); if (e1) e1.textContent = nd.name || ''; - var e2 = document.getElementById('sm-info-type'); if (e2) e2.textContent = nd.type || ''; - var e3 = document.getElementById('sm-info-mentions'); if (e3) e3.textContent = (nd.mention_count || 0) + ''; - var lk = starmapEdges.filter(function(e) { return e.source_id === nd.id || e.target_id === nd.id }).length; - var e4 = document.getElementById('sm-info-links'); if (e4) e4.textContent = lk + ''; - infoEl.style.display = 'block'; + var e1 = document.getElementById("sm-info-name"); + if (e1) e1.textContent = nd.name || ""; + var e2 = document.getElementById("sm-info-type"); + if (e2) e2.textContent = nd.type || ""; + var e3 = document.getElementById("sm-info-mentions"); + if (e3) e3.textContent = (nd.mention_count || 0) + ""; + var lk = starmapEdges.filter( + (e) => e.source_id === nd.id || e.target_id === nd.id, + ).length; + var e4 = document.getElementById("sm-info-links"); + if (e4) e4.textContent = lk + ""; + infoEl.style.display = "block"; } } } else { - if (starmapHovered) { starmapHovered.scale.set(1, 1, 1); starmapHovered = null } - if (!starmapSelected && infoEl) infoEl.style.display = 'none'; + if (starmapHovered) { + starmapHovered.scale.set(1, 1, 1); + starmapHovered = null; + } + if (!starmapSelected && infoEl) infoEl.style.display = "none"; } } function onStarmapClick(e) { if (!starmapRen || !starmapCam) return; var rect = starmapRen.domElement.getBoundingClientRect(); - var mouse = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1); + var mouse = new THREE.Vector2( + ((e.clientX - rect.left) / rect.width) * 2 - 1, + -((e.clientY - rect.top) / rect.height) * 2 + 1, + ); var rc = new THREE.Raycaster(); rc.setFromCamera(mouse, starmapCam); var hits = rc.intersectObjects(starmapNodeMeshes); if (hits.length > 0) { var n = hits[0].object; - starmapSelected = (starmapSelected === n) ? null : n; - if (starmapAutoView && starmapSelected) flyStarmapTo(starmapSelected.userData.nodeId, 500); + starmapSelected = starmapSelected === n ? null : n; + if (starmapAutoView && starmapSelected) + flyStarmapTo(starmapSelected.userData.nodeId, 500); onStarmapMove(e); } else { starmapSelected = null; @@ -1517,13 +2738,17 @@ function onStarmapClick(e) { function flyStarmapTo(nodeId, dur) { if (!starmapAutoView) return; - var m = starmapNodeMeshes.find(function(x) { return x.userData.nodeId === nodeId }); + var m = starmapNodeMeshes.find((x) => x.userData.nodeId === nodeId); if (!m) return; - var tp = m.position.clone(), sp = starmapCam.position.clone(), st = starmapCtrl.target.clone(); - var dist = tp.length() + 25, ep = new THREE.Vector3(tp.x, tp.y + dist * 0.4, tp.z + dist * 0.8); + var tp = m.position.clone(), + sp = starmapCam.position.clone(), + st = starmapCtrl.target.clone(); + var dist = tp.length() + 25, + ep = new THREE.Vector3(tp.x, tp.y + dist * 0.4, tp.z + dist * 0.8); var t0 = Date.now(); (function lerp() { - var t = Math.min((Date.now() - t0) / dur, 1), e = 1 - Math.pow(1 - t, 3); + var t = Math.min((Date.now() - t0) / dur, 1), + e = 1 - (1 - t) ** 3; starmapCam.position.lerpVectors(sp, ep, e); starmapCtrl.target.lerpVectors(st, tp, e); if (t < 1) requestAnimationFrame(lerp); @@ -1535,26 +2760,37 @@ function onStarmapResize() { var cont = starmapRen.domElement.parentElement; if (!cont) return; var rect = cont.getBoundingClientRect(); - var w = rect.width || 800, h = Math.max(rect.height || 250, 100); - if (w > 0 && h > 0) { starmapCam.aspect = w / h; starmapCam.updateProjectionMatrix(); starmapRen.setSize(w, h) } + var w = rect.width || 800, + h = Math.max(rect.height || 250, 100); + if (w > 0 && h > 0) { + starmapCam.aspect = w / h; + starmapCam.updateProjectionMatrix(); + starmapRen.setSize(w, h); + } } function toggleStarmapAuto() { starmapAutoView = !starmapAutoView; - var b = document.getElementById('sm-auto-btn'); - if (b) b.className = starmapAutoView ? 'on' : ''; + var b = document.getElementById("sm-auto-btn"); + if (b) b.className = starmapAutoView ? "on" : ""; } function resetStarmapCamera() { if (!starmapCam || !starmapCtrl || !starmapNodeMeshes) return; var maxD = 0; - starmapNodeMeshes.forEach(function(m) { var d = m.position.length(); if (d > maxD) maxD = d }); + starmapNodeMeshes.forEach((m) => { + var d = m.position.length(); + if (d > maxD) maxD = d; + }); if (maxD < 1) maxD = 30; var td = Math.min(Math.max(maxD + 20, 30), 150); - var sp = starmapCam.position.clone(), ep = new THREE.Vector3(td * 0.9, td * 0.6, td * 0.9); - var st = starmapCtrl.target.clone(), t0 = Date.now(); + var sp = starmapCam.position.clone(), + ep = new THREE.Vector3(td * 0.9, td * 0.6, td * 0.9); + var st = starmapCtrl.target.clone(), + t0 = Date.now(); (function lerp() { - var t = Math.min((Date.now() - t0) / 400, 1), e = 1 - Math.pow(1 - t, 3); + var t = Math.min((Date.now() - t0) / 400, 1), + e = 1 - (1 - t) ** 3; starmapCam.position.lerpVectors(sp, ep, e); starmapCtrl.target.lerpVectors(st, new THREE.Vector3(0, 0, 0), e); if (t < 1) requestAnimationFrame(lerp); @@ -1565,225 +2801,510 @@ function starmapAnimate() { starmapRaf = requestAnimationFrame(starmapAnimate); if (starmapCtrl) starmapCtrl.update(); if (starmapStarField) starmapStarField.rotation.y += 0.0001; - if (starmapRen && starmapScene && starmapCam) starmapRen.render(starmapScene, starmapCam); + if (starmapRen && starmapScene && starmapCam) + starmapRen.render(starmapScene, starmapCam); } function createNebula() { var nc = 500; - var p = new Float32Array(nc * 3), cl = new Float32Array(nc * 3); + var p = new Float32Array(nc * 3), + cl = new Float32Array(nc * 3); for (var i = 0; i < nc; i++) { var i3 = i * 3; p[i3] = (Math.random() - 0.5) * 800; - p[i3+1] = (Math.random() - 0.5) * 800; - p[i3+2] = (Math.random() - 0.5) * 800; + p[i3 + 1] = (Math.random() - 0.5) * 800; + p[i3 + 2] = (Math.random() - 0.5) * 800; var ch = Math.random(); if (ch < 0.33) { - cl[i3]=0.5+Math.random()*0.3; cl[i3+1]=0.2+Math.random()*0.2; cl[i3+2]=0.7+Math.random()*0.3; + cl[i3] = 0.5 + Math.random() * 0.3; + cl[i3 + 1] = 0.2 + Math.random() * 0.2; + cl[i3 + 2] = 0.7 + Math.random() * 0.3; } else if (ch < 0.66) { - cl[i3]=0.2+Math.random()*0.2; cl[i3+1]=0.3+Math.random()*0.3; cl[i3+2]=0.8+Math.random()*0.2; + cl[i3] = 0.2 + Math.random() * 0.2; + cl[i3 + 1] = 0.3 + Math.random() * 0.3; + cl[i3 + 2] = 0.8 + Math.random() * 0.2; } else { - cl[i3]=0.7+Math.random()*0.3; cl[i3+1]=0.2+Math.random()*0.2; cl[i3+2]=0.5+Math.random()*0.3; + cl[i3] = 0.7 + Math.random() * 0.3; + cl[i3 + 1] = 0.2 + Math.random() * 0.2; + cl[i3 + 2] = 0.5 + Math.random() * 0.3; } } var g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.BufferAttribute(p, 3)); - g.setAttribute('color', new THREE.BufferAttribute(cl, 3)); - var m = new THREE.PointsMaterial({ size: 8, vertexColors: true, transparent: true, opacity: 0.15, sizeAttenuation: true, blending: THREE.AdditiveBlending }); + g.setAttribute("position", new THREE.BufferAttribute(p, 3)); + g.setAttribute("color", new THREE.BufferAttribute(cl, 3)); + var m = new THREE.PointsMaterial({ + size: 8, + vertexColors: true, + transparent: true, + opacity: 0.15, + sizeAttenuation: true, + blending: THREE.AdditiveBlending, + }); var np = new THREE.Points(g, m); starmapScene.add(np); } // ===== Settings ===== function pluginDisplayName(p) { - if (p === 'core') return __('核心', 'Core'); - var name = p.replace('plugin.', ''); + if (p === "core") return __("核心", "Core"); + var name = p.replace("plugin.", ""); var meta = state.pluginMeta && state.pluginMeta[name]; - if (meta) return state.lang === 'en' ? (meta.name_en || name) : (meta.name_zh || name); + if (meta) + return state.lang === "en" ? meta.name_en || name : meta.name_zh || name; return name; } function renderSettingsTabs() { - var el = document.getElementById('settings-tabs'); + var el = document.getElementById("settings-tabs"); if (!el) return; - el.innerHTML = ''; - state.settingsPlugins.forEach(function(p) { - var s = document.createElement('span'); + el.innerHTML = ""; + state.settingsPlugins.forEach((p) => { + var s = document.createElement("span"); s.textContent = pluginDisplayName(p); - if (p === state.selectedSection) s.className = 'active'; - s.onclick = function() { state.selectedSection = p; renderOneSettings() }; + if (p === state.selectedSection) s.className = "active"; + s.onclick = () => { + state.selectedSection = p; + renderOneSettings(); + }; el.appendChild(s); }); } function renderOneSettings() { - var prefix = state.selectedSection + '.'; + var prefix = state.selectedSection + "."; var allKeys = Object.keys(state.settings || {}); - var filtered = allKeys.filter(function(k) { return k === prefix.slice(0, -1) || k.startsWith(prefix) }); + var filtered = allKeys.filter( + (k) => k === prefix.slice(0, -1) || k.startsWith(prefix), + ); filtered.sort(); - var hideTopLlms = ['core.llm.base_url','core.llm.model','core.llm.api_key','core.llm.adapter','core.llm.adapter_path','core.llm.thinking_enabled']; - var sourceKeys = filtered.filter(function(k) { return k.startsWith('core.llm.sources.') }); + var hideTopLlms = [ + "core.llm.base_url", + "core.llm.model", + "core.llm.api_key", + "core.llm.adapter", + "core.llm.adapter_path", + "core.llm.thinking_enabled", + ]; + var sourceKeys = filtered.filter((k) => k.startsWith("core.llm.sources.")); var sourceMap = {}; - sourceKeys.forEach(function(k) { - var parts = k.split('.'); + sourceKeys.forEach((k) => { + var parts = k.split("."); var srcName = parts[3]; if (!sourceMap[srcName]) sourceMap[srcName] = {}; sourceMap[srcName][k] = true; }); - var mcpServerKeys = filtered.filter(function(k) { return k.startsWith('plugin.mcp.servers.') && k.split('.').length >= 5 }); + var mcpServerKeys = filtered.filter( + (k) => k.startsWith("plugin.mcp.servers.") && k.split(".").length >= 5, + ); var mcpServerMap = {}; - mcpServerKeys.forEach(function(k) { - var parts = k.split('.'); + mcpServerKeys.forEach((k) => { + var parts = k.split("."); var srvName = parts[3]; if (!mcpServerMap[srvName]) mcpServerMap[srvName] = {}; mcpServerMap[srvName][k] = true; }); - var regularKeys = filtered.filter(function(k) { - return !k.startsWith('core.llm.sources.') && hideTopLlms.indexOf(k) === -1 && !k.startsWith('plugin.mcp.servers.') && k !== 'plugin.mcp.servers'; - }); - var html = '

' + __('后端连接','Backend Connections') + '

' - + '
' - + '
' - + '
'; - if (regularKeys.length === 0 && Object.keys(sourceMap).length === 0 && Object.keys(mcpServerMap).length === 0 && state.selectedSection !== 'plugin.mcp') { - html += '

' + escHtml(state.selectedSection) + '

' + __('暂无设置项','No settings') + '

'; + var regularKeys = filtered.filter( + (k) => + !k.startsWith("core.llm.sources.") && + hideTopLlms.indexOf(k) === -1 && + !k.startsWith("plugin.mcp.servers.") && + k !== "plugin.mcp.servers", + ); + var html = + '

' + + __("后端连接", "Backend Connections") + + "

" + + '
' + + '
' + + '
'; + if ( + regularKeys.length === 0 && + Object.keys(sourceMap).length === 0 && + Object.keys(mcpServerMap).length === 0 && + state.selectedSection !== "plugin.mcp" + ) { + html += + '

' + + escHtml(state.selectedSection) + + '

' + + __("暂无设置项", "No settings") + + "

"; } else { - regularKeys.forEach(function(k) { + regularKeys.forEach((k) => { var v = state.settings[k]; - var sv = typeof v === 'object' ? JSON.stringify(v) : String(v); + var sv = typeof v === "object" ? JSON.stringify(v) : String(v); var m = state.meta?.[k]; - var shortName = k.split('.').pop().replace(/_/g, ' '); + var shortName = k.split(".").pop().replace(/_/g, " "); var label = m?.display_name || shortName; - var desc = m?.description || ''; - var typ = m?.type || 'string'; - var ph = m?.placeholder || ''; + var desc = m?.description || ""; + var typ = m?.type || "string"; + var ph = m?.placeholder || ""; var opts = m?.options || []; - var inpId = 'inp-' + k.replace(/\./g, '_'); - var inp = ''; - if (typ === 'bool') { - var chk = sv === 'true' ? 'checked' : ''; - inp = ''; - } else if (typ === 'select') { - var selOpts = ''; - opts.forEach(function(o) { selOpts += '' }); - inp = ''; - } else if (typ === 'text') { - inp = ''; + var inpId = "inp-" + k.replace(/\./g, "_"); + var inp = ""; + if (typ === "bool") { + var chk = sv === "true" ? "checked" : ""; + inp = + '"; + } else if (typ === "select") { + var selOpts = ""; + opts.forEach((o) => { + selOpts += + '"; + }); + inp = + ""; + } else if (typ === "text") { + inp = + ""; } else { - inp = ''; + inp = + ""; } - var extra = ''; + var extra = ""; if (m?.extra) { - m.extra.forEach(function(f) { - var fk = (k ? k + '.' : '') + f.key; + m.extra.forEach((f) => { + var fk = (k ? k + "." : "") + f.key; var fv = state.settings?.[fk]; - var fph = f.placeholder || __('输入','Enter ') + f.label; - extra += '
'; - if (f.type === 'select') { - var fopts = ''; - if (f.options) f.options.forEach(function(o) { fopts += '' }); - extra += ''; + var fph = f.placeholder || __("输入", "Enter ") + f.label; + extra += + '
"; + if (f.type === "select") { + var fopts = ""; + if (f.options) + f.options.forEach((o) => { + fopts += + '"; + }); + extra += + ""; } else { - extra += ''; + extra += + ''; } - extra += '
'; + extra += "
"; }); } - var descHtml = desc ? '

' + escHtml(desc) + '

' : ''; - html += '
' + escHtml(k) + '
' + inp + descHtml + extra - + '
'; + var descHtml = desc + ? '

' + + escHtml(desc) + + "

" + : ""; + html += + '
' + + escHtml(k) + + "
" + + inp + + descHtml + + extra + + '
"; }); // LLM Sources - Object.keys(sourceMap).sort().forEach(function(src) { - var baseKey = 'core.llm.sources.' + src; - var srcData = state.settings?.[baseKey + '.adapter'] || state.settings?.[baseKey + '.base_url'] || ''; - var fields = [ - { key: 'adapter', label: __('适配器','Adapter'), type: 'text' }, - { key: 'base_url', label: 'Base URL', type: 'text' }, - { key: 'model', label: __('模型','Model'), type: 'text' }, - { key: 'api_key', label: 'API Key', type: 'text' }, - { key: 'thinking_enabled', label: __('思考模式','Thinking Mode'), type: 'select', options: ['true','false'] }, - { key: 'adapter_path', label: __('适配器路径','Adapter Path'), type: 'text' } - ]; - var headerLabel = mL10n(src, 'LLM Source: ' + src); - html += '

' + escHtml(headerLabel) + '

'; - fields.forEach(function(f) { - var fk = baseKey + '.' + f.key; - var fv = state.settings?.[fk] || ''; - var flabel = f.label; - var fieldId = 'inp-' + fk.replace(/\./g, '_'); - if (f.type === 'select') { - var fopts = ''; - f.options.forEach(function(o) { fopts += '' }); - html += ''; - } else { - html += ''; - } + Object.keys(sourceMap) + .sort() + .forEach((src) => { + var baseKey = "core.llm.sources." + src; + var srcData = + state.settings?.[baseKey + ".adapter"] || + state.settings?.[baseKey + ".base_url"] || + ""; + var fields = [ + { key: "adapter", label: __("适配器", "Adapter"), type: "text" }, + { key: "base_url", label: "Base URL", type: "text" }, + { key: "model", label: __("模型", "Model"), type: "text" }, + { key: "api_key", label: "API Key", type: "text" }, + { + key: "thinking_enabled", + label: __("思考模式", "Thinking Mode"), + type: "select", + options: ["true", "false"], + }, + { + key: "adapter_path", + label: __("适配器路径", "Adapter Path"), + type: "text", + }, + ]; + var headerLabel = mL10n(src, "LLM Source: " + src); + html += '

' + escHtml(headerLabel) + "

"; + fields.forEach((f) => { + var fk = baseKey + "." + f.key; + var fv = state.settings?.[fk] || ""; + var flabel = f.label; + var fieldId = "inp-" + fk.replace(/\./g, "_"); + if (f.type === "select") { + var fopts = ""; + f.options.forEach((o) => { + fopts += + '"; + }); + html += + ""; + } else { + html += + "'; + } + }); + html += + '
' + + '" + + '
"; }); - html += '
' - + '' - + '
'; - }); - if (Object.keys(sourceMap).length > 0 || state.selectedSection === 'core.llm') { - html += ''; + if ( + Object.keys(sourceMap).length > 0 || + state.selectedSection === "core.llm" + ) { + html += + '"; } // MCP Servers - if (state.selectedSection === 'plugin.mcp' || Object.keys(mcpServerMap).length > 0) { - html += '

' + __('MCP 服务器','MCP Servers') + '

' + __('配置 Model Context Protocol 服务端连接','Configure Model Context Protocol server connections') + '

'; - Object.keys(mcpServerMap).sort().forEach(function(srv) { - var baseKey = 'plugin.mcp.servers.' + srv; - var fields = [ - { key: 'command', label: __('启动命令','Command'), type: 'text' }, - { key: 'url', label: 'SSE URL', type: 'text' }, - { key: 'args', label: __('参数(JSON数组)','Args (JSON array)'), type: 'text' }, - { key: 'env', label: __('环境变量(JSON数组)','Env (JSON array)'), type: 'text' } - ]; - html += '

' + escHtml(srv) + '

'; - fields.forEach(function(f) { - var fk = baseKey + '.' + f.key; - var fv = state.settings?.[fk] || ''; - var fieldId = 'inp-' + fk.replace(/\./g, '_'); - html += ''; + if ( + state.selectedSection === "plugin.mcp" || + Object.keys(mcpServerMap).length > 0 + ) { + html += + '

' + + __("MCP 服务器", "MCP Servers") + + '

' + + __( + "配置 Model Context Protocol 服务端连接", + "Configure Model Context Protocol server connections", + ) + + "

"; + Object.keys(mcpServerMap) + .sort() + .forEach((srv) => { + var baseKey = "plugin.mcp.servers." + srv; + var fields = [ + { key: "command", label: __("启动命令", "Command"), type: "text" }, + { key: "url", label: "SSE URL", type: "text" }, + { + key: "args", + label: __("参数(JSON数组)", "Args (JSON array)"), + type: "text", + }, + { + key: "env", + label: __("环境变量(JSON数组)", "Env (JSON array)"), + type: "text", + }, + ]; + html += '

' + escHtml(srv) + "

"; + fields.forEach((f) => { + var fk = baseKey + "." + f.key; + var fv = state.settings?.[fk] || ""; + var fieldId = "inp-" + fk.replace(/\./g, "_"); + html += + "'; + }); + html += + '
' + + '" + + '
"; }); - html += '
' - + '' - + '
'; - }); - html += ''; + html += + '"; } } - html += '
'; - document.getElementById('view-settings').innerHTML = html; + html += ""; + document.getElementById("view-settings").innerHTML = html; renderSettingsTabs(); renderConnSection(); } function markDirty(k) { - var inp = document.getElementById('inp-' + k.replace(/\./g, '_')); - if (inp) inp.style.borderColor = 'var(--save-btn-border)'; + var inp = document.getElementById("inp-" + k.replace(/\./g, "_")); + if (inp) inp.style.borderColor = "var(--save-btn-border)"; } async function saveSetting(k) { - var inp = document.getElementById('inp-' + k.replace(/\./g, '_')); + var inp = document.getElementById("inp-" + k.replace(/\./g, "_")); if (!inp) return; var val; var m = state.meta?.[k]; - if (m?.type === 'bool') { val = inp.checked ? 'true' : 'false' } - else if (m?.type === 'select') { val = inp.value } - else { var raw = inp.value; try { val = JSON.parse(raw) } catch(e) { val = raw } } - try { - var r = await api('/settings', { method: 'PUT', body: JSON.stringify({ key: k, value: val }) }); - if (r.status === 'ok') { - inp.style.borderColor = ''; - state.settings[k] = val; - toast(__('已保存: ','Saved: ') + k); - } else { - toast(__('保存失败: ','Save failed: ') + (r.error || 'unknown'), true); + if (m?.type === "bool") { + val = inp.checked ? "true" : "false"; + } else if (m?.type === "select") { + val = inp.value; + } else { + var raw = inp.value; + try { + val = JSON.parse(raw); + } catch (e) { + val = raw; } - } catch(e) { toast(__('保存失败: ','Save failed: ') + e.message, true) } + } + try { + var r = await api("/settings", { + method: "PUT", + body: JSON.stringify({ key: k, value: val }), + }); + if (r.status === "ok") { + inp.style.borderColor = ""; + state.settings[k] = val; + toast(__("已保存: ", "Saved: ") + k); + } else { + toast(__("保存失败: ", "Save failed: ") + (r.error || "unknown"), true); + } + } catch (e) { + toast(__("保存失败: ", "Save failed: ") + e.message, true); + } } function renderConfigDisabled() { - document.getElementById('view-settings').innerHTML = '

' + __('设置','Settings') + '

' + __('设置面板已加载','Settings panel loaded') + '

'; + document.getElementById("view-settings").innerHTML = + '

' + + __("设置", "Settings") + + '

' + + __("设置面板已加载", "Settings panel loaded") + + "

"; renderOneSettings(); } @@ -1794,107 +3315,301 @@ function mL10n(key, fallback) { } function showAddSourceDialog() { - var name = prompt(__('输入新 LLM 源名称(如 openai、anthropic):','Enter new LLM source name (e.g. openai, anthropic):')); + var name = prompt( + __( + "输入新 LLM 源名称(如 openai、anthropic):", + "Enter new LLM source name (e.g. openai, anthropic):", + ), + ); if (!name || !name.trim()) return; - name = name.trim().toLowerCase().replace(/[^a-z0-9_]/g, '_'); - if (!name) { toast(__('名称无效','Invalid name'), true); return } - var keys = ['base_url','model','api_key','adapter','adapter_path','thinking_enabled']; - var values = { base_url: 'https://api.' + name + '.com', model: '', api_key: '', adapter: name, adapter_path: '', thinking_enabled: 'false' }; - var promises = keys.map(function(f) { - return api('/settings', { method: 'PUT', body: JSON.stringify({ key: 'core.llm.sources.' + name + '.' + f, value: values[f] }) }); - }); - Promise.all(promises).then(function() { toast(__('源','Source') + ' "' + name + '" ' + __('已创建,请配置各项参数','created, please configure parameters')); renderAll() }).catch(function(e) { toast(__('创建失败: ','Create failed: ') + e.message, true) }); + name = name + .trim() + .toLowerCase() + .replace(/[^a-z0-9_]/g, "_"); + if (!name) { + toast(__("名称无效", "Invalid name"), true); + return; + } + var keys = [ + "base_url", + "model", + "api_key", + "adapter", + "adapter_path", + "thinking_enabled", + ]; + var values = { + base_url: "https://api." + name + ".com", + model: "", + api_key: "", + adapter: name, + adapter_path: "", + thinking_enabled: "false", + }; + var promises = keys.map((f) => + api("/settings", { + method: "PUT", + body: JSON.stringify({ + key: "core.llm.sources." + name + "." + f, + value: values[f], + }), + }), + ); + Promise.all(promises) + .then(() => { + toast( + __("源", "Source") + + ' "' + + name + + '" ' + + __("已创建,请配置各项参数", "created, please configure parameters"), + ); + renderAll(); + }) + .catch((e) => { + toast(__("创建失败: ", "Create failed: ") + e.message, true); + }); } async function deleteSource(name) { - if (!confirm(__('确认删除源','Are you sure to delete source') + ' "' + name + '"?')) return; - var base = 'core.llm.sources.' + name; - var fields = ['adapter','base_url','model','api_key','thinking_enabled','adapter_path']; + if ( + !(await confirmDialog( + __("确认删除源", "Are you sure to delete source") + ' "' + name + '"?', + true, + )) + ) + return; + var base = "core.llm.sources." + name; + var fields = [ + "adapter", + "base_url", + "model", + "api_key", + "thinking_enabled", + "adapter_path", + ]; try { - for (var f of fields) { await api('/settings', { method: 'PUT', body: JSON.stringify({ key: base + '.' + f, value: null }) }) } - toast(__('源','Source') + ' "' + name + '" ' + __('已删除','deleted')); renderAll(); - } catch(e) { toast(__('删除失败: ','Delete failed: ') + e.message, true) } + for (var f of fields) { + await api("/settings", { + method: "PUT", + body: JSON.stringify({ key: base + "." + f, value: null }), + }); + } + toast(__("源", "Source") + ' "' + name + '" ' + __("已删除", "deleted")); + renderAll(); + } catch (e) { + toast(__("删除失败: ", "Delete failed: ") + e.message, true); + } } function addMCPSource() { - var name = prompt(__('输入新 MCP 服务器名称:','Enter new MCP server name:')); + var name = prompt(__("输入新 MCP 服务器名称:", "Enter new MCP server name:")); if (!name || !name.trim()) return; - name = name.trim().toLowerCase().replace(/[^a-z0-9_]/g, '_'); - if (!name) { toast(__('名称无效','Invalid name'), true); return } - var fields = ['command','url','args','env']; - var values = { command: '', url: '', args: '[]', env: '[]' }; - var promises = fields.map(function(f) { - return api('/settings', { method: 'PUT', body: JSON.stringify({ key: 'plugin.mcp.servers.' + name + '.' + f, value: values[f] }) }); - }); - Promise.all(promises).then(function() { toast('MCP ' + __('服务器','server') + ' "' + name + '" ' + __('已创建','created')); renderAll() }).catch(function(e) { toast(__('创建失败: ','Create failed: ') + e.message, true) }); + name = name + .trim() + .toLowerCase() + .replace(/[^a-z0-9_]/g, "_"); + if (!name) { + toast(__("名称无效", "Invalid name"), true); + return; + } + var fields = ["command", "url", "args", "env"]; + var values = { command: "", url: "", args: "[]", env: "[]" }; + var promises = fields.map((f) => + api("/settings", { + method: "PUT", + body: JSON.stringify({ + key: "plugin.mcp.servers." + name + "." + f, + value: values[f], + }), + }), + ); + Promise.all(promises) + .then(() => { + toast( + "MCP " + + __("服务器", "server") + + ' "' + + name + + '" ' + + __("已创建", "created"), + ); + renderAll(); + }) + .catch((e) => { + toast(__("创建失败: ", "Create failed: ") + e.message, true); + }); } async function deleteMCPServer(name) { - if (!confirm(__('确认删除 MCP 服务器','Are you sure to delete MCP server') + ' "' + name + '"?')) return; - var fields = ['command','url','args','env']; + if ( + !(await confirmDialog( + __("确认删除 MCP 服务器", "Are you sure to delete MCP server") + + ' "' + + name + + '"?', + true, + )) + ) + return; + var fields = ["command", "url", "args", "env"]; try { - for (var f of fields) { await api('/settings', { method: 'PUT', body: JSON.stringify({ key: 'plugin.mcp.servers.' + name + '.' + f, value: null }) }) } - toast('MCP ' + __('服务器','server') + ' "' + name + '" ' + __('已删除','deleted')); renderAll(); - } catch(e) { toast(__('删除失败: ','Delete failed: ') + e.message, true) } + for (var f of fields) { + await api("/settings", { + method: "PUT", + body: JSON.stringify({ + key: "plugin.mcp.servers." + name + "." + f, + value: null, + }), + }); + } + toast( + "MCP " + + __("服务器", "server") + + ' "' + + name + + '" ' + + __("已删除", "deleted"), + ); + renderAll(); + } catch (e) { + toast(__("删除失败: ", "Delete failed: ") + e.message, true); + } } // ===== Adapters ===== async function renderAdapters() { - var html = ''; + var html = ""; try { - var r = await api('/adapters'); + var r = await api("/adapters"); var adapters = r.adapters || []; window._adapters = adapters; - html += '

' + __('已加载的适配器','Loaded Adapters') + ' (' + adapters.length + ')

'; + html += + '

' + + __("已加载的适配器", "Loaded Adapters") + + " (" + + adapters.length + + ")

"; if (adapters.length === 0) { - html += '

' + __('暂无适配器','No adapters') + '

'; + html += + '

' + + __("暂无适配器", "No adapters") + + "

"; } else { - html += ''; - adapters.forEach(function(a) { - html += '' - + ''; + html += + "
' + __('名称','Name') + '' + __('版本','Version') + '' + __('操作','Actions') + '
' + escHtml(a.name) + '' + escHtml(a.version || '-') + '
"; + adapters.forEach((a) => { + html += + "" + + '"; }); - html += '
" + + __("名称", "Name") + + "" + + __("版本", "Version") + + "" + + __("操作", "Actions") + + "
" + + escHtml(a.name) + + "" + + escHtml(a.version || "-") + + "
'; + html += ""; } - html += '
'; - html += '

' + __('上传新适配器','Upload New Adapter') + '

' - + '' - + '' - + '' - + '' - + '
'; - } catch(e) { - html += '

' + __('加载适配器失败: ','Failed to load adapters: ') + escHtml(e.message) + '

'; + html += "
"; + html += + '

' + + __("上传新适配器", "Upload New Adapter") + + "

" + + "" + + '' + + "" + + '' + + '
"; + } catch (e) { + html += + '

' + + __("加载适配器失败: ", "Failed to load adapters: ") + + escHtml(e.message) + + "

"; } - document.getElementById('view-adapters').innerHTML = html; + document.getElementById("view-adapters").innerHTML = html; } async function uploadAdapter() { - var name = document.getElementById('adapter-name')?.value; - var code = document.getElementById('adapter-code')?.value; - if (!name || !code) { toast(__('名称和代码不能为空','Name and code cannot be empty'), true); return } + var name = document.getElementById("adapter-name")?.value; + var code = document.getElementById("adapter-code")?.value; + if (!name || !code) { + toast(__("名称和代码不能为空", "Name and code cannot be empty"), true); + return; + } try { - var r = await api('/adapters', { method: 'POST', body: JSON.stringify({ name: name, code: code }) }); - if (r.status === 'loaded') { toast(__('适配器','Adapter') + ' "' + name + '" ' + __('已加载','loaded')); renderAdapters() } - else { toast(__('上传失败: ','Upload failed: ') + (r.error || 'unknown'), true) } - } catch(e) { toast(__('上传失败: ','Upload failed: ') + e.message, true) } + var r = await api("/adapters", { + method: "POST", + body: JSON.stringify({ name: name, code: code }), + }); + if (r.status === "loaded") { + toast( + __("适配器", "Adapter") + ' "' + name + '" ' + __("已加载", "loaded"), + ); + renderAdapters(); + } else { + toast(__("上传失败: ", "Upload failed: ") + (r.error || "unknown"), true); + } + } catch (e) { + toast(__("上传失败: ", "Upload failed: ") + e.message, true); + } } async function deleteAdapter(name) { - if (!confirm(__('确定删除适配器','Are you sure to delete adapter') + ' "' + name + '"?')) return; + if ( + !(await confirmDialog( + __("确定删除适配器", "Are you sure to delete adapter") + + ' "' + + name + + '"?', + true, + )) + ) + return; try { - var r = await api('/adapters/' + encodeURIComponent(name), { method: 'DELETE' }); - if (r.status === 'deleted') { toast(__('适配器','Adapter') + ' "' + name + '" ' + __('已删除','deleted')); renderAdapters() } - else { toast(__('删除失败','Delete failed'), true) } - } catch(e) { toast(__('删除失败: ','Delete failed: ') + e.message, true) } + var r = await api("/adapters/" + encodeURIComponent(name), { + method: "DELETE", + }); + if (r.status === "deleted") { + toast( + __("适配器", "Adapter") + ' "' + name + '" ' + __("已删除", "deleted"), + ); + renderAdapters(); + } else { + toast(__("删除失败", "Delete failed"), true); + } + } catch (e) { + toast(__("删除失败: ", "Delete failed: ") + e.message, true); + } } // ===== Init ===== -(async function() { +(async () => { var data = await window.homeagent.connections.list(); state.connections = data.connections || []; - if (data.currentId) state.currentConn = state.connections.find(function(c) { return c.id === data.currentId }) || null; + if (data.currentId) + state.currentConn = + state.connections.find((c) => c.id === data.currentId) || null; if (state.currentConn) { await syncConnAuth(); connectSSE(); @@ -1910,210 +3625,349 @@ async function deleteAdapter(name) { // ===== Connection Management ===== function updateConnIndicator() { - var el = document.getElementById('conn-name-display'); - var dot = document.getElementById('conn-dot'); - var rdot = document.getElementById('rail-conn-dot'); + var el = document.getElementById("conn-name-display"); + var dot = document.getElementById("conn-dot"); + var rdot = document.getElementById("rail-conn-dot"); if (state.currentConn) { el.textContent = state.currentConn.name; - var cls = state.status.status === 'running' ? 'dot-green pulse' : 'dot-yellow'; - dot.className = 'status-dot ' + cls; - if (rdot) rdot.className = 'conn-dot ' + (state.status.status === 'running' ? 'dot-green' : 'dot-yellow'); + var cls = + state.status.status === "running" ? "dot-green pulse" : "dot-yellow"; + dot.className = "status-dot " + cls; + if (rdot) + rdot.className = + "conn-dot " + + (state.status.status === "running" ? "dot-green" : "dot-yellow"); } else { - el.textContent = __('未连接','Not connected'); - dot.className = 'status-dot dot-gray'; - if (rdot) rdot.className = 'conn-dot'; + el.textContent = __("未连接", "Not connected"); + dot.className = "status-dot dot-gray"; + if (rdot) rdot.className = "conn-dot"; } } function goSettingsConn() { - switchView('settings'); + switchView("settings"); renderConnSection(); } -function openConnManager() { renderConnSection(); switchView('settings'); } +function openConnManager() { + renderConnSection(); + switchView("settings"); +} function renderConnSection() { - var cont = document.getElementById('conn-manager'); + var cont = document.getElementById("conn-manager"); if (!cont) return; - cont.innerHTML = ''; + cont.innerHTML = ""; if (state.connections.length === 0) { - cont.innerHTML += '

' + __('暂无后端连接,添加一个以开始使用','No backend connections yet. Add one to get started.') + '

'; + cont.innerHTML += + '

' + + __( + "暂无后端连接,添加一个以开始使用", + "No backend connections yet. Add one to get started.", + ) + + "

"; } else { - state.connections.forEach(function(c) { - var div = document.createElement('div'); - div.className = 'conn-item ' + (state.currentConn && state.currentConn.id === c.id ? 'active' : ''); - div.innerHTML = '' - + '
' + escHtml(c.name) + '
' + escHtml(c.url) + '
' - + '
' - + ' ' - + ' ' - + '
'; + state.connections.forEach((c) => { + var div = document.createElement("div"); + div.className = + "conn-item " + + (state.currentConn && state.currentConn.id === c.id ? "active" : ""); + div.innerHTML = + '' + + '
' + + escHtml(c.name) + + (c.gateway + ? ' ' + __("总网关", "Gateway") + "" + : "") + + '
' + + escHtml(c.url) + + "
" + + '
' + + ' " + + ' " + + '
"; cont.appendChild(div); }); } - var form = document.createElement('div'); - form.className = 'conn-form'; - form.id = 'conn-form'; - form.style.display = 'none'; - form.innerHTML = '

' + __('添加连接','Add Connection') + '

' - + '' - + '' - + '
' - + '' - + '
' - + '' - + '' - + '' - + '
' - + '' - + '' - + '
' - + '' - + '' - + '' - + '
' - + '' - + '' - + '
' - + '' - + '
'; + var form = document.createElement("div"); + form.className = "conn-form"; + form.id = "conn-form"; + form.style.display = "none"; + form.innerHTML = + '

' + + __("添加连接", "Add Connection") + + "

" + + "' + + "' + + '
' + + '' + + '
' + + "" + + '' + + "' + + '
' + + '' + + '" + + "
" + + '" + + "" + + '' + + "
" + + "" + + '' + + '
' + + '" + + '
"; cont.appendChild(form); - var addBtn = document.createElement('button'); - addBtn.className = 'btn btn-primary'; - addBtn.id = 'conn-add-btn'; - addBtn.textContent = '+ ' + __('添加连接','Add Connection'); - addBtn.style.marginTop = '8px'; + var addBtn = document.createElement("button"); + addBtn.className = "btn btn-primary"; + addBtn.id = "conn-add-btn"; + addBtn.textContent = "+ " + __("添加连接", "Add Connection"); + addBtn.style.marginTop = "8px"; addBtn.onclick = showConnForm; cont.appendChild(addBtn); } function toggleConnType() { - var t = document.getElementById('conn-type').value; - document.getElementById('conn-addr-webui').style.display = t === 'cli' ? 'none' : 'block'; - document.getElementById('conn-addr-cli').style.display = t === 'cli' ? 'block' : 'none'; - document.getElementById('conn-auth-webui').style.display = t === 'cli' ? 'none' : 'block'; + var t = document.getElementById("conn-type").value; + document.getElementById("conn-addr-webui").style.display = + t === "cli" ? "none" : "block"; + document.getElementById("conn-addr-cli").style.display = + t === "cli" ? "block" : "none"; + document.getElementById("conn-auth-webui").style.display = + t === "cli" ? "none" : "block"; toggleGwFields(); } function toggleGwFields() { - var gw = document.getElementById('conn-gw'); - var fields = document.getElementById('conn-gw-fields'); - if (gw && fields) fields.style.display = gw.checked ? 'block' : 'none'; + var gw = document.getElementById("conn-gw"); + var fields = document.getElementById("conn-gw-fields"); + if (gw && fields) fields.style.display = gw.checked ? "block" : "none"; } async function openLoginWindow(useForm) { if (useForm === undefined) useForm = true; var url, us, ps; if (useForm) { - url = document.getElementById('conn-url').value.trim().replace(/\/+$/, ''); - us = document.getElementById('conn-user').value.trim(); - ps = document.getElementById('conn-pass').value; + url = document.getElementById("conn-url").value.trim().replace(/\/+$/, ""); + us = document.getElementById("conn-user").value.trim(); + ps = document.getElementById("conn-pass").value; } else { url = arguments[1]; - us = arguments[2] || ''; - ps = arguments[3] || ''; + us = arguments[2] || ""; + ps = arguments[3] || ""; + } + if (!url) { + toast(__("请先填写地址", "Set URL first"), true); + return; } - if (!url) { toast(__('请先填写地址','Set URL first'), true); return; } var handled = false; - window.homeagent.webui.onLoginResult(function(d) { - if (handled) return; handled = true; - if (window.homeagent && window.homeagent.log) window.homeagent.log('r: login-result ok=' + (d && d.ok) + ' count=' + (d && d.count)); + window.homeagent.webui.onLoginResult((d) => { + if (handled) return; + handled = true; + if (window.homeagent && window.homeagent.log) + window.homeagent.log( + "r: login-result ok=" + (d && d.ok) + " count=" + (d && d.count), + ); if (_loginWaitRes) { - var r = _loginWaitRes; _loginWaitRes = null; + var r = _loginWaitRes; + _loginWaitRes = null; r(d); return; } if (!d || !d.ok) { - toast(__('未取得 Cookie: ','No cookies: ') + ((d && d.error) || 'unknown'), true); + toast( + __("未取得 Cookie: ", "No cookies: ") + ((d && d.error) || "unknown"), + true, + ); return; } - var form = document.getElementById('conn-form'); - var editing = form && form.style.display === 'block'; + var form = document.getElementById("conn-form"); + var editing = form && form.style.display === "block"; if (editing) { - document.getElementById('conn-cookie').value = d.cookie || ''; - toast(__('已取得 ','Got ') + (d.count || 0) + __(' 个 Cookie,点保存生效',' cookies, click Save to apply')); + document.getElementById("conn-cookie").value = d.cookie || ""; + toast( + __("已取得 ", "Got ") + + (d.count || 0) + + __(" 个 Cookie,点保存生效", " cookies, click Save to apply"), + ); return; } - if (state.currentConn && d.url.replace(/\/+$/, '') === state.currentConn.url) { - window.homeagent.connections.update(state.currentConn.id, { cookie: d.cookie || '' }) - .then(function (data) { + if ( + state.currentConn && + d.url.replace(/\/+$/, "") === state.currentConn.url + ) { + window.homeagent.connections + .update(state.currentConn.id, { cookie: d.cookie || "" }) + .then((data) => { state.connections = data.connections; - state.currentConn = data.connections.find(function (c) { return c.id === data.currentId }) || state.currentConn; + state.currentConn = + data.connections.find((c) => c.id === data.currentId) || + state.currentConn; updateConnIndicator(); return syncConnAuth(); }) - .then(function () { - toast(__('总网关 Cookie 已自动生效','Gateway cookie applied automatically')); - if (state.messages.length === 0) loadChatHistory().then(function(){ rerenderChat() }).catch(function(){}); + .then(() => { + toast( + __( + "总网关 Cookie 已自动生效", + "Gateway cookie applied automatically", + ), + ); + if (state.messages.length === 0) + loadChatHistory() + .then(() => { + rerenderChat(); + }) + .catch(() => {}); return null; }) - .catch(function (e) { toast(__('应用 Cookie 失败: ','Apply cookie failed: ') + e.message, true); }); + .catch((e) => { + toast( + __("应用 Cookie 失败: ", "Apply cookie failed: ") + e.message, + true, + ); + }); } else { - toast(__('已获得 Cookie(请切换到对应连接后保存)','Cookies acquired (switch to the matching connection to save)'), false); + toast( + __( + "已获得 Cookie(请切换到对应连接后保存)", + "Cookies acquired (switch to the matching connection to save)", + ), + false, + ); } }); var r = await window.homeagent.webui.openLogin(url, us, ps); - if (!r || !r.ok) toast(__('无法打开登录窗口: ','Cannot open login window: ') + ((r && r.error) || ''), true); + if (!r || !r.ok) + toast( + __("无法打开登录窗口: ", "Cannot open login window: ") + + ((r && r.error) || ""), + true, + ); } function showConnForm() { editingConnId = null; - document.getElementById('conn-form-title').textContent = __('添加连接','Add Connection'); - document.getElementById('conn-name').value = ''; - document.getElementById('conn-url').value = 'http://localhost:18080'; - document.getElementById('conn-sock').value = ''; - document.getElementById('conn-key').value = ''; - document.getElementById('conn-user').value = ''; - document.getElementById('conn-pass').value = ''; - document.getElementById('conn-cookie').value = ''; - document.getElementById('conn-headers').value = ''; - document.getElementById('conn-gw').checked = false; + document.getElementById("conn-form-title").textContent = __( + "添加连接", + "Add Connection", + ); + document.getElementById("conn-name").value = ""; + document.getElementById("conn-url").value = "http://localhost:18080"; + document.getElementById("conn-sock").value = ""; + document.getElementById("conn-key").value = ""; + document.getElementById("conn-user").value = ""; + document.getElementById("conn-pass").value = ""; + document.getElementById("conn-cookie").value = ""; + document.getElementById("conn-headers").value = ""; + document.getElementById("conn-gw").checked = false; toggleGwFields(); - document.getElementById('conn-type').value = 'webui'; + document.getElementById("conn-type").value = "webui"; toggleConnType(); - document.getElementById('conn-form').style.display = 'block'; - document.getElementById('conn-add-btn').style.display = 'none'; + document.getElementById("conn-form").style.display = "block"; + document.getElementById("conn-add-btn").style.display = "none"; } function editConnection(id, e) { if (e) e.stopPropagation(); - var c = state.connections.find(function(x) { return x.id === id }); + var c = state.connections.find((x) => x.id === id); if (!c) return; editingConnId = id; - document.getElementById('conn-form-title').textContent = __('编辑连接','Edit Connection'); - document.getElementById('conn-name').value = c.name; - document.getElementById('conn-url').value = c.url || 'http://localhost:18080'; - document.getElementById('conn-sock').value = c.socketPath || ''; - document.getElementById('conn-key').value = c.apiKey; - document.getElementById('conn-user').value = c.username || ''; - document.getElementById('conn-pass').value = c.password || ''; - document.getElementById('conn-cookie').value = c.cookie || ''; - document.getElementById('conn-headers').value = c.headers || ''; - document.getElementById('conn-gw').checked = !!(c.gateway || c.cookie); + document.getElementById("conn-form-title").textContent = __( + "编辑连接", + "Edit Connection", + ); + document.getElementById("conn-name").value = c.name; + document.getElementById("conn-url").value = c.url || "http://localhost:18080"; + document.getElementById("conn-sock").value = c.socketPath || ""; + document.getElementById("conn-key").value = c.apiKey; + document.getElementById("conn-user").value = c.username || ""; + document.getElementById("conn-pass").value = c.password || ""; + document.getElementById("conn-cookie").value = c.cookie || ""; + document.getElementById("conn-headers").value = c.headers || ""; + document.getElementById("conn-gw").checked = !!(c.gateway || c.cookie); toggleGwFields(); - document.getElementById('conn-type').value = c.type === 'cli' ? 'cli' : 'webui'; + document.getElementById("conn-type").value = + c.type === "cli" ? "cli" : "webui"; toggleConnType(); - document.getElementById('conn-form').style.display = 'block'; - document.getElementById('conn-add-btn').style.display = 'none'; + document.getElementById("conn-form").style.display = "block"; + document.getElementById("conn-add-btn").style.display = "none"; } function cancelConnForm() { - document.getElementById('conn-form').style.display = 'none'; - document.getElementById('conn-add-btn').style.display = 'block'; + document.getElementById("conn-form").style.display = "none"; + document.getElementById("conn-add-btn").style.display = "block"; } async function selectConnection(id) { - if (state.eventSource) { state.eventSource.close(); state.eventSource = null; } + if (state.eventSource) { + state.eventSource.close(); + state.eventSource = null; + } var data = await window.homeagent.connections.setCurrent(id); - state.currentConn = data.connections.find(function(c) { return c.id === id }) || null; + state.currentConn = data.connections.find((c) => c.id === id) || null; state.connections = data.connections; state.messages = []; updateConnIndicator(); @@ -2122,23 +3976,38 @@ async function selectConnection(id) { await loadChatHistory(); doRenderAll(); startUptimeTicker(); - switchView('chat'); + switchView("chat"); renderConnSection(); } async function deleteConnection(id, e) { if (e) e.stopPropagation(); - if (!confirm(__('确定删除此连接?','Delete this connection?'))) return; + if ( + !(await confirmDialog( + __("确定删除此连接?", "Delete this connection?"), + true, + )) + ) + return; var wasCurrent = state.currentConn && state.currentConn.id === id; var data = await window.homeagent.connections.delete(id); state.connections = data.connections; - state.currentConn = data.currentId ? state.connections.find(function(c) { return c.id === data.currentId }) : null; - if (wasCurrent && state.eventSource) { state.eventSource.close(); state.eventSource = null; } + state.currentConn = data.currentId + ? state.connections.find((c) => c.id === data.currentId) + : null; + if (wasCurrent && state.eventSource) { + state.eventSource.close(); + state.eventSource = null; + } if (state.currentConn) { - updateConnIndicator(); doRenderAll(); syncConnAuth(); connectSSE(); + updateConnIndicator(); + doRenderAll(); + syncConnAuth(); + connectSSE(); } else { updateConnIndicator(); - if (window.homeagent.webui) await window.homeagent.webui.setAuth('', '', '', '', ''); + if (window.homeagent.webui) + await window.homeagent.webui.setAuth("", "", "", "", ""); } renderConnSection(); } @@ -2147,105 +4016,228 @@ var editingConnId = null; var _loginWaitRes = null; function waitLogin() { - return new Promise(function (res) { _loginWaitRes = res; }); + return new Promise((res) => { + _loginWaitRes = res; + }); } async function syncConnAuth() { var c = state.currentConn; - if (!c || c.type !== 'webui' || !c.url) { - if (window.homeagent.webui) await window.homeagent.webui.setAuth('', '', '', '', ''); + if (!c || c.type !== "webui" || !c.url) { + if (window.homeagent.webui) + await window.homeagent.webui.setAuth("", "", "", "", ""); return true; } var headers = {}; - if (c.headers) { try { headers = JSON.parse(c.headers) || {} } catch (e) {} } - var r = await window.homeagent.webui.setAuth(c.url, c.cookie || '', headers, c.username || '', c.password || ''); + if (c.headers) { + try { + headers = JSON.parse(c.headers) || {}; + } catch (e) {} + } + var r = await window.homeagent.webui.setAuth( + c.url, + c.cookie || "", + headers, + c.username || "", + c.password || "", + ); if (r && r.ok === false) { - toast(__('自动登录 WebUI 失败(已忽略,继续使用现有 Cookie): ','WebUI auto-login failed (ignored): ') + r.error, true); + toast( + __( + "自动登录 WebUI 失败(已忽略,继续使用现有 Cookie): ", + "WebUI auto-login failed (ignored): ", + ) + r.error, + true, + ); if (c.gateway && !c.cookie) { - setTimeout(function () { openLoginWindow(false, c.url, c.username || '', c.password || '') }, 900); + setTimeout(() => { + openLoginWindow(false, c.url, c.username || "", c.password || ""); + }, 900); } return false; } if (c.gateway && c.cookie && r && r.ok !== false) { - toast(__('总网关 Cookie 已生效','Gateway cookie active')); + toast(__("总网关 Cookie 已生效", "Gateway cookie active")); } return true; } async function saveConnForm() { - if (window.homeagent && window.homeagent.log) window.homeagent.log('save: start'); - var name = document.getElementById('conn-name').value.trim(); - var ctype = document.getElementById('conn-type').value; - var url = document.getElementById('conn-url').value.trim().replace(/\/+$/, ''); - var sock = document.getElementById('conn-sock').value.trim(); - var apiKey = document.getElementById('conn-key').value.trim(); - var username = document.getElementById('conn-user').value.trim(); - var password = document.getElementById('conn-pass').value; - var gwEnabled = !!(document.getElementById('conn-gw') && document.getElementById('conn-gw').checked); - var cookie = gwEnabled ? document.getElementById('conn-cookie').value.trim() : ''; - var headersRaw = document.getElementById('conn-headers').value.trim(); - var headers = ''; + if (window.homeagent && window.homeagent.log) + window.homeagent.log("save: start"); + var name = document.getElementById("conn-name").value.trim(); + var ctype = document.getElementById("conn-type").value; + var url = document + .getElementById("conn-url") + .value.trim() + .replace(/\/+$/, ""); + var sock = document.getElementById("conn-sock").value.trim(); + var apiKey = document.getElementById("conn-key").value.trim(); + var username = document.getElementById("conn-user").value.trim(); + var password = document.getElementById("conn-pass").value; + var gwEnabled = !!( + document.getElementById("conn-gw") && + document.getElementById("conn-gw").checked + ); + var cookie = gwEnabled + ? document.getElementById("conn-cookie").value.trim() + : ""; + var headersRaw = document.getElementById("conn-headers").value.trim(); + var headers = ""; if (headersRaw) { - try { JSON.parse(headersRaw); headers = headersRaw; } - catch (e) { toast(__('额外请求头不是合法 JSON','Extra headers not valid JSON'), true); return; } + try { + JSON.parse(headersRaw); + headers = headersRaw; + } catch (e) { + toast( + __("额外请求头不是合法 JSON", "Extra headers not valid JSON"), + true, + ); + return; + } } - if (ctype === 'cli') { - if (!name || !sock) { toast(__('名称和 Socket 路径不能为空','Name and Socket Path required'), true); return; } - } else { - if (!name || !url) { toast(__('名称和地址不能为空','Name and URL required'), true); return; } + if (ctype === "cli") { + if (!name || !sock) { + toast( + __("名称和 Socket 路径不能为空", "Name and Socket Path required"), + true, + ); + return; + } + } else if (!name || !url) { + toast(__("名称和地址不能为空", "Name and URL required"), true); + return; } - var testBtn = document.querySelector('#conn-form .btn-primary'); - testBtn.textContent = __('测试中...','Testing...'); testBtn.disabled = true; + var testBtn = document.querySelector("#conn-form .btn-primary"); + testBtn.textContent = __("测试中...", "Testing..."); + testBtn.disabled = true; try { - if (ctype === 'cli') { - if (!window.homeagent.cli) throw new Error('cli bridge unavailable'); - var testR = await window.homeagent.cli.request(sock, apiKey, '/status'); - if (testR.error || testR.type === 'error') { - toast(__('CLI 连接测试失败: ','CLI test failed: ') + (testR.error || testR.type), true); - testBtn.textContent = __('保存','Save'); testBtn.disabled = false; return; + if (ctype === "cli") { + if (!window.homeagent.cli) throw new Error("cli bridge unavailable"); + var testR = await window.homeagent.cli.request(sock, apiKey, "/status"); + if (testR.error || testR.type === "error") { + toast( + __("CLI 连接测试失败: ", "CLI test failed: ") + + (testR.error || testR.type), + true, + ); + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; + return; } } else { if (window.homeagent && window.homeagent.webui) { if (gwEnabled && !cookie) { - testBtn.textContent = __('请在登录窗口完成网关登录…','Complete gateway login…'); + testBtn.textContent = __( + "请在登录窗口完成网关登录…", + "Complete gateway login…", + ); testBtn.disabled = true; openLoginWindow(false, url, username, password); var lg = await waitLogin(); if (!lg || !lg.ok) { - toast(__('网关登录未完成,已取消保存','Gateway login incomplete, save cancelled') + ((lg && lg.error) ? ': ' + lg.error : ''), true); - testBtn.textContent = __('保存','Save'); testBtn.disabled = false; + toast( + __( + "网关登录未完成,已取消保存", + "Gateway login incomplete, save cancelled", + ) + (lg && lg.error ? ": " + lg.error : ""), + true, + ); + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; return; } - cookie = lg.cookie || ''; + cookie = lg.cookie || ""; } var tHeaders = {}; - if (headersRaw) { try { tHeaders = JSON.parse(headersRaw) } catch (e) {} } - if (window.homeagent.log) window.homeagent.log('save: setAuth url=' + url + ' gw=' + gwEnabled + ' cookieLen=' + cookie.length); + if (headersRaw) { + try { + tHeaders = JSON.parse(headersRaw); + } catch (e) {} + } + if (window.homeagent.log) + window.homeagent.log( + "save: setAuth url=" + + url + + " gw=" + + gwEnabled + + " cookieLen=" + + cookie.length, + ); try { - await window.homeagent.webui.setAuth(url, cookie, tHeaders, username, password); - } catch (e) { toast(__('应用认证失败: ','Apply auth failed: ') + e.message, true); } + await window.homeagent.webui.setAuth( + url, + cookie, + tHeaders, + username, + password, + ); + } catch (e) { + toast(__("应用认证失败: ", "Apply auth failed: ") + e.message, true); + } } - if (window.homeagent.log) window.homeagent.log('save: testing ' + url + '/api/v1/status'); + if (window.homeagent.log) + window.homeagent.log("save: testing " + url + "/api/v1/status"); var testR; try { - testR = await fetch(url + '/api/v1/status', { headers: apiKey ? { 'X-API-Key': apiKey } : {} }); + testR = await fetch(url + "/api/v1/status", { + headers: apiKey ? { "X-API-Key": apiKey } : {}, + }); } catch (e) { - if (window.homeagent.log) window.homeagent.log('save: fetch error: ' + e.message); - toast(__('无法连接到 ','Cannot connect to ') + url + ': ' + e.message, true); - testBtn.textContent = __('保存','Save'); testBtn.disabled = false; + if (window.homeagent.log) + window.homeagent.log("save: fetch error: " + e.message); + toast( + __("无法连接到 ", "Cannot connect to ") + url + ": " + e.message, + true, + ); + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; + return; + } + if (window.homeagent.log) + window.homeagent.log("save: status=" + testR.status); + if (!testR.ok) { + toast( + __("连接测试失败: HTTP ", "Connection test failed: HTTP ") + + testR.status + + "(" + + (await testR.text()).slice(0, 120) + + ")", + true, + ); + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; return; } - if (window.homeagent.log) window.homeagent.log('save: status=' + testR.status); - if (!testR.ok) { toast(__('连接测试失败: HTTP ','Connection test failed: HTTP ') + testR.status + '(' + (await testR.text()).slice(0, 120) + ')', true); testBtn.textContent = __('保存','Save'); testBtn.disabled = false; return; } } - } catch(e) { - toast(__('无法连接到 ','Cannot connect to ') + (ctype === 'cli' ? sock : url) + ': ' + e.message, true); - testBtn.textContent = __('保存','Save'); testBtn.disabled = false; return; + } catch (e) { + toast( + __("无法连接到 ", "Cannot connect to ") + + (ctype === "cli" ? sock : url) + + ": " + + e.message, + true, + ); + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; + return; } - testBtn.textContent = __('保存','Save'); testBtn.disabled = false; - var connData = ctype === 'cli' - ? { name: name, type: 'cli', socketPath: sock, url: '', apiKey: apiKey } - : { name: name, type: 'webui', url: url, apiKey: apiKey, username: username, password: password, cookie: cookie, headers: headers, gateway: gwEnabled }; + testBtn.textContent = __("保存", "Save"); + testBtn.disabled = false; + var connData = + ctype === "cli" + ? { name: name, type: "cli", socketPath: sock, url: "", apiKey: apiKey } + : { + name: name, + type: "webui", + url: url, + apiKey: apiKey, + username: username, + password: password, + cookie: cookie, + headers: headers, + gateway: gwEnabled, + }; var data; if (editingConnId) { data = await window.homeagent.connections.update(editingConnId, connData); @@ -2253,146 +4245,252 @@ async function saveConnForm() { data = await window.homeagent.connections.add(connData); } state.connections = data.connections; - var cur = data.connections.find(function(c) { return c.id === data.currentId }); - var switched = !!cur && (!state.currentConn || state.currentConn.id !== cur.id); + var cur = data.connections.find((c) => c.id === data.currentId); + var switched = + !!cur && (!state.currentConn || state.currentConn.id !== cur.id); if (cur) { state.currentConn = cur; await syncConnAuth(); if (switched) { - if (state.eventSource) { state.eventSource.close(); state.eventSource = null; } + if (state.eventSource) { + state.eventSource.close(); + state.eventSource = null; + } state.messages = []; - updateConnIndicator(); connectSSE(); await loadChatHistory(); doRenderAll(); startUptimeTicker(); - switchView('chat'); + updateConnIndicator(); + connectSSE(); + await loadChatHistory(); + doRenderAll(); + startUptimeTicker(); + switchView("chat"); } else { - updateConnIndicator(); doRenderAll(); + updateConnIndicator(); + doRenderAll(); } } - cancelConnForm(); renderConnSection(); + cancelConnForm(); + renderConnSection(); } -document.addEventListener('keydown', function(e) { - if (e.key === 'Escape' && document.getElementById('conn-form').style.display === 'block') cancelConnForm(); +document.addEventListener("keydown", (e) => { + if ( + e.key === "Escape" && + document.getElementById("conn-form").style.display === "block" + ) + cancelConnForm(); }); // ===== SSE (override for fetch-based) ===== -connectSSE = function() { - if (state.eventSource) { state.eventSource.close(); state.eventSource = null; } +connectSSE = () => { + if (state.eventSource) { + state.eventSource.close(); + state.eventSource = null; + } if (!state.currentConn) return; // CLI 连接无 SSE 通道,聊天走同步 cli:request - if (state.currentConn.type === 'cli') return; - connectFetchSSE(state.currentConn.url + '/api/v1/chat/events'); + if (state.currentConn.type === "cli") return; + connectFetchSSE(state.currentConn.url + "/api/v1/chat/events"); }; async function connectFetchSSE(url) { try { var headers = {}; - if (state.currentConn && state.currentConn.apiKey) headers['X-API-Key'] = state.currentConn.apiKey; - var resp = await fetch(url, { headers: headers, cache: 'no-store' }); - if (!resp.ok || !resp.body) { setTimeout(function() { connectSSE() }, 5000); return; } - var reader = resp.body.getReader(); var decoder = new TextDecoder(); - var buffer = ''; var reconnectTimer = null; - state.eventSource = { close: function() { reader.cancel(); if (reconnectTimer) clearTimeout(reconnectTimer) } }; + if (state.currentConn && state.currentConn.apiKey) + headers["X-API-Key"] = state.currentConn.apiKey; + var resp = await fetch(url, { headers: headers, cache: "no-store" }); + if (!resp.ok || !resp.body) { + setTimeout(() => { + connectSSE(); + }, 5000); + return; + } + var reader = resp.body.getReader(); + var decoder = new TextDecoder(); + var buffer = ""; + var reconnectTimer = null; + state.eventSource = { + close: () => { + reader.cancel(); + if (reconnectTimer) clearTimeout(reconnectTimer); + }, + }; function processLines() { - var lines = buffer.split('\n'); buffer = lines.pop() || ''; - var eventType = '', data = ''; + var lines = buffer.split("\n"); + buffer = lines.pop() || ""; + var eventType = "", + data = ""; for (var i = 0; i < lines.length; i++) { var line = lines[i]; - if (line.startsWith('event: ')) eventType = line.slice(7).trim(); - else if (line.startsWith('data: ')) data = line.slice(6).trim(); - else if (line === '' && eventType && data) { handleSSEEvent(eventType, data); eventType = ''; data = ''; } + if (line.startsWith("event: ")) eventType = line.slice(7).trim(); + else if (line.startsWith("data: ")) data = line.slice(6).trim(); + else if (line === "" && eventType && data) { + handleSSEEvent(eventType, data); + eventType = ""; + data = ""; + } } } function handleSSEEvent(type, raw) { try { - var ev = JSON.parse(raw); var p = ev.payload || {}; - if (type === 'agent_output') { - state.chatStage = __('AI 回复中...','AI replying...'); - if (p.kind === 'channel_output') { - var cm = { role: 'assistant', content: p.content || '', source: p.channel || '', _final: true, _grow: true }; - if (state.chatFinalIdx >= 0 && state.chatFinalIdx < state.messages.length) { + var ev = JSON.parse(raw); + var p = ev.payload || {}; + if (type === "agent_output") { + state.chatStage = __("AI 回复中...", "AI replying..."); + if (p.kind === "channel_output") { + var cm = { + role: "assistant", + content: p.content || "", + source: p.channel || "", + _final: true, + _grow: true, + }; + if ( + state.chatFinalIdx >= 0 && + state.chatFinalIdx < state.messages.length + ) { state.messages.splice(state.chatFinalIdx, 0, cm); state.chatFinalIdx++; } else { state.messages.push(cm); } - rerenderChatIfActive(); return; + rerenderChatIfActive(); + return; } - var last = state.messages.length > 0 ? state.messages[state.messages.length - 1] : null; - if (last && last.role === 'assistant' && !last._final) { + var last = + state.messages.length > 0 + ? state.messages[state.messages.length - 1] + : null; + if (last && last.role === "assistant" && !last._final) { last._grow = true; - last.content += (p.content || ''); - rerenderChatIfActive(); return; + last.content += p.content || ""; + rerenderChatIfActive(); + return; } - state.messages.push({ role: 'assistant', content: p.content || '', _streaming: true, _grow: true }); + state.messages.push({ + role: "assistant", + content: p.content || "", + _streaming: true, + _grow: true, + }); rerenderChatIfActive(); - } else if (type === 'reasoning') { + } else if (type === "reasoning") { if (p.content) { - state.chatStage = __('AI 思考中...','AI thinking...'); - var last = state.messages.length > 0 ? state.messages[state.messages.length - 1] : null; - if (!last || last.role !== 'assistant' || last._final) { - state.messages.push({ role: 'assistant', content: '', reasoning_content: '', tool_calls: [], _streaming: true }); + state.chatStage = __("AI 思考中...", "AI thinking..."); + var last = + state.messages.length > 0 + ? state.messages[state.messages.length - 1] + : null; + if (!last || last.role !== "assistant" || last._final) { + state.messages.push({ + role: "assistant", + content: "", + reasoning_content: "", + tool_calls: [], + _streaming: true, + }); last = state.messages[state.messages.length - 1]; } - last.reasoning_content = (last.reasoning_content || '') + (p.content || ''); + last.reasoning_content = + (last.reasoning_content || "") + (p.content || ""); rerenderChatIfActive(); } - } else if (type === 'tool_call') { + } else if (type === "tool_call") { if (!p.tool) return; - var last = state.messages.length > 0 ? state.messages[state.messages.length - 1] : null; - if (!last || last.role !== 'assistant' || last._final) { - state.messages.push({ role: 'assistant', content: '', tool_calls: [], _streaming: true }); + var last = + state.messages.length > 0 + ? state.messages[state.messages.length - 1] + : null; + if (!last || last.role !== "assistant" || last._final) { + state.messages.push({ + role: "assistant", + content: "", + tool_calls: [], + _streaming: true, + }); last = state.messages[state.messages.length - 1]; } if (!last.tool_calls) last.tool_calls = []; - last.tool_calls.push({ tool: p.tool, name: p.tool, args: p.args || {}, result: p.result || '', status: p.status || 'ok', plugin: p.plugin || '' }); + last.tool_calls.push({ + tool: p.tool, + name: p.tool, + args: p.args || {}, + result: p.result || "", + status: p.status || "ok", + plugin: p.plugin || "", + }); var pidx = (state.pendingTools || []).indexOf(p.tool); if (pidx !== -1) state.pendingTools.splice(pidx, 1); - state.chatStage = __('工具调用: ','Tool: ') + (p.tool || ''); + state.chatStage = __("工具调用: ", "Tool: ") + (p.tool || ""); rerenderChatIfActive(); - } else if (type === 'terminal_output') { + } else if (type === "terminal_output") { if (!p.terminal_id) return; var tid = p.terminal_id; if (!state.termScreens) state.termScreens = {}; - var scr = state.termScreens[tid] || (state.termScreens[tid] = { output: '', running: true }); + var scr = + state.termScreens[tid] || + (state.termScreens[tid] = { output: "", running: true }); if (p.output) scr.output += p.output; - if (typeof p.running === 'boolean') scr.running = p.running; - var bufel = document.getElementById('term-buf-' + tid); + if (typeof p.running === "boolean") scr.running = p.running; + var bufel = document.getElementById("term-buf-" + tid); if (bufel) { - appendTermBuf(bufel, p.output || ''); - var dot = document.getElementById('term-dot-' + tid); - if (dot) dot.className = 'term-dot' + (scr.running ? '' : ' stopped'); + appendTermBuf(bufel, p.output || ""); + var dot = document.getElementById("term-dot-" + tid); + if (dot) + dot.className = "term-dot" + (scr.running ? "" : " stopped"); } - } else if (type === 'stage') { - var phase = p.phase || ''; var tool = p.tool || ''; - if (p.channel !== '_consolidation_') { - if (phase === 'pre_action') state.chatStage = __('AI 思考中...','AI thinking...'); - else if (phase === 'before_toolcall') { - state.chatStage = __('工具调用: ','Tool: ') + (tool || ''); + } else if (type === "stage") { + var phase = p.phase || ""; + var tool = p.tool || ""; + if (p.channel !== "_consolidation_") { + if (phase === "pre_action") + state.chatStage = __("AI 思考中...", "AI thinking..."); + else if (phase === "before_toolcall") { + state.chatStage = __("工具调用: ", "Tool: ") + (tool || ""); if (tool && (state.pendingTools || []).indexOf(tool) === -1) { if (!state.pendingTools) state.pendingTools = []; state.pendingTools.push(tool); rerenderChatIfActive(); } - } - else if (phase === 'before_output') state.chatStage = __('生成回复中...','Generating response...'); + } else if (phase === "before_output") + state.chatStage = __("生成回复中...", "Generating response..."); + } + var badge = document.getElementById("chat-stage"); + if (badge) { + badge.textContent = state.chatStage || ""; + badge.style.display = "none"; } - var badge = document.getElementById('chat-stage'); - if (badge) { badge.textContent = state.chatStage || ''; badge.style.display = 'none'; } } - } catch(err) {} + } catch (err) {} } async function pump() { while (true) { - try { var result = await reader.read(); if (result.done) break; buffer += decoder.decode(result.value, { stream: true }); processLines(); } catch(e) { break; } + try { + var result = await reader.read(); + if (result.done) break; + buffer += decoder.decode(result.value, { stream: true }); + processLines(); + } catch (e) { + break; + } } - reconnectTimer = setTimeout(function() { connectSSE() }, 3000); + reconnectTimer = setTimeout(() => { + connectSSE(); + }, 3000); } pump(); - } catch(e) { setTimeout(function() { connectSSE() }, 5000); } + } catch (e) { + setTimeout(() => { + connectSSE(); + }, 5000); + } } function rerenderChatIfActive() { - var tab = document.getElementById('view-chat'); - if (tab && tab.classList.contains('active')) { renderChat(); renderChatStarmap(); renderTerminals(); renderCmdHistory(); } + var tab = document.getElementById("view-chat"); + if (tab && tab.classList.contains("active")) { + renderChat(); + renderChatStarmap(); + renderTerminals(); + renderCmdHistory(); + } } - diff --git a/cmd/gui/renderer/index.html b/cmd/gui/renderer/index.html index 98a7f4b..d825bfe 100644 --- a/cmd/gui/renderer/index.html +++ b/cmd/gui/renderer/index.html @@ -81,6 +81,7 @@
+
diff --git a/cmd/gui/renderer/style.css b/cmd/gui/renderer/style.css index dc43e97..78e66e0 100644 --- a/cmd/gui/renderer/style.css +++ b/cmd/gui/renderer/style.css @@ -23,13 +23,19 @@ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.25); --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.28); --shadow-lg: 0 12px 36px rgba(0, 0, 0, 0.38); - --shadow-glow: 0 0 0 1px rgba(255, 127, 172, 0.4), 0 4px 20px rgba(255, 127, 172, 0.18); + --shadow-glow: + 0 0 0 1px rgba(255, 127, 172, 0.4), 0 4px 20px rgba(255, 127, 172, 0.18); --radius-sm: 6px; --radius-md: 10px; --radius-lg: 14px; --radius-pill: 999px; - --font-sans: "Segoe UI", "Segoe UI Variable Text", -apple-system, BlinkMacSystemFont, Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", sans-serif; - --font-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", "SF Mono", "Menlo", "Consolas", monospace; + --font-sans: + "Segoe UI", "Segoe UI Variable Text", -apple-system, BlinkMacSystemFont, + Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", + "Microsoft YaHei", sans-serif; + --font-mono: + "JetBrains Mono", ui-monospace, "SFMono-Regular", "SF Mono", "Menlo", + "Consolas", monospace; --ease-out: cubic-bezier(0.22, 1, 0.36, 1); --dur-micro: 150ms; --dur-normal: 300ms; @@ -76,7 +82,7 @@ --c-amber: #fbbf24; --c-blue: #60a5fa; } -[data-theme=light] { +[data-theme="light"] { --glass-bg: rgba(255, 255, 255, 0.66); --glass-bg-strong: rgba(255, 255, 255, 0.88); --glass-border: rgba(255, 127, 172, 0.22); @@ -84,7 +90,8 @@ --shadow-sm: 0 1px 3px rgba(153, 27, 75, 0.08); --shadow-md: 0 6px 20px rgba(153, 27, 75, 0.1); --shadow-lg: 0 16px 40px rgba(153, 27, 75, 0.14); - --shadow-glow: 0 0 0 1px rgba(243, 59, 124, 0.3), 0 6px 22px rgba(243, 59, 124, 0.14); + --shadow-glow: + 0 0 0 1px rgba(243, 59, 124, 0.3), 0 6px 22px rgba(243, 59, 124, 0.14); --bg-primary: #ffffff; --bg-secondary: rgba(255, 255, 255, 0.78); --bg-card: rgba(255, 255, 255, 0.72); @@ -255,8 +262,21 @@ --grad-a: rgba(37, 99, 235, 0.13); --grad-c: rgba(37, 99, 235, 0.08); } -* { margin:0; padding:0; box-sizing:border-box; font-family:var(--font-sans) } -.selectable, .msg .text, .msg .tc-args, .msg .tc-result, .msg .reasoning-body, pre, input, textarea, .term-buf { +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: var(--font-sans); +} +.selectable, +.msg .text, +.msg .tc-args, +.msg .tc-result, +.msg .reasoning-body, +pre, +input, +textarea, +.term-buf { user-select: text; -webkit-user-select: text; } @@ -266,36 +286,86 @@ body { color: var(--text-primary); min-height: 100vh; overflow-x: hidden; - transition: background .2s, color .2s; + transition: + background 0.2s, + color 0.2s; font-size: 14px; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; user-select: none; -webkit-user-select: none; } -#app { display:flex; height:100vh; overflow:hidden; position:relative; z-index:1 } +#app { + display: flex; + height: 100vh; + overflow: hidden; + position: relative; + z-index: 1; +} /* ===== 沉浸式标题栏 ===== */ .titlebar { - position: fixed; top: 0; left: 0; right: 0; height: 36px; z-index: 1100; - display: flex; align-items: center; + position: fixed; + top: 0; + left: 0; + right: 0; + height: 36px; + z-index: 1100; + display: flex; + align-items: center; background: var(--bg-secondary); backdrop-filter: blur(var(--glass-blur)) saturate(1.4); -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(1.4); border-bottom: 1px solid var(--glass-border); - -webkit-app-region: drag; user-select: none; + -webkit-app-region: drag; + user-select: none; +} +.titlebar-title { + font-size: 12px; + font-weight: 600; + color: var(--text-muted); + letter-spacing: 0.02em; + padding-left: 12px; + display: flex; + align-items: center; + gap: 8px; +} +.titlebar-logo { + width: 18px; + height: 18px; + border-radius: 50%; + object-fit: cover; + flex-shrink: 0; +} +.titlebar-controls { + margin-left: auto; + display: flex; + height: 36px; + -webkit-app-region: no-drag; } -.titlebar-title { font-size: 12px; font-weight: 600; color: var(--text-muted); letter-spacing: .02em; padding-left: 12px; display: flex; align-items: center; gap: 8px } -.titlebar-logo { width: 18px; height: 18px; border-radius: 50%; object-fit: cover; flex-shrink: 0 } -.titlebar-controls { margin-left: auto; display: flex; height: 36px; -webkit-app-region: no-drag } .tb-btn { - width: 46px; height: 36px; border: none; background: transparent; - color: var(--text-secondary); display: flex; align-items: center; justify-content: center; - cursor: pointer; transition: background .13s; + width: 46px; + height: 36px; + border: none; + background: transparent; + color: var(--text-secondary); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background 0.13s; +} +.tb-btn:hover { + background: var(--glass-hover); + color: var(--text-primary); +} +.tb-btn.tb-close:hover { + background: #e81123; + color: #fff; +} +body.maximized .tb-max svg { + transform: scale(0.85); } -.tb-btn:hover { background: var(--glass-hover); color: var(--text-primary) } -.tb-btn.tb-close:hover { background: #e81123; color: #fff } -body.maximized .tb-max svg { transform: scale(.85) } /* ===== Icon Rail (主视图导航) ===== */ .rail { @@ -315,75 +385,162 @@ body.maximized .tb-max svg { transform: scale(.85) } height: calc(100% - 36px); z-index: 100; } -.rail .rail-logo { width:34px; height:34px; margin-bottom:10px; overflow:hidden } -.rail .rail-logo img { width:100%; height:100%; border-radius:50%; object-fit:cover } -.rail .rail-btn { - width: 38px; height: 38px; - display: flex; align-items: center; justify-content: center; - border: none; background: transparent; color: var(--text-muted); - cursor: pointer; border-radius: var(--radius-md); - transition: all .15s; position: relative; +.rail .rail-logo { + width: 34px; + height: 34px; + margin-bottom: 10px; + overflow: hidden; +} +.rail .rail-logo img { + width: 100%; + height: 100%; + border-radius: 50%; + object-fit: cover; +} +.rail .rail-btn { + width: 38px; + height: 38px; + display: flex; + align-items: center; + justify-content: center; + border: none; + background: transparent; + color: var(--text-muted); + cursor: pointer; + border-radius: var(--radius-md); + transition: all 0.15s; + position: relative; +} +.rail .rail-btn svg { + width: 20px; + height: 20px; +} +.rail .rail-btn:hover { + color: var(--text-primary); + background: var(--glass-hover); +} +.rail .rail-btn.active { + color: var(--accent); + background: var(--accent-bg); } -.rail .rail-btn svg { width:20px; height:20px } -.rail .rail-btn:hover { color: var(--text-primary); background: var(--glass-hover) } -.rail .rail-btn.active { color: var(--accent); background: var(--accent-bg) } .rail .rail-btn.active::before { - content: ""; position: absolute; left: -8px; top: 8px; bottom: 8px; width: 3px; - background: var(--accent); border-radius: var(--radius-pill); + content: ""; + position: absolute; + left: -8px; + top: 8px; + bottom: 8px; + width: 3px; + background: var(--accent); + border-radius: var(--radius-pill); } .rail .rail-btn[title]:hover::after { content: attr(title); - position: absolute; left: 46px; top: 50%; transform: translateY(-50%); - background: var(--glass-bg-strong); backdrop-filter: blur(8px); - color: var(--text-primary); font-size: 12px; padding: 4px 10px; - border-radius: var(--radius-sm); border: 1px solid var(--glass-border); - white-space: nowrap; z-index: 200; pointer-events: none; + position: absolute; + left: 46px; + top: 50%; + transform: translateY(-50%); + background: var(--glass-bg-strong); + backdrop-filter: blur(8px); + color: var(--text-primary); + font-size: 12px; + padding: 4px 10px; + border-radius: var(--radius-sm); + border: 1px solid var(--glass-border); + white-space: nowrap; + z-index: 200; + pointer-events: none; +} +.rail .rail-spacer { + flex: 1; } -.rail .rail-spacer { flex: 1 } .rail .conn-dot { - width: 10px; height: 10px; border-radius: 50%; - background: var(--text-muted); margin-bottom: 4px; + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--text-muted); + margin-bottom: 4px; +} +.rail .conn-dot.dot-green { + background: var(--success); + box-shadow: 0 0 8px rgba(23, 169, 100, 0.6); +} +.rail .conn-dot.dot-red { + background: var(--error); +} +.rail .conn-dot.dot-yellow { + background: var(--warning); } -.rail .conn-dot.dot-green { background: var(--success); box-shadow: 0 0 8px rgba(23,169,100,.6) } -.rail .conn-dot.dot-red { background: var(--error) } -.rail .conn-dot.dot-yellow { background: var(--warning) } /* ===== Main ===== */ .main { - flex: 1; min-width: 0; min-height: 0; - display: flex; flex-direction: column; + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; overflow: hidden; padding-top: 36px; } .topbar { - display: flex; align-items: center; gap: 12px; + display: flex; + align-items: center; + gap: 12px; padding: 10px 24px; background: var(--bg-secondary); backdrop-filter: blur(var(--glass-blur)) saturate(1.4); -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(1.4); border-bottom: 1px solid var(--glass-border); - position: sticky; top: 0; z-index: 50; + position: sticky; + top: 0; + z-index: 50; flex-shrink: 0; } -.topbar h1 { font-size: 16px; font-weight: 700; color: var(--accent); white-space: nowrap } +.topbar h1 { + font-size: 16px; + font-weight: 700; + color: var(--accent); + white-space: nowrap; +} .topbar .conn-indicator { - display: flex; align-items: center; gap: 6px; cursor: pointer; - padding: 4px 10px; border-radius: var(--radius-pill); - font-size: 12px; color: var(--text-secondary); + display: flex; + align-items: center; + gap: 6px; + cursor: pointer; + padding: 4px 10px; + border-radius: var(--radius-pill); + font-size: 12px; + color: var(--text-secondary); border: 1px solid var(--glass-border); - transition: all .15s; user-select: none; + transition: all 0.15s; + user-select: none; +} +.topbar .conn-indicator:hover { + background: var(--glass-hover); + color: var(--text-primary); +} +.topbar .spacer { + flex: 1; } -.topbar .conn-indicator:hover { background: var(--glass-hover); color: var(--text-primary) } -.topbar .spacer { flex: 1 } .theme-btn { - background: none; border: 1px solid var(--border-color); - color: var(--text-secondary); cursor: pointer; - padding: 4px 8px; border-radius: var(--radius-sm); font-size: 14px; line-height: 1; - transition: all .15s; + background: none; + border: 1px solid var(--border-color); + color: var(--text-secondary); + cursor: pointer; + padding: 4px 8px; + border-radius: var(--radius-sm); + font-size: 14px; + line-height: 1; + transition: all 0.15s; +} +.theme-btn:hover { + color: var(--accent); + border-color: var(--accent); } -.theme-btn:hover { color: var(--accent); border-color: var(--accent) } #bg-layer { - position: fixed; inset: 0; z-index: 0; pointer-events: none; + position: fixed; + inset: 0; + z-index: 0; + pointer-events: none; background-image: radial-gradient(900px 700px at 85% -10%, var(--grad-a), transparent 60%), radial-gradient(800px 600px at -10% 20%, var(--grad-b), transparent 60%), @@ -394,42 +551,129 @@ body.maximized .tb-max svg { transform: scale(.85) } background-repeat: no-repeat; transform: scale(1.04); filter: blur(calc(var(--bg-blur, 0) * 1px)); - transition: filter .25s var(--ease-out); + transition: filter 0.25s var(--ease-out); } .palette-pop { - position: fixed; bottom: 56px; left: 6px; width: 210px; - padding: 12px; background: var(--glass-bg-strong); - backdrop-filter: blur(12px); border: 1px solid var(--glass-border); - border-radius: var(--radius-md); box-shadow: var(--shadow-lg); - display: none; z-index: 300; + position: fixed; + bottom: 56px; + left: 6px; + width: 210px; + padding: 12px; + background: var(--glass-bg-strong); + backdrop-filter: blur(12px); + border: 1px solid var(--glass-border); + border-radius: var(--radius-md); + box-shadow: var(--shadow-lg); + display: none; + z-index: 300; +} +.palette-pop.on { + display: block; + animation: viewIn 0.16s var(--ease-out); +} +.palette-pop h4 { + font-size: 11px; + font-weight: 600; + color: var(--text-secondary); + margin: 2px 0 6px; } -.palette-pop.on { display: block; animation: viewIn .16s var(--ease-out) } -.palette-pop h4 { font-size: 11px; font-weight: 600; color: var(--text-secondary); margin: 2px 0 6px } .palette-pop button.cdot { - width: 22px; height: 22px; border-radius: 50%; - border: 2px solid rgba(255,255,255,.18); cursor: pointer; - margin: 3px; padding: 0; vertical-align: middle; transition: transform .15s; + width: 22px; + height: 22px; + border-radius: 50%; + border: 2px solid rgba(255, 255, 255, 0.18); + cursor: pointer; + margin: 3px; + padding: 0; + vertical-align: middle; + transition: transform 0.15s; +} +.palette-pop button.cdot:hover { + transform: scale(1.25); +} +.palette-pop button.cdot.on { + border-color: var(--text-primary); + box-shadow: var(--shadow-glow); + transform: scale(1.15); } -.palette-pop button.cdot:hover { transform: scale(1.25) } -.palette-pop button.cdot.on { border-color: var(--text-primary); box-shadow: var(--shadow-glow); transform: scale(1.15) } .palette-pop input[type="text"] { - background: var(--bg-input); border: 1px solid var(--border-color); - border-radius: var(--radius-sm); padding: 5px 8px; color: var(--text-primary); - font-size: 11px; width: 100%; margin-bottom: 6px; outline: none; + background: var(--bg-input); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + padding: 5px 8px; + color: var(--text-primary); + font-size: 11px; + width: 100%; + margin-bottom: 6px; + outline: none; +} +.palette-pop input[type="range"] { + width: 80px; + margin: 0; + accent-color: var(--accent); + vertical-align: middle; +} +.palette-pop .pp-row { + display: flex; + align-items: center; + gap: 6px; + margin-top: 4px; +} +.palette-pop .pp-row .btn { + padding: 3px 10px; + font-size: 11px; +} +.palette-pop .pp-val { + font-size: 10px; + color: var(--text-muted); + min-width: 96px; + text-align: right; +} +.lang-btn { + font-size: 13px; + min-width: 28px; + cursor: pointer; + padding: 4px 8px; + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + text-align: center; + background: none; + color: var(--text-secondary); +} +.lang-btn:hover { + color: var(--accent); + border-color: var(--accent); +} +.container { + padding: 16px 24px; + flex: 1; + min-width: 0; + min-height: 0; + overflow: hidden; +} +.view { + display: none; + height: 100%; + overflow-y: auto; +} +.view.active { + display: block; + animation: viewIn 0.18s var(--ease-out); +} +@keyframes viewIn { + from { + opacity: 0; + transform: translateY(6px); + } + to { + opacity: 1; + transform: translateY(0); + } } -.palette-pop input[type="range"] { width: 80px; margin: 0; accent-color: var(--accent); vertical-align: middle } -.palette-pop .pp-row { display: flex; align-items: center; gap: 6px; margin-top: 4px } -.palette-pop .pp-row .btn { padding: 3px 10px; font-size: 11px } -.palette-pop .pp-val { font-size: 10px; color: var(--text-muted); min-width: 96px; text-align: right } -.lang-btn { font-size: 13px; min-width: 28px; cursor: pointer; padding: 4px 8px; border: 1px solid var(--border-color); border-radius: var(--radius-sm); text-align: center; background:none; color:var(--text-secondary) } -.lang-btn:hover { color: var(--accent); border-color: var(--accent) } -.container { padding: 16px 24px; flex: 1; min-width: 0; min-height: 0; overflow: hidden } -.view { display: none; height: 100%; overflow-y: auto } -.view.active { display: block; animation: viewIn .18s var(--ease-out) } -@keyframes viewIn { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: translateY(0) } } /* ===== Cards ===== */ .card { + position: relative; background: var(--bg-card); backdrop-filter: blur(var(--glass-blur)) saturate(1.3); -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(1.3); @@ -438,241 +682,1281 @@ body.maximized .tb-max svg { transform: scale(.85) } padding: 20px; margin-bottom: 16px; box-shadow: var(--shadow-sm); - transition: background .2s, border .2s, box-shadow .2s; + transition: + background 0.2s, + border 0.2s, + box-shadow 0.2s, + transform 0.2s var(--ease-out); +} +.card:hover { + box-shadow: var(--shadow-md); + border-color: color-mix(in srgb, var(--accent) 28%, transparent); + transform: translateY(-1px); +} +.card h2 { + font-size: 15px; + font-weight: 600; + margin-bottom: 12px; + color: var(--text-primary); +} +.card h3 { + font-size: 13px; + font-weight: 600; + color: var(--text-secondary); + margin: 16px 0 8px; +} +.grid-2 { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} +.grid-3 { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: 16px; +} +.grid-4 { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 16px; +} +.stat-value { + font-size: 26px; + font-weight: 700; + color: var(--accent); +} +.stat-label { + font-size: 11px; + color: var(--text-muted); + margin-top: 2px; +} +.stat-card { + padding: 16px 20px; + transition: transform 0.12s var(--ease-out); +} +.stat-card:hover { + transform: translateY(-2px); +} +.status-dot { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 6px; +} +.dot-green { + background: var(--success); +} +.dot-green.pulse { + animation: pulseDot 2s ease-in-out infinite; +} +.dot-yellow { + background: var(--warning); +} +.dot-red { + background: var(--error); +} +.dot-gray { + background: #475569; +} +@keyframes pulseDot { + 0%, + 100% { + opacity: 1; + transform: scale(1); + } + 50% { + opacity: 0.6; + transform: scale(1.3); + } +} +table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} +th { + text-align: left; + padding: 8px 10px; + color: var(--text-muted); + font-weight: 500; + border-bottom: 1px solid var(--border-color); + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.5px; +} +td { + padding: 8px 10px; + border-bottom: 1px solid var(--kv-border); +} +tr:hover td { + background: var(--bg-hover); +} +.badge { + display: inline-block; + padding: 2px 8px; + border-radius: 4px; + font-size: 11px; + font-weight: 500; +} +.badge-green { + background: rgba(23, 169, 100, 0.18); + color: #6ee7a8; +} +.badge-red { + background: rgba(219, 54, 148, 0.18); + color: #ff9ec6; +} +.badge-yellow { + background: rgba(217, 154, 43, 0.18); + color: #fcd9a0; +} +.badge-blue { + background: rgba(63, 110, 245, 0.18); + color: #a3b8ff; } -.card:hover { box-shadow: var(--shadow-md) } -.card h2 { font-size: 15px; font-weight: 600; margin-bottom: 12px; color: var(--text-primary) } -.card h3 { font-size: 13px; font-weight: 600; color: var(--text-secondary); margin: 16px 0 8px } -.grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:16px } -.grid-3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:16px } -.grid-4 { display:grid; grid-template-columns:repeat(4,1fr); gap:16px } -.stat-value { font-size: 26px; font-weight: 700; color: var(--accent) } -.stat-label { font-size: 11px; color: var(--text-muted); margin-top: 2px } -.stat-card { padding: 16px 20px; transition: transform .12s var(--ease-out) } -.stat-card:hover { transform: translateY(-2px) } -.status-dot { display:inline-block; width:8px; height:8px; border-radius:50%; margin-right:6px } -.dot-green { background: var(--success) } -.dot-green.pulse { animation: pulseDot 2s ease-in-out infinite } -.dot-yellow { background: var(--warning) } -.dot-red { background: var(--error) } -.dot-gray { background: #475569 } -@keyframes pulseDot { 0%,100% { opacity:1; transform:scale(1) } 50% { opacity:.6; transform:scale(1.3) } } -table { width:100%; border-collapse:collapse; font-size:13px } -th { text-align:left; padding:8px 10px; color:var(--text-muted); font-weight:500; border-bottom:1px solid var(--border-color); font-size:11px; text-transform:uppercase; letter-spacing:.5px } -td { padding:8px 10px; border-bottom:1px solid var(--kv-border) } -tr:hover td { background: var(--bg-hover) } -.badge { display:inline-block; padding:2px 8px; border-radius:4px; font-size:11px; font-weight:500 } -.badge-green { background: rgba(23,169,100,.18); color: #6ee7a8 } -.badge-red { background: rgba(219,54,148,.18); color: #ff9ec6 } -.badge-yellow { background: rgba(217,154,43,.18); color: #fcd9a0 } -.badge-blue { background: rgba(63,110,245,.18); color: #a3b8ff } .btn { - padding: 6px 14px; border-radius: var(--radius-md); border: none; - font-size: 12px; cursor: pointer; font-weight: 500; - transition: all .12s var(--ease-out); + padding: 6px 14px; + border-radius: var(--radius-md); + border: none; + font-size: 12px; + cursor: pointer; + font-weight: 500; + transition: all 0.12s var(--ease-out); } -.btn:active { transform: scale(.97) } -.btn-primary { background: var(--accent); color: #fff } -.btn-primary:hover { background: var(--sakura-500) } -.btn-danger { background: var(--error); color: #fff } -.btn-danger:hover { background: var(--sakura-700) } -.btn-warning { background: var(--save-btn-border); color: #fff } -.btn-warning:hover { background: #b87e1f } -.btn-sm { padding: 4px 10px; font-size: 11px } -.btn-ghost { background: transparent; border: 1px solid var(--btn-ghost-border); color: var(--text-secondary) } -.btn-ghost:hover { background: var(--btn-ghost-hover-bg); color: var(--text-primary) } -input, textarea, select { - background: var(--bg-input); border: 1px solid var(--border-color); - border-radius: var(--radius-sm); padding: 8px 12px; - color: var(--text-primary); font-size: 13px; width: 100%; - margin-bottom: 10px; outline: none; - transition: border .15s, background .2s, color .2s; +.btn:active { + transform: scale(0.97); +} +.btn-primary { + background: var(--accent); + color: #fff; +} +.btn-primary:hover { + background: var(--sakura-500); +} +.btn-danger { + background: var(--error); + color: #fff; +} +.btn-danger:hover { + background: var(--sakura-700); +} +.btn-warning { + background: var(--save-btn-border); + color: #fff; +} +.btn-warning:hover { + background: #b87e1f; +} +.btn-sm { + padding: 4px 10px; + font-size: 11px; +} +.btn-ghost { + background: transparent; + border: 1px solid var(--btn-ghost-border); + color: var(--text-secondary); +} +.btn-ghost:hover { + background: var(--btn-ghost-hover-bg); + color: var(--text-primary); +} +input, +textarea, +select { + background: var(--bg-input); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + padding: 8px 12px; + color: var(--text-primary); + font-size: 13px; + width: 100%; + margin-bottom: 10px; + outline: none; + transition: + border 0.15s, + background 0.2s, + color 0.2s; +} +input:focus, +textarea:focus, +select:focus { + border-color: var(--accent); +} +textarea { + resize: vertical; + min-height: 80px; + font-family: var(--font-mono); + font-size: 12px; +} +label { + display: block; + font-size: 11px; + color: var(--text-secondary); + margin-bottom: 3px; + font-weight: 500; +} +pre { + background: var(--pre-bg); + border-radius: var(--radius-sm); + padding: 12px; + font-size: 12px; + overflow-x: auto; + color: var(--pre-color); + font-family: var(--font-mono); + max-height: 400px; + overflow-y: auto; +} +code { + font-family: var(--font-mono); + font-size: 12px; + color: var(--pre-color); +} +.empty-state { + text-align: center; + padding: 40px 20px; + color: var(--text-muted); +} +.empty-state p { + font-size: 14px; + margin-bottom: 8px; } -input:focus, textarea:focus, select:focus { border-color: var(--accent) } -textarea { resize: vertical; min-height: 80px; font-family: var(--font-mono); font-size: 12px } -label { display: block; font-size: 11px; color: var(--text-secondary); margin-bottom: 3px; font-weight: 500 } -pre { background: var(--pre-bg); border-radius: var(--radius-sm); padding: 12px; font-size: 12px; overflow-x: auto; color: var(--pre-color); font-family: var(--font-mono); max-height: 400px; overflow-y: auto } -code { font-family: var(--font-mono); font-size: 12px; color: var(--pre-color) } -.empty-state { text-align: center; padding: 40px 20px; color: var(--text-muted) } -.empty-state p { font-size: 14px; margin-bottom: 8px } /* ===== Chat (对话主页) ===== */ -.chat-layout { display: flex; flex-direction: column; gap: 12px; height: 100%; min-height: 0 } -.chat-tabs { display: flex; gap: 4px; flex-wrap: wrap; border-bottom: 1px solid var(--border-color); padding-bottom: 10px } -.chat-tabs span { padding: 6px 14px; font-size: 13px; cursor: pointer; color: var(--text-muted); border-radius: var(--radius-pill); border: 1px solid transparent; transition: all .15s } -.chat-tabs span:hover { color: var(--text-primary); background: var(--bg-hover) } -.chat-tabs span.active { color: var(--accent); background: var(--accent-bg); border-color: color-mix(in srgb, var(--accent) 35%, transparent) } -.chat-panel { display: none; flex: 1; min-height: 0; flex-direction: column; overflow: hidden } -.chat-panel.active { display: flex } -.chat-main { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column } -.chat-main .card { flex: 1; display: flex; flex-direction: column; margin-bottom: 0; min-height: 0; background: transparent; border: none; box-shadow: none; backdrop-filter: none; padding: 0; overflow: hidden } -.chat-main .card h2 { flex-shrink: 0 } -.chat-messages { flex: 1; overflow-y: auto; padding: 18px 18px 26px; margin-bottom: 0; display: flex; flex-direction: column; gap: 6px; min-height: 0 } -.msg { display: flex; gap: 8px; margin-bottom: 2px; align-items: flex-start; max-width: 100% } -.msg-user { flex-direction: row-reverse; align-self: flex-end } -.msg-assistant { align-self: flex-start } -.msg-system { align-self: center; max-width: 90% } -.msg-avatar { width: 28px; height: 28px; border-radius: 50%; overflow: hidden; display: flex; align-items: center; justify-content: center; font-size: 12px; flex-shrink: 0 } -.msg-avatar img { width: 100%; height: 100%; object-fit: cover; display: block } -.msg-assistant .msg-avatar img { transform: scale(1.5) } -.msg-avatar svg { display: block; width: 16px; height: 16px } -.msg-user .msg-avatar { background: var(--msg-user-bg); color: var(--msg-user-color) } -.msg-assistant .msg-avatar { background: transparent } -.msg-system .msg-avatar { background: var(--msg-system-bg); color: var(--msg-system-color) } -.msg-content { min-width: 0; flex: 1 } - .msg-content .msg-bubble + .msg-bubble { margin-top: 6px } - .msg-channel { align-self: flex-start } - .msg-channel .msg-avatar.chan-avatar { color: #ffffff; font-weight: 700; font-size: 13px; text-transform: uppercase } - .msg-channel .msg-chan-name { font-size: 10px; color: var(--text-muted); opacity: .8; margin-bottom: 2px; padding-left: 4px; letter-spacing: .5px } - .msg-channel .msg-bubble { background: var(--msg-bubble-bg); color: var(--msg-bubble-color); border-bottom-left-radius: 4px; border: 1px solid var(--msg-bubble-border); box-shadow: 0 2px 8px rgba(0,0,0,.28) } -.msg-bubble { padding: 9px 12px; border-radius: var(--radius-md); font-size: 15px; line-height: 1.62; word-break: break-word; position: relative } -.msg-source { font-size: 11px; opacity: .55; margin-bottom: 4px; color: inherit } -.msg-user .msg-bubble { background: var(--msg-bubble-bg); color: var(--msg-bubble-color); border-bottom-right-radius: 4px; border: 1px solid var(--msg-bubble-border) } -.msg-assistant .msg-bubble { background: var(--msg-bubble-bg); color: var(--msg-bubble-color); border-bottom-left-radius: 4px; border: 1px solid var(--msg-bubble-border); box-shadow: 0 2px 10px rgba(0,0,0,.3) } -.msg-system .msg-bubble { background: var(--msg-system-bg); color: var(--msg-system-color); text-align: center; font-size: 12px; border: 1px solid var(--msg-bubble-border) } -.msg-bubble .text { white-space: pre-wrap } -.msg-bubble .text p { margin: 4px 0 } -.msg-bubble .text h1, .msg-bubble .text h2, .msg-bubble .text h3 { font-size: 1em; margin: 8px 0 4px } -.msg-bubble .text ul, .msg-bubble .text ol { padding-left: 20px; margin: 4px 0 } -.msg-bubble .text pre { background: var(--pre-bg); color: var(--pre-color); border-radius: var(--radius-sm); padding: 8px; margin: 4px 0; overflow-x: auto; font-size: 12px; line-height: 1.5; border: 1px solid var(--border-color); max-height: 200px } -.msg-bubble .text code { background: var(--pre-bg); color: var(--pre-color); padding: 1px 4px; border-radius: 3px; font-size: 12px } -.msg-bubble .text pre code { background: none; padding: 0 } -.msg-bubble .text blockquote { border-left: 3px solid var(--border-color); padding-left: 8px; margin: 4px 0; opacity: .8 } -.msg-bubble .text table { border-collapse: collapse; margin: 4px 0; font-size: 12px; width: 100% } -.msg-bubble .text th, .msg-bubble .text td { border: 1px solid var(--border-color); padding: 3px 6px; text-align: left } -.msg-bubble .text img { max-width: 100%; border-radius: var(--radius-sm) } -.msg-bubble .reasoning { border-left: 2px solid #dddddd; padding-left: 8px; margin: 6px 0; font-size: 11px; opacity: .8 } -.msg-bubble .reasoning-title { cursor: pointer; font-size: 10px; font-weight: 600; user-select: none; margin-bottom: 2px; opacity: .6 } -.msg-bubble .reasoning-body { line-height: 1.4 } -.msg-bubble .tool-call { background: var(--bg-hover); color: var(--text-secondary); border-radius: var(--radius-sm); padding: 7px 10px; margin: 6px 0; font-size: 11px; border: 1px solid var(--kv-border); border-left: 3px solid var(--accent); cursor: pointer } -.msg-bubble .tool-call .tc-line { display: flex; align-items: center; gap: 6px; font-size: 11px; user-select: none } -.msg-bubble .tool-call .tc-ico { display: inline-flex; flex-shrink: 0 } -.msg-bubble .tool-call .tc-name { font-weight: 600; color: var(--text-primary) } -.msg-bubble .tool-call .tc-state { margin-left: 6px; font-size: 9.5px; font-weight: 500; padding: 1px 6px; border-radius: 999px; flex-shrink: 0; margin-left: auto } -.msg-bubble .tool-call .tc-run { background: rgba(63,110,245,.18); color: #a3b8ff } -.msg-bubble .tool-call .tc-done { background: rgba(23,169,100,.18); color: #6ee7a8 } -.msg-bubble .tool-call .tc-deny { background: rgba(219,54,148,.18); color: #ff9ec6 } -.msg-bubble .tool-call .tc-caret { font-size: 10px; color: var(--text-muted); transition: transform .15s var(--ease-out) } -.msg-bubble .tool-call.open .tc-caret { transform: rotate(180deg) } -.msg-bubble .tool-call .tc-detail { margin-top: 6px } -.msg-bubble .tool-call .tc-args { font-family: var(--font-mono); font-size: 11px; opacity: .85; white-space: pre-wrap; word-break: break-all; margin-top: 5px; background: var(--pre-bg); color: var(--pre-color); border-radius: 4px; padding: 5px 7px } -.msg-bubble .tool-call .tc-result { font-family: var(--font-mono); font-size: 11px; opacity: .72; white-space: pre-wrap; word-break: break-all; margin-top: 5px; background: var(--pre-bg); color: var(--pre-color); border-radius: 4px; padding: 5px 7px; max-height: 80px; overflow-y: auto } -[data-theme=light] .msg-bubble .tool-call .tc-run { color: #3f6ef5 } -[data-theme=light] .msg-bubble .tool-call .tc-done { color: #128a52 } -[data-theme=light] .msg-bubble .tool-call .tc-deny { color: #c2185b } -.msg-bubble .thinking-tools { display: flex; gap: 6px; align-items: center; flex-wrap: wrap } -.msg-bubble .thinking-tool { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--text-secondary); background: var(--pre-bg); border-radius: 999px; padding: 3px 10px } -.msg-bubble .thinking-tool.pill-in { animation: pillIn .25s var(--ease-out) both } -@keyframes pillIn { from { opacity: 0; transform: translateX(8px) } to { opacity: 1; transform: none } } -.msg-bubble .live-spinner { width: 15px; height: 15px; border-radius: 50%; border: 2px solid var(--msg-user-bg); border-top-color: var(--accent); animation: spin .7s linear infinite; flex-shrink: 0; display: inline-block; vertical-align: middle } +.chat-layout { + display: flex; + flex-direction: column; + gap: 12px; + height: 100%; + min-height: 0; +} +.chat-tabs { + display: flex; + gap: 4px; + flex-wrap: wrap; + border-bottom: 1px solid var(--border-color); + padding-bottom: 10px; +} +.chat-tabs span { + padding: 6px 14px; + font-size: 13px; + cursor: pointer; + color: var(--text-muted); + border-radius: var(--radius-pill); + border: 1px solid transparent; + transition: all 0.15s; +} +.chat-tabs span:hover { + color: var(--text-primary); + background: var(--bg-hover); +} +.chat-tabs span.active { + color: var(--accent); + background: var(--accent-bg); + border-color: color-mix(in srgb, var(--accent) 35%, transparent); +} +.chat-panel { + display: none; + flex: 1; + min-height: 0; + flex-direction: column; + overflow: hidden; +} +.chat-panel.active { + display: flex; +} +.chat-main { + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; +} +.chat-main .card { + flex: 1; + display: flex; + flex-direction: column; + margin-bottom: 0; + min-height: 0; + background: transparent; + border: none; + box-shadow: none; + backdrop-filter: none; + padding: 0; + overflow: hidden; +} +.chat-main .card h2 { + flex-shrink: 0; +} +.chat-messages { + flex: 1; + overflow-y: auto; + padding: 18px 18px 26px; + margin-bottom: 0; + display: flex; + flex-direction: column; + gap: 6px; + min-height: 0; +} +.msg { + display: flex; + gap: 8px; + margin-bottom: 2px; + align-items: flex-start; + max-width: 100%; +} +.msg-user { + flex-direction: row-reverse; + align-self: flex-end; +} +.msg-assistant { + align-self: flex-start; +} +.msg-system { + align-self: center; + max-width: 90%; +} +.msg-avatar { + width: 28px; + height: 28px; + border-radius: 50%; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + flex-shrink: 0; +} +.msg-avatar img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} +.msg-assistant .msg-avatar img { + transform: scale(1.5); +} +.msg-avatar svg { + display: block; + width: 16px; + height: 16px; +} +.msg-user .msg-avatar { + background: var(--msg-user-bg); + color: var(--msg-user-color); +} +.msg-assistant .msg-avatar { + background: transparent; +} +.msg-system .msg-avatar { + background: var(--msg-system-bg); + color: var(--msg-system-color); +} +.msg-content { + min-width: 0; + flex: 1; +} +.msg-content .msg-bubble + .msg-bubble { + margin-top: 6px; +} +.msg-channel { + align-self: flex-start; +} +.msg-channel .msg-avatar.chan-avatar { + color: #ffffff; + font-weight: 700; + font-size: 13px; + text-transform: uppercase; +} +.msg-channel .msg-chan-name { + font-size: 10px; + color: var(--text-muted); + opacity: 0.8; + margin-bottom: 2px; + padding-left: 4px; + letter-spacing: 0.5px; +} +.msg-channel .msg-bubble { + background: var(--msg-bubble-bg); + color: var(--msg-bubble-color); + border-bottom-left-radius: 4px; + border: 1px solid var(--msg-bubble-border); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.28); +} +.msg-bubble { + padding: 9px 12px; + border-radius: var(--radius-md); + font-size: 15px; + line-height: 1.62; + word-break: break-word; + position: relative; +} +.msg-source { + font-size: 11px; + opacity: 0.55; + margin-bottom: 4px; + color: inherit; +} +.msg-user .msg-bubble { + background: var(--msg-bubble-bg); + color: var(--msg-bubble-color); + border-bottom-right-radius: 4px; + border: 1px solid var(--msg-bubble-border); +} +.msg-assistant .msg-bubble { + background: var(--msg-bubble-bg); + color: var(--msg-bubble-color); + border-bottom-left-radius: 4px; + border: 1px solid var(--msg-bubble-border); + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); +} +.msg-system .msg-bubble { + background: var(--msg-system-bg); + color: var(--msg-system-color); + text-align: center; + font-size: 12px; + border: 1px solid var(--msg-bubble-border); +} +.msg-bubble .text { + white-space: pre-wrap; +} +.msg-bubble .text p { + margin: 4px 0; +} +.msg-bubble .text h1, +.msg-bubble .text h2, +.msg-bubble .text h3 { + font-size: 1em; + margin: 8px 0 4px; +} +.msg-bubble .text ul, +.msg-bubble .text ol { + padding-left: 20px; + margin: 4px 0; +} +.msg-bubble .text pre { + background: var(--pre-bg); + color: var(--pre-color); + border-radius: var(--radius-sm); + padding: 8px; + margin: 4px 0; + overflow-x: auto; + font-size: 12px; + line-height: 1.5; + border: 1px solid var(--border-color); + max-height: 200px; +} +.msg-bubble .text code { + background: var(--pre-bg); + color: var(--pre-color); + padding: 1px 4px; + border-radius: 3px; + font-size: 12px; +} +.msg-bubble .text pre code { + background: none; + padding: 0; +} +.msg-bubble .text blockquote { + border-left: 3px solid var(--border-color); + padding-left: 8px; + margin: 4px 0; + opacity: 0.8; +} +.msg-bubble .text table { + border-collapse: collapse; + margin: 4px 0; + font-size: 12px; + width: 100%; +} +.msg-bubble .text th, +.msg-bubble .text td { + border: 1px solid var(--border-color); + padding: 3px 6px; + text-align: left; +} +.msg-bubble .text img { + max-width: 100%; + border-radius: var(--radius-sm); +} +.msg-bubble .reasoning { + border-left: 2px solid #dddddd; + padding-left: 8px; + margin: 6px 0; + font-size: 11px; + opacity: 0.8; +} +.msg-bubble .reasoning-title { + cursor: pointer; + font-size: 10px; + font-weight: 600; + user-select: none; + margin-bottom: 2px; + opacity: 0.6; +} +.msg-bubble .reasoning-body { + line-height: 1.4; +} +.msg-bubble .tool-call { + background: var(--bg-hover); + color: var(--text-secondary); + border-radius: var(--radius-sm); + padding: 7px 10px; + margin: 6px 0; + font-size: 11px; + border: 1px solid var(--kv-border); + border-left: 3px solid var(--accent); + cursor: pointer; +} +.msg-bubble .tool-call .tc-line { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + user-select: none; +} +.msg-bubble .tool-call .tc-ico { + display: inline-flex; + flex-shrink: 0; +} +.msg-bubble .tool-call .tc-name { + font-weight: 600; + color: var(--text-primary); +} +.msg-bubble .tool-call .tc-state { + margin-left: 6px; + font-size: 9.5px; + font-weight: 500; + padding: 1px 6px; + border-radius: 999px; + flex-shrink: 0; + margin-left: auto; +} +.msg-bubble .tool-call .tc-run { + background: rgba(63, 110, 245, 0.18); + color: #a3b8ff; +} +.msg-bubble .tool-call .tc-done { + background: rgba(23, 169, 100, 0.18); + color: #6ee7a8; +} +.msg-bubble .tool-call .tc-deny { + background: rgba(219, 54, 148, 0.18); + color: #ff9ec6; +} +.msg-bubble .tool-call .tc-caret { + font-size: 10px; + color: var(--text-muted); + transition: transform 0.15s var(--ease-out); +} +.msg-bubble .tool-call.open .tc-caret { + transform: rotate(180deg); +} +.msg-bubble .tool-call .tc-detail { + margin-top: 6px; +} +.msg-bubble .tool-call .tc-args { + font-family: var(--font-mono); + font-size: 11px; + opacity: 0.85; + white-space: pre-wrap; + word-break: break-all; + margin-top: 5px; + background: var(--pre-bg); + color: var(--pre-color); + border-radius: 4px; + padding: 5px 7px; +} +.msg-bubble .tool-call .tc-result { + font-family: var(--font-mono); + font-size: 11px; + opacity: 0.72; + white-space: pre-wrap; + word-break: break-all; + margin-top: 5px; + background: var(--pre-bg); + color: var(--pre-color); + border-radius: 4px; + padding: 5px 7px; + max-height: 80px; + overflow-y: auto; +} +[data-theme="light"] .msg-bubble .tool-call .tc-run { + color: #3f6ef5; +} +[data-theme="light"] .msg-bubble .tool-call .tc-done { + color: #128a52; +} +[data-theme="light"] .msg-bubble .tool-call .tc-deny { + color: #c2185b; +} +.msg-bubble .thinking-tools { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; +} +.msg-bubble .thinking-tool { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 11px; + color: var(--text-secondary); + background: var(--pre-bg); + border-radius: 999px; + padding: 3px 10px; +} +.msg-bubble .thinking-tool.pill-in { + animation: pillIn 0.25s var(--ease-out) both; +} +@keyframes pillIn { + from { + opacity: 0; + transform: translateX(8px); + } + to { + opacity: 1; + transform: none; + } +} +.msg-bubble .live-spinner { + width: 15px; + height: 15px; + border-radius: 50%; + border: 2px solid var(--msg-user-bg); + border-top-color: var(--accent); + animation: spin 0.7s linear infinite; + flex-shrink: 0; + display: inline-block; + vertical-align: middle; +} .msg-bubble .live-spinner + .thinking-tools, -.msg-bubble .live-spinner + .text { margin-left: 8px } -.msg-bubble.grow-in { animation: bubbleGrow .5s var(--ease-out) both } -.msg-bubble.grow-in .text { animation: textFadeIn .35s ease .125s both } -@keyframes bubbleGrow { from { max-height: 28px; opacity: .4 } to { max-height: 3000px; opacity: 1 } } -@keyframes textFadeIn { from { opacity: 0 } to { opacity: 1 } } -.tool-call.tool-drip-in { animation: toolDripIn .3s var(--ease-out) both } -@keyframes toolDripIn { from { opacity: 0; transform: translateY(-14px) scale(.98) } to { opacity: 1; transform: none } } -.chat-input-row { display: flex; gap: 8px; flex-shrink: 0; padding-top: 10px } -.chat-input-row input { flex: 1; margin-bottom: 0 } -.chat-input-row button { flex-shrink: 0; margin-bottom: 0 } -#sm-container-chat { height: 480px; background: var(--bg-input); border-radius: var(--radius-md); border: 1px solid var(--glass-border); overflow: hidden; position: relative } -#sm-container-chat canvas { display: block } -.loading { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--loading-border); border-radius: 50%; border-top-color: var(--loading-top); animation: spin .6s linear infinite } -.loading-spinner { width: 32px; height: 32px; border: 3px solid color-mix(in srgb, var(--accent) 15%, transparent); border-top: 3px solid var(--accent); border-radius: 50%; animation: spin .8s linear infinite } -@keyframes spin { to { transform: rotate(360deg) } } +.msg-bubble .live-spinner + .text { + margin-left: 8px; +} +.msg-bubble.grow-in { + animation: bubbleGrow 0.5s var(--ease-out) both; +} +.msg-bubble.grow-in .text { + animation: textFadeIn 0.35s ease 0.125s both; +} +@keyframes bubbleGrow { + from { + max-height: 28px; + opacity: 0.4; + } + to { + max-height: 3000px; + opacity: 1; + } +} +@keyframes textFadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +.tool-call.tool-drip-in { + animation: toolDripIn 0.3s var(--ease-out) both; +} +@keyframes toolDripIn { + from { + opacity: 0; + transform: translateY(-14px) scale(0.98); + } + to { + opacity: 1; + transform: none; + } +} +.chat-input-row { + display: flex; + gap: 8px; + flex-shrink: 0; + padding-top: 10px; +} +.chat-input-row input { + flex: 1; + margin-bottom: 0; +} +.chat-input-row button { + flex-shrink: 0; + margin-bottom: 0; +} +#sm-container-chat { + height: 480px; + background: var(--bg-input); + border-radius: var(--radius-md); + border: 1px solid var(--glass-border); + overflow: hidden; + position: relative; +} +#sm-container-chat canvas { + display: block; +} +.loading { + display: inline-block; + width: 16px; + height: 16px; + border: 2px solid var(--loading-border); + border-radius: 50%; + border-top-color: var(--loading-top); + animation: spin 0.6s linear infinite; +} +.loading-spinner { + width: 32px; + height: 32px; + border: 3px solid color-mix(in srgb, var(--accent) 15%, transparent); + border-top: 3px solid var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} /* ===== 未配置后端引导 ===== */ .setup-card { - text-align: center; padding: 48px 32px; - display: flex; flex-direction: column; align-items: center; gap: 16px; + text-align: center; + padding: 48px 32px; + display: flex; + flex-direction: column; + align-items: center; + gap: 16px; +} +.setup-card .setup-icon { + width: 64px; + height: 64px; + opacity: 0.8; +} +.setup-card h2 { + font-size: 18px; + margin-bottom: 0; +} +.setup-card p { + color: var(--text-muted); + font-size: 13px; + max-width: 420px; + line-height: 1.6; +} +.setup-card .btn { + padding: 8px 20px; + font-size: 13px; } -.setup-card .setup-icon { width: 64px; height: 64px; opacity: .8 } -.setup-card h2 { font-size: 18px; margin-bottom: 0 } -.setup-card p { color: var(--text-muted); font-size: 13px; max-width: 420px; line-height: 1.6 } -.setup-card .btn { padding: 8px 20px; font-size: 13px } /* ===== Settings ===== */ -.settings-tabs { display: flex; gap: 4px; flex-wrap: wrap; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin-bottom: 16px } -.settings-tabs span { padding: 6px 14px; font-size: 13px; cursor: pointer; color: var(--text-muted); border-radius: var(--radius-pill); border: 1px solid transparent; transition: all .15s } -.settings-tabs span:hover { color: var(--text-primary); background: var(--bg-hover) } -.settings-tabs span.active { color: var(--accent); background: var(--accent-bg); border-color: color-mix(in srgb, var(--accent) 35%, transparent) } -.settings-content { min-width: 0 } -.settings-key { font-family: var(--font-mono); font-size: 11px; color: var(--text-muted); margin-bottom: 2px } -.kv-row { display: flex; padding: 6px 0; border-bottom: 1px solid var(--kv-border); font-size: 13px } -.kv-row .key { color: var(--text-muted); width: 180px; flex-shrink: 0 } -.kv-row .val { color: var(--text-primary); word-break: break-all } -.tool-badge { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 10px; background: var(--accent-bg); color: var(--accent); margin: 1px } -.check-pass { color: #6ee7a8 } -.check-fail { color: #ff9ec6 } -.check-skip { color: var(--text-secondary) } -.health-item { display: flex; align-items: center; gap: 10px; padding: 8px 12px; background: var(--bg-input); border-radius: var(--radius-sm); font-size: 13px } -.health-item .check-name { flex: 1 } -.health-item .check-status { font-size: 11px; font-weight: 500 } +.settings-tabs { + display: flex; + gap: 4px; + flex-wrap: wrap; + border-bottom: 1px solid var(--border-color); + padding-bottom: 10px; + margin-bottom: 16px; +} +.settings-tabs span { + padding: 6px 14px; + font-size: 13px; + cursor: pointer; + color: var(--text-muted); + border-radius: var(--radius-pill); + border: 1px solid transparent; + transition: all 0.15s; +} +.settings-tabs span:hover { + color: var(--text-primary); + background: var(--bg-hover); +} +.settings-tabs span.active { + color: var(--accent); + background: var(--accent-bg); + border-color: color-mix(in srgb, var(--accent) 35%, transparent); +} +.settings-content { + min-width: 0; +} +.settings-key { + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-muted); + margin-bottom: 2px; +} +.kv-row { + display: flex; + padding: 6px 0; + border-bottom: 1px solid var(--kv-border); + font-size: 13px; +} +.kv-row .key { + color: var(--text-muted); + width: 180px; + flex-shrink: 0; +} +.kv-row .val { + color: var(--text-primary); + word-break: break-all; +} +.tool-badge { + display: inline-block; + padding: 1px 6px; + border-radius: 3px; + font-size: 10px; + background: var(--accent-bg); + color: var(--accent); + margin: 1px; +} +.check-pass { + color: #6ee7a8; +} +.check-fail { + color: #ff9ec6; +} +.check-skip { + color: var(--text-secondary); +} +.health-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + background: var(--bg-input); + border-radius: var(--radius-sm); + font-size: 13px; +} +.health-item .check-name { + flex: 1; +} +.health-item .check-status { + font-size: 11px; + font-weight: 500; +} /* ===== 连接管理 (设置页内嵌) ===== */ -.conn-item { display: flex; align-items: center; gap: 12px; padding: 12px 16px; border: 1px solid var(--glass-border); border-radius: var(--radius-md); margin-bottom: 8px; cursor: pointer; transition: all .12s } -.conn-item:hover { background: var(--bg-hover); border-color: var(--accent) } -.conn-item.active { border-color: var(--accent); background: var(--accent-bg) } -.conn-item .conn-info { flex: 1; min-width: 0 } -.conn-item .conn-name { font-size: 14px; font-weight: 600; color: var(--text-primary) } -.conn-item .conn-url { font-size: 11px; color: var(--text-muted); margin-top: 2px } -.conn-item .conn-actions { display: flex; gap: 4px; flex-shrink: 0 } -.conn-form h3 { font-size: 15px; margin-bottom: 12px } -.conn-form-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px } +.conn-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + border: 1px solid var(--glass-border); + border-radius: var(--radius-md); + margin-bottom: 8px; + cursor: pointer; + transition: all 0.12s; +} +.conn-item:hover { + background: var(--bg-hover); + border-color: var(--accent); +} +.conn-item.active { + border-color: var(--accent); + background: var(--accent-bg); +} +.conn-item .conn-info { + flex: 1; + min-width: 0; +} +.conn-item .conn-name { + font-size: 14px; + font-weight: 600; + color: var(--text-primary); +} +.conn-item .gw-badge { + display: inline-block; + margin-left: 6px; + padding: 1px 6px; + font-size: 10px; + font-weight: 600; + line-height: 1.4; + color: var(--accent); + background: var(--accent-bg); + border: 1px solid var(--accent); + border-radius: 8px; + vertical-align: 1px; +} +.conn-item .conn-url { + font-size: 11px; + color: var(--text-muted); + margin-top: 2px; +} +.conn-item .conn-actions { + display: flex; + gap: 4px; + flex-shrink: 0; +} +.conn-form h3 { + font-size: 15px; + margin-bottom: 12px; +} +.conn-form-actions { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 12px; +} /* ===== Toast ===== */ .toast { - position: fixed; bottom: 20px; right: 20px; - background: var(--toast-bg); color: var(--toast-color); + position: fixed; + bottom: 20px; + right: 20px; + background: var(--toast-bg); + color: var(--toast-color); backdrop-filter: blur(10px); - padding: 10px 20px; border-radius: var(--radius-md); font-size: 13px; - display: none; z-index: 300; - border: 1px solid rgba(23,169,100,.3); + padding: 10px 20px; + border-radius: var(--radius-md); + font-size: 13px; + display: none; + z-index: 300; + border: 1px solid rgba(23, 169, 100, 0.3); box-shadow: var(--shadow-md); - animation: toastIn .15s var(--ease-out); + animation: toastIn 0.15s var(--ease-out); +} +.toast.error { + background: var(--toast-error-bg); + color: var(--toast-error-color); + border-color: rgba(219, 54, 148, 0.3); +} +.toast.warn { + background: rgba(217, 154, 43, 0.16); + color: #fcd9a0; + border-color: rgba(217, 154, 43, 0.35); +} +[data-theme="light"] .toast.warn { + background: rgba(217, 154, 43, 0.14); + color: #92400e; + border-color: rgba(217, 154, 43, 0.3); +} +@keyframes toastIn { + from { + opacity: 0; + transform: translateX(30px); + } + to { + opacity: 1; + transform: translateX(0); + } +} + +/* ===== 动效补齐:自定义确认弹窗(替换原生 confirm) ===== */ +.confirm-overlay { + position: fixed; + inset: 0; + z-index: 400; + display: none; + align-items: center; + justify-content: center; + background: rgba(8, 10, 20, 0.55); + backdrop-filter: blur(6px); + -webkit-backdrop-filter: blur(6px); + animation: overlayIn 0.18s var(--ease-out); +} +.confirm-box { + width: min(420px, 88vw); + background: var(--glass-bg-strong); + backdrop-filter: blur(14px); + -webkit-backdrop-filter: blur(14px); + border: 1px solid var(--glass-border); + border-radius: var(--radius-lg); + padding: 22px 24px; + box-shadow: var(--shadow-lg); + animation: confirmIn 0.22s var(--ease-out); +} +.confirm-box h3 { + font-size: 15px; + font-weight: 600; + color: var(--text-primary); + margin-bottom: 10px; +} +.confirm-box p { + font-size: 13px; + color: var(--text-secondary); + line-height: 1.6; + margin-bottom: 18px; + white-space: pre-wrap; + word-break: break-word; +} +.confirm-actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} +@keyframes overlayIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +@keyframes confirmIn { + from { + opacity: 0; + transform: translateY(10px) scale(0.97); + } + to { + opacity: 1; + transform: none; + } +} + +/* ===== 动效补齐:卡片 3D tilt + 光标光斑 ===== */ +.card.tilt { + transform-style: preserve-3d; + transition: + box-shadow var(--dur-normal) var(--ease-out), + transform 0.15s ease-out; +} +.card.tilt .tilt-glow { + position: absolute; + inset: 0; + border-radius: inherit; + pointer-events: none; + opacity: 0; + transition: opacity 0.3s ease-out; + background: radial-gradient( + 240px circle at var(--mx, 50%) var(--my, 50%), + rgba(255, 127, 172, 0.12), + transparent 70% + ); +} +.card.tilt:hover .tilt-glow { + opacity: 1; +} + +/* ===== 动效补齐:无障碍(焦点环 / 选区 / 降级动效) ===== */ +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: var(--radius-sm); +} +::selection { + background: rgba(255, 127, 172, 0.35); +} + +/* ===== 动效补齐:主题化滚动条 ===== */ +::-webkit-scrollbar { + width: 10px; + height: 10px; +} +::-webkit-scrollbar-track { + background: transparent; +} +::-webkit-scrollbar-thumb { + background: rgba(255, 127, 172, 0.25); + border-radius: var(--radius-pill); + border: 2px solid transparent; + background-clip: content-box; +} +::-webkit-scrollbar-thumb:hover { + background: rgba(255, 127, 172, 0.45); + background-clip: content-box; + border: 2px solid transparent; +} +* { + scrollbar-width: thin; + scrollbar-color: rgba(255, 127, 172, 0.35) transparent; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } + .card.tilt { + transform: none !important; + transition: none !important; + } + .card.tilt .tilt-glow { + display: none !important; + } } -.toast.error { background: var(--toast-error-bg); color: var(--toast-error-color); border-color: rgba(219,54,148,.3) } -@keyframes toastIn { from { opacity: 0; transform: translateX(30px) } to { opacity: 1; transform: translateX(0) } } /* ===== Starmap ===== */ -#starmap-stats, #starmap-info { - position: absolute; top: 16px; - background: rgba(10,10,26,.85); padding: 12px 16px; border-radius: var(--radius-md); - border: 1px solid rgba(100,100,255,.3); font-size: 13px; z-index: 10; - backdrop-filter: blur(10px); color: #ccc; +#starmap-stats, +#starmap-info { + position: absolute; + top: 16px; + background: rgba(10, 10, 26, 0.85); + padding: 12px 16px; + border-radius: var(--radius-md); + border: 1px solid rgba(100, 100, 255, 0.3); + font-size: 13px; + z-index: 10; + backdrop-filter: blur(10px); + color: #ccc; +} +#starmap-stats { + left: 16px; +} +#starmap-info { + right: 16px; + display: none; + max-width: 260px; +} +#starmap-stats h3, +#starmap-info h3 { + margin-bottom: 6px; + font-size: 14px; +} +#starmap-stats h3 { + color: #4488ff; +} +#starmap-info h3 { + color: #44ff88; +} +#starmap-stats p, +#starmap-info p { + margin: 2px 0; + color: #888; + font-size: 12px; +} +#starmap-stats span { + color: #fff; + font-weight: 700; +} +#starmap-info .label { + color: #666; +} +#starmap-loading { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + font-size: 18px; + color: #4488ff; + z-index: 20; +} +.starmap-toggle { + position: absolute; + bottom: 16px; + left: 50%; + transform: translateX(-50%); + display: flex; + gap: 8px; + z-index: 10; +} +.starmap-toggle button { + background: rgba(10, 10, 26, 0.85); + border: 1px solid rgba(100, 100, 255, 0.3); + color: #aaa; + padding: 6px 14px; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 12px; + font-family: inherit; + backdrop-filter: blur(10px); + transition: all 0.2s; +} +.starmap-toggle button:hover { + background: rgba(68, 136, 255, 0.2); + color: #fff; + border-color: rgba(68, 136, 255, 0.6); +} +.starmap-toggle button.on { + background: rgba(68, 136, 255, 0.3); + color: #4488ff; + border-color: #4488ff; +} +.fade-in { + animation: fadeIn 0.2s var(--ease-out); +} +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(4px); + } + to { + opacity: 1; + transform: translateY(0); + } } -#starmap-stats { left: 16px } -#starmap-info { right: 16px; display: none; max-width: 260px } -#starmap-stats h3, #starmap-info h3 { margin-bottom: 6px; font-size: 14px } -#starmap-stats h3 { color: #4488ff } -#starmap-info h3 { color: #44ff88 } -#starmap-stats p, #starmap-info p { margin: 2px 0; color: #888; font-size: 12px } -#starmap-stats span { color: #fff; font-weight: 700 } -#starmap-info .label { color: #666 } -#starmap-loading { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); font-size: 18px; color: #4488ff; z-index: 20 } -.starmap-toggle { position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%); display: flex; gap: 8px; z-index: 10 } -.starmap-toggle button { background: rgba(10,10,26,.85); border: 1px solid rgba(100,100,255,.3); color: #aaa; padding: 6px 14px; border-radius: var(--radius-sm); cursor: pointer; font-size: 12px; font-family: inherit; backdrop-filter: blur(10px); transition: all .2s } -.starmap-toggle button:hover { background: rgba(68,136,255,.2); color: #fff; border-color: rgba(68,136,255,.6) } -.starmap-toggle button.on { background: rgba(68,136,255,.3); color: #4488ff; border-color: #4488ff } -.fade-in { animation: fadeIn .2s var(--ease-out) } -@keyframes fadeIn { from { opacity: 0; transform: translateY(4px) } to { opacity: 1; transform: translateY(0) } } -@media(max-width:768px) { - .rail { width: 48px } - .container { padding: 12px } - .card { padding: 12px } - .grid-2, .grid-3, .grid-4 { grid-template-columns: 1fr } - .stat-value { font-size: 20px } - .kv-row { flex-direction: column; gap: 2px } - .kv-row .key { width: auto } - .msg { max-width: 100% } - .term-screen { background: #0f1115; border: 1px solid #2a2e35; border-radius: 8px; margin: 6px 0 4px 0; overflow: hidden; font-size: 11px; line-height: 1.45 } - .term-screen .term-head { display: flex; align-items: center; gap: 6px; padding: 4px 8px; background: #1a1d23; color: #9aa0a8; font-size: 10px; border-bottom: 1px solid #2a2e35; font-family: var(--font-mono) } - .term-screen .term-head .term-dot { width: 8px; height: 8px; border-radius: 50%; background: #3fb950; flex-shrink: 0 } - .term-screen .term-head .term-dot.stopped { background: #d29922 } - .term-screen pre.term-buf { margin: 0; padding: 6px 8px; background: transparent; color: #d8dee9; font-family: var(--font-mono); font-size: 11px; white-space: pre-wrap; word-break: break-all; max-height: 260px; overflow-y: auto; scrollbar-width: thin } - .term-screen pre.term-buf::-webkit-scrollbar { width: 6px } - .term-screen pre.term-buf::-webkit-scrollbar-thumb { background: #33373d; border-radius: 3px } - .health-item { flex-wrap: wrap; gap: 4px } +@media (max-width: 768px) { + .rail { + width: 48px; + } + .container { + padding: 12px; + } + .card { + padding: 12px; + } + .grid-2, + .grid-3, + .grid-4 { + grid-template-columns: 1fr; + } + .stat-value { + font-size: 20px; + } + .kv-row { + flex-direction: column; + gap: 2px; + } + .kv-row .key { + width: auto; + } + .msg { + max-width: 100%; + } + .term-screen { + background: #0f1115; + border: 1px solid #2a2e35; + border-radius: 8px; + margin: 6px 0 4px 0; + overflow: hidden; + font-size: 11px; + line-height: 1.45; + } + .term-screen .term-head { + display: flex; + align-items: center; + gap: 6px; + padding: 4px 8px; + background: #1a1d23; + color: #9aa0a8; + font-size: 10px; + border-bottom: 1px solid #2a2e35; + font-family: var(--font-mono); + } + .term-screen .term-head .term-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #3fb950; + flex-shrink: 0; + } + .term-screen .term-head .term-dot.stopped { + background: #d29922; + } + .term-screen pre.term-buf { + margin: 0; + padding: 6px 8px; + background: transparent; + color: #d8dee9; + font-family: var(--font-mono); + font-size: 11px; + white-space: pre-wrap; + word-break: break-all; + max-height: 260px; + overflow-y: auto; + scrollbar-width: thin; + } + .term-screen pre.term-buf::-webkit-scrollbar { + width: 6px; + } + .term-screen pre.term-buf::-webkit-scrollbar-thumb { + background: #33373d; + border-radius: 3px; + } + .health-item { + flex-wrap: wrap; + gap: 4px; + } } diff --git a/cmd/gui/renderer/vendor/three.min.js b/cmd/gui/renderer/vendor/three.min.js new file mode 100644 index 0000000..e63cd53 --- /dev/null +++ b/cmd/gui/renderer/vendor/three.min.js @@ -0,0 +1,6 @@ +/** + * @license + * Copyright 2010-2021 Three.js Authors + * SPDX-License-Identifier: MIT + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="128",n=100,i=300,r=301,s=302,a=303,o=304,l=306,c=307,h=1e3,u=1001,d=1002,p=1003,m=1004,f=1005,g=1006,v=1007,y=1008,x=1009,_=1012,w=1014,b=1015,M=1016,S=1020,T=1022,E=1023,A=1026,L=1027,R=33776,C=33777,P=33778,D=33779,I=35840,N=35841,B=35842,z=35843,F=37492,O=37496,H=2300,G=2301,U=2302,k=2400,V=2401,W=2402,j=2500,q=2501,X=3e3,Y=3001,Z=3007,J=3002,Q=3004,K=3005,$=3006,tt=7680,et=35044,nt=35048,it="300 es";class rt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e>8&255]+st[t>>16&255]+st[t>>24&255]+"-"+st[255&e]+st[e>>8&255]+"-"+st[e>>16&15|64]+st[e>>24&255]+"-"+st[63&n|128]+st[n>>8&255]+"-"+st[n>>16&255]+st[n>>24&255]+st[255&i]+st[i>>8&255]+st[i>>16&255]+st[i>>24&255]).toUpperCase()}function ht(t,e,n){return Math.max(e,Math.min(n,t))}function ut(t,e){return(t%e+e)%e}function dt(t,e,n){return(1-n)*t+n*e}function pt(t){return 0==(t&t-1)&&0!==t}function mt(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function ft(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}var gt=Object.freeze({__proto__:null,DEG2RAD:ot,RAD2DEG:lt,generateUUID:ct,clamp:ht,euclideanModulo:ut,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:dt,damp:function(t,e,n,i){return dt(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(ut(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){return void 0!==t&&(at=t%2147483647),at=16807*at%2147483647,(at-1)/2147483646},degToRad:function(t){return t*ot},radToDeg:function(t){return t*lt},isPowerOfTwo:pt,ceilPowerOfTwo:mt,floorPowerOfTwo:ft,setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}});class vt{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t,e){return void 0!==e?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this)}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t,e){return void 0!==e?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this)}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.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}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e,n){return void 0!==n&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}}vt.prototype.isVector2=!0;class yt{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],y=i[4],x=i[7],_=i[2],w=i[5],b=i[8];return r[0]=s*m+a*v+o*_,r[3]=s*f+a*y+o*w,r[6]=s*g+a*x+o*b,r[1]=l*m+c*v+h*_,r[4]=l*f+c*y+h*w,r[7]=l*g+c*x+h*b,r[2]=u*m+d*v+p*_,r[5]=u*f+d*y+p*w,r[8]=u*g+d*x+p*b,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){const n=this.elements;return n[0]*=t,n[3]*=t,n[6]*=t,n[1]*=e,n[4]*=e,n[7]*=e,this}rotate(t){const e=Math.cos(t),n=Math.sin(t),i=this.elements,r=i[0],s=i[3],a=i[6],o=i[1],l=i[4],c=i[7];return i[0]=e*r+n*o,i[3]=e*s+n*l,i[6]=e*a+n*c,i[1]=-n*r+e*o,i[4]=-n*s+e*l,i[7]=-n*a+e*c,this}translate(t,e){const n=this.elements;return n[0]+=t*n[2],n[3]+=t*n[5],n[6]+=t*n[8],n[1]+=e*n[2],n[4]+=e*n[5],n[7]+=e*n[8],this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}let xt;yt.prototype.isMatrix3=!0;class _t{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===xt&&(xt=document.createElementNS("http://www.w3.org/1999/xhtml","canvas")),xt.width=t.width,xt.height=t.height;const n=xt.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=xt}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}}let wt=0;class bt extends rt{constructor(t=bt.DEFAULT_IMAGE,e=bt.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,l=1,c=3e3){super(),Object.defineProperty(this,"id",{value:wt++}),this.uuid=ct(),this.name="",this.image=t,this.mipmaps=[],this.mapping=e,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new vt(0,0),this.repeat=new vt(1,1),this.center=new vt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new yt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=c,this.version=0,this.onUpdate=null}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(t){return this.name=t.name,this.image=t.image,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.encoding=t.encoding,this}toJSON(t){const e=void 0===t||"string"==typeof t;if(!e&&void 0!==t.textures[this.uuid])return t.textures[this.uuid];const n={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,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,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(void 0!==this.image){const i=this.image;if(void 0===i.uuid&&(i.uuid=ct()),!e&&void 0===t.images[i.uuid]){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t1)switch(this.wrapS){case h:t.x=t.x-Math.floor(t.x);break;case u:t.x=t.x<0?0:1;break;case d:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case h:t.y=t.y-Math.floor(t.y);break;case u:t.y=t.y<0?0:1;break;case d:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&this.version++}}function Mt(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?_t.getDataURL(t):t.data?{data:Array.prototype.slice.call(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}bt.DEFAULT_IMAGE=void 0,bt.DEFAULT_MAPPING=i,bt.prototype.isTexture=!0;class St{constructor(t=0,e=0,n=0,i=1){this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){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: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t,e){return void 0!==e?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this)}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t,e){return void 0!==e?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this)}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e){if(!t||!t.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!1!==e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(ht(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,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(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._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 t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t,e){return void 0!==e?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(t,e)):this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this._onChangeCallback(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){this.copy(t).slerp(e,n)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}At.prototype.isQuaternion=!0;class Lt{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t,e){return void 0!==e?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(t,e)):(this.x+=t.x,this.y+=t.y,this.z+=t.z,this)}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t,e){return void 0!==e?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(t,e)):(this.x-=t.x,this.y-=t.y,this.z-=t.z,this)}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t,e){return void 0!==e?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(t,e)):(this.x*=t.x,this.y*=t.y,this.z*=t.z,this)}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return t&&t.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(Ct.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Ct.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=o*e+s*i-a*n,c=o*n+a*e-r*i,h=o*i+r*n-s*e,u=-r*e-s*n-a*i;return this.x=l*o+u*-r+c*-a-h*-s,this.y=c*o+u*-s+h*-r-l*-a,this.z=h*o+u*-a+l*-s-c*-r,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}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=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.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(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t,e){return void 0!==e?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(t,e)):this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Rt.copy(this).projectOnVector(t),this.sub(Rt)}reflect(t){return this.sub(Rt.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(ht(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e,n){return void 0!==n&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}}Lt.prototype.isVector3=!0;const Rt=new Lt,Ct=new At;class Pt{constructor(t=new Lt(1/0,1/0,1/0),e=new Lt(-1/0,-1/0,-1/0)){this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.length;or&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromBufferAttribute(t){let e=1/0,n=1/0,i=1/0,r=-1/0,s=-1/0,a=-1/0;for(let o=0,l=t.count;or&&(r=l),c>s&&(s=c),h>a&&(a=h)}return this.min.set(e,n,i),this.max.set(r,s,a),this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return void 0===e&&(console.warn("THREE.Box3: .getParameter() target is now required"),e=new Lt),e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)}intersectsSphere(t){return this.clampPoint(t.center,It),It.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Ut),kt.subVectors(this.max,Ut),Bt.subVectors(t.a,Ut),zt.subVectors(t.b,Ut),Ft.subVectors(t.c,Ut),Ot.subVectors(zt,Bt),Ht.subVectors(Ft,zt),Gt.subVectors(Bt,Ft);let e=[0,-Ot.z,Ot.y,0,-Ht.z,Ht.y,0,-Gt.z,Gt.y,Ot.z,0,-Ot.x,Ht.z,0,-Ht.x,Gt.z,0,-Gt.x,-Ot.y,Ot.x,0,-Ht.y,Ht.x,0,-Gt.y,Gt.x,0];return!!jt(e,Bt,zt,Ft,kt)&&(e=[1,0,0,0,1,0,0,0,1],!!jt(e,Bt,zt,Ft,kt)&&(Vt.crossVectors(Ot,Ht),e=[Vt.x,Vt.y,Vt.z],jt(e,Bt,zt,Ft,kt)))}clampPoint(t,e){return void 0===e&&(console.warn("THREE.Box3: .clampPoint() target is now required"),e=new Lt),e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return It.copy(t).clamp(this.min,this.max).sub(t).length()}getBoundingSphere(t){return void 0===t&&console.error("THREE.Box3: .getBoundingSphere() target is now required"),this.getCenter(t.center),t.radius=.5*this.getSize(It).length(),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Dt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Dt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Dt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Dt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Dt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Dt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Dt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Dt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Dt)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}Pt.prototype.isBox3=!0;const Dt=[new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt],It=new Lt,Nt=new Pt,Bt=new Lt,zt=new Lt,Ft=new Lt,Ot=new Lt,Ht=new Lt,Gt=new Lt,Ut=new Lt,kt=new Lt,Vt=new Lt,Wt=new Lt;function jt(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Wt.fromArray(t,s);const a=r.x*Math.abs(Wt.x)+r.y*Math.abs(Wt.y)+r.z*Math.abs(Wt.z),o=e.dot(Wt),l=n.dot(Wt),c=i.dot(Wt);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const qt=new Pt,Xt=new Lt,Yt=new Lt,Zt=new Lt;class Jt{constructor(t=new Lt,e=-1){this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):qt.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return void 0===t&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),t=new Pt),this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){Zt.subVectors(t,this.center);const e=Zt.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.add(Zt.multiplyScalar(n/t)),this.radius+=n}return this}union(t){return Yt.subVectors(t.center,this.center).normalize().multiplyScalar(t.radius),this.expandByPoint(Xt.copy(t.center).add(Yt)),this.expandByPoint(Xt.copy(t.center).sub(Yt)),this}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Qt=new Lt,Kt=new Lt,$t=new Lt,te=new Lt,ee=new Lt,ne=new Lt,ie=new Lt;class re{constructor(t=new Lt,e=new Lt(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return void 0===e&&(console.warn("THREE.Ray: .at() target is now required"),e=new Lt),e.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Qt)),this}closestPointToPoint(t,e){void 0===e&&(console.warn("THREE.Ray: .closestPointToPoint() target is now required"),e=new Lt),e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Qt.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Qt.copy(this.direction).multiplyScalar(e).add(this.origin),Qt.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){Kt.copy(t).add(e).multiplyScalar(.5),$t.copy(e).sub(t).normalize(),te.copy(this.origin).sub(Kt);const r=.5*t.distanceTo(e),s=-this.direction.dot($t),a=te.dot(this.direction),o=-te.dot($t),l=te.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.direction).multiplyScalar(h).add(this.origin),i&&i.copy($t).multiplyScalar(u).add(Kt),d}intersectSphere(t,e){Qt.subVectors(t.center,this.origin);const n=Qt.dot(this.direction),i=Qt.dot(Qt)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return a<0&&o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||n!=n)&&(n=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,Qt)}intersectTriangle(t,e,n,i,r){ee.subVectors(e,t),ne.subVectors(n,t),ie.crossVectors(ee,ne);let s,a=this.direction.dot(ie);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}te.subVectors(this.origin,t);const o=s*this.direction.dot(ne.crossVectors(te,ne));if(o<0)return null;const l=s*this.direction.dot(ee.cross(te));if(l<0)return null;if(o+l>a)return null;const c=-s*te.dot(ie);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class se{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,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 se).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/ae.setFromMatrixColumn(t,0).length(),r=1/ae.setFromMatrixColumn(t,1).length(),s=1/ae.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){t&&t.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(le,t,ce)}lookAt(t,e,n){const i=this.elements;return de.subVectors(t,e),0===de.lengthSq()&&(de.z=1),de.normalize(),he.crossVectors(n,de),0===he.lengthSq()&&(1===Math.abs(n.z)?de.x+=1e-4:de.z+=1e-4,de.normalize(),he.crossVectors(n,de)),he.normalize(),ue.crossVectors(de,he),i[0]=he.x,i[4]=ue.x,i[8]=de.x,i[1]=he.y,i[5]=ue.y,i[9]=de.y,i[2]=he.z,i[6]=ue.z,i[10]=de.z,this}multiply(t,e){return void 0!==e?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(t,e)):this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],y=n[7],x=n[11],_=n[15],w=i[0],b=i[4],M=i[8],S=i[12],T=i[1],E=i[5],A=i[9],L=i[13],R=i[2],C=i[6],P=i[10],D=i[14],I=i[3],N=i[7],B=i[11],z=i[15];return r[0]=s*w+a*T+o*R+l*I,r[4]=s*b+a*E+o*C+l*N,r[8]=s*M+a*A+o*P+l*B,r[12]=s*S+a*L+o*D+l*z,r[1]=c*w+h*T+u*R+d*I,r[5]=c*b+h*E+u*C+d*N,r[9]=c*M+h*A+u*P+d*B,r[13]=c*S+h*L+u*D+d*z,r[2]=p*w+m*T+f*R+g*I,r[6]=p*b+m*E+f*C+g*N,r[10]=p*M+m*A+f*P+g*B,r[14]=p*S+m*L+f*D+g*z,r[3]=v*w+y*T+x*R+_*I,r[7]=v*b+y*E+x*C+_*N,r[11]=v*M+y*A+x*P+_*B,r[15]=v*S+y*L+x*D+_*z,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,y=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,_=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,w=e*v+n*y+i*x+r*_;if(0===w)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/w;return t[0]=v*b,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*b,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*b,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*b,t[4]=y*b,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*b,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*b,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*b,t[8]=x*b,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*b,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*b,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*b,t[12]=_*b,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*b,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*b,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*b,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n){return this.set(1,e,n,0,t,1,n,0,t,e,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,y=o*c,x=o*h,_=n.x,w=n.y,b=n.z;return i[0]=(1-(m+g))*_,i[1]=(d+x)*_,i[2]=(p-y)*_,i[3]=0,i[4]=(d-x)*w,i[5]=(1-(u+g))*w,i[6]=(f+v)*w,i[7]=0,i[8]=(p+y)*b,i[9]=(f-v)*b,i[10]=(1-(u+m))*b,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=ae.set(i[0],i[1],i[2]).length();const s=ae.set(i[4],i[5],i[6]).length(),a=ae.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],oe.copy(this);const o=1/r,l=1/s,c=1/a;return oe.elements[0]*=o,oe.elements[1]*=o,oe.elements[2]*=o,oe.elements[4]*=l,oe.elements[5]*=l,oe.elements[6]*=l,oe.elements[8]*=c,oe.elements[9]*=c,oe.elements[10]*=c,e.setFromRotationMatrix(oe),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s){void 0===s&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const a=this.elements,o=2*r/(e-t),l=2*r/(n-i),c=(e+t)/(e-t),h=(n+i)/(n-i),u=-(s+r)/(s-r),d=-2*s*r/(s-r);return a[0]=o,a[4]=0,a[8]=c,a[12]=0,a[1]=0,a[5]=l,a[9]=h,a[13]=0,a[2]=0,a[6]=0,a[10]=u,a[14]=d,a[3]=0,a[7]=0,a[11]=-1,a[15]=0,this}makeOrthographic(t,e,n,i,r,s){const a=this.elements,o=1/(e-t),l=1/(n-i),c=1/(s-r),h=(e+t)*o,u=(n+i)*l,d=(s+r)*c;return a[0]=2*o,a[4]=0,a[8]=0,a[12]=-h,a[1]=0,a[5]=2*l,a[9]=0,a[13]=-u,a[2]=0,a[6]=0,a[10]=-2*c,a[14]=-d,a[3]=0,a[7]=0,a[11]=0,a[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}se.prototype.isMatrix4=!0;const ae=new Lt,oe=new se,le=new Lt(0,0,0),ce=new Lt(1,1,1),he=new Lt,ue=new Lt,de=new Lt,pe=new se,me=new At;class fe{constructor(t=0,e=0,n=0,i=fe.DefaultOrder){this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._order=i||this._order,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e,n){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e=e||this._order){case"XYZ":this._y=Math.asin(ht(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ht(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(ht(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-ht(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(ht(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-ht(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!1!==n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return pe.makeRotationFromQuaternion(t),this.setFromRotationMatrix(pe,e,n)}setFromVector3(t,e){return this.set(t.x,t.y,t.z,e||this._order)}reorder(t){return me.setFromEuler(this),this.setFromQuaternion(me,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}toVector3(t){return t?t.set(this._x,this._y,this._z):new Lt(this._x,this._y,this._z)}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}}fe.prototype.isEuler=!0,fe.DefaultOrder="XYZ",fe.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class ge{constructor(){this.mask=1}set(t){this.mask=1<1){for(let t=0;t1){for(let t=0;t0){i.children=[];for(let e=0;e0){i.animations=[];for(let e=0;e0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e1?null:e.copy(n).multiplyScalar(r).add(t.start)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return void 0===t&&(console.warn("THREE.Plane: .coplanarPoint() target is now required"),t=new Lt),t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||Ie.getNormalMatrix(t),i=this.coplanarPoint(Pe).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}Ne.prototype.isPlane=!0;const Be=new Lt,ze=new Lt,Fe=new Lt,Oe=new Lt,He=new Lt,Ge=new Lt,Ue=new Lt,ke=new Lt,Ve=new Lt,We=new Lt;class je{constructor(t=new Lt,e=new Lt,n=new Lt){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,i){void 0===i&&(console.warn("THREE.Triangle: .getNormal() target is now required"),i=new Lt),i.subVectors(n,e),Be.subVectors(t,e),i.cross(Be);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){Be.subVectors(i,e),ze.subVectors(n,e),Fe.subVectors(t,e);const s=Be.dot(Be),a=Be.dot(ze),o=Be.dot(Fe),l=ze.dot(ze),c=ze.dot(Fe),h=s*l-a*a;if(void 0===r&&(console.warn("THREE.Triangle: .getBarycoord() target is now required"),r=new Lt),0===h)return r.set(-2,-1,-1);const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return this.getBarycoord(t,e,n,i,Oe),Oe.x>=0&&Oe.y>=0&&Oe.x+Oe.y<=1}static getUV(t,e,n,i,r,s,a,o){return this.getBarycoord(t,e,n,i,Oe),o.set(0,0),o.addScaledVector(r,Oe.x),o.addScaledVector(s,Oe.y),o.addScaledVector(a,Oe.z),o}static isFrontFacing(t,e,n,i){return Be.subVectors(n,e),ze.subVectors(t,e),Be.cross(ze).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Be.subVectors(this.c,this.b),ze.subVectors(this.a,this.b),.5*Be.cross(ze).length()}getMidpoint(t){return void 0===t&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),t=new Lt),t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return je.getNormal(this.a,this.b,this.c,t)}getPlane(t){return void 0===t&&(console.warn("THREE.Triangle: .getPlane() target is now required"),t=new Ne),t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return je.getBarycoord(t,this.a,this.b,this.c,e)}getUV(t,e,n,i,r){return je.getUV(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return je.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return je.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){void 0===e&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),e=new Lt);const n=this.a,i=this.b,r=this.c;let s,a;He.subVectors(i,n),Ge.subVectors(r,n),ke.subVectors(t,n);const o=He.dot(ke),l=Ge.dot(ke);if(o<=0&&l<=0)return e.copy(n);Ve.subVectors(t,i);const c=He.dot(Ve),h=Ge.dot(Ve);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(He,s);We.subVectors(t,r);const d=He.dot(We),p=Ge.dot(We);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Ge,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return Ue.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(Ue,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(He,s).addScaledVector(Ge,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}let qe=0;function Xe(){Object.defineProperty(this,"id",{value:qe++}),this.uuid=ct(),this.name="",this.type="Material",this.fog=!0,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=n,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=tt,this.stencilZFail=tt,this.stencilZPass=tt,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.alphaTest=0,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0}Xe.prototype=Object.assign(Object.create(rt.prototype),{constructor:Xe,isMaterial:!0,onBuild:function(){},onBeforeCompile:function(){},customProgramCacheKey:function(){return this.onBeforeCompile.toString()},setValues:function(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn("THREE.Material: '"+e+"' parameter is undefined.");continue}if("shading"===e){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===n;continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn("THREE."+this.type+": '"+e+"' is not a property of this material.")}},toJSON:function(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),this.sheen&&this.sheen.isColor&&(n.sheen=this.sheen.getHex()),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaToCoverage&&(n.alphaToCoverage=this.alphaToCoverage),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.morphTargets&&(n.morphTargets=!0),!0===this.morphNormals&&(n.morphNormals=!0),!0===this.skinning&&(n.skinning=!0),!0===this.flatShading&&(n.flatShading=this.flatShading),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),"{}"!==JSON.stringify(this.userData)&&(n.userData=this.userData),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n},clone:function(){return(new this.constructor).copy(this)},copy:function(t){this.name=t.name,this.fog=t.fog,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),Object.defineProperty(Xe.prototype,"needsUpdate",{set:function(t){!0===t&&this.version++}});const Ye={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},Ze={h:0,s:0,l:0},Je={h:0,s:0,l:0};function Qe(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}function Ke(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function $e(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}class tn{constructor(t,e,n){return void 0===e&&void 0===n?this.set(t):this.setRGB(t,e,n)}set(t){return t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t),this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,this}setRGB(t,e,n){return this.r=t,this.g=e,this.b=n,this}setHSL(t,e,n){if(t=ut(t,1),e=ht(e,0,1),n=ht(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=Qe(r,i,t+1/3),this.g=Qe(r,i,t),this.b=Qe(r,i,t-1/3)}return this}setStyle(t){function e(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(t)){let t;const i=n[1],r=n[2];switch(i){case"rgb":case"rgba":if(t=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(255,parseInt(t[1],10))/255,this.g=Math.min(255,parseInt(t[2],10))/255,this.b=Math.min(255,parseInt(t[3],10))/255,e(t[4]),this;if(t=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return this.r=Math.min(100,parseInt(t[1],10))/100,this.g=Math.min(100,parseInt(t[2],10))/100,this.b=Math.min(100,parseInt(t[3],10))/100,e(t[4]),this;break;case"hsl":case"hsla":if(t=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r)){const n=parseFloat(t[1])/360,i=parseInt(t[2],10)/100,r=parseInt(t[3],10)/100;return e(t[4]),this.setHSL(n,i,r)}}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const t=n[1],e=t.length;if(3===e)return this.r=parseInt(t.charAt(0)+t.charAt(0),16)/255,this.g=parseInt(t.charAt(1)+t.charAt(1),16)/255,this.b=parseInt(t.charAt(2)+t.charAt(2),16)/255,this;if(6===e)return this.r=parseInt(t.charAt(0)+t.charAt(1),16)/255,this.g=parseInt(t.charAt(2)+t.charAt(3),16)/255,this.b=parseInt(t.charAt(4)+t.charAt(5),16)/255,this}return t&&t.length>0?this.setColorName(t):this}setColorName(t){const e=Ye[t.toLowerCase()];return void 0!==e?this.setHex(e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copyGammaToLinear(t,e=2){return this.r=Math.pow(t.r,e),this.g=Math.pow(t.g,e),this.b=Math.pow(t.b,e),this}copyLinearToGamma(t,e=2){const n=e>0?1/e:1;return this.r=Math.pow(t.r,n),this.g=Math.pow(t.g,n),this.b=Math.pow(t.b,n),this}convertGammaToLinear(t){return this.copyGammaToLinear(this,t),this}convertLinearToGamma(t){return this.copyLinearToGamma(this,t),this}copySRGBToLinear(t){return this.r=Ke(t.r),this.g=Ke(t.g),this.b=Ke(t.b),this}copyLinearToSRGB(t){return this.r=$e(t.r),this.g=$e(t.g),this.b=$e(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(t){void 0===t&&(console.warn("THREE.Color: .getHSL() target is now required"),t={h:0,s:0,l:0});const e=this.r,n=this.g,i=this.b,r=Math.max(e,n,i),s=Math.min(e,n,i);let a,o;const l=(s+r)/2;if(s===r)a=0,o=0;else{const t=r-s;switch(o=l<=.5?t/(r+s):t/(2-r-s),r){case e:a=(n-i)/t+(ne&&(e=t[n]);return e}const vn={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function yn(t,e){return new vn[t](e)}let xn=0;const _n=new se,wn=new Ce,bn=new Lt,Mn=new Pt,Sn=new Pt,Tn=new Lt;class En extends rt{constructor(){super(),Object.defineProperty(this,"id",{value:xn++}),this.uuid=ct(),this.name="",this.type="BufferGeometry",this.index=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(t){return Array.isArray(t)?this.index=new(gn(t)>65535?dn:hn)(t,1):this.index=t,this}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return void 0!==this.attributes[t]}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;void 0!==e&&(e.applyMatrix4(t),e.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const e=(new yt).getNormalMatrix(t);n.applyNormalMatrix(e),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(t),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}rotateX(t){return _n.makeRotationX(t),this.applyMatrix4(_n),this}rotateY(t){return _n.makeRotationY(t),this.applyMatrix4(_n),this}rotateZ(t){return _n.makeRotationZ(t),this.applyMatrix4(_n),this}translate(t,e,n){return _n.makeTranslation(t,e,n),this.applyMatrix4(_n),this}scale(t,e,n){return _n.makeScale(t,e,n),this.applyMatrix4(_n),this}lookAt(t){return wn.lookAt(t),wn.updateMatrix(),this.applyMatrix4(wn.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(bn).negate(),this.translate(bn.x,bn.y,bn.z),this}setFromPoints(t){const e=[];for(let n=0,i=t.length;n0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new En).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t0){const t=e[n[0]];if(void 0!==t){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,n=t.length;e0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(t,e){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0===i)return;if(null===n.boundingSphere&&n.computeBoundingSphere(),Rn.copy(n.boundingSphere),Rn.applyMatrix4(r),!1===t.ray.intersectsSphere(Rn))return;if(An.copy(r).invert(),Ln.copy(t.ray).applyMatrix4(An),null!==n.boundingBox&&!1===Ln.intersectsBox(n.boundingBox))return;let s;if(n.isBufferGeometry){const r=n.index,a=n.attributes.position,o=n.morphAttributes.position,l=n.morphTargetsRelative,c=n.attributes.uv,h=n.attributes.uv2,u=n.groups,d=n.drawRange;if(null!==r)if(Array.isArray(i))for(let n=0,p=u.length;nn.far?null:{distance:c,point:Vn.clone(),object:t}}(t,e,n,i,Cn,Pn,Dn,kn);if(p){o&&(Hn.fromBufferAttribute(o,c),Gn.fromBufferAttribute(o,h),Un.fromBufferAttribute(o,u),p.uv=je.getUV(kn,Cn,Pn,Dn,Hn,Gn,Un,new vt)),l&&(Hn.fromBufferAttribute(l,c),Gn.fromBufferAttribute(l,h),Un.fromBufferAttribute(l,u),p.uv2=je.getUV(kn,Cn,Pn,Dn,Hn,Gn,Un,new vt));const t={a:c,b:h,c:u,normal:new Lt,materialIndex:0};je.getNormal(Cn,Pn,Dn,t.normal),p.face=t}return p}Wn.prototype.isMesh=!0;class qn extends En{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const y=s/f,x=p/g,_=s/2,w=p/2,b=m/2,M=f+1,S=g+1;let T=0,E=0;const A=new Lt;for(let s=0;s0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}Jn.prototype.isShaderMaterial=!0;class Qn extends Ce{constructor(){super(),this.type="Camera",this.matrixWorldInverse=new se,this.projectionMatrix=new se,this.projectionMatrixInverse=new se}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this}getWorldDirection(t){void 0===t&&(console.warn("THREE.Camera: .getWorldDirection() target is now required"),t=new Lt),this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}Qn.prototype.isCamera=!0;class Kn extends Qn{constructor(t=50,e=1,n=.1,i=2e3){super(),this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*lt*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*ot*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*lt*Math.atan(Math.tan(.5*ot*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*ot*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}Kn.prototype.isPerspectiveCamera=!0;const $n=90;class ti extends Ce{constructor(t,e,n){if(super(),this.type="CubeCamera",!0!==n.isWebGLCubeRenderTarget)return void console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");this.renderTarget=n;const i=new Kn($n,1,t,e);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new Lt(1,0,0)),this.add(i);const r=new Kn($n,1,t,e);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new Lt(-1,0,0)),this.add(r);const s=new Kn($n,1,t,e);s.layers=this.layers,s.up.set(0,0,1),s.lookAt(new Lt(0,1,0)),this.add(s);const a=new Kn($n,1,t,e);a.layers=this.layers,a.up.set(0,0,-1),a.lookAt(new Lt(0,-1,0)),this.add(a);const o=new Kn($n,1,t,e);o.layers=this.layers,o.up.set(0,-1,0),o.lookAt(new Lt(0,0,1)),this.add(o);const l=new Kn($n,1,t,e);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new Lt(0,0,-1)),this.add(l)}update(t,e){null===this.parent&&this.updateMatrixWorld();const n=this.renderTarget,[i,r,s,a,o,l]=this.children,c=t.xr.enabled,h=t.getRenderTarget();t.xr.enabled=!1;const u=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0),t.render(e,i),t.setRenderTarget(n,1),t.render(e,r),t.setRenderTarget(n,2),t.render(e,s),t.setRenderTarget(n,3),t.render(e,a),t.setRenderTarget(n,4),t.render(e,o),n.texture.generateMipmaps=u,t.setRenderTarget(n,5),t.render(e,l),t.setRenderTarget(h),t.xr.enabled=c}}class ei extends bt{constructor(t,e,n,i,s,a,o,l,c,h){super(t=void 0!==t?t:[],e=void 0!==e?e:r,n,i,s,a,o=void 0!==o?o:T,l,c,h),this._needsFlipEnvMap=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}ei.prototype.isCubeTexture=!0;class ni extends Tt{constructor(t,e,n){Number.isInteger(e)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),e=n),super(t,t,e),e=e||{},this.texture=new ei(void 0,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.encoding),this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:g,this.texture._needsFlipEnvMap=!1}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.format=E,this.texture.encoding=e.encoding,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new qn(5,5,5),r=new Jn({name:"CubemapFromEquirect",uniforms:Xn(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=e;const s=new Wn(i,r),a=e.minFilter;e.minFilter===y&&(e.minFilter=g);return new ti(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}ni.prototype.isWebGLCubeRenderTarget=!0;class ii extends bt{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.image={data:t||null,width:e||1,height:n||1},this.magFilter=void 0!==l?l:p,this.minFilter=void 0!==c?c:p,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.needsUpdate=!0}}ii.prototype.isDataTexture=!0;const ri=new Jt,si=new Lt;class ai{constructor(t=new Ne,e=new Ne,n=new Ne,i=new Ne,r=new Ne,s=new Ne){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t){const e=this.planes,n=t.elements,i=n[0],r=n[1],s=n[2],a=n[3],o=n[4],l=n[5],c=n[6],h=n[7],u=n[8],d=n[9],p=n[10],m=n[11],f=n[12],g=n[13],v=n[14],y=n[15];return e[0].setComponents(a-i,h-o,m-u,y-f).normalize(),e[1].setComponents(a+i,h+o,m+u,y+f).normalize(),e[2].setComponents(a+r,h+l,m+d,y+g).normalize(),e[3].setComponents(a-r,h-l,m-d,y-g).normalize(),e[4].setComponents(a-s,h-c,m-p,y-v).normalize(),e[5].setComponents(a+s,h+c,m+p,y+v).normalize(),this}intersectsObject(t){const e=t.geometry;return null===e.boundingSphere&&e.computeBoundingSphere(),ri.copy(e.boundingSphere).applyMatrix4(t.matrixWorld),this.intersectsSphere(ri)}intersectsSprite(t){return ri.center.set(0,0,0),ri.radius=.7071067811865476,ri.applyMatrix4(t.matrixWorld),this.intersectsSphere(ri)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)0?t.max.x:t.min.x,si.y=i.normal.y>0?t.max.y:t.min.y,si.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(si)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function oi(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function li(t,e){const n=e.isWebGL2,i=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),i.get(t)},remove:function(e){e.isInterleavedBufferAttribute&&(e=e.data);const n=i.get(e);n&&(t.deleteBuffer(n.buffer),i.delete(e))},update:function(e,r){if(e.isGLBufferAttribute){const t=i.get(e);return void((!t||t.version 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",encodings_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn 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 );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn 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 );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(\t\t0, 1,\t\t0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;",normal_fragment_maps:"#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t\tf.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif",shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3(\t1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108,\t1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605,\t1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmissionmap_fragment:"#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif",transmissionmap_pars_fragment:"#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif",uv_pars_fragment:"#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif",uv_vertex:"#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif",uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_frag:"uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",cube_frag:"#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}",normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"},ui={common:{diffuse:{value:new tn(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new yt},uv2Transform:{value:new yt},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new vt(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new tn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{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 tn(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},uvTransform:{value:new yt}},sprite:{diffuse:{value:new tn(15658734)},opacity:{value:1},center:{value:new vt(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},uvTransform:{value:new yt}}},di={basic:{uniforms:Yn([ui.common,ui.specularmap,ui.envmap,ui.aomap,ui.lightmap,ui.fog]),vertexShader:hi.meshbasic_vert,fragmentShader:hi.meshbasic_frag},lambert:{uniforms:Yn([ui.common,ui.specularmap,ui.envmap,ui.aomap,ui.lightmap,ui.emissivemap,ui.fog,ui.lights,{emissive:{value:new tn(0)}}]),vertexShader:hi.meshlambert_vert,fragmentShader:hi.meshlambert_frag},phong:{uniforms:Yn([ui.common,ui.specularmap,ui.envmap,ui.aomap,ui.lightmap,ui.emissivemap,ui.bumpmap,ui.normalmap,ui.displacementmap,ui.fog,ui.lights,{emissive:{value:new tn(0)},specular:{value:new tn(1118481)},shininess:{value:30}}]),vertexShader:hi.meshphong_vert,fragmentShader:hi.meshphong_frag},standard:{uniforms:Yn([ui.common,ui.envmap,ui.aomap,ui.lightmap,ui.emissivemap,ui.bumpmap,ui.normalmap,ui.displacementmap,ui.roughnessmap,ui.metalnessmap,ui.fog,ui.lights,{emissive:{value:new tn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:hi.meshphysical_vert,fragmentShader:hi.meshphysical_frag},toon:{uniforms:Yn([ui.common,ui.aomap,ui.lightmap,ui.emissivemap,ui.bumpmap,ui.normalmap,ui.displacementmap,ui.gradientmap,ui.fog,ui.lights,{emissive:{value:new tn(0)}}]),vertexShader:hi.meshtoon_vert,fragmentShader:hi.meshtoon_frag},matcap:{uniforms:Yn([ui.common,ui.bumpmap,ui.normalmap,ui.displacementmap,ui.fog,{matcap:{value:null}}]),vertexShader:hi.meshmatcap_vert,fragmentShader:hi.meshmatcap_frag},points:{uniforms:Yn([ui.points,ui.fog]),vertexShader:hi.points_vert,fragmentShader:hi.points_frag},dashed:{uniforms:Yn([ui.common,ui.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:hi.linedashed_vert,fragmentShader:hi.linedashed_frag},depth:{uniforms:Yn([ui.common,ui.displacementmap]),vertexShader:hi.depth_vert,fragmentShader:hi.depth_frag},normal:{uniforms:Yn([ui.common,ui.bumpmap,ui.normalmap,ui.displacementmap,{opacity:{value:1}}]),vertexShader:hi.normal_vert,fragmentShader:hi.normal_frag},sprite:{uniforms:Yn([ui.sprite,ui.fog]),vertexShader:hi.sprite_vert,fragmentShader:hi.sprite_frag},background:{uniforms:{uvTransform:{value:new yt},t2D:{value:null}},vertexShader:hi.background_vert,fragmentShader:hi.background_frag},cube:{uniforms:Yn([ui.envmap,{opacity:{value:1}}]),vertexShader:hi.cube_vert,fragmentShader:hi.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:hi.equirect_vert,fragmentShader:hi.equirect_frag},distanceRGBA:{uniforms:Yn([ui.common,ui.displacementmap,{referencePosition:{value:new Lt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:hi.distanceRGBA_vert,fragmentShader:hi.distanceRGBA_frag},shadow:{uniforms:Yn([ui.lights,ui.fog,{color:{value:new tn(0)},opacity:{value:1}}]),vertexShader:hi.shadow_vert,fragmentShader:hi.shadow_frag}};function pi(t,e,n,i,r){const s=new tn(0);let a,o,c=0,h=null,u=0,d=null;function p(t,e){n.buffers.color.setClear(t.r,t.g,t.b,e,r)}return{getClearColor:function(){return s},setClearColor:function(t,e=1){s.set(t),c=e,p(s,c)},getClearAlpha:function(){return c},setClearAlpha:function(t){c=t,p(s,c)},render:function(n,r,m,f){let g=!0===r.isScene?r.background:null;g&&g.isTexture&&(g=e.get(g));const v=t.xr,y=v.getSession&&v.getSession();y&&"additive"===y.environmentBlendMode&&(g=null),null===g?p(s,c):g&&g.isColor&&(p(g,1),f=!0),(t.autoClear||f)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),g&&(g.isCubeTexture||g.mapping===l)?(void 0===o&&(o=new Wn(new qn(1,1,1),new Jn({name:"BackgroundCubeMaterial",uniforms:Xn(di.cube.uniforms),vertexShader:di.cube.vertexShader,fragmentShader:di.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),o.geometry.deleteAttribute("normal"),o.geometry.deleteAttribute("uv"),o.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(o.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(o)),o.material.uniforms.envMap.value=g,o.material.uniforms.flipEnvMap.value=g.isCubeTexture&&g._needsFlipEnvMap?-1:1,h===g&&u===g.version&&d===t.toneMapping||(o.material.needsUpdate=!0,h=g,u=g.version,d=t.toneMapping),n.unshift(o,o.geometry,o.material,0,0,null)):g&&g.isTexture&&(void 0===a&&(a=new Wn(new ci(2,2),new Jn({name:"BackgroundMaterial",uniforms:Xn(di.background.uniforms),vertexShader:di.background.vertexShader,fragmentShader:di.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),a.geometry.deleteAttribute("normal"),Object.defineProperty(a.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(a)),a.material.uniforms.t2D.value=g,!0===g.matrixAutoUpdate&&g.updateMatrix(),a.material.uniforms.uvTransform.value.copy(g.matrix),h===g&&u===g.version&&d===t.toneMapping||(a.material.needsUpdate=!0,h=g,u=g.version,d=t.toneMapping),n.unshift(a,a.geometry,a.material,0,0,null))}}}function mi(t,e,n,i){const r=t.getParameter(34921),s=i.isWebGL2?null:e.get("OES_vertex_array_object"),a=i.isWebGL2||null!==s,o={},l=d(null);let c=l;function h(e){return i.isWebGL2?t.bindVertexArray(e):s.bindVertexArrayOES(e)}function u(e){return i.isWebGL2?t.deleteVertexArray(e):s.deleteVertexArrayOES(e)}function d(t){const e=[],n=[],i=[];for(let t=0;t=0){const s=l[e];if(void 0!==s){const e=s.normalized,r=s.itemSize,a=n.get(s);if(void 0===a)continue;const l=a.buffer,c=a.type,h=a.bytesPerElement;if(s.isInterleavedBufferAttribute){const n=s.data,a=n.stride,u=s.offset;n&&n.isInstancedInterleavedBuffer?(f(i,n.meshPerAttribute),void 0===o._maxInstanceCount&&(o._maxInstanceCount=n.meshPerAttribute*n.count)):m(i),t.bindBuffer(34962,l),v(i,r,c,e,a*h,u*h)}else s.isInstancedBufferAttribute?(f(i,s.meshPerAttribute),void 0===o._maxInstanceCount&&(o._maxInstanceCount=s.meshPerAttribute*s.count)):m(i),t.bindBuffer(34962,l),v(i,r,c,e,0,0)}else if("instanceMatrix"===e){const e=n.get(r.instanceMatrix);if(void 0===e)continue;const s=e.buffer,a=e.type;f(i+0,1),f(i+1,1),f(i+2,1),f(i+3,1),t.bindBuffer(34962,s),t.vertexAttribPointer(i+0,4,a,!1,64,0),t.vertexAttribPointer(i+1,4,a,!1,64,16),t.vertexAttribPointer(i+2,4,a,!1,64,32),t.vertexAttribPointer(i+3,4,a,!1,64,48)}else if("instanceColor"===e){const e=n.get(r.instanceColor);if(void 0===e)continue;const s=e.buffer,a=e.type;f(i,1),t.bindBuffer(34962,s),t.vertexAttribPointer(i,3,a,!1,12,0)}else if(void 0!==h){const n=h[e];if(void 0!==n)switch(n.length){case 2:t.vertexAttrib2fv(i,n);break;case 3:t.vertexAttrib3fv(i,n);break;case 4:t.vertexAttrib4fv(i,n);break;default:t.vertexAttrib1fv(i,n)}}}}g()}(r,l,u,y),null!==x&&t.bindBuffer(34963,n.get(x).buffer))},reset:y,resetDefaultState:x,dispose:function(){y();for(const t in o){const e=o[t];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t]}},releaseStatesOfGeometry:function(t){if(void 0===o[t.id])return;const e=o[t.id];for(const t in e){const n=e[t];for(const t in n)u(n[t].object),delete n[t];delete e[t]}delete o[t.id]},releaseStatesOfProgram:function(t){for(const e in o){const n=o[e];if(void 0===n[t.id])continue;const i=n[t.id];for(const t in i)u(i[t].object),delete i[t];delete n[t.id]}},initAttributes:p,enableAttribute:m,disableUnusedAttributes:g}}function fi(t,e,n,i){const r=i.isWebGL2;let s;this.setMode=function(t){s=t},this.render=function(e,i){t.drawArrays(s,e,i),n.update(i,s,1)},this.renderInstances=function(i,a,o){if(0===o)return;let l,c;if(r)l=t,c="drawArraysInstanced";else if(l=e.get("ANGLE_instanced_arrays"),c="drawArraysInstancedANGLE",null===l)return void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");l[c](s,i,a,o),n.update(a,s,o)}}function gi(t,e,n){let i;function r(e){if("highp"===e){if(t.getShaderPrecisionFormat(35633,36338).precision>0&&t.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(35633,36337).precision>0&&t.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const s="undefined"!=typeof WebGL2RenderingContext&&t instanceof WebGL2RenderingContext||"undefined"!=typeof WebGL2ComputeRenderingContext&&t instanceof WebGL2ComputeRenderingContext;let a=void 0!==n.precision?n.precision:"highp";const o=r(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,c=t.getParameter(34930),h=t.getParameter(35660),u=t.getParameter(3379),d=t.getParameter(34076),p=t.getParameter(34921),m=t.getParameter(36347),f=t.getParameter(36348),g=t.getParameter(36349),v=h>0,y=s||e.has("OES_texture_float");return{isWebGL2:s,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");i=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:r,precision:a,logarithmicDepthBuffer:l,maxTextures:c,maxVertexTextures:h,maxTextureSize:u,maxCubemapSize:d,maxAttributes:p,maxVertexUniforms:m,maxVaryings:f,maxFragmentUniforms:g,vertexTextures:v,floatFragmentTextures:y,floatVertexTextures:v&&y,maxSamples:s?t.getParameter(36183):0}}function vi(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new Ne,o=new yt,l={value:null,needsUpdate:!1};function c(){l.value!==n&&(l.value=n,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0){const a=t.getRenderTarget(),o=new ni(s.height/2);return o.fromEquirectangularTexture(t,r),e.set(r,o),t.setRenderTarget(a),r.addEventListener("dispose",i),n(o.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}function xi(t){const e={};function n(n){if(void 0!==e[n])return e[n];let i;switch(n){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(n)}return e[n]=i,i}return{has:function(t){return null!==n(t)},init:function(t){t.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float")},get:function(t){const e=n(t);return null===e&&console.warn("THREE.WebGLRenderer: "+t+" extension not supported."),e}}}function _i(t,e,n,i){const r={},s=new WeakMap;function a(t){const o=t.target;null!==o.index&&e.remove(o.index);for(const t in o.attributes)e.remove(o.attributes[t]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(e.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(t){const n=[],i=t.index,r=t.attributes.position;let a=0;if(null!==i){const t=i.array;a=i.version;for(let e=0,i=t.length;e65535?dn:hn)(n,1);o.version=a;const l=s.get(t);l&&e.remove(l),s.set(t,o)}return{get:function(t,e){return!0===r[e.id]||(e.addEventListener("dispose",a),r[e.id]=!0,n.memory.geometries++),e},update:function(t){const n=t.attributes;for(const t in n)e.update(n[t],34962);const i=t.morphAttributes;for(const t in i){const n=i[t];for(let t=0,i=n.length;t0)return t;const r=e*n;let s=Ii[r];if(void 0===s&&(s=new Float32Array(r),Ii[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function Hi(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n