diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f12ac54..8f14231 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -120,6 +120,28 @@ sent on a reliable ordered event stream, since a dropped wall is a gameplay lie. | `src/audio/` | Sound playback, music | `src/sim/` (read only) | | `src/app/` | Startup and mode selection | Everything | +## Bots + +Bots live in `src/bots/` and play through the same door as humans: each tick a bot +reads the simulation and returns one `PlayerCommand`, which the server submits like +any other. They never write to the simulation. + +`NavGrid` is the shared map they plan on: one point per 2 m terrain sample, solid +where the ground is a cliff or a solid stands between step and head height, and eight +times as costly where the water is deeper than wading. Path search is Godot's +`AStarGrid2D`. The server builds the grid while the lobby waits (about 0.4 s, next to +the island's own generation) and syncs it every tick before bots think: new solids +block points at once, removed solids are found by a rolling scan within a few ticks, +and points turn wet as the tide and flood reach them. Every change is stamped with its +tick, and each bot checks its remaining path against the stamps twice a second, so a +new wall or rising water across a path makes it plan again. Only one path is planned +per server tick across all bots; others wait their turn. + +`NavBot` follows a path: it steers at the next waypoint, sprints on long dry stretches, +jumps when it stops making progress, and after a few tries marks the point blocked and +plans around it. The brains in M5 choose its goals; until then the server's bots roam +between random reachable places. + ## Terrain The island's heightfield (`Island`, in `src/sim/`) is the only terrain collision, on diff --git a/src/bots/nav_bot.gd b/src/bots/nav_bot.gd new file mode 100644 index 0000000..00a1702 --- /dev/null +++ b/src/bots/nav_bot.gd @@ -0,0 +1,192 @@ +## A bot body that walks to a goal: it plans a path on the shared NavGrid and steers +## along it with the same PlayerCommands a human sends. It plans again when its path +## floods or a wall goes up across it, jumps when it's stuck, and gives up on a point it +## can't get through after a few tries. M5's brains choose the goals; on its own, with +## `roam` set, it wanders between random reachable places. +class_name NavBot +extends RefCounted + +const IDLE: int = 0 +const MOVING: int = 1 +const ARRIVED: int = 2 +const UNREACHABLE: int = 3 +const STATUS_NAMES: Array[String] = ["idle", "moving", "arrived", "unreachable"] +## Roaming goals are this far away at most, in metres. +const ROAM_RANGE: float = 150.0 +## Tries at a random roaming goal before waiting for the next tick. +const ROAM_TRIES: int = 8 + +var player_id: int = 0 +var status: int = IDLE +var goal: Vector3 = Vector3.ZERO +## Within this horizontal distance of the goal counts as there. +var arrive_radius: float = 1.5 +## Pick a new random goal whenever idle, arrived or stuck for good. +var roam: bool = false +## The planned grid points, and the one being walked to. +var path: Array[Vector2i] = [] +var path_index: int = 0 +## How many times a path has been planned, for tests and logs. +var plans: int = 0 + +var _needs_plan: bool = false +var _planned_tick: int = -1 +var _best_distance: float = INF +var _stuck_ticks: int = 0 +var _stuck_tries: int = 0 +var _jump_next: bool = false +var _leap_tick: int = -1 + + +func _init(id: int) -> void: + player_id = id + + +func set_goal(target: Vector3) -> void: + goal = target + status = MOVING + path.clear() + path_index = 0 + _needs_plan = true + _reset_stuck() + + +func clear_goal() -> void: + status = IDLE + path.clear() + _needs_plan = false + + +func status_name() -> String: + return STATUS_NAMES[status] + + +## Returns this bot's command for `sim.tick`. The grid must be synced for this tick. +func think(sim: Simulation, grid: NavGrid) -> PlayerCommand: + var player: SimEntity = sim.entities.find(player_id) + if player == null or player.eliminated: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0) + if roam and status != MOVING: + _pick_roam_goal(sim, grid, player) + if player.drop_state == Drop.ABOARD: + return _ride(sim, player) + if player.drop_state != Drop.NONE: + # Gliding down: head for the goal. + return _steer(sim, player, goal, 0) + if status != MOVING: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, deg_to_rad(player.yaw * 360.0 / PlayerCommand.YAW_STEPS), 0.0) + if not _needs_plan and (sim.tick + player_id) % Tuning.BOT_PATH_CHECK_TICKS == 0: + if not grid.path_still_valid(path, path_index, _planned_tick): + _needs_plan = true + if _needs_plan and grid.can_plan(): + _plan(sim, grid, player) + if status != MOVING: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0) + var horizontal: Vector2 = Vector2(goal.x - player.position.x, goal.z - player.position.z) + if horizontal.length() <= arrive_radius: + status = ARRIVED + path.clear() + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, atan2(horizontal.x, horizontal.y), 0.0) + var target: Vector3 = goal + if not path.is_empty(): + _advance_waypoints(grid, player) + target = goal if path_index >= path.size() - 1 else grid.position_of(path[path_index]) + _check_stuck(sim, grid, player, target) + var buttons: int = 0 + if _jump_next: + buttons |= PlayerCommand.BUTTON_JUMP + _jump_next = false + if not player.swimming and horizontal.length() > 8.0: + buttons |= PlayerCommand.BUTTON_SPRINT + return _steer(sim, player, target, buttons) + + +func _plan(sim: Simulation, grid: NavGrid, player: SimEntity) -> void: + _needs_plan = false + _planned_tick = sim.tick + plans += 1 + path = grid.find_path(player.position, goal) + path_index = 0 + _reset_stuck() + if path.is_empty(): + status = UNREACHABLE + + +## Skips waypoints already reached, or that the bot is already nearer the next one than. +func _advance_waypoints(grid: NavGrid, player: SimEntity) -> void: + var feet: Vector2 = Vector2(player.position.x, player.position.z) + while path_index < path.size() - 1: + var here: Vector3 = grid.position_of(path[path_index]) + var reached: bool = feet.distance_to(Vector2(here.x, here.z)) <= Tuning.BOT_WAYPOINT_RADIUS + if not reached: + break + path_index += 1 + _reset_stuck() + + +## Watches progress toward the current waypoint: jump when stalled, and after a few +## stalled jumps mark the waypoint blocked and plan around it. +func _check_stuck(sim: Simulation, grid: NavGrid, player: SimEntity, target: Vector3) -> void: + var distance: float = Vector2(target.x - player.position.x, target.z - player.position.z).length() + if distance < _best_distance - Tuning.BOT_STUCK_PROGRESS: + _best_distance = distance + _stuck_ticks = 0 + return + _stuck_ticks += 1 + if _stuck_ticks < Tuning.BOT_STUCK_TICKS: + return + _stuck_ticks = 0 + _stuck_tries += 1 + _jump_next = true + if _stuck_tries >= Tuning.BOT_STUCK_REPATHS and not path.is_empty(): + var point: Vector2i = path[mini(path_index, path.size() - 1)] + if grid.point_of(player.position) != point: + grid.mark_blocked(point, sim.tick) + _needs_plan = true + _stuck_tries = 0 + + +func _reset_stuck() -> void: + _best_distance = INF + _stuck_ticks = 0 + _stuck_tries = 0 + + +func _steer(sim: Simulation, player: SimEntity, target: Vector3, buttons: int) -> PlayerCommand: + var to: Vector2 = Vector2(target.x - player.position.x, target.z - player.position.z) + if to.length_squared() < 0.0001: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, buttons) + return PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), atan2(to.x, to.y), 0.0, buttons) + + +## Aboard the barge: leap once the goal is within gliding reach, or at a time set by +## the player ID, whichever comes first. The end of the route puts everyone off anyway. +func _ride(sim: Simulation, player: SimEntity) -> PlayerCommand: + if _leap_tick < 0 and sim.drop != null: + _leap_tick = sim.drop.began_tick + Tuning.TICK_RATE_HZ * 2 + (player_id * 53) % (Tuning.TICK_RATE_HZ * 20) + var leap: bool = sim.tick >= _leap_tick + if status == MOVING: + var gap: float = Vector2(goal.x - player.position.x, goal.z - player.position.z).length() + leap = leap or gap < 0.6 * (player.position.y - goal.y) + var buttons: int = PlayerCommand.BUTTON_JUMP if leap else 0 + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, buttons) + + +## A random open dry point within ROAM_RANGE that a path reaches, from the "bots" +## stream. Plans the path at once, so it uses the tick's planning budget. +func _pick_roam_goal(sim: Simulation, grid: NavGrid, player: SimEntity) -> void: + if not grid.can_plan(): + return + var rng: RandomNumberGenerator = sim.rng.stream("bots") + var centre: Vector3 = player.position + if player.drop_state == Drop.ABOARD: + centre = Vector3(Tuning.WORLD_SIZE_METRES * 0.5, 0.0, Tuning.WORLD_SIZE_METRES * 0.5) + for _try: int in ROAM_TRIES: + var angle: float = rng.randf() * TAU + var reach: float = rng.randf_range(20.0, ROAM_RANGE) + var point: Vector2i = grid.point_of(centre + Vector3(cos(angle), 0.0, sin(angle)) * reach) + if grid.is_open(point) and grid.wet[grid.index_of(point)] == 0: + set_goal(grid.position_of(point)) + if player.drop_state == Drop.NONE: + _plan(sim, grid, player) + return diff --git a/src/bots/nav_bot.gd.uid b/src/bots/nav_bot.gd.uid new file mode 100644 index 0000000..784cb49 --- /dev/null +++ b/src/bots/nav_bot.gd.uid @@ -0,0 +1 @@ +uid://b7uhmvb00i3uu diff --git a/src/bots/nav_grid.gd b/src/bots/nav_grid.gd new file mode 100644 index 0000000..9a1c375 --- /dev/null +++ b/src/bots/nav_grid.gd @@ -0,0 +1,341 @@ +## The grid bots plan paths on: one point per terrain sample, 2 m apart, built from the +## island's heightfield and solids and kept in step with the match. Points become solid +## where the ground is a cliff or a solid stands in the way, and cost more where the +## water is too deep to wade. Flooding, new walls and broken props change points while +## the match runs; each change is stamped with the tick it happened, so bots can tell +## when their path crosses something new and plan again. +## +## The path search itself is Godot's AStarGrid2D, which is deterministic and fast. It +## only reads the simulation; it never changes it. +class_name NavGrid +extends RefCounted + +const CELL: float = Tuning.BOT_NAV_CELL_METRES +## How many solids to re-check for removal each tick: every solid is seen again within +## a few seconds, without a spike. +const SOLID_SCAN_PER_TICK: int = 256 + +## Points per side. +var side: int = 0 +## Terrain height at each point, row-major (index = z * side + x). +var heights: PackedFloat32Array = PackedFloat32Array() +## 1 where the terrain itself is impassable on foot (a cliff or too steep). +var steep: PackedByteArray = PackedByteArray() +## How many solids block each point. +var blocked: PackedInt32Array = PackedInt32Array() +## 1 where the water over the point is deeper than wading depth. +var wet: PackedByteArray = PackedByteArray() +## The tick each point last changed, or -1. +var changed_tick: PackedInt32Array = PackedInt32Array() +## Paths planned so far this tick, for the per-tick limit. +var paths_this_tick: int = 0 +var astar: AStarGrid2D = AStarGrid2D.new() + +## Solid ID -> the points it blocks, for every solid that blocks any. +var _solid_points: Dictionary = {} +## How many of ground.solids have been seen. +var _solids_seen: int = 0 +var _scan_at: int = 0 +## Point indices ordered by height, and how far up them the water has been checked. +var _by_height: PackedInt32Array = PackedInt32Array() +var _wet_checked: int = 0 +## Points under the sea level that the flood hadn't reached when last checked. +var _dry_below: Dictionary = {} +var _flooded_seen: int = -1 +var _last_tick: int = -1 + + +## Builds the grid for a simulation's ground, as it is now. +static func build(sim: Simulation) -> NavGrid: + var grid: NavGrid = NavGrid.new() + grid._build(sim) + return grid + + +func _build(sim: Simulation) -> void: + var ground: SimGround = sim.ground + side = roundi(Tuning.WORLD_SIZE_METRES / CELL) + 1 + var count: int = side * side + heights.resize(count) + if is_equal_approx(ground.cell, CELL) and ground.samples == side: + heights = ground.heights.duplicate() + else: + for z: int in side: + for x: int in side: + heights[z * side + x] = ground.terrain_height(x * CELL, z * CELL) + steep.resize(count) + steep.fill(0) + blocked.resize(count) + blocked.fill(0) + wet.resize(count) + wet.fill(0) + changed_tick.resize(count) + changed_tick.fill(-1) + astar.region = Rect2i(0, 0, side, side) + astar.cell_size = Vector2(CELL, CELL) + astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_ONLY_IF_NO_OBSTACLES + astar.default_compute_heuristic = AStarGrid2D.HEURISTIC_OCTILE + astar.default_estimate_heuristic = AStarGrid2D.HEURISTIC_OCTILE + astar.update() + _mark_steep() + _solids_seen = 0 + _take_new_solids(ground, -1) + _by_height = _order_by_height() + _update_water(sim, -1) + for index: int in count: + if steep[index] != 0 or blocked[index] != 0 or wet[index] != 0: + _apply(index, -1) + + +## Brings the grid up to date with the simulation: new and removed solids and the +## water. Call once per tick, before bots plan; repeated calls in a tick do nothing. +func sync(sim: Simulation) -> void: + if sim.tick == _last_tick: + return + _last_tick = sim.tick + paths_this_tick = 0 + _take_new_solids(sim.ground, sim.tick) + _scan_removed_solids(sim.ground, sim.tick) + _update_water(sim, sim.tick) + + +## The grid point nearest a world position. +func point_of(position: Vector3) -> Vector2i: + return Vector2i(clampi(roundi(position.x / CELL), 0, side - 1), clampi(roundi(position.z / CELL), 0, side - 1)) + + +func index_of(point: Vector2i) -> int: + return point.y * side + point.x + + +## The world position of a grid point, on the terrain. +func position_of(point: Vector2i) -> Vector3: + return Vector3(point.x * CELL, heights[index_of(point)], point.y * CELL) + + +func is_open(point: Vector2i) -> bool: + return astar.is_in_boundsv(point) and not astar.is_point_solid(point) + + +## The open point nearest `point`, searching outward up to `radius` points, or (-1, -1). +func nearest_open(point: Vector2i, radius: int = 4) -> Vector2i: + if is_open(point): + return point + for ring: int in range(1, radius + 1): + for dz: int in range(-ring, ring + 1): + for dx: int in range(-ring, ring + 1): + if maxi(absi(dx), absi(dz)) != ring: + continue + var candidate: Vector2i = point + Vector2i(dx, dz) + if is_open(candidate): + return candidate + return Vector2i(-1, -1) + + +## Whether this tick's planning budget has room for another path. +func can_plan() -> bool: + return paths_this_tick < Tuning.BOT_NAV_PATHS_PER_TICK + + +## Plans a path of grid points from one world position to another. Empty if either end +## has no open point nearby or no route joins them; with `partial`, the path to the +## reachable point closest to the goal instead. Counts against the tick's budget. +func find_path(from: Vector3, to: Vector3, partial: bool = false) -> Array[Vector2i]: + paths_this_tick += 1 + var start: Vector2i = nearest_open(point_of(from)) + var goal: Vector2i = nearest_open(point_of(to)) + if start.x < 0 or goal.x < 0: + return [] + return astar.get_id_path(start, goal, partial) + + +## True if no point of `path` from `from_index` on has changed since `since_tick`. +func path_still_valid(path: Array[Vector2i], from_index: int, since_tick: int) -> bool: + for at: int in range(from_index, path.size()): + var point: Vector2i = path[at] + if changed_tick[index_of(point)] > since_tick and astar.is_point_solid(point): + return false + if changed_tick[index_of(point)] > since_tick and wet[index_of(point)] != 0: + return false + return true + + +## Marks a point as blocked by something the grid can't see (a bot found it couldn't +## get through). Counts as one more blocking solid. +func mark_blocked(point: Vector2i, tick: int) -> void: + if not astar.is_in_boundsv(point): + return + var index: int = index_of(point) + blocked[index] += 1 + _apply(index, tick) + + +func _mark_steep() -> void: + var max_rise: float = Tuning.BOT_NAV_MAX_RISE + var min_normal_y: float = cos(deg_to_rad(Tuning.MAX_SLOPE_DEGREES)) + for z: int in side: + var row: int = z * side + for x: int in side: + var index: int = row + x + var h: float = heights[index] + var too_steep: bool = false + if x + 1 < side and absf(heights[index + 1] - h) > max_rise: + too_steep = true + steep[index + 1] = 1 + if z + 1 < side and absf(heights[index + side] - h) > max_rise: + too_steep = true + steep[index + side] = 1 + if not too_steep and x > 0 and x + 1 < side and z > 0 and z + 1 < side: + var dx: float = heights[index + 1] - heights[index - 1] + var dz: float = heights[index + side] - heights[index - side] + var normal_y: float = 2.0 * CELL / sqrt(dx * dx + dz * dz + 4.0 * CELL * CELL) + too_steep = normal_y < min_normal_y + if too_steep: + steep[index] = 1 + + +## Points a solid blocks: those whose central square metre the solid, widened by a +## player's radius, overlaps, where the solid stands between step height and head +## height above the terrain. +func _points_of_solid(box: AABB) -> PackedInt32Array: + var points: PackedInt32Array = PackedInt32Array() + var grow: float = Tuning.PLAYER_RADIUS + 0.5 + var low_x: int = maxi(ceili((box.position.x - grow) / CELL), 0) + var high_x: int = mini(floori((box.end.x + grow) / CELL), side - 1) + var low_z: int = maxi(ceili((box.position.z - grow) / CELL), 0) + var high_z: int = mini(floori((box.end.z + grow) / CELL), side - 1) + for z: int in range(low_z, high_z + 1): + for x: int in range(low_x, high_x + 1): + var index: int = z * side + x + var h: float = heights[index] + if box.end.y > h + Tuning.STEP_HEIGHT and box.position.y < h + Tuning.PLAYER_HEIGHT: + points.append(index) + return points + + +func _take_new_solids(ground: SimGround, tick: int) -> void: + while _solids_seen < ground.solids.size(): + var id: int = _solids_seen + _solids_seen += 1 + var box: AABB = ground.solids[id] + if box == SimGround.REMOVED: + continue + var points: PackedInt32Array = _points_of_solid(box) + if points.is_empty(): + continue + _solid_points[id] = points + for index: int in points: + blocked[index] += 1 + if tick >= 0: + _apply(index, tick) + + +## Re-checks a slice of the blocking solids each tick and frees the points of any that +## are gone. +func _scan_removed_solids(ground: SimGround, tick: int) -> void: + var ids: Array = _solid_points.keys() + if ids.is_empty(): + return + var count: int = mini(SOLID_SCAN_PER_TICK, ids.size()) + for _step: int in count: + _scan_at = _scan_at % ids.size() + var id: int = ids[_scan_at] + _scan_at += 1 + if ground.solids[id] != SimGround.REMOVED: + continue + for index: int in _solid_points[id]: + blocked[index] -= 1 + _apply(index, tick) + _solid_points.erase(id) + + +## Removes a solid's blocking at once, rather than waiting for the scan. For callers +## that know a solid just went (a broken wall in front of a bot). +func solid_removed(id: int, tick: int) -> void: + if not _solid_points.has(id): + return + for index: int in _solid_points[id]: + blocked[index] -= 1 + _apply(index, tick) + _solid_points.erase(id) + + +func _order_by_height() -> PackedInt32Array: + # A bucket sort on 5 cm steps: the order within a bucket doesn't matter, because + # water is checked against the bucket's whole range a tick at most early. + var low: float = INF + var high: float = -INF + for h: float in heights: + low = minf(low, h) + high = maxf(high, h) + var step: float = 0.05 + var buckets: int = floori((high - low) / step) + 1 + var counts: PackedInt32Array = PackedInt32Array() + counts.resize(buckets + 1) + counts.fill(0) + var bucket_of: PackedInt32Array = PackedInt32Array() + bucket_of.resize(heights.size()) + for index: int in heights.size(): + var bucket: int = floori((heights[index] - low) / step) + bucket_of[index] = bucket + counts[bucket + 1] += 1 + for bucket: int in buckets: + counts[bucket + 1] += counts[bucket] + var order: PackedInt32Array = PackedInt32Array() + order.resize(heights.size()) + for index: int in heights.size(): + var bucket: int = bucket_of[index] + order[counts[bucket]] = index + counts[bucket] += 1 + return order + + +## Marks points wet as the sea rises over them: wherever the flood reaches and the +## water is deeper than wading depth, which slows a walker and soon means swimming. Points the flood doesn't reach yet (behind a +## breakwater, in a basin) are re-checked whenever the flood spreads. +func _update_water(sim: Simulation, tick: int) -> void: + var limit: float = sim.sea_level - Tuning.WADE_DEPTH + while _wet_checked < _by_height.size() and heights[_by_height[_wet_checked]] < limit: + var index: int = _by_height[_wet_checked] + _wet_checked += 1 + if _flood_reaches(sim, index): + _set_wet(index, tick) + else: + _dry_below[index] = true + if sim.flood == null or _dry_below.is_empty(): + return + var flooded: int = sim.flood.flooded_count() if tick % Tuning.TICK_RATE_HZ == 0 or tick < 0 else _flooded_seen + if flooded == _flooded_seen: + return + _flooded_seen = flooded + for index: int in _dry_below.keys(): + if _flood_reaches(sim, index): + _dry_below.erase(index) + _set_wet(index, tick) + + +func _flood_reaches(sim: Simulation, index: int) -> bool: + if sim.flood == null: + return true + return sim.flood.is_flooded((index % side) * CELL, (index / side) * CELL) + + +func _set_wet(index: int, tick: int) -> void: + if wet[index] != 0: + return + wet[index] = 1 + if tick >= 0: + _apply(index, tick) + + +## Pushes a point's state into the path search and stamps the change. +func _apply(index: int, tick: int) -> void: + var point: Vector2i = Vector2i(index % side, index / side) + var solid: bool = blocked[index] > 0 or (steep[index] != 0 and wet[index] == 0) + if solid != astar.is_point_solid(point): + astar.set_point_solid(point, solid) + var weight: float = Tuning.BOT_NAV_WATER_WEIGHT if wet[index] != 0 else 1.0 + if not is_equal_approx(weight, astar.get_point_weight_scale(point)): + astar.set_point_weight_scale(point, weight) + if tick >= 0: + changed_tick[index] = tick diff --git a/src/bots/nav_grid.gd.uid b/src/bots/nav_grid.gd.uid new file mode 100644 index 0000000..7269a41 --- /dev/null +++ b/src/bots/nav_grid.gd.uid @@ -0,0 +1 @@ +uid://v6gxn1p82fkf diff --git a/src/bots/wander_bot.gd b/src/bots/wander_bot.gd deleted file mode 100644 index 10029f9..0000000 --- a/src/bots/wander_bot.gd +++ /dev/null @@ -1,33 +0,0 @@ -## A placeholder bot that walks in a seeded direction and turns now and then. -## It exists so headless servers and smoke runs carry realistic load before the real -## bot brains arrive in v0.4. Like every bot, it only produces PlayerCommands. -class_name WanderBot -extends RefCounted - -## How often, in ticks, the bot may pick a new heading. -const TURN_INTERVAL_TICKS: int = 45 - -var player_id: int = 0 - -var _yaw: float = 0.0 -var _sprint: bool = false - - -func _init(id: int) -> void: - player_id = id - - -## Returns this bot's command for `sim.tick`. Draws only from the "bots" stream. -func think(sim: Simulation) -> PlayerCommand: - var rng: RandomNumberGenerator = sim.rng.stream("bots") - if sim.tick % TURN_INTERVAL_TICKS == 0: - _yaw = rng.randf() * TAU - _sprint = rng.randf() < 0.3 - var buttons: int = PlayerCommand.BUTTON_SPRINT if _sprint else 0 - # Leap from the barge at a time fixed by the player ID, between 2 and 22 seconds in. - var player: SimEntity = sim.entities.find(player_id) - if player != null and player.drop_state == Drop.ABOARD and sim.drop != null: - var leap_tick: int = sim.drop.began_tick + Tuning.TICK_RATE_HZ * 2 + (player_id * 53) % (Tuning.TICK_RATE_HZ * 20) - if sim.tick >= leap_tick: - buttons = PlayerCommand.BUTTON_JUMP - return PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), _yaw, 0.0, buttons) diff --git a/src/bots/wander_bot.gd.uid b/src/bots/wander_bot.gd.uid deleted file mode 100644 index 3686436..0000000 --- a/src/bots/wander_bot.gd.uid +++ /dev/null @@ -1 +0,0 @@ -uid://cfc5ckk0du602 diff --git a/src/server/server_loop.gd b/src/server/server_loop.gd index e0f8e89..6d6ec43 100644 --- a/src/server/server_loop.gd +++ b/src/server/server_loop.gd @@ -14,7 +14,9 @@ var sim: Simulation: return match_flow.sim ## Entity IDs of everyone in the current match, humans first. var player_ids: Array[int] = [] -var bots: Array[WanderBot] = [] +var bots: Array[NavBot] = [] +## The current or next match's navigation grid, built while the lobby waits. +var nav: NavGrid = null ## Wall-clock duration of every tick run, in microseconds. var tick_usec: PackedInt64Array = PackedInt64Array() ## Server ticks run, across every match. @@ -32,6 +34,7 @@ func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRule # With only bots there's nobody to wait for, so the lobby starts with no one in it. rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1 match_flow = Match.new(match_seed, rules) + nav = NavGrid.build(match_flow.sim) for handle: int in range(1, human_players + 1): match_flow.join(handle) if rules.lobby_ticks == 0 and rules.countdown_ticks == 0: @@ -43,8 +46,9 @@ func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRule func run_tick() -> void: var started: int = Time.get_ticks_usec() if match_flow.in_match(): - for bot: WanderBot in bots: - sim.submit_command(bot.player_id, bot.think(sim)) + nav.sync(sim) + for bot: NavBot in bots: + sim.submit_command(bot.player_id, bot.think(sim, nav)) _advance() ticks += 1 tick_usec.append(Time.get_ticks_usec() - started) @@ -58,6 +62,8 @@ func _advance() -> void: elif event["type"] == "phase" and event["to"] == "lobby": player_ids.clear() bots.clear() + if event["from"] == "results": + nav = NavGrid.build(match_flow.sim) func _track_players() -> void: @@ -67,7 +73,9 @@ func _track_players() -> void: var entity_id: int = match_flow.entity_of[handle] player_ids.append(entity_id) if match_flow.bot_handles.has(handle): - bots.append(WanderBot.new(entity_id)) + var bot: NavBot = NavBot.new(entity_id) + bot.roam = true + bots.append(bot) ## Timing statistics over every tick run so far, in microseconds. diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index 813dca3..a0c5ce2 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -203,6 +203,26 @@ const TIDE_SUDDEN_DEATH_DPS: int = 5 ## line up with cell edges. const FLOOD_CELL_METRES: float = 4.0 +# Bot navigation. Bots path over a grid of terrain samples and steer along it with the +# same commands players send. +## Spacing of the navigation grid, in metres. Matches the terrain heightfield. +const BOT_NAV_CELL_METRES: float = 2.0 +## Neighbouring nav points further apart in height than this are a cliff, not a slope. +const BOT_NAV_MAX_RISE: float = 1.9 +## Path cost multiplier for water too deep to wade: bots swim only when they must. +const BOT_NAV_WATER_WEIGHT: float = 8.0 +## Most paths the shared grid plans in one server tick; other requests wait their turn. +const BOT_NAV_PATHS_PER_TICK: int = 1 +## A bot moves on to the next waypoint within this horizontal distance of it. +const BOT_WAYPOINT_RADIUS: float = 1.3 +## A bot that gains less than this toward its waypoint in BOT_STUCK_TICKS jumps, and +## after BOT_STUCK_REPATHS tries it marks the waypoint blocked and plans again. +const BOT_STUCK_PROGRESS: float = 0.5 +const BOT_STUCK_TICKS: int = 20 +const BOT_STUCK_REPATHS: int = 3 +## Each bot re-checks its remaining path against grid changes this often, in ticks. +const BOT_PATH_CHECK_TICKS: int = 15 + # Building const GRID_CELL_METRES: float = 4.0 ## The most of each material a player can carry. diff --git a/test/bots/nav_sweep.gd b/test/bots/nav_sweep.gd new file mode 100644 index 0000000..c651836 --- /dev/null +++ b/test/bots/nav_sweep.gd @@ -0,0 +1,57 @@ +## Walks a bot to random reachable targets on many islands and counts how many it +## reaches. Shared by the test and `make nav-sweep`. +class_name NavSweep +extends RefCounted + +## Results: {"trials", "reached", "failures": [{"seed", "from", "to", "status", "left"}]} +static func run(seeds: Array[int], targets_per_seed: int) -> Dictionary: + var trials: int = 0 + var reached: int = 0 + var failures: Array[Dictionary] = [] + for seed_value: int in seeds: + var sim: Simulation = Simulation.new(seed_value) + var grid: NavGrid = NavGrid.build(sim) + var player_id: int = sim.add_player() + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = seed_value + for _target: int in targets_per_seed: + var player: SimEntity = sim.entities.find(player_id) + var goal: Vector3 = _reachable_goal(grid, player.position, rng) + if goal.y <= -999.0: + continue + trials += 1 + var bot: NavBot = NavBot.new(player_id) + bot.set_goal(goal) + var start: Vector3 = player.position + var limit: int = roundi((start.distance_to(goal) * 2.5 / Tuning.WALK_SPEED + 15.0) * Tuning.TICK_RATE_HZ) + for _tick: int in limit: + grid.sync(sim) + sim.submit_command(player_id, bot.think(sim, grid)) + sim.step() + if bot.status != NavBot.MOVING: + break + var left: float = Vector2(goal.x - player.position.x, goal.z - player.position.z).length() + if bot.status == NavBot.ARRIVED: + reached += 1 + else: + failures.append({"seed": seed_value, "from": start, "to": goal, "status": bot.status_name(), "left": left, "plans": bot.plans}) + # Start the next trial from wherever this one ended, back on its feet. + player.health = Tuning.PLAYER_MAX_HEALTH + Water.reset(player) + return {"trials": trials, "reached": reached, "failures": failures} + + +## A dry open point 40 to 160 m away with a complete path from `from`, or y = -1000. +static func _reachable_goal(grid: NavGrid, from: Vector3, rng: RandomNumberGenerator) -> Vector3: + for _try: int in 40: + var angle: float = rng.randf() * TAU + var reach: float = rng.randf_range(40.0, 160.0) + var point: Vector2i = grid.point_of(from + Vector3(cos(angle), 0.0, sin(angle)) * reach) + if not grid.is_open(point) or grid.wet[grid.index_of(point)] != 0: + continue + var goal: Vector3 = grid.position_of(point) + if goal.y <= Tuning.ISLAND_BEACH_TOP: + continue + if not grid.find_path(from, goal).is_empty(): + return goal + return Vector3(0.0, -1000.0, 0.0) diff --git a/test/bots/nav_sweep.gd.uid b/test/bots/nav_sweep.gd.uid new file mode 100644 index 0000000..2bd44db --- /dev/null +++ b/test/bots/nav_sweep.gd.uid @@ -0,0 +1 @@ +uid://bx7pvcewg5whp diff --git a/test/bots/test_nav.gd b/test/bots/test_nav.gd new file mode 100644 index 0000000..14af3d3 --- /dev/null +++ b/test/bots/test_nav.gd @@ -0,0 +1,214 @@ +extends TestCase + +## Bot navigation from issue M4: bots reach random reachable places on 50 islands, +## plan again when water or new walls cross their path, and 23 of them stay inside the +## server's tick budget. Bots only ever send PlayerCommands. + +const FLOOR: float = 8.0 +## Building level whose base is FLOOR. +const LEVEL: int = 4 +const START: Vector3 = Vector3(100.0, FLOOR, 100.0) +const GOAL: Vector3 = Vector3(100.0, FLOOR, 170.0) + + +func test_bots_reach_random_reachable_targets_on_50_islands() -> void: + var seeds: Array[int] = [] + for seed_value: int in range(100, 150): + seeds.append(seed_value) + var result: Dictionary = NavSweep.run(seeds, 2) + var trials: int = result["trials"] + var reached: int = result["reached"] + assert_true(trials >= 95, "found reachable targets for %d trials" % trials) + var rate: float = float(reached) / maxi(trials, 1) + for failure: Dictionary in result["failures"]: + print(" nav miss: %s" % failure) + assert_true(rate >= 0.95, "reached %d of %d (%.1f%%)" % [reached, trials, rate * 100.0]) + + +## A flat world with one player at START and a bot walking it to `goal`. +func _flat() -> Simulation: + var sim: Simulation = Simulation.new(7, SimGround.flat(FLOOR)) + var player: SimEntity = sim.entities.find(sim.add_player()) + player.position = START + player.on_ground = true + return sim + + +## Steps the bot until it stops moving or `limit` ticks pass, calling `each` (if +## given) with the tick number before every step. +func _walk(sim: Simulation, grid: NavGrid, bot: NavBot, limit: int, each: Callable = Callable()) -> void: + for index: int in limit: + if each.is_valid(): + each.call(index) + grid.sync(sim) + var command: PlayerCommand = bot.think(sim, grid) + assert_true(command is PlayerCommand) + sim.submit_command(bot.player_id, command) + sim.step() + if bot.status != NavBot.MOVING: + return + + +func test_a_bot_walks_straight_across_open_ground() -> void: + var sim: Simulation = _flat() + var grid: NavGrid = NavGrid.build(sim) + var bot: NavBot = NavBot.new(1) + bot.set_goal(GOAL) + _walk(sim, grid, bot, 30 * 30) + assert_eq(bot.status_name(), "arrived") + assert_eq(bot.plans, 1) + var feet: Vector3 = sim.entities.find(1).position + assert_true(Vector2(feet.x - GOAL.x, feet.z - GOAL.z).length() <= bot.arrive_radius) + + +func test_a_new_wall_across_the_path_triggers_a_new_path_around_it() -> void: + var sim: Simulation = _flat() + var grid: NavGrid = NavGrid.build(sim) + var bot: NavBot = NavBot.new(1) + bot.set_goal(GOAL) + # Lambdas capture locals by value, so the first path goes into a shared array. + var first_path: Array[Vector2i] = [] + var build_wall: Callable = func(index: int) -> void: + if index == 1: + first_path.append_array(bot.path) + if index == 20: + # A row of real wooden walls across the way, 30 m ahead: x 80 to 120 m, z 136 m. + for x: int in range(20, 30): + sim.structures.add(StructureSet.WALL, 0, Vector4i(x, LEVEL, 34, StructureSet.SLOT_WALL_Z), 0, 0, sim.tick, sim.ground) + _walk(sim, grid, bot, 60 * 30, build_wall) + assert_eq(bot.status_name(), "arrived") + assert_true(bot.plans >= 2, "planned again after the wall went up (%d plans)" % bot.plans) + var crosses: bool = false + for point: Vector2i in first_path: + if point.x * 2.0 > 80.0 and point.x * 2.0 < 120.0 and point.y * 2.0 == 136.0: + crosses = true + assert_true(crosses, "the first path went straight through where the wall is") + for point: Vector2i in bot.path: + var x: float = point.x * NavGrid.CELL + var z: float = point.y * NavGrid.CELL + assert_false(x > 79.0 and x < 121.0 and absf(z - 136.0) < 1.0, "the new path avoids the wall at %s" % point) + + +func test_a_broken_wall_opens_the_way_again() -> void: + var sim: Simulation = _flat() + var wall: StructureSet.Piece = sim.structures.add(StructureSet.WALL, 0, Vector4i(25, LEVEL, 34, StructureSet.SLOT_WALL_Z), 0, 0, 0, sim.ground) + var grid: NavGrid = NavGrid.build(sim) + var blocked_point: Vector2i = grid.point_of(Vector3(102.0, FLOOR, 136.0)) + assert_false(grid.is_open(blocked_point), "the wall blocks the grid") + sim.structures.remove(wall.id, sim.ground) + for _index: int in 40: + sim.step() + grid.sync(sim) + assert_true(grid.is_open(blocked_point), "the scan frees points once the wall is gone") + assert_true(grid.changed_tick[grid.index_of(blocked_point)] > 0) + + +## Ground at 3 m with a sunken strip, x 60 to 140 m and z 124 to 136 m, whose floor is +## level with the starting sea. Its banks slope over 6 m, so it's walkable while the +## sea is low. +func _strip_ground() -> SimGround: + var side: int = roundi(Tuning.WORLD_SIZE_METRES / 2.0) + 1 + var values: PackedFloat32Array = PackedFloat32Array() + values.resize(side * side) + for z: int in side: + for x: int in side: + var wx: float = x * 2.0 + var wz: float = z * 2.0 + var dx: float = maxf(maxf(60.0 - wx, wx - 140.0), 0.0) + var dz: float = maxf(maxf(124.0 - wz, wz - 136.0), 0.0) + var distance: float = sqrt(dx * dx + dz * dz) + values[z * side + x] = lerpf(0.0, 3.0, clampf(distance / 6.0, 0.0, 1.0)) + return SimGround.from_heights(values, side, 2.0) + + +func test_rising_water_across_the_path_triggers_a_new_path_around_it() -> void: + var sim: Simulation = Simulation.new(7, _strip_ground()) + var player: SimEntity = sim.entities.find(sim.add_player()) + player.position = Vector3(100.0, 3.0, 100.0) + player.on_ground = true + var grid: NavGrid = NavGrid.build(sim) + var bot: NavBot = NavBot.new(1) + var goal: Vector3 = Vector3(100.0, 3.0, 160.0) + bot.set_goal(goal) + var swam: Array[bool] = [false] + var crossed_strip: Array[bool] = [false] + var flood: Callable = func(index: int) -> void: + if index == 1: + for point: Vector2i in bot.path: + if point.y * 2.0 > 124.0 and point.y * 2.0 < 136.0 and point.x * 2.0 > 60.0 and point.x * 2.0 < 140.0: + crossed_strip[0] = true + if index == 15: + sim.set_sea_level(2.0) + if player.swimming: + swam[0] = true + _walk(sim, grid, bot, 90 * 30, flood) + assert_true(crossed_strip[0], "the first path crossed the dry strip") + assert_eq(bot.status_name(), "arrived") + assert_true(bot.plans >= 2, "planned again when the strip flooded") + assert_false(swam[0], "walked around the water instead of swimming") + for point: Vector2i in bot.path: + assert_eq(grid.wet[grid.index_of(point)], 0, "the new path stays dry") + + +func test_with_no_dry_way_round_the_bot_swims() -> void: + # The same strip, but the sea rises over everything around it too: the only way is + # through water, and the bot takes it. + var sim: Simulation = Simulation.new(7, _strip_ground()) + var player: SimEntity = sim.entities.find(sim.add_player()) + player.position = Vector3(100.0, 3.0, 100.0) + player.on_ground = true + var grid: NavGrid = NavGrid.build(sim) + sim.set_sea_level(4.5) + grid.sync(sim) + var bot: NavBot = NavBot.new(1) + bot.set_goal(Vector3(100.0, 3.0, 130.0)) + _walk(sim, grid, bot, 60 * 30) + assert_eq(bot.status_name(), "arrived") + + +func test_a_goal_inside_a_solid_block_is_unreachable() -> void: + var sim: Simulation = _flat() + # A closed box of solid rock around the goal. + sim.ground.add_solid(AABB(Vector3(90.0, FLOOR - 1.0, 150.0), Vector3(20.0, 10.0, 20.0))) + var grid: NavGrid = NavGrid.build(sim) + var bot: NavBot = NavBot.new(1) + bot.set_goal(Vector3(100.0, FLOOR, 160.0)) + _walk(sim, grid, bot, 30) + assert_eq(bot.status_name(), "unreachable") + + +func test_planning_is_limited_per_tick() -> void: + var sim: Simulation = _flat() + for _index: int in 3: + var other: SimEntity = sim.entities.find(sim.add_player()) + other.position = START + other.on_ground = true + var grid: NavGrid = NavGrid.build(sim) + grid.sync(sim) + var bots: Array[NavBot] = [] + for id: int in [1, 2, 3, 4]: + var bot: NavBot = NavBot.new(id) + bot.set_goal(GOAL) + bots.append(bot) + bot.think(sim, grid) + var planned: int = 0 + for bot: NavBot in bots: + planned += bot.plans + assert_eq(planned, Tuning.BOT_NAV_PATHS_PER_TICK, "one tick plans at most the budget") + + +func test_23_bots_stay_within_the_tick_budget_and_get_somewhere() -> void: + var loop: ServerLoop = ServerLoop.new(20261111, 1, 23) + var ticks: int = 75 * Tuning.TICK_RATE_HZ + for _index: int in ticks: + loop.run_tick() + var stats: Dictionary = loop.timing_stats() + print(" 23 bots, %d ticks: p50 %d us, p99 %d us, max %d us, %d over budget" % [stats["ticks"], stats["p50_us"], stats["p99_us"], stats["max_us"], stats["over_budget"]]) + assert_true(stats["p99_us"] < ServerLoop.TICK_BUDGET_USEC, "p99 tick under budget") + assert_true(stats["over_budget"] <= ticks / 200, "at most 0.5% of ticks over budget (a busy shared host)") + var walking: int = 0 + for bot: NavBot in loop.bots: + if bot.plans > 0: + walking += 1 + assert_true(walking >= 20, "%d of 23 bots planned paths after landing" % walking) + assert_eq(loop.bots.size(), 23) diff --git a/test/bots/test_nav.gd.uid b/test/bots/test_nav.gd.uid new file mode 100644 index 0000000..bf9aead --- /dev/null +++ b/test/bots/test_nav.gd.uid @@ -0,0 +1 @@ +uid://c45gq3yi0pda3 diff --git a/test/server/test_server_loop.gd b/test/server/test_server_loop.gd index 8db90d7..e3eaa33 100644 --- a/test/server/test_server_loop.gd +++ b/test/server/test_server_loop.gd @@ -77,7 +77,7 @@ func test_server_returns_to_the_lobby_and_starts_the_next_match() -> void: assert_eq(loop.match_flow.phase, Match.DROP) assert_eq(loop.bots.size(), 3) var first_seed: int = loop.match_flow.current_seed() - for bot: WanderBot in loop.bots.slice(1): + for bot: NavBot in loop.bots.slice(1): loop.sim.entities.find(bot.player_id).health = 0 loop.run_tick() assert_eq(loop.match_flow.phase, Match.RESULTS)