code wiki / _hdl_build / nx_lockstep.nx

nx_lockstep.nx source

↩ module page · 32 lines · 1486 B

1// nx_lockstep.nx -- N-R2: sovereign DETERMINISTIC LOCKSTEP core (P2 networking, the RTS netcode model). 2// Lockstep = every client runs the SAME deterministic simulation on the SAME inputs, so only inputs cross 3// the wire (tiny bandwidth) and all clients stay byte-identical. ls_update is a pure-integer deterministic 4// step; ls_checksum hashes world state so a DESYNC (any divergence) is detectable by comparing checksums. 5// Pure integer logic -> reproducible by construction. 100% sovereign. license_tier: ORIGINAL 6 7// advance the world one tick from a single shared input. Deterministic: same (state,input) -> same state. 8func ls_update(state: *i64, k: i64, input: i64) -> i64 { 9 var i: i64 = 0 10 while i < k { 11 state[2*i] = state[2*i] + (((input + i) % 3) - 1) 12 state[2*i + 1] = state[2*i + 1] + (((input * (i + 1)) % 3) - 1) 13 i = i + 1 14 } 15 return 0 16} 17 18// deterministic checksum of world state (polynomial rolling hash; i64 wraps). Different state -> (almost 19// always) different checksum -> the desync detector. 20func ls_checksum(state: *i64, n: i64) -> i64 { 21 var h: i64 = 0 22 var i: i64 = 0 23 while i < n { h = h * 131 + state[i]; i = i + 1 } 24 return h 25} 26 27// run nticks of the shared input stream; returns the final state checksum. 28func ls_run(state: *i64, k: i64, inputs: *i64, nticks: i64) -> i64 { 29 var t: i64 = 0 30 while t < nticks { ls_update(state, k, inputs[t]); t = t + 1 } 31 return ls_checksum(state, 2 * k) 32}