Sans-IO deterministic rollback netcode for MoonBit: input ring buffer, prediction, rollback re-simulation, state checksums, Q16.16 fixed-point math.
Sans-IO deterministic rollback netcode for MoonBit.
///|
pub(open) trait Sim {
fn save(Self) -> Bytes // 编码完整状态
fn restore(Self, Bytes) -> Unit // 与 save 严格互逆
fn step(Self, UInt64, UInt64) // 推进一帧,p0 / p1 是双方输入位图
fn hash(Self) -> UInt64 // 状态哈希,不一致即 desync
}moon add weopqrst/moonroll// 1) 实现 Sim(略去 save/restore/hash)
impl @session.Sim for World with fn step(self, p0, p1) {
self.x = self.x * 31UL + p0 + (p1 << 32)
}
// 2) 每个对等体一个会话,local_id 是本地玩家(0 / 1)
let peer = @session.Session::with_window(world, 0, 128)
// 3) 每帧推进;收到对端输入时自动回滚重放
ignore(peer.advance(my_input))
peer.receive(remote_frame, opponent_input)
// 4) 双方定期比对
if peer.hash() != remote_hash {
// desync
}let a = @fixed.Fixed::from_double(1.5)
let b = @fixed.Fixed::from_double(2.25)
let c = a * b
let d = @digest.Digest::new()
d.feed_bytes(b"state")
let checksum = d.finish()
let ring = @input.InputRing::new(64)
ring.set(frame, 0b101UL)| 帧 | 布局 |
|---|---|
| Input | [0x01][varint frame][varint count][varint bits] × count |
| Confirm | [0x02][varint frame] |
| Checksum | [0x03][varint frame][8 bytes hash] |
let wire = @protocol.encode(@protocol.Message::Input(
@protocol.InputFrame::new(42, [0b101UL]),
))
let msg = @protocol.decode(wire) // Some(Input(...))
// 一条链路每帧只发一个包时,把多个帧塞进同一个包
let batch = @protocol.encode_batch(msgs)
for m in @protocol.decode_batch(batch) { /* ... */ }let net = @sim_net.NetSim::new(
@sim_net.Link::new(delay, jitter, loss_pct, reorder_pct, seed),
)
net.send(frame, payload) // 可能被丢弃
for packet in net.recv(frame) { /* ... */ } // 到达的包,按到达时间排序
net.delivered() // 已交付包数
net.dropped() // 丢弃包数
net.in_flight() // 在途包数| 场景 | 耗时(均值) |
|---|---|
| 每帧预测 + 深度 16 回滚重放 | 0.51 µs |
| 每帧预测 + 深度 128 回滚重放 | 14.4 µs |
| 包 | 内容 | 状态 |
|---|---|---|
| weopqrst/moonroll/fixed | Q16.16 定点数(+ - * /、开方、lerp、clamp) | V0.1 |
| weopqrst/moonroll/digest | FNV-1a 64 状态哈希 | V0.1 |
| weopqrst/moonroll/input | 帧号 -> 输入位图的环形缓冲 | V0.1 |
| weopqrst/moonroll/session | Sim 协议 + 预测 / 确认 / 回滚重放 | V0.2 |
| weopqrst/moonroll/protocol | 输入帧、确认帧、校验和帧的字节编解码 | V0.3 |
| weopqrst/moonroll/sim_net | 延迟 / 抖动 / 丢包 / 乱序模拟器 | V0.3 |
moon test --target wasm-gc
moon test --target js
moon run cmd/main --target wasm-gcInput : [0x01][varint frame][varint count][varint bits] * count
Confirm : [0x02][varint frame]
Checksum : [0x03][varint frame][8 bytes hash]Install
Download zipSans-IO deterministic rollback netcode for MoonBit: input ring buffer, prediction, rollback re-simulation, state checksums, Q16.16 fixed-point math.