feat(match): 同步比赛计时与装甲板扣血许可
- feat(client): 增加裁判比赛计时、技术暂停与选手端局域网同步 - feat(armor): 红蓝共用通用固件,按客户端选队并显示网络连接状态 - feat(armor): 仅在对局进行中允许扣血,其他阶段保留受击闪烁 - feat(client): 将计时置于血条中间并增加开赛前五秒全屏动画 - fix(client): 修复连续血条、对手镜像和图传断连灰度遮罩 - fix(client): 统一界面中文字体并整理各页面文案 - fix(maintenance): 备份迁移装甲板分区,恢复 SDK 构建与固件打包 - refactor(repo): 按 armor、vt 和 client 整理工程与脚本,移除旧参考实现 - test: 补充线路、受击许可、回环 UDP、维护和 HUD 验证 - docs: 同步构建、协议、比赛控制和硬件验证边界 验证:前端构建与 19 项相关测试通过;核心 91 项单元测试与 2 项回环 UDP 集成测试通过;装甲板规则 25 项、线路 26 项、Tauri 51 项测试通过;独立探测器 5 项与目录回归 4 项通过。完成 C3 两组阈值实际编译、导出与 ZIP 校验,检查 900×600 / 1280×720 页面、倒计时和随包中文字体。 未执行烧录、板上运行、跨电脑广播或硬件稳定性验证。
This commit is contained in:
581 files changed
+6596
-7683
No files matched your search
@@ -0,0 +1,575 @@
|
||||
/**
|
||||
* 仅开发用的浏览器预览。
|
||||
*
|
||||
* # 它解决什么问题
|
||||
*
|
||||
* Tauri 的界面跑在 WKWebView 里,改一行 CSS 要走一次 cargo 构建;而且截图要靠 macOS 的
|
||||
* 屏幕录制权限。预览模式让同一套 React 组件在浏览器里跑起来:状态由本文件合成,画面用
|
||||
* `createImageBitmap` 从一块 canvas 上取——`VideoSurface`、血条、瞄准器、命中反馈全都是
|
||||
* 真代码,只有"后端"是假的。
|
||||
*
|
||||
* # 它绝不可能进到正式构建里
|
||||
*
|
||||
* 两重门:
|
||||
*
|
||||
* 1. `import.meta.env.DEV` —— 只在 `vite dev` 下为真;`vite build` 时是 false,
|
||||
* 2. 并且页面里没有 Tauri 注入的 `__TAURI_INTERNALS__`。
|
||||
*
|
||||
* 调用点还用 `await import(...)`:条件为假时整个模块不会被打进产物,而不是打进去再靠
|
||||
* 运行时不走。
|
||||
*
|
||||
* # 用法
|
||||
*
|
||||
* ```sh
|
||||
* pnpm dev # 用户端
|
||||
* open 'http://127.0.0.1:1420/?preview=referee' # 裁判端
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { DEFAULT_TEAM_NAMES } from "./format";
|
||||
import { previewMatch, previewMatchAction } from "./match-preview";
|
||||
import type { MatchAction } from "./types";
|
||||
import type { StreamClient } from "./stream";
|
||||
import type {
|
||||
ConfigView,
|
||||
HudView,
|
||||
Snapshot,
|
||||
WireMsg,
|
||||
} from "./types";
|
||||
|
||||
/** 页面里有没有 Tauri 注入。 */
|
||||
function hasTauri(): boolean {
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
/** 现在是不是在预览模式。 */
|
||||
export function isPreview(): boolean {
|
||||
return import.meta.env.DEV && !hasTauri();
|
||||
}
|
||||
|
||||
const params = new URLSearchParams(typeof location === "undefined" ? "" : location.search);
|
||||
const startAsReferee = params.get("preview") === "referee";
|
||||
/**
|
||||
* 首次启动的两道门。
|
||||
*
|
||||
* `?preview=first-run` 让 `roleChosen` 为假、`?preview=password` 让 `passwordSet` 为假,
|
||||
* 这样不删配置也能看到那两块界面。它们只在预览里存在,正式构建里这段代码不会被打进去。
|
||||
*/
|
||||
const firstRun = params.get("preview") === "first-run";
|
||||
const needsPassword = params.get("preview") === "password";
|
||||
// 复现无信号时的 HUD;仍然使用合成状态,不连接真实设备。
|
||||
const offlinePreview = params.get("preview") === "offline";
|
||||
// 前 12 秒收流,随后断流 12 秒,再恢复;用于检查最后一帧的灰度遮罩。
|
||||
const reconnectPreview = params.get("preview") === "reconnect";
|
||||
const previewStartedAt = performance.now();
|
||||
const missingBindingPreview = params.get("preview") === "missing-binding";
|
||||
const wideLayoutPreview = params.get("layout") === "wide";
|
||||
|
||||
function videoOffline(): boolean {
|
||||
const elapsed = performance.now() - previewStartedAt;
|
||||
return offlinePreview || (reconnectPreview && elapsed >= 12_000 && elapsed < 24_000);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 可变状态:设置面板里的改动会落到这里,界面因此是可交互的
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const DEFAULT_HUD: HudView = {
|
||||
health: {
|
||||
visible: true,
|
||||
showNumbers: true,
|
||||
showTeamName: true,
|
||||
lowThreshold: 30,
|
||||
pulse: true,
|
||||
width: 0.42,
|
||||
},
|
||||
crosshair: {
|
||||
visible: true,
|
||||
style: "cross-dot",
|
||||
size: 0.045,
|
||||
thickness: 0.004,
|
||||
gap: 0.012,
|
||||
color: "#3dff88",
|
||||
offsetX: 0,
|
||||
offsetY: 0,
|
||||
},
|
||||
grid: { visible: false, style: "thirds", divisions: 6, opacity: 0.22 },
|
||||
hitFeedback: { flash: true, shake: false, marker: true, intensity: 1 },
|
||||
showZoom: true,
|
||||
showStats: true,
|
||||
};
|
||||
|
||||
const CAMERA_A = 0x0de0_0001;
|
||||
const CAMERA_B = 0x0de0_0002;
|
||||
const ARMOR_A = 0x0a20_0001;
|
||||
const ARMOR_B = 0x0a20_0002;
|
||||
|
||||
interface PreviewState {
|
||||
role: "team" | "referee";
|
||||
hud: HudView;
|
||||
cameraId: number | null;
|
||||
armorId: number | null;
|
||||
team: number;
|
||||
/** 两边显示的名字,与后端配置里的 `teamNames` 对应。 */
|
||||
teamNames: [string, string];
|
||||
mirror: boolean;
|
||||
unlocked: boolean;
|
||||
password: string | null;
|
||||
calibrating: boolean;
|
||||
recordings: { camera: number; frames: number; startedMs: number }[];
|
||||
hp: [number, number];
|
||||
}
|
||||
|
||||
const state: PreviewState = {
|
||||
role: startAsReferee ? "referee" : "team",
|
||||
hud: { ...structuredClone(DEFAULT_HUD), health: { ...DEFAULT_HUD.health, width: wideLayoutPreview ? 0.9 : DEFAULT_HUD.health.width } },
|
||||
cameraId: startAsReferee ? null : missingBindingPreview ? 0x0de0_9999 : CAMERA_A,
|
||||
armorId: startAsReferee ? null : ARMOR_A,
|
||||
team: 0,
|
||||
teamNames: wideLayoutPreview ? ["用户端长队名布局验证一队", "用户端长队名布局验证二队"] : ["队伍一", "队伍二"],
|
||||
mirror: true,
|
||||
// 预览里直接是已解锁状态,免得每次刷新都要输密码。
|
||||
unlocked: false,
|
||||
password: "1234",
|
||||
calibrating: false,
|
||||
recordings: [],
|
||||
hp: [100, 100],
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 假的命令实现
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 供 `ipc.ts` 在有 Tauri 时不会走到的分支上用。 */
|
||||
export async function previewInvoke<T>(command: string, args?: Record<string, unknown>): Promise<T> {
|
||||
const value = handle(command, args ?? {});
|
||||
return value as T;
|
||||
}
|
||||
|
||||
function handle(command: string, args: Record<string, unknown>): unknown {
|
||||
switch (command) {
|
||||
case "match_action":
|
||||
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
|
||||
previewMatchAction(args.action as MatchAction);
|
||||
return;
|
||||
case "release_match_source": return;
|
||||
case "stream_info":
|
||||
return { url: "preview://", port: 0, clients: 1 };
|
||||
case "get_snapshot":
|
||||
return snapshot();
|
||||
case "get_config":
|
||||
return configView();
|
||||
case "list_media_files":
|
||||
return [];
|
||||
case "config_path":
|
||||
return "/预览模式/没有真实配置文件";
|
||||
case "unlock":
|
||||
state.unlocked = String(args.password) === state.password;
|
||||
return state.unlocked;
|
||||
case "lock":
|
||||
state.unlocked = false;
|
||||
return undefined;
|
||||
case "set_password":
|
||||
state.password = String(args.fresh);
|
||||
state.unlocked = true;
|
||||
return configView();
|
||||
case "set_discovery_open":
|
||||
return undefined;
|
||||
case "bind_camera":
|
||||
guard();
|
||||
state.cameraId = (args.cameraId as number | null) ?? null;
|
||||
return configView();
|
||||
case "bind_armor":
|
||||
guard();
|
||||
state.armorId = (args.armorId as number | null) ?? null;
|
||||
return configView();
|
||||
case "set_team":
|
||||
guard();
|
||||
state.team = Number(args.team);
|
||||
return configView();
|
||||
case "set_team_name": {
|
||||
guard();
|
||||
const team = Number(args.team);
|
||||
if (team !== 0 && team !== 1) throw new Error("队伍号只能是 0 或 1");
|
||||
// 与后端一样:合并空白、按字符截断、留空回落默认名。
|
||||
state.teamNames[team] = sanitizeName(String(args.name ?? ""), team);
|
||||
return configView();
|
||||
}
|
||||
case "set_role":
|
||||
state.role = args.role as "team" | "referee";
|
||||
return configView();
|
||||
case "set_mirror":
|
||||
state.mirror = Boolean(args.mirror);
|
||||
return configView();
|
||||
case "save_hud":
|
||||
state.hud = args.hud as HudView;
|
||||
return configView();
|
||||
case "set_referee_slots":
|
||||
return configView();
|
||||
case "set_recording_options":
|
||||
return configView();
|
||||
case "screenshot":
|
||||
return "/预览模式/没有截图";
|
||||
case "start_recording": {
|
||||
const cameras = (args.cameras as number[]) ?? [];
|
||||
const startedMs = Date.now();
|
||||
for (const camera of cameras) {
|
||||
if (!state.recordings.some((r) => r.camera === camera)) {
|
||||
state.recordings.push({ camera, frames: 0, startedMs });
|
||||
}
|
||||
}
|
||||
return recordings();
|
||||
}
|
||||
case "stop_recording": {
|
||||
const cameras = (args.cameras as number[]) ?? [];
|
||||
state.recordings = cameras.length
|
||||
? state.recordings.filter((r) => !cameras.includes(r.camera))
|
||||
: [];
|
||||
return recordings();
|
||||
}
|
||||
case "refresh":
|
||||
case "reveal":
|
||||
case "open_file":
|
||||
return undefined;
|
||||
case "clear_config":
|
||||
return "预览模式:没有真实配置可清空";
|
||||
case "quit":
|
||||
return undefined;
|
||||
default:
|
||||
throw new Error(`预览模式没有实现命令 ${command}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 预览里模拟后端的密码闸门,好让解锁流程也能被看到。 */
|
||||
function guard() {
|
||||
if (state.role === "team" && state.password !== null && !state.unlocked) {
|
||||
throw new Error("修改设置需要密码。请先解锁,预览模式密码为 1234。");
|
||||
}
|
||||
}
|
||||
|
||||
function configView(): ConfigView {
|
||||
return {
|
||||
role: state.role,
|
||||
roleChosen: !firstRun,
|
||||
team: state.team,
|
||||
teamNames: [...state.teamNames] as [string, string],
|
||||
cameraId: state.cameraId,
|
||||
cameraIdText: state.cameraId === null ? null : hex(state.cameraId),
|
||||
armorId: state.armorId,
|
||||
armorIdText: state.armorId === null ? null : hex(state.armorId),
|
||||
mirror: state.mirror,
|
||||
passwordSet: needsPassword ? false : state.password !== null,
|
||||
hud: structuredClone(state.hud),
|
||||
recordingDir: "/预览模式/recordings",
|
||||
ffmpeg: "ffmpeg",
|
||||
};
|
||||
}
|
||||
|
||||
function recordings() {
|
||||
return state.recordings.map((recording) => ({
|
||||
camera: recording.camera,
|
||||
cameraText: hex(recording.camera),
|
||||
active: true,
|
||||
path: `/预览模式/rec-${recording.camera.toString(16)}.mp4`,
|
||||
inputFps: 20,
|
||||
framesWritten: recording.frames,
|
||||
framesDropped: 0,
|
||||
startedMs: recording.startedMs,
|
||||
error: null,
|
||||
}));
|
||||
}
|
||||
|
||||
/** 与后端 `config::sanitize_team_name` 一致:合并空白、按字符截断、留空回落默认名。 */
|
||||
function sanitizeName(name: string | undefined, team: number): string {
|
||||
const collapsed = (name ?? "").split(/\s+/).filter(Boolean).join(" ");
|
||||
const text = collapsed.length > 0 ? collapsed : DEFAULT_TEAM_NAMES[team];
|
||||
return [...text].slice(0, 12).join("");
|
||||
}
|
||||
|
||||
function hex(id: number): string {
|
||||
return `0x${id.toString(16).toUpperCase().padStart(8, "0")}`;
|
||||
}
|
||||
|
||||
function snapshot(): Snapshot {
|
||||
const cameraOffline = videoOffline();
|
||||
const cameras = [
|
||||
{ id: CAMERA_A, team: 0 },
|
||||
{ id: CAMERA_B, team: 1 },
|
||||
].map(({ id, team }) => ({
|
||||
id,
|
||||
idText: hex(id),
|
||||
addr: team === 0 ? "192.168.1.41" : "192.168.1.42",
|
||||
online: !cameraOffline,
|
||||
silenceMs: 120,
|
||||
// 预览里模拟一块"版本对得上"的板子:界面上的固件标签因此能被看到。
|
||||
firmwareVersion: "0.2.0",
|
||||
firmwareBuild: 34,
|
||||
protocol: 1,
|
||||
compatible: true,
|
||||
}));
|
||||
|
||||
const boards = [
|
||||
{ id: ARMOR_A, team: 0 },
|
||||
{ id: ARMOR_B, team: 1 },
|
||||
].map(({ id, team }, index) => ({
|
||||
id,
|
||||
idText: hex(id),
|
||||
addr: team === 0 ? "192.168.1.51" : "192.168.1.52",
|
||||
online: !offlinePreview,
|
||||
team,
|
||||
hp: state.hp[index],
|
||||
platesSeen: 4,
|
||||
reportsAllPlates: true,
|
||||
silenceMs: 90,
|
||||
}));
|
||||
|
||||
const stats = cameras.map((camera) => ({
|
||||
camera: camera.id,
|
||||
cameraText: camera.idText,
|
||||
online: !cameraOffline,
|
||||
status: camera.idText,
|
||||
hasFrames: !offlinePreview,
|
||||
fps: cameraOffline ? 0 : 20,
|
||||
width: 640,
|
||||
height: 480,
|
||||
framesShown: 1000,
|
||||
framesDropped: 3,
|
||||
lossPercent: 0.3,
|
||||
datagrams: 17000,
|
||||
lastFrameBytes: 22000,
|
||||
gapMs: 50,
|
||||
}));
|
||||
|
||||
// 与后端 `cam_core::snapshot::resolve_outcomes` 同一套规则,包括那条不对称:
|
||||
// 输只看自己,赢要看对手归零**且**自己还活着。
|
||||
const outcomeFor = (team: number) => {
|
||||
const mine = state.hp[team];
|
||||
const theirs = state.hp[team === 0 ? 1 : 0];
|
||||
|
||||
if (mine === 0 && theirs === 0) return "draw" as const;
|
||||
if (theirs === 0 && mine > 0) return "victory" as const;
|
||||
if (mine === 0) return "defeat" as const;
|
||||
return null;
|
||||
};
|
||||
|
||||
const healthFor = (team: number) => {
|
||||
const hp = state.hp[team];
|
||||
const board = team === 0 ? ARMOR_A : ARMOR_B;
|
||||
|
||||
return {
|
||||
team,
|
||||
name: state.teamNames[team],
|
||||
available: !offlinePreview,
|
||||
placeholder: offlinePreview ? "装甲板未接入" : "",
|
||||
hp: offlinePreview ? null : hp,
|
||||
hps: [hp, hp, hp, hp],
|
||||
board,
|
||||
boardText: hex(board),
|
||||
critical: hp === 0 || hp <= state.hud.health.lowThreshold,
|
||||
outcome: outcomeFor(team),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
role: state.role,
|
||||
team: state.team,
|
||||
mirrored: state.mirror,
|
||||
matchClock: previewMatch(),
|
||||
demo: true,
|
||||
diagnostics: true,
|
||||
unlocked: state.unlocked || state.role === "referee",
|
||||
discoveryOpen: true,
|
||||
uptimeMs: performance.now(),
|
||||
clients: 1,
|
||||
config: configView(),
|
||||
cameras,
|
||||
armorBoards: boards,
|
||||
stats,
|
||||
slots: {
|
||||
cameraA: state.role === "referee" ? CAMERA_A : state.cameraId,
|
||||
cameraB: state.role === "referee" ? CAMERA_B : null,
|
||||
armorA: state.role === "referee" ? ARMOR_A : state.armorId,
|
||||
armorB: state.role === "referee" ? ARMOR_B : null,
|
||||
manual: false,
|
||||
},
|
||||
// 两边都给:用户端也要显示对手的血量(画面右上角那一条)。
|
||||
health: [healthFor(0), healthFor(1)],
|
||||
recordings: recordings(),
|
||||
notes: ["浏览器预览:状态与画面均为合成数据,不代表真实链路。"],
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 假的画面与心跳
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 启动预览的数据源:每 200ms 一份快照,每 50ms 一帧画面。 */
|
||||
export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void) {
|
||||
let frameId = 0;
|
||||
const started = performance.now();
|
||||
|
||||
// 快照。
|
||||
const snapshotTimer = window.setInterval(() => {
|
||||
emit({ t: "snapshot", ...snapshot() } as WireMsg);
|
||||
}, 200);
|
||||
|
||||
// 两路画面,各 20fps。
|
||||
const canvases = new Map<number, HTMLCanvasElement>();
|
||||
const render = async (camera: number, team: number) => {
|
||||
const canvas = canvases.get(camera) ?? makeCanvas();
|
||||
canvases.set(camera, canvas);
|
||||
draw(canvas, team, frameId);
|
||||
|
||||
const bitmap = await createImageBitmap(canvas);
|
||||
client.injectFrame(camera, frameId, canvas.width, canvas.height, bitmap);
|
||||
};
|
||||
|
||||
const frameTimer = window.setInterval(() => {
|
||||
if (videoOffline()) return;
|
||||
frameId += 1;
|
||||
|
||||
const cameras =
|
||||
state.role === "referee"
|
||||
? [
|
||||
[CAMERA_A, 0],
|
||||
[CAMERA_B, 1],
|
||||
]
|
||||
: state.cameraId === CAMERA_A || state.cameraId === CAMERA_B
|
||||
? [[state.cameraId, state.cameraId === CAMERA_A ? 0 : 1]]
|
||||
: [];
|
||||
|
||||
for (const [camera, team] of cameras as [number, number][]) {
|
||||
void render(camera, team);
|
||||
}
|
||||
|
||||
for (const recording of state.recordings) recording.frames += 1;
|
||||
}, 50);
|
||||
|
||||
// 掉血:每 3 秒一次,轮流打两块板子,顺便把命中反馈也验证了。
|
||||
//
|
||||
// 打空的那一拍只做重置、不出命中(胜负横幅要真的能看到),其余每一拍都出一次
|
||||
// 命中。早先的写法是 `to = from === 0 ? 100 : ...` 然后按 `to >= from` 判断——那样一旦
|
||||
// 两块都打空,之后每次都是重置,命中就再也不会出现,盯着界面等闪红会等到超时。
|
||||
let tick = 0;
|
||||
const hitTimer = window.setInterval(() => {
|
||||
if (offlinePreview) return;
|
||||
tick += 1;
|
||||
const team = tick % 2;
|
||||
|
||||
if (state.hp[team] === 0) {
|
||||
state.hp[team] = 100;
|
||||
return;
|
||||
}
|
||||
|
||||
const from = state.hp[team];
|
||||
const damage = 3 + ((tick * 7) % 20);
|
||||
const to = Math.max(0, from - damage);
|
||||
state.hp[team] = to;
|
||||
|
||||
emit({
|
||||
t: "hit",
|
||||
board: team === 0 ? ARMOR_A : ARMOR_B,
|
||||
team,
|
||||
index: 0,
|
||||
from,
|
||||
to,
|
||||
damage: from - to,
|
||||
atMs: Date.now(),
|
||||
} as WireMsg);
|
||||
}, 3000);
|
||||
|
||||
// 第一帧不必等 200ms。
|
||||
emit({ t: "snapshot", ...snapshot() } as WireMsg);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(snapshotTimer);
|
||||
window.clearInterval(frameTimer);
|
||||
window.clearInterval(hitTimer);
|
||||
void started;
|
||||
};
|
||||
}
|
||||
|
||||
function makeCanvas(): HTMLCanvasElement {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 640;
|
||||
canvas.height = 480;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
/** 与 `src-tauri/src/demo.rs` 画的是同一类东西:底色区分两路、中心靶心、二进制帧号。 */
|
||||
function draw(canvas: HTMLCanvasElement, team: number, frameId: number) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
|
||||
const { width, height } = canvas;
|
||||
const tint = team === 0 ? [0, 46, 40] : [58, 30, 0];
|
||||
|
||||
const gradient = ctx.createLinearGradient(0, 0, 0, height);
|
||||
gradient.addColorStop(0, `rgb(${18 + tint[0] / 3}, ${18 + tint[1] / 3}, ${22 + tint[2] / 3})`);
|
||||
gradient.addColorStop(1, `rgb(${78 + tint[0] / 3}, ${78 + tint[1] / 3}, ${82 + tint[2] / 3})`);
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
|
||||
ctx.strokeStyle = "rgba(255,255,255,0.07)";
|
||||
ctx.lineWidth = 1;
|
||||
for (let x = 0; x < width; x += 40) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + 0.5, 0);
|
||||
ctx.lineTo(x + 0.5, height);
|
||||
ctx.stroke();
|
||||
}
|
||||
for (let y = 0; y < height; y += 40) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, y + 0.5);
|
||||
ctx.lineTo(width, y + 0.5);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
const cx = width / 2;
|
||||
const cy = height / 2;
|
||||
ctx.strokeStyle = "#c8c8d2";
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, 60, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = "#96969f";
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, 28, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.strokeStyle = "#78788a";
|
||||
for (const [dx, dy] of [
|
||||
[1, 0],
|
||||
[-1, 0],
|
||||
[0, 1],
|
||||
[0, -1],
|
||||
]) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cx + dx * 40, cy + dy * 40);
|
||||
ctx.lineTo(cx + dx * 90, cy + dy * 90);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
for (let bit = 0; bit < 16; bit += 1) {
|
||||
const on = ((frameId >> bit) & 1) === 1;
|
||||
ctx.fillStyle = on ? "#78ffa0" : "#34343c";
|
||||
ctx.fillRect(12 + bit * 14, 12, 10, 10);
|
||||
}
|
||||
|
||||
const t = frameId / 20;
|
||||
const phase = team === 0 ? 0 : 1.7;
|
||||
ctx.fillStyle = "#ffd25a";
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx + 250 * Math.sin(t * 0.9 + phase), cy + 150 * Math.cos(t * 1.3 + phase), 26, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#5ac8ff";
|
||||
ctx.fillRect(((t * 60) % (width - 80)) | 0, height - 24, 60, 8);
|
||||
|
||||
ctx.font = "600 20px ui-monospace, monospace";
|
||||
ctx.fillStyle = "#e8e8ec";
|
||||
ctx.fillText(team === 0 ? "PREVIEW · TEAM 1" : "PREVIEW · TEAM 2", 14, height - 40);
|
||||
ctx.font = "500 16px ui-monospace, monospace";
|
||||
ctx.fillStyle = "#8a8a95";
|
||||
ctx.fillText(`frame ${frameId}`, 14, height - 16);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/** 纯格式化函数。界面里所有"给人看的数字"都从这里过一遍。 */
|
||||
|
||||
/** `0x3D4D8A9A`。与 Rust 侧的 `snapshot::id_text` 输出一致。 */
|
||||
export function idText(id: number | null | undefined): string {
|
||||
if (id === null || id === undefined) return "—";
|
||||
return `0x${id.toString(16).toUpperCase().padStart(8, "0")}`;
|
||||
}
|
||||
|
||||
/** 22000 → `21.5 kB`。 */
|
||||
export function bytes(value: number): string {
|
||||
if (value <= 0) return "—";
|
||||
if (value < 1024) return `${value} B`;
|
||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} kB`;
|
||||
return `${(value / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
/** 毫秒 → 人话。 */
|
||||
export function elapsed(ms: number | null | undefined): string {
|
||||
if (ms === null || ms === undefined) return "—";
|
||||
|
||||
if (ms < 1000) return `${Math.round(ms)} ms`;
|
||||
if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
|
||||
|
||||
const totalSeconds = Math.round(ms / 1000);
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
if (minutes < 60) return `${minutes} 分 ${seconds} 秒`;
|
||||
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours} 小时 ${minutes % 60} 分`;
|
||||
}
|
||||
|
||||
/** 录制时长:从开始到现在的墙钟。 */
|
||||
export function since(ms: number | null | undefined, now = Date.now()): string {
|
||||
if (!ms) return "—";
|
||||
return elapsed(now - ms);
|
||||
}
|
||||
|
||||
/** Unix 毫秒 → `14:03:22`。 */
|
||||
export function clockTime(ms: number | null | undefined): string {
|
||||
if (!ms) return "—";
|
||||
|
||||
const date = new Date(ms);
|
||||
const pad = (value: number) => value.toString().padStart(2, "0");
|
||||
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/** 队伍名的兜底值。与 Rust 侧的 `config::DEFAULT_TEAM_NAMES` 一致。 */
|
||||
export const DEFAULT_TEAM_NAMES = ["队伍一", "队伍二"];
|
||||
|
||||
/**
|
||||
* 队伍名。
|
||||
*
|
||||
* 名字是**配置里可以改的**(裁判端能直接编辑),所以显示的地方一律从这里取:散在各处的
|
||||
* `team === 0 ? "队伍一" : "队伍二"` 会在改名之后留下一半旧名字,而且不会报错。
|
||||
*
|
||||
* `names` 传配置里的两条;缺省或留空时回落到默认名。
|
||||
*/
|
||||
export function teamName(team: number, names?: readonly string[] | null): string {
|
||||
if (team === 255) return "待分配队伍";
|
||||
const custom = names?.[team]?.trim();
|
||||
if (custom) return custom;
|
||||
return DEFAULT_TEAM_NAMES[team] ?? "队伍";
|
||||
}
|
||||
|
||||
/**
|
||||
* 队伍配色:与装甲板灯色一致(队伍一红、队伍二蓝)。
|
||||
*
|
||||
* 返回的是 CSS 变量而不是十六进制:这两个颜色是设计令牌(`tokens.css`),改一处就该
|
||||
* 全站跟着变。返回值直接塞进 `style` 也行,`var()` 在那里是合法的。
|
||||
*/
|
||||
export function teamColor(team: number): string {
|
||||
if (team === 255) return "var(--text-muted)";
|
||||
return team === 0 ? "var(--team-0)" : "var(--team-1)";
|
||||
}
|
||||
/**
|
||||
* 固件版本的一行标签:`v0.2.0 · 34`。
|
||||
*
|
||||
* 板子太老、没带版本字段时返回"版本未知"——不要拼出一个 `v0.0.0`,那是假信息。
|
||||
*/
|
||||
export function firmwareLabel(camera: {
|
||||
firmwareVersion: string | null;
|
||||
firmwareBuild: number;
|
||||
}): string {
|
||||
if (!camera.firmwareVersion) {
|
||||
return camera.firmwareBuild > 0 ? `构建 ${camera.firmwareBuild}` : "版本未知";
|
||||
}
|
||||
return camera.firmwareBuild > 0
|
||||
? `v${camera.firmwareVersion} · ${camera.firmwareBuild}`
|
||||
: `v${camera.firmwareVersion}`;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 后端命令的封装。
|
||||
*
|
||||
* 每个函数对应 `client/src-tauri/src/commands.rs` 里的一个 `#[tauri::command]`。
|
||||
* Tauri 会把 JS 侧的 camelCase 参数名转成 Rust 侧的 snake_case,所以这里的参数名写成
|
||||
* 前端习惯的样子即可。
|
||||
*
|
||||
* # 错误
|
||||
*
|
||||
* 后端的 `Err(String)` 会以 rejected promise 的形式回来,字符串就是给现场的人看的那句
|
||||
* 话。`call()` 把 `unknown` 归一成 `Error`,调用方只管 `catch (err) { err.message }`。
|
||||
*/
|
||||
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
import type {
|
||||
ConfigView,
|
||||
HudView,
|
||||
MediaFileDto,
|
||||
RecordingDto,
|
||||
Role,
|
||||
Snapshot,
|
||||
MatchAction,
|
||||
StreamInfo,
|
||||
} from "./types";
|
||||
|
||||
/**
|
||||
* 把后端的字符串错误变成真正的 `Error`。
|
||||
*
|
||||
* 在没有 Tauri 的 `vite dev` 会话里(`?preview=` 那种),这条走预览实现——它用
|
||||
* `await import()` 引入,所以正式构建里那段代码根本不会被打进产物(见 `dev-preview.ts`)。
|
||||
*/
|
||||
async function call<T>(command: string, args?: Record<string, unknown>): Promise<T> {
|
||||
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
|
||||
const preview = await import("./dev-preview");
|
||||
return preview.previewInvoke<T>(command, args);
|
||||
}
|
||||
|
||||
try {
|
||||
return await invoke<T>(command, args);
|
||||
} catch (raw) {
|
||||
throw new Error(typeof raw === "string" ? raw : String(raw));
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
matchAction: (action: MatchAction) => call<void>("match_action", { action }),
|
||||
releaseMatchSource: () => call<void>("release_match_source"),
|
||||
// ---- 只读 ----
|
||||
streamInfo: () => call<StreamInfo>("stream_info"),
|
||||
snapshot: () => call<Snapshot>("get_snapshot"),
|
||||
config: () => call<ConfigView>("get_config"),
|
||||
mediaFiles: () => call<MediaFileDto[]>("list_media_files"),
|
||||
configPath: () => call<string>("config_path"),
|
||||
|
||||
// ---- 密码 ----
|
||||
unlock: (password: string) => call<boolean>("unlock", { password }),
|
||||
lock: () => call<void>("lock"),
|
||||
setPassword: (fresh: string, current?: string) =>
|
||||
call<ConfigView>("set_password", { current: current ?? null, fresh }),
|
||||
setDiscoveryOpen: (open: boolean) => call<void>("set_discovery_open", { open }),
|
||||
|
||||
// ---- 绑定与身份 ----
|
||||
bindCamera: (cameraId: number | null, password?: string) =>
|
||||
call<ConfigView>("bind_camera", { cameraId, password: password ?? null }),
|
||||
bindArmor: (armorId: number | null, password?: string) =>
|
||||
call<ConfigView>("bind_armor", { armorId, password: password ?? null }),
|
||||
setTeam: (team: number, password?: string) =>
|
||||
call<ConfigView>("set_team", { team, password: password ?? null }),
|
||||
setRole: (role: Role, password?: string) =>
|
||||
call<ConfigView>("set_role", { role, password: password ?? null }),
|
||||
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
||||
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
||||
/** 改一边的队名(0 = 队伍一,1 = 队伍二)。一次只改一边,避免覆盖另一边的改动。 */
|
||||
setTeamName: (team: number, name: string, password?: string) =>
|
||||
call<ConfigView>("set_team_name", { team, name, password: password ?? null }),
|
||||
setRefereeSlots: (slots: {
|
||||
cameraA: number | null;
|
||||
cameraB: number | null;
|
||||
armorA: number | null;
|
||||
armorB: number | null;
|
||||
manual: boolean;
|
||||
}) => call<ConfigView>("set_referee_slots", slots),
|
||||
setRecordingOptions: (options: {
|
||||
dir: string | null;
|
||||
ffmpeg: string | null;
|
||||
crf: number | null;
|
||||
preset: string | null;
|
||||
}) => call<ConfigView>("set_recording_options", options),
|
||||
|
||||
// ---- 截图与录制 ----
|
||||
screenshot: (camera: number) => call<string>("screenshot", { camera }),
|
||||
startRecording: (cameras: number[]) => call<RecordingDto[]>("start_recording", { cameras }),
|
||||
stopRecording: (cameras: number[]) => call<RecordingDto[]>("stop_recording", { cameras }),
|
||||
reveal: (path: string) => call<void>("reveal", { path }),
|
||||
openFile: (path: string) => call<void>("open_file", { path }),
|
||||
|
||||
// ---- 退出与重置 ----
|
||||
clearConfig: (password?: string) =>
|
||||
call<string>("clear_config", { password: password ?? null }),
|
||||
quit: (password?: string) => call<void>("quit_app", { password: password ?? null }),
|
||||
|
||||
refresh: () => call<void>("refresh"),
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
/** A screen marker observed through the real camera. No device clock sync. */
|
||||
export type Point = { x: number; y: number };
|
||||
export const CORNERS = [[255,32,32],[32,255,32],[32,96,255],[255,32,255]] as const;
|
||||
export const MARKER_BITS = 16;
|
||||
|
||||
export function markerBits(counter: number): number[] {
|
||||
const gray=(counter&4095)^((counter&4095)>>>1);
|
||||
return [1,0,1,0,...Array.from({length:12},(_,i)=>(gray>>>(11-i))&1)];
|
||||
}
|
||||
|
||||
export function drawMarker(ctx: CanvasRenderingContext2D, counter:number) {
|
||||
const w=ctx.canvas.width,h=ctx.canvas.height;
|
||||
ctx.fillStyle='#30363e';ctx.fillRect(0,0,w,h);
|
||||
// Static coloured detail keeps the target from being an unrealistically tiny JPEG.
|
||||
for(let y=0;y<8;y++) for(let x=0;x<12;x++) {
|
||||
ctx.fillStyle=`hsl(${(x*31+y*47)%360} 10% ${20+(x+y)%3*7}%)`;
|
||||
ctx.fillRect(x*w/12,y*h/8,w/12,h/8);
|
||||
}
|
||||
[[.06,.08],[.94,.08],[.94,.92],[.06,.92]].forEach(([x,y],i)=>{
|
||||
ctx.fillStyle=`rgb(${CORNERS[i].join(',')})`;
|
||||
ctx.fillRect(x*w-.035*w,y*h-.045*h,.07*w,.09*h);
|
||||
});
|
||||
const bits=markerBits(counter);
|
||||
ctx.fillStyle='#222';ctx.fillRect(.12*w,.34*h,.76*w,.32*h);
|
||||
bits.forEach((bit,i)=>{
|
||||
const x=(.14+.72*i/MARKER_BITS)*w,cw=.72*w/MARKER_BITS;
|
||||
ctx.fillStyle=bit?'#fff':'#000';ctx.fillRect(x,.38*h,cw,.10*h);
|
||||
ctx.fillStyle=bit?'#000':'#fff';ctx.fillRect(x,.52*h,cw,.10*h);
|
||||
});
|
||||
}
|
||||
|
||||
function colour(r:number,g:number,b:number):number {
|
||||
// Screen primaries can clip and bloom through exposure/white balance.
|
||||
// Absolute channel separation admits pastel green/cyan while excluding
|
||||
// the low-saturation background (which can otherwise look more blue).
|
||||
if(r>150 && b>150 && r-g>40 && b-g>40 && Math.abs(r-b)<100) return 4;
|
||||
if(r>150 && r-g>40 && r-b>40) return 1;
|
||||
if(g>150 && g-r>35 && g-b>30) return 2;
|
||||
if(b>150 && b>r*1.7 && b-g>20) return 3;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function project(corners:Point[],u:number,v:number):Point|null {
|
||||
const [p0,p1,p2,p3]=corners;
|
||||
const dx1=p1.x-p2.x, dx2=p3.x-p2.x, dx3=p0.x-p1.x+p2.x-p3.x;
|
||||
const dy1=p1.y-p2.y, dy2=p3.y-p2.y, dy3=p0.y-p1.y+p2.y-p3.y;
|
||||
const det=dx1*dy2-dx2*dy1;
|
||||
if(Math.abs(det)<1e-6) return null;
|
||||
const g=(dx3*dy2-dx2*dy3)/det, h=(dx1*dy3-dx3*dy1)/det;
|
||||
const den=g*u+h*v+1;
|
||||
if(Math.abs(den)<.01) return null;
|
||||
return {x:((p1.x-p0.x+g*p1.x)*u+(p3.x-p0.x+h*p3.x)*v+p0.x)/den,
|
||||
y:((p1.y-p0.y+g*p1.y)*u+(p3.y-p0.y+h*p3.y)*v+p0.y)/den};
|
||||
}
|
||||
|
||||
export function decodeMarker(pixels:Uint8ClampedArray,w:number,h:number):{counter:number;corners:Point[]}|null {
|
||||
const labels=new Uint8Array(w*h);
|
||||
for(let i=0;i<labels.length;i++) labels[i]=colour(pixels[i*4],pixels[i*4+1],pixels[i*4+2]);
|
||||
const best=Array.from({length:4},()=>({count:0,x:0,y:0}));
|
||||
const queue=new Int32Array(w*h);
|
||||
for(let start=0;start<labels.length;start++) {
|
||||
const cls=labels[start]; if(!cls) continue;
|
||||
let head=0,tail=1,count=0,sx=0,sy=0;
|
||||
queue[0]=start;labels[start]=0;
|
||||
while(head<tail) {
|
||||
const i=queue[head++],x=i%w,y=Math.floor(i/w);
|
||||
count++;sx+=x;sy+=y;
|
||||
for(const n of [x>0?i-1:-1,x<w-1?i+1:-1,y>0?i-w:-1,y<h-1?i+w:-1]) {
|
||||
if(n>=0 && labels[n]===cls) { labels[n]=0;queue[tail++]=n; }
|
||||
}
|
||||
}
|
||||
if(count>=6 && count<w*h/6 && count>best[cls-1].count) best[cls-1]={count,x:sx/count,y:sy/count};
|
||||
}
|
||||
if(best.some(b=>!b.count)) return null;
|
||||
const corners=best.map(({x,y})=>({x,y}));
|
||||
const area=Math.abs(corners.reduce((a,p,i)=>a+p.x*corners[(i+1)%4].y-p.y*corners[(i+1)%4].x,0))/2;
|
||||
if(area<1500) return null;
|
||||
const luma=(x:number,y:number)=>{
|
||||
let total=0,count=0;
|
||||
for(let dy=-1;dy<=1;dy++) for(let dx=-1;dx<=1;dx++) {
|
||||
const xx=Math.round(x)+dx,yy=Math.round(y)+dy;
|
||||
if(xx<0||xx>=w||yy<0||yy>=h) continue;
|
||||
const i=(yy*w+xx)*4;total+=(pixels[i]+pixels[i+1]+pixels[i+2])/3;count++;
|
||||
}
|
||||
return count?total/count:NaN;
|
||||
};
|
||||
const bits:number[]=[];
|
||||
for(let i=0;i<MARKER_BITS;i++) {
|
||||
const x=.14+.72*(i+.5)/MARKER_BITS;
|
||||
const top=project(corners,(x-.06)/.88,(.43-.08)/.84);
|
||||
const bottom=project(corners,(x-.06)/.88,(.57-.08)/.84);
|
||||
if(!top||!bottom) return null;
|
||||
const delta=luma(top.x,top.y)-luma(bottom.x,bottom.y);
|
||||
if(!Number.isFinite(delta)||Math.abs(delta)<60) return null;
|
||||
bits.push(delta>0?1:0);
|
||||
}
|
||||
if(bits.slice(0,4).join('')!=='1010') return null;
|
||||
let gray=bits.slice(4).reduce((n,b)=>(n<<1)|b,0),counter=gray;
|
||||
while(gray>>>=1) counter^=gray;
|
||||
return {counter,corners};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/** 仅开发浏览器预览,展示合成设备/进度;不模拟可调用的 USB 后端。 */
|
||||
import type { BundleInfo, DeviceSnapshot, FlashPlan, FlashReport } from "./maintenance";
|
||||
|
||||
export function maintenancePreview(stage: string) {
|
||||
const partitions = [
|
||||
{ name: "nvs", kind: 1, subtype: 2, offset: 0x9000, size: 0x6000, flags: 0 },
|
||||
{ name: "phy_init", kind: 1, subtype: 1, offset: 0xf000, size: 0x1000, flags: 0 },
|
||||
{ name: "factory", kind: 0, subtype: 0, offset: 0x10000, size: 0x200000, flags: 0 },
|
||||
];
|
||||
const hash = "0".repeat(64);
|
||||
const device: DeviceSnapshot = { port: "PREVIEW-USB", chip: "esp32c3", revision: "v0.4", flashSize: 0x400000, flashSizeText: "4 MB", mac: "02:00:00:00:00:01", features: [], secureBoot: false, secureDownload: false, flashEncryption: false, securityFlags: 0, flashCryptCnt: 0, partitionTable: partitions, app: null, freeRanges: [], tableSha256: hash };
|
||||
const bundle: BundleInfo = { firmwareKind: "armor", armorTeam: stage === "mismatch" ? 0 : null, armorThreshold: 2000, path: "PREVIEW ONLY", sourceKind: "zip", sourcePath: "PREVIEW ONLY", sourceSha256: hash, entryCount: 4, name: "合成装甲板固件", version: "预览", chip: "esp32c3", appFile: "armor-app.bin", appSha256: hash, appSize: 1084736, partitionTableFile: "partition-table.bin", partitionTableSha256: hash, bootloaderFile: "bootloader.bin", bootloaderSha256: hash, appPartitionSize: 0x200000, flashSize: "4mb", flashSizeBytes: 0x400000, flashMode: "dio", flashFrequency: "40mhz", notes: "合成数据,不可烧录" };
|
||||
const plan: FlashPlan = { mode: "armor-install", confirmation: "PREVIEW ONLY", port: device.port, device, bundle, candidates: [{ offset: 0x10000, size: 0x200000 }], targetOffset: 0x10000, targetSize: 0x200000, appSize: bundle.appSize, appPartitionSize: 0x200000, currentFactoryOffset: 0x10000, currentFactorySize: 0x200000, currentTable: partitions, patchedTable: partitions, tableShaBefore: hash, tableShaAfter: hash, oldAppPreserved: false, warnings: ["C3 固定地址安装:写入 Bootloader(0x0)、分区表(0x8000)和 App(0x10000),旧 App 会被覆盖。", "先完整备份 4 MB Flash,备份失败则停止;失败后需用同一设备的完整备份恢复,仅恢复分区表无效。", "保留 NVS / PHY;通用固件在客户端绑定后按所选队伍改变灯色。"], canFlash: true };
|
||||
if (stage === "migrate") {
|
||||
device.partitionTable = partitions.map(entry => entry.name === "factory" ? { ...entry, size: 0x100000 } : entry);
|
||||
plan.currentTable = device.partitionTable;
|
||||
plan.currentFactorySize = 0x100000;
|
||||
plan.warnings[2] = "现有布局需迁移:完整备份成功后初始化新布局的 NVS / PHY(0x9000–0x10000),原配置会清除;旧数据可通过完整备份恢复。";
|
||||
}
|
||||
const report: FlashReport = { mode: "armor-install", bootloaderVerified: true, ok: stage !== "failure", port: device.port, chip: device.chip, mac: device.mac, bundleName: bundle.name, bundleVersion: bundle.version, targetOffset: 0x10000, targetSize: 0x200000, appSize: bundle.appSize, appSha256: hash, tableShaBefore: hash, tableShaAfter: hash, attempts: [], appVerified: stage !== "failure", tableVerified: stage !== "failure", tableRestored: false, needsRollback: stage === "failure", bootOk: null, bootLog: "合成日志 / 未连接设备", backupDir: "PREVIEW ONLY", note: "合成结果,不能代表硬件验证。", error: stage === "failure" ? "合成故障:App 回读不一致。" : null, startedAt: "PREVIEW ONLY", finishedAt: "PREVIEW ONLY" };
|
||||
return { device, bundle, plan, report };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { BundleInfo, DeviceSnapshot } from "./maintenance";
|
||||
|
||||
export function maintenanceMismatch(
|
||||
kind: "" | "camera" | "armor",
|
||||
team: string,
|
||||
device: Pick<DeviceSnapshot, "chip"> | null,
|
||||
bundle: Pick<BundleInfo, "firmwareKind" | "armorTeam"> | null,
|
||||
): string | null {
|
||||
if (!kind) return "请先选择维护对象。";
|
||||
const chip = kind === "armor" ? "esp32c3" : "esp32s3";
|
||||
if (device && device.chip !== chip) return `所选对象需要 ${chip},读取到 ${device.chip}。请核对设备和串口。`;
|
||||
if (bundle && bundle.firmwareKind !== kind) return "固件包与所选设备类型不符,请重新选择。";
|
||||
if (kind === "armor" && bundle?.armorTeam != null && team !== "0" && team !== "1") return "请先选择目标装甲板的队伍,再核对固件包是否对应。";
|
||||
if (kind === "armor" && bundle?.armorTeam != null && bundle.armorTeam !== Number(team)) return "固件包队伍与目标队伍不同,请重新编译或选择对应队伍的包。";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* 固件维护页的 IPC 与 DTO。
|
||||
*
|
||||
* 字段名与 `client/src-tauri/src/maintenance.rs` 的 `#[serde(rename_all = "camelCase")]`
|
||||
* 一一对应;改一边必须改另一边。
|
||||
*/
|
||||
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
|
||||
export interface PortInfo {
|
||||
portName: string;
|
||||
label: string;
|
||||
vid: number | null;
|
||||
pid: number | null;
|
||||
likelyEsp: boolean;
|
||||
}
|
||||
|
||||
export interface PartitionEntry {
|
||||
name: string;
|
||||
kind: number;
|
||||
subtype: number;
|
||||
offset: number;
|
||||
size: number;
|
||||
flags: number;
|
||||
}
|
||||
|
||||
export interface FreeRange {
|
||||
start: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface AppInfo {
|
||||
offset: number;
|
||||
version: string;
|
||||
projectName: string;
|
||||
buildTime: string;
|
||||
idfVersion: string;
|
||||
}
|
||||
|
||||
export interface DeviceSnapshot {
|
||||
port: string;
|
||||
chip: string;
|
||||
revision: string | null;
|
||||
flashSize: number;
|
||||
flashSizeText: string;
|
||||
mac: string | null;
|
||||
features: string[];
|
||||
secureBoot: boolean;
|
||||
secureDownload: boolean;
|
||||
flashEncryption: boolean;
|
||||
securityFlags: number;
|
||||
flashCryptCnt: number;
|
||||
partitionTable: PartitionEntry[];
|
||||
app: AppInfo | null;
|
||||
freeRanges: FreeRange[];
|
||||
tableSha256: string;
|
||||
}
|
||||
|
||||
export interface BundleInfo {
|
||||
firmwareKind: "camera" | "armor";
|
||||
armorTeam: number | null;
|
||||
armorThreshold: number | null;
|
||||
path: string;
|
||||
sourceKind: string;
|
||||
sourcePath: string;
|
||||
sourceSha256: string | null;
|
||||
entryCount: number | null;
|
||||
name: string;
|
||||
version: string;
|
||||
chip: string;
|
||||
appFile: string;
|
||||
appSha256: string;
|
||||
appSize: number;
|
||||
partitionTableFile: string;
|
||||
partitionTableSha256: string;
|
||||
bootloaderFile: string | null;
|
||||
bootloaderSha256: string | null;
|
||||
appPartitionSize: number;
|
||||
flashSize: string;
|
||||
flashSizeBytes: number;
|
||||
flashMode: string;
|
||||
flashFrequency: string;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
export interface SlotCandidate {
|
||||
offset: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface FlashPlan {
|
||||
mode: "camera-relocate" | "armor-install";
|
||||
confirmation: string;
|
||||
port: string;
|
||||
device: DeviceSnapshot;
|
||||
bundle: BundleInfo;
|
||||
candidates: SlotCandidate[];
|
||||
targetOffset: number;
|
||||
targetSize: number;
|
||||
appSize: number;
|
||||
appPartitionSize: number;
|
||||
currentFactoryOffset: number;
|
||||
currentFactorySize: number;
|
||||
currentTable: PartitionEntry[];
|
||||
patchedTable: PartitionEntry[];
|
||||
tableShaBefore: string;
|
||||
tableShaAfter: string;
|
||||
oldAppPreserved: boolean;
|
||||
warnings: string[];
|
||||
canFlash: boolean;
|
||||
}
|
||||
|
||||
export interface Mismatch {
|
||||
offset: number;
|
||||
expected: number;
|
||||
actual: number;
|
||||
}
|
||||
|
||||
export interface SlotAttempt {
|
||||
offset: number;
|
||||
size: number;
|
||||
writeOk: boolean;
|
||||
verifyOk: boolean;
|
||||
mismatches: Mismatch[];
|
||||
badSectors: number[];
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface FlashProgress {
|
||||
phase: string;
|
||||
message: string;
|
||||
current: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface FlashReport {
|
||||
mode: "camera-relocate" | "armor-install";
|
||||
bootloaderVerified: boolean;
|
||||
ok: boolean;
|
||||
port: string;
|
||||
chip: string;
|
||||
mac: string | null;
|
||||
bundleName: string;
|
||||
bundleVersion: string;
|
||||
targetOffset: number;
|
||||
targetSize: number;
|
||||
appSize: number;
|
||||
appSha256: string;
|
||||
tableShaBefore: string;
|
||||
tableShaAfter: string;
|
||||
attempts: SlotAttempt[];
|
||||
appVerified: boolean;
|
||||
tableVerified: boolean;
|
||||
tableRestored: boolean;
|
||||
needsRollback: boolean;
|
||||
bootOk: boolean | null;
|
||||
bootLog: string;
|
||||
backupDir: string;
|
||||
note: string | null;
|
||||
error: string | null;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
}
|
||||
|
||||
async function call<T>(command: string, args?: Record<string, unknown>): Promise<T> {
|
||||
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
|
||||
if (command === "maintenance_list_ports") return [] as T;
|
||||
throw new Error("浏览器预览仅展示界面;编译和 USB 烧录请在原生客户端操作。");
|
||||
}
|
||||
try {
|
||||
return await invoke<T>(command, args);
|
||||
} catch (raw) {
|
||||
throw new Error(typeof raw === "string" ? raw : String(raw));
|
||||
}
|
||||
}
|
||||
|
||||
export const maintenanceApi = {
|
||||
buildArmor: (request: ArmorBuildRequest) => call<BundleInfo>("maintenance_build_armor", { request }),
|
||||
listPorts: () => call<PortInfo[]>("maintenance_list_ports"),
|
||||
loadBundle: (path: string) => call<BundleInfo>("maintenance_load_bundle", { path }),
|
||||
probe: (port: string) => call<DeviceSnapshot>("maintenance_probe", { port }),
|
||||
plan: (port: string, bundlePath: string) =>
|
||||
call<FlashPlan>("maintenance_plan", { port, bundlePath }),
|
||||
flash: (port: string, bundlePath: string, confirmation: string, backupApp = true) =>
|
||||
call<FlashReport>("maintenance_flash", { port, bundlePath, backupApp, confirmation }),
|
||||
restoreTable: (port: string, backupDir: string, firmwareKind: "camera" | "armor") =>
|
||||
call<string>("maintenance_restore_table", { port, backupDir, firmwareKind }),
|
||||
cancel: () => call<void>("maintenance_cancel"),
|
||||
};
|
||||
|
||||
export interface ArmorBuildRequest {
|
||||
repoPath: string;
|
||||
targetDir: string;
|
||||
idfPath: string;
|
||||
threshold: number;
|
||||
ssid: string;
|
||||
password: string;
|
||||
proxyUrl: string;
|
||||
}
|
||||
|
||||
export async function selectMaintenanceDirectory(title: string): Promise<string | null> {
|
||||
const selected = await open({ directory: true, multiple: false, title });
|
||||
return typeof selected === "string" ? selected : null;
|
||||
}
|
||||
|
||||
/** 原生 .zip 选择。返回 null 表示用户取消。 */
|
||||
export async function selectBundleZip(): Promise<string | null> {
|
||||
const selected = await open({
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title: "选择对应设备的固件包(.zip)",
|
||||
filters: [{ name: "固件包", extensions: ["zip"] }],
|
||||
});
|
||||
return typeof selected === "string" ? selected : null;
|
||||
}
|
||||
|
||||
/** 兼容旧包:选择目录。返回 null 表示用户取消。 */
|
||||
export async function selectBundleDirectory(): Promise<string | null> {
|
||||
const selected = await open({
|
||||
directory: true,
|
||||
multiple: false,
|
||||
title: "选择固件包目录(含 bundle.json)",
|
||||
});
|
||||
return typeof selected === "string" ? selected : null;
|
||||
}
|
||||
|
||||
export function formatBytes(value: number): string {
|
||||
if (value >= 1024 * 1024) return `${(value / (1024 * 1024)).toFixed(2)} MiB`;
|
||||
if (value >= 1024) return `${(value / 1024).toFixed(1)} KiB`;
|
||||
return `${value} B`;
|
||||
}
|
||||
|
||||
export function formatOffset(value: number): string {
|
||||
return `0x${value.toString(16).toUpperCase().padStart(6, "0")}`;
|
||||
}
|
||||
|
||||
export function shortSha(value: string): string {
|
||||
return value.length > 16 ? `${value.slice(0, 12)}…${value.slice(-4)}` : value;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/** 仅被 dev-preview 引用的合成计时,不能作为网络同步测试。 */
|
||||
import { projectMatch } from "./match-time";
|
||||
import type { MatchAction, MatchClockView, MatchPhase } from "./types";
|
||||
|
||||
const scenario = new URLSearchParams(location.search).get("match");
|
||||
const blank = (): MatchClockView => ({ phase: "idle", resumePhase: "idle", pauseKind: null, applicant: null,
|
||||
reason: "", remainingMs: 0, elapsedMs: 0, pauseRemainingMs: null, pauseElapsedMs: 0,
|
||||
connected: true, freshForMs: 1500, source: "预览 / 合成数据", syncError: null });
|
||||
let view = blank();
|
||||
let at = performance.now();
|
||||
if (scenario === "offline") Object.assign(view, { phase: "running", remainingMs: 93_000, elapsedMs: 87_000, connected: false });
|
||||
if (["preparation", "ready", "countdown", "running", "finished"].includes(scenario ?? "")) {
|
||||
view.phase = scenario as MatchPhase;
|
||||
view.remainingMs = scenario === "countdown" ? 5000 : scenario === "ready" || scenario === "finished" ? 0 : 180_000;
|
||||
}
|
||||
if (scenario?.startsWith("paused")) {
|
||||
Object.assign(view, { phase: "paused", resumePhase: "running", remainingMs: 93_000, elapsedMs: 87_000,
|
||||
pauseKind: scenario === "paused-official" ? "official" : "player", applicant: scenario === "paused-official" ? null : 0,
|
||||
reason: "合成演示:检查图传接线", pauseRemainingMs: scenario === "paused-official" ? null : scenario === "paused-expired" ? 0 : 300_000 });
|
||||
}
|
||||
export function previewMatch(): MatchClockView {
|
||||
const now = performance.now();
|
||||
// 预览的合成来源持续在线;通过查询参数单独复现掉线。
|
||||
view = projectMatch({ ...view, freshForMs: Number.MAX_SAFE_INTEGER }, now - at, true); at = now;
|
||||
if (view.phase === "preparation" && view.remainingMs === 0) view.phase = "ready";
|
||||
if (view.phase === "countdown" && view.remainingMs === 0) { view.phase = "running"; view.remainingMs = 180_000; }
|
||||
if (view.phase === "running" && view.remainingMs === 0) view.phase = "finished";
|
||||
return { ...view, connected: scenario !== "offline", freshForMs: scenario === "offline" ? 0 : 1500 };
|
||||
}
|
||||
export function previewMatchAction(action: MatchAction) {
|
||||
previewMatch();
|
||||
switch (action.type) {
|
||||
case "prepare": view = { ...blank(), phase: "preparation", remainingMs: 180_000 }; break;
|
||||
case "countdown": view.phase = "countdown"; view.remainingMs = action.seconds * 1000; break;
|
||||
case "pausePlayer":
|
||||
if (!action.approved) throw new Error("选手技术暂停须经主裁判批准");
|
||||
view = { ...view, resumePhase: view.phase, phase: "paused", pauseKind: "player", applicant: action.team, reason: action.reason, pauseElapsedMs: 0, pauseRemainingMs: 300_000 }; break;
|
||||
case "pauseOfficial": view = { ...view, resumePhase: view.phase, phase: "paused", pauseKind: "official", applicant: null, reason: action.reason, pauseElapsedMs: 0, pauseRemainingMs: null }; break;
|
||||
case "resume": view = { ...view, phase: view.resumePhase, resumePhase: "idle", pauseKind: null, applicant: null, reason: "", pauseRemainingMs: null, pauseElapsedMs: 0 }; break;
|
||||
case "end": view.phase = "finished"; view.pauseKind = null; break;
|
||||
case "reset": view = blank(); break;
|
||||
}
|
||||
at = performance.now();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { MatchClockView, MatchPhase } from "./types";
|
||||
|
||||
export const MATCH_PHASE: Record<MatchPhase, string> = {
|
||||
idle: "等待准备", preparation: "赛前准备", ready: "准备结束 · 等待裁判", countdown: "开赛倒计时",
|
||||
running: "对局进行中", paused: "技术暂停", finished: "本局计时结束",
|
||||
};
|
||||
export function matchTime(ms: number, countingUp = false): string {
|
||||
const seconds = Math.max(0, countingUp ? Math.floor(ms / 1000) : Math.ceil(ms / 1000));
|
||||
return `${Math.floor(seconds / 60).toString().padStart(2, "0")}:${(seconds % 60).toString().padStart(2, "0")}`;
|
||||
}
|
||||
/** 只插值当前快照,不在界面自行切换比赛阶段。后端或网络失联时停止。 */
|
||||
export function projectMatch(view: MatchClockView, age: number, transportLive: boolean) {
|
||||
const delta = transportLive && view.connected ? Math.min(Math.max(0, age), view.freshForMs) : 0;
|
||||
const moving = ["preparation", "countdown", "running"].includes(view.phase);
|
||||
const spent = moving ? Math.min(view.remainingMs, delta) : 0;
|
||||
return { ...view,
|
||||
connected: transportLive && view.connected && age < view.freshForMs,
|
||||
remainingMs: view.remainingMs - spent,
|
||||
elapsedMs: view.elapsedMs + (view.phase === "running" ? spent : 0),
|
||||
pauseElapsedMs: view.pauseElapsedMs + (view.phase === "paused" ? delta : 0),
|
||||
pauseRemainingMs: view.pauseRemainingMs === null ? null : Math.max(0, view.pauseRemainingMs - (view.phase === "paused" ? delta : 0)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* 画面上的叠加图形:瞄准器、网格,以及"图像落在哪"的那一道换算。
|
||||
*
|
||||
* # 为什么单独拆出来
|
||||
*
|
||||
* 这三段代码现在有两个使用者:`VideoSurface` 里的真画面,和设置面板里的小预览窗。预览窗
|
||||
* 存在的意义就是"改完立刻看见",如果它另写一套绘制,两边迟早会不一样——而出现差异时,
|
||||
* 用户看到的是预览里对、画面上偏,这比没有预览更糟。
|
||||
*
|
||||
* 所以这里只放**纯函数**:给 ctx 和数字,画完就退出。不碰 React、不碰请求、不认识 store。
|
||||
*/
|
||||
|
||||
import type { CrosshairConfig, GridConfig } from "./types";
|
||||
|
||||
/** 图像在窗格里的落点与大小(CSS 像素)。 */
|
||||
export interface Geometry {
|
||||
left: number;
|
||||
top: number;
|
||||
drawWidth: number;
|
||||
drawHeight: number;
|
||||
}
|
||||
|
||||
export interface Box {
|
||||
clientWidth: number;
|
||||
clientHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一帧按 `contain` 放进窗格,再乘缩放。
|
||||
*
|
||||
* 平移是**屏幕像素**而不是画面比例:拖动时手感必须是 1:1 的,否则放大之后拖动会变黏。
|
||||
*/
|
||||
export function computeLayout(
|
||||
box: Box,
|
||||
frameWidth: number,
|
||||
frameHeight: number,
|
||||
view: { zoom: number; x: number; y: number },
|
||||
): Geometry {
|
||||
const width = box.clientWidth;
|
||||
const height = box.clientHeight;
|
||||
|
||||
if (frameWidth <= 0 || frameHeight <= 0) {
|
||||
return { left: 0, top: 0, drawWidth: 0, drawHeight: 0 };
|
||||
}
|
||||
|
||||
const fit = Math.min(width / frameWidth, height / frameHeight);
|
||||
const drawWidth = frameWidth * fit * view.zoom;
|
||||
const drawHeight = frameHeight * fit * view.zoom;
|
||||
|
||||
return {
|
||||
left: (width - drawWidth) / 2 + view.x,
|
||||
top: (height - drawHeight) / 2 + view.y,
|
||||
drawWidth,
|
||||
drawHeight,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 瞄准点的屏幕位置。
|
||||
*
|
||||
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时横向要翻过来,
|
||||
* 否则准星会站在画面的另一边——偏移量是相对**摄像头光轴**定的,光轴在镜像之后换了位置。
|
||||
*/
|
||||
export function aimPoint(
|
||||
geometry: Geometry,
|
||||
crosshair: CrosshairConfig | null,
|
||||
mirrored: boolean,
|
||||
canvasWidth: number,
|
||||
canvasHeight: number,
|
||||
): { x: number; y: number } {
|
||||
if (!crosshair || geometry.drawWidth <= 0) {
|
||||
return { x: canvasWidth / 2, y: canvasHeight / 2 };
|
||||
}
|
||||
|
||||
const rawX = geometry.left + (0.5 + crosshair.offsetX) * geometry.drawWidth;
|
||||
return {
|
||||
x: mirrored ? canvasWidth - rawX : rawX,
|
||||
y: geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight,
|
||||
};
|
||||
}
|
||||
|
||||
/** 画网格。网格画在**图像矩形**里:它标的是画面里的比例,用来估距离。 */
|
||||
export function paintGrid(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
geometry: Geometry,
|
||||
grid: GridConfig,
|
||||
): void {
|
||||
if (geometry.drawWidth <= 0 || geometry.drawHeight <= 0) return;
|
||||
|
||||
ctx.save();
|
||||
ctx.strokeStyle = `rgba(255, 255, 255, ${grid.opacity})`;
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
const x0 = geometry.left;
|
||||
const y0 = geometry.top;
|
||||
const x1 = x0 + geometry.drawWidth;
|
||||
const y1 = y0 + geometry.drawHeight;
|
||||
|
||||
if (grid.style === "thirds") {
|
||||
for (const fraction of [1 / 3, 2 / 3]) {
|
||||
line(ctx, x0 + geometry.drawWidth * fraction, y0, x0 + geometry.drawWidth * fraction, y1);
|
||||
line(ctx, x0, y0 + geometry.drawHeight * fraction, x1, y0 + geometry.drawHeight * fraction);
|
||||
}
|
||||
} else if (grid.style === "squares") {
|
||||
const divisions = Math.max(2, grid.divisions);
|
||||
for (let i = 1; i < divisions; i += 1) {
|
||||
const fraction = i / divisions;
|
||||
line(ctx, x0 + geometry.drawWidth * fraction, y0, x0 + geometry.drawWidth * fraction, y1);
|
||||
line(ctx, x0, y0 + geometry.drawHeight * fraction, x1, y0 + geometry.drawHeight * fraction);
|
||||
}
|
||||
} else {
|
||||
line(ctx, x0 + geometry.drawWidth / 2, y0, x0 + geometry.drawWidth / 2, y1);
|
||||
line(ctx, x0, y0 + geometry.drawHeight / 2, x1, y0 + geometry.drawHeight / 2);
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 画瞄准器。
|
||||
*
|
||||
* 两遍描边:先一圈半透明的深色(光环),再画本体。浅色背景下亮绿准星会消失,这一圈让
|
||||
* 它在任何画面上都看得见——这是可读性要求,不是装饰。
|
||||
*/
|
||||
export function paintCrosshair(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
cx: number,
|
||||
cy: number,
|
||||
shortSide: number,
|
||||
config: CrosshairConfig,
|
||||
): void {
|
||||
const arm = Math.max(3, config.size * shortSide);
|
||||
const gap = config.gap * shortSide;
|
||||
const thickness = Math.max(1, config.thickness * shortSide);
|
||||
|
||||
const stroke = (color: string, width: number, radius: number) => {
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = width;
|
||||
ctx.beginPath();
|
||||
|
||||
if (config.style === "circle-dot") {
|
||||
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
|
||||
} else {
|
||||
ctx.moveTo(cx - radius, cy);
|
||||
ctx.lineTo(cx - gap, cy);
|
||||
ctx.moveTo(cx + gap, cy);
|
||||
ctx.lineTo(cx + radius, cy);
|
||||
ctx.moveTo(cx, cy - radius);
|
||||
ctx.lineTo(cx, cy - gap);
|
||||
ctx.moveTo(cx, cy + gap);
|
||||
ctx.lineTo(cx, cy + radius);
|
||||
}
|
||||
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
stroke("rgba(0, 0, 0, 0.55)", thickness + 2, arm + 1);
|
||||
stroke(config.color, thickness, arm);
|
||||
|
||||
if (config.style !== "cross") {
|
||||
const dot = Math.max(1.2, thickness * 0.9);
|
||||
|
||||
ctx.fillStyle = "rgba(0, 0, 0, 0.55)";
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, dot + 1, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = config.color;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, dot, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
/** 半像素偏移,让 1px 的线落在像素中心而不是跨两个像素发虚。 */
|
||||
function line(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x0: number,
|
||||
y0: number,
|
||||
x1: number,
|
||||
y1: number,
|
||||
): void {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(Math.round(x0) + 0.5, Math.round(y0) + 0.5);
|
||||
ctx.lineTo(Math.round(x1) + 0.5, Math.round(y1) + 0.5);
|
||||
ctx.stroke();
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 后端状态的订阅式存储。
|
||||
*
|
||||
* 后端每 200 ms 推一份完整快照,前端只做渲染——没有轮询、没有"各处分别拉数据"带来的
|
||||
* 两种时刻的状态混在一起。实现用一个模块级单例 + `useSyncExternalStore`。
|
||||
*
|
||||
* 快照对象**每次整体替换**:`useSyncExternalStore` 靠引用比较判断要不要重渲染,就地
|
||||
* 修改字段不会触发更新。
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
import { StreamClient } from "./stream";
|
||||
import type { HitEvent, Snapshot, WireMsg } from "./types";
|
||||
|
||||
/**
|
||||
* 一次掉血在界面上的记录。
|
||||
*
|
||||
* `receivedAt` 用 `performance.now()` 而不是后端给的 `atMs`(Unix 毫秒):动画的时钟必须
|
||||
* 与 `requestAnimationFrame` 的时间戳同源,把两个时钟相减会得到一个荒唐的年龄,动画也
|
||||
* 就不会出现。
|
||||
*/
|
||||
export interface HitPulseRecord extends HitEvent {
|
||||
seq: number;
|
||||
receivedAt: number;
|
||||
}
|
||||
|
||||
export interface AppStore {
|
||||
/** 还没收到第一份快照时为 null。 */
|
||||
snapshot: Snapshot | null;
|
||||
/** 与后端的视频通道是否连着。 */
|
||||
connected: boolean;
|
||||
/** 最近一次掉血,界面用它做闪红与伤害数字。 */
|
||||
lastHit: HitPulseRecord | null;
|
||||
/** 后端要求弹出解锁框(用户端点关闭窗口时)。 */
|
||||
confirmQuit: number;
|
||||
/** 一条条要显示的说明。 */
|
||||
notes: string[];
|
||||
/** 通道本身的问题(连不上、丢帧)。 */
|
||||
channelError: string | null;
|
||||
}
|
||||
|
||||
const initial: AppStore = {
|
||||
snapshot: null,
|
||||
connected: false,
|
||||
lastHit: null,
|
||||
confirmQuit: 0,
|
||||
notes: [],
|
||||
channelError: null,
|
||||
};
|
||||
|
||||
let store: AppStore = initial;
|
||||
let hitSeq = 0;
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function emit(next: Partial<AppStore>) {
|
||||
store = { ...store, ...next };
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** 组件里读状态。 */
|
||||
export function useAppStore(): AppStore {
|
||||
return useSyncExternalStore(subscribe, () => store);
|
||||
}
|
||||
|
||||
/** 组件外读状态(事件处理、命令回调里用)。 */
|
||||
export function currentStore(): AppStore {
|
||||
return store;
|
||||
}
|
||||
|
||||
function handleMessage(msg: WireMsg) {
|
||||
switch (msg.t) {
|
||||
case "frameTiming":
|
||||
return; // Consumed by StreamClient before reaching application state.
|
||||
case "snapshot": {
|
||||
const { t: _tag, ...snapshot } = msg;
|
||||
emit({ snapshot: snapshot as Snapshot });
|
||||
return;
|
||||
}
|
||||
case "hit":
|
||||
hitSeq += 1;
|
||||
emit({ lastHit: { ...msg, seq: hitSeq, receivedAt: performance.now() } });
|
||||
return;
|
||||
case "note":
|
||||
emit({ notes: [...store.notes, msg.message].slice(-6) });
|
||||
return;
|
||||
case "confirmQuit":
|
||||
emit({ confirmQuit: store.confirmQuit + 1 });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let client: StreamClient | null = null;
|
||||
|
||||
/**
|
||||
* 建立与后端的通道。整个界面只调一次(在 `App` 里)。
|
||||
*/
|
||||
export function startStream(url: string): StreamClient {
|
||||
client?.close();
|
||||
|
||||
client = new StreamClient({
|
||||
onMessage: handleMessage,
|
||||
onConnection: (connected) =>
|
||||
emit({
|
||||
connected,
|
||||
channelError: connected ? null : "本机视频服务已断开,正在重新连接…",
|
||||
}),
|
||||
});
|
||||
|
||||
// 浏览器预览:没有 WebSocket,状态与画面由 dev-preview.ts 合成。
|
||||
// 动态引入让这段代码在正式构建里被完全剔掉。
|
||||
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
|
||||
emit({ connected: true });
|
||||
|
||||
const current = client;
|
||||
void import("./dev-preview").then((preview) => preview.startPreview(current, handleMessage));
|
||||
return client;
|
||||
}
|
||||
|
||||
client.connect(url);
|
||||
return client;
|
||||
}
|
||||
|
||||
export function streamClient(): StreamClient {
|
||||
if (!client) throw new Error("视频通道尚未启动");
|
||||
return client;
|
||||
}
|
||||
|
||||
/** 手动塞一条说明(本地校验失败之类)。 */
|
||||
export function pushNote(message: string) {
|
||||
emit({ notes: [...store.notes, message].slice(-6) });
|
||||
}
|
||||
|
||||
/** 关掉一条说明。 */
|
||||
export function dismissNote(index: number) {
|
||||
emit({ notes: store.notes.filter((_, i) => i !== index) });
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* 视频与状态通道的客户端。
|
||||
*
|
||||
* # 为什么是 WebSocket 而不是 invoke
|
||||
*
|
||||
* 两路 22fps、每帧约 22 kB,也就是每秒约 1 MB 的裸 JPEG。走 IPC 的话它要变成 base64
|
||||
* 再涨 1/3,然后在 JS 里解回来——CPU 花在没人需要的编解码上。二进制 WebSocket 帧把
|
||||
* 原始 JPEG 字节直接交给我们,交给 `createImageBitmap` 解码。
|
||||
*
|
||||
* # 解码是异步的,所以帧号要看着用
|
||||
*
|
||||
* `createImageBitmap` 返回 Promise,两个相邻帧的解码**可能**乱序完成。所以每路记住最后
|
||||
* 画过的帧号,只有更新的那帧才会被采用。没有这一步,画面会偶发地往回跳一帧——看起来
|
||||
* 像"卡了一下",极难归因。
|
||||
*
|
||||
* # `ImageBitmap` 必须显式 close
|
||||
*
|
||||
* 它持有解码后的像素(不吃 GC 的账)。每收到新帧就替换旧的那张并不够,必须把旧的那张
|
||||
* `close()` 掉,否则两路 22fps 跑上几分钟就是几百 MB 的显存/内存。
|
||||
*/
|
||||
|
||||
import { FRAME_HEADER_LEN, type WireMsg } from "./types";
|
||||
|
||||
/** 每路最新一张画面。 */
|
||||
export interface FrameInfo {
|
||||
camera: number;
|
||||
frameId: number;
|
||||
width: number;
|
||||
height: number;
|
||||
bitmap: ImageBitmap;
|
||||
/** 本地完成解码的时刻(`performance.now()`),用于判断帧的新旧。 */
|
||||
receivedAt: number;
|
||||
}
|
||||
|
||||
interface Handlers {
|
||||
onMessage: (msg: WireMsg) => void;
|
||||
onConnection: (connected: boolean) => void;
|
||||
}
|
||||
|
||||
/** 断线重连的退避上限。 */
|
||||
const MAX_BACKOFF_MS = 3000;
|
||||
const MAX_LOCAL_VIDEO_AGE_MS = 100;
|
||||
|
||||
interface PendingFrame {
|
||||
bytes: ArrayBuffer;
|
||||
arrivedAt: number;
|
||||
publishedUnixMs?: number;
|
||||
}
|
||||
|
||||
export class StreamClient {
|
||||
private ws: WebSocket | null = null;
|
||||
private url: string | null = null;
|
||||
private readonly frames = new Map<number, FrameInfo>();
|
||||
private readonly handlers: Handlers;
|
||||
private retryTimer: number | null = null;
|
||||
private backoff = 250;
|
||||
private closed = false;
|
||||
private generation = 0;
|
||||
private readonly pending = new Map<number, PendingFrame>();
|
||||
private readonly frameTimes = new Map<number, { frameId: number; publishedUnixMs: number }>();
|
||||
private readonly decoding = new Map<number, number>();
|
||||
/** 统计:收到多少帧、解码失败多少张。界面用它区分"链路没数据"和"数据坏了"。 */
|
||||
readonly counters = { frames: 0, decodeFailures: 0, reconnects: 0, skippedDecodes: 0, staleFrames: 0 };
|
||||
|
||||
constructor(handlers: Handlers, private readonly now = () => performance.now(), private readonly wallNow = () => Date.now()) {
|
||||
this.handlers = handlers;
|
||||
}
|
||||
|
||||
connect(url: string) {
|
||||
this.close();
|
||||
this.url = url;
|
||||
this.closed = false;
|
||||
this.open();
|
||||
}
|
||||
|
||||
private open() {
|
||||
if (!this.url || this.closed) return;
|
||||
|
||||
let socket: WebSocket;
|
||||
try {
|
||||
socket = new WebSocket(this.url);
|
||||
} catch {
|
||||
this.scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
socket.binaryType = "arraybuffer";
|
||||
this.ws = socket;
|
||||
|
||||
socket.onopen = () => {
|
||||
if (this.ws !== socket) return;
|
||||
this.backoff = 250;
|
||||
this.handlers.onConnection(true);
|
||||
};
|
||||
|
||||
socket.onclose = () => {
|
||||
if (this.ws !== socket) return;
|
||||
this.generation += 1;
|
||||
this.pending.clear();
|
||||
this.frameTimes.clear();
|
||||
this.decoding.clear();
|
||||
this.handlers.onConnection(false);
|
||||
this.scheduleReconnect();
|
||||
};
|
||||
|
||||
socket.onerror = () => {
|
||||
// onerror 之后一定会有 onclose,重连交给那一条路径。
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
if (this.ws !== socket) return;
|
||||
if (typeof event.data === "string") {
|
||||
try {
|
||||
const message = JSON.parse(event.data) as WireMsg;
|
||||
if (message.t === "frameTiming") this.onTiming(message);
|
||||
else this.handlers.onMessage(message);
|
||||
} catch {
|
||||
// 前端解析不了的消息只可能是版本不匹配,忽略比崩掉好。
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void this.onBinary(event.data as ArrayBuffer);
|
||||
};
|
||||
}
|
||||
|
||||
private onTiming(message: { camera: number; frameId: number; publishedUnixMs: number }) {
|
||||
if (Number.isFinite(message.publishedUnixMs) && message.publishedUnixMs > 0) {
|
||||
this.frameTimes.set(message.camera, message);
|
||||
}
|
||||
}
|
||||
|
||||
private expired(frame: PendingFrame): boolean {
|
||||
return this.now() - frame.arrivedAt >= MAX_LOCAL_VIDEO_AGE_MS ||
|
||||
(frame.publishedUnixMs !== undefined && this.wallNow() - frame.publishedUnixMs >= MAX_LOCAL_VIDEO_AGE_MS);
|
||||
}
|
||||
|
||||
private async onBinary(buffer: ArrayBuffer) {
|
||||
if (this.closed || buffer.byteLength < FRAME_HEADER_LEN) return;
|
||||
|
||||
const view = new DataView(buffer);
|
||||
const camera = view.getUint32(0, true);
|
||||
const length = view.getUint32(12, true);
|
||||
|
||||
if (buffer.byteLength !== FRAME_HEADER_LEN + length) return;
|
||||
|
||||
this.counters.frames += 1;
|
||||
const timing = this.frameTimes.get(camera);
|
||||
const received: PendingFrame = { bytes: buffer, arrivedAt: this.now(),
|
||||
publishedUnixMs: timing?.frameId === view.getUint32(4, true) ? timing.publishedUnixMs : undefined };
|
||||
if (this.expired(received)) { this.counters.staleFrames += 1; return; }
|
||||
if (this.pending.has(camera)) this.counters.skippedDecodes += 1;
|
||||
this.pending.set(camera, received);
|
||||
if (this.decoding.has(camera)) return;
|
||||
|
||||
const generation = this.generation;
|
||||
this.decoding.set(camera, generation);
|
||||
try {
|
||||
while (!this.closed && this.generation === generation) {
|
||||
const next = this.pending.get(camera);
|
||||
if (!next) break;
|
||||
this.pending.delete(camera);
|
||||
if (this.expired(next)) { this.counters.staleFrames += 1; continue; }
|
||||
const header = new DataView(next.bytes);
|
||||
const jpeg = new Uint8Array(next.bytes, FRAME_HEADER_LEN);
|
||||
let bitmap: ImageBitmap;
|
||||
try {
|
||||
bitmap = await createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }));
|
||||
} catch {
|
||||
this.counters.decodeFailures += 1;
|
||||
continue;
|
||||
}
|
||||
if (this.closed || this.generation !== generation) {
|
||||
bitmap.close();
|
||||
break;
|
||||
}
|
||||
if (this.expired(next)) {
|
||||
bitmap.close();
|
||||
this.counters.staleFrames += 1;
|
||||
continue;
|
||||
}
|
||||
this.store(camera, header.getUint32(4, true), header.getUint16(8, true), header.getUint16(10, true), bitmap);
|
||||
}
|
||||
} finally {
|
||||
if (this.decoding.get(camera) === generation) this.decoding.delete(camera);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 放进一帧。
|
||||
*
|
||||
* 解码是异步的,所以这里要再判一次"更新的一帧有没有先到":`createImageBitmap` 的
|
||||
* 完成顺序不保证与发起顺序一致,不判的话画面会偶发地往回跳一帧。
|
||||
*
|
||||
* 预览模式(`dev-preview.ts`)直接调它,绕过 WebSocket——两条路径共用同一套存储逻辑,
|
||||
* 所以预览里看到的画面行为与真机一致。
|
||||
*/
|
||||
private store(
|
||||
camera: number,
|
||||
frameId: number,
|
||||
width: number,
|
||||
height: number,
|
||||
bitmap: ImageBitmap,
|
||||
) {
|
||||
const current = this.frames.get(camera);
|
||||
|
||||
// 带符号差处理 u32 回绕。
|
||||
// After a quiet interval the board may have rebooted and restarted its
|
||||
// frame counter. An older in-flight decode cannot hold the display forever.
|
||||
if (current && ((frameId - current.frameId) | 0) <= 0 && this.now() - current.receivedAt < 1000) {
|
||||
bitmap.close();
|
||||
return;
|
||||
}
|
||||
|
||||
current?.bitmap.close();
|
||||
|
||||
this.frames.set(camera, {
|
||||
camera,
|
||||
frameId,
|
||||
width,
|
||||
height,
|
||||
bitmap,
|
||||
receivedAt: this.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/** 给预览模式用的入口:直接塞一帧。 */
|
||||
injectFrame(
|
||||
camera: number,
|
||||
frameId: number,
|
||||
width: number,
|
||||
height: number,
|
||||
bitmap: ImageBitmap,
|
||||
) {
|
||||
this.counters.frames += 1;
|
||||
this.store(camera, frameId, width, height, bitmap);
|
||||
}
|
||||
|
||||
private scheduleReconnect() {
|
||||
if (this.closed || this.retryTimer !== null) return;
|
||||
|
||||
this.retryTimer = window.setTimeout(() => {
|
||||
this.retryTimer = null;
|
||||
this.counters.reconnects += 1;
|
||||
this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF_MS);
|
||||
this.open();
|
||||
}, this.backoff);
|
||||
}
|
||||
|
||||
/** 某一路最新的一帧。 */
|
||||
latest(camera: number | null | undefined): FrameInfo | undefined {
|
||||
if (camera === null || camera === undefined) return undefined;
|
||||
return this.frames.get(camera);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.generation += 1;
|
||||
this.pending.clear();
|
||||
this.frameTimes.clear();
|
||||
this.decoding.clear();
|
||||
|
||||
if (this.retryTimer !== null) {
|
||||
window.clearTimeout(this.retryTimer);
|
||||
this.retryTimer = null;
|
||||
}
|
||||
|
||||
this.ws?.close();
|
||||
this.ws = null;
|
||||
|
||||
for (const frame of this.frames.values()) frame.bitmap.close();
|
||||
this.frames.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
/**
|
||||
* 与 Rust 侧 DTO 一一对应的类型。
|
||||
*
|
||||
* 这些名字不是随手起的:Rust 那边的结构体带 `#[serde(rename_all = "camelCase")]`,
|
||||
* 字段名就是这里写的这样。改任何一边都要同时改另一边——**编译器不会帮你发现这件事**,
|
||||
* 所以两边都留了指向对方的注释。
|
||||
*
|
||||
* 对应的 Rust 定义在 `client/core/src/snapshot.rs` 与 `client/src-tauri/src/recording.rs`。
|
||||
*/
|
||||
|
||||
export type Role = "team" | "referee";
|
||||
|
||||
/** `cam_core::config::CrosshairStyle` */
|
||||
export type CrosshairStyle = "cross" | "cross-dot" | "circle-dot" | "dot";
|
||||
|
||||
/** `cam_core::config::GridStyle` */
|
||||
export type GridStyle = "thirds" | "squares" | "cross";
|
||||
|
||||
/** `cam_core::config::HealthConfig` */
|
||||
export interface HealthConfig {
|
||||
visible: boolean;
|
||||
showNumbers: boolean;
|
||||
showTeamName: boolean;
|
||||
lowThreshold: number;
|
||||
pulse: boolean;
|
||||
/** 血条宽度占画面宽度的比例。 */
|
||||
width: number;
|
||||
}
|
||||
|
||||
/** `cam_core::config::CrosshairConfig` */
|
||||
export interface CrosshairConfig {
|
||||
visible: boolean;
|
||||
style: CrosshairStyle;
|
||||
/** 臂长 / 半径,画面短边的比例。 */
|
||||
size: number;
|
||||
/** 线宽,画面短边的比例。 */
|
||||
thickness: number;
|
||||
/** 中心空隙,画面短边的比例。 */
|
||||
gap: number;
|
||||
/** `#RRGGBB` */
|
||||
color: string;
|
||||
/** 校准偏移,画面宽度的比例,正数向右。 */
|
||||
offsetX: number;
|
||||
/** 校准偏移,画面高度的比例,正数向下。 */
|
||||
offsetY: number;
|
||||
}
|
||||
|
||||
/** `cam_core::config::GridConfig` */
|
||||
export interface GridConfig {
|
||||
visible: boolean;
|
||||
style: GridStyle;
|
||||
divisions: number;
|
||||
opacity: number;
|
||||
}
|
||||
|
||||
/** `cam_core::config::HitFeedbackConfig` */
|
||||
export interface HitFeedbackConfig {
|
||||
flash: boolean;
|
||||
/**
|
||||
* 已废弃:命中时不再抖动画面。
|
||||
*
|
||||
* 字段留着只是为了读得进旧配置文件(Rust 侧 `deny_unknown_fields`,删字段会让写过
|
||||
* `shake = true` 的配置直接解析失败)。界面不读它。
|
||||
*/
|
||||
shake: boolean;
|
||||
marker: boolean;
|
||||
intensity: number;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::HudView` */
|
||||
export interface HudView {
|
||||
health: HealthConfig;
|
||||
crosshair: CrosshairConfig;
|
||||
grid: GridConfig;
|
||||
hitFeedback: HitFeedbackConfig;
|
||||
showZoom: boolean;
|
||||
showStats: boolean;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::ConfigView`(不含密码哈希) */
|
||||
export interface ConfigView {
|
||||
role: Role;
|
||||
roleChosen: boolean;
|
||||
team: number;
|
||||
/** 两边在界面上显示的名字,下标就是队伍号。裁判端可以直接改。 */
|
||||
teamNames: [string, string];
|
||||
cameraId: number | null;
|
||||
cameraIdText: string | null;
|
||||
armorId: number | null;
|
||||
armorIdText: string | null;
|
||||
mirror: boolean;
|
||||
passwordSet: boolean;
|
||||
hud: HudView;
|
||||
recordingDir: string;
|
||||
ffmpeg: string;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::CameraDto` */
|
||||
export interface CameraDto {
|
||||
id: number;
|
||||
idText: string;
|
||||
addr: string;
|
||||
online: boolean;
|
||||
silenceMs: number;
|
||||
/**
|
||||
* 固件版本,来自板子广播的 Hello。固件太老、没带这个字段时是 `null`——
|
||||
* 这时界面显示"版本未知",而不是一个看起来像真值的 `0.0.0`。
|
||||
*/
|
||||
firmwareVersion: string | null;
|
||||
/** 自增构建号,0 = 未知。 */
|
||||
firmwareBuild: number;
|
||||
/** 板子自报的线路协议版本。 */
|
||||
protocol: number;
|
||||
/**
|
||||
* 本客户端能不能和它通信。
|
||||
*
|
||||
* 为 `false` 时它不会有画面(帧被严格解析挡掉了),但界面**能说出原因**——
|
||||
* 这正是把版本号放进 Hello 的全部意义。
|
||||
*/
|
||||
compatible: boolean;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::ArmorBoardDto` */
|
||||
export interface ArmorBoardDto {
|
||||
id: number;
|
||||
idText: string;
|
||||
addr: string;
|
||||
online: boolean;
|
||||
team: number;
|
||||
hp: number;
|
||||
platesSeen: number;
|
||||
reportsAllPlates: boolean;
|
||||
silenceMs: number;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::CameraStatsDto` */
|
||||
export interface CameraStatsDto {
|
||||
camera: number;
|
||||
cameraText: string;
|
||||
online: boolean;
|
||||
status: string;
|
||||
hasFrames: boolean;
|
||||
fps: number;
|
||||
width: number;
|
||||
height: number;
|
||||
framesShown: number;
|
||||
framesDropped: number;
|
||||
lossPercent: number;
|
||||
datagrams: number;
|
||||
lastFrameBytes: number;
|
||||
gapMs: number | null;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::SlotsDto` */
|
||||
export interface SlotsDto {
|
||||
cameraA: number | null;
|
||||
cameraB: number | null;
|
||||
armorA: number | null;
|
||||
armorB: number | null;
|
||||
manual: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* `cam_core::snapshot::MatchOutcome`。
|
||||
*
|
||||
* 是**从这一边看**的结论,不是"谁赢了"这个全局判断:同一场对局里两边的 DTO 各带一份。
|
||||
*/
|
||||
export type MatchOutcome = "victory" | "defeat" | "draw";
|
||||
|
||||
/** `cam_core::snapshot::TeamHealthDto` */
|
||||
export interface TeamHealthDto {
|
||||
team: number;
|
||||
name: string;
|
||||
available: boolean;
|
||||
placeholder: string;
|
||||
hp: number | null;
|
||||
hps: number[];
|
||||
board: number | null;
|
||||
boardText: string | null;
|
||||
critical: boolean;
|
||||
/** 有结论时(有人归零)才有值;两边都活着时是 null。 */
|
||||
outcome: MatchOutcome | null;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::RecordingDto` */
|
||||
export interface RecordingDto {
|
||||
camera: number;
|
||||
cameraText: string;
|
||||
active: boolean;
|
||||
path: string | null;
|
||||
inputFps: number;
|
||||
framesWritten: number;
|
||||
framesDropped: number;
|
||||
startedMs: number | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** `client/src-tauri/src/recording.rs` 的 `MediaFileDto` */
|
||||
export interface MediaFileDto {
|
||||
name: string;
|
||||
path: string;
|
||||
kind: "video" | "image";
|
||||
bytes: number;
|
||||
modifiedMs: number;
|
||||
}
|
||||
|
||||
/** `cam_core::snapshot::Snapshot` */
|
||||
export interface Snapshot {
|
||||
matchClock: MatchClockView;
|
||||
role: Role;
|
||||
team: number;
|
||||
mirrored: boolean;
|
||||
demo: boolean;
|
||||
diagnostics: boolean;
|
||||
unlocked: boolean;
|
||||
discoveryOpen: boolean;
|
||||
uptimeMs: number;
|
||||
clients: number;
|
||||
config: ConfigView;
|
||||
cameras: CameraDto[];
|
||||
armorBoards: ArmorBoardDto[];
|
||||
stats: CameraStatsDto[];
|
||||
slots: SlotsDto;
|
||||
health: TeamHealthDto[];
|
||||
recordings: RecordingDto[];
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export type MatchPhase = "idle" | "preparation" | "ready" | "countdown" | "running" | "paused" | "finished";
|
||||
export interface MatchClockView {
|
||||
phase: MatchPhase;
|
||||
resumePhase: MatchPhase;
|
||||
pauseKind: "player" | "official" | null;
|
||||
applicant: number | null;
|
||||
reason: string;
|
||||
remainingMs: number;
|
||||
elapsedMs: number;
|
||||
pauseRemainingMs: number | null;
|
||||
pauseElapsedMs: number;
|
||||
connected: boolean;
|
||||
freshForMs: number;
|
||||
source: string | null;
|
||||
syncError: string | null;
|
||||
}
|
||||
export type MatchAction = { type: "prepare" | "resume" | "end" | "reset" }
|
||||
| { type: "countdown"; seconds: number }
|
||||
| { type: "pausePlayer"; team: number; reason: string; approved: boolean }
|
||||
| { type: "pauseOfficial"; reason: string };
|
||||
|
||||
/** `client/src-tauri/src/server.rs` 的 `StreamInfo` */
|
||||
export interface StreamInfo {
|
||||
url: string;
|
||||
port: number;
|
||||
clients: number;
|
||||
}
|
||||
|
||||
/** `server::WireMsg` 的 `Hit`。 */
|
||||
export interface HitEvent {
|
||||
board: number;
|
||||
team: number;
|
||||
index: number;
|
||||
from: number;
|
||||
to: number;
|
||||
damage: number;
|
||||
atMs: number;
|
||||
}
|
||||
|
||||
/** `server::WireMsg` 的文本信封。`t` 是 serde 的内部标签。 */
|
||||
export type WireMsg =
|
||||
| ({ t: "snapshot" } & Snapshot)
|
||||
| ({ t: "hit" } & HitEvent)
|
||||
| { t: "note"; message: string }
|
||||
| { t: "frameTiming"; camera: number; frameId: number; publishedUnixMs: number }
|
||||
| { t: "confirmQuit" };
|
||||
|
||||
/** 二进制视频帧的头部长度,与 `server::FRAME_HEADER_LEN` 一致。 */
|
||||
export const FRAME_HEADER_LEN = 16;
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* F11 / Alt+Enter 全屏切换。
|
||||
*
|
||||
* 状态由 Tauri 窗口持有,不落 localStorage:现场重启后回到窗口化更安全。
|
||||
* 400 ms 去抖避免 F11 自动重复把窗口来回切;输入框内不抢键。
|
||||
*
|
||||
* # 为什么每一处都要先看 `__TAURI_INTERNALS__`
|
||||
*
|
||||
* `getCurrentWindow()` 不是一个"返回 null"的函数:没有 Tauri 注入时它会在**取
|
||||
* metadata 的那一步直接抛**(`Cannot read properties of undefined`)。而抛在
|
||||
* `getCurrentWindow().isFullscreen()` 里意味着抛在 effect 的同步段——React 接不住,
|
||||
* 整棵树会被卸掉,浏览器里 `pnpm dev` 的预览就变成一块空白。
|
||||
*
|
||||
* 所以这里不写 try/catch 去兜:先判断在不在 Tauri 里,不在就整段跳过。
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
|
||||
/** 页面里有没有 Tauri 注入。与 `dev-preview.ts` 用同一个判据。 */
|
||||
function hasTauri(): boolean {
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
export function useFullscreen() {
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const lastToggle = useRef(0);
|
||||
|
||||
const toggle = useCallback(async () => {
|
||||
const now = Date.now();
|
||||
if (now - lastToggle.current < 400) return;
|
||||
lastToggle.current = now;
|
||||
|
||||
if (!hasTauri()) {
|
||||
setFullscreen((value) => !value);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const window = getCurrentWindow();
|
||||
const next = !(await window.isFullscreen());
|
||||
await window.setFullscreen(next);
|
||||
setFullscreen(next);
|
||||
} catch {
|
||||
// 窗口在切换途中被销毁之类。界面不应该为此报错。
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasTauri()) return;
|
||||
|
||||
try {
|
||||
void getCurrentWindow()
|
||||
.isFullscreen()
|
||||
.then(setFullscreen)
|
||||
.catch(() => undefined);
|
||||
} catch {
|
||||
// 同上:没有窗口也要能跑。
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const tag = target?.tagName;
|
||||
if (
|
||||
tag === "INPUT" ||
|
||||
tag === "TEXTAREA" ||
|
||||
tag === "SELECT" ||
|
||||
target?.isContentEditable
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "F11" || (event.altKey && event.key === "Enter")) {
|
||||
event.preventDefault();
|
||||
void toggle();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [toggle]);
|
||||
|
||||
return { fullscreen, toggle };
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 几个只服务于界面节奏的小 hook。
|
||||
*
|
||||
* 它们都不碰后端状态——快照每 200 ms 已经推过来了,重算一次读数不需要再发命令。
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
/**
|
||||
* 「多久没有新的输入了」。
|
||||
*
|
||||
* 用户端用它做 HUD 的休眠:没人碰、没挨打的时候,角上的标签与提示淡下去,把注意力还给
|
||||
* 画面本身;一旦有事件(鼠标、滚轮、键、命中)就整块醒过来。这不是装饰——它是"朴素"
|
||||
* 那一条的落地方式:不动的时候屏幕上的东西越少越好。
|
||||
*/
|
||||
export function useIdle(delay = 6000): boolean {
|
||||
const [idle, setIdle] = useState(false);
|
||||
const timer = useRef<number | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const wake = () => {
|
||||
setIdle(false);
|
||||
window.clearTimeout(timer.current);
|
||||
timer.current = window.setTimeout(() => setIdle(true), delay);
|
||||
};
|
||||
|
||||
wake();
|
||||
|
||||
const events: (keyof WindowEventMap)[] = [
|
||||
"pointermove",
|
||||
"pointerdown",
|
||||
"wheel",
|
||||
"keydown",
|
||||
"focus",
|
||||
];
|
||||
for (const name of events) window.addEventListener(name, wake, { passive: true });
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timer.current);
|
||||
for (const name of events) window.removeEventListener(name, wake);
|
||||
};
|
||||
}, [delay]);
|
||||
|
||||
return idle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个以固定频率重算的时钟。
|
||||
*
|
||||
* 录制时长、"静默 3.2 秒前"这类读数如果没有自己的节拍,就只能等下一份快照才更新——而快照
|
||||
* 200 ms 一份,等于一直在跳。反过来,秒级的读数每秒动一次就够了。
|
||||
*
|
||||
* 返回的 `now` 是墙钟毫秒(`Date.now()`),与快照里的 `startedMs` 同源。
|
||||
*/
|
||||
export function useNow(intervalMs = 1000): number {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [intervalMs]);
|
||||
|
||||
return now;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* 构建信息。**由 `scripts/version.mjs` 生成,请勿手改。**
|
||||
*
|
||||
* 版本号与构建号都从 git 历史算出来(见该脚本的文件头),所以界面显示的一定就是
|
||||
* 这一份二进制的来源,不会出现"装包里写着 0.1.0,其实是两周后的代码"。
|
||||
*/
|
||||
|
||||
export const BUILD = {
|
||||
version: "0.3.0",
|
||||
major: 0,
|
||||
minor: 3,
|
||||
patch: 0,
|
||||
/** git 提交数,单调递增。 */
|
||||
build: 41,
|
||||
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
||||
protocol: 1,
|
||||
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
||||
date: "2026-10-22",
|
||||
} as const;
|
||||
|
||||
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
|
||||
export const VERSION_LABEL = `v${BUILD.version}+${BUILD.build}`;
|
||||
Reference in new issue
Block a user