feat: CS 枪火对决 —— Rust 权威服务端 + 手写 WebGL 前端的第一人称 1v1 对枪

- 服务端 60Hz 固定步长模拟:重力/摩擦/轴分离碰撞/上台阶,客户端预测回滚
- 命中裁决:射线打墙打人(身体 + 头部盒),射速/弹匣/换弹/伤害/比分全在服务端
- 回合制:3 秒准备、先到 8 分、100 秒平局;观战自由视角
- 机器人陪练:视线检测 + 反应延迟 + 点射偏差,能单人开练
- 前端零依赖:手写 WebGL(程序化贴图、地图合批、粒子、曳光弹、假投影、黄昏天空)
- 2D Canvas 枪模 + WebAudio 合成音效,无任何图片/音频/CDN 资源
- 地图 level.json 前后端同源,tools/gen_level.py 四分镜像生成,绝对对称
- 测试:14 组规则单测 + 6 组联机 e2e
This commit is contained in:
rong committed 2026-10-22 21:53:45 +08:00
commit 00d63ba736
32 files changed
+8599

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
//! 联机端到端:两个浏览器(这里是两个 WebSocket 客户端)从建房到开打。
//!
//! 运行:cargo test --test e2e
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
use cs::server::{self, App};
type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
async fn start() -> String {
let app = App::new();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = server::serve(listener, app).await;
});
format!("127.0.0.1:{}", addr.port())
}
struct Client {
ws: Ws,
}
impl Client {
async fn connect(addr: &str) -> Client {
let (ws, _) = connect_async(format!("ws://{addr}/ws")).await.expect("连接失败");
Client { ws }
}
async fn send(&mut self, v: Value) {
self.ws
.send(Message::Text(v.to_string().into()))
.await
.expect("发送失败");
}
/// 收下一条 JSON(跳过 ping/pong/binary)
async fn recv(&mut self) -> Option<Value> {
loop {
let msg = tokio::time::timeout(Duration::from_secs(8), self.ws.next())
.await
.ok()??;
match msg.ok()? {
Message::Text(t) => return serde_json::from_str(t.as_str()).ok(),
Message::Close(_) => return None,
_ => continue,
}
}
}
async fn wait_for(&mut self, kind: &str, within: Duration) -> Value {
let deadline = tokio::time::Instant::now() + within;
loop {
let left = deadline.saturating_duration_since(tokio::time::Instant::now());
if left.is_zero() {
panic!("等 {kind} 超时");
}
let msg = match tokio::time::timeout(left, self.recv()).await {
Ok(Some(m)) => m,
_ => panic!("等 {kind} 超时"),
};
if msg["t"] == kind {
return msg;
}
}
}
/// 等某个条件的快照
async fn wait_snap(&mut self, pred: impl Fn(&Value) -> bool, within: Duration) -> Value {
let deadline = tokio::time::Instant::now() + within;
loop {
let left = deadline.saturating_duration_since(tokio::time::Instant::now());
if left.is_zero() {
panic!("等快照条件超时");
}
let msg = match tokio::time::timeout(left, self.recv()).await {
Ok(Some(m)) => m,
_ => panic!("等快照条件超时"),
};
if msg["t"] == "snap" && pred(&msg) {
return msg;
}
}
}
async fn input(&mut self, seq: u32, keys: u8, yaw: f32) {
self.send(json!({
"t": "input", "seq": seq, "keys": keys,
"yaw": yaw, "pitch": 0.0, "fire": false, "reload": false, "weapon": 0
}))
.await;
}
}
fn pos_of(snap: &Value, slot: u64) -> Option<[f64; 3]> {
let p = snap["players"]
.as_array()?
.iter()
.find(|p| p["slot"] == slot)?;
let a = p["pos"].as_array()?;
Some([a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?])
}
#[tokio::test]
async fn 建房加入然后开打() {
let addr = start().await;
let mut a = Client::connect(&addr).await;
a.send(json!({ "t": "create" })).await;
let welcome = a.wait_for("welcome", Duration::from_secs(3)).await;
let code = welcome["code"].as_str().unwrap().to_string();
assert_eq!(welcome["you"], 0);
assert_eq!(welcome["code"].as_str().unwrap().len(), 4);
let mut b = Client::connect(&addr).await;
b.send(json!({ "t": "join", "code": code.to_lowercase() })).await;
let wb = b.wait_for("welcome", Duration::from_secs(3)).await;
assert_eq!(wb["you"], 1, "第二个进来的人应该坐 1 号位");
// 双方都能看到两个玩家
for c in [&mut a, &mut b] {
let snap = c
.wait_snap(|s| s["players"].as_array().map(|p| p.len()).unwrap_or(0) == 2, Duration::from_secs(3))
.await;
assert_eq!(snap["score"], json!([0, 0]));
}
// 冻结 3 秒后开打
let live = a
.wait_snap(|s| s["phase"] == "live", Duration::from_secs(6))
.await;
assert_eq!(live["phase"], "live");
assert!(live["leftMs"].as_u64().unwrap() > 90_000);
// 一直按住 W:位置应该真的变了
let start_pos = pos_of(&live, 0).unwrap();
let yaw = live["players"][0]["yaw"].as_f64().unwrap();
for i in 0..50u32 {
a.input(i, 1, yaw as f32).await;
tokio::time::sleep(Duration::from_millis(16)).await;
}
let moved = a
.wait_snap(
|s| {
pos_of(s, 0)
.map(|p| {
let dx = p[0] - start_pos[0];
let dz = p[2] - start_pos[2];
(dx * dx + dz * dz).sqrt() > 0.8
})
.unwrap_or(false)
},
Duration::from_secs(3),
)
.await;
let p = pos_of(&moved, 0).unwrap();
assert!(p[2] != start_pos[2] || p[0] != start_pos[0]);
}
#[tokio::test]
async fn 观战者能看不能打() {
let addr = start().await;
let mut a = Client::connect(&addr).await;
a.send(json!({ "t": "create" })).await;
let code = a.wait_for("welcome", Duration::from_secs(3)).await["code"]
.as_str()
.unwrap()
.to_string();
let mut spec = Client::connect(&addr).await;
spec.send(json!({ "t": "join", "code": code, "spectate": true }))
.await;
let w = spec.wait_for("welcome", Duration::from_secs(3)).await;
assert_eq!(w["you"], Value::Null);
assert_eq!(w["spectating"], true);
let snap = spec
.wait_snap(|s| s["spectators"].as_u64().unwrap_or(0) >= 1, Duration::from_secs(4))
.await;
assert_eq!(snap["spectators"], 1);
// 观战者发 input 不应影响任何玩家
spec.input(1, 1, 0.0).await;
tokio::time::sleep(Duration::from_millis(200)).await;
let snap2 = spec.wait_for("snap", Duration::from_secs(3)).await;
assert_eq!(snap2["players"].as_array().unwrap().len(), 1);
}
#[tokio::test]
async fn 机器人会出家门() {
let addr = start().await;
let mut a = Client::connect(&addr).await;
a.send(json!({ "t": "create" })).await;
a.wait_for("welcome", Duration::from_secs(3)).await;
a.send(json!({ "t": "addBot" })).await;
let snap = a
.wait_snap(|s| s["players"].as_array().map(|p| p.len()).unwrap_or(0) == 2, Duration::from_secs(3))
.await;
let bot = snap["players"]
.as_array()
.unwrap()
.iter()
.find(|p| p["bot"] == true)
.expect("应该有机器人");
assert_eq!(bot["slot"], 1);
a.wait_snap(|s| s["phase"] == "live", Duration::from_secs(6))
.await;
let start = pos_of(&snap, 1).unwrap();
let later = a
.wait_snap(
|s| {
pos_of(s, 1)
.map(|p| {
let dx = p[0] - start[0];
let dz = p[2] - start[2];
(dx * dx + dz * dz).sqrt() > 3.0
})
.unwrap_or(false)
},
Duration::from_secs(12),
)
.await;
let p = pos_of(&later, 1).unwrap();
assert!((p[0] - start[0]).abs() + (p[2] - start[2]).abs() > 3.0);
}
#[tokio::test]
async fn 狂发输入不会瞬移() {
let addr = start().await;
let mut a = Client::connect(&addr).await;
a.send(json!({ "t": "create" })).await;
a.wait_for("welcome", Duration::from_secs(3)).await;
a.send(json!({ "t": "addBot" })).await;
let live = a
.wait_snap(|s| s["phase"] == "live", Duration::from_secs(6))
.await;
let start = pos_of(&live, 0).unwrap();
let yaw = live["players"][0]["yaw"].as_f64().unwrap();
// 一口气灌 200 帧前进
for i in 0..200u32 {
a.input(i, 1, yaw as f32).await;
}
tokio::time::sleep(Duration::from_millis(400)).await;
let snap = a.wait_for("snap", Duration::from_secs(3)).await;
let p = pos_of(&snap, 0).unwrap();
let dist = ((p[0] - start[0]).powi(2) + (p[2] - start[2]).powi(2)).sqrt();
assert!(dist < 3.0, "400ms 跑了 {dist} 米,明显不对劲");
}
#[tokio::test]
async fn 未知房号会报错() {
let addr = start().await;
let mut a = Client::connect(&addr).await;
a.send(json!({ "t": "join", "code": "ZZZZ" })).await;
let msg = a.wait_for("err", Duration::from_secs(3)).await;
assert!(msg["msg"].as_str().unwrap().contains("房间不存在"));
}
/* ------------------------------- HTTP 部分 ------------------------------- */
async fn http_get(addr: &str, path: &str) -> (u16, String, String) {
let mut stream = TcpStream::connect(addr).await.unwrap();
let req = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
stream.write_all(req.as_bytes()).await.unwrap();
let mut buf = Vec::new();
stream.read_to_end(&mut buf).await.unwrap();
let text = String::from_utf8_lossy(&buf).to_string();
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
let status = head
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.and_then(|s| s.parse().ok())
.unwrap_or(0);
(status, head.to_lowercase(), body.to_string())
}
#[tokio::test]
async fn 静态资源与健康检查都在() {
let addr = start().await;
let (status, head, body) = http_get(&addr, "/health").await;
assert_eq!(status, 200);
assert!(head.contains("application/json"));
let v: Value = serde_json::from_str(&body).unwrap();
assert_eq!(v["ok"], true);
assert_eq!(v["engine"], "rust");
assert_eq!(v["tick"], 60);
assert_eq!(v["snapshot"], 30);
let (status, head, body) = http_get(&addr, "/").await;
assert_eq!(status, 200);
assert!(head.contains("text/html"));
assert!(body.contains("枪火对决"));
let (status, head, body) = http_get(&addr, "/level.json").await;
assert_eq!(status, 200);
assert!(head.contains("application/json"));
let level: Value = serde_json::from_str(&body).unwrap();
assert!(level["boxes"].as_array().unwrap().len() > 40);
assert_eq!(level["spawns"].as_array().unwrap().len(), 2);
// 地图数据前后端同源,服务端启动时会解析它
let lv = cs::level::Level::embedded();
assert!(lv.blocks.len() > 40);
let (status, head, _) = http_get(&addr, "/js/client/renderer.js").await;
assert_eq!(status, 200);
assert!(head.contains("javascript"));
let (status, _, _) = http_get(&addr, "/nope.js").await;
assert_eq!(status, 200, "未知路径回退到首页");
}