From 27e08db51d5eb55cc43ab3d4e35f553569162c46 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 17:16:03 -0500 Subject: [PATCH] F5: Simulation core and player command stream Add the fixed-tick Simulation, the EntityRegistry with never-reused IDs, SimRng's named seeded streams, and the 14-byte PlayerCommand used by humans, bots and the network. state_hash is a SHA-256 over a canonical encoding of the state. Movement is a flat placeholder until the v0.2 character controller. Tests replay a 24-player command log over 10,000 ticks and scan src/sim for unseeded randomness and presentation code. Closes #5 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 11 +- src/sim/entity_registry.gd | 47 +++++++++ src/sim/entity_registry.gd.uid | 1 + src/sim/player_command.gd | 99 +++++++++++++++++ src/sim/player_command.gd.uid | 1 + src/sim/sim_entity.gd | 18 ++++ src/sim/sim_entity.gd.uid | 1 + src/sim/sim_rng.gd | 46 ++++++++ src/sim/sim_rng.gd.uid | 1 + src/sim/simulation.gd | 112 ++++++++++++++++++++ src/sim/simulation.gd.uid | 1 + src/sim/tuning.gd | 4 + test/project/test_sim_isolation.gd | 51 +++++++-- test/sim/test_entity_registry.gd | 37 +++++++ test/sim/test_entity_registry.gd.uid | 1 + test/sim/test_player_command.gd | 74 +++++++++++++ test/sim/test_player_command.gd.uid | 1 + test/sim/test_sim_rng.gd | 35 ++++++ test/sim/test_sim_rng.gd.uid | 1 + test/sim/test_simulation.gd | 152 +++++++++++++++++++++++++++ test/sim/test_simulation.gd.uid | 1 + 21 files changed, 686 insertions(+), 9 deletions(-) create mode 100644 src/sim/entity_registry.gd create mode 100644 src/sim/entity_registry.gd.uid create mode 100644 src/sim/player_command.gd create mode 100644 src/sim/player_command.gd.uid create mode 100644 src/sim/sim_entity.gd create mode 100644 src/sim/sim_entity.gd.uid create mode 100644 src/sim/sim_rng.gd create mode 100644 src/sim/sim_rng.gd.uid create mode 100644 src/sim/simulation.gd create mode 100644 src/sim/simulation.gd.uid create mode 100644 test/sim/test_entity_registry.gd create mode 100644 test/sim/test_entity_registry.gd.uid create mode 100644 test/sim/test_player_command.gd create mode 100644 test/sim/test_player_command.gd.uid create mode 100644 test/sim/test_sim_rng.gd create mode 100644 test/sim/test_sim_rng.gd.uid create mode 100644 test/sim/test_simulation.gd create mode 100644 test/sim/test_simulation.gd.uid diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 59b283f..124d928 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -55,7 +55,10 @@ Clients stamp commands for the tick they predict, and each packet repeats recent commands to survive loss. The server applies the command for each tick, or a neutral command with the player's last look direction if none has arrived. -The binary encoding is a fixed 15 bytes per command. See `src/sim/player_command.gd`. +The binary encoding is a fixed 14 bytes per command, little-endian, in the order of +the table above. See `src/sim/player_command.gd`. Decoding a truncated buffer returns +nothing, and out-of-range values are clamped, so bad input can't reach the simulation. +The player a command belongs to comes from its connection, never from the packet. ## Entity IDs @@ -68,13 +71,17 @@ deterministic. - A match has one `u64` seed, always logged. - Gameplay randomness comes only from named streams, created from the match seed and a - stable name: `SimRng.stream("loot")`, `"weapons"`, `"bots"`, `"worldgen"`, and so on. + stable name: `rng.stream("loot")`, `"weapons"`, `"bots"`, `"worldgen"`, and so on, on one `SimRng`. One system's extra rolls can't disturb another's. - Simulation code **never** calls `randf`, `randi`, `Time`, or anything else that varies between runs. Presentation can use whatever randomness it likes, for effects. - The same seed and the same command log produce the same state hash, on the same engine build. Worldgen runs on both ends from the same seed, so the terrain itself is never sent. +`Simulation.state_hash()` is a SHA-256 over a canonical encoding of the tick, the next +entity ID, every RNG stream's state and every entity in ID order, with positions rounded +to millimetres. + Determinism is for tests, replays and worldgen. Clients don't rely on bit-exact matches with the server. Reconciliation corrects any difference. diff --git a/src/sim/entity_registry.gd b/src/sim/entity_registry.gd new file mode 100644 index 0000000..4d8a240 --- /dev/null +++ b/src/sim/entity_registry.gd @@ -0,0 +1,47 @@ +## Owns every entity. IDs count up from 1 and are never reused within a match, and +## iteration is always in ascending ID order. +class_name EntityRegistry +extends RefCounted + +## Reserved: no entity has this ID. +const NONE: int = 0 + +var _next_id: int = 1 +var _by_id: Dictionary = {} + + +func create(archetype: int) -> SimEntity: + var entity: SimEntity = SimEntity.new(_next_id, archetype) + _next_id += 1 + # Dictionaries keep insertion order, and IDs only grow, so this stays sorted. + _by_id[entity.id] = entity + return entity + + +## Returns the entity, or null if it doesn't exist or has been removed. +func find(id: int) -> SimEntity: + return _by_id.get(id) + + +func remove(id: int) -> bool: + return _by_id.erase(id) + + +func contains(id: int) -> bool: + return _by_id.has(id) + + +func count() -> int: + return _by_id.size() + + +func next_id() -> int: + return _next_id + + +## All entities in ascending ID order. Safe to modify the registry while looping over this. +func entities() -> Array[SimEntity]: + var all: Array[SimEntity] = [] + for entity: SimEntity in _by_id.values(): + all.append(entity) + return all diff --git a/src/sim/entity_registry.gd.uid b/src/sim/entity_registry.gd.uid new file mode 100644 index 0000000..d8308ca --- /dev/null +++ b/src/sim/entity_registry.gd.uid @@ -0,0 +1 @@ +uid://b5d0n6yjh2qqd diff --git a/src/sim/player_command.gd b/src/sim/player_command.gd new file mode 100644 index 0000000..6b2cd27 --- /dev/null +++ b/src/sim/player_command.gd @@ -0,0 +1,99 @@ +## One tick of one player's intent. Humans, bots and network clients all produce these. +## See "Player command stream" in docs/ARCHITECTURE.md. +class_name PlayerCommand +extends RefCounted + +const ENCODED_SIZE: int = 14 + +const BUTTON_FIRE: int = 1 << 0 +const BUTTON_AIM: int = 1 << 1 +const BUTTON_JUMP: int = 1 << 2 +const BUTTON_CROUCH: int = 1 << 3 +const BUTTON_SPRINT: int = 1 << 4 +const BUTTON_RELOAD: int = 1 << 5 +const BUTTON_INTERACT: int = 1 << 6 +const BUTTON_BUILD: int = 1 << 7 + +const AXIS_MAX: int = 127 +const YAW_STEPS: int = 65536 +const PITCH_MAX: int = 32767 + +var tick: int = 0 +var move_x: int = 0 +var move_y: int = 0 +var yaw: int = 0 +var pitch: int = 0 +var buttons: int = 0 +var selection: int = 0 +var material: int = 0 + + +## Builds a command from real-valued input, clamping every field into range. +static func from_input( + at_tick: int, + move: Vector2, + yaw_radians: float, + pitch_radians: float, + pressed: int = 0, + selected: int = 0, + chosen_material: int = 0, +) -> PlayerCommand: + var command: PlayerCommand = PlayerCommand.new() + command.tick = at_tick + command.move_x = roundi(clampf(move.x, -1.0, 1.0) * AXIS_MAX) + command.move_y = roundi(clampf(move.y, -1.0, 1.0) * AXIS_MAX) + command.yaw = posmod(roundi(yaw_radians / TAU * YAW_STEPS), YAW_STEPS) + command.pitch = clampi(roundi(pitch_radians / (PI * 0.5) * PITCH_MAX), -PITCH_MAX, PITCH_MAX) + command.buttons = pressed + command.selection = selected + command.material = chosen_material + return command + + +## Returns the movement axes, scaled to -1..1, with diagonals no faster than straight lines. +func move_vector() -> Vector2: + return Vector2(move_x, move_y) / float(AXIS_MAX) + + +func yaw_radians() -> float: + return float(yaw) / YAW_STEPS * TAU + + +func pitch_radians() -> float: + return float(pitch) / PITCH_MAX * (PI * 0.5) + + +func is_pressed(button: int) -> bool: + return buttons & button != 0 + + +## Encodes to ENCODED_SIZE bytes, little-endian. Out-of-range fields are clamped. +func encode() -> PackedByteArray: + var bytes: PackedByteArray = PackedByteArray() + bytes.resize(ENCODED_SIZE) + bytes.encode_u32(0, tick & 0xFFFFFFFF) + bytes.encode_s8(4, clampi(move_x, -AXIS_MAX, AXIS_MAX)) + bytes.encode_s8(5, clampi(move_y, -AXIS_MAX, AXIS_MAX)) + bytes.encode_u16(6, posmod(yaw, YAW_STEPS)) + bytes.encode_s16(8, clampi(pitch, -PITCH_MAX, PITCH_MAX)) + bytes.encode_u16(10, buttons & 0xFFFF) + bytes.encode_u8(12, selection & 0xFF) + bytes.encode_u8(13, material & 0xFF) + return bytes + + +## Decodes a command at `offset`, or returns null if the buffer is too short. +## Values from the wire are clamped, so a hostile client can't exceed the valid range. +static func decode(bytes: PackedByteArray, offset: int = 0) -> PlayerCommand: + if offset < 0 or offset + ENCODED_SIZE > bytes.size(): + return null + var command: PlayerCommand = PlayerCommand.new() + command.tick = bytes.decode_u32(offset) + command.move_x = clampi(bytes.decode_s8(offset + 4), -AXIS_MAX, AXIS_MAX) + command.move_y = clampi(bytes.decode_s8(offset + 5), -AXIS_MAX, AXIS_MAX) + command.yaw = bytes.decode_u16(offset + 6) + command.pitch = clampi(bytes.decode_s16(offset + 8), -PITCH_MAX, PITCH_MAX) + command.buttons = bytes.decode_u16(offset + 10) + command.selection = bytes.decode_u8(offset + 12) + command.material = bytes.decode_u8(offset + 13) + return command diff --git a/src/sim/player_command.gd.uid b/src/sim/player_command.gd.uid new file mode 100644 index 0000000..38c6ca9 --- /dev/null +++ b/src/sim/player_command.gd.uid @@ -0,0 +1 @@ +uid://6cm8jy0sdyp0 diff --git a/src/sim/sim_entity.gd b/src/sim/sim_entity.gd new file mode 100644 index 0000000..c4e0100 --- /dev/null +++ b/src/sim/sim_entity.gd @@ -0,0 +1,18 @@ +## One object in the simulation. IDs are assigned by EntityRegistry and never change. +class_name SimEntity +extends RefCounted + +const ARCHETYPE_PLAYER: int = 1 + +var id: int = 0 +var archetype: int = 0 +var position: Vector3 = Vector3.ZERO +var velocity: Vector3 = Vector3.ZERO +var yaw: int = 0 +var pitch: int = 0 +var health: int = 0 + + +func _init(entity_id: int, entity_archetype: int) -> void: + id = entity_id + archetype = entity_archetype diff --git a/src/sim/sim_entity.gd.uid b/src/sim/sim_entity.gd.uid new file mode 100644 index 0000000..5757030 --- /dev/null +++ b/src/sim/sim_entity.gd.uid @@ -0,0 +1 @@ +uid://bqogpyfd311pn diff --git a/src/sim/sim_rng.gd b/src/sim/sim_rng.gd new file mode 100644 index 0000000..a1c3132 --- /dev/null +++ b/src/sim/sim_rng.gd @@ -0,0 +1,46 @@ +## The match's seeded randomness. Each system draws from its own named stream, so one +## system's extra rolls can't change what another rolls. +class_name SimRng +extends RefCounted + +const FNV_PRIME: int = 16777619 +const FNV_OFFSET_LOW: int = 2166136261 +const FNV_OFFSET_HIGH: int = 3735928559 +const MASK_32: int = 0xFFFFFFFF + +var match_seed: int = 0 + +var _streams: Dictionary = {} + + +func _init(seed_value: int) -> void: + match_seed = seed_value + + +## Returns the named stream, creating it on first use. +func stream(stream_name: String) -> RandomNumberGenerator: + if not _streams.has(stream_name): + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = match_seed ^ _hash_name(stream_name) + _streams[stream_name] = rng + return _streams[stream_name] + + +## Stream names, sorted, so that state can be hashed in a stable order. +func stream_names() -> Array[String]: + var names: Array[String] = [] + for key: String in _streams: + names.append(key) + names.sort() + return names + + +## 64-bit name hash built from two 32-bit FNV-1a passes. It stays within 64-bit signed +## arithmetic, and doesn't rely on String.hash(), which can change between engine versions. +static func _hash_name(text: String) -> int: + var low: int = FNV_OFFSET_LOW + var high: int = FNV_OFFSET_HIGH + for byte: int in text.to_utf8_buffer(): + low = ((low ^ byte) * FNV_PRIME) & MASK_32 + high = ((high ^ (byte + 1)) * FNV_PRIME) & MASK_32 + return (high << 32) | low diff --git a/src/sim/sim_rng.gd.uid b/src/sim/sim_rng.gd.uid new file mode 100644 index 0000000..aad8ea6 --- /dev/null +++ b/src/sim/sim_rng.gd.uid @@ -0,0 +1 @@ +uid://dtl1a4nii45cq diff --git a/src/sim/simulation.gd b/src/sim/simulation.gd new file mode 100644 index 0000000..fe9be10 --- /dev/null +++ b/src/sim/simulation.gd @@ -0,0 +1,112 @@ +## The authoritative fixed-tick game state. It takes commands and a seed and nothing +## else: no scene tree, no wall clock, no unseeded randomness. +## +## Movement here is a flat placeholder until the character controller lands in v0.2. +class_name Simulation +extends RefCounted + +const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ + +var tick: int = 0 +var entities: EntityRegistry = EntityRegistry.new() +var rng: SimRng + +## Player entity ID -> { command tick -> PlayerCommand } +var _pending: Dictionary = {} +## Player entity IDs, ascending. +var _players: Array[int] = [] + + +func _init(match_seed: int) -> void: + rng = SimRng.new(match_seed) + + +## Adds a player at a seeded spawn position and returns its entity ID. +func add_player() -> int: + var player: SimEntity = entities.create(SimEntity.ARCHETYPE_PLAYER) + var spawn: RandomNumberGenerator = rng.stream("spawn") + var size: float = Tuning.WORLD_SIZE_METRES + player.position = Vector3(spawn.randf() * size, 0.0, spawn.randf() * size) + player.health = Tuning.PLAYER_MAX_HEALTH + _players.append(player.id) + _pending[player.id] = {} + return player.id + + +## Removes a player and any commands queued for it. +func remove_player(player_id: int) -> void: + entities.remove(player_id) + _players.erase(player_id) + _pending.erase(player_id) + + +## Queues a command for the tick it names. Returns false if it was rejected: the player +## is unknown, the tick has passed, or the tick is too far ahead to be legitimate. +## A later command for the same tick replaces an earlier one. +func submit_command(player_id: int, command: PlayerCommand) -> bool: + if not _pending.has(player_id): + return false + if command.tick < tick or command.tick > tick + Tuning.MAX_COMMAND_LEAD_TICKS: + return false + _pending[player_id][command.tick] = command + return true + + +## Advances the simulation by one tick. +func step() -> void: + for player_id: int in _players: + var queued: Dictionary = _pending[player_id] + var command: PlayerCommand = queued.get(tick) + queued.erase(tick) + _apply_command(entities.find(player_id), command) + tick += 1 + + +func _apply_command(player: SimEntity, command: PlayerCommand) -> void: + # With no command this tick, the player keeps looking the same way and stands still. + if command == null: + return + player.yaw = command.yaw + player.pitch = command.pitch + + var move: Vector2 = command.move_vector() + if move.length() > 1.0: + move = move.normalized() + var angle: float = command.yaw_radians() + var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle)) + var right: Vector3 = Vector3(cos(angle), 0.0, -sin(angle)) + var speed: float = ( + Tuning.SPRINT_SPEED if command.is_pressed(PlayerCommand.BUTTON_SPRINT) + else Tuning.WALK_SPEED + ) + var delta: Vector3 = (right * move.x + forward * move.y) * speed * SECONDS_PER_TICK + var size: float = Tuning.WORLD_SIZE_METRES + player.position = (player.position + delta).clamp(Vector3.ZERO, Vector3(size, 0.0, size)) + + +## SHA-256 hex digest of a canonical encoding of the whole state. +func state_hash() -> String: + var buffer: StreamPeerBuffer = StreamPeerBuffer.new() + buffer.big_endian = false + buffer.put_64(tick) + buffer.put_64(entities.next_id()) + buffer.put_64(rng.match_seed) + for stream_name: String in rng.stream_names(): + buffer.put_utf8_string(stream_name) + buffer.put_64(rng.stream(stream_name).state) + buffer.put_64(entities.count()) + for entity: SimEntity in entities.entities(): + buffer.put_64(entity.id) + buffer.put_32(entity.archetype) + buffer.put_32(entity.health) + buffer.put_32(entity.yaw) + buffer.put_32(entity.pitch) + for value: float in [entity.position.x, entity.position.y, entity.position.z]: + buffer.put_64(roundi(value * 1000.0)) + for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]: + buffer.put_64(roundi(value * 1000.0)) + + var hasher: HashingContext = HashingContext.new() + hasher.start(HashingContext.HASH_SHA256) + hasher.update(buffer.data_array) + return hasher.finish().hex_encode() diff --git a/src/sim/simulation.gd.uid b/src/sim/simulation.gd.uid new file mode 100644 index 0000000..365fe5e --- /dev/null +++ b/src/sim/simulation.gd.uid @@ -0,0 +1 @@ +uid://c33yi2km6174w diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index 490a40b..94bc9b6 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -5,6 +5,10 @@ extends RefCounted # Simulation const TICK_RATE_HZ: int = 30 +## Commands further ahead of the current tick than this are rejected. +const MAX_COMMAND_LEAD_TICKS: int = 60 +## Width and depth of the playable world. Positions are clamped inside it. +const WORLD_SIZE_METRES: float = 1024.0 # Match sizes const SOLO_PLAYERS: int = 24 diff --git a/test/project/test_sim_isolation.gd b/test/project/test_sim_isolation.gd index ce1f3de..1c901f8 100644 --- a/test/project/test_sim_isolation.gd +++ b/test/project/test_sim_isolation.gd @@ -6,9 +6,11 @@ const FORBIDDEN: Array[String] = [ "Node2D", "Node3D", "MeshInstance3D", "Camera3D", "Control", "CanvasItem", "Viewport", "SceneTree", "get_tree", "Input.", ] -const NONDETERMINISTIC: Array[String] = [ - "randf(", "randi(", "randf_range(", "randi_range(", "randomize(", "Time.", "OS.get_ticks", -] +const NONDETERMINISTIC: Array[String] = ["Time.", "OS.get_ticks"] +## Global random calls. A method call on a seeded stream (stream.randf()) is allowed. +const GLOBAL_RANDOM: String = "(? void: @@ -19,16 +21,51 @@ func test_simulation_has_no_unseeded_randomness() -> void: _scan(NONDETERMINISTIC) +func test_simulation_makes_no_global_random_calls() -> void: + for path: String in _scripts_under("res://src/sim"): + for line: String in _code_lines(path): + if _global_random().search(line) != null: + fail("%s makes a global random call: %s" % [path, line.strip_edges()]) + + +func test_only_sim_rng_creates_generators() -> void: + for path: String in _scripts_under("res://src/sim"): + if path == RNG_OWNER: + continue + for line: String in _code_lines(path): + if line.contains("RandomNumberGenerator.new"): + fail("%s creates its own generator: %s" % [path, line.strip_edges()]) + + +func test_scanner_tells_global_calls_from_seeded_ones() -> void: + var pattern: RegEx = _global_random() + assert_not_null(pattern.search("var x: float = randf()"), "global call must match") + assert_not_null(pattern.search("foo(randi_range(1, 2))"), "nested global call must match") + assert_null(pattern.search("var x: float = stream.randf()"), "seeded call must not match") + assert_null(pattern.search("my_randf(1)"), "other identifiers must not match") + + +func _global_random() -> RegEx: + var pattern: RegEx = RegEx.new() + pattern.compile(GLOBAL_RANDOM) + return pattern + + +func _code_lines(path: String) -> Array[String]: + var lines: Array[String] = [] + for line: String in FileAccess.get_file_as_string(path).split("\n"): + lines.append(line.get_slice("#", 0)) + return lines + + func _scan(needles: Array[String]) -> void: var paths: Array[String] = _scripts_under("res://src/sim") assert_true(not paths.is_empty(), "expected scripts in src/sim") for path: String in paths: - var source: String = FileAccess.get_file_as_string(path) for needle: String in needles: # Comments may mention these; only code counts. - for line: String in source.split("\n"): - var code: String = line.get_slice("#", 0) - if code.contains(needle): + for line: String in _code_lines(path): + if line.contains(needle): fail("%s uses %s: %s" % [path, needle, line.strip_edges()]) diff --git a/test/sim/test_entity_registry.gd b/test/sim/test_entity_registry.gd new file mode 100644 index 0000000..36a68a4 --- /dev/null +++ b/test/sim/test_entity_registry.gd @@ -0,0 +1,37 @@ +extends TestCase + + +func test_ids_start_at_one_and_none_is_never_used() -> void: + var registry: EntityRegistry = EntityRegistry.new() + assert_eq(registry.create(1).id, 1) + assert_eq(EntityRegistry.NONE, 0) + assert_null(registry.find(EntityRegistry.NONE)) + + +func test_ids_are_never_reused() -> void: + var registry: EntityRegistry = EntityRegistry.new() + var first: int = registry.create(1).id + assert_true(registry.remove(first)) + assert_false(registry.contains(first)) + assert_ne(registry.create(1).id, first) + + +func test_iteration_is_in_ascending_id_order_after_removals() -> void: + var registry: EntityRegistry = EntityRegistry.new() + for _index: int in 5: + registry.create(1) + registry.remove(2) + registry.create(1) + var ids: Array[int] = [] + for entity: SimEntity in registry.entities(): + ids.append(entity.id) + assert_eq(ids, [1, 3, 4, 5, 6] as Array[int]) + + +func test_removing_while_iterating_is_safe() -> void: + var registry: EntityRegistry = EntityRegistry.new() + for _index: int in 4: + registry.create(1) + for entity: SimEntity in registry.entities(): + registry.remove(entity.id) + assert_eq(registry.count(), 0) diff --git a/test/sim/test_entity_registry.gd.uid b/test/sim/test_entity_registry.gd.uid new file mode 100644 index 0000000..11d311c --- /dev/null +++ b/test/sim/test_entity_registry.gd.uid @@ -0,0 +1 @@ +uid://boob5j7i4dnrr diff --git a/test/sim/test_player_command.gd b/test/sim/test_player_command.gd new file mode 100644 index 0000000..06ff9c8 --- /dev/null +++ b/test/sim/test_player_command.gd @@ -0,0 +1,74 @@ +extends TestCase + + +func test_round_trip_preserves_every_field() -> void: + var command: PlayerCommand = PlayerCommand.new() + command.tick = 4_000_000_000 + command.move_x = -127 + command.move_y = 90 + command.yaw = 65535 + command.pitch = -32767 + command.buttons = PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD | 0x8000 + command.selection = 200 + command.material = 3 + + var decoded: PlayerCommand = PlayerCommand.decode(command.encode()) + assert_not_null(decoded) + assert_eq(decoded.tick, 4_000_000_000) + assert_eq(decoded.move_x, -127) + assert_eq(decoded.move_y, 90) + assert_eq(decoded.yaw, 65535) + assert_eq(decoded.pitch, -32767) + assert_eq(decoded.buttons, command.buttons) + assert_eq(decoded.selection, 200) + assert_eq(decoded.material, 3) + + +func test_encoding_is_compact_and_fixed_size() -> void: + assert_eq(PlayerCommand.new().encode().size(), PlayerCommand.ENCODED_SIZE) + assert_eq(PlayerCommand.ENCODED_SIZE, 14) + + +func test_decode_at_an_offset() -> void: + var first: PlayerCommand = PlayerCommand.new() + first.tick = 7 + var second: PlayerCommand = PlayerCommand.new() + second.tick = 8 + var stream: PackedByteArray = first.encode() + second.encode() + assert_eq(PlayerCommand.decode(stream, PlayerCommand.ENCODED_SIZE).tick, 8) + + +func test_truncated_buffer_returns_null_without_error() -> void: + var bytes: PackedByteArray = PlayerCommand.new().encode() + bytes.resize(PlayerCommand.ENCODED_SIZE - 1) + assert_null(PlayerCommand.decode(bytes)) + assert_null(PlayerCommand.decode(PackedByteArray())) + assert_null(PlayerCommand.decode(PlayerCommand.new().encode(), 1)) + assert_null(PlayerCommand.decode(PlayerCommand.new().encode(), -1)) + + +func test_hostile_wire_values_are_clamped() -> void: + var bytes: PackedByteArray = PlayerCommand.new().encode() + bytes.encode_s8(4, -128) + bytes.encode_s16(8, -32768) + var decoded: PlayerCommand = PlayerCommand.decode(bytes) + assert_eq(decoded.move_x, -PlayerCommand.AXIS_MAX) + assert_eq(decoded.pitch, -PlayerCommand.PITCH_MAX) + + +func test_from_input_clamps_and_wraps() -> void: + var command: PlayerCommand = PlayerCommand.from_input(1, Vector2(5.0, -5.0), -PI * 0.5, 9.0) + assert_eq(command.move_x, PlayerCommand.AXIS_MAX) + assert_eq(command.move_y, -PlayerCommand.AXIS_MAX) + assert_eq(command.yaw, PlayerCommand.YAW_STEPS * 3 / 4) + assert_eq(command.pitch, PlayerCommand.PITCH_MAX) + + +func test_input_helpers_read_back() -> void: + var command: PlayerCommand = PlayerCommand.from_input( + 1, Vector2(0.5, 0.0), PI, 0.0, PlayerCommand.BUTTON_JUMP + ) + assert_near(command.yaw_radians(), PI, 0.001) + assert_near(command.move_vector().x, 0.5, 0.01) + assert_true(command.is_pressed(PlayerCommand.BUTTON_JUMP)) + assert_false(command.is_pressed(PlayerCommand.BUTTON_FIRE)) diff --git a/test/sim/test_player_command.gd.uid b/test/sim/test_player_command.gd.uid new file mode 100644 index 0000000..0e49b78 --- /dev/null +++ b/test/sim/test_player_command.gd.uid @@ -0,0 +1 @@ +uid://w38lfvpvwmym diff --git a/test/sim/test_sim_rng.gd b/test/sim/test_sim_rng.gd new file mode 100644 index 0000000..4d86fe1 --- /dev/null +++ b/test/sim/test_sim_rng.gd @@ -0,0 +1,35 @@ +extends TestCase + + +func test_same_seed_and_name_give_the_same_rolls() -> void: + assert_eq(_rolls(SimRng.new(42), "loot"), _rolls(SimRng.new(42), "loot")) + + +func test_different_seeds_give_different_rolls() -> void: + assert_ne(_rolls(SimRng.new(42), "loot"), _rolls(SimRng.new(43), "loot")) + + +func test_different_streams_give_different_rolls() -> void: + var rng: SimRng = SimRng.new(42) + assert_ne(_rolls(rng, "loot"), _rolls(rng, "weapons")) + + +func test_extra_rolls_in_one_stream_do_not_disturb_another() -> void: + var noisy: SimRng = SimRng.new(42) + _rolls(noisy, "loot") + assert_eq(_rolls(noisy, "weapons"), _rolls(SimRng.new(42), "weapons")) + + +func test_stream_names_are_sorted() -> void: + var rng: SimRng = SimRng.new(1) + rng.stream("zebra") + rng.stream("alpha") + assert_eq(rng.stream_names(), ["alpha", "zebra"] as Array[String]) + + +func _rolls(rng: SimRng, stream_name: String) -> Array[int]: + var results: Array[int] = [] + var stream: RandomNumberGenerator = rng.stream(stream_name) + for _index: int in 16: + results.append(stream.randi()) + return results diff --git a/test/sim/test_sim_rng.gd.uid b/test/sim/test_sim_rng.gd.uid new file mode 100644 index 0000000..a012ce8 --- /dev/null +++ b/test/sim/test_sim_rng.gd.uid @@ -0,0 +1 @@ +uid://b12mib1013p6k diff --git a/test/sim/test_simulation.gd b/test/sim/test_simulation.gd new file mode 100644 index 0000000..bbd8af8 --- /dev/null +++ b/test/sim/test_simulation.gd @@ -0,0 +1,152 @@ +extends TestCase + +const SEED: int = 123456789 +const PLAYERS: int = Tuning.SOLO_PLAYERS +const TICKS: int = 10_000 + + +func test_same_seed_and_log_produce_the_same_hash_over_ten_thousand_ticks() -> void: + var log_bytes: PackedByteArray = _build_command_log(SEED, PLAYERS, TICKS) + var first: String = _replay(SEED, log_bytes) + var second: String = _replay(SEED, log_bytes) + assert_eq(first, second) + assert_eq(first.length(), 64, "expected a SHA-256 hex digest") + + +func test_a_different_seed_changes_the_hash() -> void: + var log_bytes: PackedByteArray = _build_command_log(SEED, 4, 200) + assert_ne(_replay(SEED, log_bytes, 4), _replay(SEED + 1, log_bytes, 4)) + + +func test_a_single_changed_command_changes_the_hash() -> void: + var log_bytes: PackedByteArray = _build_command_log(SEED, 4, 200) + var changed: PackedByteArray = log_bytes.duplicate() + # Flip one bit of move_x in the middle of the log. + changed[changed.size() / 2 / PlayerCommand.ENCODED_SIZE * PlayerCommand.ENCODED_SIZE + 4] ^= 1 + assert_ne(_replay(SEED, log_bytes, 4), _replay(SEED, changed, 4)) + + +func test_submission_order_across_players_does_not_matter() -> void: + var a: Simulation = _simulation(SEED, 2) + var b: Simulation = _simulation(SEED, 2) + var cmd_one: PlayerCommand = PlayerCommand.from_input(0, Vector2.RIGHT, 0.5, 0.0) + var cmd_two: PlayerCommand = PlayerCommand.from_input(0, Vector2.UP, 1.5, 0.0) + a.submit_command(1, cmd_one) + a.submit_command(2, cmd_two) + b.submit_command(2, cmd_two) + b.submit_command(1, cmd_one) + a.step() + b.step() + assert_eq(a.state_hash(), b.state_hash()) + + +func test_missing_command_keeps_the_last_look_and_stops_moving() -> void: + var sim: Simulation = _simulation(SEED, 1) + sim.submit_command(1, PlayerCommand.from_input(0, Vector2(0.0, 1.0), 1.0, 0.25)) + sim.step() + var player: SimEntity = sim.entities.find(1) + var yaw: int = player.yaw + var position: Vector3 = player.position + assert_ne(yaw, 0) + sim.step() + assert_eq(player.yaw, yaw) + assert_eq(player.position, position) + + +func test_movement_speed_matches_tuning() -> void: + var sim: Simulation = _simulation(SEED, 1) + var player: SimEntity = sim.entities.find(1) + # Start from the middle of the world so clamping can't interfere. + player.position = Vector3.ONE * 500.0 + player.position.y = 0.0 + var start: Vector3 = player.position + sim.submit_command(1, PlayerCommand.from_input(0, Vector2(0.0, 1.0), 0.0, 0.0)) + sim.step() + assert_near(start.distance_to(player.position), Tuning.WALK_SPEED / Tuning.TICK_RATE_HZ, 0.001) + + +func test_stale_and_far_future_commands_are_rejected() -> void: + var sim: Simulation = _simulation(SEED, 1) + sim.step() + assert_false(sim.submit_command(1, PlayerCommand.from_input(0, Vector2.ZERO, 0.0, 0.0))) + var too_far: int = sim.tick + Tuning.MAX_COMMAND_LEAD_TICKS + 1 + assert_false(sim.submit_command(1, PlayerCommand.from_input(too_far, Vector2.ZERO, 0.0, 0.0))) + assert_true(sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0))) + + +func test_commands_for_unknown_players_are_rejected() -> void: + var sim: Simulation = _simulation(SEED, 1) + assert_false(sim.submit_command(99, PlayerCommand.from_input(0, Vector2.ZERO, 0.0, 0.0))) + + +func test_removed_player_is_gone_and_id_is_not_reused() -> void: + var sim: Simulation = _simulation(SEED, 2) + sim.remove_player(1) + assert_false(sim.entities.contains(1)) + assert_false(sim.submit_command(1, PlayerCommand.from_input(0, Vector2.ZERO, 0.0, 0.0))) + assert_eq(sim.add_player(), 3) + sim.step() + + +func test_positions_stay_inside_the_world() -> void: + var sim: Simulation = _simulation(SEED, 1) + var player: SimEntity = sim.entities.find(1) + player.position = Vector3(Tuning.WORLD_SIZE_METRES, 0.0, Tuning.WORLD_SIZE_METRES) + for at_tick: int in 30: + sim.submit_command(1, PlayerCommand.from_input(at_tick, Vector2(1.0, 1.0), 0.8, 0.0)) + sim.step() + assert_true(player.position.x <= Tuning.WORLD_SIZE_METRES) + assert_true(player.position.z <= Tuning.WORLD_SIZE_METRES) + assert_true(player.position.x >= 0.0 and player.position.z >= 0.0) + + +func test_simulation_needs_no_scene_tree() -> void: + # Simulation is a plain object: it steps with no Node and no tree involved. + var sim: Variant = Simulation.new(SEED) + assert_false(sim is Node) + (sim as Simulation).add_player() + (sim as Simulation).step() + assert_eq((sim as Simulation).tick, 1) + + +func _simulation(match_seed: int, players: int) -> Simulation: + var sim: Simulation = Simulation.new(match_seed) + for _index: int in players: + sim.add_player() + return sim + + +## Builds a log of ticks * players encoded commands, in a compact byte array. +func _build_command_log(log_seed: int, players: int, ticks: int) -> PackedByteArray: + var random: RandomNumberGenerator = RandomNumberGenerator.new() + random.seed = log_seed + var bytes: PackedByteArray = PackedByteArray() + bytes.resize(players * ticks * PlayerCommand.ENCODED_SIZE) + var offset: int = 0 + for at_tick: int in ticks: + for _player: int in players: + var command: PlayerCommand = PlayerCommand.new() + command.tick = at_tick + command.move_x = random.randi_range(-127, 127) + command.move_y = random.randi_range(-127, 127) + command.yaw = random.randi_range(0, 65535) + command.pitch = random.randi_range(-32767, 32767) + command.buttons = random.randi_range(0, 255) + var encoded: PackedByteArray = command.encode() + for index: int in encoded.size(): + bytes[offset + index] = encoded[index] + offset += PlayerCommand.ENCODED_SIZE + return bytes + + +func _replay(match_seed: int, log_bytes: PackedByteArray, players: int = PLAYERS) -> String: + var sim: Simulation = _simulation(match_seed, players) + var per_tick: int = players * PlayerCommand.ENCODED_SIZE + var ticks: int = log_bytes.size() / per_tick + for at_tick: int in ticks: + for player: int in players: + var offset: int = at_tick * per_tick + player * PlayerCommand.ENCODED_SIZE + var command: PlayerCommand = PlayerCommand.decode(log_bytes, offset) + sim.submit_command(player + 1, command) + sim.step() + return sim.state_hash() diff --git a/test/sim/test_simulation.gd.uid b/test/sim/test_simulation.gd.uid new file mode 100644 index 0000000..5e745a8 --- /dev/null +++ b/test/sim/test_simulation.gd.uid @@ -0,0 +1 @@ +uid://b3x1unn67dxq6