feat(client): 锁定终局结果并接入 Windows 签名构建
构建客户端 / 检查(类型 + 单元测试) (push) Canceled after 0s
构建客户端 / Linux x64(deb + AppImage) (push) Canceled after 0s
构建客户端 / Windows x64(NSIS 安装包) (push) Canceled after 0s
构建客户端 / macOS 通用(.app + .dmg) (push) Canceled after 0s

- fix(match): 首次归零结束对局并撤销双方扣血许可,裁判结果同步后不再改判

- fix(hud): 蓝方低血量始终保留队伍颜色

- build(windows): 校验代码签名身份和时间戳,明确标注未签名测试包

- docs(version): 说明发布标签基线与语义版本迭代
This commit is contained in:
sloray committed 2026-10-31 10:18:09 +08:00
1 parent 338efa5c2e
commit dac763eb3e
26 files changed
+823 -229

No files matched your search

+25 -5
View File
@@ -104,8 +104,9 @@
# vt/protocol/ 的主机测试必须显式 +stable,并清空继承自 vt/ 的 build-std。
#
# ── 没做的事 ────────────────────────────────────────────────────────────────
# 不签名、不公证:Windows 的 exe 与 macOS 的 app 在别人机器上会被 SmartScreen /
# Gatekeeper 拦一次(右键打开即可)。要做的话给 macOS 那几个 job 加
# Windows 可用 runner 用户证书库中的签名身份;未配置时仅生成标注 unsigned 的测试包,
# v* 标签构建要求签名证书。有效签名仍可能遇到 SmartScreen 信誉提示。
# macOS 仍不签名、不公证,可能被 Gatekeeper 拦截。要做的话给 macOS 那几个 job 加
# APPLE_CERTIFICATE / APPLE_SIGNING_IDENTITY / APPLE_ID / APPLE_PASSWORD /
# APPLE_TEAM_ID(tauri 认这些环境变量,构建步骤不用改)。也没有自动发 Release:
# 要发的话在最后加一个下载全部 artifact 再创建 release 的 job。
@@ -501,9 +502,26 @@ jobs:
# nsis 是纯安装包,不需要 WiX;tauri 会自己把 NSIS 下到用户缓存里(这个缓存
# 也跟着 LOCALAPPDATA 走,见上面 job env),所以这台 runner 要能访问 GitHub
# (离线环境改成 --bundles msi 也一样要下 WiX)。
- name: 打包(tauri build)
- name: Windows 签名配置回归
working-directory: client
run: pnpm tauri build --target ${{ env.TARGET }} --bundles nsis
shell: pwsh
run: ./scripts/test-windows-signing.ps1
- name: 打包并检查 Authenticode
working-directory: client
shell: pwsh
env:
RMIC_WINDOWS_CERT_THUMBPRINT: ${{ vars.WINDOWS_CODE_SIGNING_THUMBPRINT }}
RMIC_RELEASE_REF: ${{ github.ref }}
RMIC_EVENT_NAME: ${{ github.event_name }}
run: |
if ($env:RMIC_EVENT_NAME -eq 'pull_request') {
./scripts/build-windows-release.ps1 -CertificateThumbprint '' -AllowUnsigned
} elseif ($env:RMIC_WINDOWS_CERT_THUMBPRINT -or $env:RMIC_RELEASE_REF -like 'refs/tags/v*') {
./scripts/build-windows-release.ps1
} else {
./scripts/build-windows-release.ps1 -AllowUnsigned
}
- name: 检查安装包与主程序完整性标签
working-directory: client
@@ -522,7 +540,9 @@ jobs:
if-no-files-found: error
retention-days: 14
path: |
client/src-tauri/target/${{ env.TARGET }}/release/bundle/nsis/*.exe
target/releases/**/RMIC-2026*setup.exe
target/releases/**/*.exe.sha256
target/releases/**/windows-signature-verification.json
# ───────────────────────────────────────────────────────────────────────────
# macOS 通用包:.app + .dmg
+18
View File
@@ -40,6 +40,7 @@ MSG_ARMOR_CONTROL = 6
MSG_MATCH_STATE = 7 # 比赛计时广播;装甲板探测器忽略
MSG_ARMOR_DAMAGE_CONTROL = 8 # 扣血许可;装甲板探测器忽略
MSG_ARMOR_RESET = 9 # 复位与回执;探测器只解析,不发送
MSG_MATCH_RESULT = 10 # 裁判终局快照;探测器忽略
PROTOCOL_VERSION = 1
TEAM_NAMES = {0: "队伍一", 1: "队伍二", 255: "待分配队伍"}
@@ -67,6 +68,23 @@ def decode_damage_control(data):
return (board, session, sequence, bool(data[47])) if board and session and sequence else None
def decode_match_result(data):
"""独立检查裁判终局格式;不产生装甲板控制操作。"""
if len(data) != HEADER + 34 or int.from_bytes(data[:4], "little") != MAGIC:
return None
if data[4] != MSG_MATCH_RESULT or int.from_bytes(data[5:7], "little") != PROTOCOL_VERSION or int.from_bytes(data[7:11], "little") != 0:
return None
session = int.from_bytes(data[27:35], "little")
sequence = int.from_bytes(data[35:43], "little")
result_id = int.from_bytes(data[43:51], "little")
remaining = int.from_bytes(data[51:55], "little")
elapsed = int.from_bytes(data[55:59], "little")
outcomes = tuple(data[59:61])
if not session or not 0 < result_id <= sequence or max(remaining, elapsed) > 180000 or outcomes not in ((1, 2), (2, 1), (2, 0), (0, 2), (3, 3)):
return None
return session, sequence, result_id, remaining, elapsed, outcomes
def decode_reset(data):
"""独立核对复位及回执的 56 字节格式,不向设备发送复位。"""
if len(data) != HEADER + 29 or int.from_bytes(data[:4], "little") != MAGIC:
+6
View File
@@ -32,5 +32,11 @@ class WireTests(unittest.TestCase):
self.assertIsNone(probe.decode(packet))
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x01', ack[:-1] + b'\x00', packet[:47] + bytes(8) + packet[55:]):
self.assertIsNone(probe.decode_reset(invalid))
def test_match_result_golden(self):
packet = bytes.fromhex("3143564d0a0100" + "00" * 20 + "0900000000000000" + "1400000000000000" + "1200000000000000" + "a0860100" + "80380100" + "0201")
self.assertEqual(probe.decode_match_result(packet), (9, 20, 18, 100000, 80000, (2, 1)))
self.assertIsNone(probe.decode(packet))
for invalid in (packet[:-1], packet + b'\x00', packet[:-1] + b'\x02', packet[:43] + bytes(8) + packet[51:]):
self.assertIsNone(probe.decode_match_result(invalid))
if __name__ == "__main__": unittest.main()
+20
View File
@@ -113,6 +113,7 @@ pub struct ArmorReport {
/// 在接收线程里被调用,所以必须是非阻塞的。Tauri 层在这里做掉血检测并把结果推给界面。
pub type ArmorSink = Arc<dyn Fn(ArmorReport) + Send + Sync>;
pub type MatchSink = Arc<dyn Fn(protocol::MatchState, Ipv4Addr) + Send + Sync>;
pub type MatchResultSink = Arc<dyn Fn(protocol::MatchResult, Ipv4Addr) + Send + Sync>;
/// 已收到的最新血量。
#[derive(Debug, Default)]
@@ -199,6 +200,7 @@ pub struct ArmorHealthStore {
sink: Mutex<Option<ArmorSink>>,
assignments: Mutex<Vec<(u32, u8)>>,
match_sink: Mutex<Option<MatchSink>>,
match_result_sink: Mutex<Option<MatchResultSink>>,
damage_participants: Mutex<HashSet<u32>>,
reset: Mutex<Option<crate::armor_reset::ArmorResetTracker>>,
}
@@ -217,6 +219,7 @@ impl ArmorHealthStore {
sink: Mutex::new(None),
assignments: Mutex::new(Vec::new()),
match_sink: Mutex::new(None),
match_result_sink: Mutex::new(None),
damage_participants: Mutex::new(HashSet::new()),
reset: Mutex::new(None),
}
@@ -284,6 +287,17 @@ impl ArmorHealthStore {
}
return;
}
if let Some(packet) = protocol::MatchResult::decode(bytes) {
if let Some(sink) = self
.match_result_sink
.lock()
.expect("match result sink poisoned")
.clone()
{
sink(packet, *addr.ip());
}
return;
}
if let Some(packet) = protocol::ArmorReset::decode(bytes) {
if let Some(reset) = self.reset.lock().expect("armor reset poisoned").as_mut() {
reset.acknowledge(packet, addr);
@@ -404,6 +418,12 @@ impl ArmorHealthStore {
pub fn set_match_sink(&self, sink: MatchSink) {
*self.match_sink.lock().expect("match sink poisoned") = Some(sink);
}
pub fn set_match_result_sink(&self, sink: MatchResultSink) {
*self
.match_result_sink
.lock()
.expect("match result sink poisoned") = Some(sink);
}
pub fn set_sink(&self, sink: ArmorSink) {
*self.sink.lock().expect("armor sink mutex poisoned") = Some(sink);
+206 -1
View File
@@ -1,5 +1,6 @@
//! 裁判计时规则与选手端快照跟随。所有时间来自调用方的单调时钟。
//! UDP 会话锁定到首次收到的来源;掉线不自动换裁判,需显式重新接收。
use crate::snapshot::{resolve_outcomes, MatchOutcome, TeamHealthDto};
use protocol::MatchState;
use serde::{Deserialize, Serialize};
use std::net::Ipv4Addr;
@@ -53,6 +54,7 @@ pub struct MatchClock {
at: u64,
source: Option<(Ipv4Addr, u64)>,
received_at: Option<u64>,
result: Option<protocol::MatchResult>,
}
fn idle(session: u64) -> MatchState {
@@ -117,6 +119,7 @@ impl MatchClock {
at: now,
source: None,
received_at: None,
result: None,
}
}
pub fn set_authority(&mut self, authority: bool, now: u64) {
@@ -128,6 +131,7 @@ impl MatchClock {
self.at = now;
self.source = None;
self.received_at = None;
self.result = None;
}
}
fn advance(&mut self, now: u64) {
@@ -156,7 +160,7 @@ impl MatchClock {
}
self.advance(now);
match action {
MatchAction::Prepare if matches!(self.state.phase, 0 | 6) => {
MatchAction::Prepare if matches!(self.state.phase, 0 | 6) && self.result.is_none() => {
let seq = self.state.sequence;
self.state = idle(self.local_session);
self.state.sequence = seq;
@@ -199,6 +203,7 @@ impl MatchClock {
let seq = self.state.sequence;
self.state = idle(self.local_session);
self.state.sequence = seq;
self.result = None;
}
_ => {
return Err(
@@ -223,6 +228,109 @@ impl MatchClock {
self.state.sequence = self.state.sequence.saturating_add(1);
Ok(self.state.clone())
}
/// 首次归零结束正在进行的对局;后续上报不得重新结算。
pub fn finish_on_health(&mut self, hp: [Option<u16>; 2], now: u64) -> bool {
if !self.authority || self.result.is_some() {
return false;
}
self.advance(now);
let playing =
self.state.phase == 4 || (self.state.phase == 5 && self.state.resume_phase == 4);
if !playing || !hp.contains(&Some(0)) {
return false;
}
let outcomes = match hp {
[Some(0), Some(0)] => [3, 3],
[Some(0), Some(hp)] if hp > 0 => [2, 1],
[Some(hp), Some(0)] if hp > 0 => [1, 2],
[Some(0), _] => [2, 0],
_ => [0, 2],
};
self.state.phase = 6;
clear_pause(&mut self.state);
self.state.sequence = self.state.sequence.saturating_add(1);
self.result = Some(protocol::MatchResult {
session: self.state.session,
sequence: self.state.sequence,
result_id: self.state.sequence,
remaining_ms: self.state.remaining_ms,
elapsed_ms: self.state.elapsed_ms,
outcomes,
});
true
}
pub fn result_packet(&self) -> Option<protocol::MatchResult> {
if !self.authority || self.state.phase != 6 {
return None;
}
self.result.map(|result| protocol::MatchResult {
sequence: self.state.sequence,
..result
})
}
/// 终局只投影锁定结论,不篡改装甲板的真实血量。正式选手端以裁判结论为准。
pub fn apply_outcomes(&self, health: &mut [TeamHealthDto]) {
for entry in health.iter_mut() {
entry.outcome = None;
}
if let Some(result) = self.result {
for entry in health {
entry.outcome = match result.outcomes.get(usize::from(entry.team)) {
Some(1) => Some(MatchOutcome::Victory),
Some(2) => Some(MatchOutcome::Defeat),
Some(3) => Some(MatchOutcome::Draw),
_ => None,
};
}
} else if (self.authority && self.state.phase != 6)
|| (!self.authority && self.source.is_none())
{
resolve_outcomes(health);
}
}
pub fn receive_result(
&mut self,
result: protocol::MatchResult,
ip: Ipv4Addr,
now: u64,
) -> bool {
if self.authority || !result.valid() {
return false;
}
if let Some(previous) = self.result {
if previous.session == result.session
&& (result.result_id < previous.result_id
|| (result.result_id == previous.result_id
&& (result.outcomes != previous.outcomes
|| result.remaining_ms != previous.remaining_ms
|| result.elapsed_ms != previous.elapsed_ms)))
{
return false;
}
}
let same_snapshot = self.source == Some((ip, result.session))
&& self.state.sequence == result.sequence
&& self.state.phase == 6
&& self.state.remaining_ms == result.remaining_ms
&& self.state.elapsed_ms == result.elapsed_ms;
if !same_snapshot {
let mut state = idle(result.session);
state.sequence = result.sequence;
state.phase = 6;
state.remaining_ms = result.remaining_ms;
state.elapsed_ms = result.elapsed_ms;
if !self.receive(state, ip, now) {
return false;
}
}
let changed = self.result != Some(result);
self.result = Some(result);
changed
}
fn pause(&mut self, kind: u8, team: u8, reason: String) -> Result<(), String> {
if !(1..=4).contains(&self.state.phase) {
return Err("当前阶段不能申请技术暂停".into());
@@ -258,6 +366,9 @@ impl MatchClock {
}
}
self.source = Some((ip, packet.session));
if packet.phase != 6 {
self.result = None;
}
self.state = packet;
self.received_at = Some(now);
true
@@ -270,6 +381,7 @@ impl MatchClock {
self.source = None;
self.received_at = None;
self.state = idle(self.local_session);
self.result = None;
Ok(())
}
pub fn view(&mut self, now: u64) -> MatchView {
@@ -315,6 +427,99 @@ mod tests {
c.action(MatchAction::Prepare, 0).unwrap();
assert_eq!(c.view(180_000).phase, "ready");
}
fn running(c: &mut MatchClock) {
c.action(MatchAction::Prepare, 0).unwrap();
c.action(MatchAction::SkipPreparation, 100).unwrap();
c.action(MatchAction::Countdown { seconds: 1 }, 100)
.unwrap();
assert_eq!(c.view(1100).phase, "running");
}
#[test]
fn first_knockout_stops_time_and_locks_result_through_late_health_and_reset_attempts() {
let mut c = MatchClock::new(true, 44, 0);
assert!(!c.finish_on_health([Some(0), Some(10)], 0));
running(&mut c);
assert!(c.finish_on_health([Some(0), Some(10)], 2100));
let result = c.result_packet().unwrap();
assert_eq!(result.outcomes, [2, 1]);
assert_eq!(
(c.view(10_000).phase, c.view(10_000).elapsed_ms),
("finished", 1000)
);
assert!(!c.finish_on_health([Some(0), Some(0)], 10_000));
assert!(!c.finish_on_health([Some(100), Some(0)], 10_000));
let names = ["红队".into(), "蓝队".into()];
let mut health = [
TeamHealthDto::present(0, Some(1), [0; 4], 25, &names),
TeamHealthDto::present(1, Some(2), [0; 4], 25, &names),
];
c.apply_outcomes(&mut health);
assert_eq!(health[0].outcome, Some(MatchOutcome::Defeat));
assert_eq!(health[1].outcome, Some(MatchOutcome::Victory));
assert_eq!(health[1].hp, Some(0), "结论锁定不篡改真实上报");
assert!(c.action(MatchAction::Prepare, 10_000).is_err());
c.begin_reset(true, 10_000).unwrap();
assert_eq!(c.result_packet().unwrap().result_id, result.result_id);
c.action(MatchAction::Reset, 10_000).unwrap();
assert!(c.result_packet().is_none());
c.action(MatchAction::Prepare, 10_000).unwrap();
}
#[test]
fn knockout_handles_paused_play_draw_and_missing_opponent_without_inventing_a_win() {
for (hp, expected) in [
([Some(0), Some(0)], [3, 3]),
([Some(0), None], [2, 0]),
([None, Some(0)], [0, 2]),
] {
let mut c = MatchClock::new(true, 44, 0);
running(&mut c);
c.action(
MatchAction::PauseOfficial {
reason: "检查".into(),
},
2100,
)
.unwrap();
assert!(c.finish_on_health(hp, 2200));
assert_eq!(c.result_packet().unwrap().outcomes, expected);
}
assert!(!MatchClock::new(false, 2, 0).finish_on_health([Some(0), Some(10)], 0));
}
#[test]
fn result_sync_is_self_contained_order_independent_and_cannot_revive_after_reset() {
let mut referee = MatchClock::new(true, 44, 0);
running(&mut referee);
referee.finish_on_health([Some(10), Some(0)], 2100);
let state = referee.broadcast(2100).unwrap();
let result = referee.result_packet().unwrap();
for result_first in [false, true] {
let mut player = MatchClock::new(false, 2, 0);
if result_first {
assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 0));
assert!(!player.receive(state.clone(), Ipv4Addr::LOCALHOST, 1));
} else {
assert!(player.receive(state.clone(), Ipv4Addr::LOCALHOST, 0));
assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 1));
}
assert_eq!(player.view(1).phase, "finished");
assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1400));
assert!(!player.view(1500).connected, "重复回执不能续约");
assert!(!player.receive_result(
protocol::MatchResult {
outcomes: [2, 1],
..result
},
Ipv4Addr::LOCALHOST,
1501
));
assert!(!player.receive_result(result, Ipv4Addr::new(1, 2, 3, 4), 1501));
referee.action(MatchAction::Reset, 2200).unwrap();
let reset = referee.broadcast(2200).unwrap();
assert!(player.receive(reset, Ipv4Addr::LOCALHOST, 1600));
assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1601));
assert!(player.result.is_none());
}
}
#[test]
fn preparation_waits_for_referee_then_countdown_carries_excess_time() {
let mut c = MatchClock::new(true, 1, 0);
+99
View File
@@ -94,3 +94,102 @@ fn udp_snapshot_routes_to_follower_without_polluting_armor_health() {
store.datagram(&packet, from);
assert_eq!(follower.lock().unwrap().view(1000).remaining_ms, 160_000);
}
#[test]
fn knockout_revokes_both_boards_and_result_survives_late_winner_death() {
let tx = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let store = ArmorHealthStore::new();
let boards: Vec<_> = (1..=2)
.map(|id| {
let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
store.datagram(
&protocol::ArmorHealth {
team: id - 1,
index: 0,
hp: 100,
}
.encode_from(u32::from(id)),
socket.local_addr().unwrap(),
);
socket
})
.collect();
let mut clock = MatchClock::new(true, 80, 0);
clock.action(MatchAction::Prepare, 0).unwrap();
clock.action(MatchAction::SkipPreparation, 100).unwrap();
clock
.action(MatchAction::Countdown { seconds: 1 }, 100)
.unwrap();
let state = clock.broadcast(1100).unwrap();
let mut buf = [0; 512];
store
.send_damage_controls(&tx, &state, [Some(1), Some(2)])
.unwrap();
for board in &boards {
let (n, _) = board.recv_from(&mut buf).unwrap();
assert!(
protocol::ArmorDamageControl::decode(&buf[..n])
.unwrap()
.enabled
);
}
assert!(clock.finish_on_health([Some(0), Some(10)], 2100));
let state = clock.broadcast(2100).unwrap();
store
.send_damage_controls(&tx, &state, [Some(1), Some(2)])
.unwrap();
for board in &boards {
let (n, _) = board.recv_from(&mut buf).unwrap();
assert!(
!protocol::ArmorDamageControl::decode(&buf[..n])
.unwrap()
.enabled
);
}
assert!(!clock.finish_on_health([Some(0), Some(0)], 2200));
let follower = Arc::new(Mutex::new(MatchClock::new(false, 2, 0)));
let reader = ArmorHealthStore::new();
let follow = follower.clone();
reader.set_match_result_sink(Arc::new(move |result, ip| {
follow.lock().unwrap().receive_result(result, ip, 2100);
}));
let rx = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
rx.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
tx.send_to(
&clock.result_packet().unwrap().encode().unwrap(),
rx.local_addr().unwrap(),
)
.unwrap();
let (n, from) = rx.recv_from(&mut buf).unwrap();
reader.datagram(&buf[..n], from);
assert_eq!(follower.lock().unwrap().view(2100).phase, "finished");
assert!(reader.boards().is_empty());
for (index, board) in boards.iter().enumerate() {
reader.datagram(
&protocol::ArmorHealth {
team: index as u8,
index: 0,
hp: 0,
}
.encode_from(index as u32 + 1),
board.local_addr().unwrap(),
);
}
let names = ["红队".into(), "蓝队".into()];
let mut health = [
cam_core::snapshot::TeamHealthDto::present(0, Some(1), [0; 4], 25, &names),
cam_core::snapshot::TeamHealthDto::present(1, Some(2), [0; 4], 25, &names),
];
follower.lock().unwrap().apply_outcomes(&mut health);
assert_eq!(
health[0].outcome,
Some(cam_core::snapshot::MatchOutcome::Defeat)
);
assert_eq!(
health[1].outcome,
Some(cam_core::snapshot::MatchOutcome::Victory)
);
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "rmic-2026",
"private": true,
"version": "0.3.0",
"version": "0.4.0",
"type": "module",
"description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)",
"scripts": {
+104
View File
@@ -0,0 +1,104 @@
# Build with Tauri's native Authenticode signing support. No private keys or
# personal signing identities are stored in the shared Tauri configuration.
[CmdletBinding()]
param(
[string]$CertificateThumbprint = $env:RMIC_WINDOWS_CERT_THUMBPRINT,
[string]$TimestampUrl = 'http://timestamp.digicert.com',
[switch]$AllowUnsigned,
[switch]$PreflightOnly,
[string]$OutputDirectory
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$clientRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$repoRoot = Split-Path -Parent $clientRoot
$thumbprint = ($CertificateThumbprint -replace '\s', '').ToUpperInvariant()
$signed = $thumbprint.Length -gt 0
if ($signed) {
if ($thumbprint -notmatch '^[0-9A-F]{40}$') { throw 'Invalid code-signing certificate thumbprint.' }
$certificate = Get-Item -LiteralPath "Cert:\CurrentUser\My\$thumbprint" -ErrorAction SilentlyContinue
if (-not $certificate) { throw 'Code-signing certificate was not found in CurrentUser/My.' }
$now = Get-Date
if (-not $certificate.HasPrivateKey -or $certificate.NotBefore -gt $now -or $certificate.NotAfter -le $now) {
throw 'The signing certificate needs an accessible private key and must be currently valid.'
}
if ($certificate.Subject -eq $certificate.Issuer) { throw 'A self-signed certificate cannot be used as a public release identity.' }
$usageOids = @($certificate.Extensions |
Where-Object { $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } |
ForEach-Object { $_.EnhancedKeyUsages } | ForEach-Object { $_.Value })
if ('1.3.6.1.5.5.7.3.3' -notin $usageOids) {
throw 'The certificate is not authorized for code signing.'
}
} elseif (-not $AllowUnsigned) {
throw 'A code-signing certificate is required. Set RMIC_WINDOWS_CERT_THUMBPRINT or explicitly use -AllowUnsigned for a test package.'
}
$timestamp = $null
if (-not [Uri]::TryCreate($TimestampUrl, [UriKind]::Absolute, [ref]$timestamp) -or
$timestamp.Scheme -notin @('http', 'https') -or -not $timestamp.Host -or $timestamp.UserInfo) {
throw 'Timestamp URL must be an HTTP(S) server without credentials.'
}
if ($PreflightOnly) {
[pscustomobject]@{ signing = $signed; unsignedExplicitlyAllowed = [bool]$AllowUnsigned; digestAlgorithm = 'sha256'; tsp = $true }
return
}
& (Join-Path $PSScriptRoot 'prepare-windows-bundle.ps1') -CheckProcessOnly
& node (Join-Path $repoRoot 'scripts/version.mjs') --check
if ($LASTEXITCODE -ne 0) { throw 'Regenerate versions before packaging.' }
$version = Get-Content -LiteralPath (Join-Path $repoRoot 'version.json') -Raw | ConvertFrom-Json
$label = "v$($version.version)+$($version.build)"
if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repoRoot "target/releases/$label" }
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
$temporaryConfig = Join-Path $OutputDirectory 'windows-signing.local.json'
$windows = if ($signed) {
@{ certificateThumbprint = $thumbprint; digestAlgorithm = 'sha256'; timestampUrl = $TimestampUrl; tsp = $true }
} else {
@{ certificateThumbprint = $null; digestAlgorithm = $null; timestampUrl = $null; tsp = $false; signCommand = $null }
}
$utf8 = New-Object Text.UTF8Encoding($false)
[IO.File]::WriteAllText($temporaryConfig, (@{ bundle = @{ windows = $windows } } | ConvertTo-Json -Depth 6), $utf8)
$previousTarget = $env:CARGO_TARGET_DIR
$previousToolchain = $env:RUSTUP_TOOLCHAIN
try {
Remove-Item Env:CARGO_TARGET_DIR -ErrorAction SilentlyContinue
$env:RUSTUP_TOOLCHAIN = 'stable'
Push-Location $clientRoot
try {
& pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci --config $temporaryConfig -- --locked --config 'unstable.build-std=[]'
if ($LASTEXITCODE -ne 0) { throw 'Windows build or signing failed; no verified installer was delivered.' }
& (Join-Path $PSScriptRoot 'prepare-windows-bundle.ps1') -CheckOnly
$metadata = (& cargo +stable metadata --no-deps --format-version 1 --manifest-path src-tauri/Cargo.toml | ConvertFrom-Json)
if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve Cargo output path.' }
} finally { Pop-Location }
$release = Join-Path $metadata.target_directory 'x86_64-pc-windows-msvc/release'
$main = Join-Path $release 'cam-desktop.exe'
$installer = Join-Path $release "bundle/nsis/RMIC-2026_$($version.version)_x64-setup.exe"
$signatures = @()
foreach ($file in @($main, $installer)) {
$signature = Get-AuthenticodeSignature -LiteralPath $file
if ($signed -and ($signature.Status -ne 'Valid' -or -not $signature.TimeStamperCertificate -or
$signature.SignerCertificate.Thumbprint -ne $thumbprint)) {
throw "The signature, signer or timestamp could not be verified: $file"
}
if (-not $signed -and $signature.Status -ne 'NotSigned') { throw "Unexpected signature on explicitly unsigned output: $file" }
$signatures += @{ file = [IO.Path]::GetFileName($file); status = [string]$signature.Status; timestamped = $null -ne $signature.TimeStamperCertificate }
}
$suffix = if ($signed) { '' } else { '-unsigned' }
$delivery = Join-Path $OutputDirectory "RMIC-2026_${label}_windows-x64${suffix}-setup.exe"
Copy-Item -LiteralPath $installer -Destination $delivery
& icacls.exe $delivery /setintegritylevel M | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Cannot set installer Medium integrity label.' }
$hash = (Get-FileHash -LiteralPath $delivery -Algorithm SHA256).Hash.ToLowerInvariant()
[IO.File]::WriteAllText("$delivery.sha256", "$hash $([IO.Path]::GetFileName($delivery))`n", $utf8)
$report = @{ version = $label; installer = $delivery; sha256 = $hash; signed = $signed;
signatures = $signatures; smartScreenReputationVerified = $false }
[IO.File]::WriteAllText((Join-Path $OutputDirectory 'windows-signature-verification.json'), ($report | ConvertTo-Json -Depth 6), $utf8)
$report | ConvertTo-Json -Depth 6
} finally {
# This config contains a personal public certificate identity, and is local only.
Remove-Item -LiteralPath $temporaryConfig -ErrorAction SilentlyContinue
if ($null -eq $previousTarget) { Remove-Item Env:CARGO_TARGET_DIR -ErrorAction SilentlyContinue } else { $env:CARGO_TARGET_DIR = $previousTarget }
if ($null -eq $previousToolchain) { Remove-Item Env:RUSTUP_TOOLCHAIN -ErrorAction SilentlyContinue } else { $env:RUSTUP_TOOLCHAIN = $previousToolchain }
}
+15
View File
@@ -70,6 +70,21 @@ test("the low-health marker uses the exact threshold in the track's mirrored coo
}
});
test("critical health preserves each team's color for name, number, fill and border", () => {
for (const [team, color] of [[0, "red"], [1, "blue"]]) {
for (const hp of [30, 1, 0]) {
const html = renderToStaticMarkup(createElement(healthModule.HealthBar, {
health: { ...health, team, hp, critical: true }, config: { ...config, pulse: true }, align: "right",
}));
assert.match(html, /hp--critical/);
assert.match(html, /hp--pulsing/);
assert.match(html, new RegExp(`hp__fill" style="width:${hp}%;background-color:${color}`));
assert.match(html, new RegExp(`hp__value num" style="color:${color}"`));
assert.doesNotMatch(html, /var\(--error\)/);
}
}
});
function snapshot() {
return {
config: { cameraId: 1, armorId: 2, teamNames: ["我方", "对手"] },
+23
View File
@@ -0,0 +1,23 @@
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$build = Join-Path $PSScriptRoot 'build-windows-release.ps1'
function Must-Reject([scriptblock]$Action, [string]$Expected) {
$rejected = $false
try { & $Action } catch {
if ($_.Exception.Message -notmatch $Expected) { throw }
$rejected = $true
}
if (-not $rejected) { throw 'Signing preflight accepted an invalid configuration.' }
}
Must-Reject { & $build -CertificateThumbprint '' -PreflightOnly } 'certificate is required'
Must-Reject { & $build -CertificateThumbprint 'not-a-certificate' -AllowUnsigned -PreflightOnly } 'Invalid.*thumbprint'
Must-Reject { & $build -CertificateThumbprint ('0' * 40) -AllowUnsigned -PreflightOnly } 'not found'
Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'file:///tmp/timestamp' -PreflightOnly } 'Timestamp URL'
Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'https://user:secret@example.invalid' -PreflightOnly } 'Timestamp URL'
$result = & $build -CertificateThumbprint '' -AllowUnsigned -PreflightOnly
if ($result.signing -or -not $result.unsignedExplicitlyAllowed -or $result.digestAlgorithm -ne 'sha256' -or -not $result.tsp) {
throw 'Explicit unsigned preflight returned inconsistent signing metadata.'
}
Write-Host 'Windows signing preflight: 6 checks passed; no certificates or system settings were changed.'
+2 -2
View File
@@ -135,7 +135,7 @@ fn spawn_armor(state: Arc<AppState>) {
hits = [0, 1];
dead_for = [0; 2];
}
let scripted = reset_epoch == 0 || state.demo_damage_enabled();
let scripted = state.demo_damage_enabled();
for (slot, (board, team, port)) in boards.iter().enumerate() {
if scripted {
ticks[slot] += 1;
@@ -144,7 +144,7 @@ fn spawn_armor(state: Arc<AppState>) {
if hp[slot] == 0 {
// 打空之后停一会儿再重置:让界面上的胜负横幅真的能被看到。
dead_for[slot] += 1;
if reset_epoch == 0 && dead_for[slot] >= 10 {
if reset_epoch == 0 && scripted && dead_for[slot] >= 10 {
hp[slot] = 100;
dead_for[slot] = 0;
ticks[slot] = 0;
+62 -11
View File
@@ -27,8 +27,7 @@ use cam_core::password;
use cam_core::receiver::{Discovery, LatestFrames, Receiver};
use cam_core::slots::SlotAllocator;
use cam_core::snapshot::{
resolve_outcomes, ArmorBoardDto, CameraDto, CameraStatsDto, ConfigView, HitDto, SlotsDto,
Snapshot, TeamHealthDto,
ArmorBoardDto, CameraDto, CameraStatsDto, ConfigView, HitDto, SlotsDto, Snapshot, TeamHealthDto,
};
use cam_core::stats::{FpsWindow, DEFAULT_WINDOW};
use cam_core::ArmorSource;
@@ -59,6 +58,7 @@ pub struct AppState {
match_clock: Mutex<MatchClock>,
match_socket: Option<std::net::UdpSocket>,
match_error: Mutex<Option<String>>,
match_changed: tokio::sync::Notify,
resetting: AtomicBool,
pub demo_reset_epoch: AtomicUsize,
discovery: Arc<Discovery>,
@@ -91,7 +91,19 @@ impl AppState {
}
pub fn demo_damage_enabled(&self) -> bool {
self.match_view().phase == "running"
let phase = self.match_view().phase;
phase == "running"
|| (phase == "idle" && self.demo_reset_epoch.load(Ordering::Acquire) == 0)
}
/// 接收路径只更新核心终局并唤醒发送任务,不等待网络、UI 或写盘。
fn observe_match_health(&self) -> bool {
let health = [self.health_for(0), self.health_for(1)];
let hp = health.map(|entry| if entry.available { entry.hp } else { None });
self.match_clock
.lock()
.expect("match clock poisoned")
.finish_on_health(hp, self.match_now())
}
pub fn match_action(&self, action: MatchAction) -> Result<(), String> {
@@ -311,6 +323,7 @@ impl AppState {
match_clock: Mutex::new(MatchClock::new(role == Role::Referee, session, 0)),
match_socket,
match_error: Mutex::new(match_error),
match_changed: tokio::sync::Notify::new(),
resetting: AtomicBool::new(false),
demo_reset_epoch: AtomicUsize::new(0),
discovery,
@@ -351,6 +364,21 @@ impl AppState {
}
}
}));
let weak = Arc::downgrade(self);
self.armor
.set_match_result_sink(Arc::new(move |packet, ip| {
if let Some(state) = weak.upgrade() {
if !state.demo
&& state
.match_clock
.lock()
.expect("match clock poisoned")
.receive_result(packet, ip, state.match_now())
{
state.match_changed.notify_one();
}
}
}));
let video = self.video.clone();
let recordings = Arc::clone(&self.recordings);
@@ -363,9 +391,17 @@ impl AppState {
let tx = self.tx.clone();
let tracker = Arc::new(Mutex::new(HealthTracker::new()));
let weak = Arc::downgrade(self);
// 装甲板的 sink:把"现在多少血"派生为"刚刚掉了几点",立刻推给界面。
self.armor.set_sink(Arc::new(move |report| {
if report.hp == 0 {
if let Some(state) = weak.upgrade() {
if state.observe_match_health() {
state.match_changed.notify_one();
}
}
}
let hit = tracker
.lock()
.expect("health tracker mutex poisoned")
@@ -426,8 +462,10 @@ impl AppState {
let mut ticker = tokio::time::interval(SNAPSHOT_INTERVAL);
loop {
ticker.tick().await;
state_for_loop.tick();
tokio::select! {
_ = ticker.tick() => state_for_loop.tick(),
_ = state_for_loop.match_changed.notified() => state_for_loop.tick_match(),
}
state_for_loop.push_snapshot();
}
});
@@ -643,12 +681,12 @@ impl AppState {
/// 推进帧率窗口与槽位分配。
fn tick_match(&self) {
self.observe_match_health();
if !self.demo && self.config().role_chosen {
let packet = self
.match_clock
.lock()
.expect("match clock poisoned")
.broadcast(self.match_now());
let (packet, result) = {
let mut clock = self.match_clock.lock().expect("match clock poisoned");
(clock.broadcast(self.match_now()), clock.result_packet())
};
if let (Some(socket), Some(packet)) = (&self.match_socket, packet) {
if let Some(bytes) = packet.encode() {
let config = self.config();
@@ -667,9 +705,19 @@ impl AppState {
.send_damage_controls(socket, &packet, participants)
.err();
let reset_error = self.armor.send_reset_controls(socket, &packet).err();
let result_error =
result.and_then(|result| result.encode()).and_then(|bytes| {
socket
.send_to(
&bytes,
(std::net::Ipv4Addr::BROADCAST, protocol::ARMOR_PORT),
)
.err()
});
let error = sync_error
.or(damage_error)
.or(reset_error)
.or(result_error)
.map(|err| format!("比赛状态发送失败:{err}。请检查网络和防火墙"));
*self.match_error.lock().expect("match error poisoned") = error;
}
@@ -782,7 +830,10 @@ impl AppState {
let mut health = vec![self.health_for(0), self.health_for(1)];
// 胜负是**两边合起来**才能算出来的东西,所以在这里补一步。
resolve_outcomes(&mut health);
self.match_clock
.lock()
.expect("match clock poisoned")
.apply_outcomes(&mut health);
Snapshot {
match_clock: self.match_view(),
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RMIC-2026",
"version": "0.3.0",
"version": "0.4.0",
"identifier": "com.simbarobotics.rmic2026",
"build": {
"beforeDevCommand": "pnpm dev",
+3 -3
View File
@@ -15,10 +15,10 @@ interface Props {
}
export function HealthBar({ health, config, align, tag, asleep = false }: Props) {
// 脉动交给 CSS,减少动态效果时仍保留低血颜色,停止闪动。
// 脉动交给 CSS;减少动态效果时保留低血边框,队伍色始终不变。
const pulsing = config.pulse && health.available && health.critical;
const color = health.critical ? "var(--error)" : teamColor(health.team);
const color = teamColor(health.team);
const raw = health.available ? Math.max(0, Math.min(100, health.hp ?? 0)) : 0;
const showThreshold = config.lowThreshold > 0 && config.lowThreshold < 100;
@@ -31,7 +31,7 @@ export function HealthBar({ health, config, align, tag, asleep = false }: Props)
className={`hp hp--${align}${asleep ? " hp--asleep" : ""}${
pulsing ? " hp--pulsing" : ""
}${health.critical ? " hp--critical" : ""}`}
style={{ width }}
style={{ width, color }}
title={health.available ? undefined : health.placeholder}
>
<div className="hp__head">
+22 -2
View File
@@ -120,6 +120,7 @@ interface PreviewState {
recordings: { camera: number; frames: number; startedMs: number }[];
hp: [number, number];
matchControlled: boolean;
finalOutcomes: ["victory" | "defeat" | "draw" | null, "victory" | "defeat" | "draw" | null] | null;
}
const state: PreviewState = {
@@ -138,8 +139,22 @@ const state: PreviewState = {
recordings: [],
hp: [100, 100],
matchControlled: new URLSearchParams(location.search).has("match"),
finalOutcomes: null,
};
if (new URLSearchParams(location.search).get("match") === "finished") state.hp = [0, 76];
if (new URLSearchParams(location.search).get("match") === "finished") {
state.hp = [0, 76]; state.finalOutcomes = ["defeat", "victory"];
}
if (new URLSearchParams(location.search).get("health") === "blue-low") {
state.hp = [73, 10]; state.matchControlled = true;
}
function finishPreviewKnockout() {
const clock = previewMatch();
if (state.finalOutcomes || !state.matchControlled || (clock.phase !== "running" && !(clock.phase === "paused" && clock.resumePhase === "running")) || !state.hp.includes(0)) return;
state.finalOutcomes = state.hp[0] === 0 && state.hp[1] === 0 ? ["draw", "draw"]
: state.hp[0] === 0 ? ["defeat", "victory"] : ["victory", "defeat"];
previewMatchAction({ type: "end" });
}
// ---------------------------------------------------------------------------
// 假的命令实现
@@ -156,9 +171,10 @@ function handle(command: string, args: Record<string, unknown>): unknown {
case "match_action": {
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
const action = args.action as MatchAction;
if (action.type === "prepare" && state.finalOutcomes) throw new Error("请先重置本局");
previewMatchAction(action);
state.matchControlled = true;
if (action.type === "reset") state.hp = [100, 100];
if (action.type === "reset") { state.hp = [100, 100]; state.finalOutcomes = null; }
return;
}
case "release_match_source": return;
@@ -304,6 +320,7 @@ function hex(id: number): string {
}
function snapshot(): Snapshot {
finishPreviewKnockout();
const cameraOffline = videoOffline();
const cameras = [
{ id: CAMERA_A, team: 0 },
@@ -356,6 +373,8 @@ function snapshot(): Snapshot {
// 与后端 `cam_core::snapshot::resolve_outcomes` 同一套规则,包括那条不对称:
// 输只看自己,赢要看对手归零**且**自己还活着。
const outcomeFor = (team: number) => {
if (state.finalOutcomes) return state.finalOutcomes[team];
if (state.matchControlled && previewMatch().phase === "finished") return null;
const mine = state.hp[team];
const theirs = state.hp[team === 0 ? 1 : 0];
@@ -480,6 +499,7 @@ export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void)
const damage = 3 + ((tick * 7) % 20);
const to = Math.max(0, from - damage);
state.hp[team] = to;
finishPreviewKnockout();
emit({
t: "hit",
+4 -4
View File
@@ -6,16 +6,16 @@
*/
export const BUILD = {
version: "0.3.0",
version: "0.4.0",
major: 0,
minor: 3,
minor: 4,
patch: 0,
/** git 提交数,单调递增。 */
build: 42,
build: 44,
/** 线路协议版本。与固件自报的那个数直接比对。 */
protocol: 1,
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
date: "2026-10-24",
date: "2026-10-31",
} as const;
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
+1 -1
View File
@@ -387,7 +387,7 @@
}
.hp--critical .hp__track {
border-color: var(--error-line);
border-color: currentColor;
}
.hp--pulsing .hp__track {
+20 -2
View File
@@ -36,7 +36,7 @@ client/
暂停期间,原阶段与对局用时冻结。选手暂停满 5 分钟后显示到期,等待裁判手动恢复,也允许提前恢复。官方暂停显示已用时,不设自动恢复时限,因为规则页未规定其时长。恢复后继续暂停前的阶段,不重新计整局。提前结束会停止计时和装甲板扣血,胜负由裁判判定;计时不能控制机器人运动或代替判罚。
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息和最近命中流水,回到等待准备;胜负横幅随真实血量恢复而消失。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
一方血量归零显示胜负后,或本局计时结束后,控制条显示“重置到未开始”。点击一次会先停止本局计时和扣血,再向当前装甲板槽位定向发送复位请求。收到每块目标主板的回执及回执后的四路 100 血上报后,才清除本局计时、暂停信息、胜负结果和最近命中流水,回到等待准备。设备槽位、队伍名、画面及录制设置保留,已有录制文件不删除。重置后的等待准备状态会同步到选手端,血量仍来自装甲板的真实上报。
远程复位需要更新装甲板固件。请求最多等待 3 秒,未确认或未收到四路满血时保留结束状态,提示具体主板及检查步骤;部分主板成功复位时也不会报告整局重置成功。离线主板或两队误用同一块主板会报错。重置过程中禁止开赛和修改配置;没有分配装甲板时只重置计时。旧固件仍可长按 BOOT 复位血量,但不会确认远程请求,不能完成这项一键重置。
@@ -44,6 +44,8 @@ client/
正式裁判端会向当前比赛装甲板下发独立扣血许可:仅对局进行中允许扣血,准备、等待开赛、倒计时、暂停和结束均禁止。禁止时受击仍闪灯,血量不变。许可丢失 1 秒后停止扣血,恢复比赛不会补血。此功能必须更新装甲板固件;旧固件忽略许可消息。绑定、灯色和扣血许可的规则见[装甲板说明](../hardware/armor.md#规则)。
对局进行中首次确认任一方血量归零时,Rust 核心会锁定本局结论、结束计时,并唤醒发送任务向双方下发禁止扣血许可;接收线程不等待网络发送或界面消费。结论由裁判端持续广播给选手端,后续扣血、迟到报文、掉线或补血均不重新改判;只有成功重置本局才清除。血量仍显示主板实际读数,不伪造满血。若首次结算快照中双方都已归零则保留平局;结算后另一方才上报归零不会把原结果改成平局。缺少一方有效血量时不凭空宣布其获胜。禁止扣血仍受网络可达性与原有 1 秒租约约束,发布前需复测实际停止时间。裁判端与选手端均需更新客户端;已有支持扣血许可的 C3 固件可继续使用。
计时失联 1.5 秒后冻结,显示“计时同步中断”;同一裁判会话恢复时自动校正。裁判端重启或网卡地址改变后,按 ESC,在操作菜单中选择“重新接收裁判计时”。该操作会解除原会话锁定并接收下一份广播,因此操作前应确保局域网中只有一个正式裁判端。
计时不写入个人配置。裁判进程重启后从等待准备开始,需现场人工核对,不会自行恢复或判罚上一局。
@@ -203,6 +205,20 @@ icacls .\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\*-setup.exe
权限回归检查:打包下载过 NSIS 工具后,在 `client/` 执行 `./scripts/test-windows-bundle.ps1`。它在独立样例目录验证 Low 进程拒绝、文件标签修复及重复执行,并编译一个仅写临时文件后退出的 NSIS 程序;不安装应用。工具不在默认缓存时可传 `-NsisCompiler <makensis.exe 路径>`。
SmartScreen 的发布者与文件信誉和上述完整性标签是两套机制。未签名的软件、使用自签证书的软件以及信誉尚未建立的新签名包都可能出现提示;有效代码签名也不保证新包立即免提示,见[微软的 SmartScreen 开发者说明](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/smartscreen-reputation)。
正式 Windows 构建使用 `scripts/build-windows-release.ps1`,通过 Tauri 原生签名配置,对主程序及 NSIS 安装包使用 SHA-256 和 RFC 3161 时间戳,并检查签名状态、发布者指纹和时间戳。将公开信任 CA 签发的代码签名证书及可访问的私钥配置到构建用户的 `CurrentUser/My`,再在进程环境指定 `RMIC_WINDOWS_CERT_THUMBPRINT`;个人证书身份不会写进共享 Tauri 配置。没有证书时默认停止,需要明确传入 `-AllowUnsigned` 才生成文件名带 `unsigned` 的测试包,并在校验报告中标明 `signed=false`。这不解决 SmartScreen 信誉问题,也不改变系统防护设置。
```powershell
# 在 client/ 执行。已有证书时,将其指纹放入进程环境后运行。
.\scripts\build-windows-release.ps1
# 仅用于明确接受未签名限制的开发测试。
.\scripts\build-windows-release.ps1 -AllowUnsigned
.\scripts\test-windows-signing.ps1
```
交付文件与签名报告输出到根目录 `target/releases/v<版本>+<构建号>/`。CI 的 `WINDOWS_CODE_SIGNING_THUMBPRINT` 仓库变量引用 runner 用户证书库中的身份;`v*` 标签构建缺少证书时失败,其他构建可输出明确标注的未签名测试包。PR 构建只生成未签名测试包。签名 runner 应仅接受可信源码;私钥或证书密码不写入仓库、构建参数或报告。
NSIS 安装流程使用简体中文,包括欢迎、安装位置、安装完成、覆盖安装、卸载与 WebView2 错误提示。`src-tauri/installer/hooks.nsh` 定义页面提示和安装日志,`SimpChinese.nsh` 定义 Tauri 安装器的补充翻译;`tauri.windows.conf.json` 引用这些脚本和主题图片。沿用 Tauri 默认安装模板和当前用户安装方式;首次启动的模式选择与裁判系统绑定仍在客户端内完成。
现场裁判系统采用固定热点约定:SSID 为 `SR-602-2G4`,密码为 `12345678`。热点需提供 2.4 GHz Wi-Fi;运行客户端的电脑也应接入同一网络,并允许设备间互访。固定这组参数是为了便于现场连接和调试,安装完成页会直接显示它们。
@@ -345,6 +361,8 @@ Rust 侧的配置修改命令会调用 `AppState::require_unlocked`。即使从
血量归零后,血条保留数字 0 和空条,比赛结果由中央横幅显示。
低血量时保留队伍原色:红方保持红色、蓝方保持蓝色,队名、数字、填充和低血边框使用同一队伍色。低血提示通过边框与可配置的脉动体现;开启减少动态效果时停止动画,保留边框。
图传离线或本机视频通道断开时,保留的最后一帧会灰度化并叠加灰色遮罩,同时显示等待或重连原因;图传恢复后自动移除。遮罩仅作用于视频层,HUD 的队伍色、血量和状态仍保持可读;装甲板单独离线不会使正常图传变灰。
### 胜负横幅
@@ -352,7 +370,7 @@ Rust 侧的配置修改命令会调用 `AppState::require_unlocked`。即使从
一方血量归零后,图传中央显示结果:获胜方为“胜利”,落败方为“落败”,双方同时归零为“平局”。提示带上对手名字,便于在裁判端两路画面中判断胜负。
- 结果由 Rust 侧计算(`snapshot::resolve_outcomes`,有单测)。自己归零即可判负,即使对手掉线;判胜则要求对手归零且自己仍有血,避免在本队从未上报时误判获胜。
- 横幅持续显示到装甲板血量复位(长按 BOOT,或裁判端“重置到未开始”),供截图、回放和现场核对。单纯开始准备不会补血。
- 正式比赛的终局横幅由裁判端锁定并同步,持续显示到裁判端成功“重置到未开始”。单独长按 BOOT 补血不会清除本局结论,单纯开始准备也不会补血。
- 比赛结果放在画面中央;比赛中的命中反馈避开中央瞄准区域。
### 瞄准器
+2
View File
@@ -25,6 +25,8 @@ node scripts/version.mjs --print
构建号取 `git rev-list --count HEAD`。提交正文中,以 `- ` 开头且符合 `type(scope): 说明` 的行也会归为独立条目,可用于记录 squash 提交中的多项改动。历史发布按标签区间重新计算,不从上一次生成的文件续写。
发布基线以 `v<major>.<minor>.<patch>` 标签为准。同一未发布区间内即使有多次 `feat`,也只相对基线提升一次 minor;生成版本文件或增加构建号不表示已经建立新发布基线。完成一次正式版本交付后,应在对应源码提交上记录该语义版本标签;标签推送按发布安排执行。下一轮功能变更再从该标签计算,不能用反复更新构建号代替语义版本迭代。
## 派生文件
| 文件 | 用途 |
+18
View File
@@ -76,6 +76,7 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
| 7 `MatchState` | 裁判端 → 选手端 | 完整比赛计时快照,广播至 UDP 5601,5 Hz |
| 8 `ArmorDamageControl` | 裁判端 → 当前比赛装甲板 | 定向发送扣血许可,每 200 ms 续约 |
| 9 `ArmorReset` | 裁判端 ↔ 当前比赛装甲板 | 定向复位请求与回执 |
| 10 `MatchResult` | 裁判端 → 选手端 | 锁定的终局结论与结束计时,广播至 UDP 5601 |
### 比赛计时快照(类型 7)
@@ -102,6 +103,23 @@ cargo +stable test --locked --target x86_64-pc-windows-msvc --config 'unstable.b
选手端锁定首次收到的来源 IP 与 session;1500 ms 无新快照则冻结,重复包不续约。同一会话恢复后直接校正到最新快照,不补播错过的倒计时。其他来源与重启后的新会话需通过操作菜单“重新接收裁判计时”显式接入。会话锁定防止意外混用,不提供来源认证;现场同一局域网只运行一个正式裁判端。
### 终局快照(类型 10)
`MatchResult` 使用协议版本 1、27 字节共用头和 `sender_id=0`,其他头部业务字段置零,不改变类型 7 的布局。负载固定 34 字节,整包 61 字节:
| 负载偏移 | 字段 | 类型 / 取值 |
| --- | --- | --- |
| 0 | session | u64 LE,非零,与裁判计时会话相同 |
| 8 | sequence | u64 LE,本次完整快照的序号 |
| 16 | result_id | u64 LE,首次结算时的序号;重发不变,非零且不大于 sequence |
| 24 | remaining_ms | u32 LE,结束时的剩余毫秒,最多 180000 |
| 28 | elapsed_ms | u32 LE,结束时的对局用时,最多 180000 |
| 32 | outcomes | 两个 u8,分别对应队伍 0/1:0 未判定、1 胜、2 负、3 平局 |
有效结论组合仅为 `[1,2]`、`[2,1]`、`[2,0]`、`[0,2]` 或 `[3,3]`。缺少一队有效血量时只记录已知败方,不凭空判胜。首次归零会锁定结论并结束计时,裁判端立即唤醒发送任务下发双方禁止扣血许可,之后随每 200 ms 心跳重发终局快照。血量读数继续反映实际主板上报,但不能重算已锁定的胜负。
终局包自包含结束阶段及计时,可在类型 7 丢失或乱序时独立应用;同序号的计时与终局包以完整终局结论合并,重复包不延长租约。来源 IP、session 和序号沿用计时会话规则,同一 result_id 的结论与结束时间不得变更。成功重置后,新的空闲计时序号会使旧终局包失效;新一局使用递增的 result_id。旧选手客户端忽略类型 10,需与裁判端一起更新。装甲板扣血许可格式不变,已有支持类型 8 的 C3 固件无需为此更新。
### 四个设计决定
头长保留为 27 字节,不额外补齐。它只占每个 1427 字节数据报的 1.9%;为对齐而在固件和客户端分别维护手写偏移常量,反而更容易引入不易察觉的错位。
+7 -190
View File
@@ -1,195 +1,12 @@
{
"version": "0.3.0",
"version": "0.4.0",
"major": 0,
"minor": 3,
"minor": 4,
"patch": 0,
"build": 42,
"build": 44,
"protocol": 1,
"date": "2026-10-24",
"baseline": "v0.2.1",
"commits": 7,
"groups": {
"feat": [
{
"scope": "client",
"text": "改进启动窗口、维护交互与操作图标",
"breaking": false
},
{
"scope": "client",
"text": "增加无边框动画启动窗口,加载完成后恢复主窗口",
"breaking": false
},
{
"scope": "ui",
"text": "为操作按钮引入本地 Material Symbols Rounded 图标",
"breaking": false
},
{
"scope": "match",
"text": "同步比赛计时与装甲板扣血许可",
"breaking": false
},
{
"scope": "client",
"text": "增加裁判比赛计时、技术暂停与选手端局域网同步",
"breaking": false
},
{
"scope": "armor",
"text": "红蓝共用通用固件,按客户端选队并显示网络连接状态",
"breaking": false
},
{
"scope": "armor",
"text": "仅在对局进行中允许扣血,其他阶段保留受击闪烁",
"breaking": false
},
{
"scope": "client",
"text": "将计时置于血条中间并增加开赛前五秒全屏动画",
"breaking": false
}
],
"fix": [
{
"scope": "maintenance",
"text": "移除烧录前无效的原生确认框,保留页面检查与后端校验",
"breaking": false
},
{
"scope": "maintenance",
"text": "统一板卡示意风格并修正装甲板比例和图传右侧 USB 接线",
"breaking": false
},
{
"scope": "client",
"text": "修复连续血条、对手镜像和图传断连灰度遮罩",
"breaking": false
},
{
"scope": "client",
"text": "统一界面中文字体并整理各页面文案",
"breaking": false
},
{
"scope": "maintenance",
"text": "备份迁移装甲板分区,恢复 SDK 构建与固件打包",
"breaking": false
},
{
"scope": "installer",
"text": "保留现场固定热点约定并说明连接要求",
"breaking": false
},
{
"scope": "installer",
"text": "使用共享热点默认值,并修正本地覆盖配置的包含路径",
"breaking": false
},
{
"scope": "packaging",
"text": "修复 Windows 安装与固件打包并完善客户端文案",
"breaking": false
},
{
"scope": "installer",
"text": "修复低完整性产物无法写入临时目录的问题,并在 CI 打包前后检查完整性标签",
"breaking": false
},
{
"scope": "firmware",
"text": "从本次 Cargo ELF 打包并同步配套镜像,修正短目录说明与 LLVM 搜索顺序",
"breaking": false
},
{
"scope": "installer",
"text": "修复中文完成页和页眉遮挡,侧栏使用等比缩放的原始 Logo",
"breaking": false
},
{
"scope": "config",
"text": "安装提示改用可选本地热点配置,排除 Wi-Fi 凭据",
"breaking": false
},
{
"scope": "client",
"text": "统一状态与操作文案,录制和截图成功后再显示完成提示",
"breaking": false
}
],
"refactor": [
{
"scope": "repo",
"text": "按 armor、vt 和 client 整理工程与脚本,移除旧参考实现",
"breaking": false
}
],
"docs": [
{
"scope": null,
"text": "按 humanizer-zh 润色项目文档并将写作约定纳入 AGENTS.md",
"breaking": false
},
{
"scope": null,
"text": "同步构建、协议、比赛控制和硬件验证边界",
"breaking": false
},
{
"scope": "network",
"text": "明确设备按固件中的固定热点参数连接,客户端电脑需接入同一网络,更换热点后需重新编译烧录",
"breaking": false
},
{
"scope": "agents",
"text": "区分现场统一热点约定与个人 Wi-Fi 配置,保留前者及对应安装说明",
"breaking": false
},
{
"scope": null,
"text": "润色项目说明并统一裁判系统术语",
"breaking": false
},
{
"scope": null,
"text": "整理项目文档并统一界面表述",
"breaking": false
},
{
"scope": null,
"text": "README 不写死构建号,改由 version.json 提供",
"breaking": false
},
{
"scope": null,
"text": "按 humanizer 重写项目文档并同步 RMIC::2026 现状",
"breaking": false
}
],
"test": [
{
"scope": null,
"text": "补充线路、受击许可、回环 UDP、维护和 HUD 验证",
"breaking": false
},
{
"scope": "packaging",
"text": "补充 Windows 完整性和固件打包回归,覆盖外部输出目录、旧镜像与重复生成",
"breaking": false
},
{
"scope": "client",
"text": "按文件名核对媒体类型,避免依赖时间戳排序",
"breaking": false
}
],
"style": [
{
"scope": "client",
"text": "应用图标增加圆角,统一“裁判系统客户端”命名",
"breaking": false
}
]
}
"date": "2026-10-31",
"baseline": "v0.4.0",
"commits": 0,
"groups": {}
}
+23 -1
View File
@@ -4,9 +4,31 @@
> 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。
> 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。
## v0.4.0 — 2026-10-31
2 个提交
### 新增
- **client** · 锁定终局结果并接入 Windows 签名构建
- **match** · 添加画面上下镜像、跳过准备和装甲板整局复位
### 修复
- **match** · 首次归零结束对局并撤销双方扣血许可,裁判结果同步后不再改判
- **hud** · 蓝方低血量始终保留队伍颜色
### 构建
- **windows** · 校验代码签名身份和时间戳,明确标注未签名测试包
### 文档
- **version** · 说明发布标签基线与语义版本迭代
## v0.3.0 — 2026-10-24
构建号 **42** · 线路协议 **1** · 7 个提交(v0.2.1 → v0.3.0)
7 个提交
### 新增
+5 -5
View File
@@ -1,11 +1,11 @@
{
"version": "0.3.0",
"version": "0.4.0",
"major": 0,
"minor": 3,
"minor": 4,
"patch": 0,
"build": 42,
"build": 44,
"protocol": 1,
"date": "2026-10-24",
"baseline": "v0.2.1",
"date": "2026-10-31",
"baseline": "v0.4.0",
"note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。"
}
+5
View File
@@ -50,6 +50,8 @@ use std::net::{Ipv4Addr, SocketAddrV4};
mod match_state;
pub use match_state::MatchState;
mod match_result;
pub use match_result::MatchResult;
mod armor_damage;
pub use armor_damage::ArmorDamageControl;
mod armor_reset;
@@ -128,6 +130,8 @@ pub enum MsgType {
ArmorDamageControl = 8,
/// 裁判定向复位装甲板及板端回执。
ArmorReset = 9,
/// 裁判广播的锁定胜负及结束计时,自包含快照(5601)。
MatchResult = 10,
}
impl MsgType {
@@ -143,6 +147,7 @@ impl MsgType {
7 => MsgType::MatchState,
8 => MsgType::ArmorDamageControl,
9 => MsgType::ArmorReset,
10 => MsgType::MatchResult,
_ => return None,
})
}
+129
View File
@@ -0,0 +1,129 @@
use crate::{decode_header, encode_header_into, Header, MsgType, HEADER_LEN, PROTOCOL_VERSION};
/// 自包含的裁判终局快照。独立消息保持原计时和装甲板许可格式兼容。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MatchResult {
pub session: u64,
pub sequence: u64,
/// 首次结算时的序号;重发时不变,下一局严格递增。
pub result_id: u64,
pub remaining_ms: u32,
pub elapsed_ms: u32,
/// 队伍 0/1:0 未判定、1 胜、2 负、3 平局。
pub outcomes: [u8; 2],
}
impl MatchResult {
pub fn valid(&self) -> bool {
self.session != 0
&& self.result_id != 0
&& self.result_id <= self.sequence
&& self.remaining_ms <= 180_000
&& self.elapsed_ms <= 180_000
&& matches!(self.outcomes, [1, 2] | [2, 1] | [2, 0] | [0, 2] | [3, 3])
}
pub fn encode(&self) -> Option<Vec<u8>> {
if !self.valid() {
return None;
}
let mut out = Vec::with_capacity(HEADER_LEN + 34);
encode_header_into(
&Header {
msg_type: MsgType::MatchResult,
version: PROTOCOL_VERSION,
..Default::default()
},
&mut out,
);
out.extend(self.session.to_le_bytes());
out.extend(self.sequence.to_le_bytes());
out.extend(self.result_id.to_le_bytes());
out.extend(self.remaining_ms.to_le_bytes());
out.extend(self.elapsed_ms.to_le_bytes());
out.extend(self.outcomes);
Some(out)
}
pub fn decode(bytes: &[u8]) -> Option<Self> {
let header = decode_header(bytes)?;
if header.msg_type != MsgType::MatchResult
|| header.sender_id != 0
|| bytes.len() != HEADER_LEN + 34
{
return None;
}
let p = &bytes[HEADER_LEN..];
let result = Self {
session: u64::from_le_bytes(p[0..8].try_into().ok()?),
sequence: u64::from_le_bytes(p[8..16].try_into().ok()?),
result_id: u64::from_le_bytes(p[16..24].try_into().ok()?),
remaining_ms: u32::from_le_bytes(p[24..28].try_into().ok()?),
elapsed_ms: u32::from_le_bytes(p[28..32].try_into().ok()?),
outcomes: p[32..34].try_into().ok()?,
};
result.valid().then_some(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_result_roundtrip_rejects_bad_identity_length_and_conclusions() {
let result = MatchResult {
session: 9,
sequence: 20,
result_id: 18,
remaining_ms: 100_000,
elapsed_ms: 80_000,
outcomes: [2, 1],
};
let bytes = result.encode().unwrap();
assert_eq!(bytes.len(), 61);
let hex = bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
assert_eq!(
hex,
concat!(
"3143564d0a0100",
"0000000000000000000000000000000000000000",
"0900000000000000",
"1400000000000000",
"1200000000000000",
"a0860100",
"80380100",
"0201"
)
);
assert_eq!(MatchResult::decode(&bytes), Some(result));
assert!(crate::MatchState::decode(&bytes).is_none());
assert!(crate::ArmorHealth::decode_from(&bytes).is_none());
for n in 0..bytes.len() {
assert!(MatchResult::decode(&bytes[..n]).is_none());
}
let mut extra = bytes.clone();
extra.push(0);
assert!(MatchResult::decode(&extra).is_none());
for (offset, value) in [(4, 7), (5, 99), (7, 1), (HEADER_LEN + 33, 4)] {
let mut bad = bytes.clone();
bad[offset] = value;
assert!(MatchResult::decode(&bad).is_none());
}
for outcomes in [[1, 1], [0, 1], [2, 2], [3, 0], [0, 0]] {
assert!(MatchResult { outcomes, ..result }.encode().is_none());
}
assert!(MatchResult {
result_id: 21,
..result
}
.encode()
.is_none());
assert!(MatchResult {
elapsed_ms: 180_001,
..result
}
.encode()
.is_none());
}
}
+2
View File
@@ -38,6 +38,7 @@ MSG_ARMOR_CONTROL = 6
MSG_MATCH_STATE = 7
MSG_ARMOR_DAMAGE_CONTROL = 8
MSG_ARMOR_RESET = 9
MSG_MATCH_RESULT = 10
TYPE_NAMES = {
MSG_VIDEO: "video",
@@ -49,6 +50,7 @@ TYPE_NAMES = {
MSG_MATCH_STATE: "match-state",
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
MSG_ARMOR_RESET: "armor-reset",
MSG_MATCH_RESULT: "match-result",
}