| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689 |
- <!doctype html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>线架模拟器 · 3D</title>
- <style>
- :root {
- --bg: #0d1117;
- --panel: rgba(22, 27, 34, 0.92);
- --border: #30363d;
- --text: #e6edf3;
- --muted: #8b949e;
- --green: #52c41a;
- --grey: #d9d9d9;
- --red: #ff4d4f;
- --blue: #1890ff;
- }
- * { box-sizing: border-box; }
- html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
- font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
- #scene { position: fixed; inset: 0; }
- #scene canvas { display: block; }
- .panel-label {
- padding: 4px 10px; border-radius: 6px; background: rgba(13, 17, 23, 0.82);
- border: 1px solid var(--border); color: var(--text); font-size: 12px; white-space: nowrap;
- pointer-events: none; text-align: center; line-height: 1.35;
- }
- .panel-label b { font-size: 13px; }
- .panel-label span { color: var(--muted); display: block; font-size: 11px; }
- .panel-label.offline { border-color: #6e7681; color: var(--muted); }
- .panel-label.offline span { color: #f85149; }
- #topbar {
- position: fixed; top: 12px; left: 50%; transform: translateX(-50%);
- display: flex; align-items: center; gap: 16px; padding: 8px 16px;
- background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
- backdrop-filter: blur(8px); white-space: nowrap; z-index: 10;
- }
- #topbar h1 { font-size: 14px; margin: 0; font-weight: 600; }
- #topbar .stat { color: var(--muted); font-size: 12px; }
- #topbar code { color: #79c0ff; font-size: 12px; }
- #side {
- position: fixed; top: 12px; left: 12px; width: 268px; max-height: calc(100vh - 24px);
- overflow: auto; padding: 12px; background: var(--panel); border: 1px solid var(--border);
- border-radius: 10px; backdrop-filter: blur(8px); z-index: 10;
- }
- #side h2 { margin: 0 0 10px; font-size: 13px; font-weight: 600; color: var(--muted); }
- .row { display: flex; align-items: center; gap: 8px; padding: 7px 8px; border-radius: 7px;
- border: 1px solid transparent; cursor: pointer; }
- .row:hover { background: rgba(110, 118, 129, 0.12); }
- .row.selected { border-color: #1f6feb; background: rgba(31, 111, 235, 0.12); }
- .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--grey); }
- .dot.on { background: var(--green); box-shadow: 0 0 6px var(--green); }
- .dot.off { background: #f85149; }
- .row .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .row .addr { color: var(--muted); font-variant-numeric: tabular-nums; }
- .row button, .btn {
- background: #21262d; color: var(--text); border: 1px solid var(--border); border-radius: 6px;
- padding: 3px 7px; font-size: 11px; cursor: pointer;
- }
- .row button:hover, .btn:hover { border-color: #8b949e; }
- .btn.primary { background: #1f6feb; border-color: #1f6feb; }
- .btn.danger:hover { border-color: #f85149; color: #f85149; }
- #add { width: 100%; margin-top: 10px; padding: 7px; }
- #takeCard { width: 100%; margin-top: 6px; padding: 7px; }
- #cardInfo { margin-top: 8px; font-size: 11px; color: var(--muted); line-height: 1.5; word-break: break-all; }
- .legend { margin-top: 12px; display: grid; grid-template-columns: 1fr 1fr; gap: 4px 10px;
- color: var(--muted); font-size: 11px; }
- .legend i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 5px; }
- #hint {
- position: fixed; bottom: 12px; left: 50%; transform: translateX(-50%);
- padding: 7px 14px; background: var(--panel); border: 1px solid var(--border);
- border-radius: 8px; color: var(--muted); font-size: 12px; z-index: 10; white-space: nowrap;
- }
- #hint b { color: var(--text); font-weight: 600; }
- #tooltip {
- position: fixed; pointer-events: none; padding: 6px 10px; border-radius: 7px; font-size: 12px;
- background: rgba(13, 17, 23, 0.95); border: 1px solid var(--border); display: none; z-index: 20;
- white-space: pre; line-height: 1.5;
- }
- #toast {
- position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%);
- padding: 8px 14px; border-radius: 8px; background: #da3633; color: #fff; font-size: 12px;
- display: none; z-index: 30;
- }
- </style>
- <script type="importmap">
- {
- "imports": {
- "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
- "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
- }
- }
- </script>
- </head>
- <body>
- <div id="scene"></div>
- <div id="topbar">
- <h1>线架模拟器</h1>
- <span class="stat">虚拟串口 <code id="transport">—</code></span>
- <span class="stat">帧 <span id="stats">0 / 0</span></span>
- </div>
- <div id="side">
- <h2>线架列表</h2>
- <div id="list"></div>
- <button class="btn primary" id="add">+ 新增线架</button>
- <button class="btn" id="takeCard">拿卡靠近 · 模拟识别</button>
- <div id="cardInfo" style="display:none"></div>
- <div class="legend">
- <div><i style="background:var(--green)"></i>已连接</div>
- <div><i style="background:var(--grey)"></i>未连接</div>
- <div><i style="background:var(--red)"></i>非法插入</div>
- <div><i style="background:var(--blue)"></i>非法拔出</div>
- </div>
- </div>
- <div id="hint">点击端口 <b>插/拔卡</b> Shift+点击插入 <b>期望卡</b> 点「拿卡靠近」后把卡移到端口上方停 <b>0.5s</b> 自动识别 拖动旋转 / 滚轮缩放</div>
- <div id="tooltip"></div>
- <div id="toast"></div>
- <script type="module">
- import * as THREE from 'three';
- import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
- import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
- const STATE_COLOR = {
- CONNECTED: 0x52c41a,
- DISCONNECTED: 0x8b949e,
- ILLEGAL_CONNECT: 0xff4d4f,
- ILLEGAL_DISCONNECT: 0x1890ff,
- };
- const STATE_TEXT = {
- CONNECTED: '已连接',
- DISCONNECTED: '未连接',
- ILLEGAL_CONNECT: '非法插入',
- ILLEGAL_DISCONNECT: '非法拔出',
- };
- const HEX = '0123456789ABCDEF';
- const randomCard = () => Array.from({ length: 12 }, () => HEX[Math.floor(Math.random() * 16)]).join('');
- /* ---------- Three.js 基础 ---------- */
- const container = document.getElementById('scene');
- const scene = new THREE.Scene();
- scene.background = new THREE.Color(0x0d1117);
- scene.fog = new THREE.Fog(0x0d1117, 30, 90);
- const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 300);
- camera.position.set(0, 5.2, 10.5);
- const renderer = new THREE.WebGLRenderer({ antialias: true });
- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
- renderer.setSize(innerWidth, innerHeight);
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- container.appendChild(renderer.domElement);
- const labelRenderer = new CSS2DRenderer();
- labelRenderer.setSize(innerWidth, innerHeight);
- Object.assign(labelRenderer.domElement.style, { position: 'fixed', inset: '0', pointerEvents: 'none' });
- container.appendChild(labelRenderer.domElement);
- const controls = new OrbitControls(camera, renderer.domElement);
- controls.target.set(0, 1.4, 0);
- controls.enableDamping = true;
- controls.dampingFactor = 0.08;
- controls.maxPolarAngle = Math.PI * 0.52;
- controls.minDistance = 3;
- controls.maxDistance = 80;
- scene.add(new THREE.AmbientLight(0x8fa3bf, 0.75));
- const key = new THREE.DirectionalLight(0xffffff, 1.5);
- key.position.set(6, 14, 10);
- key.castShadow = true;
- key.shadow.mapSize.set(2048, 2048);
- key.shadow.camera.left = -30;
- key.shadow.camera.right = 30;
- key.shadow.camera.top = 30;
- key.shadow.camera.bottom = -30;
- scene.add(key);
- scene.add(new THREE.DirectionalLight(0x3b82f6, 0.35).translateX(-8).translateY(6).translateZ(-6));
- const floor = new THREE.Mesh(
- new THREE.PlaneGeometry(200, 200),
- new THREE.MeshStandardMaterial({ color: 0x0b0f14, roughness: 1, metalness: 0 }),
- );
- floor.rotation.x = -Math.PI / 2;
- floor.receiveShadow = true;
- scene.add(floor);
- const grid = new THREE.GridHelper(120, 120, 0x1f6feb, 0x1b222c);
- grid.position.y = 0.002;
- grid.material.opacity = 0.35;
- grid.material.transparent = true;
- scene.add(grid);
- /* ---------- 线架 3D 构造 ---------- */
- const PANEL_W = 3.0, PANEL_H = 1.0, PANEL_D = 0.26;
- const COLS_PER_ROW = 6;
- const SPACING_X = 3.7, SPACING_Z = 2.3;
- const BASE_Y = 1.35;
- const bodyGeo = new THREE.BoxGeometry(PANEL_W, PANEL_H, PANEL_D);
- const faceGeo = new THREE.BoxGeometry(PANEL_W - 0.05, PANEL_H - 0.05, 0.02);
- const portGeo = new THREE.CylinderGeometry(0.09, 0.09, 0.04, 20);
- portGeo.rotateX(Math.PI / 2);
- const panelObjects = new Map(); // id -> { group, body, face, ports: [{mesh, port}] }
- const pickables = []; // 射线拾取(端口 + 面板实体)
- let selectedId = null;
- let state = { panels: [], transport: '', stats: { rx: 0, tx: 0 } };
- function portStateOf(panel, port) {
- if (!panel.online) return 'OFFLINE';
- const card = panel.cards[String(port)] || null;
- const expected = panel.expected[String(port)] || null;
- if (card && expected && card !== expected) return 'ILLEGAL_CONNECT';
- if (card) return 'CONNECTED';
- if (expected) return 'ILLEGAL_DISCONNECT';
- return 'DISCONNECTED';
- }
- function createPanelObject(panel) {
- const group = new THREE.Group();
- group.userData = { type: 'panel', id: panel.id };
- const bodyMat = new THREE.MeshStandardMaterial({ color: 0x1c2533, metalness: 0.55, roughness: 0.45 });
- const body = new THREE.Mesh(bodyGeo, bodyMat);
- body.castShadow = true;
- body.receiveShadow = true;
- body.userData = { type: 'panel', id: panel.id };
- group.add(body);
- const faceMat = new THREE.MeshStandardMaterial({ color: 0x25344a, metalness: 0.25, roughness: 0.75 });
- const face = new THREE.Mesh(faceGeo, faceMat);
- face.position.z = PANEL_D / 2 + 0.005;
- face.userData = { type: 'panel', id: panel.id };
- group.add(face);
- const ports = [];
- const x0 = -(PANEL_W / 2) + 0.25;
- const dx = (PANEL_W - 0.50) / 11;
- const rows = [0.21, -0.21];
- for (let r = 0; r < 2; r++) {
- for (let c = 0; c < 12; c++) {
- const port = r * 12 + c + 1;
- const mat = new THREE.MeshStandardMaterial({ color: STATE_COLOR.DISCONNECTED, emissive: 0x000000 });
- const mesh = new THREE.Mesh(portGeo, mat);
- mesh.position.set(x0 + c * dx, rows[r], PANEL_D / 2 + 0.03);
- mesh.userData = { type: 'port', id: panel.id, port };
- group.add(mesh);
- ports.push({ mesh, port });
- pickables.push(mesh);
- }
- }
- const el = document.createElement('div');
- el.className = 'panel-label';
- const label = new CSS2DObject(el);
- label.position.set(0, PANEL_H / 2 + 0.42, 0);
- group.add(label);
- group.userData.parts = { body, face, ports, label, el };
- pickables.push(body, face);
- scene.add(group);
- return group;
- }
- function removePanelObject(id) {
- const obj = panelObjects.get(id);
- if (!obj) return;
- const parts = obj.userData.parts;
- for (const { mesh } of parts.ports) {
- const i = pickables.indexOf(mesh);
- if (i >= 0) pickables.splice(i, 1);
- mesh.material.dispose();
- }
- for (const m of [parts.body, parts.face]) {
- const i = pickables.indexOf(m);
- if (i >= 0) pickables.splice(i, 1);
- }
- parts.body.material.dispose();
- parts.face.material.dispose();
- parts.label.element.remove();
- scene.remove(obj);
- panelObjects.delete(id);
- }
- function layout(panel, index) {
- const col = index % COLS_PER_ROW;
- const row = Math.floor(index / COLS_PER_ROW);
- const totalCols = Math.min(COLS_PER_ROW, Math.max(1, state.panels.length));
- const x = (col - (totalCols - 1) / 2) * SPACING_X;
- const z = row * SPACING_Z;
- return { x, z };
- }
- /* ---------- 拿卡靠近识别 ---------- */
- const DETECT_MS = 500; // 停留多久判定识别
- const DETECT_RADIUS = 0.11; // 距端口中心的识别半径(线架局部坐标)
- const cardGroup = new THREE.Group();
- const cardBody = new THREE.Mesh(
- new THREE.BoxGeometry(0.5, 0.32, 0.022),
- new THREE.MeshStandardMaterial({ color: 0xe6edf3, metalness: 0.15, roughness: 0.55, emissive: 0x1f6feb, emissiveIntensity: 0.25 }),
- );
- const cardChip = new THREE.Mesh(
- new THREE.BoxGeometry(0.15, 0.11, 0.008),
- new THREE.MeshStandardMaterial({ color: 0xd4a017, metalness: 0.85, roughness: 0.3, emissive: 0x6b4b00, emissiveIntensity: 0.3 }),
- );
- cardChip.position.set(-0.12, 0.03, 0.015);
- const cardEdge = new THREE.LineSegments(
- new THREE.EdgesGeometry(new THREE.BoxGeometry(0.5, 0.32, 0.022)),
- new THREE.LineBasicMaterial({ color: 0x58a6ff }),
- );
- cardGroup.add(cardBody, cardChip, cardEdge);
- cardGroup.visible = false;
- cardGroup.renderOrder = 5;
- scene.add(cardGroup);
- const ringMat = new THREE.MeshBasicMaterial({ color: 0x58a6ff, transparent: true, opacity: 0.8, side: THREE.DoubleSide });
- const targetRing = new THREE.Mesh(new THREE.TorusGeometry(0.115, 0.013, 8, 40), ringMat);
- targetRing.visible = false;
- targetRing.renderOrder = 6;
- scene.add(targetRing);
- let cardMode = false;
- let heldUid = null;
- let hover = null; // { id, port, mesh }
- let hoverSince = 0;
- const flashes = []; // 识别成功的端口闪光
- function cardInfoEl() { return document.getElementById('cardInfo'); }
- function setCardMode(on) {
- cardMode = on;
- const btn = document.getElementById('takeCard');
- btn.classList.toggle('primary', on);
- btn.textContent = on ? '放回卡 · 取消持卡' : '拿卡靠近 · 模拟识别';
- const info = cardInfoEl();
- if (on) {
- heldUid = randomCard();
- cardGroup.visible = false;
- targetRing.visible = false;
- hover = null;
- info.style.display = 'block';
- info.textContent = `持卡中 ${heldUid} —— 移到端口上方停留 0.5s 会被识别(Esc 取消)`;
- } else {
- heldUid = null;
- cardGroup.visible = false;
- targetRing.visible = false;
- hover = null;
- info.style.display = 'none';
- }
- }
- function moveCard(e) {
- const hits = pickAt(e.clientX, e.clientY);
- const hit = hits.find(h => h.object.userData && (h.object.userData.type === 'port' || h.object.userData.type === 'panel'));
- if (!hit) {
- cardGroup.visible = false;
- targetRing.visible = false;
- hover = null;
- return;
- }
- const id = hit.object.userData.id;
- const obj = panelObjects.get(id);
- if (!obj) return;
- cardGroup.position.copy(hit.point).add(new THREE.Vector3(0, 0.08, 0.3));
- cardGroup.rotation.z = Math.sin(performance.now() / 320) * 0.05;
- cardGroup.visible = true;
- // 找线架局部坐标里最近的端口
- const local = obj.worldToLocal(cardGroup.position.clone());
- let best = null;
- let bestD = Infinity;
- for (const item of obj.userData.parts.ports) {
- const d = Math.hypot(local.x - item.mesh.position.x, local.y - item.mesh.position.y);
- if (d < bestD) { bestD = d; best = item; }
- }
- if (best && bestD <= DETECT_RADIUS) {
- if (!hover || hover.id !== id || hover.port !== best.port) {
- hover = { id, port: best.port, mesh: best.mesh };
- hoverSince = performance.now();
- }
- const wp = new THREE.Vector3();
- best.mesh.getWorldPosition(wp);
- targetRing.position.copy(wp).add(new THREE.Vector3(0, 0, 0.035));
- targetRing.scale.setScalar(0.8);
- targetRing.visible = true;
- } else {
- hover = null;
- targetRing.visible = false;
- }
- }
- async function recognizeCard() {
- if (!hover || !cardMode) return;
- const { id, port } = hover;
- const panel = state.panels.find(p => p.id === id);
- hover = null;
- targetRing.visible = false;
- if (!panel) return;
- if (panel.cards[String(port)]) {
- toast(`端口 ${port} 已有卡,未识别`);
- return;
- }
- const uid = heldUid;
- setCardMode(false);
- await api('/api/port/set', { id, port, card_uid: uid });
- flashPort(id, port);
- toast(`已识别 ${uid} → 线架 #${id} 端口 ${port}`);
- pollOnce();
- }
- function flashPort(id, port) {
- const obj = panelObjects.get(id);
- const item = obj?.userData.parts.ports.find(p => p.port === port);
- if (item) flashes.push({ mesh: item.mesh, t0: performance.now() });
- }
- function updateFlashes(now) {
- for (let i = flashes.length - 1; i >= 0; i--) {
- const f = flashes[i];
- const t = (now - f.t0) / 650;
- if (t >= 1) {
- f.mesh.scale.setScalar(1);
- flashes.splice(i, 1);
- continue;
- }
- f.mesh.scale.setScalar(1 + Math.sin(t * Math.PI) * 0.9);
- }
- }
- /* ---------- 渲染状态 ---------- */
- function render() {
- const ids = new Set(state.panels.map(p => p.id));
- for (const id of [...panelObjects.keys()]) {
- if (!ids.has(id)) removePanelObject(id);
- }
- state.panels.forEach((panel, index) => {
- let obj = panelObjects.get(panel.id);
- if (!obj) {
- obj = createPanelObject(panel);
- panelObjects.set(panel.id, obj);
- }
- const { x, z } = layout(panel, index);
- obj.position.set(x, BASE_Y, z);
- const parts = obj.userData.parts;
- parts.el.innerHTML = `<b>${'线架'} #${panel.id}</b><span>地址 ${panel.address} · ${panel.online ? '在线' : '已断联'}</span>`;
- parts.el.className = 'panel-label' + (panel.online ? '' : ' offline');
- const selected = panel.id === selectedId;
- parts.body.material.color.setHex(selected ? 0x2b4a7a : 0x1c2533);
- parts.body.material.emissive.setHex(selected ? 0x0b2c4d : 0x000000);
- parts.face.material.color.setHex(panel.online ? 0x25344a : 0x1a1e24);
- for (const { mesh, port } of parts.ports) {
- const st = portStateOf(panel, port);
- if (st === 'OFFLINE') {
- mesh.material.color.setHex(0x3a3f46);
- mesh.material.emissive.setHex(0x000000);
- mesh.material.emissiveIntensity = 0;
- continue;
- }
- const color = STATE_COLOR[st] ?? STATE_COLOR.DISCONNECTED;
- mesh.material.color.setHex(color);
- mesh.material.emissive.setHex(color);
- mesh.material.emissiveIntensity = st === 'DISCONNECTED' ? 0.05 : 0.85;
- }
- });
- // 侧边列表
- const list = document.getElementById('list');
- list.innerHTML = state.panels.map(p => `
- <div class="row${p.id === selectedId ? ' selected' : ''}" data-id="${p.id}">
- <span class="dot ${p.online ? 'on' : 'off'}"></span>
- <span class="name">#${p.id} <span class="addr">地址 ${p.address}</span></span>
- <button data-act="toggle">${p.online ? '断联' : '恢复'}</button>
- <button data-act="addr">改址</button>
- <button data-act="del" class="danger">删</button>
- </div>`).join('') || '<div style="color:var(--muted)">暂无(点下面新增)</div>';
- document.getElementById('transport').textContent = state.transport || '—';
- document.getElementById('stats').textContent = `${state.stats.rx} / ${state.stats.tx}`;
- }
- /* ---------- API ---------- */
- async function api(path, body) {
- const res = await fetch(path, {
- method: body === undefined ? 'GET' : 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok || data.success === false) {
- toast(data.message || `请求失败 (${res.status})`);
- }
- return data;
- }
- let toastTimer = null;
- function toast(msg) {
- const el = document.getElementById('toast');
- el.textContent = msg;
- el.style.display = 'block';
- clearTimeout(toastTimer);
- toastTimer = setTimeout(() => { el.style.display = 'none'; }, 2600);
- }
- async function poll() {
- try {
- const res = await fetch('/api/state', { cache: 'no-store' });
- const data = await res.json();
- if (data.success) {
- state = data;
- render();
- }
- } catch (e) {
- document.getElementById('transport').textContent = '连接模拟器失败';
- }
- setTimeout(poll, 400);
- }
- /* ---------- 交互 ---------- */
- const raycaster = new THREE.Raycaster();
- const pointer = new THREE.Vector2();
- const tooltip = document.getElementById('tooltip');
- function pickAt(clientX, clientY) {
- const rect = renderer.domElement.getBoundingClientRect();
- pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
- pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
- raycaster.setFromCamera(pointer, camera);
- return raycaster.intersectObjects(pickables, false);
- }
- let downAt = null;
- renderer.domElement.addEventListener('pointerdown', (e) => {
- if (e.button !== 0) return;
- downAt = { x: e.clientX, y: e.clientY };
- });
- renderer.domElement.addEventListener('pointerup', async (e) => {
- if (e.button !== 0 || !downAt) return;
- const moved = Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y);
- downAt = null;
- if (cardMode) return; // 持卡模式:点击不插拔,靠靠近识别
- if (moved > 6) return; // 拖动视角,不算点击
- const hits = pickAt(e.clientX, e.clientY);
- if (!hits.length) return;
- const hit = hits[0].object;
- const { type, id, port } = hit.userData || {};
- if (type === 'port') {
- const panel = state.panels.find(p => p.id === id);
- if (!panel) return;
- const current = panel.cards[String(port)] || null;
- const expected = panel.expected[String(port)] || null;
- let card = null;
- if (e.shiftKey && expected) card = expected;
- else if (!current) card = randomCard();
- await api('/api/port/set', { id, port, card_uid: card });
- pollOnce();
- } else if (type === 'panel') {
- selectedId = id;
- render();
- }
- });
- renderer.domElement.addEventListener('pointermove', (e) => {
- if (cardMode) {
- tooltip.style.display = 'none';
- moveCard(e);
- return;
- }
- const hits = pickAt(e.clientX, e.clientY);
- if (!hits.length) {
- tooltip.style.display = 'none';
- return;
- }
- const { type, id, port } = hits[0].object.userData || {};
- if (type !== 'port') {
- tooltip.style.display = 'none';
- return;
- }
- const panel = state.panels.find(p => p.id === id);
- if (!panel) return;
- const st = portStateOf(panel, port);
- const card = panel.cards[String(port)] || '—';
- const expected = panel.expected[String(port)] || '—';
- tooltip.textContent = `线架 #${panel.id} · 端口 ${port}\n状态:${st === 'OFFLINE' ? '已断联' : (STATE_TEXT[st] || st)}\n卡号:${card}\n期望:${expected}`;
- tooltip.style.display = 'block';
- tooltip.style.left = `${e.clientX + 14}px`;
- tooltip.style.top = `${e.clientY + 14}px`;
- });
- renderer.domElement.addEventListener('pointerleave', () => {
- if (!cardMode) return;
- cardGroup.visible = false;
- targetRing.visible = false;
- hover = null;
- });
- document.getElementById('list').addEventListener('click', async (e) => {
- const btn = e.target.closest('button');
- const row = e.target.closest('.row');
- if (!row) return;
- const id = Number(row.dataset.id);
- const panel = state.panels.find(p => p.id === id);
- if (!panel) return;
- if (!btn) {
- selectedId = id;
- render();
- return;
- }
- const act = btn.dataset.act;
- if (act === 'toggle') {
- await api('/api/panel/update', { id, online: !panel.online });
- } else if (act === 'addr') {
- const input = prompt('设置线架地址(1-247)', String(panel.address));
- if (input === null) return;
- const address = parseInt(input, 10);
- if (!Number.isFinite(address)) return toast('地址必须是数字');
- await api('/api/panel/update', { id, address });
- } else if (act === 'del') {
- if (!confirm(`删除线架 #${id}(地址 ${panel.address})?`)) return;
- await api('/api/panel/delete', { id });
- if (selectedId === id) selectedId = null;
- }
- pollOnce();
- });
- document.getElementById('add').addEventListener('click', async () => {
- const input = prompt('新线架地址(留空=自动分配)', '');
- if (input === null) return;
- const address = input.trim() === '' ? undefined : parseInt(input, 10);
- if (address !== undefined && !Number.isFinite(address)) return toast('地址必须是数字');
- const data = await api('/api/panel/add', { address });
- if (data.success) selectedId = data.id;
- pollOnce();
- });
- document.getElementById('takeCard').addEventListener('click', () => setCardMode(!cardMode));
- addEventListener('keydown', (e) => {
- if (e.key === 'Escape' && cardMode) setCardMode(false);
- });
- async function pollOnce() {
- try {
- const res = await fetch('/api/state', { cache: 'no-store' });
- const data = await res.json();
- if (data.success) { state = data; render(); }
- } catch (_) { /* 忽略 */ }
- }
- addEventListener('resize', () => {
- camera.aspect = innerWidth / innerHeight;
- camera.updateProjectionMatrix();
- renderer.setSize(innerWidth, innerHeight);
- labelRenderer.setSize(innerWidth, innerHeight);
- });
- /* ---------- 主循环 ---------- */
- function animate() {
- requestAnimationFrame(animate);
- controls.update();
- const now = performance.now();
- if (cardMode && hover) {
- const p = Math.min(1, (now - hoverSince) / DETECT_MS);
- ringMat.opacity = 0.35 + 0.6 * p;
- const s = 0.75 + 0.55 * p;
- targetRing.scale.set(s, s, 1);
- if (p >= 1) recognizeCard();
- }
- updateFlashes(now);
- renderer.render(scene, camera);
- labelRenderer.render(scene, camera);
- }
- animate();
- poll();
- </script>
- </body>
- </html>
|