feat(client): 同步每路镜像并精简操控入口与 HUD 映射
This commit is contained in:
28 files changed
+503
-62
No files matched your search
@@ -200,6 +200,7 @@ pub struct ArmorHealthStore {
|
||||
sink: Mutex<Option<ArmorSink>>,
|
||||
assignments: Mutex<Vec<(u32, u8)>>,
|
||||
match_sink: Mutex<Option<MatchSink>>,
|
||||
mirror_sink: Mutex<Option<Arc<dyn Fn(protocol::CameraMirror) + Send + Sync>>>,
|
||||
match_result_sink: Mutex<Option<MatchResultSink>>,
|
||||
damage_participants: Mutex<HashSet<u32>>,
|
||||
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
|
||||
@@ -219,6 +220,7 @@ impl ArmorHealthStore {
|
||||
sink: Mutex::new(None),
|
||||
assignments: Mutex::new(Vec::new()),
|
||||
match_sink: Mutex::new(None),
|
||||
mirror_sink: Mutex::new(None),
|
||||
match_result_sink: Mutex::new(None),
|
||||
damage_participants: Mutex::new(HashSet::new()),
|
||||
reset: Mutex::new(None),
|
||||
@@ -278,6 +280,17 @@ impl ArmorHealthStore {
|
||||
|
||||
/// 处理一条上报。测试从这里喂字节。
|
||||
pub fn datagram(&self, bytes: &[u8], from: SocketAddr) {
|
||||
if let Some(packet) = protocol::CameraMirror::decode(bytes) {
|
||||
if let Some(sink) = self
|
||||
.mirror_sink
|
||||
.lock()
|
||||
.expect("mirror sink poisoned")
|
||||
.clone()
|
||||
{
|
||||
sink(packet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let SocketAddr::V4(addr) = from else {
|
||||
return;
|
||||
};
|
||||
@@ -418,6 +431,9 @@ impl ArmorHealthStore {
|
||||
pub fn set_match_sink(&self, sink: MatchSink) {
|
||||
*self.match_sink.lock().expect("match sink poisoned") = Some(sink);
|
||||
}
|
||||
pub fn set_mirror_sink(&self, sink: Arc<dyn Fn(protocol::CameraMirror) + Send + Sync>) {
|
||||
*self.mirror_sink.lock().expect("mirror sink poisoned") = Some(sink);
|
||||
}
|
||||
pub fn set_match_result_sink(&self, sink: MatchResultSink) {
|
||||
*self
|
||||
.match_result_sink
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CameraOrientation {
|
||||
pub revision: u64,
|
||||
pub origin: u64,
|
||||
pub mirror: bool,
|
||||
pub mirror_vertical: bool,
|
||||
}
|
||||
pub type CameraMirrors = BTreeMap<String, CameraOrientation>;
|
||||
impl CameraOrientation {
|
||||
pub fn packet(&self, camera_id: u32) -> protocol::CameraMirror {
|
||||
protocol::CameraMirror {
|
||||
camera_id,
|
||||
revision: self.revision,
|
||||
origin: self.origin,
|
||||
mirror: self.mirror,
|
||||
mirror_vertical: self.mirror_vertical,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn merge(entries: &mut CameraMirrors, packet: protocol::CameraMirror) -> bool {
|
||||
if packet.encode().is_none()
|
||||
|| entries
|
||||
.get(&packet.camera_id.to_string())
|
||||
.is_some_and(|old| (old.revision, old.origin) >= (packet.revision, packet.origin))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
entries.insert(
|
||||
packet.camera_id.to_string(),
|
||||
CameraOrientation {
|
||||
revision: packet.revision,
|
||||
origin: packet.origin,
|
||||
mirror: packet.mirror,
|
||||
mirror_vertical: packet.mirror_vertical,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn concurrent_writes_converge_without_echo_or_cross_camera_changes() {
|
||||
let a = protocol::CameraMirror {
|
||||
camera_id: 7,
|
||||
revision: 2,
|
||||
origin: 8,
|
||||
mirror: true,
|
||||
mirror_vertical: false,
|
||||
};
|
||||
let b = protocol::CameraMirror {
|
||||
origin: 9,
|
||||
mirror: false,
|
||||
mirror_vertical: true,
|
||||
..a
|
||||
};
|
||||
let mut left = CameraMirrors::new();
|
||||
let mut right = CameraMirrors::new();
|
||||
merge(&mut left, a);
|
||||
merge(&mut left, b);
|
||||
merge(&mut right, b);
|
||||
assert!(!merge(&mut right, a));
|
||||
assert_eq!(left, right);
|
||||
assert!(!merge(&mut left, b));
|
||||
merge(&mut left, protocol::CameraMirror { camera_id: 9, ..a });
|
||||
assert_eq!(left.len(), 2);
|
||||
let mut config = crate::Config::default();
|
||||
config.camera_mirrors = left;
|
||||
assert_eq!(
|
||||
crate::Config::parse(&toml::to_string(&config).unwrap())
|
||||
.unwrap()
|
||||
.camera_mirrors,
|
||||
config.camera_mirrors
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -440,6 +440,7 @@ pub struct Config {
|
||||
pub mirror: bool,
|
||||
/// 上下镜像,与左右镜像独立;旧配置默认关闭。
|
||||
pub mirror_vertical: bool,
|
||||
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||
/// 密码的 Argon2id PHC 字符串。`None` = 还没设过。
|
||||
///
|
||||
/// 只对用户端有意义([`Role::needs_password`])。
|
||||
@@ -466,6 +467,7 @@ impl Default for Config {
|
||||
armor_id: None,
|
||||
mirror: true,
|
||||
mirror_vertical: false,
|
||||
camera_mirrors: Default::default(),
|
||||
password: None,
|
||||
hud: HudConfig::default(),
|
||||
referee: RefereeConfig::default(),
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
pub mod armor;
|
||||
pub mod armor_reset;
|
||||
pub mod config;
|
||||
pub mod camera_mirror;
|
||||
pub mod match_clock;
|
||||
pub mod operator;
|
||||
pub mod password;
|
||||
|
||||
@@ -385,6 +385,7 @@ pub struct SlotsDto {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Snapshot {
|
||||
pub camera_mirrors: crate::camera_mirror::CameraMirrors,
|
||||
pub operator_control: crate::operator::OperatorView,
|
||||
pub match_clock: crate::match_clock::MatchView,
|
||||
pub role: Role,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use cam_core::{armor::ArmorHealthStore, camera_mirror::{merge, CameraMirrors}};
|
||||
use std::{net::UdpSocket, sync::{Arc,Mutex}, time::Duration};
|
||||
#[test]
|
||||
fn bidirectional_udp_mirrors_remain_camera_scoped_and_ignore_stale_echoes() {
|
||||
let left=ArmorHealthStore::new();let right=ArmorHealthStore::new();
|
||||
let a=Arc::new(Mutex::new(CameraMirrors::new()));let b=Arc::new(Mutex::new(CameraMirrors::new()));
|
||||
let copy=a.clone();left.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);}));
|
||||
let copy=b.clone();right.set_mirror_sink(Arc::new(move|p|{merge(&mut copy.lock().unwrap(),p);}));
|
||||
let tx=UdpSocket::bind("127.0.0.1:0").unwrap();let rx=UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
rx.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
|
||||
let transfer=|packet:protocol::CameraMirror,store:&ArmorHealthStore|{
|
||||
tx.send_to(&packet.encode().unwrap(),rx.local_addr().unwrap()).unwrap();let mut buf=[0;128];let(n,from)=rx.recv_from(&mut buf).unwrap();store.datagram(&buf[..n],from);
|
||||
};
|
||||
let first=protocol::CameraMirror{camera_id:17,revision:1,origin:3,mirror:true,mirror_vertical:true};
|
||||
transfer(first,&right);
|
||||
let second=protocol::CameraMirror{revision:2,origin:4,mirror:false,..first};
|
||||
transfer(second,&left);transfer(second,&right);transfer(first,&left);
|
||||
assert_eq!(*a.lock().unwrap(),*b.lock().unwrap());assert!(!a.lock().unwrap()["17"].mirror);
|
||||
transfer(protocol::CameraMirror{camera_id:18,..first},&right);
|
||||
assert_eq!(a.lock().unwrap().len(),1);assert_eq!(b.lock().unwrap().len(),2);
|
||||
assert!(left.boards().is_empty());assert!(right.boards().is_empty());
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "rmic-2026",
|
||||
"private": true,
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"type": "module",
|
||||
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
|
||||
"scripts": {
|
||||
|
||||
@@ -234,9 +234,7 @@ pub fn set_role(
|
||||
/// 左右镜像。摄像头装反了才需要,不是判罚相关的东西,所以不设密码。
|
||||
#[tauri::command]
|
||||
pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
state
|
||||
.update_config(move |config| config.mirror = mirror)
|
||||
.map_err(|err| format!("{err}"))?;
|
||||
state.set_camera_mirror(None, Some(mirror), None)?;
|
||||
|
||||
Ok(ConfigView::from(&state.config()))
|
||||
}
|
||||
@@ -244,13 +242,21 @@ pub fn set_mirror(mirror: bool, state: Shared<'_>) -> Result<ConfigView, String>
|
||||
/// 上下镜像,独立保存,不改动左右镜像。
|
||||
#[tauri::command]
|
||||
pub fn set_mirror_vertical(mirror_vertical: bool, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
state
|
||||
.update_config(move |config| config.mirror_vertical = mirror_vertical)
|
||||
.map_err(|err| format!("{err}"))?;
|
||||
state.set_camera_mirror(None, None, Some(mirror_vertical))?;
|
||||
|
||||
Ok(ConfigView::from(&state.config()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_camera_mirror(
|
||||
camera: u32,
|
||||
mirror: bool,
|
||||
mirror_vertical: bool,
|
||||
state: Shared<'_>,
|
||||
) -> Result<(), String> {
|
||||
state.set_camera_mirror(Some(camera), Some(mirror), Some(mirror_vertical))
|
||||
}
|
||||
|
||||
/// 保存 HUD 设置(血条、瞄准器、网格、命中反馈)。
|
||||
#[tauri::command]
|
||||
pub fn save_hud(hud: HudConfig, state: Shared<'_>) -> Result<ConfigView, String> {
|
||||
|
||||
@@ -344,6 +344,7 @@ fn run() -> Result<(), Box<dyn Error>> {
|
||||
commands::set_team,
|
||||
commands::set_role,
|
||||
commands::set_mirror,
|
||||
commands::set_camera_mirror,
|
||||
commands::set_mirror_vertical,
|
||||
commands::save_hud,
|
||||
commands::set_team_name,
|
||||
|
||||
@@ -60,6 +60,8 @@ pub struct AppState {
|
||||
match_socket: Option<std::net::UdpSocket>,
|
||||
match_error: Mutex<Option<String>>,
|
||||
match_changed: tokio::sync::Notify,
|
||||
mirror_inbox: Mutex<cam_core::camera_mirror::CameraMirrors>,
|
||||
mirror_origin: u64,
|
||||
operator: Mutex<OperatorState>,
|
||||
operator_socket: Option<std::net::UdpSocket>,
|
||||
operator_focused: AtomicBool,
|
||||
@@ -90,6 +92,125 @@ pub struct AppState {
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn mirror_targets(&self) -> Vec<u32> {
|
||||
let config = self.config();
|
||||
if config.role == Role::Team {
|
||||
config.camera_id.into_iter().collect()
|
||||
} else {
|
||||
self.slots
|
||||
.lock()
|
||||
.expect("slots poisoned")
|
||||
.slots()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_camera_mirror(
|
||||
&self,
|
||||
camera: Option<u32>,
|
||||
horizontal: Option<bool>,
|
||||
vertical: Option<bool>,
|
||||
) -> Result<(), String> {
|
||||
let targets = self.mirror_targets();
|
||||
let ids = match camera {
|
||||
Some(id) if targets.contains(&id) => vec![id],
|
||||
Some(_) => return Err("只能修改已绑定或当前槽位的图传板".into()),
|
||||
None => targets,
|
||||
};
|
||||
let mut config = self.config.lock().expect("config poisoned");
|
||||
let revision = config
|
||||
.camera_mirrors
|
||||
.values()
|
||||
.map(|v| v.revision)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.checked_add(1)
|
||||
.ok_or("镜像修订号已用尽")?;
|
||||
for id in ids {
|
||||
let old = config.camera_mirrors.get(&id.to_string());
|
||||
let packet = protocol::CameraMirror {
|
||||
camera_id: id,
|
||||
revision,
|
||||
origin: self.mirror_origin,
|
||||
mirror: horizontal.unwrap_or(old.map_or(config.mirror, |v| v.mirror)),
|
||||
mirror_vertical: vertical
|
||||
.unwrap_or(old.map_or(config.mirror_vertical, |v| v.mirror_vertical)),
|
||||
};
|
||||
cam_core::camera_mirror::merge(&mut config.camera_mirrors, packet);
|
||||
}
|
||||
if camera.is_none() || config.role == Role::Team {
|
||||
if let Some(v) = horizontal {
|
||||
config.mirror = v;
|
||||
}
|
||||
if let Some(v) = vertical {
|
||||
config.mirror_vertical = v;
|
||||
}
|
||||
}
|
||||
config
|
||||
.save(&self.config_path)
|
||||
.map_err(|e| format!("镜像已在本次运行生效,但保存失败:{e}"))?;
|
||||
drop(config);
|
||||
self.tick_mirrors();
|
||||
self.push_snapshot();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tick_mirrors(&self) {
|
||||
let targets = self.mirror_targets();
|
||||
let inbox = std::mem::take(&mut *self.mirror_inbox.lock().expect("mirror inbox poisoned"));
|
||||
let mut config = self.config.lock().expect("config poisoned");
|
||||
let mut changed = false;
|
||||
for (id, value) in inbox {
|
||||
if let Ok(id) = id.parse::<u32>() {
|
||||
if targets.contains(&id) {
|
||||
changed |= cam_core::camera_mirror::merge(
|
||||
&mut config.camera_mirrors,
|
||||
value.packet(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.role == Role::Team {
|
||||
if let Some(value) = config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.cloned()
|
||||
{
|
||||
config.mirror = value.mirror;
|
||||
config.mirror_vertical = value.mirror_vertical;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if let Err(error) = config.save(&self.config_path) {
|
||||
log::warn!("镜像同步保存失败:{error}");
|
||||
}
|
||||
}
|
||||
let packets: Vec<_> = targets
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
config
|
||||
.camera_mirrors
|
||||
.get(&id.to_string())
|
||||
.map(|v| v.packet(id))
|
||||
})
|
||||
.collect();
|
||||
drop(config);
|
||||
if !self.demo {
|
||||
if let Some(socket) = &self.match_socket {
|
||||
for packet in packets {
|
||||
if let Some(bytes) = packet.encode() {
|
||||
let _ = socket.send_to(
|
||||
&bytes,
|
||||
(std::net::Ipv4Addr::BROADCAST, protocol::ARMOR_PORT),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn operator_context(&self) -> OperatorContext {
|
||||
let config = self.config();
|
||||
let clock = self.match_view();
|
||||
@@ -432,6 +553,8 @@ impl AppState {
|
||||
match_socket,
|
||||
match_error: Mutex::new(match_error),
|
||||
match_changed: tokio::sync::Notify::new(),
|
||||
mirror_inbox: Mutex::new(Default::default()),
|
||||
mirror_origin: session.max(1),
|
||||
operator: Mutex::new(OperatorState::new(session)),
|
||||
operator_socket,
|
||||
operator_focused: AtomicBool::new(true),
|
||||
@@ -462,6 +585,17 @@ impl AppState {
|
||||
///
|
||||
/// 必须在 `Arc<AppState>` 建好之后调用(sink 里要持有 state 的通道)。
|
||||
pub fn install_sinks(self: &Arc<Self>) {
|
||||
let weak = Arc::downgrade(self);
|
||||
self.armor.set_mirror_sink(Arc::new(move |packet| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
if !state.demo && state.mirror_targets().contains(&packet.camera_id) {
|
||||
cam_core::camera_mirror::merge(
|
||||
&mut state.mirror_inbox.lock().expect("mirror inbox poisoned"),
|
||||
packet,
|
||||
);
|
||||
}
|
||||
}
|
||||
}));
|
||||
let weak = Arc::downgrade(self);
|
||||
self.armor.set_match_sink(Arc::new(move |packet, ip| {
|
||||
if let Some(state) = weak.upgrade() {
|
||||
@@ -848,6 +982,7 @@ impl AppState {
|
||||
}
|
||||
|
||||
pub fn tick(&self) {
|
||||
self.tick_mirrors();
|
||||
self.tick_match();
|
||||
let online: Vec<u32> = self
|
||||
.discovery
|
||||
@@ -958,12 +1093,19 @@ impl AppState {
|
||||
.apply_outcomes(&mut health);
|
||||
|
||||
Snapshot {
|
||||
camera_mirrors: config.camera_mirrors.clone(),
|
||||
operator_control: self.operator.lock().expect("operator poisoned").view(),
|
||||
match_clock: self.match_view(),
|
||||
role: config.role,
|
||||
team: config.team,
|
||||
mirrored: config.mirror,
|
||||
mirrored_vertical: config.mirror_vertical,
|
||||
mirrored: config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.map_or(config.mirror, |v| v.mirror),
|
||||
mirrored_vertical: config
|
||||
.camera_id
|
||||
.and_then(|id| config.camera_mirrors.get(&id.to_string()))
|
||||
.map_or(config.mirror_vertical, |v| v.mirror_vertical),
|
||||
demo: self.demo,
|
||||
diagnostics,
|
||||
unlocked: self.is_unlocked(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RMIC-2026",
|
||||
"version": "0.5.0",
|
||||
"version": "0.6.0",
|
||||
"identifier": "com.simbarobotics.rmic2026",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Snapshot } from "../lib/types";
|
||||
import { operatorGate, type useOperatorControl } from "../lib/use-operator-control";
|
||||
import { Slider } from "./controls";
|
||||
import { OperatorMapping } from "./OperatorMapping";
|
||||
|
||||
export function OperatorControls({ control, snapshot, connected, blocked }: {
|
||||
control: ReturnType<typeof useOperatorControl>;
|
||||
snapshot: Snapshot;
|
||||
connected: boolean;
|
||||
blocked: boolean;
|
||||
control: ReturnType<typeof useOperatorControl>; snapshot: Snapshot; connected: boolean; blocked: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const root = useRef<HTMLElement>(null);
|
||||
const matchReason = operatorGate(snapshot, connected, "match");
|
||||
const debugReason = operatorGate(snapshot, connected, "debug");
|
||||
return <section className={`operator-controls${control.activeMode ? " is-active" : ""}${control.activeMode === "debug" ? " is-debug" : ""}`} aria-label="机器人操作" onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()}>
|
||||
{control.activeMode ? <>
|
||||
<strong>{control.activeMode === "debug" ? "赛前调试发送中" : "操作输入发送中"}{snapshot.demo ? " · 合成输入" : ""}</strong>
|
||||
<span>WASD 移动 · 鼠标控制云台 · 左键发射 · ESC 退出</span>
|
||||
<small>{snapshot.demo ? "仅合成预览,无真实发送" : "仅表示客户端发送状态;装甲板及下位机无应答"}</small>
|
||||
</> : <>
|
||||
<div className="operator-controls__actions">
|
||||
<button className="btn btn--primary" disabled={blocked || control.pending || !!matchReason} title={matchReason ?? "锁定鼠标并开始接收键鼠输入"} onClick={() => control.start("match")}>{control.pending ? "正在处理…" : "开启比赛操作"}</button>
|
||||
<button className="btn" disabled={blocked || control.pending || !!debugReason} title={debugReason ?? "未开赛时显式开启调试,开始倒数后自动停止"} onClick={() => control.start("debug")}>开启赛前调试</button>
|
||||
</div>
|
||||
<label className="operator-controls__sensitivity">鼠标灵敏度 <input aria-label="本次鼠标灵敏度" type="range" min="0.25" max="4" step="0.25" value={control.sensitivity} onChange={event => control.setSensitivity(Number(event.target.value))} /><span>×{control.sensitivity.toFixed(2)} · 本次</span></label>
|
||||
<p>{snapshot.demo ? "预览使用合成数据,不向装甲板发送真实操作。" : "WASD 移动 · 鼠标控制云台速度 · 左键发射;ESC 或失焦立即停止。"}</p>
|
||||
{!snapshot.demo && <p>仅确认客户端发送,装甲板及下位机未提供应答。装甲板重启或连接超时后,请退出再开启。</p>}
|
||||
{matchReason && debugReason && <p>{matchReason};{debugReason}</p>}
|
||||
{control.error && <p className="operator-controls__error" role="alert">{control.error}</p>}
|
||||
</>}
|
||||
</section>;
|
||||
useEffect(() => { if (blocked || control.activeMode) setOpen(false); }, [blocked, control.activeMode]);
|
||||
useEffect(() => {
|
||||
const dismiss = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); };
|
||||
document.addEventListener("pointerdown", dismiss);
|
||||
return () => document.removeEventListener("pointerdown", dismiss);
|
||||
}, []);
|
||||
return <>
|
||||
<section ref={root} className="operator-controls" aria-label="机器人操作" onPointerDown={event => event.stopPropagation()} onWheel={event => event.stopPropagation()} onDoubleClick={event => event.stopPropagation()} onKeyDown={event => { if (open && event.key === "Escape") {event.stopPropagation();setOpen(false);} }}>
|
||||
<button className="btn operator-controls__toggle" role="switch" aria-checked={control.activeMode !== null} aria-expanded={open} aria-controls="operator-submenu" disabled={blocked || control.pending} onClick={() => control.activeMode ? control.stop() : setOpen(!open)}>
|
||||
<i className={control.activeMode ? "is-on" : ""} />{control.activeMode === "debug" ? "调试发送" : control.activeMode ? "操控发送" : "操控"}<span>{control.activeMode ? "ESC" : open ? "−" : "+"}</span>
|
||||
</button>
|
||||
{open && <div className="operator-controls__menu" id="operator-submenu">
|
||||
<div className="operator-controls__actions">
|
||||
<button className="btn" disabled={!!matchReason} title={matchReason ?? "WASD / 鼠标 / 左键"} onClick={() => {setOpen(false);control.start("match");}}>比赛操作</button>
|
||||
<button className="btn" disabled={!!debugReason} title={debugReason ?? "未开赛时发送调试输入"} onClick={() => {setOpen(false);control.start("debug");}}>赛前调试</button>
|
||||
</div>
|
||||
<label className="operator-controls__sensitivity"><span>鼠标灵敏度 · 本次</span><Slider min={0.25} max={4} step={0.25} value={control.sensitivity} onChange={control.setSensitivity} format={value => `×${value.toFixed(2)}`} /></label>
|
||||
{matchReason && debugReason && <small>{debugReason}</small>}
|
||||
{snapshot.demo && <small>合成预览</small>}
|
||||
{control.error && <small role="alert">{control.error}</small>}
|
||||
</div>}
|
||||
{!open && control.error && <span className="operator-controls__fault" role="alert" title={control.error}>操作已停止</span>}
|
||||
</section>
|
||||
{control.activeMode === "debug" && <OperatorMapping source={control.mapping} synthetic={snapshot.demo} />}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEffect, useState, type RefObject, type CSSProperties } from "react";
|
||||
import { neutralAxes, type OperatorAxes } from "../lib/operator-input";
|
||||
|
||||
/** 显示已提交的客户端通道值;不把它描述为串口回执或真实机构速度。 */
|
||||
export function OperatorMapping({ source, synthetic }: { source: RefObject<OperatorAxes>; synthetic: boolean }) {
|
||||
const [axes, setAxes] = useState(neutralAxes);
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setAxes({ ...source.current }), 40);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [source]);
|
||||
const channels = [["CH0", "W / S", "前后", axes.forward], ["CH1", "A / D", "左右", axes.strafe], ["CH2", "MOUSE X", "水平", axes.yaw], ["CH3", "MOUSE Y", "俯仰", axes.pitch]] as const;
|
||||
return <div className="operator-mapping" aria-label="调试协议映射">
|
||||
<header><span>CONTROL / MAPPING</span><b>{synthetic ? "合成输入" : "客户端输入"}</b></header>
|
||||
<div className="operator-mapping__flow"><span>键鼠</span><i>→</i><span>UDP</span><i>→</i><span>C3 / UART</span></div>
|
||||
<div className="operator-mapping__channels">{channels.map(([id, input, label, value]) => <div className="operator-mapping__channel" key={id}>
|
||||
<span>{input}</span><span>{id} / {label}</span><strong className="num">{value > 0 ? "+" : ""}{value}</strong>
|
||||
<div className="operator-mapping__track"><i style={{left: `${50 + Math.min(0, value / 20)}%`, width: `${Math.abs(value) / 20}%`} as CSSProperties} /><b /></div>
|
||||
</div>)}</div>
|
||||
<footer><span className={axes.fire ? "is-firing" : ""}>LMB → FIRE <b>{Number(axes.fire)}</b></span><span>±1000 · 速度比例</span><span>ESC 退出</span></footer>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
const previewMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }> = {};
|
||||
/**
|
||||
* 仅开发用的浏览器预览。
|
||||
*
|
||||
@@ -243,6 +244,9 @@ function handle(command: string, args: Record<string, unknown>): unknown {
|
||||
case "set_role":
|
||||
state.role = args.role as "team" | "referee";
|
||||
return configView();
|
||||
case "set_camera_mirror":
|
||||
previewMirrors[String(args.camera)] = { mirror: Boolean(args.mirror), mirrorVertical: Boolean(args.mirrorVertical) };
|
||||
return;
|
||||
case "set_mirror":
|
||||
state.mirror = Boolean(args.mirror);
|
||||
return configView();
|
||||
@@ -432,6 +436,7 @@ function snapshot(): Snapshot {
|
||||
team: state.team,
|
||||
mirrored: state.mirror,
|
||||
mirroredVertical: state.mirrorVertical,
|
||||
cameraMirrors: previewMirrors,
|
||||
matchClock: previewMatch(),
|
||||
operatorControl: { ...previewOperator },
|
||||
demo: true,
|
||||
|
||||
@@ -73,6 +73,7 @@ export const api = {
|
||||
call<ConfigView>("set_team", { team, password: password ?? null }),
|
||||
setRole: (role: Role, password?: string) =>
|
||||
call<ConfigView>("set_role", { role, password: password ?? null }),
|
||||
setCameraMirror: (camera: number, mirror: boolean, mirrorVertical: boolean) => call<void>("set_camera_mirror", { camera, mirror, mirrorVertical }),
|
||||
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
|
||||
setMirrorVertical: (mirrorVertical: boolean) => call<ConfigView>("set_mirror_vertical", { mirrorVertical }),
|
||||
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
|
||||
|
||||
@@ -227,6 +227,7 @@ export interface MediaFileDto {
|
||||
|
||||
/** `cam_core::snapshot::Snapshot` */
|
||||
export interface Snapshot {
|
||||
cameraMirrors: Record<string, { mirror: boolean; mirrorVertical: boolean }>;
|
||||
operatorControl: OperatorControlView;
|
||||
matchClock: MatchClockView;
|
||||
role: Role;
|
||||
|
||||
@@ -26,6 +26,7 @@ export function operatorGate(snapshot: Snapshot, connected: boolean, mode: Opera
|
||||
}
|
||||
|
||||
export function useOperatorControl(options: Options) {
|
||||
const mapping = useRef(neutralAxes());
|
||||
const target = useRef<HTMLDivElement>(null);
|
||||
const current = useRef(options);
|
||||
current.current = options;
|
||||
@@ -43,6 +44,7 @@ export function useOperatorControl(options: Options) {
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const stop = useCallback((reason = "") => {
|
||||
mapping.current = neutralAxes();
|
||||
generation.current++;
|
||||
attempt.current = null;
|
||||
sampler.current.reset(performance.now());
|
||||
@@ -177,6 +179,7 @@ export function useOperatorControl(options: Options) {
|
||||
}
|
||||
const sampled = sampler.current.sample(performance.now(), sensitivityRef.current);
|
||||
if (sampled.stalled) { stop("界面输入已超时,操作已停止,请重新开启"); return; }
|
||||
mapping.current = sampled.axes;
|
||||
session.sender.offer({ input: { captureId: session.id, sequence: ++session.sequence, active: true, ...sampled.axes }, at: performance.now() });
|
||||
}, INPUT_INTERVAL_MS);
|
||||
return () => {
|
||||
@@ -199,5 +202,5 @@ export function useOperatorControl(options: Options) {
|
||||
sensitivityRef.current = value;
|
||||
setSensitivityState(value);
|
||||
};
|
||||
return { target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
||||
return { mapping, target, start, stop, activeMode, pending, error, sensitivity, setSensitivity };
|
||||
}
|
||||
@@ -6,16 +6,16 @@
|
||||
*/
|
||||
|
||||
export const BUILD = {
|
||||
version: "0.5.0",
|
||||
version: "0.6.0",
|
||||
major: 0,
|
||||
minor: 5,
|
||||
minor: 6,
|
||||
patch: 0,
|
||||
/** git 提交数,单调递增。 */
|
||||
build: 46,
|
||||
build: 47,
|
||||
/** 线路协议版本。与固件自报的那个数直接比对。 */
|
||||
protocol: 1,
|
||||
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
|
||||
date: "2026-10-31",
|
||||
date: "2026-11-01",
|
||||
} as const;
|
||||
|
||||
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
|
||||
|
||||
@@ -248,8 +248,8 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
? "已连接,等待画面…"
|
||||
: `等待${label}的图传`
|
||||
}
|
||||
mirrored={snapshot.mirrored}
|
||||
mirroredVertical={snapshot.mirroredVertical}
|
||||
mirrored={snapshot.cameraMirrors[String(pane.camera)]?.mirror ?? snapshot.mirrored}
|
||||
mirroredVertical={snapshot.cameraMirrors[String(pane.camera)]?.mirrorVertical ?? snapshot.mirroredVertical}
|
||||
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
|
||||
crosshair={null}
|
||||
grid={hud.grid}
|
||||
@@ -265,6 +265,13 @@ export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }:
|
||||
focused={focused}
|
||||
onSelect={() => setScope((current) => (current === pane.key ? "all" : pane.key))}
|
||||
>
|
||||
{pane.camera !== null && <div className="ref__mirror-controls" onPointerDown={event => event.stopPropagation()}>
|
||||
{[false, true].map(vertical => {
|
||||
const value = snapshot.cameraMirrors[String(pane.camera)] ?? { mirror: snapshot.mirrored, mirrorVertical: snapshot.mirroredVertical };
|
||||
const checked = vertical ? value.mirrorVertical : value.mirror;
|
||||
return <button className="btn btn--sm" key={String(vertical)} aria-pressed={checked} title="同步到绑定此图传板的选手端" onClick={() => void api.setCameraMirror(pane.camera!, vertical ? value.mirror : !checked, vertical ? !checked : value.mirrorVertical).catch(onError)}>{vertical ? "上下镜像" : "左右镜像"}{checked ? " · 开" : " · 关"}</button>;
|
||||
})}
|
||||
</div>}
|
||||
{hud.health.visible && pane.health && (
|
||||
<div className={`ref__bar ref__bar--${pane.align}`}>
|
||||
<HealthBar health={pane.health} config={hud.health} align={pane.align} />
|
||||
|
||||
@@ -107,16 +107,34 @@
|
||||
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
|
||||
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
|
||||
|
||||
.operator-controls { position: absolute; z-index: 16; left: 50%; bottom: clamp(70px, 12vh, 120px); transform: translateX(-50%); width: min(580px, calc(100% - 48px)); padding: 14px 18px; color: var(--ink); background: #07100de8; border: 1px solid #74af8b55; font: 12px/1.5 var(--font-ui); text-align: center; }
|
||||
.operator-controls__actions { display: flex; justify-content: center; gap: 12px; }
|
||||
.operator-controls__sensitivity { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 12px; }
|
||||
.operator-controls__sensitivity input { width: 120px; }
|
||||
.operator-controls__sensitivity span { min-width: 88px; color: var(--ink-2); }
|
||||
.operator-controls p { margin: 8px 0 0; color: var(--ink-2); }
|
||||
.operator-controls .operator-controls__error { color: var(--warn); }
|
||||
.operator-controls.is-active { width: auto; max-width: calc(100% - 48px); padding: 8px 14px; bottom: 58px; display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 16px; pointer-events: none; }
|
||||
.operator-controls.is-active strong { color: var(--hud); white-space: nowrap; }
|
||||
.operator-controls.is-active small { flex-basis: 100%; color: var(--ink-2); font-size: 10px; }
|
||||
.operator-controls.is-debug { border-color: var(--warn-line); }
|
||||
.operator-controls.is-debug strong { color: var(--warn); }
|
||||
@media (max-height: 650px) { .operator-controls { bottom: 68px; padding: 10px 14px; } .operator-controls.is-active { bottom: 42px; } }
|
||||
/* 操控入口只占左下角一行,参数在二级菜单中展开。 */
|
||||
.operator-controls { position: absolute; z-index: 16; left: 28px; bottom: 48px; color: var(--ink); }
|
||||
.operator-controls__toggle { gap: 10px; min-width: 116px; background: var(--panel); }
|
||||
.operator-controls__toggle > i { width: 6px; height: 6px; background: var(--ink-3); }
|
||||
.operator-controls__toggle > i.is-on { background: var(--hud); }
|
||||
.operator-controls__toggle > span { margin-left: auto; color: var(--ink-3); font: 10px var(--font-mono); }
|
||||
.operator-controls__menu { position: absolute; bottom: calc(100% + 8px); left: 0; width: min(300px, calc(100vw - 56px)); padding: 16px; display: grid; gap: 16px; border: 1px solid var(--line-3); background: var(--panel); animation: dialog-in var(--dur-short4) var(--m3-emphasized-decelerate) both; }
|
||||
.operator-controls__actions { display: flex; gap: 8px; }
|
||||
.operator-controls__actions > button { flex: 1; }
|
||||
.operator-controls__sensitivity { display: grid; gap: 4px; font-size: 11px; color: var(--ink-2); }
|
||||
.operator-controls__menu small { font-size: 10px; color: var(--ink-3); }
|
||||
.operator-controls__fault { margin-left: 10px; font-size: 10px; color: var(--warn); }
|
||||
.operator-mapping { position: absolute; z-index: 12; pointer-events: none; top: 50%; left: 50%; width: min(460px, calc(100% - 56px)); transform: translate(-50%, -50%); color: var(--hud); padding: 18px 22px; background: rgb(5 16 12 / .28); border: 1px solid #74af8b55; font: 10px/1.5 var(--font-mono); animation: hud-reveal var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
|
||||
.operator-mapping header, .operator-mapping footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.operator-mapping header { letter-spacing: .12em; }
|
||||
.operator-mapping header b { font-weight: 400; color: var(--hud-dim); }
|
||||
.operator-mapping__flow { display: flex; justify-content: center; align-items: center; gap: 20px; padding: 12px 0; color: var(--hud-dim); }
|
||||
.operator-mapping__flow i { font-style: normal; }
|
||||
.operator-mapping__channels { display: grid; gap: 10px; }
|
||||
.operator-mapping__channel { display: grid; grid-template-columns: 80px 1fr 55px; gap: 0 12px; align-items: baseline; }
|
||||
.operator-mapping__channel > strong { text-align: right; font-size: 16px; font-weight: 400; }
|
||||
.operator-mapping__channel > span:first-child { color: var(--hud-dim); }
|
||||
.operator-mapping__track { grid-column: 1 / -1; height: 3px; background: #74af8b22; position: relative; }
|
||||
.operator-mapping__track > i { position: absolute; height: 100%; background: var(--hud); transition: left var(--dur-short1) var(--m3-standard), width var(--dur-short1) var(--m3-standard); }
|
||||
.operator-mapping__track > b { position: absolute; left: 50%; top: -2px; height: 7px; width: 1px; background: #74af8b66; }
|
||||
.operator-mapping footer { border-top: 1px solid #74af8b33; margin-top: 16px; padding-top: 10px; color: var(--hud-dim); }
|
||||
.operator-mapping .is-firing { color: var(--hud); }
|
||||
.ref__mirror-controls { position: absolute; z-index: 8; bottom: 42px; right: 12px; display: flex; gap: 6px; }
|
||||
.ref__mirror-controls .btn { background: var(--panel); font-size: 10px; }
|
||||
@media (max-height: 650px) { .operator-controls { bottom: 38px; } .operator-mapping { padding: 10px 18px; } }
|
||||
@media (prefers-reduced-motion: reduce) { .operator-controls__menu, .operator-mapping { animation: none; } .operator-mapping__track > i { transition: none; } }
|
||||
Reference in new issue
Block a user