## 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 rules live in Movement; the world's solid shape lives in `ground`. class_name Simulation extends RefCounted const SECONDS_PER_TICK: float = 1.0 / Tuning.TICK_RATE_HZ const SPAWN_ATTEMPTS: int = 64 ## The command selection that holds the boathook, which every player always carries. const BOATHOOK_SLOT: int = 0 var tick: int = 0 var entities: EntityRegistry = EntityRegistry.new() var rng: SimRng ## Terrain and solids. The island's heightfield unless a test supplied its own ground. var ground: SimGround ## The generated island, or null when a test supplied its own ground. var island: Island ## The island's points of interest, whose solids are part of `ground`. Empty when a ## test supplied its own ground. var pois: PoiSet = PoiSet.new() ## Trees, scrub, boulders, wrecks and crates, whose boxes are part of `ground`. Empty ## when a test supplied its own ground. var props: PropSet = PropSet.new() ## Height of the sea surface, in metres. The tide changes it during a match; movement ## and drowning read it every tick, so a change takes effect on the next step. var sea_level: float = Tuning.SEA_LEVEL_START ## Damage per second to a player underwater with no breath left. Set by the tide phase. var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"] ## The tide's schedule, from start_tide() on. Null in tests that set the sea by hand. var tide: Tide = null ## Where the sea reaches, on an island. Null on a test ground, where the sea is ## everywhere under `sea_level`. var flood: Flood = null ## Every built piece. Their boxes are part of `ground`. var structures: StructureSet = StructureSet.new() ## The sky barge, from start_drop() on. Null in matches and tests that start on foot. var drop: Drop = null ## Floor loot, sea chests and crate contents. Empty until place_loot(). var loot: LootSet = LootSet.new() ## Items lying in the world, as entity IDs in ascending order. See Inventory. var pickups: Array[int] = [] ## Shots in flight, as entity IDs in ascending order. See Weapons. var projectiles: Array[int] = [] ## What happened during the last step(): harvests, destroyed props, placed pieces. ## Each is a Dictionary with a "type". Cleared at the start of every step. var events: Array[Dictionary] = [] ## Where every player has been over the last half second, for judging shots against ## what a network client saw. Rebuilt identically by a replay, so not part of the hash. var hit_history: HitHistory = HitHistory.new() ## Player entity ID -> { command tick -> PlayerCommand } var _pending: Dictionary = {} ## The tide levels plan_tide() worked out, or empty. var _planned_levels: PackedFloat32Array = PackedFloat32Array() ## How many entries of props.destroyed have been checked for crate loot. var _destroyed_checked: int = 0 ## Player entity IDs, ascending. var _players: Array[int] = [] ## Generates the island from the seed, unless `world` is given. Tests that don't care ## about terrain pass `SimGround.flat()` to skip worldgen. func _init(match_seed: int, world: SimGround = null) -> void: rng = SimRng.new(match_seed) if world == null: island = Island.generate(match_seed) world = island.ground pois = PoiSet.generate(island) pois.add_solids_to(world) props = PropSet.generate(island, pois) props.add_solids_to(world) flood = Flood.create(world) ground = world structures.props = props ## 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 var x: float = spawn.randf() * size var z: float = spawn.randf() * size # Until the drop arrives (W7), spawn on dry land above the beach when there is any. for _attempt: int in SPAWN_ATTEMPTS: var feet: Vector3 = Vector3(x, ground.terrain_height(x, z), z) if feet.y > Tuning.ISLAND_BEACH_TOP and not ground.body_blocked(feet, 2.0, Tuning.PLAYER_HEIGHT, 0.0): break x = spawn.randf() * size z = spawn.randf() * size player.position = Vector3(x, ground.terrain_height(x, z), z) player.on_ground = true player.health = Tuning.PLAYER_MAX_HEALTH Water.reset(player) Inventory.reset(player) if drop != null and not drop.finished: Drop.board(player, drop.barge_position(tick)) _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) hit_history.forget(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 ## Starts the match's drop: plans the barge's route and puts every player aboard. func start_drop() -> void: drop = Drop.plan(ground, rng, tick) for player_id: int in _players: Drop.board(entities.find(player_id), drop.barge_position(tick)) ## Rolls the match's loot from the "loot" stream and puts the floor loot in the world. ## Chests and crates spill theirs when opened or broken. Does nothing on a test ground ## with no island, and only works once. func place_loot() -> void: if island == null or loot.floor_spots.size() + loot.chest_positions.size() + loot.crate_contents.size() > 0: return loot = LootSet.plan(rng.stream("loot"), pois.loot_markers(), crate_spill_points(props)) loot.place_floor(self) ## Each crate prop's index mapped to where its loot spills: the middle of its base. static func crate_spill_points(prop_set: PropSet) -> Dictionary: var points: Dictionary = {} for prop: int in prop_set.count(): if prop_set.kind_name(prop) == LootSet.CRATE_KIND and prop_set.is_standing(prop): var box: AABB = prop_set.boxes[prop] points[prop] = Vector3(box.get_center().x, box.position.y, box.get_center().z) return points ## Starts the tide's schedule from this tick. func start_tide() -> void: if island != null: plan_tide() tide = Tide.new(tick, _planned_levels) else: tide = Tide.new(tick) ## Works out the island's tide levels now, if it hasn't been done, so start_tide() is ## quick. They depend only on the island, so the server does this on the worker that ## builds the next match's island; anything that changes the ground first must not. func plan_tide() -> void: if island != null and _planned_levels.is_empty(): _planned_levels = SafeGround.new(ground).plan_levels() ## Height of the water surface over a point: the sea level where the flood reaches, ## Flood.NO_WATER where it doesn't. On a test ground, the sea level everywhere. func water_level_at(point: Vector3) -> float: if flood == null: return sea_level return flood.level_at(point.x, point.z) ## Advances the simulation by one tick. func step() -> void: events.clear() if tide != null: _advance_tide() elif flood != null: flood.flow(sea_level, SECONDS_PER_TICK) structures.advance_building() if tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1: structures.tide_damage(sea_level, ground, events, flood) for player_id: int in _players: var standing: SimEntity = entities.find(player_id) if not standing.eliminated: hit_history.note(tick, standing) for player_id: int in _players: var queued: Dictionary = _pending[player_id] var command: PlayerCommand = queued.get(tick) queued.erase(tick) var player: SimEntity = entities.find(player_id) if player.eliminated: continue if player.drop_state == Drop.ABOARD: drop.ride(player, command, tick) else: _apply_command(player, command) Weapons.advance_projectiles(self) _spill_broken_crates() _check_eliminations() if drop != null and not drop.finished and drop.is_over(tick + 1): # The end of the route: everyone still aboard goes over the side. for player_id: int in _players: var player: SimEntity = entities.find(player_id) if player.drop_state == Drop.ABOARD: drop.leap(player, tick + 1) drop.finished = true tick += 1 func _apply_command(player: SimEntity, command: PlayerCommand) -> void: var water: float = water_level_at(player.position) Movement.step(player, command, ground, water) var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT) Water.update(player, water_level_at(player.position), drown_dps, sprinting) if player.action_cooldown > 0: player.action_cooldown -= 1 if command != null: Weapons.note_view(player, command, tick) Weapons.update(player) Consumables.update(self, player, command) var held: int = command.buttons if command != null else 0 var pressed: int = held & ~player.prev_buttons player.prev_buttons = held if command != null and not command.is_pressed(PlayerCommand.BUTTON_BUILD): Inventory.select(player, command.selection) if Harvest.can_swing(player): if pressed & PlayerCommand.BUTTON_INTERACT: if loot.open_nearest(self, player) < 0: Inventory.interact(self, player) if pressed & PlayerCommand.BUTTON_DROP: Inventory.drop_held(self, player) if command != null and command.is_pressed(PlayerCommand.BUTTON_RELOAD): Weapons.start_reload(player) if command == null or not command.is_pressed(PlayerCommand.BUTTON_FIRE): return if not Building.is_allowed(player): return if command.is_pressed(PlayerCommand.BUTTON_BUILD): Building.act(self, player, command) return if player.selected == BOATHOOK_SLOT: Harvest.swing(player, ground, props, events, structures) else: var def: ItemDef = Inventory.held_def(player) if def != null and def.kind == ItemDef.CONSUMABLE: Consumables.start(self, player) else: Weapons.fire(self, player, command.is_pressed(PlayerCommand.BUTTON_AIM)) ## Spills the loot of every crate destroyed since the last check, however it broke. func _spill_broken_crates() -> void: while _destroyed_checked < props.destroyed.size(): var prop: int = props.destroyed[_destroyed_checked] _destroyed_checked += 1 if not loot.crate_contents.has(prop): continue var box: AABB = props.boxes[prop] var at: Vector3 = Vector3(box.get_center().x, box.position.y, box.get_center().z) var ids: Array[int] = loot.spill_crate(self, prop, at) events.append({"type": "crate_spilled", "prop": prop, "pickups": ids}) ## Marks players whose health reached 0 as eliminated, and drops what they carried. func _check_eliminations() -> void: for player_id: int in _players: var player: SimEntity = entities.find(player_id) if player.eliminated or player.health > 0: continue player.eliminated = true player.velocity = Vector3.ZERO events.append({ "type": "eliminated", "player": player_id, "by": player.last_attacker, "cause": SimEntity.CAUSE_NAMES[player.last_cause], }) Inventory.drop_all(self, player) ## Moves the sea surface, and spreads the flood for it at once. Takes effect on the ## next step. With the tide running, the tide sets the level every tick instead. func set_sea_level(level: float) -> void: sea_level = level if flood != null: flood.update(level, structures, 0.0) ## The tide's tick: the sea level, drowning damage, storm surges, the flood's spread and ## sudden death. func _advance_tide() -> void: sea_level = tide.level_at(tick) drown_dps = tide.drown_dps_at(tick) if flood != null: if tick % Tuning.TICK_RATE_HZ == 0: flood.update(sea_level, structures, SECONDS_PER_TICK) else: flood.flow(sea_level, SECONDS_PER_TICK) if tide.surge_starts(tick): var amount: int = tide.surge_damage_at(tick) events.append({"type": "surge", "phase": tide.phase_at(tick), "damage": amount}) if amount > 0: structures.surge(amount, sea_level, ground, events, flood) if tide.stage_at(tick) == Tide.SUDDEN_DEATH and tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1: for player_id: int in _players: var player: SimEntity = entities.find(player_id) if not player.eliminated and player.drop_state == Drop.NONE: player.health = maxi(player.health - Tuning.TIDE_SUDDEN_DEATH_DPS, 0) player.last_cause = SimEntity.CAUSE_TIDE ## Damages a piece. Returns true if this destroyed it; anything it held up collapses. func damage_piece(piece_id: int, amount: int, cause: String = "damage") -> bool: return structures.damage(piece_id, amount, cause, ground, events) ## Tells structures the terrain or fixed solids in `area` changed, so pieces that lost ## their footing can collapse. Returns how many collapsed. func ground_changed(area: AABB) -> int: return structures.ground_changed(area, ground, events) ## Damages a prop. Returns true if this destroyed it; its collision goes at once. func damage_prop(prop: int, amount: int) -> bool: return props.damage(prop, amount) ## 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) buffer.put_u8((1 if entity.on_ground else 0) | (2 if entity.crouching else 0) | (4 if entity.swimming else 0)) buffer.put_32(entity.breath_ticks) buffer.put_32(entity.stamina_ticks) buffer.put_32(entity.drown_ticks) buffer.put_u8(entity.drop_state) buffer.put_data(entity.materials.to_byte_array()) buffer.put_32(entity.action_cooldown) buffer.put_32(entity.armor) buffer.put_32(entity.selected) for array: PackedInt32Array in [entity.slot_items, entity.slot_counts, entity.slot_rounds, entity.slot_tiers, entity.ammo]: buffer.put_data(array.to_byte_array()) buffer.put_32(entity.reload_ticks) buffer.put_32(entity.use_ticks) buffer.put_64(roundi(entity.bloom * 1000.0)) buffer.put_32(entity.prev_buttons) buffer.put_u8(1 if entity.eliminated else 0) buffer.put_64(entity.view_quarters) buffer.put_32(entity.last_attacker) buffer.put_u8(entity.last_cause) buffer.put_32(entity.item) buffer.put_32(entity.item_count) buffer.put_32(entity.item_rounds) buffer.put_32(entity.item_tier) buffer.put_32(entity.owner_id) for value: float in [entity.origin.x, entity.origin.y, entity.origin.z]: buffer.put_64(roundi(value * 1000.0)) 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)) if drop != null: buffer.put_64(drop.began_tick) buffer.put_64(drop.duration_ticks) buffer.put_u8(1 if drop.finished else 0) for value: float in [drop.start.x, drop.start.z, drop.finish.x, drop.finish.z]: buffer.put_64(roundi(value * 1000.0)) buffer.put_64(roundi(sea_level * 1000.0)) buffer.put_32(drown_dps) buffer.put_64(tide.started_tick if tide != null else -1) if tide != null: buffer.put_data(tide.levels.to_byte_array()) if flood != null: flood.write_state(buffer) buffer.put_64(props.count()) buffer.put_data(props.health.to_byte_array()) structures.write_state(buffer) loot.write_state(buffer) var hasher: HashingContext = HashingContext.new() hasher.start(HashingContext.HASH_SHA256) hasher.update(buffer.data_array) return hasher.finish().hex_encode()